diff --git a/CHANGELOG.md b/CHANGELOG.md index 5695a122..3c05f7c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,23 @@ platform API version. ### Added +- **Find in the diagram.** The palette's loupe opens a box at the top of + the palette that finds nodes in the model, not in the drawing, so a node + off screen or too small to be drawn at the zoom is found too. It matches a + node by its name (`cal:entityName`, or the label of a frame) and by the + text a producer adds for find (`wf:searchText`, one text, or a text per + field). A root that names fields (`wf:searchFields`, `[{ key, label, + title? }]`) gets a tab per field. A query can be a regular expression. + With one node selected that holds others, the search stays inside it + and the chip says so, following the selection while the box is open. + Each row ends with the name of the node the match is in (its line, inside + a scope of that name), and a node's `wf:searchDetail` tells like matches + apart. A click, or Enter for the first row, selects the hit and centres + it, at the zoom shown where names are drawn there, else fitted no closer + than 1:1 (a product whose matches are read in the detail of a node says + that zoom, `ViewToolPalette.findReadableZoom`). In a palette that lists tools the same text filters the tools, + as GLSP's field did. The box is `DiagramFindPanel`, its search + `findMatches`, and its styles `diagram-find.css`. - **A failed build keeps the diagram.** A file that built before and fails to build now (a syntax error typed halfway) keeps the graph it last built for the same view, dimmed under a red bar: the first error of the build @@ -50,6 +67,11 @@ platform API version. ### Changed +- **The palette's loupe opens find**, not GLSP's field. That field + filtered the tools and the lines of the view options, and said "No + results found." when it matched neither. The text of find filters the + tools alone, and the view options stay whole while it is open: what it + finds is nodes, and it says itself what it matched. - **Command ids a product does not have.** `runWorkflow`, `stopWorkflow`, `setAgentToolConfig`, `getAgentToolConfig` and `createNewContainer` are optional in `DiagramCommandIds`: only a sidecar product registers them, and diff --git a/packages/diagram-client/src/diagram-client.css b/packages/diagram-client/src/diagram-client.css index 8b78986d..30791268 100644 --- a/packages/diagram-client/src/diagram-client.css +++ b/packages/diagram-client/src/diagram-client.css @@ -21,6 +21,7 @@ @import './graph-status.css'; @import './floating-buttons.css'; @import './hierarchy-outline.css'; +@import './diagram-find.css'; :root { --sprotty-background: var(--vscode-editor-background, #1e1e1e); diff --git a/packages/diagram-client/src/diagram-find.css b/packages/diagram-client/src/diagram-find.css new file mode 100644 index 00000000..7ea30ffd --- /dev/null +++ b/packages/diagram-client/src/diagram-find.css @@ -0,0 +1,192 @@ +/* ── Find in the diagram (diagram-find.ts) ──────────────────────────────── + A block at the top of the palette's body, not a window over it: it + extends the palette downwards, and the palette stays one thing. Its own + file, so that a product that draws its own palette imports it alone. */ + +.diagram-find { + display: flex; + flex-direction: column; + gap: 6px; + box-sizing: border-box; + width: 100%; + min-width: 180px; + padding: 6px 4px 5px; + /* The ground of the palette's tool groups: the body under it shows the + canvas through. */ + background: var(--vscode-settings-dropdownBackground, var(--vscode-editorWidget-background, #252526)); + color: var(--vscode-foreground, #ccc); + font-size: 11px; + text-align: left; +} + +.diagram-find[hidden] { + display: none; +} + +/* The rows are content, not settings: they take the breathing room the + lines of the view options take from their own padding. */ +.diagram-find > *:not(.diagram-find-results) { + margin: 0 2px; +} + +.diagram-find-heading { + font-weight: 600; +} + +.diagram-find-scope { + display: flex; + align-items: center; + gap: 4px; +} + +.diagram-find-scope-chip { + max-width: 240px; + padding: 2px 8px; + border-radius: 999px; + font-size: 10px; + background: var(--vscode-badge-background, #4d4d4d); + color: var(--vscode-badge-foreground, #fff); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.diagram-find-scope-clear { + padding: 0 2px; + border: none; + background: transparent; + color: var(--vscode-descriptionForeground, #8b8b8b); + font-size: 12px; + line-height: 1; + cursor: pointer; +} + +.diagram-find-scope-clear:hover { + color: var(--vscode-foreground, #ccc); +} + +.diagram-find-query { + display: flex; + align-items: center; + gap: 4px; +} + +.diagram-find-input { + flex: 1 1 auto; + min-width: 0; + box-sizing: border-box; + padding: 4px 6px; + border: 1px solid var(--vscode-input-border, var(--vscode-dropdown-border, #454545)); + border-radius: 3px; + background: var(--vscode-input-background, #3c3c3c); + color: var(--vscode-input-foreground, #ccc); + font-family: var(--vscode-editor-font-family, monospace); + font-size: 11px; +} + +.diagram-find-input:focus { + outline: 1px solid var(--vscode-focusBorder, #007fd4); + outline-offset: -1px; +} + +.diagram-find-fields { + display: flex; + gap: 4px; +} + +.diagram-find-fields[hidden] { + display: none; +} + +.diagram-find-field { + padding: 2px 8px; + border: 1px solid var(--vscode-dropdown-border, #454545); + border-radius: 3px; + background: transparent; + color: var(--vscode-foreground, #ccc); + font-size: 10px; + cursor: pointer; +} + +.diagram-find-field:hover { + background: var(--vscode-toolbar-hoverBackground, rgba(128, 128, 128, 0.18)); +} + +.diagram-find-field.active { + border-color: var(--vscode-inputOption-activeBorder, var(--vscode-focusBorder, #007fd4)); + background: var(--vscode-inputOption-activeBackground, rgba(51, 153, 255, 0.3)); + color: var(--vscode-inputOption-activeForeground, var(--vscode-foreground, #fff)); +} + +.diagram-find-regex { + flex: none; + font-family: var(--vscode-editor-font-family, monospace); +} + +/* The count above the list: it says whether the query was any good + without a row read. */ +.diagram-find-summary { + min-height: 13px; + font-size: 10px; + color: var(--vscode-descriptionForeground, #8b8b8b); +} + +/* Bounded, or a query matching two thousand nodes makes the palette taller + than the window and the view options out of reach. */ +.diagram-find-results { + display: flex; + flex-direction: column; + max-height: 220px; + overflow-y: auto; +} + +.diagram-find-result { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + padding: 3px 6px; + border: none; + border-radius: 3px; + background: transparent; + color: var(--vscode-foreground, #ccc); + font-size: 11px; + text-align: left; + cursor: pointer; +} + +.diagram-find-result:hover, +.diagram-find-result:focus-visible { + background: var(--vscode-list-hoverBackground, rgba(128, 128, 128, 0.18)); +} + +.diagram-find-result-primary { + flex: 0 1 auto; + font-family: var(--vscode-editor-font-family, monospace); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* What tells like matches apart (the value a step defines): beside the + match, not off in the last column. */ +.diagram-find-result-detail { + flex: 0 1 auto; + margin-right: auto; + padding-left: 8px; + font-family: var(--vscode-editor-font-family, monospace); + color: var(--vscode-charts-blue, var(--vscode-focusBorder, #3794ff)); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.diagram-find-result-context { + flex: 0 0 auto; + max-width: 130px; + font-size: 10px; + color: var(--vscode-descriptionForeground, #8b8b8b); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} diff --git a/packages/diagram-client/src/diagram-find.ts b/packages/diagram-client/src/diagram-find.ts new file mode 100644 index 00000000..206f831a --- /dev/null +++ b/packages/diagram-client/src/diagram-find.ts @@ -0,0 +1,613 @@ +/** + * Find in the diagram: the box the palette's loupe opens. + * + * It reads the model, never the drawing. The view draws only what is on + * screen and legible at the zoom, so a search of the drawing would answer + * "3 matches" for a query with fifty, and be right about the three it could + * see. The model holds every element the server built, whatever is drawn. + * + * It searches inside the selection. A large diagram has many nodes of one + * kind, and the useful question is which of them are in the part the reader + * picked: with one node selected the search starts there, and the chip says + * so. + * + * A node matches by its name (`ENTITY_NAME`, or `GROUP_LABEL` on a frame) + * and by what the producer adds for find (`SEARCH_TEXT`). A producer that + * names search fields on the root (`SEARCH_FIELDS`) gets one tab per field, + * and each tab matches its own text of the node. A hit is selected and + * centred. + * + * In a palette that lists tools, the same text filters the tools, as GLSP's + * search field does: one loupe, one box. + */ +import { WorkflowDiagramMetadata, searchFieldsOf, type SearchField } from '@dialogram/shared'; + +/** What the search reads of an element of the model. */ +export interface FindElement { + id: string; + type?: string; + args?: Record; + parent?: FindElement; + children?: readonly FindElement[]; +} + +export interface FindMatch { + elementId: string; + /** The text that matched. */ + primary: string; + /** The node's `SEARCH_DETAIL`, unless the match already holds it. */ + detail: string; + /** The name of the nearest named node around it. */ + context: string; + /** Its zero-based source line, where the node says it (`SOURCE_RANGE`). */ + line?: number; +} + +export interface FindScope { + /** The node the search is confined to, or none for the whole view. */ + elementId?: string; + /** What the chip reads. */ + label: string; + /** The name of that node, so that rows drop a context that repeats it. */ + name?: string; +} + +export interface FindQuery { + text: string; + /** The field matched, or none for the name and every text of a node. */ + field?: string; + regex?: boolean; + scope?: FindScope; + /** At most this many matches are listed; all of them are counted. */ + limit?: number; +} + +/** The field that stands for the name of a node. */ +export const NAME_FIELD = 'name'; +/** What a node's `SEARCH_TEXT` is called when it is one text. */ +const TEXT_FIELD = 'text'; +/** How many matches are listed, so that a one-letter query on a large model does not build a list nobody reads. */ +export const FIND_LIMIT = 200; + +const str = (value: unknown): string => (typeof value === 'string' ? value : ''); + +/** Elements worth matching: nodes, not ports, labels or edges. */ +function isFindable(element: FindElement): boolean { + return str(element.type).startsWith('node:'); +} + +/** The texts a node is found by, by field: its name first. */ +export function findTextsOf(element: FindElement): Record { + const args = element.args ?? {}; + const given = args[WorkflowDiagramMetadata.SEARCH_TEXT]; + const texts: Record = { + [NAME_FIELD]: str(args[WorkflowDiagramMetadata.ENTITY_NAME]) || str(args[WorkflowDiagramMetadata.GROUP_LABEL]) + }; + if (typeof given === 'string') { + texts[TEXT_FIELD] = given; + } else if (given && typeof given === 'object' && !Array.isArray(given)) { + for (const [key, value] of Object.entries(given as Record)) { + if (typeof value === 'string') { + texts[key] = value; + } + } + } + return texts; +} + +/** The name of a node for find: its `name` text. */ +export function findNameOf(element: FindElement): string { + return findTextsOf(element)[NAME_FIELD] ?? ''; +} + +/** The name of the nearest named node around this one. */ +function contextOf(element: FindElement): string { + for (let current = element.parent; current; current = current.parent) { + const name = isFindable(current) ? findNameOf(current) : ''; + if (name) { + return name; + } + } + return ''; +} + +function lineOf(element: FindElement): number | undefined { + const range = element.args?.[WorkflowDiagramMetadata.SOURCE_RANGE] as { start?: { line?: unknown } } | undefined; + const line = range?.start?.line; + return typeof line === 'number' && Number.isInteger(line) && line >= 0 ? line : undefined; +} + +/** The test a query makes, or none for an empty query or an unfinished expression. */ +function testOf(text: string, regex: boolean): ((value: string) => boolean) | undefined { + const trimmed = text.trim(); + if (trimmed === '') { + return undefined; + } + if (regex) { + try { + const expression = new RegExp(trimmed, 'i'); + return value => expression.test(value); + } catch { + // An unfinished expression is the normal state while typing, not an error. + return undefined; + } + } + const needle = trimmed.toLowerCase(); + return value => value.toLowerCase().includes(needle); +} + +/** The node of a scope, while the model holds it. */ +function scopeNodeOf(root: FindElement, scope: FindScope | undefined, byId: ((id: string) => FindElement | undefined) | undefined): FindElement | undefined { + return scope?.elementId ? byId?.(scope.elementId) ?? findById(root, scope.elementId) : undefined; +} + +/** + * The elements to start from: what the scope's node holds, while it is + * there, else the root. The node itself is not searched: the reader has it + * selected, and asked for what is inside it. + */ +function startOf(root: FindElement, scope: FindScope | undefined, byId: ((id: string) => FindElement | undefined) | undefined): readonly FindElement[] { + const node = scopeNodeOf(root, scope, byId); + return node ? node.children ?? [] : [root]; +} + +function findById(root: FindElement, id: string): FindElement | undefined { + const stack: FindElement[] = [root]; + while (stack.length > 0) { + const element = stack.pop()!; + if (element.id === id) { + return element; + } + stack.push(...(element.children ?? [])); + } + return undefined; +} + +/** + * The matches of a query, in the order the model holds them, the first + * `limit` listed and all counted. + */ +export function findMatches( + root: FindElement | undefined, + query: FindQuery, + byId?: (id: string) => FindElement | undefined +): { matches: FindMatch[]; total: number } { + const test = root ? testOf(query.text, query.regex === true) : undefined; + if (!root || !test) { + return { matches: [], total: 0 }; + } + const limit = query.limit ?? FIND_LIMIT; + const matches: FindMatch[] = []; + let total = 0; + const stack: FindElement[] = [...startOf(root, query.scope, byId)].reverse(); + while (stack.length > 0) { + const element = stack.pop()!; + if (isFindable(element)) { + const texts = findTextsOf(element); + const candidates = query.field !== undefined ? [texts[query.field] ?? ''] : Object.values(texts); + const primary = candidates.find(text => text !== '' && test(text)); + if (primary !== undefined) { + total++; + if (matches.length < limit) { + const detail = str(element.args?.[WorkflowDiagramMetadata.SEARCH_DETAIL]); + matches.push({ + elementId: element.id, + primary, + detail: detail !== '' && !primary.includes(detail) ? detail : '', + context: contextOf(element), + line: lineOf(element) + }); + } + } + } + const children = element.children ?? []; + for (let i = children.length - 1; i >= 0; i--) { + stack.push(children[i]); + } + } + return { matches, total }; +} + +/** Whether a node holds other nodes, so that a search inside it can find any. */ +function holdsNodes(element: FindElement): boolean { + const stack: FindElement[] = [...(element.children ?? [])]; + while (stack.length > 0) { + const child = stack.pop()!; + if (isFindable(child)) { + return true; + } + stack.push(...(child.children ?? [])); + } + return false; +} + +/** + * The scope of the selection: the node selected, when exactly one is and it + * holds other nodes. A node that holds none is no place to search in: the + * search stays in the whole view. + */ +export function findScopeOf(selected: readonly FindElement[]): FindScope | undefined { + const nodes = selected.filter(isFindable); + if (nodes.length !== 1 || !holdsNodes(nodes[0])) { + return undefined; + } + const node = nodes[0]; + const texts = findTextsOf(node); + const name = texts[NAME_FIELD] ?? ''; + // A node with no name reads as the first text it is found by (what kind + // of step it is), rather than as its id. + const shown = name || Object.values(texts).find(text => text !== '') || node.id; + return { elementId: node.id, label: `in ${shown}`, name: name || undefined }; +} + +/** What the count above the list says. */ +export function findSummary(total: number, listed: number): string { + if (total === 0) { + return 'no matches'; + } + if (total > listed) { + return `${total} matches, the first ${listed} listed`; + } + return `${total} match${total === 1 ? '' : 'es'}`; +} + +/** + * What a row says after the match: the context, or, inside a scope whose + * name is that context already, the line. + */ +export function findTrailing(match: FindMatch, scope: FindScope | undefined): string { + const inScope = scope?.name !== undefined && match.context === scope.name; + if (!inScope) { + return match.context; + } + return match.line !== undefined ? `:${match.line + 1}` : ''; +} + +export interface FindPanelOptions { + /** The model: read for every query, since it is replaced on every update. */ + getRoot: () => FindElement | undefined; + /** An element of the model by its id. */ + getById?: (id: string) => FindElement | undefined; + /** The elements selected, read for every query: the scope is taken from them (`findScopeOf`). */ + getSelected: () => readonly FindElement[]; + /** Select and centre a match. */ + onReveal: (elementId: string) => void; + /** Clear the selection, so that the whole view is searched. */ + onClearScope: () => void; + /** The text, each time it changes, and empty when the box closes: a palette filters its tools by it. */ + onQuery?: (text: string) => void; +} + +/** The class of the box, at the top of the palette's body. */ +export const FIND_PANEL_CLASS = 'diagram-find'; + +/** + * The box: the scope's chip, the query, a tab per field, the expression + * toggle and the list of matches. It is a block of the palette's body, not + * a window over it, so it extends the palette downwards and the palette + * stays one thing. It owns its DOM and nothing else. + */ +export class DiagramFindPanel { + readonly element: HTMLDivElement; + private readonly input: HTMLInputElement; + private readonly scopeRow: HTMLDivElement; + private readonly fieldRow: HTMLDivElement; + private readonly summary: HTMLDivElement; + private readonly results: HTMLDivElement; + private readonly regexButton: HTMLButtonElement; + private fields: SearchField[] = []; + private field: string | undefined; + private regex = false; + private scope: FindScope | undefined; + /** + * A node whose selection is no scope: the hit find selected last, or the + * scope the reader left with its ×. Both are selected or deselected by + * an action, which is handled after the click returns: `before` is the + * selection at the click, and `seen` says the selection has been that + * node since. + */ + private passed: { id: string; seen: boolean; before: string } | undefined; + /** The text the palette was last told (`onQuery`). */ + private told = ''; + /** What the list shows, so that a search with the same answer leaves its rows, and the focus on one, alone. */ + private listed = ''; + private debounce: ReturnType | undefined; + + constructor(private readonly options: FindPanelOptions) { + this.element = document.createElement('div'); + this.element.className = FIND_PANEL_CLASS; + this.element.hidden = true; + // A click inside must not reach the diagram, which would clear the + // selection the scope is read from. + this.element.addEventListener('mousedown', event => event.stopPropagation()); + + const heading = document.createElement('div'); + heading.className = 'diagram-find-heading'; + heading.textContent = 'Find'; + this.element.appendChild(heading); + + this.scopeRow = document.createElement('div'); + this.scopeRow.className = 'diagram-find-scope'; + this.element.appendChild(this.scopeRow); + + const inputRow = document.createElement('div'); + inputRow.className = 'diagram-find-query'; + this.input = document.createElement('input'); + this.input.type = 'text'; + this.input.className = 'diagram-find-input'; + this.input.placeholder = 'find in the diagram…'; + this.input.setAttribute('aria-label', 'Find in the diagram'); + this.input.addEventListener('input', () => this.schedule()); + this.input.addEventListener('keydown', event => { + if (event.key === 'Escape') { + event.stopPropagation(); + this.hide(); + } else if (event.key === 'Enter') { + // The list may still be that of the text before the last + // keys: the search waits for a pause in the typing. + this.search(); + this.results.querySelector('.diagram-find-result')?.click(); + } + }); + inputRow.appendChild(this.input); + + this.regexButton = document.createElement('button'); + this.regexButton.className = 'diagram-find-field diagram-find-regex'; + this.regexButton.textContent = '.*'; + this.regexButton.title = 'Read the query as a regular expression'; + this.regexButton.setAttribute('aria-pressed', 'false'); + this.regexButton.addEventListener('click', () => { + this.regex = !this.regex; + this.regexButton.classList.toggle('active', this.regex); + this.regexButton.setAttribute('aria-pressed', String(this.regex)); + this.search(); + }); + inputRow.appendChild(this.regexButton); + this.element.appendChild(inputRow); + + this.fieldRow = document.createElement('div'); + this.fieldRow.className = 'diagram-find-fields'; + this.element.appendChild(this.fieldRow); + + this.summary = document.createElement('div'); + this.summary.className = 'diagram-find-summary'; + this.summary.setAttribute('aria-live', 'polite'); + this.element.appendChild(this.summary); + + this.results = document.createElement('div'); + this.results.className = 'diagram-find-results'; + this.element.appendChild(this.results); + this.drawFields([]); + } + + get isOpen(): boolean { + return !this.element.hidden; + } + + /** Put the box at the top of a body. */ + mount(host: HTMLElement): void { + if (this.element.parentElement !== host || host.firstChild !== this.element) { + host.insertBefore(this.element, host.firstChild); + } + } + + /** + * What the box has of the focus, to be put back once its palette has + * drawn its body anew. GLSP replaces the whole body, which takes the box + * out of the page for a moment, and an element out of the page loses the + * focus for good: the next key would go to the page, not the query. + */ + keepFocus(): () => void { + if (typeof document === 'undefined' || document.activeElement !== this.input) { + return () => undefined; + } + const start = this.input.selectionStart; + const end = this.input.selectionEnd; + return () => { + if (this.element.isConnected && document.activeElement !== this.input) { + this.input.focus({ preventScroll: true }); + this.input.setSelectionRange(start, end); + } + }; + } + + show(): void { + this.element.hidden = false; + this.told = this.input.value; + this.options.onQuery?.(this.told); + this.input.focus(); + this.input.select(); + this.search(); + } + + hide(): void { + this.element.hidden = true; + if (this.debounce) { + clearTimeout(this.debounce); + this.debounce = undefined; + } + this.told = ''; + this.options.onQuery?.(''); + } + + toggle(): void { + if (this.isOpen) { + this.hide(); + } else { + this.show(); + } + } + + /** Search again, the model or the selection having changed. */ + refresh(): void { + if (this.isOpen) { + this.search(); + } + } + + private schedule(): void { + if (this.debounce) { + clearTimeout(this.debounce); + } + this.debounce = setTimeout(() => this.search(), 150); + } + + /** One tab per field the root names, none when it names fewer than two. */ + private drawFields(fields: SearchField[]): void { + this.fields = fields; + if (this.field === undefined || !fields.some(field => field.key === this.field)) { + this.field = fields[0]?.key; + } + const tabs = fields.length > 1 ? fields.map(field => { + const tab = document.createElement('button'); + tab.className = 'diagram-find-field'; + tab.textContent = field.label; + if (field.title) { + tab.title = field.title; + } + tab.dataset.field = field.key; + const chosen = field.key === this.field; + tab.classList.toggle('active', chosen); + tab.setAttribute('aria-pressed', String(chosen)); + tab.addEventListener('click', () => { + this.field = field.key; + for (const other of Array.from(this.fieldRow.querySelectorAll('[data-field]'))) { + const on = other.dataset.field === field.key; + other.classList.toggle('active', on); + other.setAttribute('aria-pressed', String(on)); + } + this.search(); + }); + return tab; + }) : []; + this.fieldRow.replaceChildren(...tabs); + this.fieldRow.hidden = tabs.length === 0; + } + + private drawScope(): void { + const chip = document.createElement('span'); + chip.className = 'diagram-find-scope-chip'; + chip.textContent = this.scope?.label ?? 'in view'; + const parts: HTMLElement[] = [chip]; + if (this.scope?.elementId) { + const clear = document.createElement('button'); + clear.className = 'diagram-find-scope-clear'; + clear.textContent = '×'; + clear.title = 'Find in the whole view instead'; + clear.setAttribute('aria-label', clear.title); + clear.addEventListener('click', () => { + // The node stays selected until the action that deselects it + // is handled: until then its selection is no scope. + this.passed = this.scope?.elementId ? { id: this.scope.elementId, seen: true, before: '' } : undefined; + this.scope = undefined; + this.options.onClearScope(); + this.drawScope(); + this.search(); + }); + parts.push(clear); + } + this.scopeRow.replaceChildren(...parts); + } + + private search(): void { + if (this.debounce) { + clearTimeout(this.debounce); + this.debounce = undefined; + } + const root = this.options.getRoot(); + const fields = searchFieldsOf(root?.args); + if (JSON.stringify(fields) !== JSON.stringify(this.fields)) { + this.drawFields(fields); + } + // The palette filters its tools by the text searched: told here and + // not at every key, since it draws its whole body again for it. + if (this.input.value !== this.told) { + this.told = this.input.value; + this.options.onQuery?.(this.told); + } + const scope = this.scopeNow(root); + if (scope?.elementId !== this.scope?.elementId || this.scopeRow.childElementCount === 0) { + this.scope = scope; + this.drawScope(); + } + if (this.input.value.trim() === '') { + this.listed = ''; + this.summary.textContent = ''; + this.results.replaceChildren(); + return; + } + // Tabs are drawn for two fields or more. A root that names one gets + // none, and a search of that one field alone would be a filter the + // reader cannot see: every text of a node is matched instead. + const { matches, total } = findMatches(root, { + text: this.input.value, + field: this.fields.length > 1 ? this.field : undefined, + regex: this.regex, + scope: this.scope + }, this.options.getById); + const listed = JSON.stringify([total, this.scope?.name, matches]); + if (listed === this.listed) { + return; + } + this.listed = listed; + this.summary.textContent = findSummary(total, matches.length); + this.results.replaceChildren(...matches.map(match => this.drawMatch(match))); + } + + /** + * Where to search now. Read before every query, not only when the box + * opens: the reader picks what to search in by clicking the diagram, and + * the box stays open through it. A node find selected itself, or one the + * reader left with the ×, is not where the reader asked to search: the + * scope stays what it was until something else is selected. + */ + private scopeNow(root: FindElement | undefined): FindScope | undefined { + const selected = this.options.getSelected().filter(isFindable); + const passed = this.passed; + if (passed) { + const isPassed = selected.length === 1 && selected[0].id === passed.id; + passed.seen = passed.seen || isPassed; + // Its action not handled yet, the selection is still that of the click. + if (isPassed || (!passed.seen && this.selectedIds() === passed.before)) { + // Kept while the model holds its node: a chip naming a node + // that is gone would say a search of the whole view is inside it. + return root && this.scope && !scopeNodeOf(root, this.scope, this.options.getById) ? undefined : this.scope; + } + // The reader selected something else: a later selection of that + // node is theirs, and a scope again. + this.passed = undefined; + } + return findScopeOf(selected); + } + + private selectedIds(): string { + return this.options.getSelected().filter(isFindable).map(element => element.id).join('\n'); + } + + private drawMatch(match: FindMatch): HTMLElement { + const row = document.createElement('button'); + row.className = 'diagram-find-result'; + row.addEventListener('click', () => { + this.passed = { id: match.elementId, seen: false, before: this.selectedIds() }; + this.options.onReveal(match.elementId); + }); + const primary = document.createElement('span'); + primary.className = 'diagram-find-result-primary'; + primary.textContent = match.primary; + row.appendChild(primary); + if (match.detail) { + const detail = document.createElement('span'); + detail.className = 'diagram-find-result-detail'; + detail.textContent = match.detail; + row.appendChild(detail); + } + const trailing = findTrailing(match, this.scope); + if (trailing) { + const context = document.createElement('span'); + context.className = 'diagram-find-result-context'; + context.textContent = trailing; + row.appendChild(context); + } + return row; + } +} diff --git a/packages/diagram-client/src/index.ts b/packages/diagram-client/src/index.ts index 30a88cf5..b94b8c63 100644 --- a/packages/diagram-client/src/index.ts +++ b/packages/diagram-client/src/index.ts @@ -237,6 +237,20 @@ export { // feature modules, which come after the base module that binds this one. It // draws what it has of its own in `drawOwnContent`. export { ViewToolPalette, EMPTY_PALETTE_BODY_CLASS } from './view-tool-palette'; +// Find in the diagram, which the palette's loupe opens (diagram-find.ts): a +// producer feeds it with `SEARCH_TEXT`, `SEARCH_DETAIL` and `SEARCH_FIELDS`. +// Its styles are `diagram-find.css` (diagram-client.css @imports it). +export { + DiagramFindPanel, + FIND_PANEL_CLASS, + findMatches, + findScopeOf, + findTextsOf, + type FindElement, + type FindMatch, + type FindQuery, + type FindScope +} from './diagram-find'; // The mark on a product's own card over the canvas, for Fit and `reveal` to // keep the drawing clear of it (canvas-overlays.ts). export { CANVAS_OVERLAY_ATTRIBUTE } from './canvas-overlays'; diff --git a/packages/diagram-client/src/view-tool-palette.ts b/packages/diagram-client/src/view-tool-palette.ts index 996ec007..c4db8541 100644 --- a/packages/diagram-client/src/view-tool-palette.ts +++ b/packages/diagram-client/src/view-tool-palette.ts @@ -14,12 +14,18 @@ * (`view-options.ts`, `view-options-palette.ts`), and redraws them, and only * them, when they change. GLSP says "No results found." whenever it has no * tools, which a palette with view options, or with nothing at all (a - * product that creates nothing), is not: it says it only when a filter - * matched neither a tool nor a line. + * product that creates nothing), is not: it says nothing of it, and find + * says what its text matched. * * A product's palette extends it, and draws what it has of its own in the - * body (a search, settings) in `drawOwnContent`: it is then counted, so that - * body is not hidden as empty. + * body (settings) in `drawOwnContent`: it is then counted, so that body is + * not hidden as empty. + * + * Its loupe opens find in the diagram (`diagram-find.ts`) at the top of the + * body, in place of GLSP's field that filters the tools alone: the same text + * filters the tools, where there are any, and finds nodes in the model. A + * hit is selected and centred, at the zoom shown where the names are drawn + * there, else fitted. * * It opens minimized, its button alone at the top right, until the reader * opens it; then each diagram of the product, of any file, opens it as the @@ -27,18 +33,21 @@ * at every show. */ import { type Action, type GModelRoot, SetModelAction, ToolPalette, UpdateModelAction } from '@eclipse-glsp/client'; +import { CenterAction, FitToScreenAction, SelectAction } from '@eclipse-glsp/protocol'; import { WorkflowDiagramMetadata } from '@dialogram/shared'; import { inject, injectable, optional } from 'inversify'; +import { DiagramFindPanel, type FindElement } from './diagram-find'; import { settingsNamespace } from './profile'; import { ViewOptionsService } from './view-options'; import { drawViewOptionGroups, safeStorage, VIEW_OPTIONS_CLASS, ViewOptionsCollapse } from './view-options-palette'; +import { NAME_ZOOM } from './zoom-detail'; -/** What GLSP's palette says when it has nothing to show. */ -const NO_RESULTS = 'No results found.'; /** The class of the body when it has nothing at all to show, and is not drawn. */ export const EMPTY_PALETTE_BODY_CLASS = 'palette-body-empty'; -/** The class of the words this palette says when a filter found nothing. */ -const NOTHING_FOUND_CLASS = 'palette-nothing-found'; +/** How close a hit is fitted when the zoom shown draws no names: no closer than the drawing's own size. */ +const FIND_FIT_MAX_ZOOM = 1; +/** The margin around a hit that is fitted. */ +const FIND_FIT_PADDING = 40; /** GLSP's icon on the palette's button while the palette is open, and while it is minimized. */ const OPEN_ICON_CLASS = 'codicon-chevron-right'; @@ -100,6 +109,7 @@ export class ViewToolPalette extends ToolPalette { private readonly collapse = new ViewOptionsCollapse(); private readonly openState = new PaletteOpenState(); private viewOptionsWatched = false; + private findPanel: DiagramFindPanel | undefined; /** Shown as the reader left it: GLSP opens it at every show. */ protected override onBeforeShow(containerElement: HTMLElement, root: Readonly): void { @@ -140,6 +150,86 @@ export class ViewToolPalette extends ToolPalette { super.handle(action); } + /** The loupe opens find in the diagram, not GLSP's field. */ + protected override createSearchButton(): HTMLElement { + const button = super.createSearchButton(); + button.title = 'Find in the diagram'; + button.ariaLabel = button.title; + button.onclick = event => { + event.stopPropagation(); + this.find().toggle(); + }; + return button; + } + + /** The box of find, made once and kept at the top of the body each time it is drawn. */ + protected find(): DiagramFindPanel { + if (!this.findPanel) { + this.findPanel = new DiagramFindPanel({ + getRoot: () => this.editorContext?.modelRoot as unknown as FindElement | undefined, + getById: id => (this.editorContext?.modelRoot as unknown as { index?: { getById(id: string): unknown } } | undefined) + ?.index?.getById(id) as FindElement | undefined, + getSelected: () => (this.editorContext?.selectedElements ?? []) as unknown as FindElement[], + onReveal: id => this.revealFound(id), + onClearScope: () => void this.actionDispatcher.dispatch( + SelectAction.create({ selectedElementsIDs: [], deselectedElementsIDs: true }) + ), + onQuery: text => this.filterTools(text) + }); + if (this.bodyDiv) { + this.findPanel.mount(this.bodyDiv); + } + // The reader picks where to search by clicking the diagram: the + // chip and the matches follow the selection while the box is open. + // They follow the model too, once it is the one shown: the action + // that brings a model is handled before its root is in place, and + // a search then would be of the model it replaces. + const context = this.editorContext as { + onSelectionChanged?: (listener: () => void) => unknown; + onModelRootChanged?: (listener: () => void) => unknown; + } | undefined; + context?.onSelectionChanged?.(() => this.findPanel?.refresh()); + context?.onModelRootChanged?.(() => this.findPanel?.refresh()); + } + return this.findPanel; + } + + /** + * The tools filtered by the text of find, as GLSP's field filters them, + * where the palette lists any. The text goes in GLSP's field too, hidden, + * so that the tools asked for again are filtered by it as well. + */ + private filterTools(text: string): void { + const tools = (this.paletteItemsCopy ?? []).length > 0 || (this.paletteItems ?? []).length > 0; + if (tools && this.searchField && this.searchField.value !== text) { + this.searchField.value = text; + this.requestFilterUpdate(text); + } else { + this.markEmpty(); + } + } + + /** + * The zoom from which a hit can be read where it is: the one names are + * drawn from. A product whose matches are read in the detail of a node + * (a value in a row of its body) says the zoom its detail is drawn from. + */ + protected findReadableZoom(): number { + return NAME_ZOOM; + } + + /** Select a hit and bring it in sight, where it can be read. */ + private revealFound(id: string): void { + void this.actionDispatcher.dispatch(SelectAction.create({ selectedElementsIDs: [id], deselectedElementsIDs: true })); + const zoom = (this.editorContext?.modelRoot as unknown as { zoom?: unknown } | undefined)?.zoom; + // Centred at the zoom shown when the hit can be read there, so that + // going through the matches does not zoom at every click. Below it, + // a centred hit is a box without its text: it is fitted instead. + void this.actionDispatcher.dispatch(typeof zoom === 'number' && zoom >= this.findReadableZoom() + ? CenterAction.create([id], { animate: true, retainZoom: true }) + : FitToScreenAction.create([id], { padding: FIND_FIT_PADDING, maxZoom: FIND_FIT_MAX_ZOOM, animate: true })); + } + protected override async setPaletteItems(): Promise { await super.setPaletteItems(); this.itemsDynamic = this.dynamic; @@ -156,6 +246,8 @@ export class ViewToolPalette extends ToolPalette { } protected override createBody(): void { + // GLSP draws a new body in place of the old, the box of find with it. + const refocus = this.findPanel?.keepFocus(); super.createBody(); const body = this.bodyDiv; if (body) { @@ -166,7 +258,11 @@ export class ViewToolPalette extends ToolPalette { body.lastElementChild.remove(); } this.drawOwnContent(body); + if (this.findPanel) { + this.findPanel.mount(body); + } } + refocus?.(); if (!this.viewOptionsWatched && this.viewOptions) { this.viewOptionsWatched = true; this.viewOptions.onDidChange(() => this.drawViewOptions()); @@ -189,9 +285,6 @@ export class ViewToolPalette extends ToolPalette { if (!body || typeof document === 'undefined') { return; } - const filter = this.searchField?.value ?? ''; - const tools = (this.paletteItems ?? []).length > 0; - body.querySelector(`:scope > .${NOTHING_FOUND_CLASS}`)?.remove(); let holder = body.querySelector(`:scope > .${VIEW_OPTIONS_CLASS}`); if (!holder) { holder = document.createElement('div'); @@ -214,8 +307,10 @@ export class ViewToolPalette extends ToolPalette { item: active.dataset.item, header: active.classList.contains('view-options-header') } : undefined; + // The text of find filters the tools, not the view options: what is + // found is nodes. holder.replaceChildren(...drawViewOptionGroups(service?.groups ?? [], { - filter, + filter: '', isCollapsed: group => this.collapse.isCollapsed(group), onCollapse: (group, collapsed) => { this.collapse.set(group, collapsed); @@ -236,18 +331,26 @@ export class ViewToolPalette extends ToolPalette { again?.focus({ preventScroll: true }); } } - const options = holder.childElementCount > 0; + this.markEmpty(); + } + + /** + * The body hidden when it has nothing to show: no tool, no view option, + * nothing of the product's own, and find closed. + */ + private markEmpty(): void { + const body = this.bodyDiv; + if (!body) { + return; + } + const tools = (this.paletteItems ?? []).length > 0; + const holder = body.querySelector(`:scope > .${VIEW_OPTIONS_CLASS}`); + const options = (holder?.childElementCount ?? 0) > 0; + const find = this.findPanel?.element; // What the product drew of its own: anything else in the body. - const own = Array.from(body.children).some(child => child !== holder && !child.classList.contains('tool-group') && !child.classList.contains('tool-button')) + const own = Array.from(body.children).some(child => child !== holder && child !== find + && !child.classList.contains('tool-group') && !child.classList.contains('tool-button')) || (!tools && body.querySelector(':scope > .tool-button') !== null); - if (!tools && !options && filter.trim() !== '') { - // A filter that matched neither a tool nor a line: that is what - // the words are for. - const nothing = document.createElement('div'); - nothing.classList.add('tool-button', NOTHING_FOUND_CLASS); - nothing.textContent = NO_RESULTS; - body.insertBefore(nothing, holder); - } - body.classList.toggle(EMPTY_PALETTE_BODY_CLASS, !tools && !options && !own && filter.trim() === ''); + body.classList.toggle(EMPTY_PALETTE_BODY_CLASS, !tools && !options && !own && !(this.findPanel?.isOpen ?? false)); } } diff --git a/packages/diagram-client/test/diagram-find.test.ts b/packages/diagram-client/test/diagram-find.test.ts new file mode 100644 index 00000000..1334591f --- /dev/null +++ b/packages/diagram-client/test/diagram-find.test.ts @@ -0,0 +1,550 @@ +// @vitest-environment happy-dom +/** + * Find in the diagram: what the palette's loupe finds in the model, inside + * the selection when there is one, and how the box and the palette answer. + */ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { readFileSync } from 'node:fs'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { searchFieldsOf } from '@dialogram/shared'; +import { + DiagramFindPanel, + FIND_LIMIT, + findMatches, + findScopeOf, + findSummary, + findTextsOf, + findTrailing, + type FindElement +} from '../src/diagram-find'; +import { EMPTY_PALETTE_BODY_CLASS, ViewToolPalette } from '../src/view-tool-palette'; + +/** A model with parents set, as GLSP's index gives them. */ +function model(root: FindElement): FindElement { + const link = (element: FindElement): void => { + for (const child of element.children ?? []) { + (child as { parent?: FindElement }).parent = element; + link(child); + } + }; + link(root); + return root; +} + +const node = (id: string, args: Record, children: FindElement[] = []): FindElement => + ({ id, type: 'node:task', args, children }); + +/** Two agents in a group, a port and a label that must not be found. */ +function workflow(): FindElement { + return model({ + id: 'graph', + type: 'graph', + args: {}, + children: [ + node('g', { 'wf:groupLabel': 'review' }, [ + node('a', { 'cal:entityName': 'planner', 'cal:sourceRange': { start: { line: 11, character: 4 } } }), + node('b', { 'cal:entityName': 'critic' }), + { id: 'g.port', type: 'port', args: { 'cal:entityName': 'planner_in' } } + ]), + node('c', { 'cal:entityName': 'Planner 2' }), + { id: 'label', type: 'label:name', args: { 'cal:entityName': 'planner' } } + ] + }); +} + +/** Operations with a text per field, as a producer with search fields gives them. */ +function module(): FindElement { + return model({ + id: 'graph', + type: 'graph', + args: { + 'wf:searchFields': [ + { key: 'op', label: 'Op', title: 'The operation' }, + { key: 'name', label: 'Symbol' }, + { key: 'ssa', label: 'SSA' } + ] + }, + children: [ + node('f', { 'wf:searchText': { op: 'func.func', name: '@f' } }, [ + node('f.0', { 'wf:searchText': { op: 'arith.constant', ssa: '%c0 : i32' }, 'wf:searchDetail': '%c0' }), + node('f.1', { 'wf:searchText': { op: 'arith.addi', ssa: '%1 : i32 (%c0, %a)' }, 'wf:searchDetail': '%1' }) + ]), + node('g', { 'wf:searchText': { op: 'func.func', name: '@g' } }, [ + node('g.0', { 'wf:searchText': { op: 'arith.constant', ssa: '%c1 : i32' }, 'wf:searchDetail': '%c1' }) + ]) + ] + }); +} + +const ids = (result: { matches: Array<{ elementId: string }> }): string[] => result.matches.map(match => match.elementId); + +describe('findMatches', () => { + it('finds nodes by name, whatever the case, and never a port or a label', () => { + expect(ids(findMatches(workflow(), { text: 'PLANNER' }))).toEqual(['a', 'c']); + }); + + it('finds a frame by its group label', () => { + expect(ids(findMatches(workflow(), { text: 'review' }))).toEqual(['g']); + }); + + it('finds nothing for an empty query or an unfinished expression', () => { + expect(findMatches(workflow(), { text: ' ' })).toEqual({ matches: [], total: 0 }); + expect(findMatches(workflow(), { text: 'plan(', regex: true })).toEqual({ matches: [], total: 0 }); + expect(findMatches(undefined, { text: 'planner' })).toEqual({ matches: [], total: 0 }); + }); + + it('reads the query as an expression when asked', () => { + expect(ids(findMatches(workflow(), { text: '^(planner|critic)$', regex: true }))).toEqual(['a', 'b']); + }); + + it('matches the field chosen, and the name a producer gives for find', () => { + expect(ids(findMatches(module(), { text: 'constant', field: 'op' }))).toEqual(['f.0', 'g.0']); + expect(ids(findMatches(module(), { text: '@g', field: 'name' }))).toEqual(['g']); + // `%c0` is an operand of the addi, and its own value is not. + expect(ids(findMatches(module(), { text: '%c0', field: 'ssa' }))).toEqual(['f.0', 'f.1']); + expect(ids(findMatches(module(), { text: 'constant', field: 'ssa' }))).toEqual([]); + }); + + it('matches every text of a node when no field is chosen, a single text with the name', () => { + expect(ids(findMatches(module(), { text: '@f' }))).toEqual(['f']); + const root = model({ id: 'graph', type: 'graph', children: [node('x', { 'cal:entityName': 'x', 'wf:searchText': 'retries on timeout' })] }); + expect(findMatches(root, { text: 'timeout' }).matches[0]).toMatchObject({ elementId: 'x', primary: 'retries on timeout' }); + }); + + it('searches inside the scope, and in the whole view when its node is gone', () => { + const scope = { elementId: 'g', label: 'in @g', name: '@g' }; + expect(ids(findMatches(module(), { text: 'constant', field: 'op', scope }))).toEqual(['g.0']); + expect(ids(findMatches(module(), { text: 'constant', field: 'op', scope: { ...scope, elementId: 'gone' } }))).toEqual(['f.0', 'g.0']); + }); + + it('searches what the scope holds, not the node of the scope itself', () => { + const scope = { elementId: 'g', label: 'in @g', name: '@g' }; + expect(ids(findMatches(module(), { text: 'func', field: 'op' }))).toEqual(['f', 'g']); + expect(ids(findMatches(module(), { text: 'func', field: 'op', scope }))).toEqual([]); + expect(ids(findMatches(workflow(), { text: 'review', scope: { elementId: 'g', label: 'in review' } }))).toEqual([]); + }); + + it('takes the scope from the index when it is given one', () => { + const root = module(); + const byId = vi.fn(() => root.children![1]); + expect(ids(findMatches(root, { text: 'constant', field: 'op', scope: { elementId: 'g', label: 'in @g' } }, byId))).toEqual(['g.0']); + expect(byId).toHaveBeenCalledWith('g'); + }); + + it('says where a match is: the nearest named node, its line, and its detail unless the match holds it', () => { + const [planner] = findMatches(workflow(), { text: 'planner' }).matches; + expect(planner).toEqual({ elementId: 'a', primary: 'planner', detail: '', context: 'review', line: 11 }); + const [constant] = findMatches(module(), { text: 'arith.constant', field: 'op' }).matches; + expect(constant).toMatchObject({ primary: 'arith.constant', detail: '%c0', context: '@f' }); + const [value] = findMatches(module(), { text: '%c0 :', field: 'ssa' }).matches; + expect(value.detail).toBe(''); + }); + + it('lists the first matches and counts them all', () => { + const children = Array.from({ length: FIND_LIMIT + 5 }, (_, i) => node(`n${i}`, { 'cal:entityName': `step ${i}` })); + const found = findMatches(model({ id: 'graph', type: 'graph', children }), { text: 'step' }); + expect(found.total).toBe(FIND_LIMIT + 5); + expect(found.matches).toHaveLength(FIND_LIMIT); + expect(findMatches(model({ id: 'graph', type: 'graph', children }), { text: 'step', limit: 3 }).matches).toHaveLength(3); + }); +}); + +describe('what the box says', () => { + it('counts the matches', () => { + expect(findSummary(0, 0)).toBe('no matches'); + expect(findSummary(1, 1)).toBe('1 match'); + expect(findSummary(7, 7)).toBe('7 matches'); + expect(findSummary(900, 200)).toBe('900 matches, the first 200 listed'); + }); + + it('ends a row with its context, or with its line inside a scope of that name', () => { + const match = { elementId: 'a', primary: 'planner', detail: '', context: 'review', line: 11 }; + expect(findTrailing(match, undefined)).toBe('review'); + expect(findTrailing(match, { elementId: 'g', label: 'in review', name: 'review' })).toBe(':12'); + expect(findTrailing({ ...match, line: undefined }, { elementId: 'g', label: 'in review', name: 'review' })).toBe(''); + }); + + it('scopes to the one node selected that holds other nodes', () => { + const root = workflow(); + const group = root.children![0]; + expect(findScopeOf([group])).toEqual({ elementId: 'g', label: 'in review', name: 'review' }); + expect(findScopeOf([group, root.children![1]])).toBeUndefined(); + expect(findScopeOf([{ id: 'e', type: 'edge' }])).toBeUndefined(); + // A node that holds none is no place to search in. + expect(findScopeOf([group.children![0]])).toBeUndefined(); + expect(findScopeOf([node('x', {}, [node('y', {})])])).toEqual({ elementId: 'x', label: 'in x', name: undefined }); + expect(findScopeOf([node('loop', { 'wf:searchText': { op: 'scf.for', ssa: '%i' } }, [node('body', {})])])) + .toEqual({ elementId: 'loop', label: 'in scf.for', name: undefined }); + }); + + it('reads a node name before its group label, and a field named name over both', () => { + expect(findTextsOf(node('x', { 'cal:entityName': 'a', 'wf:groupLabel': 'b' })).name).toBe('a'); + expect(findTextsOf(node('x', { 'cal:entityName': 'a', 'wf:searchText': { name: '@a', op: 'func.func' } }))).toEqual({ name: '@a', op: 'func.func' }); + }); + + it('takes the fields a root names that are well formed, once each', () => { + expect(searchFieldsOf({ 'wf:searchFields': [{ key: 'op', label: 'Op', title: '' }, { key: 'op', label: 'Again' }, { key: '', label: 'x' }, { key: 'ssa' }, null, { key: 'name', label: 'Symbol', title: 'The symbol' }] })) + .toEqual([{ key: 'op', label: 'Op' }, { key: 'name', label: 'Symbol', title: 'The symbol' }]); + expect(searchFieldsOf({ 'wf:searchFields': 'op' })).toEqual([]); + expect(searchFieldsOf(undefined)).toEqual([]); + }); +}); + +describe('the box', () => { + afterEach(() => { + vi.useRealTimers(); + document.body.replaceChildren(); + }); + + function box(root: FindElement, selected: FindElement[] = []) { + const revealed: string[] = []; + const queries: string[] = []; + let cleared = 0; + // The selection is cleared by an action, handled after the click + // returns: `land` is that moment. + const panel = new DiagramFindPanel({ + getRoot: () => root, + getSelected: () => selected, + onReveal: id => revealed.push(id), + onClearScope: () => cleared++, + onQuery: text => queries.push(text) + }); + const select = (...elements: FindElement[]): void => { + selected.splice(0, selected.length, ...elements); + panel.refresh(); + }; + const chip = (): string => panel.element.querySelector('.diagram-find-scope-chip')?.textContent ?? ''; + document.body.appendChild(panel.element); + const input = panel.element.querySelector('.diagram-find-input')!; + const type = (text: string): void => { + input.value = text; + input.dispatchEvent(new Event('input')); + vi.advanceTimersByTime(200); + }; + const rows = (): string[] => Array.from(panel.element.querySelectorAll('.diagram-find-result')).map(row => row.textContent ?? ''); + return { panel, input, type, rows, revealed, queries, select, chip, cleared: () => cleared }; + } + + it('opens on the query, lists what it finds and goes to the first on Enter', () => { + vi.useFakeTimers(); + const { panel, input, type, rows, revealed, queries } = box(workflow()); + expect(panel.isOpen).toBe(false); + panel.show(); + expect(panel.isOpen).toBe(true); + expect(document.activeElement).toBe(input); + type('planner'); + expect(queries).toEqual(['', 'planner']); + expect(panel.element.querySelector('.diagram-find-summary')?.textContent).toBe('2 matches'); + expect(rows()).toEqual(['plannerreview', 'Planner 2']); + input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' })); + expect(revealed).toEqual(['a']); + }); + + it('closes on Escape and tells the palette its text is gone', () => { + vi.useFakeTimers(); + const { panel, input, type, queries } = box(workflow()); + panel.show(); + type('critic'); + input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })); + expect(panel.isOpen).toBe(false); + expect(queries.at(-1)).toBe(''); + }); + + it('offers a tab per field, the first chosen, and searches the one clicked', () => { + vi.useFakeTimers(); + const { panel, type, rows } = box(module()); + panel.show(); + const tabs = Array.from(panel.element.querySelectorAll('.diagram-find-field[data-field]')); + expect(tabs.map(tab => [tab.textContent, tab.classList.contains('active')])).toEqual([['Op', true], ['Symbol', false], ['SSA', false]]); + expect(tabs[0].title).toBe('The operation'); + type('%c'); + expect(rows()).toEqual([]); + tabs[2].click(); + // The detail of the addi (`%1`) is dropped: its match holds it already. + expect(rows()).toEqual(['%c0 : i32@f', '%1 : i32 (%c0, %a)@f', '%c1 : i32@g']); + expect(tabs[2].getAttribute('aria-pressed')).toBe('true'); + }); + + it('offers no tab where the root names no field, and keeps the expression toggle', () => { + const { panel } = box(workflow()); + panel.show(); + expect(panel.element.querySelectorAll('.diagram-find-field[data-field]')).toHaveLength(0); + expect(panel.element.querySelector('.diagram-find-regex')).not.toBeNull(); + }); + + it('goes on Enter to the first match of the text as it is, not as it was a moment ago', () => { + vi.useFakeTimers(); + const { panel, input, type, revealed, queries } = box(workflow()); + panel.show(); + type('planner'); + // Typed and entered within the pause the search waits for. + input.value = 'critic'; + input.dispatchEvent(new Event('input')); + input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' })); + expect(revealed).toEqual(['b']); + expect(queries).toEqual(['', 'planner', 'critic']); + }); + + it('tells the palette its text with the search, not at every key', () => { + vi.useFakeTimers(); + const { panel, input, queries } = box(workflow()); + panel.show(); + for (const text of ['p', 'pl', 'pla']) { + input.value = text; + input.dispatchEvent(new Event('input')); + vi.advanceTimersByTime(50); + } + expect(queries).toEqual(['']); + vi.advanceTimersByTime(200); + expect(queries).toEqual(['', 'pla']); + }); + + it('matches every text where the root names one field, which gets no tab', () => { + vi.useFakeTimers(); + const root = model({ + id: 'graph', + type: 'graph', + args: { 'wf:searchFields': [{ key: 'op', label: 'Op' }] }, + children: [node('x', { 'cal:entityName': 'decode', 'wf:searchText': { op: 'func.func' } })] + }); + const { panel, type, rows } = box(root); + panel.show(); + expect(panel.element.querySelectorAll('.diagram-find-field[data-field]')).toHaveLength(0); + type('decode'); + expect(rows()).toEqual(['decode']); + type('func'); + expect(rows()).toEqual(['func.func']); + }); + + it('searches inside the selection, and in the whole view once the chip is cleared', () => { + vi.useFakeTimers(); + const root = module(); + const { panel, type, rows, cleared, select, chip } = box(root, [root.children![1]]); + panel.show(); + expect(chip()).toBe('in @g'); + type('constant'); + // The context repeats the scope: the row ends with nothing, having no line. + expect(rows()).toEqual(['arith.constant%c1']); + // The node stays selected until the action that deselects it is handled. + panel.element.querySelector('.diagram-find-scope-clear')!.click(); + expect(cleared()).toBe(1); + expect(chip()).toBe('in view'); + expect(rows()).toHaveLength(2); + type('constan'); + expect(chip()).toBe('in view'); + select(); + expect(chip()).toBe('in view'); + // Selected again by the reader, it is a scope again. + select(root.children![1]); + expect(chip()).toBe('in @g'); + expect(rows()).toHaveLength(1); + }); + + it('keeps its scope when it selects a hit itself, and follows the reader\'s next selection', () => { + vi.useFakeTimers(); + const root = module(); + const [f, g] = root.children!; + const { panel, type, rows, select, chip } = box(root, [f]); + const row = (index: number): HTMLButtonElement => panel.element.querySelectorAll('.diagram-find-result')[index]; + panel.show(); + type('arith'); + expect(rows()).toHaveLength(2); + // The reveal selects the hit, as the palette's does, by an action. + row(0).click(); + select(f.children![0]); + expect(chip()).toBe('in @f'); + expect(rows()).toHaveLength(2); + // The next hit, and a model update before its action is handled. + row(1).click(); + panel.refresh(); + expect(chip()).toBe('in @f'); + select(f.children![1]); + expect(chip()).toBe('in @f'); + // The reader selects another function: the search follows. + select(g); + expect(chip()).toBe('in @g'); + expect(rows()).toHaveLength(1); + }); + + it('takes a node it revealed as the scope once the reader selects it again', () => { + vi.useFakeTimers(); + const root = module(); + const g = root.children![1]; + const { panel, type, select, chip } = box(root); + panel.show(); + panel.element.querySelector('.diagram-find-field[data-field="name"]')!.click(); + type('@g'); + panel.element.querySelector('.diagram-find-result')!.click(); + select(g); + expect(chip()).toBe('in view'); + select(); + select(g); + expect(chip()).toBe('in @g'); + }); + + it('leaves its rows alone when a search gives the same answer, so that a row keeps the focus', () => { + vi.useFakeTimers(); + const root = workflow(); + const { panel, type, select } = box(root); + panel.show(); + type('planner'); + const first = panel.element.querySelector('.diagram-find-result')!; + first.focus(); + first.click(); + select(root.children![0].children![0]); + expect(panel.element.querySelector('.diagram-find-result')).toBe(first); + expect(document.activeElement).toBe(first); + type('critic'); + expect(panel.element.querySelector('.diagram-find-result')).not.toBe(first); + }); + + it('goes to the top of a body, once', () => { + const { panel } = box(workflow()); + const body = document.createElement('div'); + body.appendChild(document.createElement('span')); + panel.mount(body); + panel.mount(body); + expect(body.firstChild).toBe(panel.element); + expect(body.childElementCount).toBe(2); + }); +}); + +describe('the palette', () => { + afterEach(() => { + vi.useRealTimers(); + document.body.replaceChildren(); + }); + + function palette(items: unknown[] = [], zoom = 1) { + const dispatched: Array<{ kind: string } & Record> = []; + const root = workflow(); + (root as { zoom?: number }).zoom = zoom; + const tools: any = new ViewToolPalette(); + tools.containerElement = document.createElement('div'); + document.body.appendChild(tools.containerElement); + tools.paletteItems = items; + tools.searchField = document.createElement('input'); + tools.actionDispatcher = { dispatch: (action: any) => dispatched.push(action) }; + const selectionListeners: Array<() => void> = []; + const rootListeners: Array<() => void> = []; + tools.editorContext = { + modelRoot: root, + selectedElements: [] as FindElement[], + onSelectionChanged: (listener: () => void) => selectionListeners.push(listener), + onModelRootChanged: (listener: () => void) => rootListeners.push(listener) + }; + tools.createBody(); + const select = (...elements: FindElement[]): void => { + tools.editorContext.selectedElements = elements; + selectionListeners.forEach(listener => listener()); + }; + // A model arrives as GLSP brings it: the action is handled while the + // root it replaces is still the one shown, and the root changes after. + const update = (newRoot: FindElement): void => { + tools.handle({ kind: 'updateModel', newRoot }); + tools.editorContext.modelRoot = newRoot; + rootListeners.forEach(listener => listener()); + }; + return { tools, dispatched, root, select, update, body: (): HTMLElement => tools.bodyDiv as HTMLElement }; + } + + it('opens find with its loupe, at the top of the body, which is then not hidden as empty', () => { + const { tools, body } = palette(); + expect(body().classList.contains(EMPTY_PALETTE_BODY_CLASS)).toBe(true); + const loupe = tools.createSearchButton() as HTMLElement; + expect(loupe.title).toBe('Find in the diagram'); + loupe.click(); + expect(body().firstElementChild?.classList.contains('diagram-find')).toBe(true); + expect(body().classList.contains(EMPTY_PALETTE_BODY_CLASS)).toBe(false); + loupe.click(); + expect(body().classList.contains(EMPTY_PALETTE_BODY_CLASS)).toBe(true); + }); + + it('filters its tools by the text of find, and keeps find at the top of the body drawn again', () => { + vi.useFakeTimers(); + const { tools, body } = palette([{ label: 'Nodes', children: [{ label: 'Agent' }, { label: 'Tool call' }] }]); + const find = tools.find(); + find.show(); + const input = find.element.querySelector('.diagram-find-input') as HTMLInputElement; + input.value = 'agent'; + input.dispatchEvent(new Event('input')); + // The body is drawn again with the search, not at every key. + expect(body().querySelectorAll('.tool-button')).toHaveLength(2); + vi.advanceTimersByTime(200); + expect(Array.from(body().querySelectorAll('.tool-button')).map(button => button.textContent)).toEqual(['Agent']); + expect(body().firstElementChild).toBe(find.element); + // GLSP drew a new body: the next key still goes to the query, where the caret was. + expect(document.activeElement).toBe(input); + expect(input.selectionStart).toBe(5); + expect(tools.searchField.value).toBe('agent'); + find.hide(); + expect(Array.from(body().querySelectorAll('.tool-button')).map(button => button.textContent)).toEqual(['Agent', 'Tool call']); + }); + + it('follows the selection while find is open: the chip and the matches are those of the node clicked', () => { + vi.useFakeTimers(); + const { tools, root, select } = palette(); + const find = tools.find(); + find.show(); + const input = find.element.querySelector('.diagram-find-input') as HTMLInputElement; + input.value = 'planner'; + input.dispatchEvent(new Event('input')); + vi.advanceTimersByTime(200); + const chip = (): string => find.element.querySelector('.diagram-find-scope-chip')?.textContent ?? ''; + expect(chip()).toBe('in view'); + expect(find.element.querySelectorAll('.diagram-find-result')).toHaveLength(2); + select(root.children![0]); + expect(chip()).toBe('in review'); + expect(find.element.querySelectorAll('.diagram-find-result')).toHaveLength(1); + }); + + it('follows the model while find is open: the matches are those of the model now shown', () => { + vi.useFakeTimers(); + const { tools, root, update } = palette(); + const find = tools.find(); + find.show(); + const input = find.element.querySelector('.diagram-find-input') as HTMLInputElement; + input.value = 'planner'; + input.dispatchEvent(new Event('input')); + vi.advanceTimersByTime(200); + const rows = (): string[] => Array.from(find.element.querySelectorAll('.diagram-find-result')).map(row => row.textContent ?? ''); + expect(rows()).toHaveLength(2); + const next = workflow(); + (next as { zoom?: number }).zoom = (root as { zoom?: number }).zoom; + next.children![0].children!.push({ id: 'd', type: 'node:task', args: { 'cal:entityName': 'planner 3' }, parent: next.children![0] }); + update(next); + expect(rows()).toEqual(['plannerreview', 'planner 3review', 'Planner 2']); + }); + + it('selects a hit and centres it where names are drawn, or fits it where they are not', () => { + const near = palette([], 0.8); + near.tools.revealFound('a'); + expect(near.dispatched.map(action => action.kind)).toEqual(['elementSelected', 'center']); + expect(near.dispatched[0]).toMatchObject({ selectedElementsIDs: ['a'], deselectAll: true }); + expect(near.dispatched[1]).toMatchObject({ elementIds: ['a'], retainZoom: true }); + const far = palette([], 0.2); + far.tools.revealFound('a'); + expect(far.dispatched[1]).toMatchObject({ kind: 'fit', elementIds: ['a'], maxZoom: 1, padding: 40 }); + }); + + it('fits a hit below the zoom a product reads its matches at', () => { + const { tools, dispatched } = palette([], 0.6); + tools.findReadableZoom = (): number => 0.8; + tools.revealFound('a'); + expect(dispatched[1]).toMatchObject({ kind: 'fit', elementIds: ['a'] }); + }); +}); + +describe('the stylesheet', () => { + const dir = path.dirname(fileURLToPath(import.meta.url)); + const css = readFileSync(path.join(dir, '../src/diagram-find.css'), 'utf8'); + + it('is imported with the client styles', () => { + expect(readFileSync(path.join(dir, '../src/diagram-client.css'), 'utf8')).toContain("@import './diagram-find.css';"); + }); + + it('hides the box while it is closed', () => { + expect(css).toMatch(/\.diagram-find\[hidden\]\s*\{\s*display:\s*none;/); + }); +}); diff --git a/packages/diagram-client/test/glsp-stub.ts b/packages/diagram-client/test/glsp-stub.ts index 00ba14d5..40c49428 100644 --- a/packages/diagram-client/test/glsp-stub.ts +++ b/packages/diagram-client/test/glsp-stub.ts @@ -245,6 +245,29 @@ export class ToolPalette { this.asked++; this.dynamic = this.dynamicItems; } + protected paletteItemsCopy: unknown[] = []; + /** As GLSP's: the loupe, whose click shows or hides the header's field. */ + protected createSearchButton(): HTMLElement { + const icon = document.createElement('i'); + icon.classList.add('codicon', 'codicon-search', 'search-icon'); + icon.onclick = () => { + if (this.searchField) { + this.searchField.style.display = this.searchField.style.display === 'none' ? '' : 'none'; + } + }; + return icon; + } + /** As GLSP's: the items whose children's labels hold the filter, from a copy of them all. */ + protected requestFilterUpdate(filter: string): void { + if (this.paletteItemsCopy.length === 0) { + this.paletteItemsCopy = JSON.parse(JSON.stringify(this.paletteItems)); + } + const all = JSON.parse(JSON.stringify(this.paletteItemsCopy)) as Array<{ label: string; children?: Array<{ label: string }> }>; + this.paletteItems = all + .map(group => ({ ...group, children: (group.children ?? []).filter(child => child.label.toLowerCase().includes(filter.toLowerCase())) })) + .filter(group => group.children.length > 0); + this.createBody(); + } handle(action: unknown): void { if (UpdateModelAction.is(action) || SetModelAction.is(action)) { void this.reloadPaletteBody(); diff --git a/packages/diagram-client/test/view-options.test.ts b/packages/diagram-client/test/view-options.test.ts index 77866130..f33817b6 100644 --- a/packages/diagram-client/test/view-options.test.ts +++ b/packages/diagram-client/test/view-options.test.ts @@ -458,16 +458,18 @@ describe('the palette', () => { expect(body().textContent).not.toContain('No results found.'); }); - it('says it when a filter matched neither a tool nor a line', () => { + it('leaves the view options whole, and says nothing, whatever text the hidden field of GLSP holds', () => { + // The loupe opens find (diagram-find.ts), whose text filters the + // tools alone: what it finds is nodes, and it says so itself. const service = new TestService(); service.modelRootChanged(rootOf([kinds])); - search.value = 'zzz'; palette(service, []); - expect(body().textContent).toBe('No results found.'); - search.value = 'kind 7'; + const lines = body().querySelectorAll('.view-option').length; + expect(lines).toBeGreaterThan(1); + search.value = 'zzz'; palette(service, []); expect(body().textContent).not.toContain('No results found.'); - expect(body().querySelectorAll('.view-option')).toHaveLength(1); + expect(body().querySelectorAll('.view-option')).toHaveLength(lines); }); /** A product's palette with a row of its own in the body, drawn with the palette's classes. */ @@ -505,16 +507,12 @@ describe('the palette', () => { expect(body().classList.contains(EMPTY_PALETTE_BODY_CLASS)).toBe(false); }); - it('still says it found nothing, beside the product\'s row, when a filter matched no tool and no line', () => { + it('keeps the product\'s row and the view options, and says nothing, whatever the hidden field holds', () => { const service = new TestService(); service.modelRootChanged(rootOf([kinds])); search.value = 'zzz'; const made = ownPalette(service, []); expect(body().querySelectorAll('.own-row')).toHaveLength(1); - expect(body().textContent).toContain('No results found.'); - made.drawViewOptions(); - expect(body().textContent!.match(/No results found\./g)).toHaveLength(1); - search.value = ''; made.drawViewOptions(); expect(body().textContent).not.toContain('No results found.'); expect(body().querySelectorAll('.own-row')).toHaveLength(1); diff --git a/packages/shared/src/diagram-types.ts b/packages/shared/src/diagram-types.ts index 2061a15a..12c76054 100644 --- a/packages/shared/src/diagram-types.ts +++ b/packages/shared/src/diagram-types.ts @@ -542,6 +542,27 @@ export namespace WorkflowDiagramMetadata { * line and column). The bar offers to go to its line. */ export const STALE_ERROR = 'wf:staleError'; + /** + * On a node: what find in the diagram (the palette's loupe) matches + * besides the name of the node (`ENTITY_NAME`, or `GROUP_LABEL` on a + * frame). A text, matched with the name, or a text per search field the + * root names in `SEARCH_FIELDS`. The field `name` stands for the name of + * the node, where the producer names it otherwise for find. + */ + export const SEARCH_TEXT = 'wf:searchText'; + /** + * On a node: a text shown after a match on its row, so that like matches + * can be told apart (the value a step defines, say). It is shown only + * where the match does not already hold it. + */ + export const SEARCH_DETAIL = 'wf:searchDetail'; + /** + * On the root: the fields find offers as tabs, `[{ key, label, title? }]`, + * each matched against the text of that key in a node's `SEARCH_TEXT`. + * The first is chosen first. Tabs take two fields or more: with one, or + * none, find matches a node by its name and any text it has. + */ + export const SEARCH_FIELDS = 'wf:searchFields'; /** * On the root of a read-only view: what the reader can still edit in it, * as the producer said (`graph.meta.edits`). `transition`: the @@ -800,6 +821,36 @@ export function viewCreatesOf(rootArgs: Record | undefined): Vi return out; } +/** A field of find in the diagram, as a root names it in `SEARCH_FIELDS`. */ +export interface SearchField { + /** The key of the text it matches in a node's `SEARCH_TEXT`. */ + key: string; + /** What its tab reads. */ + label: string; + /** What its tab says on hover. */ + title?: string; +} + +/** The fields of find a root names (`SEARCH_FIELDS`), those that are well formed. */ +export function searchFieldsOf(rootArgs: Record | undefined): SearchField[] { + const fields = rootArgs?.[WorkflowDiagramMetadata.SEARCH_FIELDS]; + if (!Array.isArray(fields)) { + return []; + } + const seen = new Set(); + const out: SearchField[] = []; + for (const field of fields) { + const key = (field as { key?: unknown } | null)?.key; + const label = (field as { label?: unknown } | null)?.label; + const title = (field as { title?: unknown } | null)?.title; + if (typeof key === 'string' && key !== '' && typeof label === 'string' && label !== '' && !seen.has(key)) { + seen.add(key); + out.push(typeof title === 'string' && title !== '' ? { key, label, title } : { key, label }); + } + } + return out; +} + /** What a drawn transition can be taken by (`TRANSITION_LABELS` on a root): none when it says none. */ export function transitionLabelsOf(rootArgs: Record | undefined): Array<{ id: string; label: string; description?: string }> { const labels = rootArgs?.[WorkflowDiagramMetadata.TRANSITION_LABELS];