From 08229fdf86055d3826102a19f855f616fb5b6b7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zo=C3=AB=20Kooijmans?= Date: Fri, 9 Oct 2026 16:41:17 +0200 Subject: [PATCH] feat(ui): component kit, layout primitives and git components - UI kit: button, card, field, avatar, badge, list-item, segmented, skeleton, empty/error/loading state views, icon + icon-button, search bar - layout: Screen, SectionHeader, header buttons, QueryList with pull-to-refresh - git components: repo list item, file rows/breadcrumbs, commit row, issue row, native Markdown renderer, notification row with subject-URL parsing --- src/components/git/commit-row.tsx | 105 ++++++ src/components/git/file-row.tsx | 140 +++++++ src/components/git/issue-row.tsx | 101 ++++++ src/components/git/markdown.tsx | 382 ++++++++++++++++++++ src/components/git/notification-row.test.ts | 48 +++ src/components/git/notification-row.tsx | 144 ++++++++ src/components/git/repo-list-item.tsx | 119 ++++++ src/components/layout/header-buttons.tsx | 75 ++++ src/components/layout/query-list.tsx | 150 ++++++++ src/components/layout/screen.tsx | 67 ++++ src/components/layout/section-header.tsx | 48 +++ src/components/ui/app-text.tsx | 88 +++++ src/components/ui/avatar.tsx | 88 +++++ src/components/ui/badge.tsx | 113 ++++++ src/components/ui/button.test.tsx | 40 ++ src/components/ui/button.tsx | 111 ++++++ src/components/ui/card.tsx | 41 +++ src/components/ui/field.tsx | 163 +++++++++ src/components/ui/icon-button.tsx | 51 +++ src/components/ui/icon.tsx | 212 +++++++++++ src/components/ui/label-chip.tsx | 81 +++++ src/components/ui/list-item.tsx | 116 ++++++ src/components/ui/search-bar.tsx | 71 ++++ src/components/ui/segmented.tsx | 83 +++++ src/components/ui/skeleton.tsx | 64 ++++ src/components/ui/state-views.tsx | 115 ++++++ 26 files changed, 2816 insertions(+) create mode 100644 src/components/git/commit-row.tsx create mode 100644 src/components/git/file-row.tsx create mode 100644 src/components/git/issue-row.tsx create mode 100644 src/components/git/markdown.tsx create mode 100644 src/components/git/notification-row.test.ts create mode 100644 src/components/git/notification-row.tsx create mode 100644 src/components/git/repo-list-item.tsx create mode 100644 src/components/layout/header-buttons.tsx create mode 100644 src/components/layout/query-list.tsx create mode 100644 src/components/layout/screen.tsx create mode 100644 src/components/layout/section-header.tsx create mode 100644 src/components/ui/app-text.tsx create mode 100644 src/components/ui/avatar.tsx create mode 100644 src/components/ui/badge.tsx create mode 100644 src/components/ui/button.test.tsx create mode 100644 src/components/ui/button.tsx create mode 100644 src/components/ui/card.tsx create mode 100644 src/components/ui/field.tsx create mode 100644 src/components/ui/icon-button.tsx create mode 100644 src/components/ui/icon.tsx create mode 100644 src/components/ui/label-chip.tsx create mode 100644 src/components/ui/list-item.tsx create mode 100644 src/components/ui/search-bar.tsx create mode 100644 src/components/ui/segmented.tsx create mode 100644 src/components/ui/skeleton.tsx create mode 100644 src/components/ui/state-views.tsx diff --git a/src/components/git/commit-row.tsx b/src/components/git/commit-row.tsx new file mode 100644 index 0000000..a95d060 --- /dev/null +++ b/src/components/git/commit-row.tsx @@ -0,0 +1,105 @@ +import { Pressable, StyleSheet, View } from 'react-native'; +import { useTranslation } from 'react-i18next'; + +import { AppText } from '@/components/ui/app-text'; +import { Avatar } from '@/components/ui/avatar'; +import { Icon } from '@/components/ui/icon'; +import type { Commit } from '@/core/api/types'; +import { firstLine, formatRelativeTime, shortSha } from '@/core/utils/format'; +import { useTheme } from '@/theme/theme-provider'; +import { HIT_TARGET, radius, spacing } from '@/theme/tokens'; + +export interface CommitRowProps { + commit: Commit; + onPress?: () => void; +} + +/** Commit list row: author avatar, message, sha, date, +/− stats. */ +export function CommitRow({ commit, onPress }: CommitRowProps) { + const { t } = useTranslation(); + const { colors } = useTheme(); + + const authorName = commit.author?.login ?? commit.commit.author?.name ?? t('common.unknown'); + const avatarUrl = commit.author?.avatar_url; + const message = firstLine(commit.commit.message); + const date = commit.commit.author?.date ?? commit.created; + const additions = commit.stats?.additions ?? 0; + const deletions = commit.stats?.deletions ?? 0; + + const body = ( + + + + + {message} + + + + {authorName} + + + + + {shortSha(commit.sha)} + + + + {formatRelativeTime(date, t)} + + {commit.stats ? ( + + + +{additions} + + + −{deletions} + + + ) : null} + + + {onPress ? : null} + + ); + + if (!onPress) return body; + + return ( + pressed && { backgroundColor: colors.surfacePressed }} + > + {body} + + ); +} + +const styles = StyleSheet.create({ + row: { + flexDirection: 'row', + alignItems: 'flex-start', + gap: spacing.md, + minHeight: HIT_TARGET, + paddingVertical: spacing.md, + paddingHorizontal: spacing.lg, + borderBottomWidth: StyleSheet.hairlineWidth, + }, + body: { flex: 1, gap: spacing.xs }, + meta: { + flexDirection: 'row', + alignItems: 'center', + flexWrap: 'wrap', + gap: spacing.sm, + }, + shaChip: { + flexDirection: 'row', + alignItems: 'center', + gap: 3, + paddingHorizontal: spacing.xs, + paddingVertical: 1, + borderRadius: radius.sm, + }, + stats: { flexDirection: 'row', gap: spacing.sm }, +}); diff --git a/src/components/git/file-row.tsx b/src/components/git/file-row.tsx new file mode 100644 index 0000000..e1feb76 --- /dev/null +++ b/src/components/git/file-row.tsx @@ -0,0 +1,140 @@ +import { Pressable, StyleSheet, View } from 'react-native'; + +import { AppText } from '@/components/ui/app-text'; +import { Icon, type IconName } from '@/components/ui/icon'; +import type { ContentsEntry, ContentsType } from '@/core/api/types'; +import { formatBytes } from '@/core/utils/format'; +import { useTheme } from '@/theme/theme-provider'; +import { HIT_TARGET, radius, spacing } from '@/theme/tokens'; + +function iconForType(type: ContentsType): IconName { + switch (type) { + case 'dir': + return 'folder'; + case 'submodule': + return 'package'; + case 'symlink': + return 'link'; + default: + return 'file'; + } +} + +export interface FileRowProps { + entry: ContentsEntry; + onPress: () => void; +} + +/** One row in a directory listing. */ +export function FileRow({ entry, onPress }: FileRowProps) { + const { colors } = useTheme(); + const isDir = entry.type === 'dir'; + + return ( + [ + styles.row, + { borderBottomColor: colors.border }, + pressed && { backgroundColor: colors.surfacePressed }, + ]} + > + + + {entry.name} + + + {isDir ? '' : entry.size >= 0 ? formatBytes(entry.size) : ''} + + + ); +} + +export interface BreadcrumbProps { + /** Full path relative to repo root ("" = root). */ + path: string; + onNavigate: (path: string) => void; + rootLabel: string; +} + +/** Path breadcrumb with horizontal scrolling; last segment is the current one. */ +export function Breadcrumb({ path, onNavigate, rootLabel }: BreadcrumbProps) { + const { colors } = useTheme(); + const segments = path.split('/').filter(Boolean); + + return ( + + onNavigate('')} + accessibilityRole="button" + accessibilityLabel={rootLabel} + style={styles.crumb} + > + + + {rootLabel} + + + + {segments.map((segment, index) => { + const target = segments.slice(0, index + 1).join('/'); + const isLast = index === segments.length - 1; + return ( + + + !isLast && onNavigate(target)} + disabled={isLast} + accessibilityRole="button" + accessibilityLabel={target} + style={styles.crumb} + > + + {segment} + + + + ); + })} + + ); +} + +const styles = StyleSheet.create({ + row: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.md, + minHeight: HIT_TARGET, + paddingVertical: spacing.md, + paddingHorizontal: spacing.lg, + borderBottomWidth: StyleSheet.hairlineWidth, + }, + name: { flex: 1 }, + crumbRow: { + flexDirection: 'row', + alignItems: 'center', + flexWrap: 'nowrap', + paddingHorizontal: spacing.lg, + paddingVertical: spacing.sm, + gap: spacing.xs, + minHeight: 38, + }, + crumbWrap: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs, flexShrink: 1 }, + crumb: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.xs, + paddingVertical: spacing.xs, + paddingHorizontal: spacing.xs, + borderRadius: radius.sm, + flexShrink: 1, + }, +}); diff --git a/src/components/git/issue-row.tsx b/src/components/git/issue-row.tsx new file mode 100644 index 0000000..7721b0f --- /dev/null +++ b/src/components/git/issue-row.tsx @@ -0,0 +1,101 @@ +import { Pressable, StyleSheet, View } from 'react-native'; +import { useTranslation } from 'react-i18next'; + +import { AppText } from '@/components/ui/app-text'; +import { StatusBadge } from '@/components/ui/badge'; +import { LabelChip } from '@/components/ui/label-chip'; +import type { Issue } from '@/core/api/types'; +import { formatRelativeTime } from '@/core/utils/format'; +import { useTheme } from '@/theme/theme-provider'; +import { HIT_TARGET, spacing } from '@/theme/tokens'; + +export interface IssueRowProps { + issue: Issue; + /** Show the `owner/repo` context (cross-repo lists). */ + showRepository?: boolean; + /** Overrides the computed state (e.g. merged PRs). */ + stateOverride?: 'open' | 'closed' | 'merged' | 'draft'; + onPress?: () => void; +} + +/** Issue / pull request row used in every list. */ +export function IssueRow({ issue, showRepository = false, stateOverride, onPress }: IssueRowProps) { + const { t } = useTranslation(); + const { colors } = useTheme(); + + const isPull = Boolean(issue.pull_request); + const state: 'open' | 'closed' | 'merged' | 'draft' = + stateOverride ?? + (issue.pull_request?.merged + ? 'merged' + : isPull && issue.pull_request?.draft && issue.state === 'open' + ? 'draft' + : issue.state === 'closed' + ? 'closed' + : 'open'); + + const stateLabel = { + open: t('issues.open'), + closed: t('issues.closed'), + merged: t('pulls.stateMerged'), + draft: t('pulls.draft'), + }[state]; + + const repoName = issue.repository?.full_name; + + return ( + [ + styles.row, + { borderBottomColor: colors.border }, + pressed && onPress && { backgroundColor: colors.surfacePressed }, + ]} + > + + + + {issue.title} + + + + + + {[ + showRepository && repoName ? repoName : null, + `#${issue.number}`, + issue.created_at ? formatRelativeTime(issue.created_at, t) : null, + issue.comments ? t('issues.comments', { count: issue.comments }) : null, + ] + .filter(Boolean) + .join(' · ')} + + + + {issue.labels && issue.labels.length > 0 ? ( + + {issue.labels.slice(0, 4).map((label, index) => ( + + ))} + + ) : null} + + ); +} + +const styles = StyleSheet.create({ + row: { + gap: spacing.xs, + minHeight: HIT_TARGET, + paddingVertical: spacing.md, + paddingHorizontal: spacing.lg, + borderBottomWidth: StyleSheet.hairlineWidth, + }, + topLine: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm }, + title: { flex: 1 }, + metaLine: { flexDirection: 'row', flexWrap: 'wrap' }, + labels: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.xs, marginTop: 2 }, +}); diff --git a/src/components/git/markdown.tsx b/src/components/git/markdown.tsx new file mode 100644 index 0000000..15f0c6b --- /dev/null +++ b/src/components/git/markdown.tsx @@ -0,0 +1,382 @@ +/** + * Native markdown renderer built on `marked`'s lexer. + * + * Renders headings, paragraphs, emphasis, links, inline code, code blocks, + * lists (incl. nesting + task items), blockquotes, tables, rules and images + * (as linked placeholders — remote SVG/badges aren't rendered as images). + * No WebView: everything is native Text/View so it inherits fonts, themes + * and accessibility scaling. + */ + +import { marked, type Token, type Tokens } from 'marked'; +import { Fragment, useMemo, type ReactNode } from 'react'; +import { Linking, ScrollView, StyleSheet, Text as TextBase, View } from 'react-native'; + +import { AppText } from '@/components/ui/app-text'; +import { useTheme } from '@/theme/theme-provider'; +import { fontFamily, fontSize, radius, spacing } from '@/theme/tokens'; + +export interface MarkdownProps { + content: string; + /** Instance base URL used to resolve root-relative links (""/undefined → link skipped). */ + baseUrl?: string; +} + +interface Ctx { + colors: ReturnType['colors']; + open: (url: string) => void; +} + +export function Markdown({ content, baseUrl = '' }: MarkdownProps) { + const { colors } = useTheme(); + + const tokens = useMemo(() => { + try { + return marked.lexer(content); + } catch { + return [] as Token[]; + } + }, [content]); + + const open = (url: string) => { + let target: string | null = null; + if (/^https?:\/\//i.test(url)) target = url; + else if (baseUrl && url.startsWith('/')) target = `${baseUrl}${url}`; + // Relative links (./ ../) are intentionally not resolved — too easy to + // guess wrong; users can open the instance in a browser instead. + if (target) void Linking.openURL(target).catch(() => undefined); + }; + + const ctx: Ctx = { colors, open }; + + return ( + + {tokens.map((token, index) => ( + {renderBlock(token, ctx, String(index))} + ))} + + ); +} + +// --------------------------------------------------------------------------- +// Inline +// --------------------------------------------------------------------------- + +function renderInline(tokens: Token[] | undefined, ctx: Ctx, key: string): ReactNode { + if (!tokens || tokens.length === 0) return null; + return ( + <> + {tokens.map((token, index) => ( + {renderInlineToken(token, ctx, `${key}-${index}`)} + ))} + + ); +} + +function renderInlineToken(token: Token, ctx: Ctx, key: string): ReactNode { + const { colors } = ctx; + switch (token.type) { + case 'text': { + const t = token as Tokens.Text; + if (t.tokens && t.tokens.length > 0) return renderInline(t.tokens, ctx, key); + return {t.text}; + } + case 'escape': + return {(token as Tokens.Escape).text}; + case 'em': + return ( + + {renderInline((token as Tokens.Em).tokens, ctx, key)} + + ); + case 'strong': + return ( + + {renderInline((token as Tokens.Strong).tokens, ctx, key)} + + ); + case 'del': + return ( + + {renderInline((token as Tokens.Del).tokens, ctx, key)} + + ); + case 'codespan': + return ( + + {(token as Tokens.Codespan).text} + + ); + case 'br': + return {'\n'}; + case 'link': { + const link = token as Tokens.Link; + const internal = /^https?:\/\//i.test(link.href) || link.href.startsWith('/'); + return ( + ctx.open(link.href) : undefined} + > + {renderInline(link.tokens, ctx, key)} + + ); + } + case 'image': { + const image = token as Tokens.Image; + const label = image.text ? `[${image.text}]` : ''; + const internal = /^https?:\/\//i.test(image.href) || image.href.startsWith('/'); + return ( + ctx.open(image.href) : undefined} + > + {label} + + ); + } + case 'html': + case 'xmlprocessing': + return null; + default: { + const anyToken = token as { text?: string; tokens?: Token[] }; + if (anyToken.tokens) return renderInline(anyToken.tokens, ctx, key); + if (anyToken.text) return {anyToken.text}; + return null; + } + } +} + +/** RN requires Text inside Text; this is that primitive. */ +function TextSpan({ + children, + style, + onPress, +}: { + children: ReactNode; + style?: object | object[]; + onPress?: () => void; +}) { + return ( + + {children} + + ); +} + +// --------------------------------------------------------------------------- +// Blocks +// --------------------------------------------------------------------------- + +function renderBlock(token: Token, ctx: Ctx, key: string): ReactNode { + const { colors } = ctx; + switch (token.type) { + case 'heading': { + const heading = token as Tokens.Heading; + const variant = + heading.depth === 1 + ? 'title' + : heading.depth === 2 + ? 'heading' + : heading.depth === 3 + ? 'subheading' + : 'bodyMedium'; + return ( + + {renderInline(heading.tokens, ctx, key)} + + ); + } + case 'paragraph': + case 'text': { + const paragraph = token as Tokens.Paragraph | Tokens.Text; + const inline = paragraph.tokens ?? []; + return ( + + {renderInline(inline, ctx, key)} + + ); + } + case 'code': { + const code = token as Tokens.Code; + return ( + + + + {code.text} + + + + ); + } + case 'hr': + return ; + case 'blockquote': { + const quote = token as Tokens.Blockquote; + return ( + + {quote.tokens.map((child, index) => ( + {renderBlock(child, ctx, `${key}-${index}`)} + ))} + + ); + } + case 'list': + return {renderList(token as Tokens.List, ctx, key)}; + case 'table': + return {renderTable(token as Tokens.Table, ctx, key)}; + case 'html': + return null; + default: + return null; + } +} + +function renderList(list: Tokens.List, ctx: Ctx, key: string): ReactNode { + return ( + + {list.items.map((raw, index) => { + const item = raw as Tokens.ListItem; + const marker = list.ordered + ? `${Number(list.start ?? 1) + index}.` + : item.task + ? item.checked + ? '☑' + : '☐' + : '•'; + const inlineTokens = item.tokens?.filter(isInlineToken) ?? []; + const blockTokens = item.tokens?.filter((t) => !isInlineToken(t)) ?? []; + + return ( + + + {marker} + + + {inlineTokens.length > 0 || blockTokens.length === 0 ? ( + + {renderInline( + inlineTokens.length > 0 + ? inlineTokens + : [{ type: 'text', text: item.text } as Token], + ctx, + `${key}-${index}`, + )} + + ) : null} + {blockTokens.map((child, childIndex) => ( + + {renderBlock(child, ctx, `${key}-${index}-${childIndex}`)} + + ))} + + + + ); + })} + + + ); +} + +const INLINE_TYPES = new Set([ + 'text', + 'escape', + 'em', + 'strong', + 'del', + 'codespan', + 'br', + 'link', + 'image', + 'html', + 'xmlprocessing', +]); + +function isInlineToken(token: Token): boolean { + return INLINE_TYPES.has(token.type); +} + +function renderTable(table: Tokens.Table, ctx: Ctx, key: string): ReactNode { + const { colors } = ctx; + return ( + + + + {table.header.map((cell, index) => ( + + {renderInline(cell.tokens, ctx, `${key}-h-${index}`)} + + ))} + + {table.rows.map((row, rowIndex) => ( + + {row.map((cell, cellIndex) => ( + + + {renderInline(cell.tokens, ctx, `${key}-${rowIndex}-${cellIndex}`)} + + + ))} + + ))} + + + ); +} + +const styles = StyleSheet.create({ + block: { gap: spacing.md }, + blockItem: { marginTop: 0 }, + italic: { fontStyle: 'italic' }, + strong: { fontWeight: '700' }, + strike: { textDecorationLine: 'line-through' }, + codespan: { + fontFamily: fontFamily.mono, + fontSize: fontSize.sm, + paddingHorizontal: 4, + borderRadius: 4, + }, + codeBlock: { + borderRadius: radius.md, + padding: spacing.md, + }, + codeText: { fontSize: fontSize.sm }, + hr: { height: StyleSheet.hairlineWidth, width: '100%' }, + quote: { + borderLeftWidth: 3, + borderRadius: radius.sm, + padding: spacing.md, + gap: spacing.sm, + }, + listRow: { flexDirection: 'row', gap: spacing.sm, paddingVertical: 2 }, + listMarker: { width: 22, textAlign: 'right' }, + listMarkerOrdered: { width: 28 }, + listContent: { flex: 1, gap: spacing.xs }, + tableScroll: { flexGrow: 0 }, + tableContent: { paddingRight: spacing.md }, + tableRow: { flexDirection: 'row' }, + tableCell: { minWidth: 90, maxWidth: 260, paddingVertical: spacing.sm, paddingHorizontal: spacing.sm }, +}); diff --git a/src/components/git/notification-row.test.ts b/src/components/git/notification-row.test.ts new file mode 100644 index 0000000..d0b16be --- /dev/null +++ b/src/components/git/notification-row.test.ts @@ -0,0 +1,48 @@ +/** Notification subject URL → navigation target parsing. */ + +import { parseSubjectUrl } from './notification-row'; + +describe('parseSubjectUrl', () => { + it('returns null for missing input', () => { + expect(parseSubjectUrl(undefined)).toBeNull(); + expect(parseSubjectUrl(null)).toBeNull(); + expect(parseSubjectUrl('')).toBeNull(); + }); + + it('parses API paths', () => { + expect(parseSubjectUrl('/api/v1/repos/octo/repo/issues/7')).toEqual({ + kind: 'issue', + owner: 'octo', + repo: 'repo', + index: 7, + }); + expect(parseSubjectUrl('/repos/octo/repo/pulls/3')).toEqual({ + kind: 'pull', + owner: 'octo', + repo: 'repo', + index: 3, + }); + }); + + it('parses absolute instance URLs', () => { + expect(parseSubjectUrl('https://codeberg.org/octo/repo/commits/abc123')).toEqual({ + kind: 'commit', + owner: 'octo', + repo: 'repo', + sha: 'abc123', + }); + }); + + it('falls back to a repository target', () => { + expect(parseSubjectUrl('/api/v1/repos/octo/repo')).toEqual({ + kind: 'repo', + owner: 'octo', + repo: 'repo', + }); + }); + + it('rejects non-repository URLs and non-numeric indexes', () => { + expect(parseSubjectUrl('/api/v1/user')).toBeNull(); + expect(parseSubjectUrl('/repos/octo/repo/issues/not-a-number')).toBeNull(); + }); +}); diff --git a/src/components/git/notification-row.tsx b/src/components/git/notification-row.tsx new file mode 100644 index 0000000..e72a499 --- /dev/null +++ b/src/components/git/notification-row.tsx @@ -0,0 +1,144 @@ +import { Pressable, StyleSheet, View } from 'react-native'; +import { useTranslation } from 'react-i18next'; + +import { AppText } from '@/components/ui/app-text'; +import { Icon, type IconName } from '@/components/ui/icon'; +import type { NotificationSubjectType, NotificationThread } from '@/core/api/types'; +import { formatRelativeTime } from '@/core/utils/format'; +import { useTheme } from '@/theme/theme-provider'; +import { HIT_TARGET, radius, spacing } from '@/theme/tokens'; + +export type NotificationTarget = + | { kind: 'issue'; owner: string; repo: string; index: number } + | { kind: 'pull'; owner: string; repo: string; index: number } + | { kind: 'commit'; owner: string; repo: string; sha: string } + | { kind: 'repo'; owner: string; repo: string }; + +/** + * Extracts a navigation target from a notification subject URL. + * Accepts both API paths (`/api/v1/repos/…`) and absolute instance URLs. + */ +export function parseSubjectUrl(url: string | undefined | null): NotificationTarget | null { + if (!url) return null; + let path = url; + try { + const parsed = new URL(url); + path = parsed.pathname; + } catch { + // Relative path — use as-is. + } + const match = path.match( + /^\/(?:api\/v1\/)?(?:repos\/)?([^/]+)\/([^/]+?)(?:\/(issues|pulls|commits?)\/([^/?#]+))?$/, + ); + if (!match) return null; + const [, owner, repo, section, tail] = match; + if (section === 'issues') { + const index = Number(tail); + return Number.isInteger(index) && index > 0 ? { kind: 'issue', owner, repo, index } : null; + } + if (section === 'pulls') { + const index = Number(tail); + return Number.isInteger(index) && index > 0 ? { kind: 'pull', owner, repo, index } : null; + } + if (section === 'commits' && tail) return { kind: 'commit', owner, repo, sha: tail }; + if (section === 'commit' && tail) return { kind: 'commit', owner, repo, sha: tail }; + return { kind: 'repo', owner, repo }; +} + +function iconForType(type: NotificationSubjectType | undefined): IconName { + switch (type) { + case 'Issue': + return 'issue'; + case 'Pull': + return 'pullRequest'; + case 'Commit': + return 'commit'; + default: + return 'repo'; + } +} + +export interface NotificationRowProps { + thread: NotificationThread; + onPress: () => void; +} + +/** Inbox row: unread indicator, subject, repository and relative time. */ +export function NotificationRow({ thread, onPress }: NotificationRowProps) { + const { t } = useTranslation(); + const { colors } = useTheme(); + + const unread = thread.unread === true; + const type = thread.subject?.type; + const typeLabel = { + Issue: t('inbox.typeIssue'), + Pull: t('inbox.typePull'), + Commit: t('inbox.typeCommit'), + Repository: t('inbox.typeRepository'), + }[type ?? 'Repository']; + + return ( + [ + styles.row, + { borderBottomColor: colors.border }, + pressed && { backgroundColor: colors.surfacePressed }, + ]} + > + + + + + + + {thread.subject?.title ?? thread.repository?.full_name ?? ''} + + + {[ + thread.repository?.full_name, + typeLabel, + thread.updated_at ? formatRelativeTime(thread.updated_at, t) : null, + ] + .filter(Boolean) + .join(' · ')} + + + {unread ? {t('inbox.unread')} : null} + + ); +} + +const styles = StyleSheet.create({ + row: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + minHeight: HIT_TARGET, + paddingVertical: spacing.md, + paddingHorizontal: spacing.lg, + borderBottomWidth: StyleSheet.hairlineWidth, + }, + unreadDot: { + width: 8, + height: 8, + borderRadius: radius.pill, + }, + iconBox: { + width: 32, + height: 32, + borderRadius: radius.md, + alignItems: 'center', + justifyContent: 'center', + }, + body: { flex: 1, gap: 2 }, +}); diff --git a/src/components/git/repo-list-item.tsx b/src/components/git/repo-list-item.tsx new file mode 100644 index 0000000..2a734ae --- /dev/null +++ b/src/components/git/repo-list-item.tsx @@ -0,0 +1,119 @@ +import { Pressable, StyleSheet, View } from 'react-native'; +import { useTranslation } from 'react-i18next'; + +import { AppText } from '@/components/ui/app-text'; +import { Badge } from '@/components/ui/badge'; +import { Icon } from '@/components/ui/icon'; +import { formatCount, formatRelativeTime } from '@/core/utils/format'; +import type { Repository } from '@/core/api/types'; +import { useTheme } from '@/theme/theme-provider'; +import { HIT_TARGET, radius, spacing } from '@/theme/tokens'; + +export interface RepoListItemProps { + repo: Repository; + onPress?: () => void; +} + +/** Repository row: owner/name, description, badges and a compact meta line. */ +export function RepoListItem({ repo, onPress }: RepoListItemProps) { + const { t } = useTranslation(); + const { colors } = useTheme(); + + const owner = repo.owner?.login ?? repo.full_name.split('/')[0] ?? ''; + const name = repo.name; + + return ( + [ + styles.row, + { borderBottomColor: colors.border }, + pressed && { backgroundColor: colors.surfacePressed }, + ]} + > + + + + + + + + {owner}/ + + + {name} + + + + {repo.description ? ( + + {repo.description} + + ) : null} + + + {repo.private ? {t('repositories.private')} : null} + {repo.fork ? {t('repositories.fork')} : null} + {repo.archived ? {t('repositories.archived')} : null} + {repo.template ? {t('repositories.template')} : null} + {repo.mirror ? {t('repositories.mirror')} : null} + + {repo.stars_count ? ( + + ) : null} + {repo.forks_count ? ( + + ) : null} + + + + + {onPress ? : null} + + ); +} + +function Meta({ icon, text }: { icon: 'starOutline' | 'fork' | 'clock'; text: string }) { + const { colors } = useTheme(); + return ( + + + + {text} + + + ); +} + +const styles = StyleSheet.create({ + row: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.md, + minHeight: HIT_TARGET, + paddingVertical: spacing.md, + paddingHorizontal: spacing.lg, + borderBottomWidth: StyleSheet.hairlineWidth, + }, + iconBox: { + width: 36, + height: 36, + borderRadius: radius.md, + alignItems: 'center', + justifyContent: 'center', + }, + body: { flex: 1, gap: spacing.xs }, + titleLine: { flexDirection: 'row', alignItems: 'baseline', flexWrap: 'wrap' }, + nameText: { flexShrink: 1 }, + metaLine: { + flexDirection: 'row', + alignItems: 'center', + flexWrap: 'wrap', + gap: spacing.md, + marginTop: 2, + }, + meta: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs }, +}); diff --git a/src/components/layout/header-buttons.tsx b/src/components/layout/header-buttons.tsx new file mode 100644 index 0000000..aaaf381 --- /dev/null +++ b/src/components/layout/header-buttons.tsx @@ -0,0 +1,75 @@ +/** + * Reusable header buttons. They navigate to root-level screens (Settings, + * Accounts modal) from anywhere by typing the navigation prop as the root + * stack — React Navigation bubbles the navigation when the screen doesn't + * exist in the current navigator. + */ + +import { useNavigation } from '@react-navigation/native'; +import type { NativeStackNavigationProp } from '@react-navigation/native-stack'; +import { useTranslation } from 'react-i18next'; + +import { IconButton } from '@/components/ui/icon-button'; +import { useSession } from '@/features/accounts/use-session'; +import { Avatar } from '@/components/ui/avatar'; +import { Pressable, View } from 'react-native'; +import { HIT_TARGET } from '@/theme/tokens'; +import type { RootStackParamList } from '@/navigation/types'; + +type RootNavigation = NativeStackNavigationProp; + +export function HeaderAccountButton() { + const navigation = useNavigation(); + const { account, token, instance } = useSession(); + const { t } = useTranslation(); + + return ( + navigation.navigate('Accounts', { screen: 'Accounts' })} + accessibilityRole="button" + accessibilityLabel={t('accounts.title')} + hitSlop={6} + style={({ pressed }) => [ + { + width: HIT_TARGET, + height: HIT_TARGET, + alignItems: 'center', + justifyContent: 'center', + borderRadius: 999, + }, + pressed && { opacity: 0.7 }, + ]} + > + + + ); +} + +export function HeaderSettingsButton() { + const navigation = useNavigation(); + const { t } = useTranslation(); + return ( + navigation.navigate('Settings', { screen: 'Settings' })} + testID="header-settings" + /> + ); +} + +export function HeaderAccountAndSettings() { + return ( + + + + + ); +} diff --git a/src/components/layout/query-list.tsx b/src/components/layout/query-list.tsx new file mode 100644 index 0000000..3b8e13a --- /dev/null +++ b/src/components/layout/query-list.tsx @@ -0,0 +1,150 @@ +import { FlashList } from '@shopify/flash-list'; +import type { ReactElement, ReactNode } from 'react'; +import { ActivityIndicator, StyleSheet, View } from 'react-native'; +import { useTranslation } from 'react-i18next'; +import type { InfiniteData, UseInfiniteQueryResult } from '@tanstack/react-query'; + +import type { RawResponse } from '@/core/api/client'; +import { apiErrorMessage } from '@/core/api/error-text'; +import { ErrorState, LoadingView } from '@/components/ui/state-views'; +import { Skeleton } from '@/components/ui/skeleton'; +import { useTheme } from '@/theme/theme-provider'; +import { spacing } from '@/theme/tokens'; + +type ListQuery = UseInfiniteQueryResult>, Error>; + +export interface QueryListProps { + query: ListQuery; + items: T[]; + keyExtractor: (item: T, index: number) => string; + renderItem: (item: T, index: number) => ReactElement | null; + /** Rendered when the query succeeded with zero items. */ + empty: ReactNode; + /** Rows of skeleton placeholders during the first load. */ + loadingRows?: number; + header?: ReactElement; + footer?: ReactElement; + /** Extra bottom padding for the last item (avoids a clipped feel at scroll end). */ + bottomInset?: number; +} + +/** + * One list behaviour for the whole app: + * first-load skeleton → error+retry → empty state → FlashList with pull-to-refresh + * and infinite scroll (`onEndReached` guarded by `hasNextPage`). + */ +export function QueryList({ + query, + items, + keyExtractor, + renderItem, + empty, + loadingRows = 6, + header, + footer, + bottomInset = spacing.xl, +}: QueryListProps) { + const { t } = useTranslation(); + const { colors } = useTheme(); + + const hasData = query.data !== undefined; + + if (!hasData && query.isPending) { + return ( + + {header} + + + ); + } + + if (!hasData && query.isError) { + return ( + + {header} + void query.refetch()} + /> + + ); + } + + return ( + renderItem(item, index)} + onEndReachedThreshold={0.4} + onEndReached={() => { + if (query.hasNextPage && !query.isFetchingNextPage) void query.fetchNextPage(); + }} + refreshing={query.isRefetching && !query.isFetchingNextPage} + onRefresh={() => void query.refetch()} + ListHeaderComponent={header} + ListEmptyComponent={query.isError ? ( + void query.refetch()} + /> + ) : ( + {empty} + )} + ListFooterComponent={ + <> + {query.isFetchingNextPage ? ( + + + + ) : null} + {footer} + + + } + contentContainerStyle={items.length === 0 ? styles.grow : undefined} + showsVerticalScrollIndicator + /> + ); +} + +function EmptyWrapper({ children }: { children: ReactNode }) { + return {children}; +} + +/** First-load placeholder rows (avatar/icon + two text lines). */ +export function ListSkeleton({ rows = 6 }: { rows?: number }) { + return ( + + {Array.from({ length: rows }, (_, index) => ( + + + + + + + + ))} + + ); +} + +export const queryListLoadingView = LoadingView; + +const styles = StyleSheet.create({ + flex: { flex: 1 }, + grow: { flexGrow: 1 }, + empty: { flexGrow: 1, paddingTop: spacing.xxl }, + footerSpinner: { paddingVertical: spacing.lg, alignItems: 'center' }, + skeletonRow: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.md, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.md, + }, + skeletonBody: { flex: 1, gap: spacing.sm }, +}); diff --git a/src/components/layout/screen.tsx b/src/components/layout/screen.tsx new file mode 100644 index 0000000..760cc28 --- /dev/null +++ b/src/components/layout/screen.tsx @@ -0,0 +1,67 @@ +import type { ReactNode } from 'react'; +import { + ScrollView, + StyleSheet, + View, + type ScrollViewProps, + type StyleProp, + type ViewStyle, +} from 'react-native'; + +import { useTheme } from '@/theme/theme-provider'; +import { spacing } from '@/theme/tokens'; + +export interface ScreenProps { + children: ReactNode; + /** Wrap in a ScrollView (default false — lists bring their own). */ + scroll?: boolean; + /** Apply horizontal screen padding (default true). */ + padded?: boolean; + /** Optional pull-to-refresh control forwarded to the ScrollView. */ + refreshControl?: ScrollViewProps['refreshControl']; + contentContainerStyle?: StyleProp; + style?: StyleProp; +} + +/** Base screen container: themed background, consistent padding, optional scroll. */ +export function Screen({ + children, + scroll = false, + padded = true, + refreshControl, + contentContainerStyle, + style, +}: ScreenProps) { + const { colors } = useTheme(); + const padding = padded ? spacing.lg : 0; + + if (scroll) { + return ( + + {children} + + ); + } + + return ( + {children} + ); +} + +/** Standard vertical gap between stacked screen sections. */ +export const SECTION_GAP = spacing.lg; + +const styles = StyleSheet.create({ + flex: { flex: 1 }, + scrollContent: { gap: spacing.lg }, +}); diff --git a/src/components/layout/section-header.tsx b/src/components/layout/section-header.tsx new file mode 100644 index 0000000..5e02dd6 --- /dev/null +++ b/src/components/layout/section-header.tsx @@ -0,0 +1,48 @@ +import { Pressable, StyleSheet, View } from 'react-native'; + +import { AppText } from '@/components/ui/app-text'; +import { Icon } from '@/components/ui/icon'; +import { useTheme } from '@/theme/theme-provider'; +import { spacing } from '@/theme/tokens'; + +export interface SectionHeaderProps { + title: string; + actionLabel?: string; + onAction?: () => void; +} + +/** Small section title with an optional "view all" action. */ +export function SectionHeader({ title, actionLabel, onAction }: SectionHeaderProps) { + const { colors } = useTheme(); + return ( + + + {title} + + {actionLabel && onAction ? ( + + + {actionLabel} + + + + ) : null} + + ); +} + +const styles = StyleSheet.create({ + row: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + gap: spacing.sm, + }, + title: { flexShrink: 1 }, + action: { flexDirection: 'row', alignItems: 'center', gap: 2 }, +}); diff --git a/src/components/ui/app-text.tsx b/src/components/ui/app-text.tsx new file mode 100644 index 0000000..d164aac --- /dev/null +++ b/src/components/ui/app-text.tsx @@ -0,0 +1,88 @@ +import { Text, type StyleProp, type TextProps, type TextStyle } from 'react-native'; + +import { useTheme } from '@/theme/theme-provider'; +import { fontFamily, fontSize, fontWeight } from '@/theme/tokens'; + +export type TextVariant = + | 'display' + | 'title' + | 'heading' + | 'subheading' + | 'body' + | 'bodyMedium' + | 'secondary' + | 'caption' + | 'label' + | 'mono' + | 'monoSmall'; + +export type TextTone = + | 'default' + | 'primary' + | 'secondary' + | 'tertiary' + | 'success' + | 'warning' + | 'error' + | 'info' + | 'merged' + | 'link' + | 'onPrimary'; + +interface AppTextProps extends TextProps { + variant?: TextVariant; + tone?: TextTone; + style?: StyleProp; + children: React.ReactNode; +} + +const VARIANT_STYLE: Record = { + display: { fontSize: fontSize.xxxl, fontWeight: fontWeight.bold, lineHeight: 36 }, + title: { fontSize: fontSize.xxl, fontWeight: fontWeight.bold, lineHeight: 30 }, + heading: { fontSize: fontSize.xl, fontWeight: fontWeight.semibold, lineHeight: 26 }, + subheading: { fontSize: fontSize.lg, fontWeight: fontWeight.semibold, lineHeight: 22 }, + body: { fontSize: fontSize.md, fontWeight: fontWeight.regular, lineHeight: 21 }, + bodyMedium: { fontSize: fontSize.md, fontWeight: fontWeight.medium, lineHeight: 21 }, + secondary: { fontSize: fontSize.md, fontWeight: fontWeight.regular, lineHeight: 21 }, + caption: { fontSize: fontSize.xs, fontWeight: fontWeight.regular, lineHeight: 16 }, + label: { fontSize: fontSize.sm, fontWeight: fontWeight.semibold, lineHeight: 18 }, + mono: { fontSize: fontSize.md, fontWeight: fontWeight.regular, lineHeight: 21, fontFamily: fontFamily.mono }, + monoSmall: { fontSize: fontSize.sm, fontWeight: fontWeight.regular, lineHeight: 18, fontFamily: fontFamily.mono }, +}; + +/** + * The app's single text primitive. Every visible string in the app should be + * rendered through this component (usually with a translated `t()` value) so + * colors, type scale and font scaling behave consistently. + */ +export function AppText({ variant = 'body', tone = 'default', style, children, ...rest }: AppTextProps) { + const { colors } = useTheme(); + + const toneColor = + tone === 'default' + ? variant === 'secondary' + ? colors.textSecondary + : colors.text + : { + primary: colors.primary, + secondary: colors.textSecondary, + tertiary: colors.textTertiary, + success: colors.success, + warning: colors.warning, + error: colors.error, + info: colors.info, + merged: colors.merged, + link: colors.link, + onPrimary: colors.onPrimary, + }[tone]; + + return ( + + {children} + + ); +} diff --git a/src/components/ui/avatar.tsx b/src/components/ui/avatar.tsx new file mode 100644 index 0000000..52275c4 --- /dev/null +++ b/src/components/ui/avatar.tsx @@ -0,0 +1,88 @@ +import { Image } from 'expo-image'; +import { StyleSheet, View } from 'react-native'; + +import { AppText } from '@/components/ui/app-text'; +import { useTheme } from '@/theme/theme-provider'; +import { radius } from '@/theme/tokens'; + +export interface AvatarProps { + /** Absolute avatar URL (from the API). */ + url?: string | null; + /** Display name / username — used for initials fallback and alt text. */ + name: string; + size?: number; + /** + * Auth token for the avatar's instance, when the instance requires auth + * for avatar requests. Never persisted — passed from the in-memory session. + */ + token?: string | null; + /** Host the URL belongs to; token is only sent to this host. */ + host?: string | null; +} + +function initials(name: string): string { + const parts = name.trim().split(/[\s._-]+/).filter(Boolean); + if (parts.length === 0) return '?'; + if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase(); + return (parts[0][0] + parts[1][0]).toUpperCase(); +} + +/** + * User/org avatar with initials fallback. When a token is supplied it is only + * attached to requests for the matching host (no cross-host token leakage). + */ +export function Avatar({ url, name, size = 40, token, host }: AvatarProps) { + const { colors } = useTheme(); + + let headers: Record | undefined; + if (token && host && url) { + try { + if (new URL(url).host === host) { + headers = { Authorization: `token ${token}` }; + } + } catch { + // Malformed URL → no headers, image simply fails to its own fallback. + } + } + + if (url) { + return ( + + ); + } + + return ( + + + {initials(name)} + + + ); +} + +const styles = StyleSheet.create({ + image: { overflow: 'hidden' }, + fallback: { alignItems: 'center', justifyContent: 'center' }, +}); diff --git a/src/components/ui/badge.tsx b/src/components/ui/badge.tsx new file mode 100644 index 0000000..ecfe70d --- /dev/null +++ b/src/components/ui/badge.tsx @@ -0,0 +1,113 @@ +import { StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native'; + +import { AppText } from '@/components/ui/app-text'; +import { Icon, type IconName } from '@/components/ui/icon'; +import { useTheme } from '@/theme/theme-provider'; +import { radius, spacing } from '@/theme/tokens'; + +export type BadgeTone = 'primary' | 'success' | 'warning' | 'error' | 'info' | 'neutral' | 'merged'; + +export interface BadgeProps { + children: string; + tone?: BadgeTone; + icon?: IconName; + style?: StyleProp; +} + +/** Small pill for statuses and counts. */ +export function Badge({ children, tone = 'neutral', icon, style }: BadgeProps) { + const { colors } = useTheme(); + + const bg = { + primary: colors.primaryMuted, + success: colors.successMuted, + warning: colors.warningMuted, + error: colors.errorMuted, + info: colors.infoMuted, + neutral: colors.neutralMuted, + merged: colors.mergedMuted, + }[tone]; + + const fg = { + primary: colors.primary, + success: colors.success, + warning: colors.warning, + error: colors.error, + info: colors.info, + neutral: colors.neutral, + merged: colors.merged, + }[tone]; + + return ( + + {icon ? : null} + + {children} + + + ); +} + +export interface StatusBadgeProps { + /** 'open' | 'closed' | 'merged' | 'draft' — already translated by the caller. */ + label: string; + state: 'open' | 'closed' | 'merged' | 'draft'; +} + +/** + * The canonical issue/PR state marker (GitHub-like semantics): + * open = green, closed = red, merged = purple, draft = neutral. + */ +export function StatusBadge({ label, state }: StatusBadgeProps) { + const { colors } = useTheme(); + const { tone, icon } = { + open: { tone: 'success' as const, icon: 'check' as const }, + closed: { tone: 'error' as const, icon: 'close' as const }, + merged: { tone: 'merged' as const, icon: 'pullRequest' as const }, + draft: { tone: 'neutral' as const, icon: 'edit' as const }, + }[state]; + + const bg = { + success: colors.successMuted, + error: colors.errorMuted, + merged: colors.mergedMuted, + neutral: colors.neutralMuted, + }[tone] as string; + + const fg = { + success: colors.success, + error: colors.error, + merged: colors.merged, + neutral: colors.neutral, + }[tone] as string; + + return ( + + + + {label} + + + ); +} + +const styles = StyleSheet.create({ + pill: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.xs, + paddingHorizontal: spacing.sm, + paddingVertical: 3, + borderRadius: radius.pill, + alignSelf: 'flex-start', + }, + status: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.xs, + paddingHorizontal: spacing.md, + paddingVertical: 4, + borderRadius: radius.pill, + alignSelf: 'flex-start', + }, +}); diff --git a/src/components/ui/button.test.tsx b/src/components/ui/button.test.tsx new file mode 100644 index 0000000..5d943db --- /dev/null +++ b/src/components/ui/button.test.tsx @@ -0,0 +1,40 @@ +/** Button: press handling, disabled and busy states (minimum touch target is CSS, not asserted). */ + +import { fireEvent, render, screen } from '@testing-library/react-native'; +import type { ReactElement } from 'react'; + +import { AppThemeProvider } from '@/theme/theme-provider'; + +import { Button } from './button'; + +async function renderWithTheme(ui: ReactElement) { + await render({ui}); +} + +describe('Button', () => { + it('renders its label and fires onPress', async () => { + const onPress = jest.fn(); + await renderWithTheme(