feat(phase3): comments, issue compose, PR diff viewer, reviews, merge, checks

- API: comments CRUD, create/edit issue, milestones, collaborators, pull files,
  raw unified diff (getText), reviews, merge, combined commit status
- hooks: comment thread + composer mutations, issue compose mutations,
  pull files/diff/reviews, create review, merge, combined status
- UI: TextArea, ChipSelect, CommentItem, CommentComposer, native DiffView
  (parseDiff), StatusChecks
- screens: IssueCompose (create/edit), PullFiles, PullDiff, PullReview; issue
  detail gains thread + close/reopen; PR detail gains reviews, merge, files,
  checks; commit detail shows checks
- navigation/types + i18n (en/nl) updated; centralized safeHost helper
- tests: diff parser, endpoint body shapes (merge capitalisation), client getText
This commit is contained in:
JustZoe101 committed 2026-10-09 17:02:08 +02:00
1 parent f641238b6f
commit ddd834b7ac
32 files changed
+2546 -68

No files matched your search

@@ -12,6 +12,7 @@ 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 { safeHost } from '@/core/api/instance-url';
import type { AccountRecord, InstanceRecord } from '@/core/accounts/types';
import { useAccountsStore } from '@/core/accounts/accounts-store';
import { useAccountActions } from '@/features/accounts/use-account-actions';
@@ -158,14 +159,6 @@ export function AccountsScreen(_props: Props) {
);
}
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 },
+1 -8
View File
@@ -14,6 +14,7 @@ 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 { safeHost } from '@/core/api/instance-url';
import { useAccountsStore } from '@/core/accounts/accounts-store';
import { flattenPages } from '@/core/utils/infinite';
import { formatRelativeTime } from '@/core/utils/format';
@@ -368,14 +369,6 @@ function InlineEmpty({
);
}
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 },
+261 -1
View File
@@ -3,27 +3,59 @@
*
* Cross-repo lists (the Issues / Pull Requests tabs) go through Gitea's
* `/repos/issues/search`, which also powers PR search via `type=pulls`.
* Write paths (comments, compose, reviews, merge) invalidate the relevant
* account-scoped keys on success.
*/
import {
keepPreviousData,
useInfiniteQuery,
useMutation,
useQuery,
useQueryClient,
type InfiniteData,
} from '@tanstack/react-query';
import type { RawResponse } from '@/core/api/client';
import {
createIssue,
createIssueComment,
createPullReview,
deleteIssueComment,
fetchCombinedStatus,
fetchIssue,
fetchPull,
fetchPullDiff,
listCollaborators,
listIssueComments,
listMilestones,
listPullFiles,
listPullReviews,
listRepoIssues,
listRepoLabels,
listPulls,
mergePull,
searchIssues,
updateIssue,
updateIssueComment,
type CreateIssueInput,
type CreateReviewInput,
type EditIssueInput,
type IssueSearchParams,
type MergePullInput,
} from '@/core/api/endpoints';
import { queryKeys } from '@/core/api/query-keys';
import type { Issue, Label, PullRequest } from '@/core/api/types';
import type {
ChangedFile,
CombinedStatus,
Comment,
Issue,
Label,
Milestone,
PullRequest,
PullReview,
User,
} from '@/core/api/types';
import { useSession } from '@/features/accounts/use-session';
export type IssueScope = 'assigned' | 'created' | 'reviewRequested';
@@ -178,4 +210,232 @@ export function usePull(owner: string, name: string, index: number) {
});
}
// ---------------------------------------------------------------------------
// Comments (issues and pull requests share the endpoint)
// ---------------------------------------------------------------------------
export function useIssueComments(owner: string, name: string, index: number, limit = 30) {
const { client, account } = useSession();
const accountId = account?.id ?? '';
const params = { limit };
return useInfiniteQuery<
RawResponse<Comment[]>,
Error,
InfiniteData<RawResponse<Comment[]>>,
readonly unknown[],
number
>({
queryKey: queryKeys.issueComments(accountId, owner, name, index, params),
enabled: Boolean(client) && Boolean(accountId) && index > 0,
initialPageParam: 1,
queryFn: ({ pageParam, signal }) =>
listIssueComments(client!, owner, name, index, { ...params, page: pageParam }, { signal }),
getNextPageParam: (last, all) => (last.hasMore ? all.length + 1 : undefined),
placeholderData: keepPreviousData,
});
}
function invalidateThread(
queryClient: ReturnType<typeof useQueryClient>,
accountId: string,
owner: string,
name: string,
index: number,
) {
void queryClient.invalidateQueries({
queryKey: queryKeys.issueCommentsRoot(accountId, owner, name, index),
});
void queryClient.invalidateQueries({ queryKey: queryKeys.issue(accountId, owner, name, index) });
void queryClient.invalidateQueries({ queryKey: queryKeys.pull(accountId, owner, name, index) });
}
export function useCreateIssueComment(owner: string, name: string, index: number) {
const { client, account } = useSession();
const queryClient = useQueryClient();
const accountId = account?.id ?? '';
return useMutation({
mutationFn: (body: string) => createIssueComment(client!, owner, name, index, body),
onSuccess: () => invalidateThread(queryClient, accountId, owner, name, index),
});
}
export function useUpdateIssueComment(owner: string, name: string, index: number) {
const { client, account } = useSession();
const queryClient = useQueryClient();
const accountId = account?.id ?? '';
return useMutation({
mutationFn: ({ id, body }: { id: number; body: string }) =>
updateIssueComment(client!, owner, name, id, body),
onSuccess: () => invalidateThread(queryClient, accountId, owner, name, index),
});
}
export function useDeleteIssueComment(owner: string, name: string, index: number) {
const { client, account } = useSession();
const queryClient = useQueryClient();
const accountId = account?.id ?? '';
return useMutation({
mutationFn: (id: number) => deleteIssueComment(client!, owner, name, id),
onSuccess: () => invalidateThread(queryClient, accountId, owner, name, index),
});
}
// ---------------------------------------------------------------------------
// Compose (create / edit issues)
// ---------------------------------------------------------------------------
export function useCreateIssue(owner: string, name: string) {
const { client, account } = useSession();
const queryClient = useQueryClient();
const accountId = account?.id ?? '';
return useMutation({
mutationFn: (input: CreateIssueInput) => createIssue(client!, owner, name, input),
onSuccess: () => {
void queryClient.invalidateQueries({
queryKey: queryKeys.repoIssuesRoot(accountId, owner, name),
});
void queryClient.invalidateQueries({ queryKey: queryKeys.issueSearchRoot(accountId) });
},
});
}
export function useUpdateIssue(owner: string, name: string, index: number) {
const { client, account } = useSession();
const queryClient = useQueryClient();
const accountId = account?.id ?? '';
return useMutation({
mutationFn: (input: EditIssueInput) => updateIssue(client!, owner, name, index, input),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.issue(accountId, owner, name, index) });
void queryClient.invalidateQueries({
queryKey: queryKeys.repoIssuesRoot(accountId, owner, name),
});
void queryClient.invalidateQueries({ queryKey: queryKeys.issueSearchRoot(accountId) });
},
});
}
export function useMilestones(owner: string, name: string) {
const { client, account } = useSession();
const accountId = account?.id ?? '';
return useQuery({
queryKey: queryKeys.repoMilestones(accountId, owner, name),
enabled: Boolean(client) && Boolean(accountId),
queryFn: ({ signal }) =>
listMilestones(client!, owner, name, { state: 'open', limit: 50 }, { signal }).then(
(r) => r.data,
),
staleTime: 5 * 60_000,
});
}
export function useCollaborators(owner: string, name: string) {
const { client, account } = useSession();
const accountId = account?.id ?? '';
return useQuery({
queryKey: queryKeys.repoCollaborators(accountId, owner, name),
enabled: Boolean(client) && Boolean(accountId),
queryFn: ({ signal }) =>
listCollaborators(client!, owner, name, { limit: 50 }, { signal }).then((r) => r.data),
staleTime: 5 * 60_000,
});
}
// ---------------------------------------------------------------------------
// Pull request files, diff, reviews, merge, checks
// ---------------------------------------------------------------------------
export function usePullFiles(owner: string, name: string, index: number) {
const { client, account } = useSession();
const accountId = account?.id ?? '';
return useQuery<ChangedFile[]>({
queryKey: queryKeys.pullFiles(accountId, owner, name, index),
enabled: Boolean(client) && Boolean(accountId) && index > 0,
queryFn: ({ signal }) => listPullFiles(client!, owner, name, index, { limit: 50 }, { signal }),
staleTime: 60_000,
});
}
export function usePullDiff(owner: string, name: string, index: number) {
const { client, account } = useSession();
const accountId = account?.id ?? '';
return useQuery<string>({
queryKey: queryKeys.pullDiff(accountId, owner, name, index),
enabled: Boolean(client) && Boolean(accountId) && index > 0,
queryFn: ({ signal }) => fetchPullDiff(client!, owner, name, index, { signal }),
staleTime: 60_000,
});
}
export function usePullReviews(owner: string, name: string, index: number) {
const { client, account } = useSession();
const accountId = account?.id ?? '';
return useQuery<PullReview[]>({
queryKey: queryKeys.pullReviews(accountId, owner, name, index),
enabled: Boolean(client) && Boolean(accountId) && index > 0,
queryFn: ({ signal }) =>
listPullReviews(client!, owner, name, index, { limit: 50 }, { signal }).then((r) => r.data),
staleTime: 60_000,
});
}
export function useCreatePullReview(owner: string, name: string, index: number) {
const { client, account } = useSession();
const queryClient = useQueryClient();
const accountId = account?.id ?? '';
return useMutation({
mutationFn: (input: CreateReviewInput) => createPullReview(client!, owner, name, index, input),
onSuccess: () => {
void queryClient.invalidateQueries({
queryKey: queryKeys.pullReviews(accountId, owner, name, index),
});
void queryClient.invalidateQueries({ queryKey: queryKeys.pull(accountId, owner, name, index) });
void queryClient.invalidateQueries({ queryKey: queryKeys.issueSearchRoot(accountId) });
},
});
}
export function useMergePull(owner: string, name: string, index: number) {
const { client, account } = useSession();
const queryClient = useQueryClient();
const accountId = account?.id ?? '';
return useMutation({
mutationFn: (input: MergePullInput) => mergePull(client!, owner, name, index, input),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.pull(accountId, owner, name, index) });
void queryClient.invalidateQueries({ queryKey: queryKeys.pullsRoot(accountId, owner, name) });
void queryClient.invalidateQueries({ queryKey: queryKeys.repoDetail(accountId, owner, name) });
void queryClient.invalidateQueries({ queryKey: queryKeys.issueSearchRoot(accountId) });
},
});
}
/** Aggregated CI status for a commit / PR head. */
export function useCombinedStatus(owner: string, name: string, ref: string | undefined) {
const { client, account } = useSession();
const accountId = account?.id ?? '';
return useQuery<CombinedStatus>({
queryKey: queryKeys.combinedStatus(accountId, owner, name, ref ?? ''),
enabled: Boolean(client) && Boolean(accountId) && Boolean(ref),
queryFn: ({ signal }) => fetchCombinedStatus(client!, owner, name, ref!, { signal }),
staleTime: 30_000,
retry: false,
});
}
export type { Issue, Label, PullRequest };
export type { ChangedFile, CombinedStatus, Comment, Milestone, PullReview, User };
@@ -2,6 +2,7 @@ import { StyleSheet, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { Screen } from '@/components/layout/screen';
import { StatusChecks } from '@/components/git/status-checks';
import { AppText } from '@/components/ui/app-text';
import { Avatar } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
@@ -9,6 +10,7 @@ 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 { useCombinedStatus } from '@/features/issues/queries';
import { useCommit } from '@/features/repository/queries';
import { formatDateTime, shortSha } from '@/core/utils/format';
import { useTheme } from '@/theme/theme-provider';
@@ -26,6 +28,7 @@ export function CommitDetailScreen({ route }: Props) {
const query = useCommit(owner, name, sha);
const commit = query.data;
const checks = useCombinedStatus(owner, name, commit?.sha ?? sha);
if (query.isPending) return <LoadingView />;
if (query.isError) {
@@ -92,6 +95,8 @@ export function CommitDetailScreen({ route }: Props) {
</Badge>
) : null}
{checks.data ? <StatusChecks status={checks.data} /> : null}
{files.map((file, index) => (
<FileDiff key={`${file.filename ?? index}`} file={file} />
))}
@@ -8,6 +8,7 @@ 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 { safeHost } from '@/core/api/instance-url';
import { useSession } from '@/features/accounts/use-session';
import { decodeBase64, useFile } from '@/features/repository/queries';
import { formatBytes } from '@/core/utils/format';
@@ -134,14 +135,6 @@ export function FileViewerScreen({ route }: Props) {
);
}
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 },
@@ -0,0 +1,196 @@
import { useEffect, useMemo, useRef, useState } from 'react';
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 { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { ChipSelect } from '@/components/ui/chip-select';
import { Field } from '@/components/ui/field';
import { TextArea } from '@/components/ui/text-area';
import { ErrorState, LoadingView } from '@/components/ui/state-views';
import { apiErrorMessage } from '@/core/api/error-text';
import {
useCollaborators,
useCreateIssue,
useIssue,
useMilestones,
useRepoLabels,
useUpdateIssue,
} 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, 'IssueCompose'>;
/** Create a new issue, or edit an existing one (title, body, labels, assignees, milestone). */
export function IssueComposeScreen({ navigation, route }: Props) {
const { t } = useTranslation();
const { owner, name, index } = route.params;
const editing = typeof index === 'number' && index > 0;
const issueQuery = useIssue(owner, name, editing ? (index as number) : 0);
const labelsQuery = useRepoLabels(owner, name);
const milestonesQuery = useMilestones(owner, name);
const collaboratorsQuery = useCollaborators(owner, name);
const createMutation = useCreateIssue(owner, name);
const updateMutation = useUpdateIssue(owner, name, editing ? (index as number) : 0);
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const [labelIds, setLabelIds] = useState<string[]>([]);
const [assignees, setAssignees] = useState<string[]>([]);
const [milestoneId, setMilestoneId] = useState<string | null>(null);
const [submitted, setSubmitted] = useState(false);
const prefilled = useRef(false);
const issue = issueQuery.data;
useEffect(() => {
if (!editing || !issue || prefilled.current) return;
prefilled.current = true;
setTitle(issue.title ?? '');
setBody(issue.body ?? '');
setLabelIds((issue.labels ?? []).map((label) => String(label.id)).filter(Boolean));
setAssignees((issue.assignees ?? []).map((user) => user.login).filter(Boolean));
setMilestoneId(issue.milestone?.id ? String(issue.milestone.id) : null);
}, [editing, issue]);
const labelOptions = useMemo(
() => (labelsQuery.data ?? []).map((label) => ({ id: String(label.id), label: label.name })),
[labelsQuery.data],
);
const assigneeOptions = useMemo(
() => (collaboratorsQuery.data ?? []).map((user) => ({ id: user.login, label: user.login })),
[collaboratorsQuery.data],
);
const milestoneOptions = useMemo(
() => (milestonesQuery.data ?? []).map((m) => ({ id: String(m.id), label: m.title })),
[milestonesQuery.data],
);
const toggle = (setter: (fn: (prev: string[]) => string[]) => void) => (id: string) =>
setter((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
const titleError = submitted && title.trim().length === 0 ? t('issues.compose.titleRequired') : undefined;
const mutation = editing ? updateMutation : createMutation;
const submit = () => {
setSubmitted(true);
if (title.trim().length === 0) return;
const payload = {
title: title.trim(),
body: body.trim() || undefined,
labels: labelIds.map(Number).filter((n) => Number.isFinite(n)),
assignees,
milestone: milestoneId ? Number(milestoneId) : undefined,
};
if (editing) {
updateMutation.mutate(payload, { onSuccess: () => navigation.goBack() });
} else {
createMutation.mutate(payload, {
onSuccess: (created) =>
navigation.replace('IssueDetail', { owner, name, index: created.number }),
});
}
};
if (editing && issueQuery.isPending) return <LoadingView />;
if (editing && issueQuery.isError) {
return (
<ErrorState
title={t('errors.title')}
body={apiErrorMessage(issueQuery.error, t)}
retryLabel={t('common.retry')}
onRetry={() => void issueQuery.refetch()}
/>
);
}
return (
<Screen scroll padded>
<Field
label={t('issues.compose.title')}
value={title}
onChangeText={setTitle}
placeholder={t('issues.compose.titlePlaceholder')}
showError={Boolean(titleError)}
error={titleError}
autoCapitalize="sentences"
autoCorrect
testID="issue-title"
/>
<TextArea
label={t('issues.compose.body')}
value={body}
onChangeText={setBody}
placeholder={t('issues.compose.bodyPlaceholder')}
helper={t('issues.compose.bodyHelp')}
autoCapitalize="sentences"
autoCorrect
testID="issue-body"
/>
<Card>
<AppText variant="label" tone="secondary" style={styles.sectionLabel}>
{t('issues.labels')}
</AppText>
<ChipSelect
options={labelOptions}
selectedIds={labelIds}
onToggle={toggle(setLabelIds)}
emptyLabel={t('issues.compose.noLabels')}
/>
</Card>
<Card>
<AppText variant="label" tone="secondary" style={styles.sectionLabel}>
{t('issues.compose.assignees')}
</AppText>
<ChipSelect
options={assigneeOptions}
selectedIds={assignees}
onToggle={toggle(setAssignees)}
emptyLabel={t('issues.compose.noAssignees')}
/>
</Card>
<Card>
<AppText variant="label" tone="secondary" style={styles.sectionLabel}>
{t('issues.milestone')}
</AppText>
<ChipSelect
options={milestoneOptions}
selectedIds={milestoneId ? [milestoneId] : []}
onToggle={(id) => setMilestoneId((prev) => (prev === id ? null : id))}
emptyLabel={t('issues.compose.noMilestones')}
single
/>
</Card>
{mutation.isError ? (
<AppText variant="caption" tone="error">
{apiErrorMessage(mutation.error, t)}
</AppText>
) : null}
<Button
label={editing ? t('issues.compose.save') : t('issues.compose.create')}
onPress={submit}
loading={mutation.isPending}
disabled={title.trim().length === 0}
fullWidth
testID="issue-submit"
/>
<View style={styles.spacer} />
</Screen>
);
}
const styles = StyleSheet.create({
sectionLabel: { marginBottom: spacing.sm },
spacer: { height: spacing.xl },
});
@@ -1,18 +1,31 @@
import { StyleSheet, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { CommentItem } from '@/components/git/comment';
import { CommentComposer } from '@/components/git/comment-composer';
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 { 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 { ErrorState, LoadingView } from '@/components/ui/state-views';
import { apiErrorMessage } from '@/core/api/error-text';
import { safeHost } from '@/core/api/instance-url';
import type { Comment } from '@/core/api/types';
import { flattenPages } from '@/core/utils/infinite';
import { useSession } from '@/features/accounts/use-session';
import { useIssue } from '@/features/issues/queries';
import {
useCreateIssueComment,
useDeleteIssueComment,
useIssue,
useIssueComments,
useUpdateIssue,
useUpdateIssueComment,
} from '@/features/issues/queries';
import { formatRelativeTime } from '@/core/utils/format';
import { useTheme } from '@/theme/theme-provider';
import { spacing } from '@/theme/tokens';
@@ -21,15 +34,20 @@ 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) {
/** Full issue view: state, author, labels, milestone, body, comments and composer. */
export function IssueDetailScreen({ navigation, route }: Props) {
const { t } = useTranslation();
const { colors } = useTheme();
const { instance } = useSession();
const { instance, account, token } = useSession();
const { owner, name, index } = route.params;
const query = useIssue(owner, name, index);
const issue = query.data;
const commentsQuery = useIssueComments(owner, name, index);
const updateIssue = useUpdateIssue(owner, name, index);
const createComment = useCreateIssueComment(owner, name, index);
const updateComment = useUpdateIssueComment(owner, name, index);
const deleteComment = useDeleteIssueComment(owner, name, index);
if (query.isPending) return <LoadingView />;
if (query.isError) {
@@ -46,6 +64,12 @@ export function IssueDetailScreen({ route }: Props) {
const author = issue.user;
const state = issue.state === 'closed' ? 'closed' : 'open';
const host = instance ? safeHost(instance.baseUrl) : null;
const comments: Comment[] = flattenPages(commentsQuery.data);
const toggleState = () => {
updateIssue.mutate({ state: state === 'closed' ? 'open' : 'closed' });
};
return (
<Screen scroll padded>
@@ -63,6 +87,24 @@ export function IssueDetailScreen({ route }: Props) {
</View>
</View>
<View style={styles.actionRow}>
<Button
label={t('common.edit')}
variant="secondary"
size="md"
iconLeft="edit"
onPress={() => navigation.navigate('IssueCompose', { owner, name, index })}
/>
<Button
label={state === 'closed' ? t('issues.reopen') : t('issues.close')}
variant="secondary"
size="md"
iconLeft={state === 'closed' ? 'refresh' : 'check'}
loading={updateIssue.isPending}
onPress={toggleState}
/>
</View>
<View style={styles.authorRow}>
<Avatar url={author?.avatar_url} name={author?.login ?? '?'} size={28} />
<AppText variant="bodyMedium" style={styles.authorName}>
@@ -72,8 +114,12 @@ export function IssueDetailScreen({ route }: Props) {
{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} />
{issue.labels.map((label, labelIndex) => (
<LabelChip
key={label.id ?? `${label.name}-${labelIndex}`}
name={label.name}
color={label.color}
/>
))}
</View>
) : null}
@@ -97,18 +143,76 @@ export function IssueDetailScreen({ route }: Props) {
})}
/>
) : null}
{issue.milestone ? <MetaRow icon="tag" label={`${t('issues.milestone')}: ${issue.milestone.title}`} /> : 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 })}
label={t('issues.comments', { count: issue.comments ?? comments.length })}
color={colors.textSecondary}
/>
</View>
{/* Comments */}
<AppText variant="subheading" style={styles.sectionTitle}>
{t('comments.title')}
</AppText>
{commentsQuery.isPending ? (
<LoadingView label={t('comments.loading')} />
) : commentsQuery.isError ? (
<ErrorState
title={t('errors.title')}
body={apiErrorMessage(commentsQuery.error, t)}
retryLabel={t('common.retry')}
onRetry={() => void commentsQuery.refetch()}
/>
) : comments.length === 0 ? (
<AppText variant="secondary" tone="tertiary">
{t('comments.empty')}
</AppText>
) : (
comments.map((comment) => {
const isOwn = Boolean(account?.login && comment.user?.login === account.login);
const commentId = comment.id;
return (
<CommentItem
key={commentId}
comment={comment}
baseUrl={instance?.baseUrl}
token={token}
host={host}
isOwn={isOwn}
updating={updateComment.isPending}
onUpdate={
commentId
? (body) => updateComment.mutateAsync({ id: commentId, body })
: undefined
}
onDelete={commentId ? () => deleteComment.mutateAsync(commentId) : undefined}
/>
);
})
)}
<CommentComposer
onSubmit={(body) => createComment.mutateAsync(body)}
pending={createComment.isPending}
errorMessage={createComment.isError ? apiErrorMessage(createComment.error, t) : null}
/>
</Screen>
);
}
function MetaRow({ icon, label, color }: { icon: 'person' | 'tag' | 'mail'; label: string; color?: string }) {
function MetaRow({
icon,
label,
color,
}: {
icon: 'person' | 'tag' | 'mail';
label: string;
color?: string;
}) {
const { colors } = useTheme();
return (
<View style={styles.metaRow}>
@@ -123,10 +227,12 @@ function MetaRow({ icon, label, color }: { icon: 'person' | 'tag' | 'mail'; labe
const styles = StyleSheet.create({
titleBlock: { gap: spacing.sm },
stateRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, flexWrap: 'wrap' },
actionRow: { flexDirection: 'row', 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 },
sectionTitle: { marginTop: spacing.md },
});
@@ -1,17 +1,33 @@
import { StyleSheet, View } from 'react-native';
import { Alert, StyleSheet, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { CommentItem } from '@/components/git/comment';
import { CommentComposer } from '@/components/git/comment-composer';
import { Markdown } from '@/components/git/markdown';
import { StatusChecks } from '@/components/git/status-checks';
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 { Badge, type BadgeTone, StatusBadge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
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 { safeHost } from '@/core/api/instance-url';
import type { Comment, PullReview } from '@/core/api/types';
import { flattenPages } from '@/core/utils/infinite';
import { useSession } from '@/features/accounts/use-session';
import { usePull } from '@/features/issues/queries';
import {
useCombinedStatus,
useCreateIssueComment,
useDeleteIssueComment,
useIssueComments,
useMergePull,
usePull,
usePullReviews,
useUpdateIssueComment,
} from '@/features/issues/queries';
import { formatRelativeTime } from '@/core/utils/format';
import { spacing } from '@/theme/tokens';
import type { RepositoryStackParamList } from '@/navigation/types';
@@ -19,14 +35,41 @@ 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 REVIEW_TONE: Record<string, BadgeTone> = {
APPROVED: 'success',
REQUEST_CHANGES: 'error',
COMMENT: 'neutral',
PENDING: 'warning',
};
function reviewKey(state: string | undefined): string {
switch (state) {
case 'APPROVED':
return 'pulls.reviewStateApproved';
case 'REQUEST_CHANGES':
return 'pulls.reviewStateChanges';
case 'COMMENT':
return 'pulls.reviewStateComment';
default:
return 'pulls.reviewStatePending';
}
}
/** Full pull request view: state, branches, checks, reviews, comments, review/merge actions. */
export function PullDetailScreen({ navigation, route }: Props) {
const { t } = useTranslation();
const { instance } = useSession();
const { instance, account, token } = useSession();
const { owner, name, index } = route.params;
const query = usePull(owner, name, index);
const pull = query.data;
const checks = useCombinedStatus(owner, name, pull?.head?.sha);
const reviewsQuery = usePullReviews(owner, name, index);
const commentsQuery = useIssueComments(owner, name, index);
const createComment = useCreateIssueComment(owner, name, index);
const updateComment = useUpdateIssueComment(owner, name, index);
const deleteComment = useDeleteIssueComment(owner, name, index);
const merge = useMergePull(owner, name, index);
if (query.isPending) return <LoadingView />;
if (query.isError) {
@@ -56,6 +99,30 @@ export function PullDetailScreen({ route }: Props) {
draft: t('pulls.draft'),
}[state];
const host = instance ? safeHost(instance.baseUrl) : null;
const comments: Comment[] = flattenPages(commentsQuery.data);
const reviews: PullReview[] = reviewsQuery.data ?? [];
const canAct = state === 'open';
const mergeDisabled = merge.isPending || pull.mergeable === false;
const doMerge = (style: 'merge' | 'squash' | 'rebase') => {
merge.mutate(
{ style, deleteBranchAfterMerge: false },
{
onSuccess: () => Alert.alert(t('pulls.mergeSuccessTitle'), t('pulls.mergeSuccessBody')),
onError: (error) => Alert.alert(t('errors.title'), apiErrorMessage(error, t)),
},
);
};
const confirmMerge = () => {
Alert.alert(t('pulls.mergeConfirmTitle'), t('pulls.mergeConfirmBody'), [
{ text: t('common.cancel'), style: 'cancel' },
{ text: t('pulls.mergeSquash'), onPress: () => doMerge('squash') },
{ text: t('pulls.mergeCreate'), onPress: () => doMerge('merge') },
]);
};
return (
<Screen scroll padded>
<View style={styles.titleBlock}>
@@ -76,10 +143,72 @@ export function PullDetailScreen({ route }: Props) {
</AppText>
</View>
{/* Checks */}
{checks.data ? <StatusChecks status={checks.data} /> : null}
{/* Actions */}
<View style={styles.actionRow}>
<Button
label={t('pulls.files', { count: pull.changed_files ?? 0 })}
variant="secondary"
size="md"
iconLeft="file"
onPress={() => navigation.navigate('PullFiles', { owner, name, index })}
/>
{canAct ? (
<>
<Button
label={t('pulls.approve')}
variant="secondary"
size="md"
iconLeft="check"
onPress={() =>
navigation.navigate('PullReview', { owner, name, index, event: 'APPROVE' })
}
/>
<Button
label={t('pulls.requestChanges')}
variant="secondary"
size="md"
iconLeft="close"
onPress={() =>
navigation.navigate('PullReview', { owner, name, index, event: 'REQUEST_CHANGES' })
}
/>
<Button
label={t('pulls.comment')}
variant="secondary"
size="md"
iconLeft="mail"
onPress={() =>
navigation.navigate('PullReview', { owner, name, index, event: 'COMMENT' })
}
/>
<Button
label={t('pulls.merge')}
size="md"
iconLeft="pullRequest"
loading={merge.isPending}
disabled={mergeDisabled}
onPress={confirmMerge}
/>
</>
) : null}
</View>
{pull.mergeable === false && canAct ? (
<AppText variant="caption" tone="warning">
{t('pulls.notMergeable')}
</AppText>
) : null}
{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} />
<LabelChip
key={label.id ?? `${label.name}-${labelIndex}`}
name={label.name}
color={label.color}
/>
))}
</View>
) : null}
@@ -101,7 +230,7 @@ export function PullDetailScreen({ route }: Props) {
{t('pulls.changedFiles', { count: pull.changed_files ?? 0 })}
</AppText>
<AppText variant="caption" tone="tertiary">
{t('issues.comments', { count: pull.comments ?? 0 })}
{t('issues.comments', { count: pull.comments ?? comments.length })}
</AppText>
</View>
@@ -122,6 +251,71 @@ export function PullDetailScreen({ route }: Props) {
</View>
</View>
) : null}
{/* Reviews */}
{reviews.length > 0 ? (
<>
<AppText variant="subheading" style={styles.sectionTitle}>
{t('pulls.reviews')}
</AppText>
{reviews.map((review, reviewIndex) => (
<Card key={review.id ?? reviewIndex}>
<View style={styles.reviewHeader}>
<Avatar url={review.user?.avatar_url} name={review.user?.login ?? '?'} size={24} />
<AppText variant="bodyMedium" style={styles.reviewerName} numberOfLines={1}>
{review.user?.login ?? t('common.unknown')}
</AppText>
<Badge tone={REVIEW_TONE[review.state ?? 'PENDING'] ?? 'neutral'}>
{t(reviewKey(review.state))}
</Badge>
</View>
{review.body && review.body.trim().length > 0 ? (
<Markdown content={review.body} baseUrl={instance?.baseUrl} />
) : null}
</Card>
))}
</>
) : null}
{/* Comments */}
<AppText variant="subheading" style={styles.sectionTitle}>
{t('comments.title')}
</AppText>
{commentsQuery.isPending ? (
<LoadingView label={t('comments.loading')} />
) : comments.length === 0 ? (
<AppText variant="secondary" tone="tertiary">
{t('comments.empty')}
</AppText>
) : (
comments.map((comment) => {
const isOwn = Boolean(account?.login && comment.user?.login === account.login);
const commentId = comment.id;
return (
<CommentItem
key={commentId}
comment={comment}
baseUrl={instance?.baseUrl}
token={token}
host={host}
isOwn={isOwn}
updating={updateComment.isPending}
onUpdate={
commentId
? (body) => updateComment.mutateAsync({ id: commentId, body })
: undefined
}
onDelete={commentId ? () => deleteComment.mutateAsync(commentId) : undefined}
/>
);
})
)}
<CommentComposer
onSubmit={(body) => createComment.mutateAsync(body)}
pending={createComment.isPending}
errorMessage={createComment.isError ? apiErrorMessage(createComment.error, t) : null}
/>
</Screen>
);
}
@@ -129,10 +323,14 @@ export function PullDetailScreen({ route }: Props) {
const styles = StyleSheet.create({
titleBlock: { gap: spacing.sm },
stateRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, flexWrap: 'wrap' },
actionRow: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
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 },
reviewHeader: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
reviewerName: { flexShrink: 1, flex: 1, fontWeight: '600' },
sectionTitle: { marginTop: spacing.md },
});
@@ -0,0 +1,36 @@
import { useTranslation } from 'react-i18next';
import { DiffView } from '@/components/git/diff';
import { Screen } from '@/components/layout/screen';
import { ErrorState, LoadingView } from '@/components/ui/state-views';
import { apiErrorMessage } from '@/core/api/error-text';
import { usePullDiff } from '@/features/issues/queries';
import type { RepositoryStackParamList } from '@/navigation/types';
import type { ScreenProps } from '@/navigation/typing';
type Props = ScreenProps<RepositoryStackParamList, 'PullDiff'>;
/** Native unified diff for a pull request (all files, or a single `path`). */
export function PullDiffScreen({ route }: Props) {
const { t } = useTranslation();
const { owner, name, index, path } = route.params;
const query = usePullDiff(owner, name, index);
if (query.isPending) return <LoadingView label={t('pulls.loadingDiff')} />;
if (query.isError) {
return (
<ErrorState
title={t('errors.title')}
body={apiErrorMessage(query.error, t)}
retryLabel={t('common.retry')}
onRetry={() => void query.refetch()}
/>
);
}
return (
<Screen padded={false} scroll={false}>
<DiffView raw={query.data ?? ''} pathFilter={path} emptyLabel={t('pulls.noChanges')} />
</Screen>
);
}
@@ -0,0 +1,136 @@
import { Pressable, StyleSheet, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { Screen } from '@/components/layout/screen';
import { AppText } from '@/components/ui/app-text';
import { Badge, type BadgeTone } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Icon } from '@/components/ui/icon';
import { EmptyState, ErrorState, LoadingView } from '@/components/ui/state-views';
import { apiErrorMessage } from '@/core/api/error-text';
import type { ChangedFile } from '@/core/api/types';
import { usePullFiles } from '@/features/issues/queries';
import { fontFamily, spacing } from '@/theme/tokens';
import type { RepositoryStackParamList } from '@/navigation/types';
import type { ScreenProps } from '@/navigation/typing';
type Props = ScreenProps<RepositoryStackParamList, 'PullFiles'>;
const STATUS_TONE: Record<string, BadgeTone> = {
added: 'success',
removed: 'error',
modified: 'warning',
renamed: 'info',
copied: 'info',
changed: 'warning',
unchanged: 'neutral',
};
function statusKey(status: string | undefined): string {
switch (status) {
case 'added':
return 'pulls.fileAdded';
case 'removed':
return 'pulls.fileRemoved';
case 'renamed':
return 'pulls.fileRenamed';
case 'copied':
return 'pulls.fileCopied';
case 'modified':
case 'changed':
return 'pulls.fileModified';
default:
return 'pulls.fileChanged';
}
}
/** Changed files in a pull request; tapping a file opens its diff. */
export function PullFilesScreen({ navigation, route }: Props) {
const { t } = useTranslation();
const { owner, name, index } = route.params;
const query = usePullFiles(owner, name, index);
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()}
/>
);
}
const files: ChangedFile[] = query.data ?? [];
if (files.length === 0) {
return (
<EmptyState icon="file" title={t('pulls.noChangedFiles')} body={t('pulls.noChangesBody')} />
);
}
return (
<Screen scroll padded>
<Button
label={t('pulls.viewFullDiff')}
variant="secondary"
iconLeft="code"
fullWidth
onPress={() => navigation.navigate('PullDiff', { owner, name, index })}
/>
<Card padded={false} variant="flat">
{files.map((file, fileIndex) => {
const key = file.filename ?? `file-${fileIndex}`;
return (
<Pressable
key={key}
onPress={() =>
navigation.navigate('PullDiff', { owner, name, index, path: file.filename })
}
accessibilityRole="button"
accessibilityLabel={file.filename}
style={({ pressed }) => [
styles.row,
fileIndex < files.length - 1 && styles.divider,
pressed && styles.pressed,
]}
>
<Icon name="file" size={16} style={styles.icon} />
<View style={styles.body}>
<AppText variant="bodyMedium" numberOfLines={2} style={styles.path}>
{file.filename}
</AppText>
<View style={styles.meta}>
<Badge tone={STATUS_TONE[file.status ?? 'unchanged'] ?? 'neutral'}>
{t(statusKey(file.status))}
</Badge>
<AppText variant="caption" tone="tertiary">
{`+${file.additions ?? 0} −${file.deletions ?? 0}`}
</AppText>
</View>
</View>
</Pressable>
);
})}
</Card>
</Screen>
);
}
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
alignItems: 'flex-start',
gap: spacing.md,
paddingHorizontal: spacing.lg,
paddingVertical: spacing.md,
},
divider: { borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: 'rgba(128,128,128,0.25)' },
pressed: { opacity: 0.6 },
icon: { marginTop: 2 },
body: { flex: 1, gap: spacing.xs },
path: { fontFamily: fontFamily.mono },
meta: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
});
@@ -0,0 +1,71 @@
import { useState } from 'react';
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 { Button } from '@/components/ui/button';
import { TextArea } from '@/components/ui/text-area';
import { apiErrorMessage } from '@/core/api/error-text';
import type { ReviewEvent } from '@/core/api/types';
import { useCreatePullReview } 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, 'PullReview'>;
/** Submit a pull-request review: approve, request changes, or leave a comment. */
export function PullReviewScreen({ navigation, route }: Props) {
const { t } = useTranslation();
const { owner, name, index, event } = route.params;
const [body, setBody] = useState('');
const mutation = useCreatePullReview(owner, name, index);
const requiresBody = event === 'REQUEST_CHANGES';
const canSubmit = !requiresBody || body.trim().length > 0;
const submit = () => {
if (!canSubmit) return;
mutation.mutate(
{ event: event as ReviewEvent, body: body.trim() || undefined },
{ onSuccess: () => navigation.goBack() },
);
};
return (
<Screen scroll padded>
<AppText variant="secondary" tone="tertiary">
{t(`pulls.review.${event.toLowerCase()}`)}
</AppText>
<TextArea
label={t('pulls.review.body')}
value={body}
onChangeText={setBody}
placeholder={t('pulls.review.placeholder')}
autoCapitalize="sentences"
autoCorrect
minHeight={140}
testID="review-body"
/>
{mutation.isError ? (
<AppText variant="caption" tone="error">
{apiErrorMessage(mutation.error, t)}
</AppText>
) : null}
<Button
label={t('pulls.review.submit')}
onPress={submit}
loading={mutation.isPending}
disabled={!canSubmit}
fullWidth
testID="review-submit"
/>
<View style={styles.spacer} />
</Screen>
);
}
const styles = StyleSheet.create({
spacer: { height: spacing.xl },
});
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
import { IssueRow } from '@/components/git/issue-row';
import { QueryList } from '@/components/layout/query-list';
import { Button } from '@/components/ui/button';
import { SearchBar } from '@/components/ui/search-bar';
import { SegmentedControl } from '@/components/ui/segmented';
import { EmptyState } from '@/components/ui/state-views';
@@ -52,6 +53,15 @@ export function RepoIssuesScreen({ navigation, route }: Props) {
]}
/>
</View>
<View style={styles.newIssue}>
<Button
label={t('issues.compose.createTitle')}
variant="secondary"
iconLeft="plus"
fullWidth
onPress={() => navigation.navigate('IssueCompose', { owner, name })}
/>
</View>
</View>
}
renderItem={(issue) => (
@@ -67,4 +77,5 @@ export function RepoIssuesScreen({ navigation, route }: Props) {
const styles = StyleSheet.create({
filters: { paddingHorizontal: spacing.lg, paddingBottom: spacing.sm },
newIssue: { paddingHorizontal: spacing.lg, paddingBottom: spacing.sm },
});