mirror of
https://github.com/ChiChou/entdb.git
synced 2026-12-05 11:13:40 +01:00
feat(find): show values and filter binaries by value
- Each binary's value is shown in the tree (hidden on phones); a value shared by every binary is stated once in the header instead. - "Value" (or =) opens a typeahead of this key's values with faceted counts. Arrays match by "contains", scalars by "equals"; several picks must all match. Matches are highlighted and listed first in each row. - Picks show on their own row under the key and persist in ?v=. - Works with version compare: lost binaries filter by their old value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4b6e6a52bd
commit
e76fd472ae
6 files changed
+513
-32
No files matched your search
+104
-29
@@ -16,7 +16,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { redirect, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { BetaBadge } from "@/components/beta-badge";
|
||||
import FileSystem, { type PathStatus } from "@/components/filesystem";
|
||||
@@ -24,8 +24,10 @@ import { HeaderPortal } from "@/components/header-portal";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { ValueConditions, ValueFilter } from "@/components/value-filter";
|
||||
import { useQueryFilter } from "@/hooks/use-query-filter";
|
||||
import { createEngine } from "@/lib/engine";
|
||||
import { atomOf, isUniform, matchesAtoms } from "@/lib/entitlement-value";
|
||||
import {
|
||||
KEY_TRANSITION_NAME,
|
||||
type KeysReturn,
|
||||
@@ -65,18 +67,14 @@ function keysUrlFor(os: string, ns: string) {
|
||||
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) {
|
||||
/** Binaries with a key in a build, mapped to their values (empty if none). */
|
||||
async function valuesForKey(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;
|
||||
}
|
||||
return engine.getValuesForKey(build, key);
|
||||
}
|
||||
|
||||
const NO_VALUES = new Map<string, unknown>();
|
||||
|
||||
export default function FindByKey() {
|
||||
const params = useSearchParams();
|
||||
const router = useRouter();
|
||||
@@ -85,6 +83,11 @@ export default function FindByKey() {
|
||||
|
||||
const [group, build] = os ? os.split("/") : ["", ""];
|
||||
const compareWith = params.get("diff");
|
||||
// ?v=a&v=b: binaries whose value contains both atoms. Local state (like
|
||||
// "Changed only"), so quick successive picks never read a stale URL.
|
||||
const [selectedAtoms, setSelectedAtomsState] = useState(() =>
|
||||
params.getAll("v"),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (os && key) {
|
||||
@@ -97,9 +100,12 @@ export default function FindByKey() {
|
||||
}
|
||||
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [paths, setPaths] = useState<string[]>([]);
|
||||
const [values, setValues] = useState(NO_VALUES);
|
||||
const [versions, setVersions] = useState<OS[]>([]);
|
||||
const [comparePaths, setComparePaths] = useState<string[] | null>(null);
|
||||
const [compareValues, setCompareValues] = useState<Map<
|
||||
string,
|
||||
unknown
|
||||
> | null>(null);
|
||||
const [compareLoading, setCompareLoading] = useState(false);
|
||||
const [compareError, setCompareError] = useState(false);
|
||||
const [changesOnly, setChangesOnlyState] = useState(
|
||||
@@ -113,18 +119,18 @@ export default function FindByKey() {
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
Promise.all([
|
||||
pathsForKey(group, build, key),
|
||||
valuesForKey(group, build, key),
|
||||
createEngine(group).then((engine) =>
|
||||
engine.listOS().catch(() => [] as OS[]),
|
||||
),
|
||||
])
|
||||
.then(([result, list]) => {
|
||||
if (cancelled) return;
|
||||
setPaths(result);
|
||||
setValues(result);
|
||||
setVersions([...list].sort(compareOSVersion));
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setPaths([]);
|
||||
if (!cancelled) setValues(NO_VALUES);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
@@ -144,17 +150,17 @@ export default function FindByKey() {
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
if (!activeCompare) {
|
||||
setComparePaths(null);
|
||||
setCompareValues(null);
|
||||
setCompareLoading(false);
|
||||
setCompareError(false);
|
||||
return;
|
||||
}
|
||||
setComparePaths(null);
|
||||
setCompareValues(null);
|
||||
setCompareLoading(true);
|
||||
setCompareError(false);
|
||||
pathsForKey(group, versionTag(activeCompare), key)
|
||||
valuesForKey(group, versionTag(activeCompare), key)
|
||||
.then((result) => {
|
||||
if (!cancelled) setComparePaths(result);
|
||||
if (!cancelled) setCompareValues(result);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setCompareError(true);
|
||||
@@ -167,17 +173,43 @@ export default function FindByKey() {
|
||||
};
|
||||
}, [group, key, activeCompare]);
|
||||
|
||||
const diffReady = Boolean(activeCompare) && comparePaths !== null;
|
||||
const paths = useMemo(() => [...values.keys()], [values]);
|
||||
const diffReady = Boolean(activeCompare) && compareValues !== null;
|
||||
|
||||
const { added, removed } = useMemo(() => {
|
||||
if (!diffReady || !comparePaths) return { added: [], removed: [] };
|
||||
const current = new Set(paths);
|
||||
const base = new Set(comparePaths);
|
||||
if (!diffReady || !compareValues) return { added: [], removed: [] };
|
||||
return {
|
||||
added: paths.filter((path) => !base.has(path)),
|
||||
removed: comparePaths.filter((path) => !current.has(path)),
|
||||
added: paths.filter((path) => !compareValues.has(path)),
|
||||
removed: [...compareValues.keys()].filter((path) => !values.has(path)),
|
||||
};
|
||||
}, [comparePaths, diffReady, paths]);
|
||||
}, [compareValues, diffReady, paths, values]);
|
||||
|
||||
// A lost binary shows (and filters by) its value in the compared build.
|
||||
const valueFor = useCallback(
|
||||
(path: string) =>
|
||||
values.has(path) ? values.get(path) : compareValues?.get(path),
|
||||
[compareValues, values],
|
||||
);
|
||||
|
||||
// Every binary's value, for the value filter's suggestions.
|
||||
const allValues = useMemo(
|
||||
() => [...paths, ...removed].map(valueFor),
|
||||
[paths, removed, valueFor],
|
||||
);
|
||||
// `true` everywhere: say it once instead of on every row.
|
||||
const uniformValue = useMemo(
|
||||
() => (isUniform(allValues) ? allValues[0] : undefined),
|
||||
[allValues],
|
||||
);
|
||||
const hasValues = allValues.length > 0 && uniformValue === undefined;
|
||||
|
||||
const setSelectedAtoms = (atoms: string[]) => {
|
||||
setSelectedAtomsState(atoms);
|
||||
const next = new URLSearchParams(window.location.search);
|
||||
next.delete("v");
|
||||
for (const atom of atoms) next.append("v", atom);
|
||||
window.history.replaceState(null, "", `?${next.toString()}`);
|
||||
};
|
||||
|
||||
const showChanges = changesOnly && diffReady;
|
||||
|
||||
@@ -188,7 +220,11 @@ export default function FindByKey() {
|
||||
const all = showChanges ? [...added, ...removed] : [...paths, ...removed];
|
||||
const kw = debouncedKeyword.toLowerCase();
|
||||
return {
|
||||
list: kw ? all.filter((path) => path.toLowerCase().includes(kw)) : all,
|
||||
list: all.filter(
|
||||
(path) =>
|
||||
(!kw || path.toLowerCase().includes(kw)) &&
|
||||
matchesAtoms(valueFor(path), selectedAtoms),
|
||||
),
|
||||
statusOf: (path: string): PathStatus | undefined =>
|
||||
addedSet.has(path)
|
||||
? "added"
|
||||
@@ -196,7 +232,15 @@ export default function FindByKey() {
|
||||
? "removed"
|
||||
: undefined,
|
||||
};
|
||||
}, [added, debouncedKeyword, paths, removed, showChanges]);
|
||||
}, [
|
||||
added,
|
||||
debouncedKeyword,
|
||||
paths,
|
||||
removed,
|
||||
selectedAtoms,
|
||||
showChanges,
|
||||
valueFor,
|
||||
]);
|
||||
|
||||
const setParam = (name: string, value: string | null) => {
|
||||
const next = new URLSearchParams(params.toString());
|
||||
@@ -219,7 +263,7 @@ export default function FindByKey() {
|
||||
return () => clearTimeout(timer);
|
||||
}, [copied]);
|
||||
|
||||
const isFiltering = debouncedKeyword.length > 0;
|
||||
const isFiltering = debouncedKeyword.length > 0 || selectedAtoms.length > 0;
|
||||
// Narrowed views (filter, changes only) open every folder; otherwise the
|
||||
// tree starts with top-level folders open, as before.
|
||||
const narrowed = isFiltering || showChanges;
|
||||
@@ -439,9 +483,27 @@ export default function FindByKey() {
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{uniformValue !== undefined && (
|
||||
<>
|
||||
, all{" "}
|
||||
<code className="rounded bg-muted px-1 font-mono text-xs text-foreground">
|
||||
{typeof uniformValue === "string"
|
||||
? `"${uniformValue}"`
|
||||
: atomOf(uniformValue)}
|
||||
</code>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{!loading && hasValues && (
|
||||
<ValueFilter
|
||||
values={allValues}
|
||||
selected={selectedAtoms}
|
||||
onChange={setSelectedAtoms}
|
||||
/>
|
||||
)}
|
||||
|
||||
{compareLoading && (
|
||||
<span className="text-muted-foreground">Comparing…</span>
|
||||
)}
|
||||
@@ -516,6 +578,15 @@ export default function FindByKey() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!loading && hasValues && selectedAtoms.length > 0 && (
|
||||
<div className="-mt-2 mb-3">
|
||||
<ValueConditions
|
||||
selected={selectedAtoms}
|
||||
onChange={setSelectedAtoms}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div
|
||||
aria-busy="true"
|
||||
@@ -547,6 +618,8 @@ export default function FindByKey() {
|
||||
<p>No binaries found with this entitlement.</p>
|
||||
) : showChanges && !isFiltering ? (
|
||||
<p>No binaries gained or lost this key.</p>
|
||||
) : selectedAtoms.length > 0 && !debouncedKeyword ? (
|
||||
<p>No binaries have a value containing all of the selected.</p>
|
||||
) : (
|
||||
<p>No binaries match "{keyword}"</p>
|
||||
)}
|
||||
@@ -560,6 +633,8 @@ export default function FindByKey() {
|
||||
osFor={(path) =>
|
||||
statusOf(path) === "removed" ? compareOs : undefined
|
||||
}
|
||||
valueFor={hasValues ? valueFor : undefined}
|
||||
highlight={selectedAtoms}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
import { ValuePreview } from "@/components/value-preview";
|
||||
import filesToTree, { type TreeWithFullPath } from "@/lib/tree";
|
||||
import Link from "next/link";
|
||||
|
||||
@@ -34,9 +35,14 @@ export type PathStatus = "added" | "removed";
|
||||
interface Marks {
|
||||
status?: (path: string) => PathStatus | undefined;
|
||||
osFor?: (path: string) => string | undefined;
|
||||
/** Shows each binary's entitlement value next to its name. */
|
||||
valueFor?: (path: string) => unknown;
|
||||
/** Atoms to mark in the values (the active value filter). */
|
||||
highlight?: readonly string[];
|
||||
}
|
||||
|
||||
const MarksContext = createContext<Marks>({});
|
||||
const NO_HIGHLIGHT: readonly string[] = [];
|
||||
|
||||
function countMarks(item: TreeWithFullPath, status: Marks["status"]) {
|
||||
let added = 0;
|
||||
@@ -128,11 +134,19 @@ const FileItem = memo(function FileItem({
|
||||
className={cn(
|
||||
"font-mono text-sm hover:underline truncate",
|
||||
!mark && "text-muted-foreground hover:text-foreground",
|
||||
marks.valueFor && "sm:max-w-[60%] sm:shrink-0",
|
||||
)}
|
||||
title={fullPath}
|
||||
>
|
||||
{name}
|
||||
</Link>
|
||||
{marks.valueFor && (
|
||||
<ValuePreview
|
||||
value={marks.valueFor(fullPath)}
|
||||
highlight={marks.highlight ?? NO_HIGHLIGHT}
|
||||
className="ml-1 hidden sm:flex"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -327,13 +341,18 @@ const FileSystem = memo(function FileSystem({
|
||||
expandAll = null,
|
||||
status,
|
||||
osFor,
|
||||
valueFor,
|
||||
highlight,
|
||||
}: {
|
||||
list: string[];
|
||||
os: string;
|
||||
expandAll?: boolean | null;
|
||||
} & Marks) {
|
||||
const tree = useMemo(() => filesToTree(list), [list]);
|
||||
const marks = useMemo(() => ({ status, osFor }), [status, osFor]);
|
||||
const marks = useMemo(
|
||||
() => ({ status, osFor, valueFor, highlight }),
|
||||
[status, osFor, valueFor, highlight],
|
||||
);
|
||||
return (
|
||||
<MarksContext.Provider value={marks}>
|
||||
<div onKeyDown={onTreeKeyDown}>
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
* / focus the page filter Esc clear it, then leave it
|
||||
* j / k next / previous item ? this help
|
||||
* g h|k|f go home / keys / files v version picker
|
||||
* = value filter (find page)
|
||||
*
|
||||
* Lists opt in by marking focusable rows with `data-nav-item`. Widgets that
|
||||
* own their keys (the namespace tree, file trees) handle them first and call
|
||||
@@ -30,6 +31,9 @@ export const NAV_ITEM_ATTR = "data-nav-item";
|
||||
/** Marks the button that opens the version picker. */
|
||||
export const VERSION_PICKER_ATTR = "data-version-picker";
|
||||
|
||||
/** Marks the button that opens the value filter. */
|
||||
export const VALUE_FILTER_ATTR = "data-value-filter";
|
||||
|
||||
const GOTO_WINDOW_MS = 1200;
|
||||
|
||||
function isTyping(target: EventTarget | null) {
|
||||
@@ -149,9 +153,10 @@ export function KeyboardShortcuts({ os }: { os: string }) {
|
||||
case "g":
|
||||
gotoAt = performance.now();
|
||||
return;
|
||||
case "v": {
|
||||
case "v":
|
||||
case "=": {
|
||||
const picker = document.querySelector<HTMLElement>(
|
||||
`[${VERSION_PICKER_ATTR}]`,
|
||||
`[${event.key === "v" ? VERSION_PICKER_ATTR : VALUE_FILTER_ATTR}]`,
|
||||
);
|
||||
if (!picker) return;
|
||||
event.preventDefault();
|
||||
@@ -226,6 +231,7 @@ const SHORTCUTS: { title: string; items: [string[], string][] }[] = [
|
||||
[["/"], "Filter"],
|
||||
[["Esc"], "Clear / leave filter"],
|
||||
[["v"], "Switch version"],
|
||||
[["="], "Filter by value"],
|
||||
[["?"], "Show shortcuts"],
|
||||
],
|
||||
},
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
"use client";
|
||||
|
||||
import { Braces, Check, X } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
import { VALUE_FILTER_ATTR } from "@/components/keyboard-shortcuts";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@/components/ui/command";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { countAtoms, matchesAtoms } from "@/lib/entitlement-value";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** Rendering thousands of cmdk items is slow; typing narrows the rest. */
|
||||
const MAX_SUGGESTIONS = 150;
|
||||
|
||||
/**
|
||||
* "Value contains …" filter with suggestions drawn from this key's values.
|
||||
* Selecting several atoms means all of them (AND); the counts are faceted,
|
||||
* so they always say how many binaries would remain after adding that atom.
|
||||
*/
|
||||
export function ValueFilter({
|
||||
values,
|
||||
selected,
|
||||
onChange,
|
||||
}: {
|
||||
/** Every binary's value for the key. */
|
||||
values: unknown[];
|
||||
selected: string[];
|
||||
onChange: (selected: string[]) => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
|
||||
const facets = useMemo(
|
||||
() => countAtoms(values.filter((value) => matchesAtoms(value, selected))),
|
||||
[values, selected],
|
||||
);
|
||||
|
||||
const suggestions = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
const rest = facets.filter(({ atom }) => !selected.includes(atom));
|
||||
if (!q) return rest;
|
||||
// Prefix matches first, then anywhere; each keeps the count order.
|
||||
const prefix = [];
|
||||
const inner = [];
|
||||
for (const facet of rest) {
|
||||
const index = facet.atom.toLowerCase().indexOf(q);
|
||||
if (index === 0) prefix.push(facet);
|
||||
else if (index > 0) inner.push(facet);
|
||||
}
|
||||
return [...prefix, ...inner];
|
||||
}, [facets, query, selected]);
|
||||
|
||||
const toggle = (atom: string) => {
|
||||
onChange(
|
||||
selected.includes(atom)
|
||||
? selected.filter((a) => a !== atom)
|
||||
: [...selected, atom],
|
||||
);
|
||||
setQuery("");
|
||||
};
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
{...{ [VALUE_FILTER_ATTR]: "" }}
|
||||
className={cn(
|
||||
"inline-flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs transition-colors hover:bg-accent",
|
||||
selected.length > 0
|
||||
? "border-primary/40 text-foreground"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
title="Filter by value (=)"
|
||||
>
|
||||
<Braces className="h-3.5 w-3.5" />
|
||||
Value
|
||||
{selected.length > 0 && (
|
||||
<span className="rounded bg-primary px-1 tabular-nums text-[11px] leading-4 text-primary-foreground">
|
||||
{selected.length}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
className="w-[min(28rem,calc(100vw-2rem))] p-0"
|
||||
align="end"
|
||||
>
|
||||
<Command shouldFilter={false}>
|
||||
<CommandInput
|
||||
value={query}
|
||||
onValueChange={setQuery}
|
||||
placeholder="Value contains…"
|
||||
onKeyDown={(e) => {
|
||||
// Backspace on an empty query drops the last condition.
|
||||
if (e.key === "Backspace" && !query && selected.length > 0) {
|
||||
e.preventDefault();
|
||||
onChange(selected.slice(0, -1));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<CommandList className="max-h-[min(22rem,60vh)]">
|
||||
<CommandEmpty>
|
||||
{facets.length === 0 ? "No binaries match." : "No such value."}
|
||||
</CommandEmpty>
|
||||
{/* Hidden while typing, so Enter picks a match, not these. */}
|
||||
{!query &&
|
||||
selected.map((atom) => (
|
||||
<CommandItem
|
||||
key={`selected:${atom}`}
|
||||
value={`selected:${atom}`}
|
||||
onSelect={() => toggle(atom)}
|
||||
className="gap-2"
|
||||
>
|
||||
<Check className="h-3.5 w-3.5 shrink-0" />
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-xs">
|
||||
{atom}
|
||||
</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
{suggestions.slice(0, MAX_SUGGESTIONS).map(({ atom, count }) => (
|
||||
<CommandItem
|
||||
key={atom}
|
||||
value={atom}
|
||||
onSelect={() => toggle(atom)}
|
||||
className="gap-2"
|
||||
>
|
||||
<span className="h-3.5 w-3.5 shrink-0" />
|
||||
<span
|
||||
className="min-w-0 flex-1 truncate font-mono text-xs"
|
||||
title={atom}
|
||||
>
|
||||
{atom}
|
||||
</span>
|
||||
<span className="shrink-0 text-xs tabular-nums text-muted-foreground">
|
||||
{count}
|
||||
</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
{suggestions.length > MAX_SUGGESTIONS && (
|
||||
<div className="px-2 py-1.5 text-xs text-muted-foreground">
|
||||
{suggestions.length - MAX_SUGGESTIONS} more — type to narrow
|
||||
</div>
|
||||
)}
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The active value conditions, on their own row under the key header so
|
||||
* adding one never reflows the header controls.
|
||||
*/
|
||||
export function ValueConditions({
|
||||
selected,
|
||||
onChange,
|
||||
}: {
|
||||
selected: string[];
|
||||
onChange: (selected: string[]) => void;
|
||||
}) {
|
||||
if (selected.length === 0) return null;
|
||||
return (
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-1.5 text-xs">
|
||||
<span className="text-muted-foreground">Value contains</span>
|
||||
{selected.map((atom, i) => (
|
||||
<span key={atom} className="flex min-w-0 items-center gap-1.5">
|
||||
{i > 0 && <span className="text-muted-foreground">and</span>}
|
||||
<span
|
||||
className="inline-flex h-6 min-w-0 max-w-[20rem] items-center gap-0.5 rounded-md bg-primary/10 pl-2 pr-0.5 font-mono"
|
||||
title={atom}
|
||||
>
|
||||
<span className="truncate">{atom}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(selected.filter((a) => a !== atom))}
|
||||
className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
aria-label={`Remove ${atom}`}
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange([])}
|
||||
className="rounded px-1.5 py-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { atomOf } from "@/lib/entitlement-value";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const TITLE_LIMIT = 4000;
|
||||
|
||||
function titleFor(value: unknown) {
|
||||
const json = JSON.stringify(value, null, 2);
|
||||
return json.length > TITLE_LIMIT ? `${json.slice(0, TITLE_LIMIT)}\n…` : json;
|
||||
}
|
||||
|
||||
function Atom({ atom, hit }: { atom: string; hit: boolean }) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
hit && "rounded-sm bg-primary/10 px-0.5 font-medium text-foreground",
|
||||
)}
|
||||
>
|
||||
{atom}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One-line summary of an entitlement value, for a tree row. Array items and
|
||||
* dict keys that match the active value filter come first and are marked, so
|
||||
* the reason a binary matched is visible even when the list is truncated.
|
||||
*/
|
||||
export function ValuePreview({
|
||||
value,
|
||||
highlight,
|
||||
className,
|
||||
}: {
|
||||
value: unknown;
|
||||
highlight: readonly string[];
|
||||
className?: string;
|
||||
}) {
|
||||
const hits = new Set(highlight);
|
||||
const isList = Array.isArray(value);
|
||||
const isDict = !isList && value !== null && typeof value === "object";
|
||||
|
||||
let body: React.ReactNode;
|
||||
let count: number | null = null;
|
||||
if (isList || isDict) {
|
||||
const items = isList
|
||||
? (value as unknown[]).map((item) =>
|
||||
item !== null && typeof item === "object"
|
||||
? JSON.stringify(item)
|
||||
: atomOf(item),
|
||||
)
|
||||
: Object.keys(value as object);
|
||||
count = items.length;
|
||||
const ordered = [
|
||||
...items.filter((item) => hits.has(item)),
|
||||
...items.filter((item) => !hits.has(item)),
|
||||
];
|
||||
body = (
|
||||
<>
|
||||
{isList ? "[" : "{"}
|
||||
{ordered.map((item, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: items may repeat
|
||||
<span key={i}>
|
||||
{i > 0 && ", "}
|
||||
<Atom atom={item} hit={hits.has(item)} />
|
||||
</span>
|
||||
))}
|
||||
{isList ? "]" : "}"}
|
||||
</>
|
||||
);
|
||||
} else {
|
||||
const atom = atomOf(value);
|
||||
body = (
|
||||
<Atom
|
||||
atom={typeof value === "string" ? `"${atom}"` : atom}
|
||||
hit={hits.has(atom)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"flex min-w-0 items-center gap-1.5 font-mono text-xs text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
title={titleFor(value)}
|
||||
>
|
||||
<span className="truncate">{body}</span>
|
||||
{count !== null && count > 1 && (
|
||||
<span className="shrink-0 rounded bg-muted px-1 tabular-nums">
|
||||
{count}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Entitlement values as filterable "atoms": the scalars a value is made of.
|
||||
*
|
||||
* true -> ["true"]
|
||||
* "group.com.apple.notes" -> ["group.com.apple.notes"]
|
||||
* ["kTCCServiceCamera", ...] -> one atom per item
|
||||
* {"a": true, "b": ["x"]} -> "a", "b", "x" (dict keys and leaf values)
|
||||
*
|
||||
* Most interesting values are arrays (tcc.allow, mach-lookup names, keychain
|
||||
* groups), so filtering by atom reads as "contains", and for scalars it reads
|
||||
* as "equals". Strings are bare; other scalars are their JSON ("true", "1").
|
||||
*/
|
||||
|
||||
export function atomOf(value: unknown): string {
|
||||
return typeof value === "string" ? value : JSON.stringify(value);
|
||||
}
|
||||
|
||||
function collect(value: unknown, out: Set<string>) {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) collect(item, out);
|
||||
} else if (value !== null && typeof value === "object") {
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
out.add(key);
|
||||
collect(item, out);
|
||||
}
|
||||
} else {
|
||||
out.add(atomOf(value));
|
||||
}
|
||||
}
|
||||
|
||||
const atomCache = new WeakMap<object, Set<string>>();
|
||||
|
||||
/** Distinct atoms of a value (cached for arrays and dicts). */
|
||||
export function valueAtoms(value: unknown): Set<string> {
|
||||
if (value === null || typeof value !== "object") {
|
||||
return new Set([atomOf(value)]);
|
||||
}
|
||||
let atoms = atomCache.get(value);
|
||||
if (!atoms) {
|
||||
atoms = new Set();
|
||||
collect(value, atoms);
|
||||
atomCache.set(value, atoms);
|
||||
}
|
||||
return atoms;
|
||||
}
|
||||
|
||||
/** Whether a value contains every selected atom. */
|
||||
export function matchesAtoms(value: unknown, selected: readonly string[]) {
|
||||
if (selected.length === 0) return true;
|
||||
const atoms = valueAtoms(value);
|
||||
return selected.every((atom) => atoms.has(atom));
|
||||
}
|
||||
|
||||
export interface AtomCount {
|
||||
atom: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
/** How many of `values` contain each atom, most common first. */
|
||||
export function countAtoms(values: Iterable<unknown>): AtomCount[] {
|
||||
const counts = new Map<string, number>();
|
||||
for (const value of values) {
|
||||
for (const atom of valueAtoms(value)) {
|
||||
counts.set(atom, (counts.get(atom) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
return [...counts]
|
||||
.map(([atom, count]) => ({ atom, count }))
|
||||
.sort((a, b) => b.count - a.count || a.atom.localeCompare(b.atom));
|
||||
}
|
||||
|
||||
/** Whether every value is the same, e.g. `true` everywhere. */
|
||||
export function isUniform(values: Iterable<unknown>) {
|
||||
let first: string | undefined;
|
||||
for (const value of values) {
|
||||
const json = JSON.stringify(value);
|
||||
if (first === undefined) first = json;
|
||||
else if (json !== first) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
Reference in new issue
Block a user