feat(phase4): Quick Edit, Contents API commit flow, editor workspace

- portable UTF-8 base64 helpers (Hermes-safe), used for file round-trips
- endpoints: updateFileContents, createFileContents, createPull
- hooks: useCommitFile (invalidates repo cache), useCreatePull
- FileEdit screen: native monospace editor, dirty/discard, branch picker,
  commit-to-new-branch, protected-branch handling, post-commit PR creation;
  stale-SHA 409 surfaces as a conflict message
- settings: editor URL template; repo overview 'Open in editor' (no token)
- tests: base64 round-trips (accents/emoji), editor URL expansion
This commit is contained in:
JustZoe101 committed 2026-10-09 17:19:06 +02:00
1 parent ddd834b7ac
commit c9dd49446a
18 files changed
+733 -29

No files matched your search

@@ -0,0 +1,299 @@
import { useMemo, useState } from 'react';
import { Alert, 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 { 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 type { Branch, ContentsEntry, Repository } from '@/core/api/types';
import { encodeBase64Utf8 } from '@/core/utils/base64';
import { flattenPages } from '@/core/utils/infinite';
import { useCreatePull } from '@/features/issues/queries';
import { useRepository } from '@/features/repositories/queries';
import { decodeBase64, useBranches, useCommitFile, useFile } from '@/features/repository/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, 'FileEdit'>;
/**
* Quick Edit: edit a file in a monospace editor and commit it through the
* Contents API. Supports committing to a new branch (which also handles
* protected branches) and optionally opening a pull request afterwards.
*/
export function FileEditScreen({ navigation, route }: Props) {
const { t } = useTranslation();
const { owner, name, path, ref } = route.params;
const fileQuery = useFile(owner, name, path, ref);
const refetchFile = fileQuery.refetch;
const repoQuery = useRepository(owner, name);
const branchesQuery = useBranches(owner, name, '');
const branches = flattenPages(branchesQuery.data);
const entry = fileQuery.data;
if (fileQuery.isPending) return <LoadingView />;
if (fileQuery.isError) {
return (
<ErrorState
title={t('errors.title')}
body={apiErrorMessage(fileQuery.error, t)}
retryLabel={t('common.retry')}
onRetry={() => void refetchFile()}
/>
);
}
if (!entry) {
return (
<ErrorState
title={t('files.rawUnavailable')}
retryLabel={t('common.retry')}
onRetry={() => void refetchFile()}
/>
);
}
return (
<FileEditForm
key={entry.sha ?? entry.path}
owner={owner}
name={name}
path={path}
initialRef={ref}
entry={entry}
repo={repoQuery.data}
branches={branches}
onDone={() => navigation.goBack()}
/>
);
}
interface FormProps {
owner: string;
name: string;
path: string;
initialRef?: string;
entry: ContentsEntry;
repo?: Repository;
branches: Branch[];
onDone: () => void;
}
function FileEditForm({ owner, name, path, initialRef, entry, repo, branches, onDone }: FormProps) {
const { t } = useTranslation();
const { colors } = useTheme();
const commitFile = useCommitFile(owner, name);
const createPull = useCreatePull(owner, name);
// Initialised once per file (the parent remounts this component via `key`).
const [original] = useState(() => decodeBase64(entry.content ?? ''));
const [draft, setDraft] = useState(original);
const [message, setMessage] = useState('');
const [branch, setBranch] = useState<string | null>(initialRef ?? null);
const [useNewBranch, setUseNewBranch] = useState(false);
const [newBranch, setNewBranch] = useState('');
const [createPr, setCreatePr] = useState(false);
const [prTitle, setPrTitle] = useState('');
const [submitted, setSubmitted] = useState(false);
const targetBranch = branch ?? repo?.default_branch ?? null;
const branchOptions = useMemo(
() => branches.map((b) => ({ id: b.name, label: b.name })),
[branches],
);
const currentBranch = branches.find((b) => b.name === targetBranch);
const branchProtected = Boolean(currentBranch?.protected && currentBranch?.user_can_push !== true);
const effectiveNewBranch = useNewBranch || branchProtected;
const dirty = draft !== original;
const canSubmit =
dirty &&
message.trim().length > 0 &&
(effectiveNewBranch ? newBranch.trim().length > 0 : Boolean(targetBranch)) &&
!commitFile.isPending;
const submit = () => {
setSubmitted(true);
if (!canSubmit || !entry.sha) return;
const newBranchName = effectiveNewBranch ? newBranch.trim() : undefined;
commitFile.mutate(
{
path,
content: encodeBase64Utf8(draft),
message: message.trim(),
branch: targetBranch ?? undefined,
newBranch: newBranchName,
sha: entry.sha,
},
{
onSuccess: async () => {
if (createPr && newBranchName && targetBranch && prTitle.trim().length > 0) {
try {
await createPull.mutateAsync({
title: prTitle.trim(),
head: newBranchName,
base: targetBranch,
body: message.trim(),
});
} catch {
// The commit succeeded; a failed PR can be opened from the web UI.
}
}
Alert.alert(t('edit.commitSuccessTitle'), t('edit.commitSuccessBody'));
onDone();
},
},
);
};
return (
<Screen scroll padded>
<View style={styles.toolbar}>
<AppText variant="monoSmall" tone="tertiary" numberOfLines={1} style={styles.pathLabel}>
{path}
</AppText>
{dirty ? (
<Button
label={t('edit.discard')}
variant="ghost"
size="md"
onPress={() => setDraft(original)}
/>
) : null}
</View>
<TextArea
value={draft}
onChangeText={setDraft}
minHeight={360}
mono
autoCapitalize="none"
autoCorrect={false}
testID="file-editor"
/>
{branchProtected ? (
<AppText variant="caption" tone="warning">
{t('edit.protectedBranch', { branch: targetBranch ?? '' })}
</AppText>
) : null}
<Card>
<AppText variant="label" tone="secondary" style={styles.sectionLabel}>
{t('edit.branch')}
</AppText>
<ChipSelect
options={branchOptions}
selectedIds={targetBranch ? [targetBranch] : []}
onToggle={(id) => setBranch(id)}
emptyLabel={t('edit.loadingBranches')}
single
/>
<View style={styles.switchRow}>
<AppText variant="bodyMedium" style={styles.switchLabel}>
{t('edit.createBranch')}
</AppText>
<Switch
value={effectiveNewBranch}
onValueChange={setUseNewBranch}
disabled={branchProtected}
trackColor={{ true: colors.primary, false: colors.border }}
/>
</View>
{effectiveNewBranch ? (
<Field
label={t('edit.newBranchName')}
value={newBranch}
onChangeText={setNewBranch}
placeholder={t('edit.newBranchPlaceholder')}
autoCapitalize="none"
autoCorrect={false}
mono
testID="new-branch"
/>
) : null}
</Card>
<TextArea
label={t('edit.commitMessage')}
value={message}
onChangeText={setMessage}
placeholder={t('edit.commitMessagePlaceholder')}
minHeight={80}
autoCapitalize="sentences"
autoCorrect
testID="commit-message"
/>
{effectiveNewBranch ? (
<Card>
<View style={styles.switchRow}>
<AppText variant="bodyMedium" style={styles.switchLabel}>
{t('edit.openPullRequest')}
</AppText>
<Switch
value={createPr}
onValueChange={setCreatePr}
trackColor={{ true: colors.primary, false: colors.border }}
/>
</View>
{createPr ? (
<Field
label={t('edit.prTitle')}
value={prTitle}
onChangeText={setPrTitle}
placeholder={t('edit.prTitlePlaceholder')}
autoCapitalize="sentences"
testID="pr-title"
/>
) : null}
</Card>
) : null}
{submitted && !canSubmit ? (
<AppText variant="caption" tone="error">
{t('edit.incomplete')}
</AppText>
) : null}
{commitFile.isError ? (
<AppText variant="caption" tone="error">
{apiErrorMessage(commitFile.error, t)}
</AppText>
) : null}
<Button
label={t('edit.commit')}
onPress={submit}
loading={commitFile.isPending}
disabled={!canSubmit}
fullWidth
testID="commit-submit"
/>
<View style={styles.spacer} />
</Screen>
);
}
const styles = StyleSheet.create({
toolbar: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
pathLabel: { flex: 1 },
sectionLabel: { marginBottom: spacing.sm },
switchRow: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
gap: spacing.md,
marginTop: spacing.md,
},
switchLabel: { flex: 1 },
spacer: { height: spacing.xl },
});