diff --git a/src/app/os/find/page.tsx b/src/app/os/find/page.tsx index 97c120c..9064246 100644 --- a/src/app/os/find/page.tsx +++ b/src/app/os/find/page.tsx @@ -1,22 +1,70 @@ "use client"; -import { useState, useEffect, useMemo } from "react"; -import { redirect, useSearchParams } from "next/navigation"; -import { Search, X, ChevronsUpDown, ChevronsDownUp } from "lucide-react"; +import { + ArrowLeft, + Check, + ChevronRight, + ChevronsDownUp, + ChevronsUpDown, + CircleMinus, + CirclePlus, + Copy, + GitCompare, + ListFilter, + Search, + X, +} from "lucide-react"; +import Link from "next/link"; +import { redirect, useRouter, useSearchParams } from "next/navigation"; +import { useEffect, useMemo, useState } from "react"; -import { Input } from "@/components/ui/input"; -import { Button } from "@/components/ui/button"; -import FileSystem from "@/components/filesystem"; +import { BetaBadge } from "@/components/beta-badge"; +import FileSystem, { type PathStatus } from "@/components/filesystem"; import { HeaderPortal } from "@/components/header-portal"; -import { createEngine } from "@/lib/engine"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; import { useQueryFilter } from "@/hooks/use-query-filter"; +import { createEngine } from "@/lib/engine"; +import { + KEY_TRANSITION_NAME, + type KeysReturn, + keysPageFor, + requestScrollRestore, +} from "@/lib/key-navigation"; +import { compareOSVersion, matchesVersion, versionTag } from "@/lib/os-version"; +import type { OS } from "@/lib/types"; +import { cn } from "@/lib/utils"; + +const FILTER_INPUT_ID = "path-filter"; + +const skeletonWidths = [60, 72, 48, 80, 55, 66, 74, 52]; + +function keysUrlFor(os: string, ns: string) { + const query = new URLSearchParams({ os }); + if (ns) query.set("ns", ns); + return `/os/keys?${query.toString()}`; +} + +/** Paths for a key in a build; a key absent from the build has none. */ +async function pathsForKey(group: string, build: string, key: string) { + const engine = await createEngine(group); + try { + return await engine.getPathsForKey(build, key); + } catch (error) { + if (error instanceof Error && error.message.startsWith("key not found")) + return []; + throw error; + } +} export default function FindByKey() { const params = useSearchParams(); + const router = useRouter(); const os = params.get("os"); const key = params.get("key"); const [group, build] = os ? os.split("/") : ["", ""]; + const compareWith = params.get("diff"); useEffect(() => { if (os && key) { @@ -30,76 +78,259 @@ export default function FindByKey() { const [loading, setLoading] = useState(true); const [paths, setPaths] = useState([]); + const [versions, setVersions] = useState([]); + const [comparePaths, setComparePaths] = useState(null); + const [compareLoading, setCompareLoading] = useState(false); + const [compareError, setCompareError] = useState(false); + const [changesOnly, setChangesOnlyState] = useState( + () => params.get("changes") === "1", + ); + const [copied, setCopied] = useState(false); const [expandAll, setExpandAll] = useState(null); const { keyword, setKeyword, debouncedKeyword } = useQueryFilter(); useEffect(() => { - async function fetchPaths() { - if (!key) return; - - const engine = await createEngine(group); - const result = await engine.getPathsForKey(build, key); - setPaths(result); - } + let cancelled = false; setLoading(true); - fetchPaths().finally(() => setLoading(false)); + Promise.all([ + pathsForKey(group, build, key), + createEngine(group).then((engine) => + engine.listOS().catch(() => [] as OS[]), + ), + ]) + .then(([result, list]) => { + if (cancelled) return; + setPaths(result); + setVersions([...list].sort(compareOSVersion)); + }) + .catch(() => { + if (!cancelled) setPaths([]); + }) + .finally(() => { + if (!cancelled) setLoading(false); + }); + return () => { + cancelled = true; + }; }, [group, build, key]); - const filtered = useMemo( - () => - paths.filter((path) => - path.toLowerCase().includes(debouncedKeyword.toLowerCase()) - ), - [debouncedKeyword, paths] - ); + const currentVersion = versions.find((v) => matchesVersion(v, build)); + const compareVersion = compareWith + ? versions.find((v) => matchesVersion(v, compareWith)) + : undefined; + const activeCompare = + compareVersion && compareVersion !== currentVersion ? compareVersion : null; + + useEffect(() => { + let cancelled = false; + if (!activeCompare) { + setComparePaths(null); + setCompareLoading(false); + setCompareError(false); + return; + } + setComparePaths(null); + setCompareLoading(true); + setCompareError(false); + pathsForKey(group, versionTag(activeCompare), key) + .then((result) => { + if (!cancelled) setComparePaths(result); + }) + .catch(() => { + if (!cancelled) setCompareError(true); + }) + .finally(() => { + if (!cancelled) setCompareLoading(false); + }); + return () => { + cancelled = true; + }; + }, [group, key, activeCompare]); + + const diffReady = Boolean(activeCompare) && comparePaths !== null; + + const { added, removed } = useMemo(() => { + if (!diffReady || !comparePaths) return { added: [], removed: [] }; + const current = new Set(paths); + const base = new Set(comparePaths); + return { + added: paths.filter((path) => !base.has(path)), + removed: comparePaths.filter((path) => !current.has(path)), + }; + }, [comparePaths, diffReady, paths]); + + const showChanges = changesOnly && diffReady; + + // Lost binaries stay in the tree (marked) so changes show in place. + const { list, statusOf } = useMemo(() => { + const addedSet = new Set(added); + const removedSet = new Set(removed); + const all = showChanges ? [...added, ...removed] : [...paths, ...removed]; + const kw = debouncedKeyword.toLowerCase(); + return { + list: kw ? all.filter((path) => path.toLowerCase().includes(kw)) : all, + statusOf: (path: string): PathStatus | undefined => + addedSet.has(path) + ? "added" + : removedSet.has(path) + ? "removed" + : undefined, + }; + }, [added, debouncedKeyword, paths, removed, showChanges]); + + const setParam = (name: string, value: string | null) => { + const next = new URLSearchParams(params.toString()); + if (value) next.set(name, value); + else next.delete(name); + router.replace(`/os/find?${next.toString()}`, { scroll: false }); + }; + + const setChangesOnly = (value: boolean) => { + setChangesOnlyState(value); + const next = new URLSearchParams(window.location.search); + if (value) next.set("changes", "1"); + else next.delete("changes"); + window.history.replaceState(null, "", `?${next.toString()}`); + }; + + useEffect(() => { + if (!copied) return; + const timer = setTimeout(() => setCopied(false), 1500); + return () => clearTimeout(timer); + }, [copied]); + + // "/" focuses the filter from anywhere on the page. + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + if (event.key !== "/" || event.metaKey || event.ctrlKey || event.altKey) + return; + const target = event.target as HTMLElement | null; + if ( + target?.isContentEditable || + ["INPUT", "TEXTAREA", "SELECT"].includes(target?.tagName ?? "") + ) + return; + const input = document.getElementById(FILTER_INPUT_ID); + if (!input) return; + event.preventDefault(); + (input as HTMLInputElement).select(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, []); const isFiltering = debouncedKeyword.length > 0; - - // Reset expandAll when filter changes + // Narrowed views (filter, changes only) open every folder; otherwise the + // tree starts with top-level folders open, as before. + const narrowed = isFiltering || showChanges; useEffect(() => { - setExpandAll(isFiltering ? true : null); - }, [isFiltering]); + setExpandAll(narrowed ? true : null); + }, [narrowed]); + + const [keysReturn, setKeysReturn] = useState(null); + // sessionStorage is client-only; read it after hydration. + useEffect(() => setKeysReturn(keysPageFor(key, os)), [key, os]); + + const namespace = key.includes(".") ? key.slice(0, key.lastIndexOf(".")) : ""; + const backUrl = keysReturn?.url ?? keysUrlFor(os, namespace); + const backNs = keysReturn + ? (new URLSearchParams(keysReturn.url.split("?")[1] ?? "").get("ns") ?? "") + : namespace; + const compareOs = activeCompare + ? `${group}/${versionTag(activeCompare)}` + : os; + + /** Keys page at namespace `ns`, keeping an active comparison. */ + const keysUrl = (ns: string) => { + const query = new URLSearchParams({ os }); + if (ns) query.set("ns", ns); + if (activeCompare) query.set("diff", versionTag(activeCompare)); + return `/os/keys?${query.toString()}`; + }; + + // All keys › [namespace the user came from] › the key's namespace. + const crumbs: { ns: string; label: string }[] = [ + { ns: "", label: "All keys" }, + ]; + if (backNs && backNs !== namespace) + crumbs.push({ ns: backNs, label: backNs }); + if (namespace) + crumbs.push({ + ns: namespace, + label: + backNs && namespace.startsWith(`${backNs}.`) + ? namespace.slice(backNs.length + 1) + : namespace, + }); + + const returnToKeys = (event: React.MouseEvent) => { + if (!keysReturn) return; + requestScrollRestore(keysReturn); + // Same tab, straight from the keys page: go back in history. + if ( + window.history.length > 1 && + event.button === 0 && + !event.metaKey && + !event.ctrlKey && + !event.shiftKey + ) { + event.preventDefault(); + router.back(); + } + }; const filterControls = ( <> -
- +
+ setKeyword(e.target.value)} className="pl-9 pr-9" /> + {!keyword && ( + + / + + )} {keyword && ( )}
- {!loading && paths.length > 0 && ( -
+ {!loading && list.length > 0 && ( +
-
+
@@ -108,47 +339,214 @@ export default function FindByKey() { ); + // Versions grouped by major for the compare picker. + const versionGroups = useMemo(() => { + const groups = new Map(); + for (const version of versions) { + if (version === currentVersion) continue; + const major = version.version.split(".")[0]; + const list = groups.get(major); + if (list) list.push(version); + else groups.set(major, [version]); + } + return [...groups]; + }, [currentVersion, versions]); + return ( -
+
{filterControls} -
-
- Binaries with - {key} -
- {!loading && ( - - {isFiltering ? `${filtered.length} of ${paths.length}` : paths.length} paths + {/* Where this key lives, styled like the keys page's own path. The + arrow, and the crumb the user came from, return to exactly where + they were (namespace, filter, comparison, scroll). */} + + + {/* Key context: what we're looking at, and where it lives. */} +
+
+ + {key} + + +
+ +
+ {!loading && ( + + {isFiltering ? `${list.length} of ${paths.length}` : paths.length}{" "} + {paths.length === 1 ? "binary" : "binaries"} + {currentVersion && ( + <> + {" "} + in {currentVersion.version} + {currentVersion.beta && ( + + + + )} + + )} + + )} + + {compareLoading && ( + Comparing… + )} + {compareError && ( + Compare unavailable + )} + + {diffReady && ( + <> + + + {added.length} gained + + + + {removed.length} lost + + {added.length + removed.length > 0 && ( + + )} + + )} + + {versions.length > 1 && ( + + )} +
-
- {loading ? ( -
- {Array.from({ length: 6 }).map((_, i) => ( -
-
-
-
- ))} -
- ) : filtered.length === 0 ? ( -
- {paths.length === 0 ? ( -

No binaries found with this entitlement.

- ) : ( -

No paths match "{keyword}"

- )} -
- ) : ( - - )} -
+ {loading ? ( +
+ {skeletonWidths.map((width) => ( +
+ ))} +
+ ) : list.length === 0 ? ( +
+ {paths.length === 0 && !diffReady ? ( +

No binaries found with this entitlement.

+ ) : showChanges && !isFiltering ? ( +

No binaries gained or lost this key.

+ ) : ( +

No binaries match "{keyword}"

+ )} +
+ ) : ( + + statusOf(path) === "removed" ? compareOs : undefined + } + /> + )}
); } diff --git a/src/app/os/keys/page.tsx b/src/app/os/keys/page.tsx index b44ab42..c179947 100644 --- a/src/app/os/keys/page.tsx +++ b/src/app/os/keys/page.tsx @@ -27,6 +27,8 @@ import { } from "@/components/ui/popover"; import { useQueryFilter } from "@/hooks/use-query-filter"; import { createEngine } from "@/lib/engine"; +import { basePath } from "@/lib/env"; +import { takeScrollRestore } from "@/lib/key-navigation"; import { type NamespaceNode, allNamespaces, @@ -35,30 +37,18 @@ import { inNamespace, namespacePath, } from "@/lib/key-tree"; +import { compareOSVersion, matchesVersion, versionTag } from "@/lib/os-version"; import type { OS } from "@/lib/types"; import { cn } from "@/lib/utils"; -function versionTag(os: OS) { - return `${os.version}_${os.build}`; -} - function isCurrentVersion(os: OS, build: string) { - return os.build === build || versionTag(os) === build; + return matchesVersion(os, build); } -function matchesVersion(os: OS, tag: string) { - return os.build === tag || versionTag(os) === tag; -} - -function compareOSVersion(a: OS, b: OS) { - const vA = a.version.split(".").map(Number); - const vB = b.version.split(".").map(Number); - for (let i = 0; i < Math.max(vA.length, vB.length); i++) { - const diff = (vB[i] || 0) - (vA[i] || 0); - if (diff !== 0) return diff; - } - - return b.build.localeCompare(a.build); +function withoutBasePath(path: string) { + return basePath && path.startsWith(basePath) + ? path.slice(basePath.length) + : path; } /** Open every namespace when a filtered result is this small. */ @@ -407,7 +397,12 @@ export default function Keys() { const loweredKeyword = debouncedKeyword.toLowerCase(); return [ - ...addedKeys.map((key) => ({ key, os, status: "added" as const })), + ...addedKeys.map((key) => ({ + key, + os, + status: "added" as const, + diff: activeCompareTag ?? undefined, + })), ...removedKeys.map((key) => ({ key, os: compareOs, @@ -419,7 +414,15 @@ export default function Keys() { (a, b) => a.key.localeCompare(b.key) || a.status.localeCompare(b.status), ); - }, [addedKeys, compareOs, debouncedKeyword, diffReady, os, removedKeys]); + }, [ + activeCompareTag, + addedKeys, + compareOs, + debouncedKeyword, + diffReady, + os, + removedKeys, + ]); const displayedKeys = useMemo( () => @@ -427,8 +430,10 @@ export default function Keys() { key, os, status: diffReady && addedKeySet.has(key) ? "added" : "current", + // Open the find page comparing against the same version. + diff: diffReady ? (activeCompareTag ?? undefined) : undefined, })), - [addedKeySet, diffReady, filtered, os], + [activeCompareTag, addedKeySet, diffReady, filtered, os], ); const isFiltering = debouncedKeyword.length > 0; @@ -522,7 +527,17 @@ export default function Keys() { return Object.entries(groups).sort(([a], [b]) => Number(b) - Number(a)); }, [versions]); - // "/" focuses the filter from anywhere on the page, as on GitHub. + // Returning from a key's find page: restore the scroll position once the + // keys have rendered (browser restoration ran against the skeleton). + useEffect(() => { + if (loading) return; + const y = takeScrollRestore( + withoutBasePath(window.location.pathname) + window.location.search, + ); + if (y !== null) requestAnimationFrame(() => window.scrollTo(0, y)); + }, [loading]); + + // "/" focuses the filter from anywhere on the page. useEffect(() => { const onKey = (event: KeyboardEvent) => { if (event.key !== "/" || event.metaKey || event.ctrlKey || event.altKey) diff --git a/src/components/key-link.tsx b/src/components/key-link.tsx index cb1bab7..cb5324b 100644 --- a/src/components/key-link.tsx +++ b/src/components/key-link.tsx @@ -2,19 +2,45 @@ import { Check, Copy, Minus, Plus } from "lucide-react"; import Link from "next/link"; -import { useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { useEffect, useRef, useState } from "react"; +import { basePath } from "@/lib/env"; +import { + KEY_TRANSITION_NAME, + canAnimateNavigation, + navigateWithTransition, + rememberKeysPage, +} from "@/lib/key-navigation"; import { cn } from "@/lib/utils"; +/** router.push() adds basePath itself, so store paths without it. */ +function withoutBasePath(path: string) { + return basePath && path.startsWith(basePath) + ? path.slice(basePath.length) + : path; +} + export type DisplayedKey = { key: string; os: string; status: "current" | "added" | "removed"; + /** Version being compared against, carried over to the find page. */ + diff?: string; }; +function findHref(entry: DisplayedKey) { + const query = new URLSearchParams({ key: entry.key, os: entry.os }); + if (entry.diff) query.set("diff", entry.diff); + return `/os/find?${query.toString()}`; +} + export function KeyLink({ entry }: { entry: DisplayedKey }) { const isNew = entry.status === "added"; const isRemoved = entry.status === "removed"; + const router = useRouter(); + const labelRef = useRef(null); + const href = findHref(entry); return (
{ + // Remember exactly where we were, for the find page's back link. + rememberKeysPage({ + url: + withoutBasePath(window.location.pathname) + + window.location.search, + key: entry.key, + os: entry.os, + scrollY: window.scrollY, + }); + if (!canAnimateNavigation(event) || !labelRef.current) return; + // Morph this key name into the find page title. + event.preventDefault(); + labelRef.current.style.viewTransitionName = KEY_TRANSITION_NAME; + navigateWithTransition(() => router.push(href), "[data-key-title]"); + }} className="flex min-w-0 items-start gap-2 rounded-md py-1 pl-1 pr-7 font-mono text-sm leading-5" title={entry.key} onKeyDown={(event) => { @@ -63,7 +103,9 @@ export function KeyLink({ entry }: { entry: DisplayedKey }) { )} )} - + + +
diff --git a/src/lib/key-navigation.ts b/src/lib/key-navigation.ts new file mode 100644 index 0000000..c3633b8 --- /dev/null +++ b/src/lib/key-navigation.ts @@ -0,0 +1,123 @@ +/** + * Continuity between the keys page and a key's find page: + * - remember where on the keys page the user clicked a key, so the find page + * can offer a precise way back (same namespace, filter, comparison, scroll); + * - morph the clicked key name into the find page title with a view + * transition where the browser supports it. + */ + +const RETURN_KEY = "entdb:keys-return"; + +/** `view-transition-name` shared by the clicked key and the find page title. */ +export const KEY_TRANSITION_NAME = "entitlement-key"; + +export interface KeysReturn { + /** Keys page URL (path + query, without basePath) to return to. */ + url: string; + /** The find page this return belongs to. */ + key: string; + os: string; + /** Scroll position on the keys page when the key was clicked. */ + scrollY: number; +} + +export function rememberKeysPage(entry: KeysReturn) { + try { + sessionStorage.setItem(RETURN_KEY, JSON.stringify(entry)); + } catch { + // Storage unavailable: the find page falls back to the key's namespace. + } +} + +const RESTORE_KEY = "entdb:keys-restore"; + +/** + * Ask the keys page to restore its scroll once its data has loaded. The + * browser's own restoration runs before the async load, against a page that + * is still a short skeleton. + */ +export function requestScrollRestore(entry: KeysReturn) { + try { + sessionStorage.setItem( + RESTORE_KEY, + JSON.stringify({ url: entry.url, scrollY: entry.scrollY }), + ); + } catch { + // Not critical. + } +} + +/** One-shot: the scroll position to restore for `url`, if any. */ +export function takeScrollRestore(url: string): number | null { + try { + const raw = sessionStorage.getItem(RESTORE_KEY); + if (!raw) return null; + sessionStorage.removeItem(RESTORE_KEY); + const entry = JSON.parse(raw) as { url: string; scrollY: number }; + return entry.url === url ? entry.scrollY : null; + } catch { + return null; + } +} + +/** The remembered keys page, if it led to this exact find page. */ +export function keysPageFor(key: string, os: string): KeysReturn | null { + try { + const raw = sessionStorage.getItem(RETURN_KEY); + if (!raw) return null; + const entry = JSON.parse(raw) as KeysReturn; + return entry.key === key && entry.os === os ? entry : null; + } catch { + return null; + } +} + +type ViewTransitionDocument = Document & { + startViewTransition?: (update: () => Promise) => unknown; +}; + +/** Whether a click should animate (plain left click, motion allowed). */ +export function canAnimateNavigation(event: { + button: number; + metaKey: boolean; + ctrlKey: boolean; + shiftKey: boolean; + altKey: boolean; +}) { + return ( + event.button === 0 && + !event.metaKey && + !event.ctrlKey && + !event.shiftKey && + !event.altKey && + typeof (document as ViewTransitionDocument).startViewTransition === + "function" && + !window.matchMedia("(prefers-reduced-motion: reduce)").matches + ); +} + +/** + * Navigate inside a view transition. The transition snapshots the new state + * once `selector` exists (the destination's title), or after `timeoutMs` so a + * slow route never freezes the page. + */ +export function navigateWithTransition( + navigate: () => void, + selector: string, + timeoutMs = 800, +) { + const start = (document as ViewTransitionDocument).startViewTransition; + if (!start) { + navigate(); + return; + } + start.call(document, async () => { + navigate(); + const deadline = performance.now() + timeoutMs; + // Poll with timers: rendering (and so requestAnimationFrame) is paused + // while a view transition's update callback is pending. + while (!document.querySelector(selector) && performance.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 16)); + } + }); +} diff --git a/src/lib/os-version.ts b/src/lib/os-version.ts new file mode 100644 index 0000000..1c59368 --- /dev/null +++ b/src/lib/os-version.ts @@ -0,0 +1,23 @@ +import type { OS } from "@/lib/types"; + +/** URL tag for a build, e.g. `27.2.1_24B91034`. */ +export function versionTag(os: OS) { + return `${os.version}_${os.build}`; +} + +/** Whether `os` is the build named by `tag` (a bare build or a full tag). */ +export function matchesVersion(os: OS, tag: string) { + return os.build === tag || versionTag(os) === tag; +} + +/** Sort comparator: newest version first, then by build. */ +export function compareOSVersion(a: OS, b: OS) { + const vA = a.version.split(".").map(Number); + const vB = b.version.split(".").map(Number); + for (let i = 0; i < Math.max(vA.length, vB.length); i++) { + const diff = (vB[i] || 0) - (vA[i] || 0); + if (diff !== 0) return diff; + } + + return b.build.localeCompare(a.build); +}