1/**2 * One hosted view of a composition: a labeled slot, the rendered boxes, and3 * a caption saying what happened in that slot.4 *5 * Several previews can show the same composition at once. Each mounts its6 * own boxes, so each Switcher is decided from the space its own host gives7 * it, and each keeps its inspection anchors inside its own `.rendered` scope.8 * The host's size comes from CSS (`[data-preview]`); a preview with a9 * `width` option also lets the reader request one.10 *11 * The owner supplies the composition and the selection. A preview reports12 * the node a reader points at or chooses, by its authored path.13 */14importtype { Composition } from"./composition.ts";15import {16compositionMembers,17compositionSelector,18} from"./composition-elements.ts";19import { CompositionReadouts, ExampleReadouts } from"./example-readouts.ts";20import {21describeSelection,22prepareInspection,23updateInspection,24} from"./inspection.ts";25import { mountComposition, typeMountedComposition } from"./primitives.ts";26import { arrangementAttribute } from"./switcher-coordinator.ts";27import {28clampWidth,29maximumWidth,30minimumWidth,31widthControl,32typeWidthControl,33} from"./width-control.ts";3435exportinterfacePreviewOptions {36/** Names the slot for a reader, such as "Wide card". */37readonlylabel:string;38/** Names the slot for CSS, which sizes `[data-preview="…"]`. */39readonlyslot:string;40/** Present when the reader may request this host's width. */41readonlywidth?: {42readonlyinitial:number;43/** Independent space available for resizing when the preview itself44 * shrink-wraps its requested width. Must establish a containing block. */45readonlyavailableSpace?:HTMLElement;46/** `settled` is false while a drag continues. */47changed(width:number, settled:boolean):void;48 };49/** The reader clicked the node at `path`. */50choose(path:string):void;51/** The pointer is over the node at `path`, or has left the composition. */52attend(path:string|undefined):void;53}5455/** What the owner's selection asks every preview to show. */56exportinterfacePreviewDecoration {57/** Tint every box so nesting is visible. */58readonlystructure:boolean;59/** The node whose boundary, gaps and caption are shown. */60readonlyinspected:string|undefined;61/** The selected nodes. */62readonlychosen:readonlystring[];63/** A proposed move destination, distinct from the members being moved. */64readonlydestination?:string|undefined;65}6667exportclassCompositionPreview {68readonlyelement:HTMLElement;69readonly#rendered:HTMLElement;70readonly#caption:HTMLElement;71readonly#readouts:CompositionReadouts;72readonly#abort=newAbortController();73readonly#modeObserver=newMutationObserver(() =>this.#refreshModes());74readonly#captionObserver=newResizeObserver(() =>this.#refreshCaption());75readonly#widthControl:WidthControl|undefined;76#mounted:MountedComposition|undefined;77#modes:string[] = [];78#inspected:HTMLElement|undefined;7980constructor(document:Document, options:PreviewOptions) {81const { signal } =this.#abort;82constelement=document.createElement("section");83element.className="preview";84element.dataset.preview=options.slot;85constlabelId=`preview-${options.slot}`;86element.setAttribute("aria-labelledby", labelId);87element.innerHTML=`<div class="stage"><div class="viewport"><div class="bar"><span class="preview-label" id="${labelId}"></span>${88options.width89? `<label class="width"><span class="sr-only"></span><input type="number" min="${minimumWidth}" max="${maximumWidth}" step="1"><span aria-hidden="true">px</span></label>`90: ""91 }</div><div class="frame"><div class="rendered"></div>${92options.width93? '<div class="resize" aria-hidden="true" title="Drag to resize. Edit the width field for keyboard control."></div>'94: ""95 }</div></div></div><div class="caption"><span class="selection"></span><span class="note"></span></div>`;96constget= <TextendsHTMLElement=HTMLElement>(selector:string) =>97element.querySelector<T>(selector)!;98get(".preview-label").textContent=options.label;99this.element=element;100this.#rendered=get(".rendered");101this.#caption=get(".selection");102constviewport=get(".viewport");103constdirections= () =>this.#modes;104105if (options.width) {106const { changed } =options.width;107constinput=get<HTMLInputElement>(".width input");108get(".width .sr-only").textContent=`${options.label} width`;109constreadouts=newExampleReadouts(110options.width.availableSpace??get(".stage"),111viewport,112input,113get(".note"),114directions,115 );116this.#readouts=readouts;117viewport.style.inlineSize=`${options.width.initial}px`;118this.#widthControl=widthControl({119handle: get(".resize"),120viewport,121input,122limit: () =>readouts.maximum,123request: (width, settled, maximum=readouts.maximum) => {124if (!Number.isFinite(width)) {125readouts.refreshWidth();126return;127 }128constnext=clampWidth(width, maximum);129viewport.style.inlineSize=`${next}px`;130changed(next, settled);131 },132restore: () =>readouts.refreshWidth(),133signal,134 });135 } elsethis.#readouts=newCompositionReadouts(get(".note"), directions);136137constframe=get(".frame");138constpathAt= (target:EventTarget|null) =>139targetinstanceofElement140?target.closest<HTMLElement>(compositionSelector)?.dataset.path141:undefined;142frame.addEventListener(143"click",144 (event) => {145constpath=pathAt(event.target);146if (path) options.choose(path);147 },148 { signal },149 );150frame.addEventListener(151"pointermove",152 (event) => {153if (this.#widthControl?.dragging) return;154constpath=pathAt(event.target);155if (path) options.attend(path);156 },157 { signal },158 );159frame.addEventListener("pointerleave", () =>options.attend(undefined), {160signal,161 });162this.#modeObserver.observe(this.#rendered, {163attributes: true,164subtree: true,165attributeFilter: [arrangementAttribute],166 });167 }168169/** Shows `model`. Call `decorate` afterwards: the boxes are new. */170render(model:Composition, preserveScroll=false) {171// A wording edit keeps authored paths intact. Native scroll offsets are172// view state that DOM replacement otherwise loses; CSS cannot transfer173// them to a replacement box. Capture only for that edit, never on resize174// or regrouping, and let the browser clamp to the new scrollable extent.175constscroll=preserveScroll176? [177...this.#rendered.querySelectorAll<HTMLElement>(178'[data-kind="Shelf"]',179 ),180 ].map((shelf) => [shelf.dataset.path!, shelf.scrollLeft] asconst)181: [];182if (this.#mounted) this.#mounted.update(model);183elsethis.#mounted=mountComposition(this.#rendered, model);184for (const [path, offset] ofscroll) {185constshelf=this.#rendered.querySelector<HTMLElement>(186`[data-kind="Shelf"][data-path="${path}"]`,187 );188if (shelf) shelf.scrollLeft=offset;189 }190prepareInspection(this.#rendered);191// A group with no members and a text with no characters render nothing.192// Naming them lets CSS mark their place without adding to the layout.193for (constnodeofthis.#nodes()) {194constempty=node.classList.contains("leaf")195?node.textContent===""196:compositionMembers(node).length===0;197if (empty) node.dataset.empty="true";198 }199this.#inspected=undefined;200this.#captionObserver.disconnect();201this.#readouts.observeComposition(this.#rendered);202this.#refreshModes();203 }204205/** Applies the owner's selection to the boxes shown now. */206decorate({ structure, inspected, chosen, destination }:PreviewDecoration) {207for (constnodeofthis.#nodes()) {208constmarked=String(chosen.includes(node.dataset.path!));209if (node.dataset.chosen!==marked) node.dataset.chosen=marked;210node.toggleAttribute(211"data-destination",212node.dataset.path===destination,213 );214 }215constselected=updateInspection(this.#rendered, {216structure,217selected: inspected,218preview: [],219 });220if (selected!==this.#inspected) {221this.#captionObserver.disconnect();222this.#inspected=selected;223if (selected) {224// A primitive has one uniform gap: the first adjacent pair suffices.225for (constbandof [226...selected.querySelectorAll(227':scope > [data-decoration="gap"] [data-observation="gap"]',228 ),229 ].slice(0, 2))230this.#captionObserver.observe(band);231 }232 }233this.#refreshCaption();234 }235236dispose() {237this.#abort.abort();238this.#widthControl?.cancel();239this.#modeObserver.disconnect();240this.#captionObserver.disconnect();241this.#readouts.disconnect();242this.#mounted?.dispose();243this.#mounted=undefined;244this.#inspected=undefined;245this.element.remove();246 }247248 #nodes():HTMLElement[] {249return [250...this.#rendered.querySelectorAll<HTMLElement>(compositionSelector),251 ];252 }253254/** Effective modes can be derived from an ancestor's published arrangement.255 * Follow that signal, then read CSS for the labels alone. */256 #refreshModes() {257this.#modes= [258...this.#rendered.querySelectorAll<HTMLElement>('[data-kind="Switcher"]'),259 ].map((node) =>getComputedStyle(node).flexDirection);260this.#readouts.refreshModes();261this.#refreshCaption();262 }263264 #refreshCaption() {265consttext=describeSelection(this.#inspected);266if (this.#caption.textContent!==text) this.#caption.textContent=text;267 }268}