1/**2 * A composition's declaration, printed to fit its own panel, with every node3 * name a button.4 *5 * The declaration is where any node can always be reached: a group with no6 * members renders nothing in a preview, and its name is still here.7 *8 * The panel responds to its own inputs: the composition, the panel's width9 * and its font. It keeps keyboard focus on the same node when it reprints,10 * and one name in the tab order, moved with the Up and Down keys.11 */12import { declaration, typeComposition } from"./composition.ts";13import { atPath } from"./grouping.ts";14import { highlightSource } from"./inspection.ts";15import { inlineObservation } from"./inline-observation.ts";1617exportinterfaceSourcePanelOptions {18/** The accessible name of a node's button. */19describe(path:string, node:Composition):string;20/**21 * The reader activated a node's name. `extend` is true when Shift was22 * held, which an owner may read as adding to the selection.23 */24choose(path:string, extend:boolean):void;25/** The pointer or focus is on a node, or has left the declaration. */26attend(path:string|undefined):void;27/**28 * Whether `focus` may scroll the name into view. A panel inside its own29 * scrolling box needs this; a panel in the page's flow keeps the page30 * where its reader left it.31 */32readonlyrevealFocus?:boolean;33readonlysignal:AbortSignal;34}3536exportclassSourcePanel {37readonlycode:HTMLElement;38readonly#options:SourcePanelOptions;39readonly#observer:ResizeObserver;40readonly#width:ReturnType<typeofinlineObservation>;41#model:Composition|undefined;42#columns=80;43#characterWidth=7.2;44#inlineSize=0;45#roving="0";46#chosen:readonlystring[] = [];47#destination:string|undefined;48#moving=false;49#structure=false;50#inspected:string|undefined;5152constructor(pre:HTMLElement, options:SourcePanelOptions) {53constcode=pre.querySelector("code");54if (!code) thrownewError("A source panel needs a code element");55this.code=code;56this.#options=options;57const { signal } =options;58this.#width=inlineObservation(pre);59this.#observer=newResizeObserver((entries) => {60constsize=entries.at(-1)?.contentBoxSize[0];61if (!size) return;62this.#inlineSize=size.inlineSize;63this.#fit();64 });65this.#observer.observe(this.#width.target);66constmeasureFont= () => {67if (signal.aborted) return;68constcontext=code.ownerDocument69 .createElement("canvas")70 .getContext("2d");71if (context) {72context.font=getComputedStyle(pre).font;73this.#characterWidth=context.measureText("0").width||7.2;74 }75this.#fit();76 };77code.ownerDocument.fonts.addEventListener("loadingdone", measureFont, {78signal,79 });80voidcode.ownerDocument.fonts.ready.then(measureFont);8182constpathAt= (target:EventTarget|null) =>83targetinstanceofElement84?target.closest<HTMLElement>("[data-path]")?.dataset.path85:undefined;86code.addEventListener(87"click",88 (event) => {89constpath=pathAt(event.target);90if (path) options.choose(path, event.shiftKey);91 },92 { signal },93 );94code.addEventListener(95"pointerover",96 (event) => {97constpath=pathAt(event.target);98if (path) options.attend(path);99 },100 { signal },101 );102code.addEventListener("pointerleave", () =>options.attend(undefined), {103signal,104 });105code.addEventListener(106"focusin",107 (event) => {108constname=event.target;109if (!(nameinstanceofHTMLElement) ||!name.dataset.path) return;110this.rove(name.dataset.path);111options.attend(name.dataset.path);112 },113 { signal },114 );115code.addEventListener(116"focusout",117 (event) => {118if (119!(event.relatedTargetinstanceofNode) ||120!code.contains(event.relatedTarget)121 )122options.attend(undefined);123 },124 { signal },125 );126code.addEventListener(127"keydown",128 (event) => {129if (130 (event.key!=="ArrowUp"&&event.key!=="ArrowDown") ||131!(event.targetinstanceofHTMLElement) ||132!event.target.classList.contains("code-name")133 )134return;135constnames=this.#names();136constnext=137names[138names.indexOf(event.target) + (event.key==="ArrowDown"?1:-1)139 ];140event.preventDefault();141next?.focus();142 },143 { signal },144 );145 }146147/** Prints `model`. Focus on a name stays with the node at the same path. */148show(model:Composition) {149this.#model=model;150this.#print();151 }152153/** Marks the selection: each selected node, and the lines it spans. */154mark(chosen:readonlystring[]) {155this.#chosen=chosen;156for (constelementofthis.code.querySelectorAll<HTMLElement>(157"[data-path]",158 )) {159constpath=element.dataset.path!;160element.dataset.chosen=String(161chosen.some(162 (choice) =>path===choice||path.startsWith(`${choice}.`),163 ),164 );165if (element.classList.contains("code-name")) {166// In move mode these buttons choose a destination, not the moving167// selection. Their names describe sources; aria-current marks target.168if (this.#moving) element.removeAttribute("aria-pressed");169else170element.setAttribute("aria-pressed", String(chosen.includes(path)));171 }172 }173 }174175/** Marks a proposed move destination without changing the selection. */176destination(path:string|undefined, moving=false) {177this.#destination=path;178this.#moving=moving;179for (constnameofthis.#names()) {180name.toggleAttribute("data-destination", name.dataset.path===path);181if (name.dataset.path===path) name.setAttribute("aria-current", "true");182elsename.removeAttribute("aria-current");183constmember=this.#model&&atPath(this.#model, name.dataset.path!);184if (member)185name.setAttribute(186"aria-label",187this.#options.describe(name.dataset.path!, member),188 );189 }190 }191192/** Marks the node whose boundary the previews are showing. */193inspect(structure:boolean, path:string|undefined) {194this.#structure=structure;195this.#inspected=path;196this.code.classList.toggle("inspecting", structure);197highlightSource(this.code, structure, path);198 }199200/** Puts the name at `path`, or the root's, in the tab order. */201rove(path:string) {202constnames=this.#names();203consttarget=names.find((name) =>name.dataset.path===path) ??names[0];204this.#roving=target?.dataset.path??"0";205for (constnameofnames) name.tabIndex=name===target?0:-1;206 }207208/** Moves keyboard focus to the name at `path`. */209focus(path:string) {210this.rove(path);211this.code212 .querySelector<HTMLElement>('.code-name[tabindex="0"]')213 ?.focus({ preventScroll: !this.#options.revealFocus });214 }215216dispose() {217this.#observer.disconnect();218this.#width.dispose();219 }220221 #names():HTMLElement[] {222return [...this.code.querySelectorAll<HTMLElement>(".code-name")];223 }224225 #fit() {226if (!this.#inlineSize) return;227constcolumns=Math.max(22816,229Math.min(80, Math.floor(this.#inlineSize/this.#characterWidth)),230 );231if (columns===this.#columns) return;232this.#columns=columns;233this.#print();234 }235236 #print() {237constmodel=this.#model;238if (!model) return;239constroot=this.code.getRootNode() asDocument|ShadowRoot;240constactive=root.activeElement;241constfocused=242activeinstanceofHTMLElement&&this.code.contains(active)243?active.dataset.path244:undefined;245constfragment=this.code.ownerDocument.createDocumentFragment();246for (constlineofdeclaration(model, "0", 0, this.#columns)) {247constrow=this.code.ownerDocument.createElement("span");248row.className="code-line";249row.style.setProperty("--continuation", `${(line.depth+1) *2}ch`);250if (line.path) row.dataset.path=line.path;251for (consttokenofline.tokens) {252constspan=this.code.ownerDocument.createElement(253token.kind?"button":"span",254 );255span.className=`token ${token.tone?? "plain"}${token.kind? " code-name" : ""}`;256span.textContent=token.text;257if (token.path) span.dataset.path=token.path;258if (token.kind&&token.path) {259span.setAttribute("type", "button");260constnode=atPath(model, token.path);261if (node)262span.setAttribute(263"aria-label",264this.#options.describe(token.path, node),265 );266 }267row.append(span);268 }269fragment.append(row);270 }271this.code.replaceChildren(fragment);272this.mark(this.#chosen);273this.destination(this.#destination, this.#moving);274this.inspect(this.#structure, this.#inspected);275if (focused) this.focus(focused);276elsethis.rove(this.#roving);277 }278}