diff --git a/crates/forge-core/src/collab/parity.rs b/crates/forge-core/src/collab/parity.rs index 39295aafa..a6f8f2758 100644 --- a/crates/forge-core/src/collab/parity.rs +++ b/crates/forge-core/src/collab/parity.rs @@ -202,7 +202,7 @@ impl Collab<'_> { super::check_text("milestone description", description, 1000, 2000)?; if repo.visibility == crate::rules::v2::Visibility::Private { return Err(Error::Config( - "milestones in a private repository are sealed; this build does not seal them yet (use the web app)".into(), + "milestones in a private repository are sealed; no Forge client seals them yet (web or dg)".into(), )); } let p = milestone_props(title, description, due_on, closed); diff --git a/docs/guides/collaborating.md b/docs/guides/collaborating.md index 6b360bafe..c89d60e67 100644 --- a/docs/guides/collaborating.md +++ b/docs/guides/collaborating.md @@ -340,6 +340,21 @@ dg label delete / bug # deletes your definitions; r dg issue label / 12 --add bug ``` +On the web, **Issues → Labels** lists them and lets members create one, change its colour or description, and delete it (with the same retire-if-others-defined-it rule). A label keeps its name once defined: issues carry a label by its name, so a rename would leave them under the old one. + +### Milestones + +Members (maintainers and writers) define milestones and put issues in them: + +```sh +dg milestone create / v1.0 --description "First release" --due 2026-12-01 +dg milestone list / +dg milestone close / v1.0 # --reopen to reopen +dg issue milestone / 12 v1.0 +``` + +On the web, **Issues → Milestones** lists them open and closed, with due dates and progress, and lets members create, edit, close, reopen and delete them. Like a label, a milestone keeps its title once defined. A milestone definition can be deleted only by the member who wrote it, so one another member also defined can be closed but not deleted. Milestones in a private repository are sealed, which this release does not do yet (web or `dg`). + ### Stars ```sh @@ -356,7 +371,7 @@ On forge.dashhq.org, signed in with a limited key ([Identity and keys](identity- | You can | Not yet (coming soon) | |---|---| | Browse code, commits, branches, tags and PR diffs; download a branch as a zip | Web editing of files | -| File issues, comment, close and reopen; label them (members) | Merging a private repository's PRs, or committing to its branches (use `dg`) | +| File issues, comment, close and reopen; label them and put them in milestones, and manage the repo's labels and milestones (members) | Merging a private repository's PRs, or committing to its branches (use `dg`) | | Open a PR from a branch you have already pushed, in the repository or your fork | Merging when both sides changed the same files (use `dg pr merge`) | | Review a PR: approve, request changes or comment, with inline comments, suggestions and a pending review | | | Merge a PR (see below) | | diff --git a/forge-web/app/repo/labels/client.tsx b/forge-web/app/repo/labels/client.tsx new file mode 100644 index 000000000..68c4ae794 --- /dev/null +++ b/forge-web/app/repo/labels/client.tsx @@ -0,0 +1,14 @@ +'use client' + +import { RepoScaffold } from '@/components/repo/repo-scaffold' +import { LabelsContent } from '@/components/repo/labels-content' +import { useRepoAddress } from '@/hooks/use-query-param' + +export function LabelsClient(): JSX.Element { + const addr = useRepoAddress() + return ( + + {(home) => } + + ) +} diff --git a/forge-web/app/repo/labels/page.tsx b/forge-web/app/repo/labels/page.tsx new file mode 100644 index 000000000..820d1f358 --- /dev/null +++ b/forge-web/app/repo/labels/page.tsx @@ -0,0 +1,11 @@ +import { QueryPage } from '@/components/route-loading' +import { LabelsClient } from './client' + +/** `/repo/labels?owner=&name=` — the repo's labels: list, create, edit, delete (QW-019). */ +export default function LabelsPage(): JSX.Element { + return ( + + + + ) +} diff --git a/forge-web/app/repo/milestones/client.tsx b/forge-web/app/repo/milestones/client.tsx new file mode 100644 index 000000000..b34e2645e --- /dev/null +++ b/forge-web/app/repo/milestones/client.tsx @@ -0,0 +1,14 @@ +'use client' + +import { RepoScaffold } from '@/components/repo/repo-scaffold' +import { MilestonesContent } from '@/components/repo/milestones-content' +import { useRepoAddress } from '@/hooks/use-query-param' + +export function MilestonesClient(): JSX.Element { + const addr = useRepoAddress() + return ( + + {(home) => } + + ) +} diff --git a/forge-web/app/repo/milestones/page.tsx b/forge-web/app/repo/milestones/page.tsx new file mode 100644 index 000000000..d43555da8 --- /dev/null +++ b/forge-web/app/repo/milestones/page.tsx @@ -0,0 +1,11 @@ +import { QueryPage } from '@/components/route-loading' +import { MilestonesClient } from './client' + +/** `/repo/milestones?owner=&name=` — the repo's milestones: open / closed, progress, create, edit, close, delete (QW-019). */ +export default function MilestonesPage(): JSX.Element { + return ( + + + + ) +} diff --git a/forge-web/components/repo/issue-content.tsx b/forge-web/components/repo/issue-content.tsx index 0be2ace22..11d686d45 100644 --- a/forge-web/components/repo/issue-content.tsx +++ b/forge-web/components/repo/issue-content.tsx @@ -54,7 +54,7 @@ import { useSdk } from '@/hooks/use-sdk' import { useAsync } from '@/hooks/use-async' import { useIntent } from '@/hooks/use-intent' import { useFirstWrite } from '@/hooks/use-first-write' -import { useParam, type RepoAddress } from '@/hooks/use-query-param' +import { repoHref, useParam, type RepoAddress } from '@/hooks/use-query-param' import { useRepoLinks } from '@/components/repo/target-href' import { importedUrlOf } from '@/lib/view/ref-targets' import { CopyLinkButton } from '@/components/ui/copy-link' @@ -492,6 +492,7 @@ export function IssueContent({ home, addr, number }: { home: RepoHome; addr?: Re canDefine={!isPrivate} canEdit={isMember && !archived && guard.disabledReason === null} onChoose={(title) => setPending({ kind: 'milestone', title })} + {...(addr ? { manageHref: repoHref('/repo/milestones', addr) } : {})} /> {isMember || meta.pinned || meta.locked ? ( @@ -517,6 +518,7 @@ export function IssueContent({ home, addr, number }: { home: RepoHome; addr?: Re canEdit={isMember && !archived && guard.disabledReason === null} onToggle={(label, remove) => setPending({ kind: 'label', label, remove })} onDefine={(name, color, description) => setPending({ kind: 'defineLabel', name, color, description, apply: true })} + {...(addr ? { manageHref: repoHref('/repo/labels', addr) } : {})} /> {isPrivate ?

The labels on this issue are encrypted; the label definitions (names, colours, descriptions) are not.

: null} diff --git a/forge-web/components/repo/issues-content.tsx b/forge-web/components/repo/issues-content.tsx index 327acd684..527a7e85b 100644 --- a/forge-web/components/repo/issues-content.tsx +++ b/forge-web/components/repo/issues-content.tsx @@ -81,6 +81,7 @@ import { import { IssueTemplatePicker } from '@/components/repo/issue-templates' import { useRepoTotals } from '@/components/repo/use-repo-totals' import { useMilestones } from '@/components/repo/use-milestones' +import { TriageNav } from '@/components/repo/triage-nav' import { BodyCounter, SealedLimit, composeCost, privateComposeBlock } from '@/components/repo/private-compose' import type { RepoAddress } from '@/hooks/use-query-param' import { repoHref } from '@/hooks/use-query-param' @@ -143,6 +144,7 @@ export function IssuesContent({ home, addr }: { home: RepoHome; addr: RepoAddres
+ {canCompose ? ( + setColor(e.target.value.trim())} maxLength={7} className="w-28 font-mono" placeholder="#1d76db" /> + + +
+
+ {LABEL_COLORS.map((c) => ( +
+ {problem !== null && trimmed !== '' ?

{problem}

: null} +
+ + +
+ + ) +} + +export function LabelsContent({ home, addr }: { home: RepoHome; addr: RepoAddress }): JSX.Element { + const repo = home.repo + const { sdk, ready, network } = useSdk(repoContractIds(repo)) + const { signer } = useAuth() + const { role } = useViewerRole(repo) + const canEdit = role !== null && home.config?.archived !== true + const [creating, setCreating] = useState(false) + const [editing, setEditing] = useState(null) + const [restoring, setRestoring] = useState(null) + const [pending, setPending] = useState(null) + /** The label whose delete is being planned (its definitions read, to price it). */ + const [planning, setPlanning] = useState(null) + const [filter, setFilter] = useState('') + // After a write the page re-reads until the write shows (a node a block behind answers without it). + const expect = useRef<((l: LabelDef[]) => boolean) | null>(null) + const { data, loading, error, reload } = useAsync( + async () => { + const read = (): Promise => readLabels(sdk!, repo) + const first = await read() + const want = expect.current + if (want === null) return first + expect.current = null + return (await readUntil(read, [want], { first })) ?? first + }, + [ready, repoKey(repo), network], + { enabled: ready && sdk !== null }, + ) + const labels = useMemo(() => data ?? [], [data]) + const live = labels.filter((l) => !l.retired) + const retired = labels.filter((l) => l.retired) + const q = filter.trim().toLowerCase() + const shown = q === '' ? live : live.filter((l) => l.name.toLowerCase().includes(q) || l.description.toLowerCase().includes(q)) + const taken = useMemo(() => new Map(labels.map((l) => [l.name.toLowerCase(), l.retired])), [labels]) + const disabledReason = signer === null ? 'Sign in to change labels' : null + + // A delete is priced as it will run: a retirement (a charge) when another member also defined + // the name, then one refund per definition of the signer's. + const cost: Cost | null = + pending === null + ? null + : pending.kind === 'define' + ? previewCreate('label', { name: pending.name, color: pending.color, description: pending.description }) + : sumPreviews([ + ...(pending.retire !== false ? [previewCreate('label', { name: pending.name, retired: true })] : []), + ...Array.from({ length: pending.deletes }, () => previewDelete('label')), + ]) + + const askDelete = async (name: string): Promise => { + if (!sdk || !signer) return + setPlanning(name) + try { + const plan = planLabelDelete(await readLabelDocs(sdk, repo, name), signer.identityId) + setPending({ kind: 'delete', name, retire: plan.retire, deletes: plan.mine.length }) + } catch { + setPending({ kind: 'delete', name, retire: null, deletes: 1 }) + } finally { + setPlanning(null) + } + } + + const run = async (intent: string): Promise => { + if (!sdk || !signer || pending === null) throw new Error('sign in to continue') + const p = pending + if (p.kind === 'define') { + await defineLabel(sdk, signer, repo, { name: p.name, color: p.color, description: p.description, intent }) + expect.current = (l) => l.some((d) => d.name === p.name && !d.retired && d.color === p.color && d.description === p.description) + setCreating(false) + setEditing(null) + setRestoring(null) + } else { + await deleteLabel(sdk, signer, repo, p.name, intent) + expect.current = (l) => !l.some((d) => d.name === p.name && !d.retired) + } + // The lists' labels (and the issue pages') come from the repo feed: drop it. + invalidateRepoFeed(repo, { counts: false }) + reload() + } + + const confirm = + pending === null + ? { title: '', description: '', label: '' } + : pending.kind === 'delete' + ? { + title: `Delete label "${pending.name}"`, + description: `${ + pending.retire === true + ? 'Another member also defined it, so a retirement is written first (no one is offered it any more), then your definitions of it are deleted.' + : pending.retire === false + ? 'Deletes your definitions of it.' + : 'Deletes your definitions of it. If another member also defined it, a retirement is written first, so no one is offered it any more.' + } Issues and pull requests that carry it keep it in their history.`, + label: 'Sign & delete', + } + : { + title: pending.verb === 'create' ? `Create label "${pending.name}"` : pending.verb === 'restore' ? `Restore label "${pending.name}"` : `Edit label "${pending.name}"`, + description: 'One label definition for the whole repo (maintainers and writers). The newest definition of a name is the one shown.', + label: pending.verb === 'create' ? 'Sign & create' : pending.verb === 'restore' ? 'Sign & restore' : 'Sign & save', + } + + return ( +
+
+ + + setFilter(e.target.value)} placeholder="Search all labels" className="min-w-[10rem] flex-1" /> + {canEdit ? ( + + ) : null} +
+ + {creating ? ( + setCreating(false)} + onSubmit={(v) => setPending({ kind: 'define', verb: 'create', ...v })} + /> + ) : null} + +
+
+ {data === null ? 'Labels' : `${live.length} ${live.length === 1 ? 'label' : 'labels'}`} +
+ {loading && data === null ? ( + + ) : error ? ( +
+ ) : shown.length === 0 ? ( + + ) : ( +
    + {shown.map((l) => ( +
  • + {editing === l.name ? ( + setEditing(null)} + onSubmit={(v) => setPending({ kind: 'define', verb: 'edit', ...v })} + /> + ) : ( +
    +
    + +
    +

    {l.description || No description}

    + + + Issues + + + Pull requests + + {canEdit ? ( + <> + + + + ) : null} + +
    + )} +
  • + ))} +
+ )} +
+ + {retired.length > 0 ? ( +
+ {retired.length} retired {retired.length === 1 ? 'label' : 'labels'} +

A retired label is no longer offered; issues that carry it keep it.

+
    + {retired.map((l) => + restoring === l.name ? ( +
  • + setRestoring(null)} + onSubmit={(v) => setPending({ kind: 'define', verb: 'restore', ...v })} + /> +
  • + ) : ( +
  • + + {canEdit ? ( + + ) : null} +
  • + ), + )} +
+
+ ) : null} + + {home.repo.visibility === 'private' ? ( +

Label definitions (names, colours, descriptions) are not encrypted in a private repository; the labels on its issues are.

+ ) : null} + + setPending(null)} + title={confirm.title} + description={confirm.description} + cost={cost} + confirmLabel={confirm.label} + onConfirm={run} + /> +
+ ) +} diff --git a/forge-web/components/repo/labels-milestones.test.tsx b/forge-web/components/repo/labels-milestones.test.tsx new file mode 100644 index 000000000..eaad0d3da --- /dev/null +++ b/forge-web/components/repo/labels-milestones.test.tsx @@ -0,0 +1,189 @@ +// @vitest-environment jsdom +/** + * QW-019: the Labels and Milestones pages, as a maintainer and as a visitor. + */ + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import type { RepoHome } from '@/lib/view' +import type { LabelDef } from '@/lib/repo' +import type { Milestone } from '@/lib/rules/parity' + +const ME = 'MeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMe' +const OTHER = 'OtherOtherOtherOtherOtherOtherOtherOtherOthe' +let role: 'maintainer' | 'writer' | null = 'maintainer' + +vi.mock('next/navigation', () => ({ usePathname: () => '/repo/labels/', useSearchParams: () => new URLSearchParams(), useRouter: () => ({ replace: () => undefined, push: () => undefined }) })) +vi.mock('next/link', () => ({ default: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => {children} })) +vi.mock('@/hooks/use-sdk', () => ({ useSdk: () => ({ sdk: {}, ready: true, network: 'devnet', status: { phase: 'ready' } }) })) +vi.mock('@/contexts/auth-context', () => ({ useAuth: () => ({ signer: { identityId: ME }, identity: ME, balance: '100000000000', keyLimits: null }) })) +vi.mock('@/hooks/use-write-guard', () => ({ useWriteGuard: () => ({ check: () => true, failed: (e: unknown) => String(e), disabledReason: null }) })) +vi.mock('@/hooks/use-repo-chrome', () => ({ useViewerRole: () => ({ role, known: true, failed: false, retry: () => undefined }) })) + +const labels: LabelDef[] = [ + { name: 'bug', color: '#d73a4a', description: "Something isn't working", retired: false, createdAt: 1, id: 'l1' }, + { name: 'docs', color: '#0075ca', description: '', retired: false, createdAt: 2, id: 'l2' }, + { name: 'old', color: '', description: '', retired: true, createdAt: 3, id: 'l3' }, +] +vi.mock('@/lib/repo', async (orig) => ({ + ...(await orig()), + readLabels: async () => labels, + // `docs` was also defined by another member: deleting it writes a retirement first. + readLabelDocs: async (_sdk: unknown, _repo: unknown, name: string) => + name === 'docs' ? [{ id: 'l2', owner: OTHER, createdAt: 2 }] : [{ id: 'l1', owner: ME, createdAt: 1 }], + issueMilestoneItems: async () => [ + { open: true, milestone: 'v1.0' }, + { open: false, milestone: 'v1.0' }, + ], + pullMilestoneItems: async () => [{ open: false, milestone: 'v1.0' }], +})) +const milestones: Milestone[] = [ + { id: 'm1', title: 'v1.0', description: 'The first release', dueOn: Date.UTC(2020, 0, 1), closed: false, open: 0, closedItems: 0 }, + { id: 'm2', title: 'v2.0', description: '', dueOn: null, closed: false, open: 0, closedItems: 0 }, + { id: 'm3', title: 'v0.9', description: '', dueOn: null, closed: true, open: 0, closedItems: 0 }, +] +vi.mock('@/lib/repo/milestones', async (orig) => ({ + ...(await orig()), + readMilestoneDefs: async () => ({ + docs: milestones.map((m) => ({ id: m.id, title: m.title, description: m.description, dueOn: m.dueOn, closed: m.closed, createdAt: 1 })), + owners: new Map([ + ['v1.0', [{ id: 'm1', owner: ME }]], + ['v2.0', [{ id: 'm2', owner: OTHER }]], + ['v0.9', [{ id: 'm3', owner: ME }]], + ]), + }), +})) + +const { LabelsContent } = await import('./labels-content') +const { MilestonesContent } = await import('./milestones-content') + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +const HOME = { repo: { repoId: 'r', forge: { core: 'C', collab: 'L', community: 'M', group: 'G' }, ownerId: ME, name: 'n', visibility: 'public' }, description: '', config: null } as unknown as RepoHome +const addr = { owner: 'o', name: 'n' } + +let root: Root +let el: HTMLDivElement +beforeEach(() => { + role = 'maintainer' + el = document.createElement('div') + document.body.append(el) + root = createRoot(el) +}) +afterEach(() => { + act(() => root.unmount()) + el.remove() +}) +const settle = () => act(async () => { await new Promise((r) => setTimeout(r, 0)) }) +const button = (text: RegExp): HTMLButtonElement | undefined => [...document.querySelectorAll('button')].find((b) => text.test(b.textContent ?? '') || text.test(b.getAttribute('aria-label') ?? '')) +const type = (input: HTMLInputElement, value: string): void => { + const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set! + setter.call(input, value) + input.dispatchEvent(new Event('input', { bubbles: true })) +} + +describe('Labels page (QW-019)', () => { + it('lists the live labels with links to their issues, and the retired ones apart', async () => { + await act(async () => root.render()) + await settle() + const rows = [...el.querySelectorAll('[data-testid="label-row"]')] + expect(rows.map((r) => r.getAttribute('data-label'))).toEqual(['bug', 'docs']) + expect(rows[0]?.textContent).toContain("Something isn't working") + expect(rows[0]?.querySelector('a')?.getAttribute('href')).toBe('/repo/issues/?owner=o&name=n&label=bug&state=all') + expect(el.textContent).toContain('2 labels') + expect(el.querySelector('[data-testid="retired-labels"]')?.textContent).toContain('1 retired label') + }) + + it('lets a member create one (refusing a name in use), and edit one with its name fixed', async () => { + await act(async () => root.render()) + await settle() + act(() => button(/New label/)!.click()) + const form = el.querySelector('[data-testid="label-new-form"]')! + const name = form.querySelector('#new-label-name') as HTMLInputElement + act(() => type(name, 'bug')) + expect(form.textContent).toContain('A label with this name exists.') + expect((button(/Create label/) as HTMLButtonElement).disabled).toBe(true) + // A name differing only in case is the same label (as the issue page's picker has it). + act(() => type(name, 'Bug')) + expect(form.textContent).toContain('A label with this name exists.') + act(() => type(name, 'old')) + expect(form.textContent).toContain('A retired label has this name') + // The schema's byte bound, not only its character bound: 30 three-byte characters are 90 bytes. + act(() => type(name, '界'.repeat(30))) + expect((button(/Create label/) as HTMLButtonElement).disabled).toBe(true) + act(() => type(name, 'good first issue')) + expect((button(/Create label/) as HTMLButtonElement).disabled).toBe(false) + act(() => button(/Create label/)!.click()) + expect(document.body.textContent).toContain('Create label "good first issue"') + // Edit: the name is fixed (issues carry a label by its name). + act(() => button(/Cancel/)!.click()) + act(() => button(/Edit label bug/)!.click()) + expect((el.querySelector('#label-bug-name') as HTMLInputElement).disabled).toBe(true) + // Delete asks first, and says what it does: here a retirement, as another member defined it too. + await act(async () => button(/Delete label docs/)!.click()) + await settle() + expect(document.body.textContent).toContain('Delete label "docs"') + expect(document.body.textContent).toContain('a retirement is written first') + }) + + it('restores a retired label with a colour and description chosen afresh', async () => { + await act(async () => root.render()) + await settle() + act(() => button(/Restore/)!.click()) + const form = el.querySelector('[data-testid="label-restore-form"]')! + expect((form.querySelector('#label-old-name') as HTMLInputElement).disabled).toBe(true) + act(() => button(/Restore label/)!.click()) + expect(document.body.textContent).toContain('Restore label "old"') + }) + + it('shows a visitor no write controls', async () => { + role = null + await act(async () => root.render()) + await settle() + expect(button(/New label/)).toBeUndefined() + expect(button(/Edit label/)).toBeUndefined() + expect(button(/Delete label/)).toBeUndefined() + }) +}) + +describe('Milestones page (QW-019)', () => { + it('lists open milestones with due dates and progress, and the closed ones on their tab', async () => { + await act(async () => root.render()) + await settle() + const tabs = [...el.querySelectorAll('[role="tab"]')].map((t) => t.textContent?.trim()) + expect(tabs).toEqual(['2 Open', '1 Closed']) + const rows = [...el.querySelectorAll('[data-testid="milestone-row"]')] + expect(rows.map((r) => r.getAttribute('data-title'))).toEqual(['v1.0', 'v2.0']) + // Two of its three items (issues and PRs) are closed. + expect(rows[0]?.querySelector('[data-testid="milestone-progress"]')?.textContent).toContain('67% complete') + expect(rows[0]?.textContent).toMatch(/Past due by \d+ days/) + expect(rows[1]?.textContent).toContain('No due date') + expect(rows[0]?.querySelector('a')?.getAttribute('href')).toBe('/repo/issues/?owner=o&name=n&state=all&q=milestone%3Av1.0') + // The counts cover PRs too, so their list is linked beside the issues'. + expect([...(rows[0]?.querySelectorAll('a') ?? [])].map((a) => a.getAttribute('href'))).toContain('/repo/pulls/?owner=o&name=n&state=all&q=milestone%3Av1.0') + act(() => (el.querySelectorAll('[role="tab"]')[1] as HTMLButtonElement).click()) + expect([...el.querySelectorAll('[data-testid="milestone-row"]')].map((r) => r.getAttribute('data-title'))).toEqual(['v0.9']) + expect(button(/Reopen/)).toBeDefined() + }) + + it("does not offer to delete a milestone another member also defined; it offers to close it", async () => { + await act(async () => root.render()) + await settle() + expect(button(/Delete milestone v1.0/)?.disabled).toBe(false) + const other = button(/Delete milestone v2.0/)! + expect(other.disabled).toBe(true) + expect(other.title).toMatch(/Close it instead/) + act(() => button(/Delete milestone v1.0/)!.click()) + expect(document.body.textContent).toContain('Delete milestone "v1.0"') + }) + + it('refuses to create one in a private repository, and says why', async () => { + const priv = { ...HOME, repo: { ...HOME.repo, visibility: 'private' } } as unknown as RepoHome + await act(async () => root.render()) + await settle() + expect(button(/New milestone/)).toBeUndefined() + expect(el.querySelector('[data-testid="milestones-private-note"]')?.textContent).toMatch(/sealed/) + }) +}) diff --git a/forge-web/components/repo/milestones-content.tsx b/forge-web/components/repo/milestones-content.tsx new file mode 100644 index 000000000..ea9affd79 --- /dev/null +++ b/forge-web/components/repo/milestones-content.tsx @@ -0,0 +1,381 @@ +'use client' + +/** + * MilestonesContent — `/repo/milestones` (QW-019): the repo's milestones as GitHub lists them, + * Open / Closed, each with its due date, description and progress (its issues' and PRs' open + * and closed counts), and for maintainers and writers New milestone, Edit, Close / Reopen and + * Delete. + * + * Milestones are forge-community `milestone` definitions: member-gated, immutable, newest + * definition per title wins (`foldMilestonesV2`), and an issue joins one with a member event + * naming its title. So an edit or a close writes a new definition of the same title, and the + * title is fixed once defined (a rename would strand every issue in it under the old title). A + * delete removes the signer's definitions; when another member also defined the title it is + * refused (their older definition would come back), and closing it is offered instead. A + * private repository's milestones are sealed, which this build does not do yet (as `dg`). + */ + +import { useMemo, useRef, useState } from 'react' +import Link from 'next/link' +import { AlertTriangle, CalendarDays, CheckCircle2, Milestone as MilestoneIcon, Pencil, Plus, RotateCcw, Trash2 } from 'lucide-react' +import type { RepoHome } from '@/lib/view' +import { invalidateRepoFeed, issueMilestoneItems, pullMilestoneItems, repoContractIds, repoKey } from '@/lib/repo' +import { MILESTONE_LIMITS, checkMilestoneInput, dayOf, defineMilestone, deleteMilestone, dueOnOf, readMilestoneDefs, type MilestoneDocRef } from '@/lib/repo/milestones' +import { foldMilestonesV2, type Milestone } from '@/lib/rules/parity' +import { previewCreate, previewDelete, sumPreviews, type CostPreview as Cost } from '@/lib/sdk' +import { readUntil } from '@/lib/view/retry' +import { invalidateSessionCache } from '@/lib/view/session-cache' +import { useSdk } from '@/hooks/use-sdk' +import { useAsync } from '@/hooks/use-async' +import { useAuth } from '@/contexts/auth-context' +import { useViewerRole } from '@/hooks/use-repo-chrome' +import { repoHref, useParam, type RepoAddress } from '@/hooks/use-query-param' +import { Button } from '@/components/ui/button' +import { Field, Input, Textarea } from '@/components/ui/input' +import { ConfirmDialog } from '@/components/confirm-dialog' +import { EmptyState, ErrorState, LoadingBlock } from '@/components/ui/states' +import { StateTab } from '@/components/repo/list-controls' +import { TriageNav } from '@/components/repo/triage-nav' +import { inputProblem } from '@/lib/utils' + +/** What the page shows: the milestones, whether their progress is known, and who defined each title. */ +interface MilestonePage { + readonly milestones: readonly Milestone[] + /** + * `known`: the counts are shown. `too-large`: an index's feed was too large to read. `failed`: + * the issues or PRs could not be read (a retry may do). + */ + readonly progress: 'known' | 'too-large' | 'failed' + readonly owners: ReadonlyMap +} + +type Pending = + | { kind: 'define'; title: string; description: string; dueOn: number | null; closed: boolean; verb: 'create' | 'edit' | 'close' | 'reopen' } + | { kind: 'delete'; title: string } + | null + +const DAY_MS = 86_400_000 + +/** "Due by October 1, 2026", "Past due by 3 days", or "No due date". */ +function dueText(m: Milestone, now: number): { text: string; late: boolean } { + if (m.dueOn === null) return { text: 'No due date', late: false } + const day = new Date(m.dueOn).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' }) + // Late once the due day has ended (UTC). + const late = !m.closed && now >= m.dueOn + DAY_MS + if (!late) return { text: `Due by ${day}`, late: false } + const days = Math.max(1, Math.floor((now - m.dueOn) / DAY_MS)) + return { text: `Past due by ${days} ${days === 1 ? 'day' : 'days'} (${day})`, late: true } +} + +/** The milestone form: title (fixed when editing), due date, description. */ +function MilestoneForm({ + initial, + editing, + taken, + disabledReason, + onCancel, + onSubmit, +}: { + initial: { title: string; description: string; dueOn: number | null } + editing: boolean + taken: ReadonlySet + disabledReason: string | null + onCancel: () => void + onSubmit: (v: { title: string; description: string; dueOn: number | null }) => void +}): JSX.Element { + const [title, setTitle] = useState(initial.title) + const [due, setDue] = useState(initial.dueOn === null ? '' : dayOf(initial.dueOn)) + const [description, setDescription] = useState(initial.description) + const trimmed = title.trim() + const dueOn = due === '' ? null : dueOnOf(due) + // The schema's own bounds (characters and bytes) first, as `defineMilestone` checks them. + const problem = + inputProblem(() => checkMilestoneInput({ title: trimmed, description, dueOn })) ?? + (!editing && taken.has(trimmed) ? 'A milestone with this title exists.' : due !== '' && dueOn === null ? 'The due date is not a day.' : null) + const unchanged = editing && description === initial.description && dueOn === initial.dueOn + const id = editing ? 'edit-milestone' : 'new-milestone' + return ( +
{ + e.preventDefault() + if (problem === null && !unchanged) onSubmit({ title: trimmed, description, dueOn }) + }} + data-testid={editing ? 'milestone-edit-form' : 'milestone-new-form'} + > +
+ + setTitle(e.target.value)} + maxLength={MILESTONE_LIMITS.title} + disabled={editing} + title={editing ? 'Issues join a milestone by its title, so a defined milestone keeps its title' : undefined} + autoFocus={!editing} + placeholder="v1.0" + /> + + + setDue(e.target.value)} /> + +
+ +