diff --git a/bun.lock b/bun.lock index d765ccf9b68..23e6b6285ee 100644 --- a/bun.lock +++ b/bun.lock @@ -1349,6 +1349,7 @@ "@shepherdjerred/loaded": "workspace:*", "@shepherdjerred/ops-model": "workspace:*", "@shepherdjerred/test-postgres": "workspace:*", + "@tanstack/react-form": "catalog:", "@tanstack/react-query": "catalog:", "@tanstack/react-router": "catalog:", "@trpc/client": "catalog:", @@ -9060,6 +9061,8 @@ "@shepherdjerred/golink/@sentry/bun": ["@sentry/bun@11.18.0", "", { "dependencies": { "@sentry/bundler-plugins": "11.18.0", "@sentry/conventions": "^0.36.0", "@sentry/core": "11.18.0", "@sentry/node": "11.18.0", "@sentry/server-runtime-injection": "11.18.0", "@sentry/server-utils": "11.18.0" } }, "sha512-ESEkTStPghccjZKruy/sqzOdQeDjOMJsqEehyxyoElNK5oxpBfxqfBR6cTvQOFnTZ39pTvknDFBkZHj0Unx5rw=="], + "@shepherdjerred/golink/@tanstack/react-form": ["@tanstack/react-form@1.33.6", "", { "dependencies": { "@tanstack/form-core": "1.33.6", "@tanstack/react-store": "^0.11.0" }, "peerDependencies": { "@tanstack/react-start": "*", "react": "^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@tanstack/react-start"] }, "sha512-4JRcQZ0uQrsvkVEd2uZ/d6xIb711Jj/+MQjBLCFpK29xvSIRzz1h6YrA+BsQ+ZjQZNYoOugp1idLmoWpelUSgQ=="], + "@shepherdjerred/incidents/react-router": ["react-router@8.4.0", "", { "dependencies": { "@remix-run/route-pattern": "^0.22.1", "cookie-es": "^3.1.1" }, "peerDependencies": { "react": ">=19.2.7", "react-dom": ">=19.2.7" }, "optionalPeers": ["react-dom"] }, "sha512-JtydAkBvU9UTEe5qNC+POhu+ZBNM7rlKY2IegwXc7Idj7xfRG16x5RZrw3mju+XlqBxfvb2ky9P3jUp9WyWC1g=="], "@shepherdjerred/llm-runtime/ai": ["ai@7.0.183", "", { "dependencies": { "@ai-sdk/gateway": "4.0.156", "@ai-sdk/provider": "4.0.39", "@ai-sdk/provider-utils": "5.0.85" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-rrPZNiuOKr8L6j9acxrWpE/lKWgR+rYNHDYr9bOvfMLM8RlsX75WMJsMw4LBPZkX6tdjFL8fiLXhTKN29wkkYQ=="], @@ -10128,6 +10131,8 @@ "@shepherdjerred/golink/@sentry/bun/@sentry/server-utils": ["@sentry/server-utils@11.18.0", "", { "dependencies": { "@opentelemetry/api": "^1.9.1", "@sentry/conventions": "^0.36.0", "@sentry/core": "11.18.0" } }, "sha512-1ny+6qT8Hyt9EWplbAcf28wiFS82jiLCGwy8PQeq2IHm8lxsGbRkohAcp3hfRHZUsyiSGOVBcN3ofORLZvxSyg=="], + "@shepherdjerred/golink/@tanstack/react-form/@tanstack/form-core": ["@tanstack/form-core@1.33.6", "", { "dependencies": { "@tanstack/devtools-event-client": "^0.5.1", "@tanstack/pacer-lite": "^0.1.1", "@tanstack/store": "^0.11.0" } }, "sha512-kyJN+qYVIxv4dXatQzKkay++NwEDkwS2hmZe80lRGxs4i+AbWKAucbKPndYgwSczbEoZms2VRqNeR+WnM4jucg=="], + "@shepherdjerred/llm-runtime/ai/@ai-sdk/gateway": ["@ai-sdk/gateway@4.0.156", "", { "dependencies": { "@ai-sdk/provider": "4.0.39", "@ai-sdk/provider-utils": "5.0.85", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-Nv1ILpLYNDlIV/beyo6Uc6jZcwTDzLMiSqer4PUEmIHqyOceLHf58lv1bfntAJ0xZxaBa9BtYDOv3/Msu0mQrQ=="], "@shepherdjerred/monarch/ai/@ai-sdk/gateway": ["@ai-sdk/gateway@4.0.156", "", { "dependencies": { "@ai-sdk/provider": "4.0.39", "@ai-sdk/provider-utils": "5.0.85", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-Nv1ILpLYNDlIV/beyo6Uc6jZcwTDzLMiSqer4PUEmIHqyOceLHf58lv1bfntAJ0xZxaBa9BtYDOv3/Msu0mQrQ=="], @@ -10750,6 +10755,8 @@ "@shepherdjerred/golink/@sentry/bun/@sentry/node/@sentry/opentelemetry": ["@sentry/opentelemetry@11.18.0", "", { "dependencies": { "@sentry/conventions": "^0.36.0", "@sentry/core": "11.18.0" }, "peerDependencies": { "@opentelemetry/api": "^1.9.0" } }, "sha512-f5cyOW/cayhmFBWgVaJIeVJ+VLi0tB0rxaNjMBb8eEKAKMBoqCngfEIOeMVeurrTRlGZ0A/525YEnBbfdTCmmg=="], + "@shepherdjerred/golink/@tanstack/react-form/@tanstack/form-core/@tanstack/devtools-event-client": ["@tanstack/devtools-event-client@0.5.1", "", {}, "sha512-MiBx6Ybr65MFatCnk8IJzhGxd4hvsvEap4aT0gXOC274rV4hm0UPNHxznB5KGYtu84aXrIAsJEBElqzdPe+eeg=="], + "@shepherdjerred/tracker/@sentry/bun/@sentry/bundler-plugins/dotenv": ["dotenv@17.4.2", "", {}, "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw=="], "@shepherdjerred/tracker/@sentry/bun/@sentry/bundler-plugins/oxc-parser": ["oxc-parser@0.152.0", "", { "dependencies": { "@oxc-project/types": "^0.152.0" }, "optionalDependencies": { "@oxc-parser/binding-android-arm-eabi": "0.152.0", "@oxc-parser/binding-android-arm64": "0.152.0", "@oxc-parser/binding-darwin-arm64": "0.152.0", "@oxc-parser/binding-darwin-x64": "0.152.0", "@oxc-parser/binding-freebsd-x64": "0.152.0", "@oxc-parser/binding-linux-arm-gnueabihf": "0.152.0", "@oxc-parser/binding-linux-arm-musleabihf": "0.152.0", "@oxc-parser/binding-linux-arm64-gnu": "0.152.0", "@oxc-parser/binding-linux-arm64-musl": "0.152.0", "@oxc-parser/binding-linux-ppc64-gnu": "0.152.0", "@oxc-parser/binding-linux-riscv64-gnu": "0.152.0", "@oxc-parser/binding-linux-riscv64-musl": "0.152.0", "@oxc-parser/binding-linux-s390x-gnu": "0.152.0", "@oxc-parser/binding-linux-x64-gnu": "0.152.0", "@oxc-parser/binding-linux-x64-musl": "0.152.0", "@oxc-parser/binding-openharmony-arm64": "0.152.0", "@oxc-parser/binding-win32-arm64-msvc": "0.152.0", "@oxc-parser/binding-win32-ia32-msvc": "0.152.0", "@oxc-parser/binding-win32-x64-msvc": "0.152.0" } }, "sha512-ZztsZgaCWmPeKYMdoTT5e0oV/oxD1NeLWNR3kAtr/G707cUPYaaozRlVDHLCGnszHJRszN9mJwmPNpqgwloC0A=="], diff --git a/packages/golink/eslint-suppressions.json b/packages/golink/eslint-suppressions.json index b72e289d0a6..0967ef424bc 100644 --- a/packages/golink/eslint-suppressions.json +++ b/packages/golink/eslint-suppressions.json @@ -1,32 +1 @@ -{ - "src/client/app.tsx": { - "@typescript-eslint/no-deprecated": { - "count": 5 - } - }, - "src/client/directory-sections.tsx": { - "@typescript-eslint/no-deprecated": { - "count": 1 - } - }, - "src/client/link-dialogs.tsx": { - "@typescript-eslint/no-deprecated": { - "count": 6 - } - }, - "src/client/links-card.tsx": { - "@typescript-eslint/no-deprecated": { - "count": 4 - } - }, - "src/client/links-table.tsx": { - "@typescript-eslint/no-deprecated": { - "count": 4 - } - }, - "src/client/shell.tsx": { - "@typescript-eslint/no-deprecated": { - "count": 1 - } - } -} +{} diff --git a/packages/golink/index.html b/packages/golink/index.html index 955983c20d8..74ee0c408fd 100644 --- a/packages/golink/index.html +++ b/packages/golink/index.html @@ -6,8 +6,18 @@ name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" /> - - Go links + + + + Links · Go links { void navigate({ to: "/", search: {}, replace: true }); }, [navigate]); - const [formMode, setFormMode] = useState({ kind: "create" }); - const [shortValue, setShortValue] = useState(""); - const [targetValue, setTargetValue] = useState(""); - const [shortErrorText, setShortErrorText] = useState(INITIAL_SHORT_ERROR); - const [targetErrorText, setTargetErrorText] = useState(INITIAL_TARGET_ERROR); - const [isSubmitting, setIsSubmitting] = useState(false); - const [mutationError, setMutationError] = useState(null); + + const [formRequest, setFormRequest] = useState(null); const [statusMessage, setStatusMessage] = useState(null); const [actionError, setActionError] = useState(null); - const [query, setQuery] = useState(""); const [kindFilter, setKindFilter] = useState("all"); - const [copiedShort, setCopiedShort] = useState(null); const [pendingDelete, setPendingDelete] = useState(null); const [deletingShort, setDeletingShort] = useState(null); - - const formElementRef = useRef(null); - const shortInputRef = useRef(null); - const targetInputRef = useRef(null); - const formDialogRef = useRef(null); - const deleteDialogRef = useRef(null); const searchInputRef = useRef(null); - const copyResetTimerRef = useRef< - ReturnType | undefined - >(undefined); - - const shellRef = useCallback((node: HTMLDivElement | null) => { - if (node === null) { - return; - } - // On the document, so `/` works while focus is on the page body too. - const onKeyDown = (event: KeyboardEvent): void => { - if (!isSearchShortcut(event)) { - return; - } - event.preventDefault(); - searchInputRef.current?.focus(); - searchInputRef.current?.select(); - }; - document.addEventListener("keydown", onKeyDown); - - return () => { - document.removeEventListener("keydown", onKeyDown); - if (copyResetTimerRef.current !== undefined) { - globalThis.clearTimeout(copyResetTimerRef.current); - } - }; - }, []); - - const formRef = useCallback((node: HTMLFormElement | null) => { - formElementRef.current = node; - if (node === null) { - return; - } - return bindFormValidation(node); - }, []); + useSearchShortcut(searchInputRef); const writesEnabled = directory?.writesEnabled === true; const links = useMemo(() => directory?.links ?? [], [directory]); @@ -139,36 +85,18 @@ export function App({ ); }, [kindFilter, links, query]); - const openDialog = (mode: FormMode, short: string, target: string): void => { - setFormMode(mode); - setShortValue(short); - setTargetValue(target); - setShortErrorText(INITIAL_SHORT_ERROR); - setTargetErrorText(INITIAL_TARGET_ERROR); - setMutationError(null); + const openForm = (mode: FormMode, short: string, target: string): void => { setStatusMessage(null); setActionError(null); - if (formElementRef.current !== null) { - resetFormValidationState(formElementRef.current); - } - showModalFromFocus(formDialogRef.current); - // The values above land on the next render; select once they have. - globalThis.setTimeout(() => { - const field = - short === "" && mode.kind === "create" - ? shortInputRef.current - : targetInputRef.current; - field?.focus(); - field?.select(); - }, 0); + setFormRequest({ mode, short, target }); }; const handleNewLink = (prefill = ""): void => { - openDialog({ kind: "create" }, prefill, ""); + openForm({ kind: "create" }, prefill, ""); }; const handleEditLink = (item: LinkItem): void => { - openDialog({ kind: "edit", short: item.short }, item.short, item.targetUrl); + openForm({ kind: "edit", short: item.short }, item.short, item.targetUrl); }; const handleOverrideLink = (item: LinkItem): void => { @@ -176,7 +104,7 @@ export function App({ handleEditLink(item); return; } - openDialog( + openForm( { kind: "override", short: item.short, @@ -188,45 +116,12 @@ export function App({ ); }; - const focusSearch = (): void => { - searchInputRef.current?.focus(); - searchInputRef.current?.select(); - }; - - const submitUpsertForm = async (): Promise => { - const form = formElementRef.current; - if (form === null || isSubmitting || !writesEnabled) { - return; - } - if (shortInputRef.current !== null) { - setShortErrorText(syncShortInputValidity(shortInputRef.current)); - } - if (targetInputRef.current !== null) { - setTargetErrorText(syncTargetInputValidity(targetInputRef.current)); - } - if (!form.checkValidity()) { - focusFirstInvalidField(form); - return; - } - - setIsSubmitting(true); - setMutationError(null); - setStatusMessage(null); - - try { - const saved = await saveLink.mutateAsync({ - short: normalizeShortSlug(shortValue), - targetUrl: targetValue.trim(), - }); - clearMissingSlug(); - formDialogRef.current?.close(); - setStatusMessage(`Saved go/${saved.short} → ${saved.targetUrl}`); - await reloadDirectory(); - } catch (error) { - setMutationError(errorMessage(error, "Unable to save shortlink.")); - } finally { - setIsSubmitting(false); - } + const save = async (short: string, targetUrl: string): Promise => { + const saved = await saveLink.mutateAsync({ short, targetUrl }); + clearMissingSlug(); + setFormRequest(null); + setStatusMessage(`Saved go/${saved.short} → ${saved.targetUrl}`); + await reloadDirectory(); }; const confirmDelete = async (): Promise => { @@ -245,154 +140,113 @@ export function App({ setActionError(errorMessage(error, `Unable to delete go/${item.short}.`)); } finally { setDeletingShort(null); - deleteDialogRef.current?.close(); - } - }; - - const handleCopyLink = async (short: string): Promise => { - const shareUrl = new URL( - `/${encodeURIComponent(short)}`, - globalThis.location.origin, - ).href; - try { - await globalThis.navigator.clipboard.writeText(shareUrl); - setCopiedShort(short); - if (copyResetTimerRef.current !== undefined) { - globalThis.clearTimeout(copyResetTimerRef.current); - } - copyResetTimerRef.current = globalThis.setTimeout(() => { - setCopiedShort(null); - }, 1800); - } catch { - setStatusMessage(`Shortlink URL: ${shareUrl}`); + setPendingDelete(null); } }; return ( -
- - - } - > - - +
+ + { + setQuery(event.target.value); + }} + /> + {writesEnabled ? ( ) : directory === null ? null : ( - Read-only - ) - } - /> - - {activeMissingSlug !== null && ( - { - handleNewLink(activeMissingSlug); - }} - onDismiss={clearMissingSlug} - /> - )} - - {actionError !== null && ( -

- {actionError} -

- )} -

- {statusMessage ?? ""} -

+ Read-only + )} +
+ } + /> - - - ({ - items: filteredLinks, - totalCount: all.length, - }))} + {activeMissingSlug !== null && ( + { - void directoryQuery.refetch(); - }} - onCopy={(short) => { - void handleCopyLink(short); - }} - onEdit={handleEditLink} - onOverride={handleOverrideLink} - onDelete={(item) => { - setPendingDelete(item); - showModalFromFocus(deleteDialogRef.current); + onCreate={() => { + handleNewLink(activeMissingSlug); }} + onDismiss={clearMissingSlug} /> + )} + + {actionError !== null && ( + + {actionError} + + )} + {statusMessage !== null && ( + + {statusMessage} + + )} +

+ {statusMessage ?? ""} +

+ + - - - + ({ + items: filteredLinks, + totalCount: all.length, + }))} + writesEnabled={writesEnabled} + deletingShort={deletingShort} + onRetry={() => { + void directoryQuery.refetch(); + }} + onEdit={handleEditLink} + onOverride={handleOverrideLink} + onDelete={setPendingDelete} + /> + + + { - void submitUpsertForm(); + onSave={save} + onClose={() => { + setFormRequest(null); }} /> { @@ -402,6 +256,6 @@ export function App({ setPendingDelete(null); }} /> - + ); } diff --git a/packages/golink/src/client/client.test.tsx b/packages/golink/src/client/client.test.tsx index f2d23701c30..bd368bb007e 100644 --- a/packages/golink/src/client/client.test.tsx +++ b/packages/golink/src/client/client.test.tsx @@ -3,10 +3,10 @@ import { describe, expect, test } from "vitest"; import { createThemeStore } from "@shepherdjerred/console-ui"; import type { LinkItem } from "#shared/contract.ts"; import { DeleteConfirmDialog } from "./link-dialogs.tsx"; -import { LinksCard, summaryItems } from "./links-card.tsx"; +import { LinksSection, summaryFigures } from "./links-card.tsx"; import { Loaded } from "@shepherdjerred/loaded"; import { LinksTable } from "./links-table.tsx"; -import { GolinkSidebar } from "./shell.tsx"; +import { GolinkShell } from "./shell.tsx"; const noop = (): void => undefined; @@ -50,9 +50,7 @@ function renderTable( items={items} totalCount={totalCount} writesEnabled={writesEnabled} - copiedShort={null} deletingShort={null} - onCopy={noop} onEdit={noop} onOverride={noop} onDelete={noop} @@ -66,9 +64,9 @@ describe("LinksTable", () => { const body = html.slice(html.indexOf("")); expect(body.match(//gu)).toHaveLength(LINKS.length); expect(body).toContain("go/docs"); - expect(body).toContain(">Manual<"); - expect(body).toContain(">Tailnet Ingress<"); - expect(body).toContain(">Platform Site<"); + expect(body).toContain("Manual"); + expect(body).toContain("Tailnet Ingress"); + expect(body).toContain("Platform Site"); }); test("names the shadowed destination and truncates with a title", () => { @@ -98,32 +96,32 @@ describe("LinksTable", () => { }); test("renders an empty state for a filter and for an empty directory", () => { - expect(renderTable(true, [], LINKS.length)).toBe( - '

No shortlinks match the current filter.

', - ); + const filtered = renderTable(true, [], LINKS.length); + expect(filtered).toContain('data-kind="empty"'); + expect(filtered).toContain("No shortlinks match the current filter."); expect(renderTable(true, [], 0)).toContain("No shortlinks yet."); }); - test("is a Hub data table whose cells carry their phone-card labels", () => { + test("is a plain ui-table whose cells carry their phone labels", () => { const html = renderTable(true); expect(html).toMatch( - /^
/u, + /^
/u, ); - for (const label of ["Shortlink", "Destination", "Source", "Clicks"]) { + for (const label of ["Destination", "Source", "Clicks", "Last clicked"]) { expect(html).toContain(`data-label="${label}"`); } }); - test("shows the source as a tag titled with its detail", () => { + test("shows the source as a chip titled with its detail", () => { expect(renderTable(true)).toMatch( - /]*>(?:(?!<\/span>)[\s\S])*Tailnet Ingress<\/span>/u, + /]*>(?:(?!<\/span>)[\s\S])*Tailnet Ingress<\/span>/u, ); }); }); const COUNTS = { all: 67, manual: 4, ingress: 36, site: 25, alias: 2 }; -describe("GolinkSidebar", () => { +describe("GolinkShell", () => { const theme = createThemeStore("golink-theme", { storage: () => ({ getItem: () => null, setItem: noop, removeItem: noop }), darkQuery: { matches: false, addEventListener: noop }, @@ -131,29 +129,38 @@ describe("GolinkSidebar", () => { onStorage: noop, }); const html = renderToStaticMarkup( - , + > +
+ , ); - test("links to the page's sections with their counts", () => { - expect(html).toContain( - '', - ); - expect(html).toMatch( - /Links<\/span>67<\/span>/u, - ); + test("lists every source with its count; only the selected one is current", () => { + for (const [label, count] of [ + ["All", "67"], + ["Manual", "4"], + ["Tailnet", "36"], + ["Public sites", "25"], + ["Auto-aliases", "2"], + ] as const) { + expect(html).toContain( + `${label}${count}`, + ); + } expect(html).toMatch( - /Shortcuts<\/span>7<\/span>/u, + /aria-current="page"[^>]*>(?:(?!<\/a>)[\s\S])*Tailnet { + test("links to the shortcut reference with its count", () => { expect(html).toMatch( - /aria-keyshortcuts="\/"[^>]*aria-label="Search links"|aria-label="Search links"[^>]*aria-keyshortcuts="\/"/u, + /Shortcuts<\/span>7<\/span>/u, ); }); @@ -163,73 +170,34 @@ describe("GolinkSidebar", () => { }); }); -describe("LinksCard", () => { - const html = renderToStaticMarkup( - , - ); - - test("is a named card with a search field and a source filter", () => { - expect(html).toMatch( - /^
- - - - - +
+
+
PatternDescriptionExample
+ + + + + + + + + {shortcuts.map((spec) => ( + + + + - - - {shortcuts.map((spec) => ( - - - - - - ))} - -
PatternDescriptionExample
go/{spec.pattern}{spec.description} + go/{spec.exampleShort} + → {spec.exampleTargetUrl} +
- go/{spec.pattern} - {spec.description} - - - go/{spec.exampleShort} - - - {" "} - → {spec.exampleTargetUrl} - - -
-
- - + ))} + + + + ); } diff --git a/packages/golink/src/client/link-dialogs.tsx b/packages/golink/src/client/link-dialogs.tsx index 77b6047ebe9..ed483695418 100644 --- a/packages/golink/src/client/link-dialogs.tsx +++ b/packages/golink/src/client/link-dialogs.tsx @@ -1,15 +1,22 @@ -import type { ReactNode, RefCallback, RefObject } from "react"; -import { Button } from "@shepherdjerred/console-ui"; +import { useState } from "react"; +import { useForm } from "@tanstack/react-form"; import { - SHORT_SLUG_PATTERN, + Banner, + Button, + Dialog, + DialogClose, + Field, + fieldErrorMessage, + InputAddon, +} from "@shepherdjerred/console-ui"; +import { + normalizeShortSlug, + UpsertManualLinkInputSchema, type DynamicLinkKind, type LinkItem, } from "#shared/contract.ts"; import { describeDynamicKind } from "./directory-sections.tsx"; -import { - syncShortInputValidity, - syncTargetInputValidity, -} from "./validation.ts"; +import { errorMessage } from "./trpc.ts"; export type FormMode = | { kind: "create" } @@ -21,9 +28,14 @@ export type FormMode = previousTargetUrl: string; }; -function noop(): void { - // The form dialog keeps no state of its own to reset on close. -} +/** One opening of the form: a fresh object each time resets its fields. */ +export type LinkFormRequest = { + readonly mode: FormMode; + readonly short: string; + readonly target: string; +}; + +const FORM_ID = "link-form"; function describeFormHeading(mode: FormMode): string { switch (mode.kind) { @@ -39,67 +51,6 @@ function describeFormHeading(mode: FormMode): string { } } -const openers = new WeakMap(); - -/** - * Opens a dialog modally and remembers the focused element, so closing it (by - * button, Escape or backdrop) returns focus to whatever opened it. - */ -export function showModalFromFocus(dialog: HTMLDialogElement | null): void { - if (dialog === null || dialog.open) { - return; - } - openers.set(dialog, document.activeElement); - dialog.showModal(); -} - -/** - * A native modal ``. The browser provides the focus trap and Escape; - * the parent opens it with `showModalFromFocus` from an event handler. - */ -export function ModalDialog({ - dialogRef, - labelledBy, - busy, - onClose, - children, -}: { - dialogRef: RefObject; - labelledBy: string; - /** While a request runs the dialog cannot be dismissed, so a late result never closes a newer opening. */ - busy: boolean; - onClose: () => void; - children: ReactNode; -}) { - return ( - { - const opener = openers.get(event.currentTarget); - if (opener instanceof HTMLElement && opener.isConnected) { - opener.focus(); - } - onClose(); - }} - onCancel={(event) => { - if (busy) { - event.preventDefault(); - } - }} - onClick={(event) => { - // A click on the backdrop lands on the dialog element itself. - if (!busy && event.target === event.currentTarget) { - event.currentTarget.close(); - } - }} - > -
{children}
-
- ); -} - export function MissingSlugBanner({ slug, writesEnabled, @@ -112,254 +63,287 @@ export function MissingSlugBanner({ onDismiss: () => void; }) { return ( -
- - go/{slug} does not exist yet. - - - {writesEnabled && ( - - )} - - -
+ + {writesEnabled && ( + + )} + + + } + > + go/{slug} does not exist yet. + ); } export function DeleteConfirmDialog({ - dialogRef, item, isDeleting, onConfirm, onClose, }: { - dialogRef: RefObject; item: LinkItem | null; isDeleting: boolean; onConfirm: () => void; onClose: () => void; }) { return ( - -

- {item === null ? "Delete link" : `Delete go/${item.short}?`} -

- {item !== null && ( -

- It currently points to{" "} - {item.targetUrl}. -

- )} -
- - -
-
+ { + if (!open && !isDeleting) onClose(); + }} + title={item === null ? "Delete link" : `Delete go/${item.short}?`} + description={ + item === null ? undefined : ( + <> + It currently points to{" "} + {item.targetUrl}. + + ) + } + actions={ + <> + } nativeButton> + Cancel + + + + } + /> ); } -export function LinkFormDialog({ - dialogRef, - formMode, +type LinkFormValues = { short: string; targetUrl: string }; + +/** + * The fields on TanStack Form, validated by the contract's Zod schema (which + * wraps `validateShortSlug` and `validateTargetUrl`). It mounts while the + * dialog is open, so every opening starts from the request's values. + */ +function LinkForm({ + request, writesEnabled, - shortValue, - targetValue, - shortErrorText, - targetErrorText, - isSubmitting, - mutationError, - formRef, - shortInputRef, - targetInputRef, - onShortValueChange, - onTargetValueChange, - onShortErrorChange, - onTargetErrorChange, + submitError, + onChange, onSubmit, }: { - dialogRef: RefObject; - formMode: FormMode; + request: LinkFormRequest; writesEnabled: boolean; - shortValue: string; - targetValue: string; - shortErrorText: string; - targetErrorText: string; - isSubmitting: boolean; - mutationError: string | null; - formRef: RefCallback; - shortInputRef: RefObject; - targetInputRef: RefObject; - onShortValueChange: (value: string) => void; - onTargetValueChange: (value: string) => void; - onShortErrorChange: (message: string) => void; - onTargetErrorChange: (message: string) => void; - onSubmit: () => void; + submitError: string | null; + onChange: () => void; + onSubmit: (values: LinkFormValues) => Promise; }) { + const { mode } = request; + const focusShort = mode.kind === "create" && request.short === ""; + const form = useForm({ + defaultValues: { short: request.short, targetUrl: request.target }, + validators: { + onChange: UpsertManualLinkInputSchema, + onSubmit: UpsertManualLinkInputSchema, + }, + onSubmit: async ({ value }) => { + await onSubmit(value); + }, + onSubmitInvalid: () => { + const invalid = document.querySelector( + `#${FORM_ID} [aria-invalid="true"]`, + ); + invalid?.focus(); + }, + }); + return ( - { + event.preventDefault(); + void form.handleSubmit(); + }} > -

- {describeFormHeading(formMode)} -

- {formMode.kind === "override" && ( -

- Currently resolves via{" "} - {describeDynamicKind(formMode.dynamicKind)} to{" "} - - {formMode.previousTargetUrl} - - . A manual link takes precedence. -

+ + {(field) => { + const error = fieldErrorMessage(field.state.meta); + return ( + + {(control) => ( + { + field.handleChange(event.target.value); + }} + /> + )} + + ); + }} + + + {(field) => { + const error = fieldErrorMessage(field.state.meta); + return ( + + {(control) => ( + { + field.handleChange(event.target.value); + }} + /> + )} + + ); + }} + + {submitError !== null && ( + + {submitError} + )} + + ); +} -
{ - event.preventDefault(); - onSubmit(); - }} - > -
- -
- - { - onShortValueChange(event.target.value); - onShortErrorChange(syncShortInputValidity(event.target)); - }} - onBlur={(event) => { - onShortErrorChange(syncShortInputValidity(event.target)); - }} - /> -
-

- 1–64 letters, numbers, dots, hyphens, or underscores. -

-

- {shortErrorText} -

-
+export function LinkFormDialog({ + request, + writesEnabled, + onSave, + onClose, +}: { + request: LinkFormRequest | null; + writesEnabled: boolean; + /** Rejects with the failure to show in the dialog. */ + onSave: (short: string, targetUrl: string) => Promise; + onClose: () => void; +}) { + const [isSubmitting, setIsSubmitting] = useState(false); + const [submitError, setSubmitError] = useState(null); -
- - { - onTargetValueChange(event.target.value); - onTargetErrorChange(syncTargetInputValidity(event.target)); - }} - onBlur={(event) => { - onTargetErrorChange(syncTargetInputValidity(event.target)); - }} - /> -

- Full https:// or http:// address. -

-

- {targetErrorText} -

-
+ // A new opening starts clean: adjust during render, not in an effect. + const [seen, setSeen] = useState(null); + if (seen !== request) { + setSeen(request); + setIsSubmitting(false); + setSubmitError(null); + } - {mutationError !== null && ( -

- {mutationError} -

- )} + const mode = request?.mode ?? { kind: "create" }; -
- + -
- -
+ + } + > + {request === null ? null : ( + { + setSubmitError(null); + }} + onSubmit={save} + /> + )} +
); } diff --git a/packages/golink/src/client/link-form.test.tsx b/packages/golink/src/client/link-form.test.tsx new file mode 100644 index 00000000000..8018ace2dc3 --- /dev/null +++ b/packages/golink/src/client/link-form.test.tsx @@ -0,0 +1,119 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { LinkFormDialog, type LinkFormRequest } from "./link-dialogs.tsx"; + +Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true); + +const unmounts: (() => void)[] = []; +afterEach(() => { + for (const unmount of unmounts.splice(0)) unmount(); + document.body.replaceChildren(); +}); + +async function open(request: LinkFormRequest) { + const onSave = vi.fn<(short: string, targetUrl: string) => Promise>( + () => Promise.resolve(), + ); + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + unmounts.push(() => { + root.unmount(); + }); + await act(async () => { + root.render( + , + ); + }); + return onSave; +} + +function input(name: string): HTMLInputElement { + const element = document.querySelector( + `input[name="${name}"]`, + ); + if (element === null) throw new Error(`no input ${name}`); + return element; +} + +async function type(name: string, value: string): Promise { + const element = input(name); + await act(async () => { + // The prototype's setter, so React's value tracker sees the change. + Reflect.set(HTMLInputElement.prototype, "value", value, element); + element.dispatchEvent(new Event("input", { bubbles: true })); + }); + await act(async () => { + element.dispatchEvent(new FocusEvent("focusout", { bubbles: true })); + element.dispatchEvent(new Event("blur")); + }); +} + +async function submit(): Promise { + const form = document.querySelector("form"); + if (form === null) throw new Error("no form"); + await act(async () => { + form.dispatchEvent( + new Event("submit", { bubbles: true, cancelable: true }), + ); + }); +} + +function errors(): string[] { + return [...document.querySelectorAll(".ui-field-error")].map( + (node) => node.textContent, + ); +} + +const CREATE: LinkFormRequest = { + mode: { kind: "create" }, + short: "", + target: "", +}; + +describe("LinkFormDialog", () => { + test("shows one message per invalid field and does not save", async () => { + const onSave = await open(CREATE); + await type("short", "a b"); + await type("targetUrl", "ftp://example.com"); + await submit(); + expect(errors()).toHaveLength(2); + for (const field of ["short", "targetUrl"]) { + const wrapper = input(field).closest(".ui-field"); + expect(wrapper?.querySelectorAll(".ui-field-error")).toHaveLength(1); + expect(wrapper?.querySelector(".ui-field-hint")).toBeNull(); + } + expect(onSave).not.toHaveBeenCalled(); + }); + + test("a valid create saves the normalized values", async () => { + const onSave = await open(CREATE); + await type("short", " Grafana "); + await type("targetUrl", " https://grafana.example.com/ "); + await submit(); + expect(errors()).toHaveLength(0); + expect(onSave).toHaveBeenCalledExactlyOnceWith( + "grafana", + "https://grafana.example.com/", + ); + }); + + test("edit pre-fills the fields and locks the name", async () => { + await open({ + mode: { kind: "edit", short: "docs" }, + short: "docs", + target: "https://docs.example.com/", + }); + expect(input("short").value).toBe("docs"); + expect(input("short").readOnly).toBe(true); + expect(input("targetUrl").value).toBe("https://docs.example.com/"); + expect(document.body.textContent).toContain("Edit go/docs"); + }); +}); diff --git a/packages/golink/src/client/links-card.tsx b/packages/golink/src/client/links-card.tsx index 00ddbf9558f..4b05eca5497 100644 --- a/packages/golink/src/client/links-card.tsx +++ b/packages/golink/src/client/links-card.tsx @@ -1,24 +1,13 @@ -import type { RefObject } from "react"; -import { - Button, - Card, - CardToolbar, - SearchField, - Segmented, -} from "@shepherdjerred/console-ui"; +import { Banner, Button, Section, State } from "@shepherdjerred/console-ui"; import type { Loaded } from "@shepherdjerred/loaded"; import { LoadingBlock } from "@shepherdjerred/loaded/react.tsx"; import type { LinkItem } from "#shared/contract.ts"; -import { - KIND_FILTER_OPTIONS, - type KindCounts, - type KindFilter, -} from "./directory-sections.tsx"; +import type { KindCounts } from "./directory-sections.tsx"; import { LinksTable } from "./links-table.tsx"; import { errorMessage } from "./trpc.ts"; -/** The headline figures above the links card; dashes until the first load. */ -export function summaryItems( +/** The headline figures under the header bar; dashes until the first load. */ +export function summaryFigures( counts: KindCounts, links: readonly LinkItem[], loaded: boolean, @@ -34,100 +23,44 @@ export function summaryItems( ]; } -type DirectoryBodyProps = { +type LinksSectionProps = { directory: Loaded<{ items: readonly LinkItem[]; totalCount: number }>; writesEnabled: boolean; - copiedShort: string | null; deletingShort: string | null; onRetry: () => void; - onCopy: (short: string) => void; onEdit: (item: LinkItem) => void; onOverride: (item: LinkItem) => void; onDelete: (item: LinkItem) => void; }; -function DirectoryBody({ directory, onRetry, ...table }: DirectoryBodyProps) { +/** The links section: the table, or its loading and error line. */ +export function LinksSection({ + directory, + onRetry, + ...table +}: LinksSectionProps) { return ( - - Loading shortlink directory… -

- } - renderError={([failure]) => ( -
-

+

- )} - > - {({ directory: data }, { errors }) => ( - <> - {errors.length > 0 && ( -

- Showing the last known links. Refresh failed. -

- )} - - - )} -
- ); -} - -/** The links card: search and source filter over the table. */ -export function LinksCard({ - searchInputRef, - query, - kindFilter, - counts, - onQueryChange, - onKindFilterChange, - ...body -}: DirectoryBodyProps & { - searchInputRef: RefObject; - query: string; - kindFilter: KindFilter; - counts: KindCounts; - onQueryChange: (next: string) => void; - onKindFilterChange: (next: KindFilter) => void; -}) { - return ( - - - { - onQueryChange(event.target.value); - }} - /> - ({ - value: option.value, - label: option.label, - count: counts[option.value], - }))} - onChange={onKindFilterChange} - /> - - - + + )} + > + {({ directory: data }, { errors }) => ( + <> + {errors.length > 0 && ( + + Showing the last known links. Refresh failed. + + )} + + + )} + + ); } diff --git a/packages/golink/src/client/links-table.tsx b/packages/golink/src/client/links-table.tsx index a2e3595d6f0..1b6120bf366 100644 --- a/packages/golink/src/client/links-table.tsx +++ b/packages/golink/src/client/links-table.tsx @@ -1,5 +1,11 @@ -import { CheckIcon, CopyIcon, CornerDownRightIcon } from "lucide-react"; -import { Button, IconButton, Tag } from "@shepherdjerred/console-ui"; +import { CornerDownRightIcon } from "lucide-react"; +import { + Button, + Chip, + CopyButton, + RelativeTime, + State, +} from "@shepherdjerred/console-ui"; import type { LinkItem } from "#shared/contract.ts"; import { describeDynamicKind, @@ -7,21 +13,18 @@ import { sourceIcon, } from "./directory-sections.tsx"; -function formatLastClicked(iso: string | null | undefined): string { - if (iso === undefined || iso === null || iso.length === 0) { - return "Never clicked"; - } - const timestamp = Date.parse(iso); - if (Number.isNaN(timestamp)) { - return iso; - } - const formatter = new Intl.DateTimeFormat(undefined, { - month: "short", - day: "numeric", - }); - return `Last ${formatter.format(new Date(timestamp))}`; +/** The URL a `go/` link answers at, for the copy button. */ +function shortUrl(short: string): string { + const origin = "location" in globalThis ? globalThis.location.origin : ""; + return new URL(`/${encodeURIComponent(short)}`, origin || "http://go").href; } +type RowHandlers = { + readonly onEdit: (item: LinkItem) => void; + readonly onOverride: (item: LinkItem) => void; + readonly onDelete: (item: LinkItem) => void; +}; + function RowActionsCell({ item, writesEnabled, @@ -29,13 +32,10 @@ function RowActionsCell({ onEdit, onOverride, onDelete, -}: { - item: LinkItem; - writesEnabled: boolean; - isDeleting: boolean; - onEdit: (item: LinkItem) => void; - onOverride: (item: LinkItem) => void; - onDelete: (item: LinkItem) => void; +}: RowHandlers & { + readonly item: LinkItem; + readonly writesEnabled: boolean; + readonly isDeleting: boolean; }) { if (!writesEnabled) { return Read-only; @@ -44,7 +44,6 @@ function RowActionsCell({ return (