From 667f3f01f64a05c162e7feab25d2aaec66ae0112 Mon Sep 17 00:00:00 2001 From: pasta Date: Wed, 30 Sep 2026 10:09:11 -0500 Subject: [PATCH 1/3] feat(web): Labels and Milestones pages to create, edit and delete them QW-019: there was no web UI to create or manage milestones or labels; the issue picker pointed at 'dg milestone create' and labels could only be created inline, with no recolor, description edit or delete. Issues and Pull requests now carry a Labels | Milestones switch, as on GitHub. /repo/labels lists the labels with links to their issues and PRs and lets members create one (name, description, colour with GitHub's palette and a preview), edit its colour and description, and delete it (the signer's definitions, retiring it first when another member also defined it, parity with dg label delete); retired labels can be restored. /repo/milestones lists open and closed milestones with due dates, descriptions and progress over their issues and PRs, and lets members create, edit, close, reopen and delete them (refused, with close offered, when another member also defined the title). Names and titles stay fixed once defined, since issues carry them by name. Private repositories' milestones stay refused, as in dg. The issue sidebar's pickers link to both pages. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/guides/collaborating.md | 17 +- forge-web/app/repo/labels/client.tsx | 14 + forge-web/app/repo/labels/page.tsx | 11 + forge-web/app/repo/milestones/client.tsx | 14 + forge-web/app/repo/milestones/page.tsx | 11 + forge-web/components/repo/issue-content.tsx | 4 +- forge-web/components/repo/issues-content.tsx | 2 + forge-web/components/repo/labels-content.tsx | 337 ++++++++++++++++ .../repo/labels-milestones.test.tsx | 171 ++++++++ .../components/repo/milestones-content.tsx | 367 ++++++++++++++++++ forge-web/components/repo/pull-content.tsx | 1 + forge-web/components/repo/pulls-content.tsx | 2 + forge-web/components/repo/repo-header.test.ts | 2 + forge-web/components/repo/repo-header.tsx | 3 +- forge-web/components/repo/target-rail.tsx | 23 +- forge-web/components/repo/triage-nav.tsx | 28 ++ forge-web/lib/page-title.ts | 2 + forge-web/lib/repo/index.ts | 3 + forge-web/lib/repo/issue-index.ts | 14 + .../lib/repo/label-milestone-writes.test.ts | 119 ++++++ forge-web/lib/repo/labels.ts | 44 ++- forge-web/lib/repo/milestones.ts | 109 +++++- forge-web/lib/repo/pull-index.ts | 11 + forge-web/lib/short-url.test.ts | 4 + forge-web/lib/short-url.ts | 10 +- 25 files changed, 1304 insertions(+), 19 deletions(-) create mode 100644 forge-web/app/repo/labels/client.tsx create mode 100644 forge-web/app/repo/labels/page.tsx create mode 100644 forge-web/app/repo/milestones/client.tsx create mode 100644 forge-web/app/repo/milestones/page.tsx create mode 100644 forge-web/components/repo/labels-content.tsx create mode 100644 forge-web/components/repo/labels-milestones.test.tsx create mode 100644 forge-web/components/repo/milestones-content.tsx create mode 100644 forge-web/components/repo/triage-nav.tsx create mode 100644 forge-web/lib/repo/label-milestone-writes.test.ts diff --git a/docs/guides/collaborating.md b/docs/guides/collaborating.md index 6b360bafe..cbf858e37 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 and PRs 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..a6d6fafa6 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, { new: '1' }) } : {})} /> {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 [pending, setPending] = 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 Set(labels.map((l) => l.name)), [labels]) + const disabledReason = signer === null ? 'Sign in to change labels' : null + + const cost: Cost | null = + pending === null ? null : pending.kind === 'define' ? previewCreate('label', { name: pending.name, color: pending.color, description: pending.description }) : previewDelete('label') + + 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) + } 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: + '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) => ( +
  • + + {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..0f8e5f68d --- /dev/null +++ b/forge-web/components/repo/labels-milestones.test.tsx @@ -0,0 +1,171 @@ +// @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, + 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) => { + const real = await orig() + const { foldMilestonesV2 } = await import('@/lib/rules/parity') + return { + ...real, + readMilestones: async (_sdk: unknown, _repo: unknown, items: { open: boolean; milestone: string | null }[]) => + foldMilestonesV2( + milestones.map((m) => ({ id: m.id, title: m.title, description: m.description, dueOn: m.dueOn, closed: m.closed, createdAt: 1 })), + items, + ), + readMilestoneOwners: async () => + 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) + 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. + act(() => button(/Delete label docs/)!.click()) + expect(document.body.textContent).toContain('Delete label "docs"') + }) + + 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') + 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..67141877b --- /dev/null +++ b/forge-web/components/repo/milestones-content.tsx @@ -0,0 +1,367 @@ +'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, dayOf, defineMilestone, deleteMilestone, dueOnOf, readMilestoneOwners, readMilestones } from '@/lib/repo/milestones' +import type { Milestone } from '@/lib/rules/parity' +import { previewCreate, previewDelete, 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' + +/** What the page shows: the milestones, whether their progress is known, and who defined each title. */ +interface MilestonePage { + readonly milestones: readonly Milestone[] + /** False when an index's feed was too large to read: the counts are not shown. */ + readonly progressKnown: boolean + 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) + const problem = + trimmed === '' + ? 'A milestone needs a title.' + : [...trimmed].length > MILESTONE_LIMITS.title + ? `A milestone title is at most ${MILESTONE_LIMITS.title} characters.` + : !editing && taken.has(trimmed) + ? 'A milestone with this title exists.' + : due !== '' && dueOn === null + ? 'The due date is not a day.' + : [...description].length > MILESTONE_LIMITS.description + ? `A description is at most ${MILESTONE_LIMITS.description} characters.` + : 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)} /> + +
+ +