diff --git a/README.md b/README.md index 6caa370..f81c744 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,16 @@ Then press `i` (iOS simulator), `a` (Android emulator) or scan the QR code with a development build. Use `npx expo start` and open the app on a device/emulator with a dev build for the full feature set. +## Demo mode + +To try the app without a Gitea instance, tap **“Try the demo”** on the welcome +screen. It registers a local demo account whose API requests are served by an +in-app mock backend (`src/core/demo/demo-fetch.ts`) with sample repositories, +issues, pull requests, reviews, releases, notifications, Actions runs and more. +No network access or credentials are used, and every screen works exactly as it +does against a real instance. Remove the demo from **Settings → Accounts** to +leave demo mode. + ## Configuration There is **no server URL or credential in the repository**. Everything is diff --git a/jest.setup.ts b/jest.setup.ts index 01617d6..cccff22 100644 --- a/jest.setup.ts +++ b/jest.setup.ts @@ -11,8 +11,24 @@ jest.mock('@react-native-async-storage/async-storage', () => require('@react-native-async-storage/async-storage/jest/async-storage-mock'), ); -// Reanimated: official mock (worklets are not available in Jest). -jest.mock('react-native-reanimated', () => require('react-native-reanimated/mock')); +// Reanimated: minimal manual mock (the real package pulls native worklets). +jest.mock('react-native-reanimated', () => { + const { View } = require('react-native'); + return { + __esModule: true, + default: { View, createAnimatedComponent: (component: unknown) => component }, + useSharedValue: (value: unknown) => ({ value }), + useAnimatedStyle: () => ({}), + withTiming: (value: unknown) => value, + withRepeat: (value: unknown) => value, + withSequence: (...values: unknown[]) => values[values.length - 1], + withDelay: (_delay: number, value: unknown) => value, + cancelAnimation: () => undefined, + runOnJS: (fn: unknown) => fn, + runOnUI: (fn: unknown) => fn, + Easing: { linear: () => 0, ease: () => 0, inOut: () => 0, out: () => 0, in: () => 0 }, + }; +}); // Safe area: official mock so SafeAreaView/useSafeAreaInsets work in tests. jest.mock('react-native-safe-area-context', () => require('react-native-safe-area-context/jest/mock')); diff --git a/src/__tests__/demo-ui.test.tsx b/src/__tests__/demo-ui.test.tsx new file mode 100644 index 0000000..28d497f --- /dev/null +++ b/src/__tests__/demo-ui.test.tsx @@ -0,0 +1,67 @@ +/** + * UI-level demo E2E: render real screens against the demo backend and assert + * that remote data reaches the interface. + */ + +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { render, screen, waitFor } from '@testing-library/react-native'; + +import { AppThemeProvider } from '@/theme/theme-provider'; +import { useAccountsStore } from '@/core/accounts/accounts-store'; +import { DEMO_BASE_URL, DEMO_TOKEN } from '@/core/demo'; +import { RepositoryListScreen } from '@/features/repositories/screens/repository-list-screen'; +import { RepoOverviewScreen } from '@/features/repository/screens/repo-overview-screen'; + +function seedDemoSession() { + useAccountsStore.setState({ + hydrated: true, + instances: [{ id: 'demo-inst', baseUrl: DEMO_BASE_URL, label: 'Demo', addedAt: 0, version: '1.22.0' }], + accounts: [ + { id: 'demo-acct', instanceId: 'demo-inst', login: 'octocat', fullName: 'Octo Cat', addedAt: 0 }, + ], + activeAccountId: 'demo-acct', + tokens: { 'demo-acct': DEMO_TOKEN }, + }); +} + +function renderScreen(node: React.ReactElement) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + {node} + , + ); +} + +const navigation = { + navigate: jest.fn(), + setParams: jest.fn(), + goBack: jest.fn(), + push: jest.fn(), +} as never; + +const route = { key: 'k', name: 'test', params: undefined } as never; + +describe('demo UI', () => { + beforeEach(() => { + seedDemoSession(); + jest.clearAllMocks(); + }); + + it('renders the demo repository list', async () => { + renderScreen(); + await waitFor(() => expect(screen.getByText('hello-world')).toBeTruthy()); + }); + + it('renders the demo repository overview', async () => { + renderScreen( + , + ); + // Repository name and default-branch badge prove the detail query resolved. + await waitFor(() => expect(screen.getAllByText('hello-world').length).toBeGreaterThan(0)); + await waitFor(() => expect(screen.getAllByText('main').length).toBeGreaterThan(0)); + }); +}); diff --git a/src/core/demo/demo-fetch.test.ts b/src/core/demo/demo-fetch.test.ts new file mode 100644 index 0000000..1eb70ff --- /dev/null +++ b/src/core/demo/demo-fetch.test.ts @@ -0,0 +1,166 @@ +/** + * Demo-mode end-to-end test. + * + * The demo backend stands in for a real Gitea instance. This suite drives the + * *real* endpoint functions (the same ones the screens use) through the demo + * `FetchLike`, so it verifies that each feature has a working data path. + */ + +import { GiteaClient } from '@/core/api/client'; +import * as api from '@/core/api/endpoints'; +import { DEMO_BASE_URL, DEMO_TOKEN, demoFetch, isDemoBaseUrl, startDemoAccount } from '@/core/demo'; +import { useAccountsStore } from '@/core/accounts/accounts-store'; + +// jest.mock is hoisted above the imports by babel-jest at runtime. +jest.mock('expo-secure-store', () => ({ + getItemAsync: jest.fn(async () => null), + setItemAsync: jest.fn(async () => undefined), + deleteItemAsync: jest.fn(async () => undefined), +})); + +const client = new GiteaClient({ baseUrl: DEMO_BASE_URL, token: DEMO_TOKEN, fetchImpl: demoFetch }); +const owner = 'octocat'; +const repo = 'hello-world'; + +describe('demo mode', () => { + it('detects the demo instance URL', () => { + expect(isDemoBaseUrl(DEMO_BASE_URL)).toBe(true); + expect(isDemoBaseUrl('https://codeberg.org')).toBe(false); + expect(isDemoBaseUrl(null)).toBe(false); + }); + + it('registers a usable demo account', async () => { + useAccountsStore.setState({ + instances: [], + accounts: [], + activeAccountId: null, + tokens: {}, + hydrated: true, + }); + await startDemoAccount(); + const state = useAccountsStore.getState(); + expect(state.accounts).toHaveLength(1); + expect(state.accounts[0].login).toBe('octocat'); + expect(state.instances[0].baseUrl).toBe(DEMO_BASE_URL); + expect(state.activeAccountId).toBe(state.accounts[0].id); + }); + + it('serves identity and version', async () => { + expect((await api.fetchVersion(client)).version).toBe('1.22.0'); + expect((await api.fetchAuthenticatedUser(client)).login).toBe('octocat'); + }); + + it('serves repositories, search and stars', async () => { + expect((await api.listMyRepos(client, {})).data.length).toBeGreaterThanOrEqual(3); + expect((await api.searchRepositories(client, { q: 'hello' })).data.length).toBeGreaterThan(0); + expect((await api.listStarredRepos(client, {})).data.length).toBe(1); + const detail = await api.fetchRepository(client, owner, repo); + expect(detail.name).toBe(repo); + expect(Object.keys(await api.fetchRepositoryLanguages(client, owner, repo))).toContain('TypeScript'); + }); + + it('serves contents and README', async () => { + const root = await api.listContents(client, owner, repo, ''); + expect(root.some((entry) => entry.name === 'README.md')).toBe(true); + const readme = await api.fetchReadme(client, owner, repo); + expect(readme?.content ?? '').not.toBe(''); + }); + + it('serves branches, tags, commits and checks', async () => { + expect((await api.listBranches(client, owner, repo, {})).data[0].name).toBe('main'); + expect((await api.listTags(client, owner, repo, {})).data[0].name).toBe('v1.0.0'); + const commits = await api.listCommits(client, owner, repo, {}); + expect(commits.data.length).toBeGreaterThanOrEqual(2); + const commit = await api.fetchCommit(client, owner, repo, 'a1b2c3d4e5f6'); + expect(commit.files?.length).toBeGreaterThan(0); + const checks = await api.fetchCombinedStatus(client, owner, repo, 'a1b2c3d4e5f6'); + expect(checks.state).toBe('success'); + }); + + it('serves issues, comments, reactions, labels and milestones', async () => { + expect((await api.listRepoIssues(client, owner, repo, {})).data.length).toBeGreaterThan(0); + const issue = await api.fetchIssue(client, owner, repo, 1); + expect(issue.title).toContain('demo'); + expect((await api.listIssueComments(client, owner, repo, 1, {})).data.length).toBe(2); + expect((await api.listRepoLabels(client, owner, repo, {})).data.length).toBe(3); + expect((await api.listMilestones(client, owner, repo, {})).data.length).toBe(2); + expect((await api.listIssueReactions(client, owner, repo, 1)).length).toBe(1); + expect((await api.listIssueAttachments(client, owner, repo, 1)).length).toBe(1); + expect((await api.checkIssueSubscription(client, owner, repo, 1)).subscribed).toBe(true); + }); + + it('serves cross-repo issue and pull search', async () => { + expect((await api.searchIssues(client, { type: 'issues' })).data.length).toBeGreaterThan(0); + expect((await api.searchIssues(client, { type: 'pulls', reviewRequested: true })).data.length).toBe(1); + }); + + it('serves pull requests, files, diffs and reviews', async () => { + expect((await api.listPulls(client, owner, repo, {})).data.length).toBe(1); + const pull = await api.fetchPull(client, owner, repo, 1); + expect(pull.title).toContain('documentation'); + expect((await api.listPullFiles(client, owner, repo, 1)).length).toBe(2); + expect(await api.fetchPullDiff(client, owner, repo, 1)).toContain('diff --git'); + expect((await api.listPullReviews(client, owner, repo, 1, {})).data.length).toBe(2); + expect((await api.listReviewComments(client, owner, repo, 1, 301)).length).toBe(1); + }); + + it('serves releases and release assets', async () => { + const releases = await api.listReleases(client, owner, repo, {}); + expect(releases.data[0].tag_name).toBe('v1.0.0'); + expect((await api.fetchRelease(client, owner, repo, 501)).assets?.length).toBe(1); + }); + + it('serves notifications and unread count', async () => { + expect((await api.listNotifications(client, {})).data.length).toBeGreaterThan(0); + expect((await api.fetchUnreadNotificationCount(client)).count).toBe(1); + }); + + it('serves the activity feed', async () => { + expect((await api.listUserActivity(client, owner, {})).data.length).toBe(2); + }); + + it('serves Actions runs, jobs, logs, artifacts and workflows', async () => { + expect((await api.listWorkflows(client, owner, repo, {})).data.length).toBe(2); + const runs = await api.listActionRuns(client, owner, repo, {}); + expect(runs.data.length).toBe(2); + expect(runs.data[0].status).toBe('success'); + expect((await api.fetchActionRun(client, owner, repo, 801)).id).toBe(801); + expect((await api.listActionRunJobs(client, owner, repo, 801, {})).data.length).toBe(2); + expect(await api.fetchActionJobLogs(client, owner, repo, 901)).toContain('Build succeeded'); + expect((await api.listRunArtifacts(client, owner, repo, 801)).artifacts?.length).toBe(1); + }); + + it('serves repository settings data', async () => { + expect((await api.listCollaborators(client, owner, repo, {})).data.length).toBe(1); + expect((await api.listWebhooks(client, owner, repo, {})).data.length).toBe(1); + expect((await api.listRepoKeys(client, owner, repo, {})).data.length).toBe(1); + expect((await api.listBranchProtections(client, owner, repo, {})).data.length).toBe(1); + expect((await api.listRepoProjects(client, owner, repo, {})).data.length).toBe(1); + expect((await api.listRepoSecrets(client, owner, repo, {})).data.length).toBe(1); + expect((await api.listRepoVariables(client, owner, repo, {})).data.length).toBe(1); + expect((await api.fetchRepoTree(client, owner, repo, 'main')).entries?.length).toBeGreaterThan(0); + }); + + it('serves account, orgs, packages and credentials', async () => { + expect((await api.listUserOrgs(client, {})).data.length).toBe(1); + expect((await api.listOrgTeams(client, 'demo-org', {})).data.length).toBe(1); + expect((await api.listPackages(client, owner, {})).data.length).toBe(1); + expect((await api.listUserKeys(client, {})).data.length).toBe(1); + expect((await api.listUserGpgKeys(client, {})).data.length).toBe(1); + expect((await api.listUserTokens(client, owner, {})).data.length).toBe(1); + expect((await api.listAdminUsers(client, {})).data.length).toBe(2); + expect((await api.listAdminOrgs(client, {})).data.length).toBe(1); + expect((await api.listAdminRepos(client, {})).data.length).toBe(3); + }); + + it('accepts writes without a server', async () => { + expect((await api.createIssueComment(client, owner, repo, 1, 'hello')).id).toBeTruthy(); + expect((await api.createPullReview(client, owner, repo, 1, { event: 'COMMENT', body: 'ok' })).id).toBeTruthy(); + expect((await api.createIssue(client, owner, repo, { title: 'New' })).number).toBeTruthy(); + await api.starRepo(client, owner, repo); + await api.putRepoSecret(client, owner, repo, 'KEY', 'value'); + await api.setWorkflowEnabled(client, owner, repo, '1001', false); + await api.linkPackageToRepo(client, owner, 'npm', 'demo-pkg', repo); + await api.markNotificationThreadRead(client, 701); + }); +}); diff --git a/src/core/demo/demo-fetch.ts b/src/core/demo/demo-fetch.ts new file mode 100644 index 0000000..d50c1cc --- /dev/null +++ b/src/core/demo/demo-fetch.ts @@ -0,0 +1,620 @@ +/** + * Demo backend. + * + * A deterministic, in-memory Gitea API served through a `FetchLike`, so the app + * can be fully exercised without a real instance. Enabled by pointing an account + * at `DEMO_BASE_URL`; {@link isDemoBaseUrl} detects it and the session wires this + * fetch into the API client. + * + * It is intentionally shaped exactly like the real API (JSON bodies, `X-Total-Count` + * headers, `text/plain` diffs) so the same hooks and screens run unchanged. + */ + +import type { FetchLike } from '@/core/api/client'; +import { encodeBase64Utf8 } from '@/core/utils/base64'; + +export const DEMO_BASE_URL = 'https://demo.gitea.local'; +export const DEMO_HOST = 'demo.gitea.local'; +export const DEMO_TOKEN = 'demo-token'; +export const DEMO_LOGIN = 'octocat'; + +export function isDemoBaseUrl(baseUrl: string | null | undefined): boolean { + if (!baseUrl) return false; + try { + return new URL(baseUrl).host === DEMO_HOST; + } catch { + return false; + } +} + +const now = Date.UTC(2026, 0, 15, 12, 0, 0); + +function iso(daysAgo: number): string { + return new Date(now - daysAgo * 86_400_000).toISOString(); +} + +const user = { + id: 1, + login: DEMO_LOGIN, + full_name: 'Octo Cat', + email: 'octocat@example.com', + is_admin: true, + avatar_url: '', + created: iso(400), +}; + +const repos = [ + { + id: 1, + name: 'hello-world', + full_name: 'octocat/hello-world', + owner: { id: 1, login: DEMO_LOGIN, full_name: 'Octo Cat', avatar_url: '' }, + private: false, + description: 'A demo repository with issues, pull requests, releases and Actions.', + default_branch: 'main', + html_url: `${DEMO_BASE_URL}/${DEMO_LOGIN}/hello-world`, + clone_url: `${DEMO_BASE_URL}/${DEMO_LOGIN}/hello-world.git`, + stars_count: 42, + forks_count: 7, + watchers_count: 12, + open_issues_count: 2, + open_pr_counter: 1, + release_counter: 1, + topics: ['demo', 'gitea'], + has_issues: true, + has_pull_requests: true, + has_wiki: true, + has_releases: true, + has_projects: true, + has_packages: true, + has_actions: true, + permissions: { admin: true, push: true, pull: true }, + updated_at: iso(1), + created_at: iso(365), + }, + { + id: 2, + name: 'dotfiles', + full_name: 'octocat/dotfiles', + owner: { id: 1, login: DEMO_LOGIN }, + private: true, + description: 'My personal dotfiles.', + default_branch: 'main', + stars_count: 3, + forks_count: 0, + watchers_count: 1, + open_issues_count: 0, + open_pr_counter: 0, + release_counter: 0, + has_issues: true, + has_pull_requests: true, + has_wiki: false, + has_releases: false, + has_projects: false, + has_packages: false, + has_actions: false, + permissions: { admin: true, push: true, pull: true }, + updated_at: iso(3), + created_at: iso(200), + }, + { + id: 3, + name: 'gitea-native-demo', + full_name: 'octocat/gitea-native-demo', + owner: { id: 1, login: DEMO_LOGIN }, + private: false, + description: 'Playground repository.', + default_branch: 'main', + stars_count: 128, + forks_count: 15, + watchers_count: 40, + open_issues_count: 1, + open_pr_counter: 0, + release_counter: 2, + has_issues: true, + has_pull_requests: true, + has_wiki: true, + has_releases: true, + has_projects: true, + has_packages: true, + has_actions: true, + permissions: { admin: false, push: false, pull: true }, + updated_at: iso(5), + created_at: iso(120), + }, +]; + +const repoMeta = (repo: (typeof repos)[number]) => ({ + id: repo.id, + name: repo.name, + owner: DEMO_LOGIN, + full_name: repo.full_name, +}); + +const labels = [ + { id: 1, name: 'bug', color: 'd73a4a', description: 'Something is not working' }, + { id: 2, name: 'enhancement', color: 'a2eeef', description: 'New feature or request' }, + { id: 3, name: 'documentation', color: '0075ca' }, +]; + +const milestones = [ + { id: 1, title: 'v1.0', description: 'First stable release', state: 'open', open_issues: 1, closed_issues: 2 }, + { id: 2, title: 'v1.1', state: 'open', open_issues: 2, closed_issues: 0 }, +]; + +const issues = [ + { + id: 101, + number: 1, + title: 'Welcome to the demo', + body: '# Welcome 👋\n\nThis issue shows **Markdown**, labels, and comments.\n\n- Try the diff viewer\n- Open a pull request\n- Check the inbox', + user, + state: 'open', + labels: [labels[2]], + milestone: milestones[0], + assignees: [user], + comments: 2, + created_at: iso(10), + updated_at: iso(1), + repository: repoMeta(repos[0]), + }, + { + id: 102, + number: 2, + title: 'Add a dark theme toggle', + body: 'It would be great to switch themes quickly from the home screen.', + user, + state: 'open', + labels: [labels[1]], + comments: 0, + created_at: iso(4), + updated_at: iso(2), + repository: repoMeta(repos[0]), + }, + { + id: 103, + number: 3, + title: 'Fix a typo in the README', + body: 'Small docs fix.', + user, + state: 'closed', + labels: [labels[2]], + comments: 0, + created_at: iso(30), + updated_at: iso(25), + repository: repoMeta(repos[0]), + }, + { + id: 104, + number: 1, + title: 'Explore the playground', + body: 'First issue in the playground repo.', + user, + state: 'open', + labels: [], + comments: 0, + created_at: iso(6), + updated_at: iso(6), + repository: repoMeta(repos[2]), + }, +]; + +const comment = (id: number, body: string, daysAgo: number) => ({ + id, + body, + user, + created_at: iso(daysAgo), + updated_at: iso(daysAgo), +}); + +const issueComments: Record[]> = { + 1: [ + comment(1001, 'Thanks for trying the demo! 🎉', 9), + comment(1002, 'Tip: tap **Files → README.md** to see the editor.', 2), + ], +}; + +const pulls = [ + { + id: 201, + number: 1, + title: 'Improve the documentation', + body: 'This PR updates the docs and adds examples.\n\n> Reviewed via the demo mode.', + user, + state: 'open', + labels: [labels[2]], + head: { label: 'docs/improve', ref: 'docs/improve', sha: 'a1b2c3d' }, + base: { label: 'main', ref: 'main', sha: 'f6e5d4c' }, + mergeable: true, + additions: 24, + deletions: 6, + changed_files: 2, + comments: 1, + created_at: iso(3), + updated_at: iso(1), + repository: repoMeta(repos[0]), + }, +]; + +const reviews = [ + { + id: 301, + user, + state: 'COMMENT', + body: 'Looks good overall — one inline note.', + submitted_at: iso(1), + comments_count: 1, + }, + { + id: 302, + user: { ...user, id: 2, login: 'reviewer' }, + state: 'APPROVED', + body: 'Approved! 👍', + submitted_at: iso(1), + comments_count: 0, + }, +]; + +const reviewComments = [ + { + id: 401, + body: 'Can we add an example here?', + path: 'README.md', + position: 4, + user, + created_at: iso(1), + }, +]; + +const diffText = [ + 'diff --git a/README.md b/README.md', + 'index 111..222 100644', + '--- a/README.md', + '+++ b/README.md', + '@@ -1,4 +1,6 @@', + ' # Hello World', + ' ', + '-Old description.', + '+A clearer description with examples.', + '+', + '+## Usage', + ' Use it however you like.', + 'diff --git a/docs/guide.md b/docs/guide.md', + 'new file mode 100644', + '--- /dev/null', + '+++ b/docs/guide.md', + '@@ -0,0 +1,2 @@', + '+# Guide', + '+Step by step.', + '', +].join('\n'); + +const commits = [ + { + sha: 'a1b2c3d4e5f6', + commit: { + message: 'Improve docs\n\nAdd clearer wording and a usage section.', + author: { name: 'Octo Cat', email: 'octocat@example.com', date: iso(1) }, + }, + author: user, + stats: { additions: 24, deletions: 6, total: 30 }, + files: [ + { filename: 'README.md', status: 'modified', additions: 20, deletions: 6, patch: '@@ -1 +1 @@\n-Old\n+New' }, + { filename: 'docs/guide.md', status: 'added', additions: 4, deletions: 0, patch: '@@ -0,0 +1,2 @@\n+# Guide' }, + ], + created: iso(1), + }, + { + sha: 'f6e5d4c3b2a1', + commit: { + message: 'Initial commit', + author: { name: 'Octo Cat', email: 'octocat@example.com', date: iso(300) }, + }, + author: user, + stats: { additions: 10, deletions: 0, total: 10 }, + files: [{ filename: 'README.md', status: 'added', additions: 10, deletions: 0 }], + created: iso(300), + }, +]; + +const releases = [ + { + id: 501, + tag_name: 'v1.0.0', + name: 'First release', + body: 'Highlights:\n\n- Demo mode\n- Diff viewer', + draft: false, + prerelease: false, + author: user, + created_at: iso(20), + published_at: iso(20), + html_url: `${DEMO_BASE_URL}/${DEMO_LOGIN}/hello-world/releases/tag/v1.0.0`, + assets: [{ id: 601, name: 'demo-binary.zip', size: 2_048_000, download_count: 12, browser_download_url: '#' }], + }, +]; + +const notifications = [ + { + id: 701, + repository: repos[0], + subject: { + title: 'Welcome to the demo', + type: 'Issue', + url: `${DEMO_BASE_URL}/api/v1/repos/${DEMO_LOGIN}/hello-world/issues/1`, + }, + unread: true, + updated_at: iso(0.2), + }, + { + id: 702, + repository: repos[0], + subject: { + title: 'Improve the documentation', + type: 'Pull', + url: `${DEMO_BASE_URL}/api/v1/repos/${DEMO_LOGIN}/hello-world/pulls/1`, + }, + unread: false, + updated_at: iso(1), + }, +]; + +const actionRuns = [ + { + id: 801, + title: 'CI', + status: 'success', + conclusion: 'success', + event: 'push', + head_branch: 'main', + head_sha: 'a1b2c3d4e5f6', + run_number: 12, + created_at: iso(1), + html_url: `${DEMO_BASE_URL}/${DEMO_LOGIN}/hello-world/actions/runs/801`, + }, + { + id: 802, + title: 'CI', + status: 'failure', + conclusion: 'failure', + event: 'pull_request', + head_branch: 'docs/improve', + run_number: 11, + created_at: iso(2), + html_url: `${DEMO_BASE_URL}/${DEMO_LOGIN}/hello-world/actions/runs/802`, + }, +]; + +const actionJobs = [ + { id: 901, name: 'build (1)', run_id: 801, status: 'success', conclusion: 'success', started_at: iso(1) }, + { id: 902, name: 'test (1)', run_id: 801, status: 'success', conclusion: 'success', started_at: iso(1) }, +]; + +const workflows = [ + { id: 1001, name: 'CI', path: '.gitea/workflows/ci.yml', state: 'active' }, + { id: 1002, name: 'Release', path: '.gitea/workflows/release.yml', state: 'disabled' }, +]; + +const treeEntries = [ + { path: 'README.md', type: 'blob', size: 120, sha: 'aaa' }, + { path: 'docs', type: 'tree', sha: 'bbb' }, + { path: 'docs/guide.md', type: 'blob', size: 60, sha: 'ccc' }, + { path: 'src', type: 'tree', sha: 'ddd' }, + { path: 'src/index.ts', type: 'blob', size: 200, sha: 'eee' }, + { path: 'package.json', type: 'blob', size: 300, sha: 'fff' }, +]; + +const README_CONTENT = encodeBase64Utf8( + '# Hello World\n\nWelcome to the **Gitea Native** demo.\n\n- Browse files\n- Open issues\n- Review a pull request\n', +); + +function json(body: unknown, status = 200, headers: Record = {}): Response { + return { + ok: status >= 200 && status < 300, + status, + headers: { get: (key: string) => headers[key] ?? null }, + text: async () => JSON.stringify(body), + } as unknown as Response; +} + +function raw(text: string, status = 200): Response { + return { + ok: status >= 200 && status < 300, + status, + headers: { get: () => null }, + text: async () => text, + } as unknown as Response; +} + +function empty(status = 204): Response { + return { + ok: status >= 200 && status < 300, + status, + headers: { get: () => null }, + text: async () => '', + } as unknown as Response; +} + +function notFound(): Response { + return json({ message: 'Not found' }, 404); +} + +function listBody(items: T[], path: string): Response { + if (path.endsWith('.diff')) return raw(diffText); + return json(items, 200, { 'X-Total-Count': String(items.length) }); +} + +/** A `FetchLike` that serves the demo API. */ +export const demoFetch: FetchLike = async (input, init) => { + const method = (init?.method ?? 'GET').toUpperCase(); + const url = new URL(input); + const path = url.pathname.replace(/^.*\/api\/v1/, '') || '/'; + const query = url.searchParams; + + // Identity / version + if (method === 'GET' && path === '/version') return json({ version: '1.22.0' }); + if (method === 'GET' && path === '/user') return json(user); + if (method === 'GET' && path === '/user/settings') return json({ full_name: 'Octo Cat', location: 'Demo land' }); + if (method === 'PATCH' && path === '/user/settings') return json(user); + + // Repositories list/search + if (method === 'GET' && path === '/user/repos') return listBody(repos, path); + if (method === 'GET' && path === '/user/starred') return listBody([repos[0]], path); + if (method === 'GET' && path === '/repos/search') return listBody(repos, path); + + // Cross-repo issue search + if (method === 'GET' && path === '/repos/issues/search') { + const type = query.get('type'); + if (type === 'pulls') { + const review = query.get('review_requested'); + return listBody(review ? pulls : pulls, path); + } + const state = query.get('state') ?? 'open'; + const filtered = issues.filter((issue) => (state === 'all' ? true : issue.state === state)); + return listBody(filtered, path); + } + + // Notifications + if (method === 'GET' && path === '/notifications/new') { + return json({ count: notifications.filter((n) => n.unread).length }); + } + if (method === 'GET' && path === '/notifications') { + const all = query.get('all'); + return listBody(all ? notifications : notifications.filter((n) => n.unread), path); + } + if (method === 'PUT' && path.startsWith('/notifications')) return empty(205); + + // Activity feed + if (method === 'GET' && /^\/users\/[^/]+\/activities\/feeds$/.test(path)) { + return listBody( + [ + { id: 2001, repo: repos[0], op_type: 'create_issue', content: 'Opened issue #2', created: iso(4) }, + { id: 2002, repo: repos[0], op_type: 'create_pull_request', content: 'Opened pull request #1', created: iso(3) }, + ], + path, + ); + } + + // Account-level + if (method === 'GET' && path === '/user/orgs') return listBody([{ id: 1, username: 'demo-org', name: 'demo-org', description: 'Demo organisation' }], path); + if (method === 'GET' && /^\/orgs\/[^/]+\/teams$/.test(path)) { + return listBody([{ id: 1, name: 'Owners', permission: 'owner', organization: { username: 'demo-org' } }], path); + } + if (method === 'GET' && path === '/user/keys') return listBody([{ id: 1, title: 'Demo key', fingerprint: 'SHA256:demo', read_only: true }], path); + if (method === 'GET' && path === '/user/gpg_keys') return listBody([{ id: 1, key_id: 'ABCD1234', emails: [{ email: 'octocat@example.com', verified: true }], verified: true }], path); + if (method === 'GET' && /^\/users\/[^/]+\/tokens$/.test(path)) return listBody([{ id: 1, name: 'demo-token', token_last_eight: 'demotokn', scopes: ['read:repository'] }], path); + if (method === 'GET' && /^\/packages\/[^/]+$/.test(path)) return listBody([{ id: 1, name: 'demo-pkg', type: 'npm', version: '1.0.0', created_at: iso(5) }], path); + if (method === 'GET' && path === '/admin/users') return listBody([user, { ...user, id: 2, login: 'reviewer' }], path); + if (method === 'GET' && path === '/admin/orgs') return listBody([{ id: 1, username: 'demo-org' }], path); + if (method === 'GET' && path === '/admin/repos') return listBody(repos, path); + + // Per-repository routes + const repoMatch = path.match(/^\/repos\/([^/]+)\/([^/]+)(\/.*)?$/); + if (repoMatch) { + const [, owner, name, rest = ''] = repoMatch; + const repo = repos.find((r) => r.owner.login === owner && r.name === name); + + if (rest === '' || rest === '/') { + if (method === 'PATCH') return json(repo ?? notFound()); + if (method === 'DELETE') return empty(204); + return repo ? json(repo) : notFound(); + } + if (rest === '/languages') return json({ TypeScript: 8000, CSS: 1200, Shell: 400 }); + if (rest === '/releases') return listBody(releases, path); + if (rest === '/releases/501' || rest === '/releases/latest') return json(releases[0]); + if (rest.startsWith('/releases/')) return json(releases[0]); + if (rest === '/branches') return listBody([{ name: 'main', protected: true }, { name: 'docs/improve' }], path); + if (rest === '/tags') return listBody([{ name: 'v1.0.0', commit: { sha: 'a1b2c3d4e5f6' } }], path); + if (rest === '/commits') return listBody(commits, path); + if (/^\/commits\/[^/]+\/status$/.test(rest)) { + return json({ state: 'success', sha: 'a1b2c3d4e5f6', total_count: 2, statuses: [{ context: 'ci/build', status: 'success', description: 'Build passed' }, { context: 'ci/test', status: 'success', description: 'Tests passed' }] }); + } + if (/^\/commits\/[^/]+$/.test(rest)) return json(commits[0]); + if (rest === '/issues') { + if (method === 'POST') { + return json({ ...issues[1], number: 99, id: 999, title: 'New demo issue' }); + } + return listBody(issues.filter((issue) => issue.repository?.id === repo?.id), path); + } + if (rest === '/labels') return listBody(labels, path); + if (rest === '/milestones') return listBody(milestones, path); + if (rest === '/pulls') return listBody(pulls, path); + if (/^\/pulls\/\d+\/files$/.test(rest)) { + return json([ + { filename: 'README.md', status: 'modified', additions: 20, deletions: 6, changes: 26 }, + { filename: 'docs/guide.md', status: 'added', additions: 4, deletions: 0, changes: 4 }, + ]); + } + if (/^\/pulls\/\d+\.diff$/.test(rest)) return raw(diffText); + if (/^\/pulls\/\d+\/reviews\/\d+\/comments$/.test(rest)) return json(reviewComments); + if (/^\/pulls\/\d+\/reviews$/.test(rest)) { + if (method === 'POST') { + return json({ id: 999, user, state: 'COMMENT', body: 'Thanks!', submitted_at: iso(0) }); + } + return listBody(reviews, path); + } + if (/^\/pulls\/\d+$/.test(rest)) return json(pulls[0]); + if (rest === '/collaborators') return listBody([user], path); + if (rest === '/hooks') return listBody([{ id: 1, type: 'gitea', active: true, events: ['push'], config: { url: 'https://example.com/hook' } }], path); + if (rest === '/keys') return listBody([{ id: 1, title: 'Deploy key', read_only: true, fingerprint: 'SHA256:deploy' }], path); + if (rest === '/branch_protections') return listBody([{ rule_name: 'main', branch_name: 'main', enable_push: false, required_approvals: 1, require_signed_commits: true }], path); + if (rest === '/projects') return listBody([{ id: 1, title: 'Roadmap', description: 'What is coming', is_closed: false, num_open_issues: 2, num_closed_issues: 1, html_url: `${DEMO_BASE_URL}/${owner}/${name}/projects/1` }], path); + if (rest === '/actions/runs') return listBody(actionRuns, path); + if (/^\/actions\/runs\/\d+\/jobs$/.test(rest)) return listBody(actionJobs, path); + if (/^\/actions\/runs\/\d+\/artifacts$/.test(rest)) return json({ artifacts: [{ id: 1, name: 'build.zip', size_in_bytes: 102400, expired: false, archive_download_url: '#' }] }); + if (/^\/actions\/runs\/\d+$/.test(rest)) return json(actionRuns[0]); + if (/^\/actions\/jobs\/\d+\/logs$/.test(rest)) return raw('Build started\nCompiling…\nBuild succeeded ✅\n'); + if (rest === '/actions/workflows') return listBody(workflows, path); + if (rest === '/actions/secrets') return listBody([{ name: 'DEMO_SECRET' }], path); + if (rest === '/actions/variables') return listBody([{ name: 'DEMO_VAR', data: 'value' }], path); + if (rest.startsWith('/git/trees/')) return json({ sha: 'tree', truncated: false, total_count: treeEntries.length, entries: treeEntries }); + if (rest === '/contents' || rest === '/contents/') { + return json([ + { name: 'README.md', path: 'README.md', type: 'file', size: 120, sha: 'aaa' }, + { name: 'docs', path: 'docs', type: 'dir', size: 0, sha: 'bbb' }, + { name: 'src', path: 'src', type: 'dir', size: 0, sha: 'ddd' }, + ]); + } + if (rest.startsWith('/contents/')) { + const filePath = rest.slice('/contents/'.length); + if (filePath === 'README.md') { + return json({ name: 'README.md', path: 'README.md', type: 'file', size: 120, sha: 'aaa', encoding: 'base64', content: README_CONTENT }); + } + if (repo?.name === 'hello-world' && filePath.startsWith('src/')) { + return json({ name: 'index.ts', path: filePath, type: 'file', size: 200, sha: 'eee', encoding: 'base64', content: encodeBase64Utf8('export const demo = true;\n') }); + } + return json({ name: filePath.split('/').pop(), path: filePath, type: 'file', size: 0, sha: 'sha', encoding: 'base64', content: '' }); + } + + // Issue detail, comments, labels, reactions, attachments + const issueMatch = rest.match(/^\/issues\/(\d+)$/); + if (issueMatch) { + const n = Number(issueMatch[1]); + const found = issues.find((issue) => issue.number === n && issue.repository?.id === repo?.id) ?? issues[0]; + return json(found); + } + const issueCommentsMatch = rest.match(/^\/issues\/(\d+)\/comments$/); + if (issueCommentsMatch) { + if (method === 'POST') return json(comment(9999, 'Thanks for your comment!', 0)); + return listBody(issueComments[Number(issueCommentsMatch[1])] ?? [], path); + } + if (/^\/issues\/\d+\/reactions$/.test(rest)) { + if (method === 'GET') return json([{ content: '+1', user }]); + return json({ content: '+1', user }); + } + if (/^\/issues\/\d+\/assets$/.test(rest)) return json([{ id: 1, name: 'screenshot.png', size: 51200, browser_download_url: '#' }]); + if (/^\/issues\/\d+\/subscriptions\/check$/.test(rest)) return json({ subscribed: true }); + if (rest === '/issues' && method === 'POST') { + return json({ ...issues[1], number: 99, id: 999, title: 'New demo issue' }); + } + if (/^\/pulls\/\d+\/reviews$/.test(rest) && method === 'POST') { + return json({ id: 999, user, state: 'COMMENT', body: 'Thanks!', submitted_at: iso(0) }); + } + if (rest === '/pulls' && method === 'POST') return json(pulls[0]); + } + + // Generic mutations (star/watch/fork/labels/milestones/secrets/…): succeed. + if (method !== 'GET') return empty(204); + + // Unknown GET: empty collection rather than an error, to keep the demo usable. + return listBody([], path); +}; diff --git a/src/core/demo/index.ts b/src/core/demo/index.ts new file mode 100644 index 0000000..d2e16e6 --- /dev/null +++ b/src/core/demo/index.ts @@ -0,0 +1,23 @@ +/** + * Demo mode helpers. + * + * Starting the demo registers a local instance whose API calls are served by + * {@link demoFetch} — no network and no credentials required. + */ + +import { useAccountsStore } from '@/core/accounts/accounts-store'; + +import { DEMO_BASE_URL, DEMO_LOGIN, DEMO_TOKEN } from './demo-fetch'; + +export { demoFetch, isDemoBaseUrl, DEMO_BASE_URL, DEMO_HOST, DEMO_TOKEN, DEMO_LOGIN } from './demo-fetch'; + +/** Registers the built-in demo instance and makes it the active account. */ +export async function startDemoAccount(): Promise { + await useAccountsStore.getState().registerAccount({ + baseUrl: DEMO_BASE_URL, + label: 'Demo', + token: DEMO_TOKEN, + version: '1.22.0', + profile: { login: DEMO_LOGIN, id: 1, fullName: 'Octo Cat' }, + }); +} diff --git a/src/features/accounts/use-session.ts b/src/features/accounts/use-session.ts index f1c8766..3b78adc 100644 --- a/src/features/accounts/use-session.ts +++ b/src/features/accounts/use-session.ts @@ -7,6 +7,7 @@ import { useMemo } from 'react'; import { useAccountsStore, selectActive } from '@/core/accounts/accounts-store'; import { GiteaClient } from '@/core/api/client'; +import { demoFetch, isDemoBaseUrl } from '@/core/demo'; import type { AccountRecord, InstanceRecord } from '@/core/accounts/types'; export interface Session { @@ -32,7 +33,11 @@ export function useSession(): Session { const client = useMemo(() => { if (!active || !token) return null; - return new GiteaClient({ baseUrl: active.instance.baseUrl, token }); + return new GiteaClient({ + baseUrl: active.instance.baseUrl, + token, + fetchImpl: isDemoBaseUrl(active.instance.baseUrl) ? demoFetch : undefined, + }); }, [active, token]); return { diff --git a/src/features/auth/screens/welcome-screen.tsx b/src/features/auth/screens/welcome-screen.tsx index fea7ee1..93bb714 100644 --- a/src/features/auth/screens/welcome-screen.tsx +++ b/src/features/auth/screens/welcome-screen.tsx @@ -1,5 +1,5 @@ -import { useEffect } from 'react'; -import { StyleSheet, View } from 'react-native'; +import { useEffect, useState } from 'react'; +import { Alert, StyleSheet, View } from 'react-native'; import { useTranslation } from 'react-i18next'; import { AppText } from '@/components/ui/app-text'; @@ -8,6 +8,8 @@ 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 { startDemoAccount } from '@/core/demo'; +import { apiErrorMessage } from '@/core/api/error-text'; import { useConnectAccount } from '@/features/auth/use-connect-account'; import { useAccountActions } from '@/features/accounts/use-account-actions'; import { useTheme } from '@/theme/theme-provider'; @@ -26,6 +28,18 @@ export function WelcomeScreen({ navigation }: Props) { const activeAccountId = useAccountsStore((s) => s.activeAccountId); const switchAccount = useAccountActions().switchAccount; const { reset } = useConnectAccount(); + const [startingDemo, setStartingDemo] = useState(false); + + const startDemo = async () => { + setStartingDemo(true); + try { + await startDemoAccount(); + } catch (error) { + Alert.alert(t('errors.title'), apiErrorMessage(error, t)); + } finally { + setStartingDemo(false); + } + }; // Arriving here with accounts means a token failed validation — reset the // previous error so a fresh connect attempt starts clean. @@ -55,6 +69,19 @@ export function WelcomeScreen({ navigation }: Props) { onPress={() => navigation.navigate('Connect')} style={{ marginTop: spacing.lg }} /> +