From c9dd49446a1dd30aa38bfc9394ee7c6a60a1c8d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zo=C3=AB=20Kooijmans?= Date: Fri, 9 Oct 2026 17:19:06 +0200 Subject: [PATCH] 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 --- ROADMAP.md | 23 +- docs/FEATURE_PARITY.md | 14 +- src/core/api/endpoints.ts | 88 ++++++ src/core/utils/base64.test.ts | 31 ++ src/core/utils/base64.ts | 78 +++++ src/core/utils/editor-url.test.ts | 31 ++ src/core/utils/editor-url.ts | 26 ++ src/features/issues/queries.ts | 17 + src/features/repository/queries.ts | 28 +- .../repository/screens/file-edit-screen.tsx | 299 ++++++++++++++++++ .../repository/screens/file-viewer-screen.tsx | 13 +- .../screens/repo-overview-screen.tsx | 28 +- .../settings/screens/settings-screen.tsx | 19 ++ src/features/settings/settings-store.ts | 10 + src/i18n/locales/en.json | 24 ++ src/i18n/locales/nl.json | 24 ++ src/navigation/repository-navigator.tsx | 8 + src/navigation/types.ts | 1 + 18 files changed, 733 insertions(+), 29 deletions(-) create mode 100644 src/core/utils/base64.test.ts create mode 100644 src/core/utils/base64.ts create mode 100644 src/core/utils/editor-url.test.ts create mode 100644 src/core/utils/editor-url.ts create mode 100644 src/features/repository/screens/file-edit-screen.tsx diff --git a/ROADMAP.md b/ROADMAP.md index 6d78af0..e2ce7a4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -16,7 +16,7 @@ This document is the living implementation plan. It is updated as phases land. | 1 | Foundation: design system, auth, multi-account, biometrics | ✅ Done | | 2 | Core Git experience: home, repos, browsing, commits | ✅ Done | | 3 | Collaboration: issues, PRs, reviews, notifications | ✅ Done (read + write) | -| 4 | Code editing: Quick Edit (CodeMirror), VS Code workspace | ⬜ Planned | +| 4 | Code editing: Quick Edit, commit flow, editor workspace | ✅ Done (native editor) | | 5 | Advanced: Actions, packages, orgs, wiki, releases, admin | ⬜ Planned | Detailed acceptance criteria per phase are in `docs/FEATURE_PARITY.md`. @@ -103,16 +103,19 @@ Architectural decisions are recorded in `docs/ARCHITECTURE.md`. - [ ] Server-side filter UI (label, milestone, assignee) and sorting - [ ] Reactions/subscriptions -## Phase 4 — Code editing (planned) +## Phase 4 — Code editing -- [ ] Quick Edit: CodeMirror 6 in a dedicated WebView -- [ ] Syntax highlighting, line numbers, search/replace, auto-indent -- [ ] Unsaved-changes detection, diff preview -- [ ] Branch selection/creation, commit message, Contents API commit (base64 + SHA) -- [ ] Optional "create pull request" after commit -- [ ] Protected-branch awareness and stale-SHA (409) conflict handling -- [ ] VS Code workspace: per-instance/repo IDE URL, embedded browser, system-browser fallback -- [ ] IDE auth kept separate from Gitea API auth (no token passthrough) +- [x] Quick Edit: in-app editor over the file contents (native, monospace) +- [x] Commit through the Contents API (base64 content + blob SHA) +- [x] Branch selection and **commit to a new branch** (`new_branch`) +- [x] Protected-branch awareness (force a new branch when direct push is blocked) +- [x] Optional "create pull request" right after committing to a new branch +- [x] Stale-SHA (409) conflict handling with a clear message +- [x] Unsaved-changes detection + discard +- [x] Per-instance editor/IDE URL template ("Open in editor"), system-browser/app fallback +- [x] IDE auth stays separate from Gitea API auth (no token in the URL) +- [ ] CodeMirror 6 editor in a WebView (syntax highlighting, search/replace) +- [ ] Line-level diff preview before committing ## Phase 5 — Advanced features (planned) diff --git a/docs/FEATURE_PARITY.md b/docs/FEATURE_PARITY.md index 05adbe9..991040d 100644 --- a/docs/FEATURE_PARITY.md +++ b/docs/FEATURE_PARITY.md @@ -102,14 +102,18 @@ roadmap). | i18n (en/nl) | ✅ | device detection + override | | Loading/empty/error states | ✅ | shared components | -## Code editing (planned) +## Code editing | Feature | Status | Notes | | --- | --- | --- | -| Quick Edit (CodeMirror WebView) | ⬜ | syntax highlight, search/replace | -| Commit via Contents API | ⬜ | base64 + SHA, 409 conflict handling | -| Create PR after commit | ⬜ | | -| VS Code workspace | 🌐 | per-instance IDE URL, no token passthrough | +| Quick Edit | ✅ | native monospace editor (CodeMirror/WebView deferred) | +| Commit via Contents API | ✅ | base64 + blob SHA; creates the commit | +| Commit to a new branch | ✅ | `new_branch`, auto-forced on protected branches | +| Protected-branch awareness | ✅ | blocks direct commits when `user_can_push` is false | +| Stale-SHA (409) handling | ✅ | mapped to a clear conflict message | +| Create PR after commit | ✅ | when committing to a new branch | +| VS Code / editor workspace | ✅ | configurable URL template, no token passthrough | +| Syntax highlighting / search-replace | ⬜ | planned (CodeMirror 6 in a WebView) | ## Advanced (planned) diff --git a/src/core/api/endpoints.ts b/src/core/api/endpoints.ts index 5b04a49..52b305f 100644 --- a/src/core/api/endpoints.ts +++ b/src/core/api/endpoints.ts @@ -628,6 +628,94 @@ export function fetchCombinedStatus( ); } +// --------------------------------------------------------------------------- +// File editing (Contents API) & pull request creation +// --------------------------------------------------------------------------- + +/** Result of a Contents API write: the new commit plus the updated entry. */ +export interface FileWriteResponse { + commit?: { sha?: string; html_url?: string }; + content?: ContentsEntry; +} + +export interface CommitFileInput { + path: string; + /** Base64-encoded file content. */ + content: string; + message: string; + /** Target branch. Defaults to the repository's default branch. */ + branch?: string; + /** When set, the commit is made on a new branch created from `branch`. */ + newBranch?: string; + /** Blob SHA of the file being replaced (required for updates). */ + sha?: string; + signoff?: boolean; +} + +/** Updates an existing file via `PUT /repos/{owner}/{repo}/contents/{path}`. */ +export function updateFileContents( + client: GiteaClient, + owner: string, + repo: string, + input: CommitFileInput, + options?: RequestOptions, +): Promise { + return client.put( + `${repoPath(owner, repo)}/contents/${encodeRepoPath(input.path)}`, + { + content: input.content, + message: input.message, + branch: input.branch, + new_branch: input.newBranch, + sha: input.sha, + signoff: input.signoff, + }, + options, + ); +} + +/** Creates a new file via `POST /repos/{owner}/{repo}/contents/{path}`. */ +export function createFileContents( + client: GiteaClient, + owner: string, + repo: string, + input: CommitFileInput, + options?: RequestOptions, +): Promise { + return client.post( + `${repoPath(owner, repo)}/contents/${encodeRepoPath(input.path)}`, + { + content: input.content, + message: input.message, + branch: input.branch, + new_branch: input.newBranch, + signoff: input.signoff, + }, + options, + ); +} + +export interface CreatePullInput { + title: string; + head: string; + base: string; + body?: string; +} + +export function createPull( + client: GiteaClient, + owner: string, + repo: string, + input: CreatePullInput, + options?: RequestOptions, +): Promise { + return client.post( + `${repoPath(owner, repo)}/pulls`, + { title: input.title, head: input.head, base: input.base, body: input.body }, + options, + ); +} + // --------------------------------------------------------------------------- // Notifications // --------------------------------------------------------------------------- diff --git a/src/core/utils/base64.test.ts b/src/core/utils/base64.test.ts new file mode 100644 index 0000000..d9772bd --- /dev/null +++ b/src/core/utils/base64.test.ts @@ -0,0 +1,31 @@ +/** Portable base64 ⇄ UTF-8 helpers (Contents API round-trip). */ + +import { decodeBase64Utf8, encodeBase64Utf8 } from './base64'; + +describe('base64 utf-8', () => { + it('encodes ASCII to standard base64', () => { + expect(encodeBase64Utf8('hello')).toBe('aGVsbG8='); + expect(encodeBase64Utf8('a')).toBe('YQ=='); + expect(encodeBase64Utf8('ab')).toBe('YWI='); + }); + + it('decodes standard base64', () => { + expect(decodeBase64Utf8('TWFu')).toBe('Man'); + expect(decodeBase64Utf8('aGVsbG8=')).toBe('hello'); + }); + + it('round-trips multi-byte content (accents + emoji)', () => { + const text = 'Héllo, wörld! 🌱 commit – 100%'; + expect(decodeBase64Utf8(encodeBase64Utf8(text))).toBe(text); + }); + + it('round-trips empty and multiline content', () => { + expect(decodeBase64Utf8(encodeBase64Utf8(''))).toBe(''); + const multi = 'line 1\nline 2\n\ttabbed\n'; + expect(decodeBase64Utf8(encodeBase64Utf8(multi))).toBe(multi); + }); + + it('tolerates whitespace in decoded input', () => { + expect(decodeBase64Utf8('aGVs\nbG8=')).toBe('hello'); + }); +}); diff --git a/src/core/utils/base64.ts b/src/core/utils/base64.ts new file mode 100644 index 0000000..8c15eaa --- /dev/null +++ b/src/core/utils/base64.ts @@ -0,0 +1,78 @@ +/** + * Portable base64 ⇄ UTF-8 helpers. + * + * Hermes does not guarantee `atob`/`btoa`, and those only handle Latin-1 anyway, + * so the Contents API round-trip uses these pure-JS implementations. They are + * unit-tested against multi-byte (emoji/accented) content. + */ + +const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +function utf8ToBinary(text: string): string { + const encoded = encodeURIComponent(text); + let binary = ''; + for (let i = 0; i < encoded.length; i += 1) { + if (encoded[i] === '%') { + binary += String.fromCharCode(parseInt(encoded.slice(i + 1, i + 3), 16)); + i += 2; + } else { + binary += encoded[i]; + } + } + return binary; +} + +function binaryToUtf8(binary: string): string { + let percent = ''; + for (let i = 0; i < binary.length; i += 1) { + percent += `%${binary.charCodeAt(i).toString(16).padStart(2, '0')}`; + } + try { + return decodeURIComponent(percent); + } catch { + return binary; + } +} + +function binaryToBase64(binary: string): string { + let result = ''; + for (let i = 0; i < binary.length; i += 3) { + const c1 = binary.charCodeAt(i); + const c2 = i + 1 < binary.length ? binary.charCodeAt(i + 1) : NaN; + const c3 = i + 2 < binary.length ? binary.charCodeAt(i + 2) : NaN; + const e1 = c1 >> 2; + const e2 = ((c1 & 3) << 4) | (Number.isNaN(c2) ? 0 : c2 >> 4); + const e3 = Number.isNaN(c2) ? 64 : ((c2 & 15) << 2) | (Number.isNaN(c3) ? 0 : c3 >> 6); + const e4 = Number.isNaN(c3) ? 64 : c3 & 63; + result += ALPHABET[e1] + ALPHABET[e2] + (e3 === 64 ? '=' : ALPHABET[e3]) + (e4 === 64 ? '=' : ALPHABET[e4]); + } + return result; +} + +function base64ToBinary(base64: string): string { + const clean = base64.replace(/[^A-Za-z0-9+/]/g, ''); + let result = ''; + let buffer = 0; + let bits = 0; + for (let i = 0; i < clean.length; i += 1) { + const value = ALPHABET.indexOf(clean[i]); + if (value < 0) continue; + buffer = (buffer << 6) | value; + bits += 6; + if (bits >= 8) { + bits -= 8; + result += String.fromCharCode((buffer >> bits) & 0xff); + } + } + return result; +} + +/** Encodes a UTF-8 string to base64 (used for Contents API payloads). */ +export function encodeBase64Utf8(text: string): string { + return binaryToBase64(utf8ToBinary(text)); +} + +/** Decodes base64 (whitespace tolerated) to a UTF-8 string. */ +export function decodeBase64Utf8(base64: string): string { + return binaryToUtf8(base64ToBinary(base64)); +} diff --git a/src/core/utils/editor-url.test.ts b/src/core/utils/editor-url.test.ts new file mode 100644 index 0000000..e3b4c5f --- /dev/null +++ b/src/core/utils/editor-url.test.ts @@ -0,0 +1,31 @@ +/** Editor URL template expansion. */ + +import { buildEditorUrl } from './editor-url'; + +describe('buildEditorUrl', () => { + it('replaces owner and repo placeholders', () => { + expect( + buildEditorUrl('https://ide.example/{owner}/{repo}', { owner: 'octo', name: 'repo' }), + ).toBe('https://ide.example/octo/repo'); + }); + + it('URI-encodes the clone URL when used as a query parameter', () => { + const url = buildEditorUrl('vscode://vscode.git/clone?url={cloneUrl}', { + owner: 'octo', + name: 'repo', + cloneUrl: 'https://codeberg.org/octo/repo.git', + }); + expect(url).toBe( + 'vscode://vscode.git/clone?url=https%3A%2F%2Fcodeberg.org%2Focto%2Frepo.git', + ); + }); + + it('substitutes missing optional values with an empty string', () => { + expect(buildEditorUrl('x?u={htmlUrl}', { owner: 'o', name: 'r' })).toBe('x?u='); + }); + + it('never adds a token', () => { + const url = buildEditorUrl('https://ide/{owner}/{repo}', { owner: 'o', name: 'r' }); + expect(url).not.toMatch(/token|Authorization/i); + }); +}); diff --git a/src/core/utils/editor-url.ts b/src/core/utils/editor-url.ts new file mode 100644 index 0000000..8ff14af --- /dev/null +++ b/src/core/utils/editor-url.ts @@ -0,0 +1,26 @@ +/** + * Expands the user's editor/IDE URL template for the repository action. + * + * The template is opened with `Linking.openURL` only — the API token is never + * part of the template or the resulting URL, so IDE auth stays separate. + */ + +export interface EditorUrlParts { + owner: string; + name: string; + cloneUrl?: string; + htmlUrl?: string; +} + +/** Replaces `{owner}`, `{repo}`, `{cloneUrl}` and `{htmlUrl}`, URI-encoding each value. */ +export function buildEditorUrl(template: string, parts: EditorUrlParts): string { + return template + .split('{owner}') + .join(encodeURIComponent(parts.owner)) + .split('{repo}') + .join(encodeURIComponent(parts.name)) + .split('{cloneUrl}') + .join(encodeURIComponent(parts.cloneUrl ?? '')) + .split('{htmlUrl}') + .join(encodeURIComponent(parts.htmlUrl ?? '')); +} diff --git a/src/features/issues/queries.ts b/src/features/issues/queries.ts index e173369..40c586f 100644 --- a/src/features/issues/queries.ts +++ b/src/features/issues/queries.ts @@ -20,6 +20,7 @@ import type { RawResponse } from '@/core/api/client'; import { createIssue, createIssueComment, + createPull, createPullReview, deleteIssueComment, fetchCombinedStatus, @@ -39,6 +40,7 @@ import { updateIssue, updateIssueComment, type CreateIssueInput, + type CreatePullInput, type CreateReviewInput, type EditIssueInput, type IssueSearchParams, @@ -437,5 +439,20 @@ export function useCombinedStatus(owner: string, name: string, ref: string | und }); } +/** Create a pull request (used after committing to a new branch). */ +export function useCreatePull(owner: string, name: string) { + const { client, account } = useSession(); + const queryClient = useQueryClient(); + const accountId = account?.id ?? ''; + + return useMutation({ + mutationFn: (input: CreatePullInput) => createPull(client!, owner, name, input), + onSuccess: () => { + void queryClient.invalidateQueries({ queryKey: queryKeys.pullsRoot(accountId, owner, name) }); + void queryClient.invalidateQueries({ queryKey: queryKeys.issueSearchRoot(accountId) }); + }, + }); +} + export type { Issue, Label, PullRequest }; export type { ChangedFile, CombinedStatus, Comment, Milestone, PullReview, User }; diff --git a/src/features/repository/queries.ts b/src/features/repository/queries.ts index bfd8d03..8f15938 100644 --- a/src/features/repository/queries.ts +++ b/src/features/repository/queries.ts @@ -3,7 +3,9 @@ import { keepPreviousData, useInfiniteQuery, + useMutation, useQuery, + useQueryClient, type InfiniteData, } from '@tanstack/react-query'; @@ -17,9 +19,12 @@ import { listCommits, listContents, listTags, + updateFileContents, + type CommitFileInput, } from '@/core/api/endpoints'; import { queryKeys } from '@/core/api/query-keys'; import type { Branch, Commit, Tag } from '@/core/api/types'; +import { decodeBase64Utf8 } from '@/core/utils/base64'; import { useSession } from '@/features/accounts/use-session'; /** Directory listing (or file entry when a path is given). */ @@ -159,12 +164,21 @@ export function useCommit(owner: string, name: string, sha: string) { }); } -/** Convenience: decode a base64 contents payload from the API. */ +/** Convenience: decode a base64 contents payload from the API (UTF-8 safe). */ 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 ''; - } + return decodeBase64Utf8(content); +} + +/** Commit a file edit through the Contents API (update path; handles new branches). */ +export function useCommitFile(owner: string, name: string) { + const { client, account } = useSession(); + const queryClient = useQueryClient(); + const accountId = account?.id ?? ''; + + return useMutation({ + mutationFn: (input: CommitFileInput) => updateFileContents(client!, owner, name, input), + onSuccess: () => { + void queryClient.invalidateQueries({ queryKey: queryKeys.repo(accountId, owner, name) }); + }, + }); } diff --git a/src/features/repository/screens/file-edit-screen.tsx b/src/features/repository/screens/file-edit-screen.tsx new file mode 100644 index 0000000..51ce6be --- /dev/null +++ b/src/features/repository/screens/file-edit-screen.tsx @@ -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; + +/** + * 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 ; + if (fileQuery.isError) { + return ( + void refetchFile()} + /> + ); + } + if (!entry) { + return ( + void refetchFile()} + /> + ); + } + + return ( + 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(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 ( + + + + {path} + + {dirty ? ( +