feat(features): auth, accounts, home, repositories, issues, notifications
- auth: welcome/connect screens, shared connect form, connect flow, app lock - accounts: session hook, actions, switcher + add-account screens - home: dashboard (identity, shortcuts, recent repos, assigned issues, review requests, activity, unread badge) - repositories/repository: list+search, overview, files, file viewer, commits, commit detail, branches, tags, repo issues/pulls, issue/pull detail - issues/notifications: cross-repo search, query hooks, inbox with read marking and lifecycle-aware polling - settings: theme/language/biometrics/poll interval/cache/about
This commit is contained in:
1 parent
ad81db07b3
commit
0a889ebfed
36 files changed
+4186
No files matched your search
@@ -0,0 +1,176 @@
|
||||
import { Alert, StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
|
||||
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { Avatar } from '@/components/ui/avatar';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { IconButton } from '@/components/ui/icon-button';
|
||||
import { ListItem } from '@/components/ui/list-item';
|
||||
import { EmptyState } from '@/components/ui/state-views';
|
||||
import type { AccountRecord, InstanceRecord } from '@/core/accounts/types';
|
||||
import { useAccountsStore } from '@/core/accounts/accounts-store';
|
||||
import { useAccountActions } from '@/features/accounts/use-account-actions';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
import type { AccountsStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<AccountsStackParamList, 'Accounts'>;
|
||||
|
||||
/** Manage instances and accounts: switch, add and remove. */
|
||||
export function AccountsScreen(_props: Props) {
|
||||
const navigation = useNavigation<NativeStackNavigationProp<AccountsStackParamList>>();
|
||||
const { t } = useTranslation();
|
||||
const instances = useAccountsStore((s) => s.instances);
|
||||
const accounts = useAccountsStore((s) => s.accounts);
|
||||
const activeAccountId = useAccountsStore((s) => s.activeAccountId);
|
||||
const tokens = useAccountsStore((s) => s.tokens);
|
||||
const { removeAccount, removeInstance, switchAccount } = useAccountActions();
|
||||
|
||||
const confirmRemoveAccount = (account: AccountRecord) => {
|
||||
Alert.alert(
|
||||
t('accounts.removeAccountTitle'),
|
||||
t('accounts.removeAccountBody', { name: account.login }),
|
||||
[
|
||||
{ text: t('common.cancel'), style: 'cancel' },
|
||||
{
|
||||
text: t('common.remove'),
|
||||
style: 'destructive',
|
||||
onPress: () => {
|
||||
void removeAccount(account.id).then(() => Alert.alert(t('accounts.removeDone')));
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
};
|
||||
|
||||
const confirmRemoveInstance = (instance: InstanceRecord) => {
|
||||
Alert.alert(
|
||||
t('accounts.removeInstanceTitle'),
|
||||
t('accounts.removeInstanceBody', { instance: instance.label }),
|
||||
[
|
||||
{ text: t('common.cancel'), style: 'cancel' },
|
||||
{
|
||||
text: t('common.disconnect'),
|
||||
style: 'destructive',
|
||||
onPress: () => {
|
||||
void removeInstance(instance.id).then(() => Alert.alert(t('accounts.disconnectDone')));
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
};
|
||||
|
||||
if (instances.length === 0) {
|
||||
return (
|
||||
<Screen padded>
|
||||
<EmptyState
|
||||
icon="people"
|
||||
title={t('accounts.noAccounts')}
|
||||
body={t('accounts.addFirstAccount')}
|
||||
actionLabel={t('accounts.addAccount')}
|
||||
onAction={() => navigation.navigate('AddAccount')}
|
||||
/>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Screen scroll padded>
|
||||
<Button
|
||||
label={t('accounts.addAccount')}
|
||||
iconLeft="plus"
|
||||
variant="secondary"
|
||||
fullWidth
|
||||
onPress={() => navigation.navigate('AddAccount')}
|
||||
/>
|
||||
|
||||
{instances.map((instance) => {
|
||||
const instanceAccounts = accounts.filter((account) => account.instanceId === instance.id);
|
||||
return (
|
||||
<View key={instance.id} style={styles.group}>
|
||||
<View style={styles.groupHeader}>
|
||||
<AppText variant="subheading" numberOfLines={1} style={styles.groupTitle}>
|
||||
{instance.label}
|
||||
</AppText>
|
||||
{instance.version ? (
|
||||
<Badge tone="neutral">{t('accounts.version', { version: instance.version })}</Badge>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<Card padded={false} variant="flat">
|
||||
{instanceAccounts.map((account, index) => {
|
||||
const active = account.id === activeAccountId;
|
||||
return (
|
||||
<ListItem
|
||||
key={account.id}
|
||||
leading={
|
||||
<Avatar
|
||||
url={account.avatarUrl ?? null}
|
||||
name={account.fullName ?? account.login}
|
||||
size={36}
|
||||
token={tokens[account.id] ?? null}
|
||||
host={safeHost(instance.baseUrl)}
|
||||
/>
|
||||
}
|
||||
title={account.fullName ?? account.login}
|
||||
subtitle={t('accounts.signedInAs', { name: account.login })}
|
||||
trailing={
|
||||
<View style={styles.trailing}>
|
||||
{active ? <Badge tone="primary">{t('accounts.active')}</Badge> : null}
|
||||
<IconButton
|
||||
name="trash"
|
||||
size={18}
|
||||
muted
|
||||
accessibilityLabel={t('accounts.removeAccountTitle')}
|
||||
onPress={() => confirmRemoveAccount(account)}
|
||||
/>
|
||||
</View>
|
||||
}
|
||||
onPress={() => {
|
||||
if (!active) void switchAccount(account.id);
|
||||
}}
|
||||
accessibilityLabel={t('accounts.switchTo', { name: account.login })}
|
||||
divider={index < instanceAccounts.length - 1}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<ListItem
|
||||
leadingIcon="close"
|
||||
title={t('common.disconnect')}
|
||||
onPress={() => confirmRemoveInstance(instance)}
|
||||
divider={false}
|
||||
style={styles.disconnect}
|
||||
/>
|
||||
</Card>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
|
||||
<AppText variant="caption" tone="tertiary" style={styles.footer}>
|
||||
{t('common.unofficialNotice')}
|
||||
</AppText>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
function safeHost(baseUrl: string): string | null {
|
||||
try {
|
||||
return new URL(baseUrl).host;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
group: { gap: spacing.sm },
|
||||
groupHeader: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
|
||||
groupTitle: { flexShrink: 1 },
|
||||
trailing: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
|
||||
disconnect: { opacity: 0.9 },
|
||||
footer: { textAlign: 'center', paddingVertical: spacing.lg },
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { ConnectForm } from '@/features/auth/components/connect-form';
|
||||
import type { AccountsStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<AccountsStackParamList, 'AddAccount'>;
|
||||
|
||||
/** Adds another account/instance without leaving the signed-in app. */
|
||||
export function AddAccountScreen({ navigation, route }: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Screen scroll>
|
||||
<ConnectForm
|
||||
showHeader={false}
|
||||
initialBaseUrl={route.params?.baseUrl}
|
||||
submitLabel={t('accounts.addAccount')}
|
||||
onConnected={() => navigation.goBack()}
|
||||
/>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Account lifecycle actions that must keep the query cache consistent:
|
||||
* removing an account/instance purges every cached response belonging to it
|
||||
* BEFORE the record (and its token) is destroyed.
|
||||
*/
|
||||
|
||||
import { useCallback } from 'react';
|
||||
|
||||
import { useAccountsStore } from '@/core/accounts/accounts-store';
|
||||
import { purgeAccountCache } from '@/core/api/query-keys';
|
||||
import { queryClient } from '@/core/api/query-client';
|
||||
|
||||
export interface AccountActions {
|
||||
removeAccount: (accountId: string) => Promise<void>;
|
||||
removeInstance: (instanceId: string) => Promise<void>;
|
||||
switchAccount: (accountId: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function useAccountActions(): AccountActions {
|
||||
const removeAccount = useAccountsStore((s) => s.removeAccount);
|
||||
const removeInstance = useAccountsStore((s) => s.removeInstance);
|
||||
const switchAccount = useAccountsStore((s) => s.switchAccount);
|
||||
|
||||
const doRemoveAccount = useCallback(
|
||||
async (accountId: string) => {
|
||||
purgeAccountCache(queryClient, accountId);
|
||||
await removeAccount(accountId);
|
||||
},
|
||||
[removeAccount],
|
||||
);
|
||||
|
||||
const doRemoveInstance = useCallback(
|
||||
async (instanceId: string) => {
|
||||
const { accounts } = useAccountsStore.getState();
|
||||
for (const account of accounts) {
|
||||
if (account.instanceId === instanceId) {
|
||||
purgeAccountCache(queryClient, account.id);
|
||||
}
|
||||
}
|
||||
await removeInstance(instanceId);
|
||||
},
|
||||
[removeInstance],
|
||||
);
|
||||
|
||||
const doSwitch = useCallback(
|
||||
async (accountId: string) => {
|
||||
// Caches are account-scoped by key, so switching never exposes another
|
||||
// account's data — there is nothing to purge on switch.
|
||||
await switchAccount(accountId);
|
||||
},
|
||||
[switchAccount],
|
||||
);
|
||||
|
||||
return { removeAccount: doRemoveAccount, removeInstance: doRemoveInstance, switchAccount: doSwitch };
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Session: the active instance + account, their token, and a ready-to-use
|
||||
* API client. All values are derived from the accounts store (in-memory only).
|
||||
*/
|
||||
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useAccountsStore, selectActive } from '@/core/accounts/accounts-store';
|
||||
import { GiteaClient } from '@/core/api/client';
|
||||
import type { AccountRecord, InstanceRecord } from '@/core/accounts/types';
|
||||
|
||||
export interface Session {
|
||||
/** True once the accounts store finished hydrating from disk. */
|
||||
hydrated: boolean;
|
||||
hasAccounts: boolean;
|
||||
instance: InstanceRecord | null;
|
||||
account: AccountRecord | null;
|
||||
token: string | null;
|
||||
/** Authenticated client for the active account; null when signed out. */
|
||||
client: GiteaClient | null;
|
||||
}
|
||||
|
||||
export function useSession(): Session {
|
||||
const hydrated = useAccountsStore((s) => s.hydrated);
|
||||
const instances = useAccountsStore((s) => s.instances);
|
||||
const accounts = useAccountsStore((s) => s.accounts);
|
||||
const activeAccountId = useAccountsStore((s) => s.activeAccountId);
|
||||
const tokens = useAccountsStore((s) => s.tokens);
|
||||
|
||||
const active = selectActive({ instances, accounts, activeAccountId });
|
||||
const token = active ? (tokens[active.account.id] ?? null) : null;
|
||||
|
||||
const client = useMemo(() => {
|
||||
if (!active || !token) return null;
|
||||
return new GiteaClient({ baseUrl: active.instance.baseUrl, token });
|
||||
}, [active, token]);
|
||||
|
||||
return {
|
||||
hydrated,
|
||||
hasAccounts: accounts.length > 0,
|
||||
instance: active?.instance ?? null,
|
||||
account: active?.account ?? null,
|
||||
token,
|
||||
client,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* App lock gate.
|
||||
*
|
||||
* When biometric lock is enabled the app arms a full-screen, opaque lock
|
||||
* overlay whenever it goes to the background, and automatically prompts for
|
||||
* Face ID / fingerprint / device credentials when it becomes active again.
|
||||
*
|
||||
* Safety rules:
|
||||
* - Only arms when biometrics are enrolled AND the feature is enabled — the
|
||||
* user can never lock themselves out (no enrolled credentials → no lock).
|
||||
* - Failures/cancellations stay locked; "prompt unavailable" unlocks to avoid
|
||||
* trapping the user behind a prompt the OS refuses to show.
|
||||
* - The gate is client-side only; it protects on-device data at rest/shoulder
|
||||
* surf, it is not a server-side control.
|
||||
*/
|
||||
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { AppState, StyleSheet, View } from 'react-native';
|
||||
import Animated, { FadeIn } from 'react-native-reanimated';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Icon } from '@/components/ui/icon';
|
||||
import { getBiometricSupport, promptBiometric, type BiometricSupport } from '@/core/security/biometrics';
|
||||
import { useAccountsStore } from '@/core/accounts/accounts-store';
|
||||
import { useSettingsStore } from '@/features/settings/settings-store';
|
||||
import { useTheme } from '@/theme/theme-provider';
|
||||
import { radius, spacing } from '@/theme/tokens';
|
||||
|
||||
export function AppLockGate({ children }: { children: ReactNode }) {
|
||||
const { t } = useTranslation();
|
||||
const { colors } = useTheme();
|
||||
const biometricsEnabled = useSettingsStore((s) => s.biometricsEnabled);
|
||||
const hasAccounts = useAccountsStore((s) => s.accounts.length > 0);
|
||||
|
||||
const [support, setSupport] = useState<BiometricSupport | null>(null);
|
||||
const [locked, setLocked] = useState(true);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const prompting = useRef(false);
|
||||
|
||||
const armed = biometricsEnabled && hasAccounts && support?.usable === true;
|
||||
|
||||
// Support can change (biometrics enrolled/removed while app runs).
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
getBiometricSupport().then((value) => {
|
||||
if (!cancelled) setSupport(value);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [biometricsEnabled]);
|
||||
|
||||
// Lock when leaving the foreground.
|
||||
useEffect(() => {
|
||||
const subscription = AppState.addEventListener('change', (state) => {
|
||||
if (state === 'background') {
|
||||
setLocked(true);
|
||||
setFailed(false);
|
||||
}
|
||||
});
|
||||
return () => subscription.remove();
|
||||
}, []);
|
||||
|
||||
// Not armed → never locked. `effectiveLocked` below gates the overlay, so an
|
||||
// existing lock flag is simply ignored while the feature is off/unusable.
|
||||
|
||||
const runPrompt = async () => {
|
||||
if (prompting.current) return;
|
||||
prompting.current = true;
|
||||
setFailed(false);
|
||||
try {
|
||||
const outcome = await promptBiometric(t('lock.biometricPrompt'));
|
||||
if (outcome === 'success') {
|
||||
setLocked(false);
|
||||
} else if (outcome === 'cancelled' || outcome === 'failed') {
|
||||
setFailed(true);
|
||||
} else if (outcome === 'unavailable') {
|
||||
// OS refuses to prompt (misconfiguration) — don't trap the user.
|
||||
setLocked(false);
|
||||
}
|
||||
} finally {
|
||||
prompting.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Prompt automatically once active while locked.
|
||||
const activeRef = useRef(AppState.currentState !== 'background');
|
||||
const effectiveLocked = armed && locked;
|
||||
useEffect(() => {
|
||||
const subscription = AppState.addEventListener('change', (state) => {
|
||||
activeRef.current = state === 'active';
|
||||
if (state === 'active' && effectiveLocked && !prompting.current) {
|
||||
void runPrompt();
|
||||
}
|
||||
});
|
||||
return () => subscription.remove();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [effectiveLocked]);
|
||||
|
||||
useEffect(() => {
|
||||
if (effectiveLocked && activeRef.current && !prompting.current) {
|
||||
void runPrompt();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [effectiveLocked]);
|
||||
|
||||
const showOverlay = effectiveLocked;
|
||||
|
||||
return (
|
||||
<View style={styles.fill}>
|
||||
{children}
|
||||
{showOverlay ? (
|
||||
<Animated.View
|
||||
entering={FadeIn.duration(180)}
|
||||
style={[StyleSheet.absoluteFill, styles.overlay, { backgroundColor: colors.background }]}
|
||||
accessibilityViewIsModal
|
||||
>
|
||||
<View style={[styles.iconCircle, { backgroundColor: colors.surfaceSecondary }]}>
|
||||
<Icon name="lock" size={36} color={colors.primary} />
|
||||
</View>
|
||||
<AppText variant="title" style={{ textAlign: 'center' }}>
|
||||
{t('lock.title')}
|
||||
</AppText>
|
||||
<AppText variant="secondary" tone="tertiary" style={{ textAlign: 'center' }}>
|
||||
{t('lock.subtitle')}
|
||||
</AppText>
|
||||
{failed ? (
|
||||
<AppText variant="caption" tone="error" style={{ textAlign: 'center' }}>
|
||||
{t('lock.failed')}
|
||||
</AppText>
|
||||
) : null}
|
||||
<Button
|
||||
label={t('lock.unlock')}
|
||||
iconLeft="person"
|
||||
onPress={() => void runPrompt()}
|
||||
style={{ marginTop: spacing.lg, minWidth: 200 }}
|
||||
/>
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
fill: { flex: 1 },
|
||||
overlay: {
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: spacing.md,
|
||||
padding: spacing.xl,
|
||||
zIndex: 1000,
|
||||
elevation: 1000,
|
||||
},
|
||||
iconCircle: {
|
||||
width: 80,
|
||||
height: 80,
|
||||
borderRadius: radius.pill,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { KeyboardAvoidingView, Platform, StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { Field } from '@/components/ui/field';
|
||||
import { Icon } from '@/components/ui/icon';
|
||||
import { useConnectAccount } from '@/features/auth/use-connect-account';
|
||||
import type { ConnectResult } from '@/features/auth/connect';
|
||||
import { useTheme } from '@/theme/theme-provider';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
|
||||
export interface ConnectFormProps {
|
||||
/** Prefills the instance URL (e.g. from a deep link). */
|
||||
initialBaseUrl?: string;
|
||||
/** Show the key icon + title header (used on the standalone auth screen). */
|
||||
showHeader?: boolean;
|
||||
/** Overrides the submit label. */
|
||||
submitLabel?: string;
|
||||
/** Called after the account has been validated and persisted. */
|
||||
onConnected?: (result: ConnectResult) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Instance + token entry. Shared by the sign-in flow and the "add account"
|
||||
* flow. The token field is masked by default, never logged, and only handed to
|
||||
* the connect flow (SecureStore via the accounts store).
|
||||
*/
|
||||
export function ConnectForm({
|
||||
initialBaseUrl,
|
||||
showHeader = true,
|
||||
submitLabel,
|
||||
onConnected,
|
||||
}: ConnectFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const { colors } = useTheme();
|
||||
|
||||
const [baseUrl, setBaseUrl] = useState(initialBaseUrl ?? '');
|
||||
const [token, setToken] = useState('');
|
||||
const [label, setLabel] = useState('');
|
||||
const [submitted, setSubmitted] = useState(false);
|
||||
|
||||
const { connect, connecting, error, reset } = useConnectAccount();
|
||||
|
||||
useEffect(() => () => reset(), [reset]);
|
||||
|
||||
const urlError = useMemo(() => {
|
||||
if (!submitted) return undefined;
|
||||
if (baseUrl.trim().length === 0) return t('auth.errors.url');
|
||||
return undefined;
|
||||
}, [submitted, baseUrl, t]);
|
||||
|
||||
const tokenError = useMemo(() => {
|
||||
if (!submitted) return undefined;
|
||||
if (token.trim().length === 0) return t('auth.errors.token');
|
||||
return undefined;
|
||||
}, [submitted, token, t]);
|
||||
|
||||
const canSubmit = baseUrl.trim().length > 0 && token.trim().length > 0 && !connecting;
|
||||
|
||||
const submit = async () => {
|
||||
setSubmitted(true);
|
||||
if (baseUrl.trim().length === 0 || token.trim().length === 0) return;
|
||||
const result = await connect({
|
||||
baseUrl: baseUrl.trim(),
|
||||
token,
|
||||
label: label.trim() || undefined,
|
||||
});
|
||||
if (result) {
|
||||
// Never keep the token in component state after a successful connect.
|
||||
setToken('');
|
||||
onConnected?.(result);
|
||||
}
|
||||
};
|
||||
|
||||
const errorKey = error ? (`auth.errors.${error.code}` as const) : null;
|
||||
|
||||
return (
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
|
||||
style={styles.flex}
|
||||
>
|
||||
{showHeader ? (
|
||||
<View style={styles.header}>
|
||||
<View style={[styles.icon, { backgroundColor: colors.primaryMuted }]}>
|
||||
<Icon name="key" size={28} color={colors.primary} />
|
||||
</View>
|
||||
<AppText variant="title">{t('auth.connect.title')}</AppText>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{errorKey ? (
|
||||
<View
|
||||
style={[styles.errorBanner, { backgroundColor: colors.errorMuted }]}
|
||||
accessibilityRole="alert"
|
||||
>
|
||||
<Icon name="warning" size={18} color={colors.error} />
|
||||
<AppText variant="caption" tone="error" style={styles.flex}>
|
||||
{t(errorKey)}
|
||||
</AppText>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<Card>
|
||||
<View style={styles.fields}>
|
||||
<Field
|
||||
label={t('auth.connect.instanceUrl')}
|
||||
value={baseUrl}
|
||||
onChangeText={(next) => {
|
||||
setBaseUrl(next);
|
||||
if (submitted) setSubmitted(false);
|
||||
reset();
|
||||
}}
|
||||
placeholder={t('auth.connect.instanceUrlPlaceholder')}
|
||||
helper={t('auth.connect.instanceUrlHelp')}
|
||||
error={urlError}
|
||||
showError={Boolean(urlError)}
|
||||
keyboardType="url"
|
||||
autoCapitalize="none"
|
||||
returnKeyType="next"
|
||||
leadingIcon="globe"
|
||||
clearable
|
||||
testID="connect-instance-url"
|
||||
/>
|
||||
<Field
|
||||
label={t('auth.connect.token')}
|
||||
value={token}
|
||||
onChangeText={(next) => {
|
||||
setToken(next);
|
||||
reset();
|
||||
}}
|
||||
placeholder={t('auth.connect.tokenPlaceholder')}
|
||||
helper={t('auth.connect.tokenHelp')}
|
||||
error={tokenError}
|
||||
showError={Boolean(tokenError)}
|
||||
secureTextEntry
|
||||
mono
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
leadingIcon="key"
|
||||
testID="connect-token"
|
||||
/>
|
||||
<Field
|
||||
label={`${t('auth.connect.label')} (${t('common.optional')})`}
|
||||
value={label}
|
||||
onChangeText={setLabel}
|
||||
placeholder={t('auth.connect.labelPlaceholder')}
|
||||
autoCapitalize="sentences"
|
||||
autoCorrect
|
||||
clearable
|
||||
testID="connect-label"
|
||||
/>
|
||||
</View>
|
||||
</Card>
|
||||
|
||||
<Button
|
||||
label={submitLabel ?? (connecting ? t('auth.connect.validating') : t('auth.connect.submit'))}
|
||||
size="lg"
|
||||
fullWidth
|
||||
loading={connecting}
|
||||
disabled={!canSubmit}
|
||||
onPress={() => void submit()}
|
||||
testID="connect-submit"
|
||||
/>
|
||||
</KeyboardAvoidingView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
flex: { flex: 1, gap: spacing.lg },
|
||||
header: {
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
paddingTop: spacing.xl,
|
||||
paddingBottom: spacing.sm,
|
||||
},
|
||||
icon: {
|
||||
width: 64,
|
||||
height: 64,
|
||||
borderRadius: 999,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
errorBanner: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'flex-start',
|
||||
gap: spacing.sm,
|
||||
padding: spacing.md,
|
||||
borderRadius: 10,
|
||||
},
|
||||
fields: { gap: spacing.lg },
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* End-to-end connect flow: URL validation → version probe → token validation →
|
||||
* persistence. Uses a mocked fetch and an in-memory SecureStore so the test
|
||||
* exercises the real store wiring without touching native modules.
|
||||
*/
|
||||
|
||||
import * as SecureStore from 'expo-secure-store';
|
||||
|
||||
import { useAccountsStore } from '@/core/accounts/accounts-store';
|
||||
|
||||
import { ConnectError, connectToInstance } from './connect';
|
||||
|
||||
// jest.mock is hoisted above the imports by babel-jest at runtime.
|
||||
jest.mock('expo-secure-store', () => {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
getItemAsync: jest.fn(async (key: string) => store.get(key) ?? null),
|
||||
setItemAsync: jest.fn(async (key: string, value: string) => {
|
||||
store.set(key, value);
|
||||
}),
|
||||
deleteItemAsync: jest.fn(async (key: string) => {
|
||||
store.delete(key);
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
function res(body: string, status = 200): Response {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
headers: { get: () => null },
|
||||
text: async () => body,
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
function userResponse(status = 200): Response {
|
||||
if (status === 200) {
|
||||
return res(JSON.stringify({ login: 'alice', id: 7, full_name: 'Alice', avatar_url: 'https://x/a.png' }));
|
||||
}
|
||||
return res('', status);
|
||||
}
|
||||
|
||||
function mockFetch(userStatus = 200) {
|
||||
return jest.fn(async (url: string) => {
|
||||
if (url.endsWith('/api/v1/version')) return res(JSON.stringify({ version: '1.21.0' }));
|
||||
if (url.endsWith('/api/v1/user')) return userResponse(userStatus);
|
||||
return res('{}', 404);
|
||||
});
|
||||
}
|
||||
|
||||
async function codeOf(fn: () => Promise<unknown>): Promise<string | undefined> {
|
||||
try {
|
||||
await fn();
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
return error instanceof ConnectError ? error.code : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
describe('connectToInstance', () => {
|
||||
beforeEach(() => {
|
||||
useAccountsStore.setState({
|
||||
instances: [],
|
||||
accounts: [],
|
||||
activeAccountId: null,
|
||||
tokens: {},
|
||||
hydrated: true,
|
||||
});
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('validates the token, persists the account and stores the token securely', async () => {
|
||||
global.fetch = mockFetch() as unknown as typeof fetch;
|
||||
|
||||
const result = await connectToInstance({ baseUrl: 'codeberg.org', token: 'pat-123' });
|
||||
|
||||
expect(result.instance.baseUrl).toBe('https://codeberg.org');
|
||||
expect(result.instance.version).toBe('1.21.0');
|
||||
expect(result.account.login).toBe('alice');
|
||||
|
||||
const state = useAccountsStore.getState();
|
||||
expect(state.accounts).toHaveLength(1);
|
||||
expect(state.activeAccountId).toBe(result.account.id);
|
||||
expect(state.tokens[result.account.id]).toBe('pat-123');
|
||||
expect(state.instances[0].baseUrl).toBe('https://codeberg.org');
|
||||
|
||||
// Token written through SecureStore, never to plain storage state.
|
||||
expect(SecureStore.setItemAsync).toHaveBeenCalledWith(
|
||||
`token.${result.account.id}`,
|
||||
'pat-123',
|
||||
expect.objectContaining({ keychainService: 'gitea-native.credentials' }),
|
||||
);
|
||||
expect(JSON.stringify(state.accounts)).not.toContain('pat-123');
|
||||
});
|
||||
|
||||
it('rejects the token when the instance returns 401', async () => {
|
||||
global.fetch = mockFetch(401) as unknown as typeof fetch;
|
||||
expect(await codeOf(() => connectToInstance({ baseUrl: 'codeberg.org', token: 'bad' }))).toBe(
|
||||
'auth',
|
||||
);
|
||||
});
|
||||
|
||||
it('treats a 404 on /user as “not a Gitea instance”', async () => {
|
||||
global.fetch = mockFetch(404) as unknown as typeof fetch;
|
||||
expect(await codeOf(() => connectToInstance({ baseUrl: 'codeberg.org', token: 'x' }))).toBe(
|
||||
'url',
|
||||
);
|
||||
});
|
||||
|
||||
it('reports a network failure distinctly from a bad token', async () => {
|
||||
global.fetch = jest.fn(async () => {
|
||||
throw new TypeError('Network request failed');
|
||||
}) as unknown as typeof fetch;
|
||||
expect(await codeOf(() => connectToInstance({ baseUrl: 'codeberg.org', token: 'x' }))).toBe(
|
||||
'network',
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects insecure remote HTTP before any request', async () => {
|
||||
const fetchImpl = mockFetch();
|
||||
global.fetch = fetchImpl as unknown as typeof fetch;
|
||||
expect(await codeOf(() => connectToInstance({ baseUrl: 'http://codeberg.org', token: 'x' }))).toBe(
|
||||
'insecure',
|
||||
);
|
||||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('requires a non-empty token', async () => {
|
||||
const fetchImpl = mockFetch();
|
||||
global.fetch = fetchImpl as unknown as typeof fetch;
|
||||
expect(await codeOf(() => connectToInstance({ baseUrl: 'codeberg.org', token: ' ' }))).toBe(
|
||||
'auth',
|
||||
);
|
||||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('re-adding the same user refreshes the account instead of duplicating it', async () => {
|
||||
global.fetch = mockFetch() as unknown as typeof fetch;
|
||||
const first = await connectToInstance({ baseUrl: 'codeberg.org', token: 'pat-1' });
|
||||
const second = await connectToInstance({ baseUrl: 'https://codeberg.org/', token: 'pat-2' });
|
||||
|
||||
expect(second.account.id).toBe(first.account.id);
|
||||
expect(useAccountsStore.getState().accounts).toHaveLength(1);
|
||||
expect(useAccountsStore.getState().tokens[first.account.id]).toBe('pat-2');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* Account connection flow.
|
||||
*
|
||||
* Pipeline: normalize URL → probe server version (tolerated) → validate the
|
||||
* token against GET /user → persist the instance + account (token → SecureStore).
|
||||
*
|
||||
* All failures are mapped to stable error codes; localized messages live in
|
||||
* the screens (i18n keys under `auth.errors.*`).
|
||||
*/
|
||||
|
||||
import { GiteaClient } from '@/core/api/client';
|
||||
import { isApiError } from '@/core/api/errors';
|
||||
import { InstanceUrlError, normalizeInstanceUrl } from '@/core/api/instance-url';
|
||||
import type { User } from '@/core/api/types';
|
||||
import { useAccountsStore } from '@/core/accounts/accounts-store';
|
||||
import type { AccountRecord, InstanceRecord } from '@/core/accounts/types';
|
||||
|
||||
export type ConnectErrorCode = 'url' | 'insecure' | 'network' | 'auth' | 'forbidden' | 'generic';
|
||||
|
||||
export class ConnectError extends Error {
|
||||
readonly code: ConnectErrorCode;
|
||||
constructor(code: ConnectErrorCode, message: string) {
|
||||
super(message);
|
||||
this.name = 'ConnectError';
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ConnectInput {
|
||||
/** Raw user input — normalized inside. */
|
||||
baseUrl: string;
|
||||
token: string;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export interface ConnectResult {
|
||||
instance: InstanceRecord;
|
||||
account: AccountRecord;
|
||||
user: User;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates credentials and registers the account.
|
||||
* Pure with respect to inputs; all persistence goes through the accounts store.
|
||||
*/
|
||||
export async function connectToInstance(input: ConnectInput): Promise<ConnectResult> {
|
||||
const token = input.token.trim();
|
||||
if (token.length === 0) {
|
||||
throw new ConnectError('auth', 'A personal access token is required.');
|
||||
}
|
||||
|
||||
let normalized: string;
|
||||
try {
|
||||
normalized = normalizeInstanceUrl(input.baseUrl);
|
||||
} catch (error) {
|
||||
if (error instanceof InstanceUrlError) {
|
||||
throw new ConnectError(
|
||||
error.kind === 'insecure' ? 'insecure' : 'url',
|
||||
'The instance address was rejected.',
|
||||
);
|
||||
}
|
||||
throw new ConnectError('url', 'The instance address was rejected.');
|
||||
}
|
||||
|
||||
// Version probe: best effort, never blocks connecting (older instances may
|
||||
// not expose /version to unauthenticated callers).
|
||||
let version: string | undefined;
|
||||
try {
|
||||
const probe = new GiteaClient({ baseUrl: normalized, timeoutMs: 8_000 });
|
||||
const response = await probe.get<{ version?: string }>('/version');
|
||||
version = typeof response.version === 'string' ? response.version : undefined;
|
||||
} catch {
|
||||
version = undefined;
|
||||
}
|
||||
|
||||
const client = new GiteaClient({ baseUrl: normalized, token });
|
||||
|
||||
let user: User;
|
||||
try {
|
||||
user = await client.get<User>('/user');
|
||||
} catch (error) {
|
||||
if (isApiError(error)) {
|
||||
switch (error.kind) {
|
||||
case 'unauthorized':
|
||||
throw new ConnectError('auth', 'The token was rejected by this instance.');
|
||||
case 'forbidden':
|
||||
throw new ConnectError('forbidden', 'The token lacks permission to read this account.');
|
||||
case 'network':
|
||||
case 'timeout':
|
||||
throw new ConnectError('network', 'The instance could not be reached.');
|
||||
case 'not-found':
|
||||
// /user exists on every Gitea; 404 means this is not a Gitea API.
|
||||
throw new ConnectError('url', 'This address does not appear to be a Gitea instance.');
|
||||
default:
|
||||
throw new ConnectError('generic', 'Connecting to this instance failed.');
|
||||
}
|
||||
}
|
||||
throw new ConnectError('generic', 'Connecting to this instance failed.');
|
||||
}
|
||||
|
||||
const { instance, account } = await useAccountsStore.getState().registerAccount({
|
||||
baseUrl: normalized,
|
||||
label: input.label,
|
||||
token,
|
||||
version,
|
||||
profile: {
|
||||
login: user.login,
|
||||
id: user.id,
|
||||
fullName: user.full_name,
|
||||
avatarUrl: user.avatar_url,
|
||||
},
|
||||
});
|
||||
|
||||
return { instance, account, user };
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { ConnectForm } from '@/features/auth/components/connect-form';
|
||||
import type { AuthStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<AuthStackParamList, 'Connect'>;
|
||||
|
||||
/**
|
||||
* Standalone sign-in screen: instance + personal access token. Registration
|
||||
* flips the root navigator to the main app automatically (see RootNavigator).
|
||||
*/
|
||||
export function ConnectScreen({ route }: Props) {
|
||||
return (
|
||||
<Screen scroll>
|
||||
<ConnectForm initialBaseUrl={route.params?.baseUrl} />
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { useEffect } from 'react';
|
||||
import { StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { Icon } from '@/components/ui/icon';
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { useAccountsStore } from '@/core/accounts/accounts-store';
|
||||
import { useConnectAccount } from '@/features/auth/use-connect-account';
|
||||
import { useAccountActions } from '@/features/accounts/use-account-actions';
|
||||
import { useTheme } from '@/theme/theme-provider';
|
||||
import { BRAND_PRIMARY, radius, spacing } from '@/theme/tokens';
|
||||
import type { AuthStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<AuthStackParamList, 'Welcome'>;
|
||||
|
||||
/** Landing screen: branding, disclaimer, connect CTA, and existing accounts. */
|
||||
export function WelcomeScreen({ navigation }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { colors } = useTheme();
|
||||
const instances = useAccountsStore((s) => s.instances);
|
||||
const accounts = useAccountsStore((s) => s.accounts);
|
||||
const activeAccountId = useAccountsStore((s) => s.activeAccountId);
|
||||
const switchAccount = useAccountActions().switchAccount;
|
||||
const { reset } = useConnectAccount();
|
||||
|
||||
// Arriving here with accounts means a token failed validation — reset the
|
||||
// previous error so a fresh connect attempt starts clean.
|
||||
useEffect(() => {
|
||||
reset();
|
||||
}, [reset]);
|
||||
|
||||
const instanceById = new Map(instances.map((i) => [i.id, i]));
|
||||
|
||||
return (
|
||||
<Screen scroll>
|
||||
<View style={styles.hero}>
|
||||
<View style={[styles.logo, { backgroundColor: colors.primaryMuted }]}>
|
||||
<Icon name="repo" size={44} color={BRAND_PRIMARY} />
|
||||
</View>
|
||||
<AppText variant="display" style={{ textAlign: 'center' }}>
|
||||
{t('auth.welcome.title')}
|
||||
</AppText>
|
||||
<AppText variant="secondary" tone="tertiary" style={{ textAlign: 'center' }}>
|
||||
{t('auth.welcome.subtitle')}
|
||||
</AppText>
|
||||
<Button
|
||||
label={t('auth.welcome.connectButton')}
|
||||
iconLeft="plus"
|
||||
size="lg"
|
||||
fullWidth
|
||||
onPress={() => navigation.navigate('Connect')}
|
||||
style={{ marginTop: spacing.lg }}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{accounts.length > 0 ? (
|
||||
<Card padded={false} variant="flat">
|
||||
<AppText variant="label" tone="secondary" style={styles.sectionTitle}>
|
||||
{t('auth.welcome.yourAccounts')}
|
||||
</AppText>
|
||||
{accounts.map((account) => {
|
||||
const instance = instanceById.get(account.instanceId);
|
||||
const active = account.id === activeAccountId;
|
||||
return (
|
||||
<Button
|
||||
key={account.id}
|
||||
label={`${account.login} — ${instance?.label ?? ''}`}
|
||||
variant={active ? 'secondary' : 'ghost'}
|
||||
iconRight={active ? 'check' : 'chevronRight'}
|
||||
onPress={() => void switchAccount(account.id)}
|
||||
style={styles.accountRow}
|
||||
accessibilityLabel={t('accounts.switchTo', { name: account.login })}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
<AppText variant="caption" tone="tertiary" style={styles.disclaimer}>
|
||||
{t('auth.welcome.disclaimer')}
|
||||
</AppText>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
hero: {
|
||||
alignItems: 'center',
|
||||
gap: spacing.md,
|
||||
paddingTop: spacing.xxxl,
|
||||
paddingHorizontal: spacing.lg,
|
||||
},
|
||||
logo: {
|
||||
width: 96,
|
||||
height: 96,
|
||||
borderRadius: radius.xl,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
sectionTitle: {
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingTop: spacing.md,
|
||||
paddingBottom: spacing.xs,
|
||||
},
|
||||
accountRow: {
|
||||
justifyContent: 'space-between',
|
||||
minHeight: 48,
|
||||
},
|
||||
disclaimer: {
|
||||
textAlign: 'center',
|
||||
paddingHorizontal: spacing.xl,
|
||||
marginTop: spacing.lg,
|
||||
marginBottom: spacing.xxl,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useCallback } from 'react';
|
||||
|
||||
import { connectToInstance, type ConnectError, type ConnectInput, type ConnectResult } from './connect';
|
||||
|
||||
export interface UseConnectAccount {
|
||||
connect: (input: ConnectInput) => Promise<ConnectResult | undefined>;
|
||||
connecting: boolean;
|
||||
error: ConnectError | null;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
/** React Query mutation wrapper around the connect flow. */
|
||||
export function useConnectAccount(): UseConnectAccount {
|
||||
const mutation = useMutation({
|
||||
mutationFn: connectToInstance,
|
||||
});
|
||||
|
||||
const connect = useCallback(
|
||||
async (input: ConnectInput) => mutation.mutateAsync(input).catch(() => undefined),
|
||||
[mutation],
|
||||
);
|
||||
|
||||
return {
|
||||
connect,
|
||||
connecting: mutation.isPending,
|
||||
error: (mutation.error as ConnectError | null) ?? null,
|
||||
reset: mutation.reset,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/** Home-screen queries: activity feed and identity refresh. */
|
||||
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { fetchAuthenticatedUser, listUserActivity } from '@/core/api/endpoints';
|
||||
import { queryKeys } from '@/core/api/query-keys';
|
||||
import { useSession } from '@/features/accounts/use-session';
|
||||
|
||||
export function useActivityFeed(limit = 15) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
const username = account?.login ?? '';
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.activity(accountId, username),
|
||||
enabled: Boolean(client) && Boolean(accountId) && username.length > 0,
|
||||
queryFn: ({ signal }) =>
|
||||
listUserActivity(client!, username, { limit }, { signal }).then((r) => r.data),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Refreshes the signed-in user's profile (avatar, display name) in the
|
||||
* background so stale avatars/name changes self-heal without a re-login.
|
||||
*/
|
||||
export function useRefreshProfile() {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.me(accountId),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
queryFn: ({ signal }) => fetchAuthenticatedUser(client!, { signal }),
|
||||
staleTime: 30 * 60_000,
|
||||
meta: { persist: false },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { IssueRow } from '@/components/git/issue-row';
|
||||
import { RepoListItem } from '@/components/git/repo-list-item';
|
||||
import { SectionHeader } from '@/components/layout/section-header';
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { Avatar } from '@/components/ui/avatar';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { Icon, type IconName } from '@/components/ui/icon';
|
||||
import { ListItem } from '@/components/ui/list-item';
|
||||
import { EmptyState } from '@/components/ui/state-views';
|
||||
import type { Activity, Issue } from '@/core/api/types';
|
||||
import { useAccountsStore } from '@/core/accounts/accounts-store';
|
||||
import { flattenPages } from '@/core/utils/infinite';
|
||||
import { formatRelativeTime } from '@/core/utils/format';
|
||||
import { useSession } from '@/features/accounts/use-session';
|
||||
import { useActivityFeed, useRefreshProfile } from '@/features/home/queries';
|
||||
import { useIssueSearch } from '@/features/issues/queries';
|
||||
import { issueDetailTarget } from '@/features/issues/target';
|
||||
import { useUnreadCount } from '@/features/notifications/queries';
|
||||
import { useMyRepos } from '@/features/repositories/queries';
|
||||
import { useTheme } from '@/theme/theme-provider';
|
||||
import { radius, spacing } from '@/theme/tokens';
|
||||
import type { HomeStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<HomeStackParamList, 'Home'>;
|
||||
|
||||
function activityIcon(opType: string | undefined): IconName {
|
||||
switch (opType) {
|
||||
case 'commit_repo':
|
||||
return 'commit';
|
||||
case 'create_pull_request':
|
||||
case 'merge_pull_request':
|
||||
case 'close_pull_request':
|
||||
return 'pullRequest';
|
||||
case 'create_issue':
|
||||
case 'close_issue':
|
||||
case 'reopen_issue':
|
||||
case 'comment_issue':
|
||||
return 'issue';
|
||||
case 'create_branch':
|
||||
case 'delete_branch':
|
||||
return 'branch';
|
||||
case 'create_tag':
|
||||
case 'delete_tag':
|
||||
return 'tag';
|
||||
case 'star_repo':
|
||||
return 'star';
|
||||
case 'fork_repo':
|
||||
return 'fork';
|
||||
case 'create_repo':
|
||||
return 'repo';
|
||||
default:
|
||||
return 'history';
|
||||
}
|
||||
}
|
||||
|
||||
/** Signed-in dashboard: identity, shortcuts, unread count and recent work. */
|
||||
export function HomeScreen({ navigation }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { colors } = useTheme();
|
||||
const { account, instance, token } = useSession();
|
||||
|
||||
const recentRepos = useMyRepos('all', 8);
|
||||
const assignedIssues = useIssueSearch(
|
||||
{ scope: 'assigned', state: 'open', search: '', type: 'issues' },
|
||||
5,
|
||||
);
|
||||
const reviewPulls = useIssueSearch(
|
||||
{ scope: 'reviewRequested', state: 'open', search: '', type: 'pulls' },
|
||||
5,
|
||||
);
|
||||
const activity = useActivityFeed(10);
|
||||
const unread = useUnreadCount();
|
||||
const profile = useRefreshProfile();
|
||||
const updateProfile = useAccountsStore((s) => s.updateProfile);
|
||||
|
||||
// Keep the stored display name/avatar in sync with the server.
|
||||
useEffect(() => {
|
||||
const me = profile.data;
|
||||
if (!me || !account) return;
|
||||
const next = { fullName: me.full_name, avatarUrl: me.avatar_url, userId: me.id };
|
||||
if (
|
||||
next.fullName !== account.fullName ||
|
||||
next.avatarUrl !== account.avatarUrl ||
|
||||
next.userId !== account.userId
|
||||
) {
|
||||
void updateProfile(account.id, next);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [profile.data, account?.id]);
|
||||
|
||||
const repos = useMemo(() => flattenPages(recentRepos.data).slice(0, 4), [recentRepos.data]);
|
||||
const issues: Issue[] = useMemo(
|
||||
() => flattenPages(assignedIssues.data).slice(0, 4),
|
||||
[assignedIssues.data],
|
||||
);
|
||||
const pulls: Issue[] = useMemo(
|
||||
() => flattenPages(reviewPulls.data).slice(0, 4),
|
||||
[reviewPulls.data],
|
||||
);
|
||||
const events: Activity[] = activity.data ?? [];
|
||||
|
||||
const openTab = (name: 'RepositoriesTab' | 'IssuesTab' | 'PullsTab' | 'InboxTab') => {
|
||||
switch (name) {
|
||||
case 'RepositoriesTab':
|
||||
navigation.jumpTo('RepositoriesTab', { screen: 'RepositoryList' });
|
||||
break;
|
||||
case 'IssuesTab':
|
||||
navigation.jumpTo('IssuesTab', { screen: 'Issues' });
|
||||
break;
|
||||
case 'PullsTab':
|
||||
navigation.jumpTo('PullsTab', { screen: 'PullRequests' });
|
||||
break;
|
||||
case 'InboxTab':
|
||||
navigation.jumpTo('InboxTab', { screen: 'Inbox' });
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const openIssue = (issue: Issue) => {
|
||||
const target = issueDetailTarget(issue);
|
||||
if (target) navigation.navigate('Repository', { screen: target.screen, params: target.params });
|
||||
};
|
||||
|
||||
return (
|
||||
<Screen scroll padded={false}>
|
||||
{/* Identity */}
|
||||
<View style={styles.pad}>
|
||||
<Card>
|
||||
<View style={styles.identity}>
|
||||
<Avatar
|
||||
url={account?.avatarUrl ?? null}
|
||||
name={account?.fullName ?? account?.login ?? '?'}
|
||||
size={52}
|
||||
token={token}
|
||||
host={instance ? safeHost(instance.baseUrl) : null}
|
||||
/>
|
||||
<View style={styles.identityBody}>
|
||||
<AppText variant="heading" numberOfLines={1}>
|
||||
{account?.fullName ?? account?.login ?? ''}
|
||||
</AppText>
|
||||
<AppText variant="caption" tone="tertiary" numberOfLines={1}>
|
||||
{`@${account?.login ?? ''}`}
|
||||
</AppText>
|
||||
{instance ? (
|
||||
<AppText variant="caption" tone="tertiary" numberOfLines={1}>
|
||||
{t('home.instanceOn', { instance: instance.label })}
|
||||
</AppText>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
<View style={[styles.divider, { backgroundColor: colors.border }]} />
|
||||
<ListItem
|
||||
leadingIcon="inbox"
|
||||
title={t('inbox.title')}
|
||||
subtitle={t('home.unreadNotifications', { count: unread.data?.count ?? 0 })}
|
||||
onPress={() => openTab('InboxTab')}
|
||||
divider={false}
|
||||
style={styles.compactTile}
|
||||
/>
|
||||
</Card>
|
||||
</View>
|
||||
|
||||
{/* Shortcuts */}
|
||||
<View style={styles.section}>
|
||||
<View style={styles.pad}>
|
||||
<SectionHeader title={t('home.shortcuts')} />
|
||||
</View>
|
||||
<View style={styles.shortcuts}>
|
||||
<Shortcut
|
||||
icon="repo"
|
||||
label={t('home.shortcutRepositories')}
|
||||
onPress={() => openTab('RepositoriesTab')}
|
||||
/>
|
||||
<Shortcut
|
||||
icon="issue"
|
||||
label={t('home.shortcutIssues')}
|
||||
onPress={() => openTab('IssuesTab')}
|
||||
/>
|
||||
<Shortcut
|
||||
icon="pullRequest"
|
||||
label={t('home.shortcutPulls')}
|
||||
onPress={() => openTab('PullsTab')}
|
||||
/>
|
||||
<Shortcut
|
||||
icon="inbox"
|
||||
label={t('home.shortcutInbox')}
|
||||
badge={unread.data?.count ?? 0}
|
||||
onPress={() => openTab('InboxTab')}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{/* Recent repositories */}
|
||||
<View style={styles.section}>
|
||||
<View style={styles.pad}>
|
||||
<SectionHeader
|
||||
title={t('home.recentRepos')}
|
||||
actionLabel={t('common.viewAll')}
|
||||
onAction={() => openTab('RepositoriesTab')}
|
||||
/>
|
||||
</View>
|
||||
{repos.length === 0 ? (
|
||||
<InlineEmpty
|
||||
loading={recentRepos.isPending}
|
||||
title={t('home.emptyRepos')}
|
||||
body={recentRepos.isError ? t('errors.network') : undefined}
|
||||
/>
|
||||
) : (
|
||||
repos.map((repo) => (
|
||||
<RepoListItem
|
||||
key={repo.id}
|
||||
repo={repo}
|
||||
onPress={() =>
|
||||
navigation.navigate('Repository', {
|
||||
screen: 'RepoOverview',
|
||||
params: { owner: repo.owner?.login ?? repo.full_name.split('/')[0], name: repo.name },
|
||||
})
|
||||
}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* Assigned issues */}
|
||||
<View style={styles.section}>
|
||||
<View style={styles.pad}>
|
||||
<SectionHeader
|
||||
title={t('home.assignedIssues')}
|
||||
actionLabel={t('common.viewAll')}
|
||||
onAction={() => openTab('IssuesTab')}
|
||||
/>
|
||||
</View>
|
||||
{issues.length === 0 ? (
|
||||
<InlineEmpty loading={assignedIssues.isPending} title={t('home.emptyIssues')} />
|
||||
) : (
|
||||
issues.map((issue) => (
|
||||
<IssueRow
|
||||
key={`${issue.repository?.full_name ?? ''}-${issue.id}`}
|
||||
issue={issue}
|
||||
showRepository
|
||||
onPress={() => openIssue(issue)}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* Review requested */}
|
||||
<View style={styles.section}>
|
||||
<View style={styles.pad}>
|
||||
<SectionHeader
|
||||
title={t('home.reviewPulls')}
|
||||
actionLabel={t('common.viewAll')}
|
||||
onAction={() => openTab('PullsTab')}
|
||||
/>
|
||||
</View>
|
||||
{pulls.length === 0 ? (
|
||||
<InlineEmpty loading={reviewPulls.isPending} title={t('home.emptyPulls')} />
|
||||
) : (
|
||||
pulls.map((pull) => (
|
||||
<IssueRow
|
||||
key={`${pull.repository?.full_name ?? ''}-${pull.id}`}
|
||||
issue={pull}
|
||||
showRepository
|
||||
onPress={() => openIssue(pull)}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* Activity */}
|
||||
<View style={styles.section}>
|
||||
<View style={styles.pad}>
|
||||
<SectionHeader title={t('home.activity')} />
|
||||
</View>
|
||||
{events.length === 0 ? (
|
||||
<InlineEmpty loading={activity.isPending} title={t('home.emptyActivity')} />
|
||||
) : (
|
||||
<View style={styles.pad}>
|
||||
<Card padded={false} variant="flat">
|
||||
{events.map((event, index) => (
|
||||
<ListItem
|
||||
key={`${event.id ?? index}`}
|
||||
leadingIcon={activityIcon(event.op_type)}
|
||||
title={event.repo?.full_name ?? t('common.unknown')}
|
||||
subtitle={event.content ?? event.ref_name}
|
||||
meta={formatRelativeTime(event.created, t)}
|
||||
divider={index < events.length - 1}
|
||||
onPress={
|
||||
event.repo
|
||||
? () =>
|
||||
navigation.navigate('Repository', {
|
||||
screen: 'RepoOverview',
|
||||
params: {
|
||||
owner: event.repo?.owner?.login ?? event.repo?.full_name.split('/')[0] ?? '',
|
||||
name: event.repo?.name ?? '',
|
||||
},
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</Card>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<AppText variant="caption" tone="tertiary" style={styles.disclaimer}>
|
||||
{t('common.unofficialNotice')}
|
||||
</AppText>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
function Shortcut({
|
||||
icon,
|
||||
label,
|
||||
onPress,
|
||||
badge = 0,
|
||||
}: {
|
||||
icon: IconName;
|
||||
label: string;
|
||||
onPress: () => void;
|
||||
badge?: number;
|
||||
}) {
|
||||
const { colors } = useTheme();
|
||||
return (
|
||||
<Card onPress={onPress} style={styles.shortcut}>
|
||||
<View style={[styles.shortcutIcon, { backgroundColor: colors.primaryMuted }]}>
|
||||
<Icon name={icon} size={20} color={colors.primary} />
|
||||
</View>
|
||||
<AppText variant="caption" numberOfLines={2} style={styles.shortcutLabel}>
|
||||
{label}
|
||||
</AppText>
|
||||
{badge > 0 ? <Badge tone="primary">{String(badge)}</Badge> : null}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function InlineEmpty({
|
||||
loading,
|
||||
title,
|
||||
body,
|
||||
}: {
|
||||
loading: boolean;
|
||||
title: string;
|
||||
body?: string;
|
||||
}) {
|
||||
if (loading) {
|
||||
return (
|
||||
<View style={styles.loadingRow}>
|
||||
<AppText variant="caption" tone="tertiary">
|
||||
{title}
|
||||
</AppText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<View style={styles.emptyRow}>
|
||||
<EmptyState title={title} body={body} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function safeHost(baseUrl: string): string | null {
|
||||
try {
|
||||
return new URL(baseUrl).host;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
pad: { paddingHorizontal: spacing.lg },
|
||||
section: { gap: spacing.sm },
|
||||
identity: { flexDirection: 'row', alignItems: 'center', gap: spacing.md },
|
||||
identityBody: { flex: 1, gap: 2 },
|
||||
divider: { height: StyleSheet.hairlineWidth, marginVertical: spacing.md },
|
||||
compactTile: { paddingHorizontal: 0, minHeight: 40 },
|
||||
shortcuts: {
|
||||
flexDirection: 'row',
|
||||
gap: spacing.sm,
|
||||
paddingHorizontal: spacing.lg,
|
||||
},
|
||||
shortcut: {
|
||||
flex: 1,
|
||||
alignItems: 'center',
|
||||
gap: spacing.xs,
|
||||
paddingVertical: spacing.md,
|
||||
paddingHorizontal: spacing.sm,
|
||||
},
|
||||
shortcutIcon: {
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: radius.md,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
shortcutLabel: { textAlign: 'center' },
|
||||
emptyRow: { paddingVertical: spacing.md },
|
||||
loadingRow: { paddingHorizontal: spacing.lg, paddingVertical: spacing.lg },
|
||||
disclaimer: {
|
||||
textAlign: 'center',
|
||||
paddingHorizontal: spacing.xl,
|
||||
paddingVertical: spacing.xl,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { useState } from 'react';
|
||||
import { StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { NotificationRow, parseSubjectUrl } from '@/components/git/notification-row';
|
||||
import { QueryList } from '@/components/layout/query-list';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { SegmentedControl } from '@/components/ui/segmented';
|
||||
import { EmptyState } from '@/components/ui/state-views';
|
||||
import type { NotificationThread } from '@/core/api/types';
|
||||
import { flattenPages } from '@/core/utils/infinite';
|
||||
import {
|
||||
useMarkAllNotificationsRead,
|
||||
useMarkNotificationRead,
|
||||
useNotifications,
|
||||
} from '@/features/notifications/queries';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
import type { InboxStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<InboxStackParamList, 'Inbox'>;
|
||||
|
||||
type Filter = 'unread' | 'all';
|
||||
|
||||
/** Notification inbox with unread filter and read-marking on open. */
|
||||
export function InboxScreen({ navigation }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const [filter, setFilter] = useState<Filter>('unread');
|
||||
|
||||
const query = useNotifications(filter);
|
||||
const items: NotificationThread[] = flattenPages(query.data);
|
||||
const markRead = useMarkNotificationRead();
|
||||
const markAll = useMarkAllNotificationsRead();
|
||||
|
||||
const openThread = (thread: NotificationThread) => {
|
||||
if (thread.unread) markRead.mutate(thread.id);
|
||||
const target = parseSubjectUrl(thread.subject?.url);
|
||||
if (!target) return;
|
||||
if (target.kind === 'issue') {
|
||||
navigation.navigate('Repository', {
|
||||
screen: 'IssueDetail',
|
||||
params: { owner: target.owner, name: target.repo, index: target.index },
|
||||
});
|
||||
} else if (target.kind === 'pull') {
|
||||
navigation.navigate('Repository', {
|
||||
screen: 'PullDetail',
|
||||
params: { owner: target.owner, name: target.repo, index: target.index },
|
||||
});
|
||||
} else if (target.kind === 'commit') {
|
||||
navigation.navigate('Repository', {
|
||||
screen: 'CommitDetail',
|
||||
params: { owner: target.owner, name: target.repo, sha: target.sha },
|
||||
});
|
||||
} else {
|
||||
navigation.navigate('Repository', {
|
||||
screen: 'RepoOverview',
|
||||
params: { owner: target.owner, name: target.repo },
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const hasUnread = items.some((thread) => thread.unread);
|
||||
|
||||
return (
|
||||
<QueryList<NotificationThread>
|
||||
query={query}
|
||||
items={items}
|
||||
keyExtractor={(thread) => String(thread.id)}
|
||||
header={
|
||||
<View style={styles.header}>
|
||||
<SegmentedControl<Filter>
|
||||
value={filter}
|
||||
onChange={setFilter}
|
||||
accessibilityLabel={t('inbox.title')}
|
||||
options={[
|
||||
{ value: 'unread', label: t('inbox.filterUnread') },
|
||||
{ value: 'all', label: t('inbox.filterAll') },
|
||||
]}
|
||||
/>
|
||||
{hasUnread ? (
|
||||
<Button
|
||||
label={t('inbox.markAllRead')}
|
||||
variant="ghost"
|
||||
size="md"
|
||||
iconLeft="check"
|
||||
loading={markAll.isPending}
|
||||
onPress={() => markAll.mutate()}
|
||||
testID="inbox-mark-all-read"
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
}
|
||||
renderItem={(thread) => <NotificationRow thread={thread} onPress={() => openThread(thread)} />}
|
||||
empty={
|
||||
<EmptyState
|
||||
icon="inbox"
|
||||
title={filter === 'unread' ? t('inbox.emptyUnread') : t('inbox.empty')}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
header: { paddingHorizontal: spacing.lg, paddingTop: spacing.sm, gap: spacing.sm },
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* Issue & pull request query hooks.
|
||||
*
|
||||
* Cross-repo lists (the Issues / Pull Requests tabs) go through Gitea's
|
||||
* `/repos/issues/search`, which also powers PR search via `type=pulls`.
|
||||
*/
|
||||
|
||||
import {
|
||||
keepPreviousData,
|
||||
useInfiniteQuery,
|
||||
useQuery,
|
||||
type InfiniteData,
|
||||
} from '@tanstack/react-query';
|
||||
|
||||
import type { RawResponse } from '@/core/api/client';
|
||||
import {
|
||||
fetchIssue,
|
||||
fetchPull,
|
||||
listRepoIssues,
|
||||
listRepoLabels,
|
||||
listPulls,
|
||||
searchIssues,
|
||||
type IssueSearchParams,
|
||||
} from '@/core/api/endpoints';
|
||||
import { queryKeys } from '@/core/api/query-keys';
|
||||
import type { Issue, Label, PullRequest } from '@/core/api/types';
|
||||
import { useSession } from '@/features/accounts/use-session';
|
||||
|
||||
export type IssueScope = 'assigned' | 'created' | 'reviewRequested';
|
||||
|
||||
export interface CrossIssueFilters {
|
||||
scope: IssueScope;
|
||||
state: 'open' | 'closed' | 'all';
|
||||
search: string;
|
||||
type?: 'issues' | 'pulls';
|
||||
}
|
||||
|
||||
function scopeParams(scope: IssueScope): Partial<IssueSearchParams> {
|
||||
switch (scope) {
|
||||
case 'assigned':
|
||||
return { assigned: true };
|
||||
case 'created':
|
||||
return { created: true };
|
||||
case 'reviewRequested':
|
||||
return { reviewRequested: true };
|
||||
}
|
||||
}
|
||||
|
||||
/** Cross-repository issue list for the Issues tab. */
|
||||
export function useIssueSearch(filters: CrossIssueFilters, limit = 20) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
const params = {
|
||||
state: filters.state,
|
||||
q: filters.search.trim() || undefined,
|
||||
scope: filters.scope,
|
||||
type: filters.type ?? 'issues',
|
||||
limit,
|
||||
};
|
||||
|
||||
return useInfiniteQuery<
|
||||
RawResponse<Issue[]>,
|
||||
Error,
|
||||
InfiniteData<RawResponse<Issue[]>>,
|
||||
readonly unknown[],
|
||||
number
|
||||
>({
|
||||
queryKey: queryKeys.issueSearch(accountId, params),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
searchIssues(
|
||||
client!,
|
||||
{
|
||||
state: params.state,
|
||||
q: params.q,
|
||||
type: params.type as 'issues' | 'pulls',
|
||||
limit,
|
||||
page: pageParam,
|
||||
...scopeParams(filters.scope),
|
||||
},
|
||||
{ signal },
|
||||
),
|
||||
getNextPageParam: (last, all) => (last.hasMore ? all.length + 1 : undefined),
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
}
|
||||
|
||||
/** Issues inside one repository (used on the repository Issues tab). */
|
||||
export function useRepoIssues(
|
||||
owner: string,
|
||||
name: string,
|
||||
state: 'open' | 'closed' | 'all',
|
||||
search: string,
|
||||
limit = 20,
|
||||
) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
const params = { state, q: search.trim() || undefined, limit };
|
||||
|
||||
return useInfiniteQuery<
|
||||
RawResponse<Issue[]>,
|
||||
Error,
|
||||
InfiniteData<RawResponse<Issue[]>>,
|
||||
readonly unknown[],
|
||||
number
|
||||
>({
|
||||
queryKey: queryKeys.repoIssues(accountId, owner, name, params),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
listRepoIssues(client!, owner, name, { ...params, page: pageParam }, { signal }),
|
||||
getNextPageParam: (last, all) => (last.hasMore ? all.length + 1 : undefined),
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
}
|
||||
|
||||
export function useIssue(owner: string, name: string, index: number) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.issue(accountId, owner, name, index),
|
||||
enabled: Boolean(client) && Boolean(accountId) && Number.isInteger(index) && index > 0,
|
||||
queryFn: ({ signal }) => fetchIssue(client!, owner, name, index, { signal }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useRepoLabels(owner: string, name: string) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.repoLabels(accountId, owner, name),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
queryFn: ({ signal }) =>
|
||||
listRepoLabels(client!, owner, name, { limit: 50 }, { signal }).then((r) => r.data),
|
||||
staleTime: 5 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
/** Pull requests inside one repository. */
|
||||
export function useRepoPulls(
|
||||
owner: string,
|
||||
name: string,
|
||||
state: 'open' | 'closed' | 'all',
|
||||
limit = 20,
|
||||
) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
const params = { state, limit };
|
||||
|
||||
return useInfiniteQuery<
|
||||
RawResponse<PullRequest[]>,
|
||||
Error,
|
||||
InfiniteData<RawResponse<PullRequest[]>>,
|
||||
readonly unknown[],
|
||||
number
|
||||
>({
|
||||
queryKey: queryKeys.pulls(accountId, owner, name, params),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
listPulls(client!, owner, name, { ...params, page: pageParam }, { signal }),
|
||||
getNextPageParam: (last, all) => (last.hasMore ? all.length + 1 : undefined),
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
}
|
||||
|
||||
export function usePull(owner: string, name: string, index: number) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.pull(accountId, owner, name, index),
|
||||
enabled: Boolean(client) && Boolean(accountId) && Number.isInteger(index) && index > 0,
|
||||
queryFn: ({ signal }) => fetchPull(client!, owner, name, index, { signal }),
|
||||
});
|
||||
}
|
||||
|
||||
export type { Issue, Label, PullRequest };
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useState } from 'react';
|
||||
import { StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { IssueRow } from '@/components/git/issue-row';
|
||||
import { QueryList } from '@/components/layout/query-list';
|
||||
import { SearchBar } from '@/components/ui/search-bar';
|
||||
import { SegmentedControl } from '@/components/ui/segmented';
|
||||
import { EmptyState } from '@/components/ui/state-views';
|
||||
import type { Issue } from '@/core/api/types';
|
||||
import { flattenPages } from '@/core/utils/infinite';
|
||||
import { useIssueSearch, type IssueScope } from '@/features/issues/queries';
|
||||
import { issueDetailTarget } from '@/features/issues/target';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
import type { IssuesStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<IssuesStackParamList, 'Issues'>;
|
||||
|
||||
type StateKey = 'open' | 'closed' | 'all';
|
||||
|
||||
/** Cross-repository issues for the signed-in user. */
|
||||
export function IssuesScreen({ navigation }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const [scope, setScope] = useState<IssueScope>('assigned');
|
||||
const [state, setState] = useState<StateKey>('open');
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const query = useIssueSearch({ scope, state, search, type: 'issues' });
|
||||
const items: Issue[] = flattenPages(query.data);
|
||||
|
||||
const emptyTitle = search.trim()
|
||||
? t('issues.emptySearch', { query: search.trim() })
|
||||
: scope === 'created'
|
||||
? t('issues.emptyCreated')
|
||||
: t('issues.emptyAssigned');
|
||||
|
||||
return (
|
||||
<QueryList<Issue>
|
||||
query={query}
|
||||
items={items}
|
||||
keyExtractor={(issue) => `${issue.repository?.full_name ?? ''}-${issue.id}`}
|
||||
header={
|
||||
<View>
|
||||
<SearchBar
|
||||
value={search}
|
||||
onChangeText={setSearch}
|
||||
placeholder={t('issues.searchPlaceholder')}
|
||||
/>
|
||||
<View style={styles.filters}>
|
||||
<SegmentedControl<IssueScope>
|
||||
value={scope}
|
||||
onChange={setScope}
|
||||
accessibilityLabel={t('issues.title')}
|
||||
options={[
|
||||
{ value: 'assigned', label: t('issues.assigned') },
|
||||
{ value: 'created', label: t('issues.created') },
|
||||
{ value: 'reviewRequested', label: t('pulls.reviewRequested') },
|
||||
]}
|
||||
/>
|
||||
<SegmentedControl<StateKey>
|
||||
value={state}
|
||||
onChange={setState}
|
||||
accessibilityLabel={t('issues.title')}
|
||||
options={[
|
||||
{ value: 'open', label: t('issues.stateOpen') },
|
||||
{ value: 'closed', label: t('issues.stateClosed') },
|
||||
{ value: 'all', label: t('issues.stateAll') },
|
||||
]}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
}
|
||||
renderItem={(issue) => (
|
||||
<IssueRow
|
||||
issue={issue}
|
||||
showRepository
|
||||
onPress={() => {
|
||||
const target = issueDetailTarget(issue);
|
||||
if (target) {
|
||||
navigation.navigate('Repository', { screen: target.screen, params: target.params });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
empty={<EmptyState icon="issue" title={emptyTitle} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
filters: { gap: spacing.sm, paddingHorizontal: spacing.lg, paddingBottom: spacing.sm },
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
/** Issue/PR navigation targeting from cross-repo list responses. */
|
||||
|
||||
import type { Issue } from '@/core/api/types';
|
||||
|
||||
import { issueDetailTarget, issueRepoTarget, repoFromMeta } from './target';
|
||||
|
||||
function issue(overrides: Partial<Issue>): Issue {
|
||||
return { id: 1, number: 12, title: 't', ...overrides } as Issue;
|
||||
}
|
||||
|
||||
describe('repoFromMeta', () => {
|
||||
it('prefers explicit owner/name', () => {
|
||||
expect(repoFromMeta({ owner: 'octo', name: 'repo' })).toEqual({ owner: 'octo', name: 'repo' });
|
||||
});
|
||||
|
||||
it('splits full_name when owner/name are absent', () => {
|
||||
expect(repoFromMeta({ full_name: 'octo/repo' })).toEqual({ owner: 'octo', name: 'repo' });
|
||||
});
|
||||
|
||||
it('returns null when nothing usable is present', () => {
|
||||
expect(repoFromMeta(undefined)).toBeNull();
|
||||
expect(repoFromMeta({ full_name: 'no-slash' })).toBeNull();
|
||||
expect(repoFromMeta({})).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('issueRepoTarget', () => {
|
||||
it('resolves the repository from the embedded meta', () => {
|
||||
expect(issueRepoTarget(issue({ repository: { owner: 'o', name: 'r' } }))).toEqual({
|
||||
owner: 'o',
|
||||
name: 'r',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('issueDetailTarget', () => {
|
||||
it('routes issues to IssueDetail', () => {
|
||||
const target = issueDetailTarget(issue({ repository: { owner: 'o', name: 'r' } }));
|
||||
expect(target).toEqual({
|
||||
screen: 'IssueDetail',
|
||||
params: { owner: 'o', name: 'r', index: 12 },
|
||||
});
|
||||
});
|
||||
|
||||
it('routes pull requests to PullDetail', () => {
|
||||
const target = issueDetailTarget(
|
||||
issue({ repository: { owner: 'o', name: 'r' }, pull_request: { merged: false } }),
|
||||
);
|
||||
expect(target?.screen).toBe('PullDetail');
|
||||
});
|
||||
|
||||
it('returns null when the repository cannot be resolved', () => {
|
||||
expect(issueDetailTarget(issue({}))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { Issue, RepositoryMeta } from '@/core/api/types';
|
||||
|
||||
export interface RepoTarget {
|
||||
owner: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** Resolves owner/name for an issue's repository (list responses embed a meta object). */
|
||||
export function repoFromMeta(meta: RepositoryMeta | undefined): RepoTarget | null {
|
||||
if (!meta) return null;
|
||||
if (meta.owner && meta.name) return { owner: meta.owner, name: meta.name };
|
||||
const full = meta.full_name;
|
||||
if (full && full.includes('/')) {
|
||||
const [owner, name] = full.split('/');
|
||||
return { owner, name };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function issueRepoTarget(issue: Issue): RepoTarget | null {
|
||||
return repoFromMeta(issue.repository);
|
||||
}
|
||||
|
||||
/** Navigation target for an issue/PR row in a cross-repo list. */
|
||||
export function issueDetailTarget(
|
||||
issue: Issue,
|
||||
): { screen: 'IssueDetail' | 'PullDetail'; params: { owner: string; name: string; index: number } } | null {
|
||||
const target = issueRepoTarget(issue);
|
||||
if (!target) return null;
|
||||
return {
|
||||
screen: issue.pull_request ? 'PullDetail' : 'IssueDetail',
|
||||
params: { ...target, index: issue.number },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/** Notification (Inbox) queries + read-marking mutations. */
|
||||
|
||||
import {
|
||||
keepPreviousData,
|
||||
useInfiniteQuery,
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
type InfiniteData,
|
||||
} from '@tanstack/react-query';
|
||||
|
||||
import type { RawResponse } from '@/core/api/client';
|
||||
import {
|
||||
fetchUnreadNotificationCount,
|
||||
listNotifications,
|
||||
markAllNotificationsRead,
|
||||
markNotificationThreadRead,
|
||||
} from '@/core/api/endpoints';
|
||||
import { queryKeys } from '@/core/api/query-keys';
|
||||
import type { NotificationThread } from '@/core/api/types';
|
||||
import { useSession } from '@/features/accounts/use-session';
|
||||
|
||||
export function useNotifications(filter: 'unread' | 'all', limit = 20) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
const params = { all: filter === 'all', limit };
|
||||
|
||||
return useInfiniteQuery<
|
||||
RawResponse<NotificationThread[]>,
|
||||
Error,
|
||||
InfiniteData<RawResponse<NotificationThread[]>>,
|
||||
readonly unknown[],
|
||||
number
|
||||
>({
|
||||
queryKey: queryKeys.notifications(accountId, params),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
listNotifications(client!, { ...params, page: pageParam }, { signal }),
|
||||
getNextPageParam: (last, all) => (last.hasMore ? all.length + 1 : undefined),
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
}
|
||||
|
||||
/** Unread badge count (tab badge + Home shortcut). */
|
||||
export function useUnreadCount(pollSeconds = 60) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.unreadCount(accountId),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
queryFn: ({ signal }) => fetchUnreadNotificationCount(client!, { signal }),
|
||||
refetchInterval: pollSeconds > 0 ? pollSeconds * 1000 : false,
|
||||
staleTime: pollSeconds > 0 ? pollSeconds * 500 : 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useMarkNotificationRead() {
|
||||
const { client, account } = useSession();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (threadId: number) => markNotificationThreadRead(client!, threadId),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.notificationsRoot(account?.id ?? '') });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.unreadCount(account?.id ?? '') });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useMarkAllNotificationsRead() {
|
||||
const { client, account } = useSession();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: () => markAllNotificationsRead(client!),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.account(account?.id ?? '') });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useState } from 'react';
|
||||
import { StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { IssueRow } from '@/components/git/issue-row';
|
||||
import { QueryList } from '@/components/layout/query-list';
|
||||
import { SearchBar } from '@/components/ui/search-bar';
|
||||
import { SegmentedControl } from '@/components/ui/segmented';
|
||||
import { EmptyState } from '@/components/ui/state-views';
|
||||
import type { Issue } from '@/core/api/types';
|
||||
import { flattenPages } from '@/core/utils/infinite';
|
||||
import { useIssueSearch, type IssueScope } from '@/features/issues/queries';
|
||||
import { issueDetailTarget } from '@/features/issues/target';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
import type { PullsStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<PullsStackParamList, 'PullRequests'>;
|
||||
|
||||
type StateKey = 'open' | 'closed' | 'all';
|
||||
type PullScope = Extract<IssueScope, 'reviewRequested' | 'created'>;
|
||||
|
||||
/**
|
||||
* Cross-repository pull requests. Gitea's search endpoint covers PRs with
|
||||
* `type=pulls`, so this reuses the issue search shape.
|
||||
*/
|
||||
export function PullRequestsScreen({ navigation }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const [scope, setScope] = useState<PullScope>('reviewRequested');
|
||||
const [state, setState] = useState<StateKey>('open');
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const query = useIssueSearch({ scope, state, search, type: 'pulls' });
|
||||
const items: Issue[] = flattenPages(query.data);
|
||||
|
||||
const emptyTitle = search.trim()
|
||||
? t('pulls.emptySearch', { query: search.trim() })
|
||||
: scope === 'created'
|
||||
? t('pulls.emptyCreated')
|
||||
: t('pulls.emptyReview');
|
||||
|
||||
return (
|
||||
<QueryList<Issue>
|
||||
query={query}
|
||||
items={items}
|
||||
keyExtractor={(issue) => `${issue.repository?.full_name ?? ''}-${issue.id}`}
|
||||
header={
|
||||
<View>
|
||||
<SearchBar
|
||||
value={search}
|
||||
onChangeText={setSearch}
|
||||
placeholder={t('pulls.searchPlaceholder')}
|
||||
/>
|
||||
<View style={styles.filters}>
|
||||
<SegmentedControl<PullScope>
|
||||
value={scope}
|
||||
onChange={setScope}
|
||||
accessibilityLabel={t('pulls.title')}
|
||||
options={[
|
||||
{ value: 'reviewRequested', label: t('pulls.reviewRequested') },
|
||||
{ value: 'created', label: t('pulls.created') },
|
||||
]}
|
||||
/>
|
||||
<SegmentedControl<StateKey>
|
||||
value={state}
|
||||
onChange={setState}
|
||||
accessibilityLabel={t('pulls.title')}
|
||||
options={[
|
||||
{ value: 'open', label: t('pulls.stateOpen') },
|
||||
{ value: 'closed', label: t('pulls.stateClosed') },
|
||||
{ value: 'all', label: t('pulls.stateAll') },
|
||||
]}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
}
|
||||
renderItem={(issue) => (
|
||||
<IssueRow
|
||||
issue={issue}
|
||||
showRepository
|
||||
onPress={() => {
|
||||
const target = issueDetailTarget(issue);
|
||||
if (target) {
|
||||
navigation.navigate('Repository', { screen: target.screen, params: target.params });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
empty={<EmptyState icon="pullRequest" title={emptyTitle} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
filters: { gap: spacing.sm, paddingHorizontal: spacing.lg, paddingBottom: spacing.sm },
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Query hooks for repositories (list/search/starred) and repository detail.
|
||||
* Every key is account-scoped via queryKeys; hooks disable themselves when
|
||||
* there is no authenticated session.
|
||||
*/
|
||||
|
||||
import {
|
||||
keepPreviousData,
|
||||
useInfiniteQuery,
|
||||
useQuery,
|
||||
type InfiniteData,
|
||||
} from '@tanstack/react-query';
|
||||
|
||||
import { useSession } from '@/features/accounts/use-session';
|
||||
import {
|
||||
fetchRepository,
|
||||
fetchRepositoryLanguages,
|
||||
listMyRepos,
|
||||
listStarredRepos,
|
||||
searchRepositories,
|
||||
type ListMyReposParams,
|
||||
type SearchReposParams,
|
||||
} from '@/core/api/endpoints';
|
||||
import type { RawResponse } from '@/core/api/client';
|
||||
import { queryKeys } from '@/core/api/query-keys';
|
||||
import type { Repository } from '@/core/api/types';
|
||||
|
||||
type RepoPage = RawResponse<Repository[]>;
|
||||
|
||||
export interface RepoListFilters {
|
||||
pageLimit?: number;
|
||||
}
|
||||
|
||||
/** Repos owned by / accessible to the authenticated user. */
|
||||
export function useMyRepos(visibility: ListMyReposParams['visibility'] = 'all', limit = 20) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
const params = { visibility, limit };
|
||||
|
||||
return useInfiniteQuery<RepoPage, Error, InfiniteData<RepoPage>, readonly unknown[], number>({
|
||||
queryKey: queryKeys.repos.mine(accountId, params),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
listMyRepos(client!, { ...params, page: pageParam }, { signal }),
|
||||
getNextPageParam: (last, all) => (last.hasMore ? all.length + 1 : undefined),
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
}
|
||||
|
||||
/** Repo search with a query string; sort only applies when there is no query. */
|
||||
export function useSearchRepos(search: string, sort: SearchReposParams['sort'] = 'updated') {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
const params = { q: search.trim(), sort, limit: 20 };
|
||||
const isSearch = params.q.length > 0;
|
||||
|
||||
return useInfiniteQuery<RepoPage, Error, InfiniteData<RepoPage>, readonly unknown[], number>({
|
||||
queryKey: queryKeys.repos.search(accountId, params),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
searchRepositories(client!, { ...params, page: pageParam }, { signal }),
|
||||
getNextPageParam: (last, all) => (last.hasMore ? all.length + 1 : undefined),
|
||||
placeholderData: keepPreviousData,
|
||||
// Search endpoint ignores sort when q is set — harmless either way.
|
||||
staleTime: isSearch ? 15_000 : 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
/** Repositories the user starred. */
|
||||
export function useStarredRepos(limit = 20) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
const params = { limit };
|
||||
|
||||
return useInfiniteQuery<RepoPage, Error, InfiniteData<RepoPage>, readonly unknown[], number>({
|
||||
queryKey: queryKeys.repos.starred(accountId, params),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
listStarredRepos(client!, { ...params, page: pageParam }, { signal }),
|
||||
getNextPageParam: (last, all) => (last.hasMore ? all.length + 1 : undefined),
|
||||
});
|
||||
}
|
||||
|
||||
/** Single repository detail. */
|
||||
export function useRepository(owner: string, name: string) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.repoDetail(accountId, owner, name),
|
||||
enabled: Boolean(client) && Boolean(accountId) && owner.length > 0,
|
||||
queryFn: ({ signal }) => fetchRepository(client!, owner, name, { signal }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Language breakdown (bytes per language). */
|
||||
export function useRepositoryLanguages(owner: string, name: string) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.repoLanguages(accountId, owner, name),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
queryFn: ({ signal }) => fetchRepositoryLanguages(client!, owner, name, { signal }),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { View, StyleSheet } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { RepoListItem } from '@/components/git/repo-list-item';
|
||||
import { QueryList } from '@/components/layout/query-list';
|
||||
import { SearchBar } from '@/components/ui/search-bar';
|
||||
import { EmptyState } from '@/components/ui/state-views';
|
||||
import { SegmentedControl } from '@/components/ui/segmented';
|
||||
|
||||
import { useMyRepos, useSearchRepos } from '@/features/repositories/queries';
|
||||
import { flattenPages } from '@/core/utils/infinite';
|
||||
import type { Repository } from '@/core/api/types';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
import type { RepositoriesStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<RepositoriesStackParamList, 'RepositoryList'>;
|
||||
|
||||
type Visibility = 'all' | 'private' | 'public';
|
||||
type SortKey = 'updated' | 'name' | 'stars' | 'created';
|
||||
|
||||
/** Repository browser: search, visibility filter and client-side sorting. */
|
||||
export function RepositoryListScreen({ navigation }: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [search, setSearch] = useState('');
|
||||
const [visibility, setVisibility] = useState<Visibility>('all');
|
||||
const [sort, setSort] = useState<SortKey>('updated');
|
||||
|
||||
const searching = search.trim().length > 0;
|
||||
const browseQuery = useMyRepos(visibility);
|
||||
const searchQuery = useSearchRepos(search);
|
||||
|
||||
// One list at a time: search endpoint while typing, /user/repos otherwise.
|
||||
const query = searching ? searchQuery : browseQuery;
|
||||
const rawItems: Repository[] = useMemo(
|
||||
() => flattenPages(searching ? searchQuery.data : browseQuery.data),
|
||||
[searching, searchQuery.data, browseQuery.data],
|
||||
);
|
||||
|
||||
// /user/repos has no sort parameter; sort the loaded pages client-side.
|
||||
const items = useMemo(() => {
|
||||
if (searching) return rawItems;
|
||||
const sorted = [...rawItems];
|
||||
switch (sort) {
|
||||
case 'name':
|
||||
sorted.sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''));
|
||||
break;
|
||||
case 'stars':
|
||||
sorted.sort((a, b) => (b.stars_count ?? 0) - (a.stars_count ?? 0));
|
||||
break;
|
||||
case 'created':
|
||||
sorted.sort((a, b) => (b.created_at ?? '').localeCompare(a.created_at ?? ''));
|
||||
break;
|
||||
case 'updated':
|
||||
default:
|
||||
break; // server order = recently updated
|
||||
}
|
||||
return sorted;
|
||||
}, [rawItems, sort, searching]);
|
||||
|
||||
const header = (
|
||||
<View>
|
||||
<SearchBar
|
||||
value={search}
|
||||
onChangeText={setSearch}
|
||||
placeholder={t('repositories.searchPlaceholder')}
|
||||
testID="repo-search"
|
||||
/>
|
||||
<View style={styles.filters}>
|
||||
<SegmentedControl<Visibility>
|
||||
accessibilityLabel={t('repositories.title')}
|
||||
value={visibility}
|
||||
onChange={setVisibility}
|
||||
options={[
|
||||
{ value: 'all', label: t('repositories.visibilityAll') },
|
||||
{ value: 'private', label: t('repositories.visibilityPrivate') },
|
||||
{ value: 'public', label: t('repositories.visibilityPublic') },
|
||||
]}
|
||||
/>
|
||||
{!searching ? (
|
||||
<SegmentedControl<SortKey>
|
||||
accessibilityLabel={t('repositories.title')}
|
||||
value={sort}
|
||||
onChange={setSort}
|
||||
options={[
|
||||
{ value: 'updated', label: t('repositories.sortUpdated') },
|
||||
{ value: 'name', label: t('repositories.sortName') },
|
||||
{ value: 'stars', label: t('repositories.sortStars') },
|
||||
{ value: 'created', label: t('repositories.sortCreated') },
|
||||
]}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
|
||||
return (
|
||||
<QueryList<Repository>
|
||||
query={query}
|
||||
items={items}
|
||||
keyExtractor={(repo) => repo.full_name}
|
||||
header={header}
|
||||
loadingRows={8}
|
||||
renderItem={(repo) => (
|
||||
<RepoListItem
|
||||
repo={repo}
|
||||
onPress={() =>
|
||||
navigation.navigate('Repository', {
|
||||
screen: 'RepoOverview',
|
||||
params: { owner: repo.owner?.login ?? repo.full_name.split('/')[0], name: repo.name },
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
empty={
|
||||
searching ? (
|
||||
<EmptyState
|
||||
icon="search"
|
||||
title={t('repositories.emptySearch', { query: search.trim() })}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState icon="repo" title={t('repositories.empty')} />
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
filters: { gap: spacing.sm, paddingHorizontal: spacing.lg, paddingBottom: spacing.sm },
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
/** Query hooks for repository browsing: contents, README, branches, tags, commits. */
|
||||
|
||||
import {
|
||||
keepPreviousData,
|
||||
useInfiniteQuery,
|
||||
useQuery,
|
||||
type InfiniteData,
|
||||
} from '@tanstack/react-query';
|
||||
|
||||
import type { RawResponse } from '@/core/api/client';
|
||||
import {
|
||||
fetchBranch,
|
||||
fetchCommit,
|
||||
fetchFile,
|
||||
fetchReadme,
|
||||
listBranches,
|
||||
listCommits,
|
||||
listContents,
|
||||
listTags,
|
||||
} from '@/core/api/endpoints';
|
||||
import { queryKeys } from '@/core/api/query-keys';
|
||||
import type { Branch, Commit, Tag } from '@/core/api/types';
|
||||
import { useSession } from '@/features/accounts/use-session';
|
||||
|
||||
/** Directory listing (or file entry when a path is given). */
|
||||
export function useContents(owner: string, name: string, path: string, ref?: string) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.contents(accountId, owner, name, path, ref),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
queryFn: ({ signal }) => listContents(client!, owner, name, path, { ref }, { signal }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Single file (content + metadata). */
|
||||
export function useFile(owner: string, name: string, path: string, ref?: string) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.file(accountId, owner, name, path, ref),
|
||||
enabled: Boolean(client) && Boolean(accountId) && path.length > 0,
|
||||
queryFn: ({ signal }) => fetchFile(client!, owner, name, path, { ref }, { signal }),
|
||||
});
|
||||
}
|
||||
|
||||
/** README resolved from the repository root; null when the repo has none. */
|
||||
export function useReadme(owner: string, name: string, ref?: string) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.readme(accountId, owner, name, ref),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
queryFn: ({ signal }) => fetchReadme(client!, owner, name, { ref }, { signal }),
|
||||
staleTime: 5 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useBranches(
|
||||
owner: string,
|
||||
name: string,
|
||||
search: string,
|
||||
limit = 30,
|
||||
) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
const params = { q: search.trim() || undefined, limit };
|
||||
|
||||
return useInfiniteQuery<
|
||||
RawResponse<Branch[]>,
|
||||
Error,
|
||||
InfiniteData<RawResponse<Branch[]>>,
|
||||
readonly unknown[],
|
||||
number
|
||||
>({
|
||||
queryKey: queryKeys.branches(accountId, owner, name, params),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
listBranches(client!, owner, name, { ...params, page: pageParam }, { signal }),
|
||||
getNextPageParam: (last, all) => (last.hasMore ? all.length + 1 : undefined),
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
}
|
||||
|
||||
export function useBranch(owner: string, name: string, branch: string) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.branch(accountId, owner, name, branch),
|
||||
enabled: Boolean(client) && Boolean(accountId) && branch.length > 0,
|
||||
queryFn: ({ signal }) => fetchBranch(client!, owner, name, branch, { signal }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useTags(owner: string, name: string, limit = 30) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
const params = { limit };
|
||||
|
||||
return useInfiniteQuery<
|
||||
RawResponse<Tag[]>,
|
||||
Error,
|
||||
InfiniteData<RawResponse<Tag[]>>,
|
||||
readonly unknown[],
|
||||
number
|
||||
>({
|
||||
queryKey: queryKeys.tags(accountId, owner, name, params),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
listTags(client!, owner, name, { ...params, page: pageParam }, { signal }),
|
||||
getNextPageParam: (last, all) => (last.hasMore ? all.length + 1 : undefined),
|
||||
});
|
||||
}
|
||||
|
||||
export interface CommitListOptions {
|
||||
/** Branch/tag/SHA to walk. */
|
||||
sha?: string;
|
||||
/** Restrict to a path. */
|
||||
path?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export function useCommits(owner: string, name: string, options: CommitListOptions = {}) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
const params = { sha: options.sha, path: options.path, limit: options.limit ?? 20 };
|
||||
|
||||
return useInfiniteQuery<
|
||||
RawResponse<Commit[]>,
|
||||
Error,
|
||||
InfiniteData<RawResponse<Commit[]>>,
|
||||
readonly unknown[],
|
||||
number
|
||||
>({
|
||||
queryKey: queryKeys.commits(accountId, owner, name, params),
|
||||
enabled: Boolean(client) && Boolean(accountId),
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
listCommits(client!, owner, name, { ...params, page: pageParam }, { signal }),
|
||||
getNextPageParam: (last, all) => (last.hasMore ? all.length + 1 : undefined),
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCommit(owner: string, name: string, sha: string) {
|
||||
const { client, account } = useSession();
|
||||
const accountId = account?.id ?? '';
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.commit(accountId, owner, name, sha),
|
||||
enabled: Boolean(client) && Boolean(accountId) && sha.length > 0,
|
||||
queryFn: ({ signal }) => fetchCommit(client!, owner, name, sha, { signal }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Convenience: decode a base64 contents payload from the API. */
|
||||
export function decodeBase64(content: string): string {
|
||||
// Gitea returns base64 without line wrapping; atob is available in Hermes.
|
||||
try {
|
||||
return globalThis.atob(content.replace(/\s/g, ''));
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { QueryList } from '@/components/layout/query-list';
|
||||
import { SearchBar } from '@/components/ui/search-bar';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ListItem } from '@/components/ui/list-item';
|
||||
import { EmptyState } from '@/components/ui/state-views';
|
||||
import type { Branch } from '@/core/api/types';
|
||||
import { firstLine, formatRelativeTime, shortSha } from '@/core/utils/format';
|
||||
import { flattenPages } from '@/core/utils/infinite';
|
||||
import { useBranches } from '@/features/repository/queries';
|
||||
import { useRepository } from '@/features/repositories/queries';
|
||||
import type { RepositoryStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<RepositoryStackParamList, 'Branches'>;
|
||||
|
||||
/** Branch list with search; tapping a branch opens its file tree. */
|
||||
export function BranchesScreen({ navigation, route }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { owner, name } = route.params;
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const query = useBranches(owner, name, search);
|
||||
const repo = useRepository(owner, name);
|
||||
const defaultBranch = repo.data?.default_branch;
|
||||
const branches: Branch[] = flattenPages(query.data);
|
||||
|
||||
return (
|
||||
<QueryList<Branch>
|
||||
query={query}
|
||||
items={branches}
|
||||
keyExtractor={(branch) => branch.name}
|
||||
header={
|
||||
<SearchBar
|
||||
value={search}
|
||||
onChangeText={setSearch}
|
||||
placeholder={t('branches.searchPlaceholder')}
|
||||
/>
|
||||
}
|
||||
renderItem={(branch) => {
|
||||
const isDefault = branch.name === defaultBranch;
|
||||
return (
|
||||
<ListItem
|
||||
leadingIcon="branch"
|
||||
title={branch.name}
|
||||
subtitle={firstLine(branch.commit?.message)}
|
||||
meta={[
|
||||
branch.commit?.id ? shortSha(branch.commit.id) : null,
|
||||
formatRelativeTime(branch.commit?.timestamp, t),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
trailing={
|
||||
isDefault || branch.protected ? (
|
||||
<Badge tone={isDefault ? 'primary' : 'warning'} icon={isDefault ? 'star' : 'shield'}>
|
||||
{isDefault ? t('branches.default') : t('branches.protected')}
|
||||
</Badge>
|
||||
) : undefined
|
||||
}
|
||||
onPress={() => navigation.navigate('Files', { owner, name, ref: branch.name })}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
empty={<EmptyState icon="branch" title={t('branches.empty')} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { Avatar } from '@/components/ui/avatar';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { ErrorState, LoadingView } from '@/components/ui/state-views';
|
||||
import { apiErrorMessage } from '@/core/api/error-text';
|
||||
import type { CommitAffectedFile } from '@/core/api/types';
|
||||
import { useCommit } from '@/features/repository/queries';
|
||||
import { formatDateTime, shortSha } from '@/core/utils/format';
|
||||
import { useTheme } from '@/theme/theme-provider';
|
||||
import { fontFamily, fontSize, spacing } from '@/theme/tokens';
|
||||
import type { RepositoryStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<RepositoryStackParamList, 'CommitDetail'>;
|
||||
|
||||
/** Single commit: metadata, message, stats and per-file diffs. */
|
||||
export function CommitDetailScreen({ route }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { colors } = useTheme();
|
||||
const { owner, name, sha } = route.params;
|
||||
|
||||
const query = useCommit(owner, name, sha);
|
||||
const commit = query.data;
|
||||
|
||||
if (query.isPending) return <LoadingView />;
|
||||
if (query.isError) {
|
||||
return (
|
||||
<ErrorState
|
||||
title={t('errors.title')}
|
||||
body={apiErrorMessage(query.error, t)}
|
||||
retryLabel={t('common.retry')}
|
||||
onRetry={() => void query.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!commit) return null;
|
||||
|
||||
const message = commit.commit.message ?? '';
|
||||
const title = splitCommitTitle(message);
|
||||
const body = splitCommitBody(message);
|
||||
const author = commit.author;
|
||||
const authorName = author?.login ?? commit.commit.author?.name ?? t('common.unknown');
|
||||
const date = commit.commit.author?.date ?? commit.created;
|
||||
const files = commit.files ?? [];
|
||||
|
||||
return (
|
||||
<Screen scroll padded>
|
||||
<View style={styles.titleBlock}>
|
||||
<AppText variant="heading">{title}</AppText>
|
||||
{body ? (
|
||||
<AppText variant="secondary" tone="secondary">
|
||||
{body}
|
||||
</AppText>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<View style={styles.metaRow}>
|
||||
<Avatar url={author?.avatar_url} name={authorName} size={32} />
|
||||
<View style={styles.metaBody}>
|
||||
<AppText variant="bodyMedium">{authorName}</AppText>
|
||||
<AppText variant="caption" tone="tertiary">
|
||||
{formatDateTime(date)}
|
||||
</AppText>
|
||||
</View>
|
||||
<View style={[styles.shaChip, { backgroundColor: colors.surfaceSecondary }]}>
|
||||
<AppText variant="monoSmall" tone="tertiary">
|
||||
{shortSha(commit.sha)}
|
||||
</AppText>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{commit.stats ? (
|
||||
<View style={styles.stats}>
|
||||
<Badge tone="success">
|
||||
{`+${commit.stats.additions ?? 0}`}
|
||||
</Badge>
|
||||
<Badge tone="error">{`−${commit.stats.deletions ?? 0}`}</Badge>
|
||||
<AppText variant="caption" tone="tertiary">
|
||||
{t('commits.filesChanged', { count: files.length || (commit.stats.total ?? 0) })}
|
||||
</AppText>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{commit.commit.verification ? (
|
||||
<Badge tone={commit.commit.verification.verified ? 'success' : 'warning'} icon={commit.commit.verification.verified ? 'verified' : 'unverified'}>
|
||||
{commit.commit.verification.verified ? t('commits.verified') : t('commits.unverified')}
|
||||
</Badge>
|
||||
) : null}
|
||||
|
||||
{files.map((file, index) => (
|
||||
<FileDiff key={`${file.filename ?? index}`} file={file} />
|
||||
))}
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
function FileDiff({ file }: { file: CommitAffectedFile }) {
|
||||
const { t } = useTranslation();
|
||||
const { colors } = useTheme();
|
||||
|
||||
return (
|
||||
<Card padded={false} style={styles.diffCard}>
|
||||
<View style={[styles.diffHeader, { borderBottomColor: colors.border }]}>
|
||||
<AppText variant="monoSmall" numberOfLines={1} style={styles.diffPath}>
|
||||
{file.filename ?? ''}
|
||||
</AppText>
|
||||
<View style={styles.diffBadges}>
|
||||
<AppText variant="caption" style={{ color: colors.success }}>
|
||||
+{file.additions ?? 0}
|
||||
</AppText>
|
||||
<AppText variant="caption" style={{ color: colors.error }}>
|
||||
−{file.deletions ?? 0}
|
||||
</AppText>
|
||||
</View>
|
||||
</View>
|
||||
{file.patch ? (
|
||||
<View style={styles.patch}>
|
||||
{file.patch.split('\n').map((line, lineIndex) => (
|
||||
<AppText
|
||||
key={lineIndex}
|
||||
variant="monoSmall"
|
||||
selectable
|
||||
style={[
|
||||
styles.patchLine,
|
||||
line.startsWith('+') && !line.startsWith('+++')
|
||||
? { color: colors.diffAddText }
|
||||
: line.startsWith('-') && !line.startsWith('---')
|
||||
? { color: colors.diffDelText }
|
||||
: line.startsWith('@@')
|
||||
? { color: colors.textTertiary }
|
||||
: { color: colors.text },
|
||||
]}
|
||||
>
|
||||
{line || ' '}
|
||||
</AppText>
|
||||
))}
|
||||
</View>
|
||||
) : (
|
||||
<AppText variant="caption" tone="tertiary" style={styles.noPatch}>
|
||||
{t('files.binary')}
|
||||
</AppText>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function splitCommitTitle(message: string): string {
|
||||
return message.split('\n', 1)[0]?.trim() || '';
|
||||
}
|
||||
|
||||
function splitCommitBody(message: string): string {
|
||||
const parts = message.split('\n');
|
||||
const body = parts.slice(1).join('\n').trim();
|
||||
return body;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
titleBlock: { gap: spacing.sm },
|
||||
metaRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.md },
|
||||
metaBody: { flex: 1, gap: 2 },
|
||||
shaChip: { paddingHorizontal: spacing.sm, paddingVertical: 2, borderRadius: 6 },
|
||||
stats: { flexDirection: 'row', alignItems: 'center', gap: spacing.md, flexWrap: 'wrap' },
|
||||
diffCard: { overflow: 'hidden' },
|
||||
diffHeader: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
gap: spacing.sm,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm,
|
||||
borderBottomWidth: StyleSheet.hairlineWidth,
|
||||
},
|
||||
diffPath: { flex: 1 },
|
||||
diffBadges: { flexDirection: 'row', gap: spacing.sm },
|
||||
patch: { padding: spacing.md },
|
||||
patchLine: {
|
||||
fontFamily: fontFamily.mono,
|
||||
fontSize: fontSize.xs,
|
||||
lineHeight: 17,
|
||||
},
|
||||
noPatch: { padding: spacing.md },
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { View } from 'react-native';
|
||||
|
||||
import { CommitRow } from '@/components/git/commit-row';
|
||||
import { QueryList } from '@/components/layout/query-list';
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { EmptyState } from '@/components/ui/state-views';
|
||||
import type { Commit } from '@/core/api/types';
|
||||
import { flattenPages } from '@/core/utils/infinite';
|
||||
import { useCommits } from '@/features/repository/queries';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
import type { RepositoryStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<RepositoryStackParamList, 'Commits'>;
|
||||
|
||||
/** Commit history for a repository (optionally restricted to a path). */
|
||||
export function CommitsScreen({ navigation, route }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { owner, name, sha, path } = route.params;
|
||||
|
||||
const query = useCommits(owner, name, { sha, path });
|
||||
const items: Commit[] = flattenPages(query.data);
|
||||
|
||||
return (
|
||||
<QueryList<Commit>
|
||||
query={query}
|
||||
items={items}
|
||||
keyExtractor={(commit) => commit.sha}
|
||||
header={
|
||||
path ? (
|
||||
<View style={{ paddingHorizontal: spacing.lg, paddingTop: spacing.sm }}>
|
||||
<AppText variant="caption" tone="tertiary">
|
||||
{t('commits.fileFilter', { path })}
|
||||
</AppText>
|
||||
</View>
|
||||
) : undefined
|
||||
}
|
||||
renderItem={(commit) => (
|
||||
<CommitRow
|
||||
commit={commit}
|
||||
onPress={() => navigation.navigate('CommitDetail', { owner, name, sha: commit.sha })}
|
||||
/>
|
||||
)}
|
||||
empty={
|
||||
<EmptyState
|
||||
icon="commit"
|
||||
title={path ? t('commits.emptyPath') : t('commits.empty')}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { Image } from 'expo-image';
|
||||
import { ScrollView, StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Markdown } from '@/components/git/markdown';
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { ErrorState, LoadingView } from '@/components/ui/state-views';
|
||||
import { apiErrorMessage } from '@/core/api/error-text';
|
||||
import { useSession } from '@/features/accounts/use-session';
|
||||
import { decodeBase64, useFile } from '@/features/repository/queries';
|
||||
import { formatBytes } from '@/core/utils/format';
|
||||
import { useTheme } from '@/theme/theme-provider';
|
||||
import { fontFamily, fontSize, spacing } from '@/theme/tokens';
|
||||
import type { RepositoryStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<RepositoryStackParamList, 'FileViewer'>;
|
||||
|
||||
const IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg']);
|
||||
const MARKDOWN_EXTENSIONS = new Set(['md', 'markdown', 'mdown', 'mkd']);
|
||||
const LARGE_FILE_BYTES = 1_000_000;
|
||||
|
||||
function extensionOf(path: string): string {
|
||||
const last = path.split('/').pop() ?? '';
|
||||
const dot = last.lastIndexOf('.');
|
||||
return dot >= 0 ? last.slice(dot + 1).toLowerCase() : '';
|
||||
}
|
||||
|
||||
/** Renders a single file: image preview, markdown, or source text. */
|
||||
export function FileViewerScreen({ route }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { colors } = useTheme();
|
||||
const { instance, token } = useSession();
|
||||
const { owner, name, path, ref } = route.params;
|
||||
|
||||
const query = useFile(owner, name, path, ref);
|
||||
const entry = query.data;
|
||||
const extension = extensionOf(path);
|
||||
|
||||
if (query.isPending) return <LoadingView label={t('files.loadingFile')} />;
|
||||
|
||||
if (query.isError) {
|
||||
return (
|
||||
<ErrorState
|
||||
title={t('files.rawUnavailable')}
|
||||
body={apiErrorMessage(query.error, t)}
|
||||
retryLabel={t('common.retry')}
|
||||
onRetry={() => void query.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (!entry) return null;
|
||||
|
||||
if (entry.type === 'symlink' || entry.type === 'submodule') {
|
||||
return (
|
||||
<Screen padded>
|
||||
<Card>
|
||||
<AppText variant="bodyMedium">
|
||||
{entry.type === 'submodule' ? t('files.submodule') : t('files.symlink', { target: entry.target ?? '' })}
|
||||
</AppText>
|
||||
</Card>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
if (IMAGE_EXTENSIONS.has(extension) && entry.download_url) {
|
||||
const host = instance ? safeHost(instance.baseUrl) : null;
|
||||
const headers =
|
||||
token && host && safeHost(entry.download_url) === host
|
||||
? { Authorization: `token ${token}` }
|
||||
: undefined;
|
||||
return (
|
||||
<Screen padded>
|
||||
<Card padded={false} style={styles.imageCard}>
|
||||
<Image
|
||||
source={{ uri: entry.download_url, headers }}
|
||||
style={styles.image}
|
||||
contentFit="contain"
|
||||
transition={150}
|
||||
accessibilityLabel={entry.name}
|
||||
/>
|
||||
</Card>
|
||||
<AppText variant="caption" tone="tertiary" style={styles.center}>
|
||||
{t('files.image')} · {formatBytes(entry.size)}
|
||||
</AppText>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
const content = entry.content ? decodeBase64(entry.content) : '';
|
||||
|
||||
if (!content) {
|
||||
return (
|
||||
<Screen padded>
|
||||
<Card>
|
||||
<AppText variant="bodyMedium">{t('files.binary')}</AppText>
|
||||
<AppText variant="caption" tone="tertiary">
|
||||
{formatBytes(entry.size)}
|
||||
</AppText>
|
||||
</Card>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
const lineCount = content.length > 0 ? content.split('\n').length : 0;
|
||||
|
||||
return (
|
||||
<Screen padded={false}>
|
||||
{entry.size >= LARGE_FILE_BYTES ? (
|
||||
<AppText variant="caption" tone="warning" style={styles.notice}>
|
||||
{t('files.large', { size: formatBytes(entry.size) })}
|
||||
</AppText>
|
||||
) : null}
|
||||
{MARKDOWN_EXTENSIONS.has(extension) ? (
|
||||
<View style={styles.markdownWrap}>
|
||||
<Markdown content={content} baseUrl={instance?.baseUrl} />
|
||||
</View>
|
||||
) : (
|
||||
<ScrollView horizontal showsHorizontalScrollIndicator contentContainerStyle={styles.codeOuter}>
|
||||
<ScrollView contentContainerStyle={styles.codeInner}>
|
||||
<AppText variant="monoSmall" selectable style={[styles.code, { color: colors.text }]}>
|
||||
{content}
|
||||
</AppText>
|
||||
</ScrollView>
|
||||
</ScrollView>
|
||||
)}
|
||||
<AppText variant="caption" tone="tertiary" style={styles.notice}>
|
||||
{t('files.lines', { count: lineCount })} · {formatBytes(entry.size)}
|
||||
</AppText>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
function safeHost(url: string): string | null {
|
||||
try {
|
||||
return new URL(url).host;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
notice: { paddingHorizontal: spacing.lg, paddingVertical: spacing.sm },
|
||||
markdownWrap: { paddingHorizontal: spacing.lg },
|
||||
imageCard: { overflow: 'hidden', minHeight: 200 },
|
||||
image: { width: '100%', height: 320 },
|
||||
center: { textAlign: 'center' },
|
||||
codeOuter: {},
|
||||
codeInner: { paddingHorizontal: spacing.lg, paddingVertical: spacing.sm },
|
||||
code: {
|
||||
fontFamily: fontFamily.mono,
|
||||
fontSize: fontSize.sm,
|
||||
lineHeight: 19,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { useMemo } from 'react';
|
||||
import { StyleSheet, View } from 'react-native';
|
||||
import { FlashList } from '@shopify/flash-list';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Breadcrumb, FileRow } from '@/components/git/file-row';
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { ErrorState, EmptyState, LoadingView } from '@/components/ui/state-views';
|
||||
import { apiErrorMessage } from '@/core/api/error-text';
|
||||
import type { ContentsEntry } from '@/core/api/types';
|
||||
import { useContents } from '@/features/repository/queries';
|
||||
import { useRepository } from '@/features/repositories/queries';
|
||||
import { useTheme } from '@/theme/theme-provider';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
import type { RepositoryStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<RepositoryStackParamList, 'Files'>;
|
||||
|
||||
/** Directory listing with breadcrumb navigation. */
|
||||
export function FilesScreen({ navigation, route }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { colors } = useTheme();
|
||||
const { owner, name, ref } = route.params;
|
||||
const path = route.params.path ?? '';
|
||||
|
||||
const repoQuery = useRepository(owner, name);
|
||||
const effectiveRef = ref ?? repoQuery.data?.default_branch;
|
||||
const query = useContents(owner, name, path, effectiveRef);
|
||||
|
||||
const entries = useMemo(() => {
|
||||
const list = Array.isArray(query.data) ? (query.data as ContentsEntry[]) : [];
|
||||
return [...list].sort((a, b) => {
|
||||
if (a.type === 'dir' && b.type !== 'dir') return -1;
|
||||
if (a.type !== 'dir' && b.type === 'dir') return 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
}, [query.data]);
|
||||
|
||||
const header = (
|
||||
<View style={styles.header}>
|
||||
<Breadcrumb
|
||||
path={path}
|
||||
rootLabel={t('files.root')}
|
||||
onNavigate={(target) => navigation.setParams({ path: target || undefined })}
|
||||
/>
|
||||
{effectiveRef ? (
|
||||
<AppText variant="caption" tone="tertiary" style={styles.ref}>
|
||||
{t('files.currentRef', { ref: effectiveRef })}
|
||||
</AppText>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
|
||||
const body = () => {
|
||||
if (query.isPending) return <LoadingView label={t('common.loading')} />;
|
||||
if (query.isError) {
|
||||
return (
|
||||
<ErrorState
|
||||
title={t('files.pathNotFound')}
|
||||
body={apiErrorMessage(query.error, t)}
|
||||
retryLabel={t('common.retry')}
|
||||
onRetry={() => void query.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<FlashList
|
||||
data={entries}
|
||||
keyExtractor={(entry) => entry.path}
|
||||
renderItem={({ item }) => (
|
||||
<FileRow
|
||||
entry={item}
|
||||
onPress={() =>
|
||||
item.type === 'dir'
|
||||
? navigation.setParams({ path: item.path })
|
||||
: navigation.navigate('FileViewer', { owner, name, path: item.path, ref: effectiveRef })
|
||||
}
|
||||
/>
|
||||
)}
|
||||
refreshing={query.isRefetching}
|
||||
onRefresh={() => void query.refetch()}
|
||||
ListEmptyComponent={<EmptyState icon="folder" title={t('files.empty')} />}
|
||||
contentContainerStyle={entries.length === 0 ? styles.grow : undefined}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Screen padded={false}>
|
||||
<View style={[styles.refBar, { borderBottomColor: colors.border }]}>{header}</View>
|
||||
{body()}
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
header: { gap: spacing.xs, paddingBottom: spacing.xs },
|
||||
ref: { paddingHorizontal: spacing.lg },
|
||||
refBar: { borderBottomWidth: StyleSheet.hairlineWidth },
|
||||
grow: { flexGrow: 1 },
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import { StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Markdown } from '@/components/git/markdown';
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { Avatar } from '@/components/ui/avatar';
|
||||
import { Badge, StatusBadge } from '@/components/ui/badge';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { Icon } from '@/components/ui/icon';
|
||||
import { LabelChip } from '@/components/ui/label-chip';
|
||||
import { ErrorState, LoadingView } from '@/components/ui/state-views';
|
||||
import { apiErrorMessage } from '@/core/api/error-text';
|
||||
import { useSession } from '@/features/accounts/use-session';
|
||||
import { useIssue } from '@/features/issues/queries';
|
||||
import { formatRelativeTime } from '@/core/utils/format';
|
||||
import { useTheme } from '@/theme/theme-provider';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
import type { RepositoryStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<RepositoryStackParamList, 'IssueDetail'>;
|
||||
|
||||
/** Full issue view: state, author, labels, milestone and rendered body. */
|
||||
export function IssueDetailScreen({ route }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { colors } = useTheme();
|
||||
const { instance } = useSession();
|
||||
const { owner, name, index } = route.params;
|
||||
|
||||
const query = useIssue(owner, name, index);
|
||||
const issue = query.data;
|
||||
|
||||
if (query.isPending) return <LoadingView />;
|
||||
if (query.isError) {
|
||||
return (
|
||||
<ErrorState
|
||||
title={t('issues.notFound')}
|
||||
body={apiErrorMessage(query.error, t)}
|
||||
retryLabel={t('common.retry')}
|
||||
onRetry={() => void query.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!issue) return null;
|
||||
|
||||
const author = issue.user;
|
||||
const state = issue.state === 'closed' ? 'closed' : 'open';
|
||||
|
||||
return (
|
||||
<Screen scroll padded>
|
||||
<View style={styles.titleBlock}>
|
||||
<AppText variant="heading">
|
||||
{issue.title} <AppText variant="heading" tone="tertiary">{`#${issue.number}`}</AppText>
|
||||
</AppText>
|
||||
<View style={styles.stateRow}>
|
||||
<StatusBadge label={state === 'closed' ? t('issues.closed') : t('issues.open')} state={state} />
|
||||
{issue.is_locked ? <Badge tone="neutral" icon="lock">{`#${issue.number}`}</Badge> : null}
|
||||
<AppText variant="caption" tone="tertiary">
|
||||
{t('issues.openedBy', { name: author?.login ?? t('common.unknown') })} ·{' '}
|
||||
{formatRelativeTime(issue.created_at, t)}
|
||||
</AppText>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={styles.authorRow}>
|
||||
<Avatar url={author?.avatar_url} name={author?.login ?? '?'} size={28} />
|
||||
<AppText variant="bodyMedium" style={styles.authorName}>
|
||||
{author?.login ?? t('common.unknown')}
|
||||
</AppText>
|
||||
</View>
|
||||
|
||||
{issue.labels && issue.labels.length > 0 ? (
|
||||
<View style={styles.labels}>
|
||||
{issue.labels.map((label, index2) => (
|
||||
<LabelChip key={label.id ?? `${label.name}-${index2}`} name={label.name} color={label.color} />
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<Card style={styles.bodyCard}>
|
||||
{issue.body && issue.body.trim().length > 0 ? (
|
||||
<Markdown content={issue.body} baseUrl={instance?.baseUrl} />
|
||||
) : (
|
||||
<AppText variant="secondary" tone="tertiary">
|
||||
{t('issues.noDescription')}
|
||||
</AppText>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<View style={styles.metaGrid}>
|
||||
{issue.assignees && issue.assignees.length > 0 ? (
|
||||
<MetaRow
|
||||
icon="person"
|
||||
label={t('issues.assignedTo', {
|
||||
name: issue.assignees.map((a) => a.login).join(', '),
|
||||
})}
|
||||
/>
|
||||
) : null}
|
||||
{issue.milestone ? <MetaRow icon="tag" label={`${t('issues.milestone')}: ${issue.milestone.title}`} /> : null}
|
||||
<MetaRow
|
||||
icon="mail"
|
||||
label={t('issues.comments', { count: issue.comments ?? 0 })}
|
||||
color={colors.textSecondary}
|
||||
/>
|
||||
</View>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
function MetaRow({ icon, label, color }: { icon: 'person' | 'tag' | 'mail'; label: string; color?: string }) {
|
||||
const { colors } = useTheme();
|
||||
return (
|
||||
<View style={styles.metaRow}>
|
||||
<Icon name={icon} size={15} color={color ?? colors.textTertiary} />
|
||||
<AppText variant="caption" tone="secondary">
|
||||
{label}
|
||||
</AppText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
titleBlock: { gap: spacing.sm },
|
||||
stateRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, flexWrap: 'wrap' },
|
||||
authorRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
|
||||
authorName: { flex: 1 },
|
||||
labels: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
|
||||
bodyCard: { minHeight: 80 },
|
||||
metaGrid: { gap: spacing.sm },
|
||||
metaRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Markdown } from '@/components/git/markdown';
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { Avatar } from '@/components/ui/avatar';
|
||||
import { Badge, StatusBadge } from '@/components/ui/badge';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { LabelChip } from '@/components/ui/label-chip';
|
||||
import { ErrorState, LoadingView } from '@/components/ui/state-views';
|
||||
import { apiErrorMessage } from '@/core/api/error-text';
|
||||
import { useSession } from '@/features/accounts/use-session';
|
||||
import { usePull } from '@/features/issues/queries';
|
||||
import { formatRelativeTime } from '@/core/utils/format';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
import type { RepositoryStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<RepositoryStackParamList, 'PullDetail'>;
|
||||
|
||||
/** Full pull request view: state, branches, reviewers, stats and body. */
|
||||
export function PullDetailScreen({ route }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { instance } = useSession();
|
||||
const { owner, name, index } = route.params;
|
||||
|
||||
const query = usePull(owner, name, index);
|
||||
const pull = query.data;
|
||||
|
||||
if (query.isPending) return <LoadingView />;
|
||||
if (query.isError) {
|
||||
return (
|
||||
<ErrorState
|
||||
title={t('pulls.notFound')}
|
||||
body={apiErrorMessage(query.error, t)}
|
||||
retryLabel={t('common.retry')}
|
||||
onRetry={() => void query.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!pull) return null;
|
||||
|
||||
const author = pull.user;
|
||||
const state: 'open' | 'closed' | 'merged' | 'draft' = pull.merged
|
||||
? 'merged'
|
||||
: pull.draft && pull.state === 'open'
|
||||
? 'draft'
|
||||
: pull.state === 'closed'
|
||||
? 'closed'
|
||||
: 'open';
|
||||
const stateLabel = {
|
||||
open: t('pulls.stateOpen'),
|
||||
closed: t('pulls.stateClosed'),
|
||||
merged: t('pulls.stateMerged'),
|
||||
draft: t('pulls.draft'),
|
||||
}[state];
|
||||
|
||||
return (
|
||||
<Screen scroll padded>
|
||||
<View style={styles.titleBlock}>
|
||||
<AppText variant="heading">
|
||||
{pull.title} <AppText variant="heading" tone="tertiary">{`#${pull.number}`}</AppText>
|
||||
</AppText>
|
||||
<View style={styles.stateRow}>
|
||||
<StatusBadge label={stateLabel} state={state} />
|
||||
{pull.head?.label && pull.base?.label ? (
|
||||
<Badge tone="neutral" icon="branch">
|
||||
{t('pulls.into', { head: pull.head.label, base: pull.base.label })}
|
||||
</Badge>
|
||||
) : null}
|
||||
</View>
|
||||
<AppText variant="caption" tone="tertiary">
|
||||
{t('pulls.openedBy', { name: author?.login ?? t('common.unknown') })} ·{' '}
|
||||
{formatRelativeTime(pull.created_at, t)}
|
||||
</AppText>
|
||||
</View>
|
||||
|
||||
{pull.labels && pull.labels.length > 0 ? (
|
||||
<View style={styles.labels}>
|
||||
{pull.labels.map((label, labelIndex) => (
|
||||
<LabelChip key={label.id ?? `${label.name}-${labelIndex}`} name={label.name} color={label.color} />
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<Card style={styles.bodyCard}>
|
||||
{pull.body && pull.body.trim().length > 0 ? (
|
||||
<Markdown content={pull.body} baseUrl={instance?.baseUrl} />
|
||||
) : (
|
||||
<AppText variant="secondary" tone="tertiary">
|
||||
{t('pulls.noDescription')}
|
||||
</AppText>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<View style={styles.stats}>
|
||||
<Badge tone="success">{`+${pull.additions ?? 0}`}</Badge>
|
||||
<Badge tone="error">{`−${pull.deletions ?? 0}`}</Badge>
|
||||
<AppText variant="caption" tone="tertiary">
|
||||
{t('pulls.changedFiles', { count: pull.changed_files ?? 0 })}
|
||||
</AppText>
|
||||
<AppText variant="caption" tone="tertiary">
|
||||
{t('issues.comments', { count: pull.comments ?? 0 })}
|
||||
</AppText>
|
||||
</View>
|
||||
|
||||
{pull.requested_reviewers && pull.requested_reviewers.length > 0 ? (
|
||||
<View style={styles.reviewers}>
|
||||
<AppText variant="label" tone="secondary">
|
||||
{t('pulls.reviewers')}
|
||||
</AppText>
|
||||
<View style={styles.reviewerRow}>
|
||||
{pull.requested_reviewers.map((reviewer) => (
|
||||
<View key={reviewer.id ?? reviewer.login} style={styles.reviewer}>
|
||||
<Avatar url={reviewer.avatar_url} name={reviewer.login} size={24} />
|
||||
<AppText variant="caption" tone="secondary">
|
||||
{reviewer.login}
|
||||
</AppText>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
titleBlock: { gap: spacing.sm },
|
||||
stateRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, flexWrap: 'wrap' },
|
||||
labels: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
|
||||
bodyCard: { minHeight: 80 },
|
||||
stats: { flexDirection: 'row', alignItems: 'center', gap: spacing.md, flexWrap: 'wrap' },
|
||||
reviewers: { gap: spacing.sm },
|
||||
reviewerRow: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.lg },
|
||||
reviewer: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useState } from 'react';
|
||||
import { StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { IssueRow } from '@/components/git/issue-row';
|
||||
import { QueryList } from '@/components/layout/query-list';
|
||||
import { SearchBar } from '@/components/ui/search-bar';
|
||||
import { SegmentedControl } from '@/components/ui/segmented';
|
||||
import { EmptyState } from '@/components/ui/state-views';
|
||||
import type { Issue } from '@/core/api/types';
|
||||
import { flattenPages } from '@/core/utils/infinite';
|
||||
import { useRepoIssues } from '@/features/issues/queries';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
import type { RepositoryStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<RepositoryStackParamList, 'RepoIssues'>;
|
||||
|
||||
type StateKey = 'open' | 'closed' | 'all';
|
||||
|
||||
/** Issues scoped to one repository. */
|
||||
export function RepoIssuesScreen({ navigation, route }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { owner, name } = route.params;
|
||||
const [state, setState] = useState<StateKey>('open');
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const query = useRepoIssues(owner, name, state, search);
|
||||
const issues: Issue[] = flattenPages(query.data);
|
||||
|
||||
return (
|
||||
<QueryList<Issue>
|
||||
query={query}
|
||||
items={issues}
|
||||
keyExtractor={(issue) => String(issue.id)}
|
||||
header={
|
||||
<View>
|
||||
<SearchBar
|
||||
value={search}
|
||||
onChangeText={setSearch}
|
||||
placeholder={t('issues.searchPlaceholder')}
|
||||
/>
|
||||
<View style={styles.filters}>
|
||||
<SegmentedControl<StateKey>
|
||||
value={state}
|
||||
onChange={setState}
|
||||
accessibilityLabel={t('issues.title')}
|
||||
options={[
|
||||
{ value: 'open', label: t('issues.stateOpen') },
|
||||
{ value: 'closed', label: t('issues.stateClosed') },
|
||||
{ value: 'all', label: t('issues.stateAll') },
|
||||
]}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
}
|
||||
renderItem={(issue) => (
|
||||
<IssueRow
|
||||
issue={issue}
|
||||
onPress={() => navigation.navigate('IssueDetail', { owner, name, index: issue.number })}
|
||||
/>
|
||||
)}
|
||||
empty={<EmptyState icon="issue" title={t('issues.emptySearch', { query: search.trim() })} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
filters: { paddingHorizontal: spacing.lg, paddingBottom: spacing.sm },
|
||||
});
|
||||
@@ -0,0 +1,302 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Linking, StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Markdown } from '@/components/git/markdown';
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { Icon } from '@/components/ui/icon';
|
||||
import { LabelChip } from '@/components/ui/label-chip';
|
||||
import { ListItem } from '@/components/ui/list-item';
|
||||
import { ErrorState, LoadingView } from '@/components/ui/state-views';
|
||||
import { apiErrorMessage } from '@/core/api/error-text';
|
||||
import { useRepository, useRepositoryLanguages } from '@/features/repositories/queries';
|
||||
import { useReadme } from '@/features/repository/queries';
|
||||
import { useSession } from '@/features/accounts/use-session';
|
||||
import { useTheme } from '@/theme/theme-provider';
|
||||
import { radius, spacing } from '@/theme/tokens';
|
||||
import type { RepositoryStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<RepositoryStackParamList, 'RepoOverview'>;
|
||||
|
||||
/** Repository landing page: metadata, quick navigation, stats, languages, README. */
|
||||
export function RepoOverviewScreen({ navigation, route }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { colors } = useTheme();
|
||||
const { instance } = useSession();
|
||||
const { owner, name, ref } = route.params;
|
||||
|
||||
const repoQuery = useRepository(owner, name);
|
||||
const repo = repoQuery.data;
|
||||
const readmeRef = ref ?? repo?.default_branch;
|
||||
const readmeQuery = useReadme(owner, name, readmeRef);
|
||||
const languagesQuery = useRepositoryLanguages(owner, name);
|
||||
|
||||
const languages = useMemo(() => {
|
||||
const entries = Object.entries(languagesQuery.data ?? {});
|
||||
const total = entries.reduce((sum, [, bytes]) => sum + bytes, 0);
|
||||
if (total <= 0) return [];
|
||||
return entries
|
||||
.map(([language, bytes]) => ({ language, bytes, percent: (bytes / total) * 100 }))
|
||||
.sort((a, b) => b.bytes - a.bytes)
|
||||
.slice(0, 6);
|
||||
}, [languagesQuery.data]);
|
||||
|
||||
if (!repo && repoQuery.isPending) return <LoadingView />;
|
||||
|
||||
if (!repo && repoQuery.isError) {
|
||||
return (
|
||||
<ErrorState
|
||||
title={t('errors.title')}
|
||||
body={apiErrorMessage(repoQuery.error, t)}
|
||||
retryLabel={t('common.retry')}
|
||||
onRetry={() => void repoQuery.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (!repo) return null;
|
||||
|
||||
const readmeText = decodeReadme(readmeQuery.data?.content);
|
||||
|
||||
return (
|
||||
<Screen scroll padded={false}>
|
||||
{/* Header */}
|
||||
<View style={[styles.header, { borderBottomColor: colors.border }]}>
|
||||
<View style={styles.titleRow}>
|
||||
<AppText variant="caption" tone="tertiary">
|
||||
{owner}/
|
||||
</AppText>
|
||||
<AppText variant="title" numberOfLines={2} style={styles.name}>
|
||||
{name}
|
||||
</AppText>
|
||||
</View>
|
||||
|
||||
<AppText variant="secondary" tone={repo.description ? 'secondary' : 'tertiary'}>
|
||||
{repo.description ?? t('repo.noDescription')}
|
||||
</AppText>
|
||||
|
||||
<View style={styles.badges}>
|
||||
{repo.private ? <Badge tone="neutral" icon="lock">{t('repositories.private')}</Badge> : null}
|
||||
{repo.fork ? <Badge tone="neutral" icon="fork">{t('repositories.fork')}</Badge> : null}
|
||||
{repo.archived ? <Badge tone="warning" icon="shield">{t('repositories.archived')}</Badge> : null}
|
||||
{repo.template ? <Badge tone="info" icon="package">{t('repositories.template')}</Badge> : null}
|
||||
{repo.mirror ? <Badge tone="info" icon="autoRenew">{t('repositories.mirror')}</Badge> : null}
|
||||
{repo.default_branch ? (
|
||||
<Badge tone="primary" icon="branch">{repo.default_branch}</Badge>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
{repo.topics && repo.topics.length > 0 ? (
|
||||
<View style={styles.badges}>
|
||||
{repo.topics.slice(0, 8).map((topic) => (
|
||||
<LabelChip key={topic} name={topic} />
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{repo.html_url ? (
|
||||
<Button
|
||||
label={t('repo.viewOnInstance')}
|
||||
variant="secondary"
|
||||
iconLeft="externalLink"
|
||||
onPress={() => void Linking.openURL(repo.html_url as string).catch(() => undefined)}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
{/* Quick navigation */}
|
||||
<View style={styles.section}>
|
||||
<AppText variant="subheading" style={styles.sectionTitle}>
|
||||
{t('repo.browse')}
|
||||
</AppText>
|
||||
<Card padded={false} variant="flat" style={styles.card}>
|
||||
<ListItem
|
||||
leadingIcon="folder"
|
||||
title={t('repo.files')}
|
||||
onPress={() => navigation.navigate('Files', { owner, name, ref: readmeRef })}
|
||||
/>
|
||||
<ListItem
|
||||
leadingIcon="commit"
|
||||
title={t('repo.commits')}
|
||||
onPress={() => navigation.navigate('Commits', { owner, name, sha: readmeRef })}
|
||||
/>
|
||||
<ListItem
|
||||
leadingIcon="branch"
|
||||
title={t('repo.branches')}
|
||||
onPress={() => navigation.navigate('Branches', { owner, name })}
|
||||
/>
|
||||
<ListItem
|
||||
leadingIcon="tag"
|
||||
title={t('repo.tags')}
|
||||
onPress={() => navigation.navigate('Tags', { owner, name })}
|
||||
/>
|
||||
{repo.has_issues !== false ? (
|
||||
<ListItem
|
||||
leadingIcon="issue"
|
||||
title={t('repo.issuesTab')}
|
||||
rightText={repo.open_issues_count ? String(repo.open_issues_count) : undefined}
|
||||
onPress={() => navigation.navigate('RepoIssues', { owner, name })}
|
||||
/>
|
||||
) : null}
|
||||
{repo.has_pull_requests !== false ? (
|
||||
<ListItem
|
||||
leadingIcon="pullRequest"
|
||||
title={t('repo.pullsTab')}
|
||||
rightText={repo.open_pr_counter ? String(repo.open_pr_counter) : undefined}
|
||||
onPress={() => navigation.navigate('RepoPulls', { owner, name })}
|
||||
divider={false}
|
||||
/>
|
||||
) : null}
|
||||
</Card>
|
||||
</View>
|
||||
|
||||
{/* Statistics */}
|
||||
<View style={styles.section}>
|
||||
<AppText variant="subheading" style={styles.sectionTitle}>
|
||||
{t('repo.statistics')}
|
||||
</AppText>
|
||||
<Card style={styles.card}>
|
||||
<View style={styles.statsGrid}>
|
||||
<Stat label={t('repo.stars')} value={repo.stars_count} icon="star" />
|
||||
<Stat label={t('repo.forks')} value={repo.forks_count} icon="fork" />
|
||||
<Stat label={t('repo.watchers')} value={repo.watchers_count} icon="eye" />
|
||||
<Stat label={t('repo.openIssues')} value={repo.open_issues_count} icon="issue" />
|
||||
<Stat label={t('repo.openPulls')} value={repo.open_pr_counter} icon="pullRequest" />
|
||||
<Stat label={t('repo.releases')} value={repo.release_counter} icon="tag" />
|
||||
</View>
|
||||
</Card>
|
||||
</View>
|
||||
|
||||
{/* Languages */}
|
||||
{languages.length > 0 ? (
|
||||
<View style={styles.section}>
|
||||
<AppText variant="subheading" style={styles.sectionTitle}>
|
||||
{t('repo.languages')}
|
||||
</AppText>
|
||||
<Card style={styles.card}>
|
||||
<View style={[styles.langBar, { backgroundColor: colors.surfaceSecondary }]}>
|
||||
{languages.map((entry, index) => (
|
||||
<View
|
||||
key={entry.language}
|
||||
style={{
|
||||
flex: entry.percent,
|
||||
backgroundColor: languageColor(index, colors.primary),
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
<View style={styles.langList}>
|
||||
{languages.map((entry, index) => (
|
||||
<View key={entry.language} style={styles.langItem}>
|
||||
<View
|
||||
style={[styles.langDot, { backgroundColor: languageColor(index, colors.primary) }]}
|
||||
/>
|
||||
<AppText variant="caption" style={styles.langName} numberOfLines={1}>
|
||||
{entry.language}
|
||||
</AppText>
|
||||
<AppText variant="caption" tone="tertiary">
|
||||
{entry.percent.toFixed(1)}%
|
||||
</AppText>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</Card>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{/* README */}
|
||||
<View style={styles.section}>
|
||||
<AppText variant="subheading" style={styles.sectionTitle}>
|
||||
{t('repo.readme')}
|
||||
</AppText>
|
||||
{readmeQuery.isPending ? (
|
||||
<View style={styles.card}>
|
||||
<LoadingView />
|
||||
</View>
|
||||
) : readmeText ? (
|
||||
<Card style={styles.card}>
|
||||
<Markdown content={readmeText} baseUrl={instance?.baseUrl} />
|
||||
</Card>
|
||||
) : (
|
||||
<Card style={styles.card}>
|
||||
<AppText variant="secondary" tone="tertiary">
|
||||
{t('repo.noReadme')}
|
||||
</AppText>
|
||||
</Card>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View style={{ height: spacing.xxl }} />
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
function Stat({
|
||||
label,
|
||||
value,
|
||||
icon,
|
||||
}: {
|
||||
label: string;
|
||||
value: number | undefined;
|
||||
icon: 'star' | 'fork' | 'eye' | 'issue' | 'pullRequest' | 'tag';
|
||||
}) {
|
||||
const { colors } = useTheme();
|
||||
return (
|
||||
<View style={styles.stat}>
|
||||
<Icon name={icon} size={16} color={colors.textTertiary} />
|
||||
<AppText variant="bodyMedium">{value ?? 0}</AppText>
|
||||
<AppText variant="caption" tone="tertiary" numberOfLines={1}>
|
||||
{label}
|
||||
</AppText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const LANGUAGE_COLORS = ['#609926', '#3178c6', '#e34c26', '#f1e05a', '#563d7c', '#89e051'];
|
||||
|
||||
function languageColor(index: number, fallback: string): string {
|
||||
return LANGUAGE_COLORS[index] ?? fallback;
|
||||
}
|
||||
|
||||
function decodeReadme(content: string | undefined): string {
|
||||
if (!content) return '';
|
||||
try {
|
||||
return globalThis.atob(content.replace(/\s/g, ''));
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
header: {
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingTop: spacing.lg,
|
||||
paddingBottom: spacing.lg,
|
||||
gap: spacing.md,
|
||||
borderBottomWidth: StyleSheet.hairlineWidth,
|
||||
},
|
||||
titleRow: { flexDirection: 'row', alignItems: 'baseline', flexWrap: 'wrap' },
|
||||
name: { flexShrink: 1 },
|
||||
badges: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm, alignItems: 'center' },
|
||||
section: { marginTop: spacing.xl, gap: spacing.sm },
|
||||
sectionTitle: { paddingHorizontal: spacing.lg },
|
||||
card: { marginHorizontal: spacing.lg },
|
||||
statsGrid: { flexDirection: 'row', flexWrap: 'wrap' },
|
||||
stat: { width: '33.33%', alignItems: 'center', gap: 2, paddingVertical: spacing.sm },
|
||||
langBar: {
|
||||
flexDirection: 'row',
|
||||
height: 10,
|
||||
borderRadius: radius.pill,
|
||||
overflow: 'hidden',
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
langList: { gap: spacing.xs },
|
||||
langItem: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
|
||||
langDot: { width: 10, height: 10, borderRadius: radius.pill },
|
||||
langName: { flex: 1 },
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useState } from 'react';
|
||||
import { StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { IssueRow } from '@/components/git/issue-row';
|
||||
import { QueryList } from '@/components/layout/query-list';
|
||||
import { SegmentedControl } from '@/components/ui/segmented';
|
||||
import { EmptyState } from '@/components/ui/state-views';
|
||||
import type { PullRequest } from '@/core/api/types';
|
||||
import { flattenPages } from '@/core/utils/infinite';
|
||||
import { useRepoPulls } from '@/features/issues/queries';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
import type { RepositoryStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<RepositoryStackParamList, 'RepoPulls'>;
|
||||
|
||||
type StateKey = 'open' | 'closed' | 'all';
|
||||
|
||||
/** Pull requests scoped to one repository. */
|
||||
export function RepoPullsScreen({ navigation, route }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { owner, name } = route.params;
|
||||
const [state, setState] = useState<StateKey>('open');
|
||||
|
||||
const query = useRepoPulls(owner, name, state);
|
||||
const pulls: PullRequest[] = flattenPages(query.data);
|
||||
|
||||
return (
|
||||
<QueryList<PullRequest>
|
||||
query={query}
|
||||
items={pulls}
|
||||
keyExtractor={(pull) => String(pull.id)}
|
||||
header={
|
||||
<View style={styles.filters}>
|
||||
<SegmentedControl<StateKey>
|
||||
value={state}
|
||||
onChange={setState}
|
||||
accessibilityLabel={t('pulls.title')}
|
||||
options={[
|
||||
{ value: 'open', label: t('pulls.stateOpen') },
|
||||
{ value: 'closed', label: t('pulls.stateClosed') },
|
||||
{ value: 'all', label: t('pulls.stateAll') },
|
||||
]}
|
||||
/>
|
||||
</View>
|
||||
}
|
||||
renderItem={(pull) => (
|
||||
<IssueRow
|
||||
issue={pull}
|
||||
onPress={() => navigation.navigate('PullDetail', { owner, name, index: pull.number })}
|
||||
/>
|
||||
)}
|
||||
empty={<EmptyState icon="pullRequest" title={t('pulls.emptyCreated')} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
filters: { paddingHorizontal: spacing.lg, paddingTop: spacing.sm, paddingBottom: spacing.sm },
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { QueryList } from '@/components/layout/query-list';
|
||||
import { ListItem } from '@/components/ui/list-item';
|
||||
import { EmptyState } from '@/components/ui/state-views';
|
||||
import type { Tag } from '@/core/api/types';
|
||||
import { firstLine, shortSha } from '@/core/utils/format';
|
||||
import { flattenPages } from '@/core/utils/infinite';
|
||||
import { useTags } from '@/features/repository/queries';
|
||||
import type { RepositoryStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<RepositoryStackParamList, 'Tags'>;
|
||||
|
||||
/** Tag list; tapping a tag opens its file tree at that ref. */
|
||||
export function TagsScreen({ navigation, route }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { owner, name } = route.params;
|
||||
|
||||
const query = useTags(owner, name);
|
||||
const tags: Tag[] = flattenPages(query.data);
|
||||
|
||||
return (
|
||||
<QueryList<Tag>
|
||||
query={query}
|
||||
items={tags}
|
||||
keyExtractor={(tag) => tag.name}
|
||||
renderItem={(tag) => (
|
||||
<ListItem
|
||||
leadingIcon="tag"
|
||||
title={tag.name}
|
||||
subtitle={firstLine(tag.message)}
|
||||
meta={tag.commit?.sha ? shortSha(tag.commit.sha) : undefined}
|
||||
onPress={() => navigation.navigate('Files', { owner, name, ref: tag.name })}
|
||||
/>
|
||||
)}
|
||||
empty={<EmptyState icon="tag" title={t('branches.emptyTags')} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import Constants from 'expo-constants';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Alert, Linking, StyleSheet, Switch, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { ListItem } from '@/components/ui/list-item';
|
||||
import { SegmentedControl } from '@/components/ui/segmented';
|
||||
import { queryClient } from '@/core/api/query-client';
|
||||
import type { BiometricSupport } from '@/core/security/biometrics';
|
||||
import { getBiometricSupport } from '@/core/security/biometrics';
|
||||
import { useSettingsStore, type ThemePreference } from '@/features/settings/settings-store';
|
||||
import { useRootNavigation } from '@/navigation/use-root-navigation';
|
||||
import type { LanguagePreference } from '@/i18n';
|
||||
import { useTheme } from '@/theme/theme-provider';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
import type { SettingsStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<SettingsStackParamList, 'Settings'>;
|
||||
|
||||
type PollKey = '0' | '30' | '60' | '300';
|
||||
|
||||
const GITEA_HOME_URL = 'https://gitea.com';
|
||||
|
||||
/** App settings: appearance, language, security, notifications, data, about. */
|
||||
export function SettingsScreen(_props: Props) {
|
||||
const navigation = useRootNavigation();
|
||||
const { t } = useTranslation();
|
||||
const { colors } = useTheme();
|
||||
|
||||
const themePreference = useSettingsStore((s) => s.themePreference);
|
||||
const language = useSettingsStore((s) => s.language);
|
||||
const biometricsEnabled = useSettingsStore((s) => s.biometricsEnabled);
|
||||
const notificationPollSeconds = useSettingsStore((s) => s.notificationPollSeconds);
|
||||
const setThemePreference = useSettingsStore((s) => s.setThemePreference);
|
||||
const setLanguage = useSettingsStore((s) => s.setLanguage);
|
||||
const setBiometricsEnabled = useSettingsStore((s) => s.setBiometricsEnabled);
|
||||
const setNotificationPollSeconds = useSettingsStore((s) => s.setNotificationPollSeconds);
|
||||
|
||||
const [support, setSupport] = useState<BiometricSupport | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void getBiometricSupport().then((value) => {
|
||||
if (!cancelled) setSupport(value);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const version = Constants.expoConfig?.version ?? '0.1.0';
|
||||
|
||||
const confirmClearCache = () => {
|
||||
Alert.alert(t('settings.clearCacheTitle'), t('settings.clearCacheConfirm'), [
|
||||
{ text: t('common.cancel'), style: 'cancel' },
|
||||
{
|
||||
text: t('common.confirm'),
|
||||
style: 'destructive',
|
||||
onPress: () => {
|
||||
queryClient.clear();
|
||||
Alert.alert(t('settings.clearCacheDone'));
|
||||
},
|
||||
},
|
||||
]);
|
||||
};
|
||||
|
||||
return (
|
||||
<Screen scroll padded>
|
||||
{/* Appearance */}
|
||||
<Section title={t('settings.appearance')}>
|
||||
<Card style={styles.card}>
|
||||
<AppText variant="label" tone="secondary">
|
||||
{t('settings.theme')}
|
||||
</AppText>
|
||||
<SegmentedControl<ThemePreference>
|
||||
value={themePreference}
|
||||
onChange={setThemePreference}
|
||||
accessibilityLabel={t('settings.theme')}
|
||||
options={[
|
||||
{ value: 'system', label: t('settings.themeSystem') },
|
||||
{ value: 'light', label: t('settings.themeLight') },
|
||||
{ value: 'dark', label: t('settings.themeDark') },
|
||||
]}
|
||||
/>
|
||||
<AppText variant="label" tone="secondary" style={styles.spaced}>
|
||||
{t('settings.language')}
|
||||
</AppText>
|
||||
<SegmentedControl<LanguagePreference>
|
||||
value={language}
|
||||
onChange={setLanguage}
|
||||
accessibilityLabel={t('settings.language')}
|
||||
options={[
|
||||
{ value: 'system', label: t('settings.languageSystem') },
|
||||
{ value: 'en', label: 'English' },
|
||||
{ value: 'nl', label: 'Nederlands' },
|
||||
]}
|
||||
/>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
{/* Security */}
|
||||
<Section title={t('settings.security')}>
|
||||
<Card padded={false} variant="flat">
|
||||
<View style={styles.switchRow}>
|
||||
<View style={styles.switchBody}>
|
||||
<AppText variant="bodyMedium">{t('settings.biometrics')}</AppText>
|
||||
<AppText variant="caption" tone="tertiary">
|
||||
{support && !support.usable
|
||||
? t('settings.biometricsUnavailable')
|
||||
: t('settings.biometricsHelp')}
|
||||
</AppText>
|
||||
</View>
|
||||
<Switch
|
||||
value={biometricsEnabled}
|
||||
onValueChange={setBiometricsEnabled}
|
||||
disabled={!support?.usable}
|
||||
trackColor={{ true: colors.primary, false: colors.surfaceSecondary }}
|
||||
thumbColor={colors.surface}
|
||||
accessibilityLabel={t('settings.biometrics')}
|
||||
/>
|
||||
</View>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
{/* Notifications */}
|
||||
<Section title={t('settings.notifications')}>
|
||||
<Card style={styles.card}>
|
||||
<AppText variant="label" tone="secondary">
|
||||
{t('settings.pollInterval')}
|
||||
</AppText>
|
||||
<SegmentedControl<PollKey>
|
||||
value={String(notificationPollSeconds) as PollKey}
|
||||
onChange={(value) => setNotificationPollSeconds(Number(value))}
|
||||
accessibilityLabel={t('settings.pollInterval')}
|
||||
options={[
|
||||
{ value: '0', label: t('settings.pollIntervalManual') },
|
||||
{ value: '30', label: t('settings.pollIntervalSeconds', { count: 30 }) },
|
||||
{ value: '60', label: t('settings.pollIntervalSeconds', { count: 60 }) },
|
||||
{ value: '300', label: t('settings.pollIntervalSeconds', { count: 300 }) },
|
||||
]}
|
||||
/>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
{/* Data */}
|
||||
<Section title={t('settings.data')}>
|
||||
<Card padded={false} variant="flat">
|
||||
<ListItem
|
||||
leadingIcon="trash"
|
||||
title={t('settings.clearCache')}
|
||||
subtitle={t('settings.clearCacheConfirm')}
|
||||
onPress={confirmClearCache}
|
||||
divider={false}
|
||||
/>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
{/* Accounts */}
|
||||
<Section title={t('settings.accounts')}>
|
||||
<Card padded={false} variant="flat">
|
||||
<ListItem
|
||||
leadingIcon="people"
|
||||
title={t('accounts.title')}
|
||||
onPress={() => navigation.navigate('Accounts', { screen: 'Accounts' })}
|
||||
divider={false}
|
||||
/>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
{/* About */}
|
||||
<Section title={t('settings.about')}>
|
||||
<Card padded={false} variant="flat">
|
||||
<ListItem
|
||||
leadingIcon="info"
|
||||
title={t('settings.version', { version })}
|
||||
subtitle={t('settings.aboutBody')}
|
||||
/>
|
||||
<ListItem
|
||||
leadingIcon="globe"
|
||||
title={t('settings.giteaProject')}
|
||||
onPress={() => void Linking.openURL(GITEA_HOME_URL).catch(() => undefined)}
|
||||
divider={false}
|
||||
/>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
<AppText variant="caption" tone="tertiary" style={styles.footer}>
|
||||
{t('common.unofficialNotice')}
|
||||
</AppText>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({ title, children }: { title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<View style={styles.section}>
|
||||
<AppText variant="label" tone="secondary" style={styles.sectionTitle}>
|
||||
{title}
|
||||
</AppText>
|
||||
{children}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
section: { gap: spacing.sm },
|
||||
sectionTitle: { textTransform: 'uppercase', letterSpacing: 0.5 },
|
||||
card: { gap: spacing.sm },
|
||||
spaced: { marginTop: spacing.md },
|
||||
switchRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.md,
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingVertical: spacing.md,
|
||||
},
|
||||
switchBody: { flex: 1, gap: 2 },
|
||||
footer: { textAlign: 'center', paddingVertical: spacing.xl },
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Client-side settings (non-sensitive, persisted to AsyncStorage).
|
||||
*
|
||||
* Secrets never live here — tokens are stored via Expo SecureStore only.
|
||||
*/
|
||||
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { create } from 'zustand';
|
||||
import { createJSONStorage, persist } from 'zustand/middleware';
|
||||
|
||||
import type { LanguagePreference } from '@/i18n';
|
||||
|
||||
export type ThemePreference = 'system' | 'light' | 'dark';
|
||||
|
||||
export interface SettingsState {
|
||||
themePreference: ThemePreference;
|
||||
/** UI language; 'system' follows the device locale. */
|
||||
language: LanguagePreference;
|
||||
/** Require biometrics (Face ID / fingerprint) when the app becomes active again. */
|
||||
biometricsEnabled: boolean;
|
||||
/** Background polling interval for the notifications inbox, in seconds. 0 = only manual/foreground refresh. */
|
||||
notificationPollSeconds: number;
|
||||
setThemePreference: (preference: ThemePreference) => void;
|
||||
setLanguage: (language: LanguagePreference) => void;
|
||||
setBiometricsEnabled: (enabled: boolean) => void;
|
||||
setNotificationPollSeconds: (seconds: number) => void;
|
||||
}
|
||||
|
||||
export const useSettingsStore = create<SettingsState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
themePreference: 'system',
|
||||
language: 'system',
|
||||
biometricsEnabled: false,
|
||||
notificationPollSeconds: 60,
|
||||
setThemePreference: (themePreference) => set({ themePreference }),
|
||||
setLanguage: (language) => set({ language }),
|
||||
setBiometricsEnabled: (biometricsEnabled) => set({ biometricsEnabled }),
|
||||
setNotificationPollSeconds: (notificationPollSeconds) => set({ notificationPollSeconds }),
|
||||
}),
|
||||
{
|
||||
name: 'gitea-native:settings:v1',
|
||||
storage: createJSONStorage(() => AsyncStorage),
|
||||
partialize: (state) => ({
|
||||
themePreference: state.themePreference,
|
||||
language: state.language,
|
||||
biometricsEnabled: state.biometricsEnabled,
|
||||
notificationPollSeconds: state.notificationPollSeconds,
|
||||
}),
|
||||
},
|
||||
),
|
||||
);
|
||||
Reference in new issue
Block a user