From de643660e361f9eaebb117471e4985032c13968d Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:27:21 +0100 Subject: [PATCH 1/6] Give the locked graph, the chains of wf why and the details of wf info as values (#683) wf list --tree, wf why and wf info are now written from dependencyGraph(), whyChains() and packageDetails(), which the Packages panel of the inspectors reads too: the text of the three commands is unchanged. --- js/developer/environment/dependencies.mjs | 162 +++++++++++++------- test/developer/specs/dependencies-specs.mjs | 56 ++++++- 2 files changed, 162 insertions(+), 56 deletions(-) diff --git a/js/developer/environment/dependencies.mjs b/js/developer/environment/dependencies.mjs index 41810310..ce3e0934 100644 --- a/js/developer/environment/dependencies.mjs +++ b/js/developer/environment/dependencies.mjs @@ -1,5 +1,6 @@ -// The installed packages as a graph, read from the lock alone: wf list --tree, wf why and wf info. The lock records, for -// every package, the exact package each of its dependencies and satisfied peers resolved to. +// The installed packages as a graph, read from the lock alone: wf list --tree, wf why, wf info and the Packages panel of the +// inspectors (inspector-packages.mjs). The lock records, for every package, the exact package each of its dependencies and +// satisfied peers resolved to. import {packageRoot} from './paths.mjs'; import {inline} from './terminal.mjs'; @@ -7,47 +8,70 @@ const byName = (a, b) => a < b ? -1 : a > b ? 1 : 0; // Everything shown comes from the lock, so from the package.json of packages: control characters are made visible. const idOf = node => inline(`${node.name}@${node.version}`); -// How a package asks for one of its dependencies: the range of its package.json, marked when it is a peer. -function request(node, name) { +// How a package asks for one of its dependencies: the range of its package.json and the kind of the dependency. +function asked(node, name) { const manifest = node.manifest ?? {}; - if (manifest.dependencies?.[name] !== undefined) return inline(manifest.dependencies[name]); - if (manifest.optionalDependencies?.[name] !== undefined) return inline(`optional ${manifest.optionalDependencies[name]}`); - if (manifest.peerDependencies?.[name] !== undefined) return inline(`peer ${manifest.peerDependencies[name]}`); - return ''; + if (manifest.dependencies?.[name] !== undefined) return {kind: 'dependency', range: inline(manifest.dependencies[name])}; + if (manifest.optionalDependencies?.[name] !== undefined) return {kind: 'optional', range: inline(manifest.optionalDependencies[name])}; + if (manifest.peerDependencies?.[name] !== undefined) return {kind: 'peer', range: inline(manifest.peerDependencies[name])}; + return {kind: 'dependency', range: ''}; } +// The same as wf writes it: the range, marked when it is optional or a peer. +const written = ({kind, range}) => kind === 'dependency' ? range : `${kind} ${range}`; +const request = (node, name) => written(asked(node, name)); const requested = range => range ? ` (${inline(range)})` : ''; const edges = node => Object.entries(node.dependencies ?? {}).sort(([a], [b]) => byName(a, b)); /** - * The locked graph as a tree under the roots of the manifest, each with the range it was requested with. A package - * is opened once: where it comes again, "deduped" stands for the dependencies already shown. + * The locked graph as a tree under the roots of the manifest, for wf list --tree and for the Packages panel of the + * inspectors (#683). A package is opened once: where it comes again, `deduped` stands for the dependencies already shown + * and `children` is empty. Each node is {id, name, version, label, kind, range, requested, deduped, versions, children}: + * `kind` is 'root', 'dependency', 'optional' or 'peer', `range` what asks for it, `requested` the two as wf writes them, + * `versions` how many versions of that name are locked. `label` and the ranges have their control characters made visible. */ -export function dependencyTree(lock) { - const roots = Object.entries(lock?.roots ?? {}).sort(([a], [b]) => byName(a, b)); - if (!roots.length) return 'No installed packages.'; - const lines = [], opened = new Set(); - const children = (id, prefix) => { - const node = lock.packages[id]; - const list = edges(node); - list.forEach(([name, child], index) => { - const last = index === list.length - 1; - const childNode = lock.packages[child]; - const again = opened.has(child) && edges(childNode).length > 0; - lines.push(`${prefix}${last ? '└── ' : '├── '}${idOf(childNode)}${requested(request(node, name))}${again ? ' deduped' : ''}`); - if (opened.has(child)) return; - opened.add(child); - children(child, prefix + (last ? ' ' : '│ ')); - }); +export function dependencyGraph(lock) { + const packages = lock?.packages ?? {}; + const versions = new Map(); + for (const node of Object.values(packages)) versions.set(node.name, (versions.get(node.name) ?? 0) + 1); + const opened = new Set(); + const open = (id, kind, range, requested) => { + const node = packages[id]; + const deduped = opened.has(id) && edges(node).length > 0; + const entry = {id, name: node.name, version: node.version, label: idOf(node), kind, range, requested, deduped, + versions: versions.get(node.name), children: []}; + if (opened.has(id)) return entry; + opened.add(id); + for (const [name, child] of edges(node)) { + const how = asked(node, name); + entry.children.push(open(child, how.kind, how.range, written(how))); + } + return entry; }; - for (const [, root] of roots) { - const again = opened.has(root.id) && edges(lock.packages[root.id]).length > 0; - lines.push(`${idOf(lock.packages[root.id])}${requested(root.requested)}${again ? ' deduped' : ''}`); - if (opened.has(root.id)) continue; - opened.add(root.id); - children(root.id, ''); + const roots = Object.entries(lock?.roots ?? {}).sort(([a], [b]) => byName(a, b)) + .map(([, root]) => { + const range = root.requested ? inline(root.requested) : ''; + return open(root.id, 'root', range, range); + }); + return {roots, packages: Object.keys(packages).length}; +} + +/** wf list --tree: the tree of dependencyGraph() as text. */ +export function dependencyTree(lock) { + const graph = dependencyGraph(lock); + if (!graph.roots.length) return 'No installed packages.'; + const lines = []; + const line = entry => `${entry.label}${requested(entry.requested)}${entry.deduped ? ' deduped' : ''}`; + const children = (entry, prefix) => entry.children.forEach((child, index) => { + const last = index === entry.children.length - 1; + lines.push(`${prefix}${last ? '└── ' : '├── '}${line(child)}`); + children(child, prefix + (last ? ' ' : '│ ')); + }); + for (const root of graph.roots) { + lines.push(line(root)); + children(root, ''); } - const count = Object.keys(lock.packages).length; - lines.push('', `${roots.length} ${roots.length === 1 ? 'root' : 'roots'}, ${count} ${count === 1 ? 'package' : 'packages'}`); + const count = graph.packages; + lines.push('', `${graph.roots.length} ${graph.roots.length === 1 ? 'root' : 'roots'}, ${count} ${count === 1 ? 'package' : 'packages'}`); return lines.join('\n'); } @@ -66,29 +90,35 @@ const dependents = (lock, id) => Object.entries(lock.packages) export const chainLimit = 20; -// The chains of dependents from a package up to the roots, each written from its root down. -function chains(lock, target) { +/** + * The chains of dependents from a locked package up to the roots, each from its root down, `chainLimit` at most (`limited` + * says that there may be more). A link is {id, label, note}: `note` is how the package above asks for it, or for a root + * "root" and the range of the manifest. + */ +export function whyChains(lock, target) { const found = []; + const link = (id, note) => ({id, label: idOf(lock.packages[id]), note}); const climb = (id, below, seen) => { if (found.length >= chainLimit) return; for (const [, root] of rootsOf(lock, id)) - found.push([`${idOf(lock.packages[id])} (root${root.requested ? `, ${inline(root.requested)}` : ''})`, ...below]); + found.push([link(id, `root${root.requested ? `, ${inline(root.requested)}` : ''}`), ...below]); for (const {parent, node, name} of dependents(lock, id)) { if (seen.has(parent)) continue; // a cycle of peers: the chain through it was already taken - climb(parent, [`${idOf(lock.packages[id])}${request(node, name) ? ` (${request(node, name)})` : ''}`, ...below], new Set([...seen, parent])); + climb(parent, [link(id, request(node, name)), ...below], new Set([...seen, parent])); } }; climb(target, [], new Set([target])); - return found.slice(0, chainLimit); + const chains = found.slice(0, chainLimit); + return {chains, limited: chains.length === chainLimit}; } /** wf why : why each locked version of it is installed, as chains from the roots of the manifest. */ export function why(lock, spec) { return selectPackages(lock, spec).map(([id, node]) => { - const found = chains(lock, id); - const lines = found.map(chain => ` ${chain.join(' > ')}`); - if (!found.length) lines.push(' nothing requires it: wf install --update resolves the manifest again'); - if (found.length === chainLimit) lines.push(` ... only the first ${chainLimit} chains are shown`); + const {chains, limited} = whyChains(lock, id); + const lines = chains.map(chain => ` ${chain.map(({label, note}) => `${label}${note ? ` (${note})` : ''}`).join(' > ')}`); + if (!chains.length) lines.push(' nothing requires it: wf install --update resolves the manifest again'); + if (limited) lines.push(` ... only the first ${chainLimit} chains are shown`); return [idOf(node), ...lines].join('\n'); }).join('\n'); } @@ -105,23 +135,45 @@ function executables(node) { return bin && typeof bin === 'object' && !Array.isArray(bin) ? Object.keys(bin).map(inline) : []; } +/** + * What the lock records of one locked package, for wf info and for the Packages panel: {id, name, version, label, roots (the + * ranges of the manifest that ask for it), description, license, integrity, files, directory, dependencies ({id, label, + * request}), dependents ({id, label}), executables ({name, command})}. Every text has its control characters made visible. + */ +export function packageDetails(lock, id) { + const node = lock.packages[id]; + const bins = executables(node); + const neededBy = new Map(dependents(lock, id).map(({parent, node: above}) => [parent, {id: parent, label: idOf(above)}])); + return { + id, name: inline(node.name), version: inline(node.version), label: idOf(node), + roots: rootsOf(lock, id).map(([, root]) => inline(root.requested)), + description: typeof node.manifest?.description === 'string' ? inline(node.manifest.description) : '', + license: license(node.manifest), + integrity: inline(node.integrity), + files: node.files.map(inline), + directory: `${packageRoot}/${inline(node.key)}/`, + dependencies: edges(node).map(([name, child]) => ({id: child, label: idOf(lock.packages[child]), request: request(node, name)})), + dependents: [...neededBy.values()], + executables: bins.map(name => ({name, command: `wf exec ${inline(node.name)}${bins.length > 1 ? `:${name}` : ''}`})), + }; +} + /** wf info : what the lock records of each locked version of it. */ export function info(lock, spec) { - return selectPackages(lock, spec).map(([id, node]) => { - const roots = rootsOf(lock, id); - const needs = edges(node).map(([name, child]) => `${idOf(lock.packages[child])}${request(node, name) ? ` (${request(node, name)})` : ''}`); - const neededBy = [...new Set(dependents(lock, id).map(({node: parent}) => idOf(parent)))]; - const bins = executables(node); + return selectPackages(lock, spec).map(([id]) => { + const details = packageDetails(lock, id); + const needs = details.dependencies.map(({label, request: how}) => `${label}${how ? ` (${how})` : ''}`); + const neededBy = [...new Set(details.dependents.map(({label}) => label))]; const rows = [ - ['root', roots.length ? `yes, requested ${roots.map(([, root]) => inline(root.requested)).join(', ')}` : 'no, installed for another package (wf why)'], - ...(typeof node.manifest?.description === 'string' && node.manifest.description ? [['description', inline(node.manifest.description)]] : []), - ['license', license(node.manifest)], - ['integrity', inline(node.integrity)], - ['files', `${node.files.length} in ${packageRoot}/${inline(node.key)}/`], + ['root', details.roots.length ? `yes, requested ${details.roots.join(', ')}` : 'no, installed for another package (wf why)'], + ...(details.description ? [['description', details.description]] : []), + ['license', details.license], + ['integrity', details.integrity], + ['files', `${details.files.length} in ${details.directory}`], ['dependencies', needs.join(', ') || 'none'], ['dependents', neededBy.join(', ') || 'none'], - ...(bins.length ? [['executables', bins.map(name => `wf exec ${inline(node.name)}${bins.length > 1 ? `:${name}` : ''}`).join(', ')]] : []), + ...(details.executables.length ? [['executables', details.executables.map(({command}) => command).join(', ')]] : []), ]; - return [idOf(node), ...rows.map(([label, value]) => ` ${label.padEnd(12)} ${value}`)].join('\n'); + return [details.label, ...rows.map(([label, value]) => ` ${label.padEnd(12)} ${value}`)].join('\n'); }).join('\n'); } diff --git a/test/developer/specs/dependencies-specs.mjs b/test/developer/specs/dependencies-specs.mjs index 5b0bebd5..7db54ece 100644 --- a/test/developer/specs/dependencies-specs.mjs +++ b/test/developer/specs/dependencies-specs.mjs @@ -1,5 +1,5 @@ // Specs of the dependency graph read from the lock (dependencies.mjs): wf list --tree, wf why and wf info. -import {dependencyTree, why, info, selectPackages, chainLimit} from '../../../js/developer/environment/dependencies.mjs'; +import {dependencyTree, dependencyGraph, whyChains, packageDetails, why, info, selectPackages, chainLimit} from '../../../js/developer/environment/dependencies.mjs'; import {throws} from '../support.mjs'; describe('The graph of the installed packages', () => { @@ -47,6 +47,60 @@ describe('The graph of the installed packages', () => { }); }); + describe('as a graph, for the Packages panel', () => { + const flat = (entries, depth = 0) => entries.flatMap(entry => [ + [depth, entry.label, entry.kind, entry.range, entry.deduped, entry.versions], ...flat(entry.children, depth + 1)]); + + it('gives the roots with their ranges, the peers, the packages already opened and the versions of a name', () => { + const graph = dependencyGraph(lock); + expect(graph.packages).toBe(5); + expect(flat(graph.roots)).toEqual([ + [0, '@app/kit@1.0.0', 'root', 'latest', false, 1], + [1, 'react-dom@19.3.1', 'dependency', '19.x', false, 1], + [2, 'react@19.3.1', 'peer', '^19.3.1', false, 1], + [2, 'scheduler@0.28.0', 'dependency', '^0.28.0', false, 2], + [1, 'scheduler@0.20.0', 'dependency', '~0.20.0', false, 2], + [0, 'react@19.3.1', 'root', '^19.3.1', false, 1], + [0, 'react-dom@19.3.1', 'root', '^19.3.1', true, 1], + ]); + // A package that comes again is not opened again: its dependencies stay where it came first. + expect(graph.roots[2].children).toEqual([]); + expect(graph.roots[0].children[0].id).toBe('react-dom@19.3.1'); + expect(graph.roots[0].children[0].requested).toBe('19.x'); + expect(graph.roots[0].children[0].children[0].requested).toBe('peer ^19.3.1'); + }); + + it('marks an optional dependency, is empty without a lock, and shows the control characters of a range', () => { + expect(dependencyGraph(null)).toEqual({roots: [], packages: 0}); + const optional = {roots: {a: {requested: '1\x1b[2J', id: 'a@1'}}, + packages: {'a@1': node('a', '1', {b: 'b@1', c: 'c@1'}, {optionalDependencies: {b: '^1'}}), 'b@1': node('b', '1'), 'c@1': node('c', '1')}}; + const [root] = dependencyGraph(optional).roots; + expect(root.range).toBe('1^[[2J'); + expect(root.children.map(child => [child.label, child.kind, child.range, child.requested])) + .toEqual([['b@1', 'optional', '^1', 'optional ^1'], ['c@1', 'dependency', '', '']]); + }); + + it('gives the chains of wf why as links to the packages, and what wf info says as values', () => { + const {chains, limited} = whyChains(lock, 'scheduler@0.28.0'); + expect(limited).toBeFalse(); + expect(chains).toEqual([ + [{id: 'react-dom@19.3.1', label: 'react-dom@19.3.1', note: 'root, ^19.3.1'}, {id: 'scheduler@0.28.0', label: 'scheduler@0.28.0', note: '^0.28.0'}], + [{id: '@app+kit@1.0.0', label: '@app/kit@1.0.0', note: 'root, latest'}, {id: 'react-dom@19.3.1', label: 'react-dom@19.3.1', note: '19.x'}, + {id: 'scheduler@0.28.0', label: 'scheduler@0.28.0', note: '^0.28.0'}], + ]); + expect(packageDetails(lock, 'react-dom@19.3.1')).toEqual({ + id: 'react-dom@19.3.1', name: 'react-dom', version: '19.3.1', label: 'react-dom@19.3.1', roots: ['^19.3.1'], description: '', + license: 'MIT', integrity: 'sha512-react-dom', files: ['package.json', 'index.js'], + directory: '.webfront/developer/packages/react-dom@19.3.1-key/', + dependencies: [{id: 'react@19.3.1', label: 'react@19.3.1', request: 'peer ^19.3.1'}, {id: 'scheduler@0.28.0', label: 'scheduler@0.28.0', request: '^0.28.0'}], + dependents: [{id: '@app+kit@1.0.0', label: '@app/kit@1.0.0'}], + executables: [], + }); + expect(packageDetails(lock, '@app+kit@1.0.0').executables) + .toEqual([{name: 'make', command: 'wf exec @app/kit:make'}, {name: 'check', command: 'wf exec @app/kit:check'}]); + }); + }); + describe('why', () => { it('gives the chains from the roots to a package, for each of its versions', () => { expect(why(lock, 'scheduler')).toBe([ From 35d84c8685aa3db06b2fd0e368b8899fad7a610e Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:15:46 +0100 Subject: [PATCH 2/6] Packages panel of the inspectors: the locked packages as a tree, with search, detail and wf why chains (#683) The panel reads the manifest and the lock through the project reads of the environment, in the manifest directory of the application, and reads them again when either file changes. The texts of packages are set as text, never as HTML. --- js/developer/environment/bundles.json | 7 +- .../environment/inspector-packages.mjs | 398 ++++++++++++++++++ js/developer/environment/inspector.mjs | 8 +- js/developer/tools/bundle-inputs.json | 1 + js/developer/webfront.project.json | 1 + .../specs/inspector-packages-specs.mjs | 356 ++++++++++++++++ 6 files changed, 765 insertions(+), 6 deletions(-) create mode 100644 js/developer/environment/inspector-packages.mjs create mode 100644 test/developer/specs/inspector-packages-specs.mjs diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 053c5807..f1894268 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -25,13 +25,14 @@ "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", "js/developer/environment/inspector-host.mjs": "bffcef61b8a5778f53adfea5096c5d5fa277868bbaa39e60142a3493210076fb", - "js/developer/environment/inspector.mjs": "47d631dbc0cd3e8a4ef3c2e4883b303804694f790e87dd06799257ec3828d1a8", + "js/developer/environment/inspector.mjs": "e22d5731e7e92b821ccdb15badc2fa4aebba653763239ea813ea904719aca33a", + "js/developer/environment/inspector-packages.mjs": "1c90f9d9c84592cd9372116bcf753ee0914166f218b2f181ffb24e51710f62a0", "js/developer/environment/inspector-registry.mjs": "431153f7d7eb562262361f2f8eb60d8690f42cdfbf5ed9586270270d9e2b6038", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", "js/developer/environment/files.mjs": "199336f7f3d23f6370da352993bf4686738b1f394b79aa9883769d19824540e0", - "js/developer/environment/dependencies.mjs": "4857eb7dfb9f099266c27021ee07a8d9d9a529a8344f3e134d22d7f8b7166e2e", + "js/developer/environment/dependencies.mjs": "7f536e30584b10822dea6b5642fd584e5935c58f90a271ee70a03d3023e9dd34", "js/developer/environment/compiler.mjs": "0158931132aa9b43b7bbbd01de6fa4fc34fce8c65515d593dd494930f7a1910f", "js/developer/environment/bundler.mjs": "48658151aae4fa5ad54c9fa3386ef4095b793de0f3ad242f95e8e5de0cd0ce4d", "js/developer/environment/entry.mjs": "b2b942443e3c74ae2c008392ba244d9b7e91db70ba1b4ebbe1357c455ebf51bb", @@ -54,7 +55,7 @@ "js/developer/tools/archive.mjs": "da63bb9d796ddfd24ed945b15c53f66a0400eb177886fd4f1c8fd10cafb5a91b", "js/developer/tools/distribution.mjs": "43dfdccc912693db46fd095fd78ae79325abab672d99f89fd569914ef3499cad", "js/developer/scripts/build.mjs": "a6b64a8a75c9a30118e7f5c843a0feee89ee1372ccd19b7e468c816b23fd1367", - "js/developer/webfront.project.json": "1c6ac7dbb4282692f3f23d3e598d00735dfc99b72d7f1072f7438d29beceb7c1", + "js/developer/webfront.project.json": "2464bfd479cc8cb929dd51b7efa6363aed106dbadfd4a6bd7ef6a3f8287a69ae", "js/core/bootstrap/bootstrap.bundle.mjs": "18a0567efa928fddbaa3f8d16a4d1e8440f21709ff2e3058d10ba406b2e9b66d", "js/developer/environment/packages.bundle.mjs": "5598a590a9e859a4128075387a6c32963b2246ca120c2d7775851c780ad437f2", "include/webfront/system/DeveloperReleaseData.hpp": "8b3c8800211c13b1984e794de6110d56238e9fb1cfb16afbc2868d57eb91c70e" diff --git a/js/developer/environment/inspector-packages.mjs b/js/developer/environment/inspector-packages.mjs new file mode 100644 index 00000000..6ef2e0d4 --- /dev/null +++ b/js/developer/environment/inspector-packages.mjs @@ -0,0 +1,398 @@ +// The Packages panel of the inspectors (#683, ADR-027): the locked packages as a tree that can be walked, what wf list --tree, +// wf why and wf info say as text. It reads the manifest and the lock through the bridge (the reads of the project, which no +// function of the inspectors replaces), never the network, and writes nothing; it reads them again when either file changes +// (wf install, wf restore). Everything shown comes from the package.json of packages, which are not trusted: it is set as +// text, never as HTML, with its control characters made visible (dependencies.mjs). +import {call} from './io.mjs'; +import {setManifestDirectory, manifestPath, lockPath} from './manifest.mjs'; +import {loadProject, desynchronized} from './project.mjs'; +import {dependencyGraph, packageDetails, whyChains, chainLimit} from './dependencies.mjs'; +import {inline} from './terminal.mjs'; + +/** How often the panel asks whether the manifest or the lock changed: one call, the files are read only after a change. */ +export const lockPeriod = 1000; + +/** + * The directory of the manifest and of the lock that the application chose, as the terminal reads it from the bootstrap's + * configuration; the project root when the application says nothing, or when the configuration cannot be read. + */ +export async function manifestDirectory(bridge) { + try { return JSON.parse(await call(bridge, 'config'))?.manifestDirectory; } + catch { return undefined; } +} + +/** The project of the page: its manifest, its lock and the token of their state (project.mjs), read where the application said. */ +export async function readPackages(bridge) { + setManifestDirectory(await manifestDirectory(bridge)); + return loadProject(bridge); +} + +/** The token of the state that readPackages() read (`project.token`): it changes when the manifest or the lock does. */ +export const packagesState = bridge => call(bridge, 'state', `${manifestPath}\n${lockPath}`); + +/** + * The locked packages whose name contains `query`, whatever the case, sorted by name then version; all of them for no query. + * Each is {id, label, root, versions}: whether the manifest asks for it, and how many versions of its name are locked. + */ +export function searchPackages(lock, query) { + const wanted = String(query ?? '').trim().toLowerCase(); + const versions = new Map(); + const all = Object.entries(lock?.packages ?? {}); + for (const [, node] of all) versions.set(node.name, (versions.get(node.name) ?? 0) + 1); + const roots = new Set(Object.values(lock?.roots ?? {}).map(root => root.id)); + const order = (a, b) => a < b ? -1 : a > b ? 1 : 0; + return all.filter(([, node]) => node.name.toLowerCase().includes(wanted)) + .sort(([, a], [, b]) => order(a.name, b.name) || order(a.version, b.version)) + .map(([id, node]) => ({id, label: inline(`${node.name}@${node.version}`), root: roots.has(id), versions: versions.get(node.name)})); +} + +/** The path of a node of the tree, which names one of the places a package is shown at: the ids from its root down. */ +const pathOf = (parent, id) => parent ? `${parent}>${id}` : id; + +export const packagesStyles = ` +.packages-layout{display:grid;grid-template-columns:minmax(0,1fr);gap:12px} +@media (min-width:720px){.packages-layout{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}} +ul.packages,ul.packages ul,ul.matches,ol.chains,ul.files{list-style:none;margin:0;padding:0} +ul.packages ul{padding-left:18px} +ul.packages li>.row{display:flex;flex-wrap:wrap;align-items:center;gap:2px 8px;min-height:28px;padding:0 4px;border-radius:4px;cursor:pointer} +ul.packages li:focus{outline:none} +ul.packages li:focus-visible>.row{outline:2px solid #d7fa85;outline-offset:-2px} +ul.packages li[aria-selected=true]>.row,ul.matches button[aria-pressed=true]{background:#2f3a50} +ul.packages .twisty{flex:0 0 14px;color:#a9b3c4;text-align:center} +ul.packages li[aria-expanded=false]>ul{display:none} +.package-name{font-family:ui-monospace,monospace;font-size:13px;overflow-wrap:anywhere} +.package-range{color:#a9b3c4;font-family:ui-monospace,monospace;font-size:12px} +.badge{padding:0 6px;border:1px solid #46536a;border-radius:8px;color:#a9b3c4;font-size:11px;white-space:nowrap} +.badge.peer{color:#8fd0ff;border-color:#8fd0ff} +.badge.versions{color:#ffbd2e;border-color:#ffbd2e} +ul.matches button,.package-detail button.package-link{min-height:28px;padding:0 6px;border:0;border-radius:4px;background:none;color:#8fd0ff;font:13px ui-monospace,monospace;text-align:left;cursor:pointer;overflow-wrap:anywhere} +ul.matches li{display:flex;flex-wrap:wrap;align-items:center;gap:2px 8px} +ul.matches button:focus-visible,.package-detail button:focus-visible{outline:2px solid #d7fa85;outline-offset:-2px} +.package-detail{min-width:0;padding:8px 12px;border:1px solid #2f3a50;border-radius:4px;align-self:start} +.package-detail h2{margin:0 0 4px;font:600 14px ui-monospace,monospace;overflow-wrap:anywhere} +.package-detail h3{margin:12px 0 4px;font-size:12px;font-weight:600;color:#a9b3c4} +.package-detail p{margin:0 0 8px} +.package-detail dl{display:grid;grid-template-columns:auto minmax(0,1fr);gap:4px 12px;margin:0} +.package-detail dt{color:#a9b3c4;font-size:12px} +.package-detail dd{margin:0;overflow-wrap:anywhere} +.package-detail .code{font-family:ui-monospace,monospace;font-size:12px} +.package-detail .note,ul.matches .note{color:#a9b3c4;font-size:12px} +ol.chains li{padding:2px 0;border-bottom:1px solid #2f3a50} +ul.files{max-height:12em;overflow:auto;font-family:ui-monospace,monospace;font-size:12px}`; + +/** + * Shows the panel in `body`. `load(bridge)` reads the project and `state(bridge)` the token of its state (tests replace + * them). Resolves, once the packages are shown or the first read failed, with the parts of the panel and: + * `select(id)`: shows a package in the detail and at its first place in the tree; false when it is not locked; + * `refresh()`: asks whether the lock changed and reads it again if it did (what the timer does every `lockPeriod`); + * `settled()`: resolves once the read in progress is over; `stop()`: ends the reads (the page that hides calls it). + */ +export async function showPackagesPanel({page, view, body, status, bridge, load = readPackages, state = packagesState}) { + const element = (tag, className, text) => { + const made = page.createElement(tag); + if (className) made.className = className; + if (text !== undefined) made.textContent = text; // text of a package: never parsed as HTML + return made; + }; + const search = element('input'); + search.type = 'search'; + search.placeholder = 'Search a package by name'; + search.setAttribute('aria-label', 'Search a package by name'); + const toolbar = element('div', 'toolbar'); + toolbar.append(search); + const summary = element('p', 'summary'); + const layout = element('div', 'packages-layout'); + const lists = element('div'); + const tree = element('ul', 'packages'); + tree.setAttribute('role', 'tree'); + tree.setAttribute('aria-label', 'Locked packages, under the roots of the manifest'); + const matches = element('ul', 'matches'); + matches.setAttribute('aria-label', 'Packages found'); + matches.hidden = true; + lists.append(tree, matches); + const detail = element('section', 'package-detail'); + detail.setAttribute('aria-label', 'Package'); + detail.hidden = true; + layout.append(lists, detail); + body.append(toolbar, summary, layout); + + let project = null, graph = {roots: [], packages: 0}, selected = null; + const collapsed = new Set(); // by path, so that a package folded at one place stays folded when the lock is read again + const lock = () => project?.lock ?? null; + const items = () => [...tree.querySelectorAll('[role=treeitem]')]; + const parentItem = item => item.parentElement.closest('[role=treeitem]'); + const visible = () => items().filter(item => { + for (let above = parentItem(item); above; above = parentItem(above)) + if (above.getAttribute('aria-expanded') === 'false') return false; + return true; + }); + // The place where a package is opened, its dependencies listed under it; any place when it has none. + const first = id => items().find(item => item.dataset.package === id && item.dataset.deduped !== 'true') ?? null; + const focusable = item => { + for (const other of items()) other.tabIndex = other === item ? 0 : -1; + }; + const setExpanded = (item, expanded) => { + if (!item.hasAttribute('aria-expanded')) return; + item.setAttribute('aria-expanded', String(expanded)); + item.querySelector('.twisty').textContent = expanded ? '▾' : '▸'; + if (expanded) collapsed.delete(item.dataset.path); else collapsed.add(item.dataset.path); + }; + const reveal = item => { + for (let above = parentItem(item); above; above = parentItem(above)) setExpanded(above, true); + }; + + const badge = (className, text, title) => { + const made = element('span', `badge ${className}`, text); + made.title = title; + return made; + }; + const versionsBadge = count => badge('versions', `${count} versions`, 'Several versions of this package are locked'); + const link = (id, label) => { + const button = element('button', 'package-link', label); + button.type = 'button'; + button.dataset.package = id; + button.addEventListener('click', () => select(id)); + return button; + }; + + function renderDetail() { + const current = lock(); + if (!selected || !current?.packages[selected]) { + selected = null; + detail.hidden = true; + detail.replaceChildren(); + return; + } + const details = packageDetails(current, selected); + const row = (term, ...values) => { + const value = element('dd'); + value.append(...values); + return [element('dt', '', term), value]; + }; + const links = (list, note) => list.length ? list.flatMap((entry, index) => [ + ...(index ? [', '] : []), link(entry.id, entry.label), ...(note(entry) ? [element('span', 'note', ` (${note(entry)})`)] : [])]) : ['none']; + const rows = element('dl'); + rows.append( + ...row('Root', details.roots.length ? `yes, requested ${details.roots.join(', ')}` : 'no, installed for another package'), + ...row('License', details.license), + ...row('Integrity', element('span', 'code', details.integrity)), + ...row('Directory', element('span', 'code', details.directory)), + ...row('Dependencies', ...links(details.dependencies, entry => entry.request)), + ...row('Dependents', ...links(details.dependents, () => '')), + ...(details.executables.length ? row('Executables', ...details.executables.flatMap(({command}, index) => + [...(index ? [', '] : []), element('span', 'code', command)])) : [])); + const {chains, limited} = whyChains(current, selected); + const why = element('ol', 'chains'); + why.setAttribute('aria-label', 'Why it is installed'); + for (const chain of chains) { + const item = element('li'); + chain.forEach((step, index) => item.append(...(index ? [' > '] : []), link(step.id, step.label), + ...(step.note ? [element('span', 'note', ` (${step.note})`)] : []))); + why.append(item); + } + const files = element('details', 'package-files'); + files.append(element('summary', '', `${details.files.length} ${details.files.length === 1 ? 'file' : 'files'}`)); + const fileList = element('ul', 'files'); + for (const path of details.files) fileList.append(element('li', '', path)); + files.append(fileList); + detail.replaceChildren(element('h2', '', details.label), ...(details.description ? [element('p', 'description', details.description)] : []), rows, + element('h3', '', 'Why it is installed (wf why)'), why, + ...(chains.length ? [] : [element('p', 'note', 'Nothing requires it: wf install --update resolves the manifest again.')]), + ...(limited ? [element('p', 'note', `Only the first ${chainLimit} chains are shown.`)] : []), + element('h3', '', 'Files'), files); + detail.hidden = false; + } + + function markSelected() { + for (const item of items()) item.setAttribute('aria-selected', String(item.dataset.package === selected)); + for (const button of matches.querySelectorAll('button')) button.setAttribute('aria-pressed', String(button.dataset.package === selected)); + } + + /** Shows a locked package: its detail, and the place of the tree where its dependencies are listed. */ + function select(id) { + if (!lock()?.packages[id]) return false; + selected = id; + const item = first(id); + if (item) { + reveal(item); + focusable(item); + if (!tree.hidden) item.scrollIntoView?.({block: 'nearest'}); + } + markSelected(); + renderDetail(); + return true; + } + + function renderTree() { + const build = (entry, parent, level) => { + const item = element('li'); + const path = pathOf(parent, entry.id); + item.setAttribute('role', 'treeitem'); + item.setAttribute('aria-level', String(level)); + item.setAttribute('aria-selected', 'false'); + item.tabIndex = -1; + item.dataset.package = entry.id; + item.dataset.path = path; + if (entry.deduped) item.dataset.deduped = 'true'; + const twisty = element('span', 'twisty', entry.children.length ? (collapsed.has(path) ? '▸' : '▾') : ''); + twisty.setAttribute('aria-hidden', 'true'); + const row = element('div', 'row'); + row.append(twisty, element('span', 'package-name', entry.label)); + if (entry.range) row.append(element('span', 'package-range', entry.range)); + if (entry.kind === 'peer') row.append(badge('peer', 'peer', 'A peer dependency: the package uses the one its dependent installs')); + if (entry.kind === 'optional') row.append(badge('optional', 'optional', 'An optional dependency')); + if (entry.deduped) row.append(badge('deduped', 'deduped', 'Its dependencies are listed where it comes first: the Right arrow goes there')); + if (entry.versions > 1) row.append(versionsBadge(entry.versions)); + item.append(row); + if (entry.children.length) { + item.setAttribute('aria-expanded', String(!collapsed.has(path))); + const group = element('ul'); + group.setAttribute('role', 'group'); + for (const child of entry.children) group.append(build(child, path, level + 1)); + item.append(group); + } + return item; + }; + tree.replaceChildren(...graph.roots.map(root => build(root, '', 1))); + // Paths that no longer exist are forgotten, so that the set stays bounded by the tree shown. + const paths = new Set(items().map(item => item.dataset.path)); + for (const path of [...collapsed]) if (!paths.has(path)) collapsed.delete(path); + const start = (selected && first(selected)) || items()[0]; + if (start) focusable(start); + } + + function renderMatches() { + const query = search.value.trim(); + tree.hidden = Boolean(query); + matches.hidden = !query; + if (!query) { + matches.replaceChildren(); + return; + } + const found = searchPackages(lock(), query); + matches.replaceChildren(...found.map(match => { + const item = element('li'); + const button = link(match.id, match.label); + button.setAttribute('aria-pressed', String(match.id === selected)); + item.append(button); + if (match.root) item.append(badge('root', 'root', 'A root of the manifest')); + if (match.versions > 1) item.append(versionsBadge(match.versions)); + return item; + })); + if (!found.length) matches.append(element('li', 'note', 'No locked package has this name.')); + } + + function describe() { + status.classList.remove('error'); + const count = graph.packages, roots = graph.roots.length; + summary.textContent = roots ? `${roots} ${roots === 1 ? 'root' : 'roots'}, ${count} ${count === 1 ? 'package' : 'packages'}` : ''; + if (project.status === 'no-manifest' && !roots) status.textContent = 'This project has no webfront.project.json: wf init creates it.'; + else if (project.status === 'desynchronized') status.textContent = `Warning: ${desynchronized}.`; + else status.textContent = roots ? '' : 'No installed packages: wf install adds one.'; + } + + function render() { + graph = dependencyGraph(lock()); + renderTree(); + renderMatches(); + markSelected(); + renderDetail(); + describe(); + } + + tree.addEventListener('click', event => { + const item = event.target.closest?.('[role=treeitem]'); + if (!item) return; + focusable(item); + if (event.target.classList?.contains('twisty') && item.hasAttribute('aria-expanded')) { + setExpanded(item, item.getAttribute('aria-expanded') === 'false'); + return; + } + selected = item.dataset.package; // the place that was clicked keeps the focus, wherever the package is opened + markSelected(); + renderDetail(); + item.focus?.(); + }); + tree.addEventListener('keydown', event => { + const item = event.target.closest?.('[role=treeitem]'); + if (!item) return; + const shown = visible(), index = shown.indexOf(item); + const go = target => { + if (!target) return; + focusable(target); + target.focus(); + }; + const expanded = item.getAttribute('aria-expanded'); + if (event.key === 'ArrowDown') go(shown[index + 1]); + else if (event.key === 'ArrowUp') go(shown[index - 1]); + else if (event.key === 'Home') go(shown[0]); + else if (event.key === 'End') go(shown.at(-1)); + else if (event.key === 'ArrowRight') { + if (expanded === 'false') setExpanded(item, true); + else if (expanded === 'true') go(shown[index + 1]); + else if (item.dataset.deduped === 'true') { + const place = first(item.dataset.package); + if (place) reveal(place); + go(place); + } + } else if (event.key === 'ArrowLeft') { + if (expanded === 'true') setExpanded(item, false); + else go(parentItem(item)); + } else if (event.key === 'Enter' || event.key === ' ') { + selected = item.dataset.package; + markSelected(); + renderDetail(); + } else return; + event.preventDefault(); + }); + search.addEventListener('input', renderMatches); + + // One chain of reads: the token of the state is asked every period, and the files are read only when it changed. + let timer = null, stopped = false, running = null; + const fail = error => { + if (stopped) return; + status.classList.add('error'); + status.textContent = `The packages cannot be read: ${error?.message ?? error}`; + }; + async function read() { + const loaded = await load(bridge); + if (stopped) return; + project = loaded; + render(); + } + async function check() { + // A project that could not be read is read again; one that was is read again when its manifest or its lock changed. + if (project && await state(bridge) === project.token) { + if (!stopped && status.classList.contains('error')) describe(); + return; + } + if (!stopped) await read(); + } + function schedule() { + if (stopped || timer !== null || running !== null) return; + timer = view.setTimeout(() => { + timer = null; + refresh(); + }, lockPeriod); + } + const follow = reading => running = reading.catch(fail).finally(() => { + running = null; + schedule(); + }); + function refresh() { + if (stopped) return Promise.resolve(); + if (running) return running; + view.clearTimeout(timer); + timer = null; + return follow(check()); + } + const stop = () => { + stopped = true; + view.clearTimeout(timer); + timer = null; + }; + view.addEventListener('pagehide', stop); + await follow(read()); + return {search, tree, matches, detail, summary, select, refresh, stop, settled: () => running ?? Promise.resolve(), + get selected() { return selected; }}; +} diff --git a/js/developer/environment/inspector.mjs b/js/developer/environment/inspector.mjs index 3d16167f..f63bb1dc 100644 --- a/js/developer/environment/inspector.mjs +++ b/js/developer/environment/inspector.mjs @@ -2,9 +2,11 @@ // bridge. In a window or a tab of its own it opens its own connection; in the floating window of a page (?frame=1) it opens // none and borrows that page's bridge, since the adapters give the proof of the view to the main frame only. The panel of the // watches lists them by webfront.inspector.watches and follows the registrations and removals (section 3, "Découverte"). The -// panels of the functions and of the browsers are in inspector-registry.mjs (#681, section 7). +// panels of the functions and of the browsers are in inspector-registry.mjs (#681, section 7), the one of the packages in +// inspector-packages.mjs (#683). import {inspectorPanels as panels, panelTitle, inspectorChannel as channelName} from './menu.mjs'; import {showFunctionsPanel, showBrowsersPanel, registryStyles} from './inspector-registry.mjs'; +import {showPackagesPanel, packagesStyles} from './inspector-packages.mjs'; // --- Bridge ---------------------------------------------------------------------------------------------------- @@ -198,7 +200,6 @@ ul.watches .location{grid-column:1/3;color:#a9b3c4;font-size:12px;overflow-wrap: ul.watches .writable{color:#8fd0ff;font-size:12px}`; const placeholders = { - 'typescript.packages': 'The tree of the locked packages comes with the next versions of the environment.', 'typescript.bridge': 'The state of the bridge in the page comes with the next versions of the environment.', }; @@ -254,7 +255,7 @@ export async function main(view = window) { page.title = `WebFront inspector: ${panelTitle(id)}`; reloadWhenRestored(view); const style = page.createElement('style'); - style.textContent = styles + registryStyles; + style.textContent = styles + registryStyles + packagesStyles; page.head.append(style); const header = page.createElement('header'); const heading = page.createElement('h1'); @@ -303,6 +304,7 @@ export async function main(view = window) { const show = id === 'cpp.functions' ? showFunctionsPanel : showBrowsersPanel; return {bridge, ...await show({page, view, header, body, status, bridge})}; } + if (id === 'typescript.packages') return {bridge, ...await showPackagesPanel({page, view, header, body, status, bridge})}; if (id !== 'cpp.watches') { status.textContent = placeholders[id]; return {bridge}; diff --git a/js/developer/tools/bundle-inputs.json b/js/developer/tools/bundle-inputs.json index cdd1b0f4..e27dbc34 100644 --- a/js/developer/tools/bundle-inputs.json +++ b/js/developer/tools/bundle-inputs.json @@ -26,6 +26,7 @@ "js/developer/environment/menu.mjs", "js/developer/environment/inspector-host.mjs", "js/developer/environment/inspector.mjs", + "js/developer/environment/inspector-packages.mjs", "js/developer/environment/inspector-registry.mjs", "js/developer/environment/inspector.html", "js/developer/environment/tarball.mjs", diff --git a/js/developer/webfront.project.json b/js/developer/webfront.project.json index d88082ec..27ea4a6f 100644 --- a/js/developer/webfront.project.json +++ b/js/developer/webfront.project.json @@ -34,6 +34,7 @@ "test/developer/specs/workspace-specs.mjs", "test/developer/specs/inspector-specs.mjs", "test/developer/specs/inspector-registry-specs.mjs", + "test/developer/specs/inspector-packages-specs.mjs", "test/developer/specs/files-specs.mjs", "test/developer/specs/dependencies-specs.mjs", "test/developer/specs/distribution-specs.mjs" diff --git a/test/developer/specs/inspector-packages-specs.mjs b/test/developer/specs/inspector-packages-specs.mjs new file mode 100644 index 00000000..da3258eb --- /dev/null +++ b/test/developer/specs/inspector-packages-specs.mjs @@ -0,0 +1,356 @@ +// Specs of the Packages panel of the inspectors (#683): the tree of the locked packages read from the lock through the +// bridge, with its peers, its packages already opened and the versions of a name; the search, the detail of a package with +// the chains of wf why, the read after a change of the lock, and the texts of packages shown as text. The graph itself is in +// dependencies-specs.mjs. +import {showPackagesPanel, searchPackages, readPackages, manifestDirectory, lockPeriod} from '../../../js/developer/environment/inspector-packages.mjs'; +import {main} from '../../../js/developer/environment/inspector.mjs'; +import {idOf, cacheKey} from '../../../js/developer/environment/registry.mjs'; +import {dependenciesDigest, setManifestDirectory} from '../../../js/developer/environment/manifest.mjs'; +import {memoryBridge} from '../memory-bridge.mjs'; + +const encode = text => new TextEncoder().encode(text); + +/** A locked package as wf install records it. */ +const node = (name, version, dependencies = {}, manifest = {}) => { + const integrity = `sha512-${name.replace(/[^a-z]/g, '')}${version.replace(/\D/g, '')}`; + return [idOf(name, version), {name, version, integrity, key: cacheKey(name, version, integrity), files: ['package.json', 'index.js'], + dependencies, manifest: {name, version, ...manifest}}]; +}; + +// react-dom needs scheduler and its peer react; @app/kit needs react-dom and an older scheduler. +const packages = () => Object.fromEntries([ + node('react', '19.3.1', {}, {license: 'MIT', description: 'React'}), + node('react-dom', '19.3.1', {scheduler: 'scheduler@0.28.0', react: 'react@19.3.1'}, + {license: 'MIT', dependencies: {scheduler: '^0.28.0'}, peerDependencies: {react: '^19.3.1'}}), + node('scheduler', '0.28.0', {}, {license: 'MIT'}), + node('scheduler', '0.20.0'), + node('@app/kit', '1.0.0', {'react-dom': 'react-dom@19.3.1', scheduler: 'scheduler@0.20.0'}, + {dependencies: {'react-dom': '19.x', scheduler: '~0.20.0'}, webfront: {bin: {make: 'make.mjs', check: 'check.mjs'}}}), +]); +const dependencies = {react: '^19.3.1', 'react-dom': '^19.3.1', '@app/kit': 'latest'}; +const roots = () => ({ + react: {requested: '^19.3.1', id: 'react@19.3.1'}, + 'react-dom': {requested: '^19.3.1', id: 'react-dom@19.3.1'}, + '@app/kit': {requested: 'latest', id: '@app+kit@1.0.0'}, +}); + +/** Writes a manifest and its lock in the project, in `directory` when the application chose one. */ +async function writeProject(storage, {wanted = dependencies, lockRoots = roots(), locked = packages(), directory = '', digest = wanted} = {}) { + const prefix = directory ? `${directory}/` : ''; + storage.set(`${prefix}webfront.project.json`, encode(JSON.stringify({format: 1, name: 'app', version: '0.1.0', dependencies: wanted}))); + storage.set(`${prefix}webfront-packages.lock.json`, + encode(JSON.stringify({format: 1, manifestDigest: await dependenciesDigest(digest), roots: lockRoots, packages: locked}))); +} + +/** Timers that run only when the spec says so. */ +function manualTimers() { + let pending = null, next = 1; + const delays = []; + return { + delays, + get pending() { return pending !== null; }, + setTimeout(run, delay) { + delays.push(delay); + pending = {id: next, run}; + return next++; + }, + clearTimeout(id) { if (pending?.id === id) pending = null; }, + fire() { + const {run} = pending; + pending = null; + run(); + }, + }; +} + +/** The memory project's bridge, which also counts the calls by function. */ +function countingBridge(storage, extra = {}) { + const {bridge} = memoryBridge(storage); + const calls = []; + return {calls, cppFunction: name => async (...args) => { + calls.push(name); + return extra[name] ? extra[name](...args) : bridge.cppFunction(name)(...args); + }}; +} + +async function setup({storage = new Map(), write = true, extra = {}, ...project} = {}) { + if (write) await writeProject(storage, project); + const timers = manualTimers(), listeners = new Map(); + const view = {setTimeout: timers.setTimeout, clearTimeout: timers.clearTimeout, addEventListener: (name, handler) => listeners.set(name, handler)}; + const body = document.createElement('main'); + const status = document.createElement('p'); + body.append(status); + document.body.append(body); + const bridge = countingBridge(storage, extra); + const panel = await showPackagesPanel({page: document, view, body, status, bridge}); + return {storage, timers, view, listeners, body, status, bridge, panel}; +} + +/** The tree as lines: the depth of each item, its name, its range and its badges. */ +const lines = tree => [...tree.querySelectorAll('[role=treeitem]')].map(item => { + const row = item.querySelector(':scope > .row'); + return [Number(item.getAttribute('aria-level')), row.querySelector('.package-name').textContent, row.querySelector('.package-range')?.textContent ?? '', + [...row.querySelectorAll('.badge')].map(badge => badge.textContent).join(' ')].join('|'); +}); +const item = (tree, label, index = 0) => [...tree.querySelectorAll('[role=treeitem]')] + .filter(candidate => candidate.querySelector(':scope > .row .package-name').textContent === label)[index]; +const key = (target, name) => target.dispatchEvent(new KeyboardEvent('keydown', {key: name, bubbles: true, cancelable: true})); +const rowsOf = detail => Object.fromEntries([...detail.querySelectorAll('dt')].map(term => [term.textContent, term.nextElementSibling.textContent])); + +describe('The Packages panel of the inspectors', () => { + const shown = []; + const open = async options => { + const made = await setup(options); + shown.push(made); + return made; + }; + afterEach(() => { + for (const {panel, body} of shown.splice(0)) { + panel.stop(); + body.remove(); + } + setManifestDirectory(''); + }); + + it('shows the locked packages under the roots of the manifest, with the peers, the packages already opened and the versions of a name', async () => { + const {panel, status} = await open(); + expect(lines(panel.tree)).toEqual([ + '1|@app/kit@1.0.0|latest|', + '2|react-dom@19.3.1|19.x|', + '3|react@19.3.1|^19.3.1|peer', + '3|scheduler@0.28.0|^0.28.0|2 versions', + '2|scheduler@0.20.0|~0.20.0|2 versions', + '1|react@19.3.1|^19.3.1|', + '1|react-dom@19.3.1|^19.3.1|deduped', + ]); + expect(panel.summary.textContent).toBe('3 roots, 5 packages'); + expect(status.textContent).toBe(''); + expect(panel.tree.getAttribute('role')).toBe('tree'); + expect(panel.detail.hidden).toBeTrue(); + // One item takes the Tab key; the packages already opened have nothing to unfold. + expect([...panel.tree.querySelectorAll('[tabindex="0"]')].length).toBe(1); + expect(item(panel.tree, 'react-dom@19.3.1', 1).hasAttribute('aria-expanded')).toBeFalse(); + expect(item(panel.tree, 'react-dom@19.3.1', 0).getAttribute('aria-expanded')).toBe('true'); + }); + + it('reads the lock alone, through the reads of the project, and writes nothing', async () => { + const {bridge, storage} = await open(); + expect([...new Set(bridge.calls)].sort()).toEqual(['webfront.developer.config', 'webfront.developer.read', 'webfront.developer.state']); + expect([...storage.keys()].sort()).toEqual(['webfront-packages.lock.json', 'webfront.project.json']); + }); + + it('shows the detail of a package: what wf info says, and the chains of wf why whose packages open in a click', async () => { + const {panel} = await open(); + item(panel.tree, 'scheduler@0.28.0').querySelector('.package-name').click(); + expect(panel.selected).toBe('scheduler@0.28.0'); + expect(panel.detail.hidden).toBeFalse(); + expect(panel.detail.querySelector('h2').textContent).toBe('scheduler@0.28.0'); + expect(rowsOf(panel.detail)).toEqual({ + Root: 'no, installed for another package', License: 'MIT', Integrity: 'sha512-scheduler0280', + Directory: '.webfront/developer/packages/scheduler@0.28.0-scheduler0280/', Dependencies: 'none', Dependents: 'react-dom@19.3.1'}); + expect([...panel.detail.querySelectorAll('ol.chains li')].map(chain => chain.textContent)).toEqual([ + 'react-dom@19.3.1 (root, ^19.3.1) > scheduler@0.28.0 (^0.28.0)', + '@app/kit@1.0.0 (root, latest) > react-dom@19.3.1 (19.x) > scheduler@0.28.0 (^0.28.0)']); + expect(panel.detail.querySelector('details summary').textContent).toBe('2 files'); + expect([...panel.detail.querySelectorAll('ul.files li')].map(file => file.textContent)).toEqual(['package.json', 'index.js']); + expect(item(panel.tree, 'scheduler@0.28.0').getAttribute('aria-selected')).toBe('true'); + + // A package of a chain: its detail, with its executables, its dependencies and the ranges that ask for them. + [...panel.detail.querySelectorAll('ol.chains button')].find(button => button.textContent === '@app/kit@1.0.0').click(); + expect(panel.selected).toBe('@app+kit@1.0.0'); + const kit = rowsOf(panel.detail); + expect(kit.Root).toBe('yes, requested latest'); + expect(kit.License).toBe('not declared'); + expect(kit.Dependencies).toBe('react-dom@19.3.1 (19.x), scheduler@0.20.0 (~0.20.0)'); + expect(kit.Executables).toBe('wf exec @app/kit:make, wf exec @app/kit:check'); + expect(panel.detail.querySelector('ol.chains').textContent).toBe('@app/kit@1.0.0 (root, latest)'); + // The description of a package, and a package that is not locked. + expect(panel.select('react@19.3.1')).toBeTrue(); + expect(panel.detail.querySelector('p.description').textContent).toBe('React'); + expect(panel.select('vue@3.0.0')).toBeFalse(); + expect(panel.selected).toBe('react@19.3.1'); + }); + + it('searches the packages by name, with every version of a name', async () => { + const {panel} = await open(); + const type = text => { + panel.search.value = text; + panel.search.dispatchEvent(new Event('input')); + }; + type('SCHED'); + expect(panel.tree.hidden).toBeTrue(); + expect(panel.matches.hidden).toBeFalse(); + expect([...panel.matches.children].map(match => match.textContent)).toEqual(['scheduler@0.20.02 versions', 'scheduler@0.28.02 versions']); + type('react'); + expect([...panel.matches.querySelectorAll('button')].map(button => button.textContent)).toEqual(['react@19.3.1', 'react-dom@19.3.1']); + expect([...panel.matches.children].map(match => match.querySelector('.badge.root') !== null)).toEqual([true, true]); + panel.matches.querySelectorAll('button')[1].click(); + expect(panel.selected).toBe('react-dom@19.3.1'); + expect(panel.matches.querySelectorAll('button')[1].getAttribute('aria-pressed')).toBe('true'); + type('vue'); + expect(panel.matches.textContent).toBe('No locked package has this name.'); + // Without a query the tree comes back, the package chosen selected where its dependencies are listed. + type(' '); + expect(panel.tree.hidden).toBeFalse(); + expect(panel.matches.hidden).toBeTrue(); + expect(item(panel.tree, 'react-dom@19.3.1', 0).getAttribute('aria-selected')).toBe('true'); + expect(item(panel.tree, 'react-dom@19.3.1', 0).tabIndex).toBe(0); + expect(searchPackages(null, 'a')).toEqual([]); + expect(searchPackages({roots: roots(), packages: packages()}, '').length).toBe(5); + }); + + it('is walked with the keyboard: arrows, Home and End, folding, and from a package already opened to where it is opened', async () => { + const {panel} = await open(); + const focused = () => document.activeElement.querySelector(':scope > .row .package-name')?.textContent; + const kit = item(panel.tree, '@app/kit@1.0.0'); + kit.focus(); + key(kit, 'ArrowDown'); + expect(focused()).toBe('react-dom@19.3.1'); + expect(document.activeElement.tabIndex).toBe(0); + expect(kit.tabIndex).toBe(-1); + key(document.activeElement, 'ArrowLeft'); // folds react-dom + expect(document.activeElement.getAttribute('aria-expanded')).toBe('false'); + key(document.activeElement, 'ArrowDown'); // its dependencies are skipped + expect(focused()).toBe('scheduler@0.20.0'); + key(document.activeElement, 'ArrowLeft'); // a leaf: to its parent + expect(focused()).toBe('@app/kit@1.0.0'); + key(document.activeElement, 'End'); + expect(document.activeElement).toBe(item(panel.tree, 'react-dom@19.3.1', 1)); + key(document.activeElement, 'ArrowRight'); // deduped: to the place where it is opened + expect(document.activeElement).toBe(item(panel.tree, 'react-dom@19.3.1', 0)); + key(document.activeElement, 'ArrowRight'); // unfolds it + expect(document.activeElement.getAttribute('aria-expanded')).toBe('true'); + key(document.activeElement, 'ArrowRight'); // then goes to its first dependency + expect(focused()).toBe('react@19.3.1'); + key(document.activeElement, 'Enter'); + expect(panel.selected).toBe('react@19.3.1'); + key(document.activeElement, 'Home'); + expect(focused()).toBe('@app/kit@1.0.0'); + key(document.activeElement, 'ArrowUp'); // nothing above the first item + expect(focused()).toBe('@app/kit@1.0.0'); + // The mouse folds with the marker, without selecting. + kit.querySelector('.twisty').click(); + expect(kit.getAttribute('aria-expanded')).toBe('false'); + expect(panel.selected).toBe('react@19.3.1'); + }); + + it('reads the lock again when it changes, and only then; the folded packages and the selection stay', async () => { + const {panel, storage, timers, bridge, listeners} = await open(); + expect(timers.delays).toEqual([lockPeriod]); + panel.select('scheduler@0.20.0'); + key(item(panel.tree, 'react-dom@19.3.1'), 'ArrowLeft'); + const reads = () => bridge.calls.filter(name => name === 'webfront.developer.read').length; + const before = reads(); + timers.fire(); + await panel.settled(); + expect(reads()).withContext('an unchanged lock is not read again').toBe(before); + expect(timers.delays).toEqual([lockPeriod, lockPeriod]); + + // wf install adds a package: the tree follows at the next period. + const locked = packages(); + Object.assign(locked, Object.fromEntries([node('left-pad', '1.3.0')])); + await writeProject(storage, {wanted: {...dependencies, 'left-pad': '^1.3.0'}, lockRoots: {...roots(), 'left-pad': {requested: '^1.3.0', id: 'left-pad@1.3.0'}}, locked}); + timers.fire(); + await panel.settled(); + expect(reads()).toBeGreaterThan(before); + expect(lines(panel.tree)).toContain('1|left-pad@1.3.0|^1.3.0|'); + expect(panel.summary.textContent).toBe('4 roots, 6 packages'); + expect(item(panel.tree, 'react-dom@19.3.1').getAttribute('aria-expanded')).toBe('false'); + expect(panel.selected).toBe('scheduler@0.20.0'); + expect(panel.detail.querySelector('h2').textContent).toBe('scheduler@0.20.0'); + + // The package shown is removed: its detail goes with it. + delete locked['scheduler@0.20.0']; + locked['@app+kit@1.0.0'].dependencies = {'react-dom': 'react-dom@19.3.1'}; + await writeProject(storage, {wanted: {...dependencies, 'left-pad': '^1.3.0'}, lockRoots: {...roots(), 'left-pad': {requested: '^1.3.0', id: 'left-pad@1.3.0'}}, locked}); + await panel.refresh(); + expect(panel.selected).toBeNull(); + expect(panel.detail.hidden).toBeTrue(); + expect(lines(panel.tree)).not.toContain('2|scheduler@0.20.0|~0.20.0|2 versions'); + expect(lines(panel.tree)).toContain('3|scheduler@0.28.0|^0.28.0|'); + + // The page that hides ends the reads. + listeners.get('pagehide')(); + expect(timers.pending).toBeFalse(); + const asked = bridge.calls.length; + await panel.refresh(); + expect(bridge.calls.length).toBe(asked); + }); + + it('shows the texts of a package as text, never as HTML, with their control characters made visible', async () => { + const hostile = ''; + const locked = Object.fromEntries([node('evil', '1.0.0', {}, {description: hostile, license: `MIT\x1b[2J`, + webfront: {bin: {'run': 'run.mjs', other: 'other.mjs'}}})]); + // A path of the lock cannot hold < or >; an entity would still be decoded by an HTML parser. + locked['evil@1.0.0'].files = ['package.json', '<img src=x>.js']; + const {panel, body} = await open({wanted: {evil: '^1.0.0'}, lockRoots: {evil: {requested: '^1', id: 'evil@1.0.0'}}, locked, + digest: {evil: '^1.0.0'}}); + panel.select('evil@1.0.0'); + expect(body.querySelector('img, script, b, i, u')).toBeNull(); + expect(window.pwned).toBeUndefined(); + expect(panel.detail.querySelector('p.description').textContent).toBe(hostile); + expect(rowsOf(panel.detail).License).toBe('MIT^[[2J'); + expect(rowsOf(panel.detail).Executables).toBe('wf exec evil:run, wf exec evil:other'); + expect(panel.tree.querySelector('.package-range').textContent).toBe('^1'); + expect([...panel.detail.querySelectorAll('ul.files li')].at(-1).textContent).toBe('<img src=x>.js'); + }); + + it('says when the project has no manifest, no package, or a lock that no longer matches the manifest', async () => { + const none = await open({write: false}); + expect(none.status.textContent).toBe('This project has no webfront.project.json: wf init creates it.'); + expect(none.panel.tree.children.length).toBe(0); + expect(none.panel.summary.textContent).toBe(''); + const empty = await open({wanted: {}, lockRoots: {}, locked: {}}); + expect(empty.status.textContent).toBe('No installed packages: wf install adds one.'); + const changed = await open({digest: {react: '^18.0.0'}}); + expect(changed.status.textContent).toContain('Warning: The lock does not match the dependencies of webfront.project.json'); + expect(changed.panel.summary.textContent).toBe('3 roots, 5 packages'); + }); + + it('says why the packages cannot be read, and shows them once they can', async () => { + const storage = new Map(); + storage.set('webfront.project.json', encode(JSON.stringify({format: 1, name: 'app', version: '0.1.0'}))); + storage.set('webfront-packages.lock.json', encode('{"format":7}')); + const {panel, status, timers} = await open({storage, write: false}); + expect(status.textContent).toBe('The packages cannot be read: Unsupported package lock'); + expect(status.classList.contains('error')).toBeTrue(); + expect(timers.delays).withContext('it tries again at the next period').toEqual([lockPeriod]); + await writeProject(storage); + timers.fire(); + await panel.settled(); + expect(status.classList.contains('error')).toBeFalse(); + expect(panel.summary.textContent).toBe('3 roots, 5 packages'); + }); + + it('reads the manifest and the lock in the directory that the application chose', async () => { + const storage = new Map(); + await writeProject(storage, {directory: 'js/app'}); + const config = () => JSON.stringify({environment: 'x', manifestDirectory: 'js/app'}); + const bridge = countingBridge(storage, {'webfront.developer.config': config}); + expect(await manifestDirectory(bridge)).toBe('js/app'); + expect(Object.keys((await readPackages(bridge)).lock.packages).length).toBe(5); + // A bridge without the configuration (an older C++) reads the project root. + expect(await manifestDirectory(countingBridge(new Map()))).toBeUndefined(); + const {panel} = await open({storage, write: false, extra: {'webfront.developer.config': config}}); + expect(panel.summary.textContent).toBe('3 roots, 5 packages'); + }); + + it('is the panel of inspector.html?panel=typescript.packages, with the bridge of its host in a frame', async () => { + const frame = document.createElement('iframe'); + document.body.append(frame); + const storage = new Map(); + await writeProject(storage); + const timers = manualTimers(); + try { + const bridge = Object.assign(countingBridge(storage), {ready: Promise.resolve()}); + const view = {setTimeout: timers.setTimeout, clearTimeout: timers.clearTimeout, addEventListener() {}, document: frame.contentDocument, + parent: {webfrontInspectorHost: {bridge}}, + location: {href: 'http://localhost/webfront/developer/environment/inspector.html?panel=typescript.packages&frame=1'}}; + const made = await main(view); + expect(frame.contentDocument.title).toBe('WebFront inspector: TypeScript state: Packages'); + expect(frame.contentDocument.querySelectorAll('ul.packages [role=treeitem]').length).toBe(7); + expect(frame.contentDocument.querySelector('input[type=search]')).not.toBeNull(); + made.stop(); + } finally { frame.remove(); } + }); +}); From 184c8590a9f12e84e278b2e8893a23cef1ade683 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:15:46 +0100 Subject: [PATCH 3/6] Show the packages of Life in the panel and follow wf install in the browser integration; document the panel (#683) --- docs/CHANGELOG.md | 1 + docs/DEVELOPER_ENVIRONMENT.md | 18 ++++++++++++-- test/web/developer-specs.mjs | 46 ++++++++++++++++++++++++++++++++--- 3 files changed, 60 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 7e5ee597..be4f7776 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -19,6 +19,7 @@ these entries stays in the GitHub releases and the Git history. - See in the **Functions** panel of the inspectors what the application registered: each `cppFunction` with its signature written in TypeScript, the file and line of its registration, whether it receives the calling `UI`, its calls, failures, last error and durations, then the JavaScript functions that C++ calls; sort, search, and choose the refresh period (#681, ADR-027, `docs/DEVELOPER_ENVIRONMENT.md`). - See in the **Browsers and tasks** panel the connected browsers (embedded view or external browser, local client, pending writes and calls), the running tasks of the server and the application's terminal commands (#681, ADR-027). - Read the same registry from C++ with `app.registeredFunctions()` (#681, ADR-027). +- Browse in the **Packages** panel of the inspectors the locked packages as a tree under the roots of the manifest, with the requested ranges and the `peer`, `deduped` and multiple-version marks; search a package by name and open its detail with its `wf why` chains; the tree follows `wf install` and `wf restore` (#683, ADR-027, `docs/DEVELOPER_ENVIRONMENT.md`). - Declare what the inspectors show with `app.watch(name, source)`, whose handle removes the watch when it is destroyed; the Watches panel follows their registrations and removals. Outside the developer environment and in a distribution build, `watch` registers nothing (#680, ADR-027). - Embed a plain interface directory (HTML, JavaScript, CSS, vendored files) from CMake with `webfront_embed_directory(app ui CLASS AppUI)`, without the developer environment: the build regenerates the provider when a file changes, and `fs::DocumentRootFirstFSWith` lets a development root serve in front of it (#675, `docs/EMBEDDED_ASSETS.md`). - Set from the configuration `Referrer-Policy` (`contentPolicy.referrerPolicy`: `"no-referrer"` forbids explicitly that a capability in your URLs leaves in `Referer`), `X-Content-Type-Options: nosniff` (`noSniff`) and the `Cache-Control` of HTML pages (`htmlCacheControl`), on files, route and generated replies unless a reply sets its own (#674, `docs/CONTENT_POLICY.md`). diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index cf0e47cd..fdfe0c18 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -492,8 +492,22 @@ environment's `mount`, not to the embedded bootstrap page): whether it is a local client (`ui.isLocalClient()`), its state, the path its bridge was opened from and its space, the frames not yet written to it, the typed calls of C++ whose result it has not returned, and its calls that a C++ callback has not answered yet. It also gives the number of running tasks of the server's scope (connections, bridge - loops and the application's coroutines) and the application's terminal commands (`webfront::Commands`). The other - panels come with the next versions of the environment. + loops and the application's coroutines) and the application's terminal commands (`webfront::Commands`). + + The **Packages** panel shows the locked packages as a tree, what `wf list --tree`, `wf why` and `wf info` say as text: + the roots of the manifest with the range each was requested with, then under each package its dependencies with the + range that asks for them. A `peer` or `optional` dependency is marked; a package that comes again is marked `deduped` + and is not opened again (the Right arrow goes from it to the place where its dependencies are listed); a package + locked in several versions shows how many. The tree is walked with the arrow keys, Home and End; Left and Right fold + and unfold. The search field lists the packages whose name holds what is typed, every version of them. A click on a + package (or Enter) shows its detail: whether it is a root, its description, license, integrity, directory and files, + its dependencies and dependents, its `wf exec` entries, and the chains of `wf why` from the roots, in which each + package is a link to its own detail. The panel reads the manifest and the lock through the project reads of the + environment (`webfront.developer.read`), in the manifest directory the application chose; it uses no network and writes + nothing. Every second it asks whether either file changed and reads them again when one did, so the tree follows + `wf install` and `wf restore`; it warns when the lock no longer matches the manifest. The names and texts of packages + are not trusted: they are shown as text, never as HTML, with their control characters made visible. The Bridge panel + comes with the next versions of the environment. The tab is a button (`aria-expanded`, `aria-haspopup="menu"`, 44 px target), its menu a `menu` of `menuitem`s of 44 px, and the window a non-modal dialog. The interface stays in the preview diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index 9fa613ad..23560b72 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -158,9 +158,49 @@ try { } let lock; if (wants('app')) { - await execute(['install', 'react@19.3.1', 'react-dom@19.3.1'], context); - lock = await runtime.readLock(webFront); - assert(lock.manifestDigest?.length === 64, 'The lock must record the digest of the manifest dependencies'); + // The Packages panel of the inspectors (#683), in the inspector's page with a connection of its own, as a detached tab + // has: it reads the project of Life, which has no lock yet, and follows the lock that wf install writes. + const packages = document.createElement('iframe'); + packages.title = 'WebFront inspector: packages'; + packages.style.cssText = 'position:fixed;left:0;top:0;width:760px;height:520px;border:0;z-index:2147483647;background:#141821'; + packages.src = '/webfront/developer/environment/inspector.html?panel=typescript.packages'; + document.body.append(packages); + try { + const panel = () => packages.contentDocument; + const tree = () => [...(panel()?.querySelectorAll('ul.packages [role=treeitem]') ?? [])].map(item => { + const row = item.querySelector(':scope > .row'); + return [item.getAttribute('aria-level'), row.querySelector('.package-name').textContent, + ...[...row.querySelectorAll('.badge')].map(badge => badge.textContent)].join(' '); + }); + const shown = () => `${panel()?.querySelector('.status:not(.attach-status)')?.textContent} ${JSON.stringify(tree())}`; + const slowly = {attempts: 600}; + await eventually(() => /No installed packages/.test(panel()?.querySelector('.status:not(.attach-status)')?.textContent ?? ''), + () => `The Packages panel must say that a project without a lock has no package: ${shown()}`, slowly); + assert(tree().length === 0, `A project without a lock has no tree: ${shown()}`); + + await execute(['install', 'react@19.3.1', 'react-dom@19.3.1'], context); + lock = await runtime.readLock(webFront); + assert(lock.manifestDigest?.length === 64, 'The lock must record the digest of the manifest dependencies'); + + // The lock changed: the panel reads it again by itself. react-dom brings scheduler and its peer react. + await eventually(() => tree().length === 4, () => `The Packages panel must follow the lock that wf install wrote: ${shown()}`, slowly); + const lines = tree(); + assert(lines[0] === '1 react@19.3.1' && lines[1] === '1 react-dom@19.3.1' && lines[2] === '2 react@19.3.1 peer' && /^2 scheduler@\S+$/.test(lines[3]), + `The Packages panel must show the packages of Life under their roots: ${shown()}`); + assert(panel().querySelector('.summary').textContent === '2 roots, 3 packages', `The panel must count the roots and the packages: ${shown()}`); + // One click on a package gives what wf info and wf why say of it. + [...panel().querySelectorAll('ul.packages .package-name')].find(name => name.textContent.startsWith('scheduler@')).click(); + const detail = () => panel().querySelector('.package-detail'); + assert(!detail().hidden && /^react-dom@19\.3\.1 \(root, 19\.3\.1\) > scheduler@/.test(detail().querySelector('ol.chains li').textContent), + `A click on a package must give its chains from the roots: ${detail().textContent}`); + assert(/License\s*MIT/.test(detail().querySelector('dl').textContent) && /sha512-/.test(detail().querySelector('dl').textContent), + `A click on a package must describe it: ${detail().textContent}`); + const search = panel().querySelector('input[type=search]'); + search.value = 'dom'; + search.dispatchEvent(new Event('input')); + const found = [...panel().querySelectorAll('ul.matches button')].map(button => button.textContent); + assert(found.length === 1 && found[0] === 'react-dom@19.3.1', `The search must find the packages by name: ${found}`); + } finally { packages.remove(); } } const manifest = JSON.parse(new TextDecoder().decode(await readFile('webfront.project.json'))); if (wants('app')) assert(manifest.dependencies.react === '19.3.1' && manifest.dependencies['react-dom'] === '19.3.1', 'The manifest must record the requested ranges'); From e95e353ffb87a2e7a4261b770b8b1439fa5be7a2 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:17:57 +0100 Subject: [PATCH 4/6] Packages panel: keep the keyboard focus when a link of the detail is followed (#683) --- js/developer/environment/bundles.json | 2 +- js/developer/environment/inspector-packages.mjs | 12 ++++++++++-- test/developer/specs/inspector-packages-specs.mjs | 7 ++++++- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index f1894268..39837907 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -26,7 +26,7 @@ "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", "js/developer/environment/inspector-host.mjs": "bffcef61b8a5778f53adfea5096c5d5fa277868bbaa39e60142a3493210076fb", "js/developer/environment/inspector.mjs": "e22d5731e7e92b821ccdb15badc2fa4aebba653763239ea813ea904719aca33a", - "js/developer/environment/inspector-packages.mjs": "1c90f9d9c84592cd9372116bcf753ee0914166f218b2f181ffb24e51710f62a0", + "js/developer/environment/inspector-packages.mjs": "f7bcfc5bee182b0260ca0892962120743a74b7bb70515ec1739d115b569e497a", "js/developer/environment/inspector-registry.mjs": "431153f7d7eb562262361f2f8eb60d8690f42cdfbf5ed9586270270d9e2b6038", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", diff --git a/js/developer/environment/inspector-packages.mjs b/js/developer/environment/inspector-packages.mjs index 6ef2e0d4..b6938859 100644 --- a/js/developer/environment/inspector-packages.mjs +++ b/js/developer/environment/inspector-packages.mjs @@ -69,6 +69,7 @@ ul.matches button,.package-detail button.package-link{min-height:28px;padding:0 ul.matches li{display:flex;flex-wrap:wrap;align-items:center;gap:2px 8px} ul.matches button:focus-visible,.package-detail button:focus-visible{outline:2px solid #d7fa85;outline-offset:-2px} .package-detail{min-width:0;padding:8px 12px;border:1px solid #2f3a50;border-radius:4px;align-self:start} +.package-detail h2:focus{outline:none} .package-detail h2{margin:0 0 4px;font:600 14px ui-monospace,monospace;overflow-wrap:anywhere} .package-detail h3{margin:12px 0 4px;font-size:12px;font-weight:600;color:#a9b3c4} .package-detail p{margin:0 0 8px} @@ -151,7 +152,12 @@ export async function showPackagesPanel({page, view, body, status, bridge, load const button = element('button', 'package-link', label); button.type = 'button'; button.dataset.package = id; - button.addEventListener('click', () => select(id)); + button.addEventListener('click', () => { + // A link of the detail is replaced with it: the focus goes to the title of the package it leads to, not to the page. + const replaced = detail.contains(button); + select(id); + if (replaced) detail.querySelector('h2')?.focus(); + }); return button; }; @@ -195,7 +201,9 @@ export async function showPackagesPanel({page, view, body, status, bridge, load const fileList = element('ul', 'files'); for (const path of details.files) fileList.append(element('li', '', path)); files.append(fileList); - detail.replaceChildren(element('h2', '', details.label), ...(details.description ? [element('p', 'description', details.description)] : []), rows, + const title = element('h2', '', details.label); + title.tabIndex = -1; + detail.replaceChildren(title, ...(details.description ? [element('p', 'description', details.description)] : []), rows, element('h3', '', 'Why it is installed (wf why)'), why, ...(chains.length ? [] : [element('p', 'note', 'Nothing requires it: wf install --update resolves the manifest again.')]), ...(limited ? [element('p', 'note', `Only the first ${chainLimit} chains are shown.`)] : []), diff --git a/test/developer/specs/inspector-packages-specs.mjs b/test/developer/specs/inspector-packages-specs.mjs index da3258eb..0ce60e79 100644 --- a/test/developer/specs/inspector-packages-specs.mjs +++ b/test/developer/specs/inspector-packages-specs.mjs @@ -156,8 +156,13 @@ describe('The Packages panel of the inspectors', () => { expect(item(panel.tree, 'scheduler@0.28.0').getAttribute('aria-selected')).toBe('true'); // A package of a chain: its detail, with its executables, its dependencies and the ranges that ask for them. - [...panel.detail.querySelectorAll('ol.chains button')].find(button => button.textContent === '@app/kit@1.0.0').click(); + const followed = [...panel.detail.querySelectorAll('ol.chains button')].find(button => button.textContent === '@app/kit@1.0.0'); + followed.focus(); + followed.click(); expect(panel.selected).toBe('@app+kit@1.0.0'); + // The link was replaced with the detail: the focus is on the title of the package it led to, not lost to the page. + expect(document.activeElement).toBe(panel.detail.querySelector('h2')); + expect(document.activeElement.textContent).toBe('@app/kit@1.0.0'); const kit = rowsOf(panel.detail); expect(kit.Root).toBe('yes, requested latest'); expect(kit.License).toBe('not declared'); From b088ddc927405d5a30bc7680bf5626fc34e1edd1 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:27:34 +0100 Subject: [PATCH 5/6] Packages panel: after a lock change, give the Tab key to a package that is shown (#683) --- js/developer/environment/bundles.json | 2 +- js/developer/environment/inspector-packages.mjs | 5 ++++- test/developer/specs/inspector-packages-specs.mjs | 12 ++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 39837907..8e61ad02 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -26,7 +26,7 @@ "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", "js/developer/environment/inspector-host.mjs": "bffcef61b8a5778f53adfea5096c5d5fa277868bbaa39e60142a3493210076fb", "js/developer/environment/inspector.mjs": "e22d5731e7e92b821ccdb15badc2fa4aebba653763239ea813ea904719aca33a", - "js/developer/environment/inspector-packages.mjs": "f7bcfc5bee182b0260ca0892962120743a74b7bb70515ec1739d115b569e497a", + "js/developer/environment/inspector-packages.mjs": "1c3f6350780b841784f83bc20ead2945157c48a1f136c47e3a7a90d89bea8522", "js/developer/environment/inspector-registry.mjs": "431153f7d7eb562262361f2f8eb60d8690f42cdfbf5ed9586270270d9e2b6038", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", diff --git a/js/developer/environment/inspector-packages.mjs b/js/developer/environment/inspector-packages.mjs index b6938859..1e8f99d5 100644 --- a/js/developer/environment/inspector-packages.mjs +++ b/js/developer/environment/inspector-packages.mjs @@ -265,7 +265,10 @@ export async function showPackagesPanel({page, view, body, status, bridge, load // Paths that no longer exist are forgotten, so that the set stays bounded by the tree shown. const paths = new Set(items().map(item => item.dataset.path)); for (const path of [...collapsed]) if (!paths.has(path)) collapsed.delete(path); - const start = (selected && first(selected)) || items()[0]; + // The item that takes the Tab key is one that is shown: the selected package, or the folded package that hides it. + let start = (selected && first(selected)) || items()[0]; + for (let above = start && parentItem(start); above; above = parentItem(above)) + if (above.getAttribute('aria-expanded') === 'false') start = above; if (start) focusable(start); } diff --git a/test/developer/specs/inspector-packages-specs.mjs b/test/developer/specs/inspector-packages-specs.mjs index 0ce60e79..a5487d5a 100644 --- a/test/developer/specs/inspector-packages-specs.mjs +++ b/test/developer/specs/inspector-packages-specs.mjs @@ -263,6 +263,18 @@ describe('The Packages panel of the inspectors', () => { expect(item(panel.tree, 'react-dom@19.3.1').getAttribute('aria-expanded')).toBe('false'); expect(panel.selected).toBe('scheduler@0.20.0'); expect(panel.detail.querySelector('h2').textContent).toBe('scheduler@0.20.0'); + expect(item(panel.tree, 'scheduler@0.20.0').tabIndex).toBe(0); + + // The selected package is under a folded one when the lock changes again: the folded package, which is shown, takes + // the Tab key, and stays folded. + key(item(panel.tree, '@app/kit@1.0.0'), 'ArrowLeft'); + Object.assign(locked, Object.fromEntries([node('is-odd', '3.0.1')])); + await writeProject(storage, {wanted: {...dependencies, 'left-pad': '^1.3.0'}, lockRoots: {...roots(), 'left-pad': {requested: '^1.3.0', id: 'left-pad@1.3.0'}}, locked}); + await panel.refresh(); + expect(panel.summary.textContent).toBe('4 roots, 7 packages'); + expect(item(panel.tree, '@app/kit@1.0.0').getAttribute('aria-expanded')).toBe('false'); + expect([...panel.tree.querySelectorAll('[tabindex="0"]')]).toEqual([item(panel.tree, '@app/kit@1.0.0')]); + expect(panel.selected).toBe('scheduler@0.20.0'); // The package shown is removed: its detail goes with it. delete locked['scheduler@0.20.0']; From 929e8e26c1f0f38bac6427663d0d16d0d0ef1dd9 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:51:24 +0100 Subject: [PATCH 6/6] Inspector host specs: wait for the channel's message instead of a fixed delay (#683) Two specs gave the BroadcastChannel 20 or 50 ms to deliver a request; a loaded WebView2 runner takes longer, and DeveloperSpecs failed there three times in a row. --- test/developer/specs/inspector-specs.mjs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index aebf0dfb..a503c7a3 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -379,6 +379,11 @@ describe('The inspectors', () => { } finally { inspector.close(); } }); + // Waits for what a message of the channel causes, two seconds at most: the expectation that follows says what is missing. + async function delivered(done) { + for (let waited = 0; !done() && waited < 2000; waited += 5) await new Promise(resolve => setTimeout(resolve, 5)); + } + it('attaches a panel again only in the page that detached it', async () => { const {host: mine} = await testHost({containers: admitted(true), hostId: 'host-a'}); const {host: other, storage: otherStorage} = await testHost({containers: admitted(true), hostId: 'host-b'}); @@ -387,7 +392,8 @@ describe('The inspectors', () => { const answers = []; inspector.addEventListener('message', ({data}) => { if (data?.type === 'attached') answers.push(data.id); }); inspector.postMessage({type: 'attach', panel: 'cpp.watches', host: 'host-a', id: 'request-a'}); - await new Promise(resolve => setTimeout(resolve, 50)); + await delivered(() => answers.length > 0); + await new Promise(resolve => setTimeout(resolve, 50)); // and nobody else answers expect(answers).toEqual(['request-a']); expect(mine.shownPanel).toBe('cpp.watches'); expect(other.shownPanel).toBeNull(); @@ -419,12 +425,13 @@ describe('The inspectors', () => { const {host, calls} = await testHost({containers: admitted(true), closeWindow: () => new Promise(resolve => { closed = resolve; })}); await host.detach('cpp.watches'); const answer = askAttach('cpp.watches', 'request-close'); // answered once the close is over - await new Promise(resolve => setTimeout(resolve, 20)); + const names = () => calls.map(([name]) => name).filter(name => name.endsWith('Window')); + // The request crosses the channel in its own time (more than 20 ms on a loaded WebView2 runner): waited for, not timed. + await delivered(() => names().includes('webfront.inspector.closeWindow')); expect(host.preferences.detached.has('cpp.watches')).toBeFalse(); // The user detaches it again while the close is in progress: the window opens only once the close is over. const detaching = host.detach('cpp.watches'); await new Promise(resolve => setTimeout(resolve)); - const names = () => calls.map(([name]) => name).filter(name => name.endsWith('Window')); expect(names()).toEqual(['webfront.inspector.openWindow', 'webfront.inspector.closeWindow']); closed(true); expect((await answer).closer).toBe('host');