1import { revisionascomponentRevision } from"axiomatic:revision";2importstylesfrom"./example.css";3importinspectionStylesfrom"./inspection.css";4import { inlineObservation } from"./inline-observation.ts";5import { ExampleReadouts } from"./example-readouts.ts";6import {7widthControl,8clampWidth,9minimumWidth,10maximumWidth,11typeWidthControl,12} from"./width-control.ts";13import {14updateInspection,15prepareInspection,16highlightSource,17describeSelection,18currentArrangement,19} from"./inspection.ts";20import { example, exampleNames, declaration } from"./composition.ts";21importprimitiveStylesfrom"./primitives.css";22import { mountComposition, typeMountedComposition } from"./primitives.ts";23import { arrangementAttribute } from"./switcher-coordinator.ts";24importtype { Composition, ExampleName } from"./composition.ts";25import {26atPath,27parentPath,28groupingReason,29neighboringMembers,30groupMembers,31ungroupMembers,32restoreGrouping,33} from"./grouping.ts";34import {35arrangements,36arrangementContracts,37isArrangement,38arrangementTarget,39arrangeGroup,40changedArrangements,41restoreArrangement,42} from"./arrangement.ts";43import {44restoreComposition,45restoreSelection,46chooseMember,47selectionOf,48} from"./composition-editing.ts";49importpalettefrom"./composition-palette.generated.css";50import"./playground.ts";51import"./playground-page.ts";5253letsharedWidth=600;54letsharedStructure=false;55try {56constsaved=Number(sessionStorage.getItem("axiomatic-example-width"));57if (saved>=minimumWidth&&saved<=maximumWidth) sharedWidth=saved;58} catch {}59constlinkedExamples=newSet<AxiomaticExample>();60/** What an exercise lets its reader change. Each is an explicit opt-in. */61typeEditing="grouping"|"arrangement"|"composition";62interfaceUndoEntry {63readonlymodel:Composition;64readonlychosen:readonlystring[];65}66conststatusMarkup=67'<span class="author-status" role="status" aria-live="polite"></span>';68consthistoryMarkup=69'<span class="history"><button class="undo-action" type="button" hidden>Undo</button><button class="reset-action" type="button" hidden>Start over</button></span>';70constarrangementMarkup=`<div class="arrangement" role="radiogroup" aria-labelledby="arrangement-label"><span class="arrangement-label" id="arrangement-label"></span><span class="arrangement-options">${arrangements.map((kind) => `<label><input type="radio" name="arrangement" value="${kind}">${kind}</label>`).join("")}</span></div>`;71constgroupingMarkup=72'<button class="group-action" type="button">Group</button><button class="ungroup-action" type="button" hidden>Ungroup</button>';73constauthoringMarkup:Record<Editing, string> = {74grouping: `<div class="authoring" role="group" aria-label="Edit grouping">${statusMarkup}${groupingMarkup}${historyMarkup}</div>`,75arrangement: `<div class="authoring" role="group" aria-label="Edit arrangement">${arrangementMarkup}${statusMarkup}${historyMarkup}</div>`,76composition: `<div class="authoring combined" role="group" aria-label="Edit composition">${arrangementMarkup}<div class="composition-actions">${groupingMarkup}<button class="clear-action" type="button" hidden>Clear selection</button></div>${statusMarkup}${historyMarkup}</div>`,77};78functionsaveWidth() {79try {80sessionStorage.setItem("axiomatic-example-width", String(sharedWidth));81 } catch {}82}83functionpublishWidth(width:number, persist=true) {84sharedWidth=width;85if (persist) saveWidth();86for (constexampleoflinkedExamples) example.receiveWidth(width);87}88/** What follows a tree edit in an exercise. */89interfaceAppliedEdit {90/** Replaces the default status once. */91readonlymessage?:string;92/** The selection after the edit. */93readonlychosen?:readonlystring[];94/** A code name to focus. Without one, focus stays where the reader put it. */95readonlyfocus?:string;96}97classAxiomaticExampleextendsHTMLElement {98readonlyroot=this.attachShadow({ mode: "open" });99privatename:ExampleName="flat";100privatemodel:Composition=example("flat");101/** Names this exercise's saved state. */102privateexercise:string|undefined;103privateediting:Editing|undefined;104privatechosen:string[] = [];105privateundo:UndoEntry[] = [];106privatewidth=sharedWidth;107privatelinked=true;108privatestructure=false;109privateselected:string|undefined;110privatepinned:string|undefined;111privatesourceColumns=80;112privatecharacterWidth=7.2;113privatesourceInlineSize=0;114privatemounted:MountedComposition|undefined;115privatereadonlymodes=newMap<string, string>();116privatereadonlymodeObserver=newMutationObserver(() =>117this.refreshModes(),118 );119privateobserver?:ResizeObserver;120privatesourceObservation?:ReturnType<typeofinlineObservation>;121privatereadouts:ExampleReadouts|undefined;122privateframe!:HTMLDivElement;123privateviewport!:HTMLDivElement;124privateinput!:HTMLInputElement;125privatehandle!:HTMLDivElement;126privatecode!:HTMLElement;127privateinspected:HTMLElement|undefined;128privatecaptionObserver=newResizeObserver(() =>this.refreshCaption());129privateabort?:AbortController;130privatewidthControl:WidthControl|undefined;131connectedCallback() {132constname=this.getAttribute("example");133constknown=exampleNames.find((candidate) =>candidate===name);134if (!known) thrownewError(`Unknown example ${name}`);135this.name=known;136this.model=example(this.name);137this.exercise=this.getAttribute("exercise") ||undefined;138constedits=this.getAttribute("edits") ??"grouping";139if (140edits!=="grouping"&&141edits!=="arrangement"&&142edits!=="composition"143 )144thrownewError(`Unknown edits ${edits}`);145if (!this.exercise&&this.hasAttribute("edits"))146thrownewError("An example with edits needs an exercise name");147this.editing=this.exercise?edits:undefined;148if (this.exercise) {149// Saved state may contain only the edits this exercise offers.150constrestore=151this.editing==="arrangement"152?restoreArrangement153:this.editing==="composition"154?restoreComposition155:restoreGrouping;156constinitial=this.model;157try {158constsaved=JSON.parse(159sessionStorage.getItem(`axiomatic-exercise:v1:${this.exercise}`) ||160"null",161 );162this.model=restore(saved?.model, initial) ??initial;163this.undo=Array.isArray(saved?.undo)164?saved.undo165 .slice(-25)166 .map((value:unknown):UndoEntry|undefined=> {167// Accept the earlier tree-only history as well as snapshots.168constentry=169value&&typeofvalue==="object"&&"model"invalue170?value171: { model: value, chosen: [] };172constmodel=restore(entry.model, initial);173returnmodel174? {175model,176chosen: restoreSelection(177"chosen"inentry?entry.chosen: [],178model,179 ),180 }181:undefined;182 })183 .filter(184 (value:UndoEntry|undefined):valueisUndoEntry=>!!value,185 )186: [];187if (this.editing==="composition")188this.chosen= [...restoreSelection(saved?.chosen, this.model)];189 } catch {190/* A fresh exercise also works without storage. */191 }192 }193// The arrangement experiment opens with a group that has a parent selected,194// so the first choice needs no selection gesture.195if (this.editing==="arrangement"&&"children"inthis.model) {196constinner=this.model.children.findIndex(197 (member) =>"children"inmember,198 );199this.chosen= [inner<0?"0":`0.${inner}`];200 }201this.abort=newAbortController();202constsignal=this.abort.signal;203this.root.innerHTML=`<style>${styles}${primitiveStyles}${palette}${inspectionStyles}</style><div class="stage"><div class="viewport"><div class="bar"><button class="structure" type="button" aria-pressed="false">Show structure</button><div class="tools"><button class="link" type="button" aria-pressed="true" title="Resize linked examples together">Linked</button><label class="width"><span class="sr-only">Example width</span><input type="number" min="${minimumWidth}" max="${maximumWidth}" step="1"><span aria-hidden="true">px</span></label></div></div><div class="frame"><div class="rendered"></div><div class="resize" aria-hidden="true" title="Drag to resize. Edit the width field for keyboard control."></div></div></div></div><div class="caption"><span class="selection"></span><span class="note"></span></div>${this.name=== "switcher" ? '<label class="edit">Second item label<input value="Run lasted 4m 1s" maxlength="90"></label>' : ""}${this.editing?authoringMarkup[this.editing] : ""}<pre aria-label="Composition"><code></code></pre>`;204this.frame=this.get<HTMLDivElement>(".frame");205this.viewport=this.get<HTMLDivElement>(".viewport");206this.input=this.get<HTMLInputElement>(".width input");207this.handle=this.get<HTMLDivElement>(".resize");208this.code=this.get("code");209this.readouts=newExampleReadouts(210this.get(".stage"),211this.viewport,212this.input,213this.get(".note"),214 () => [...this.modes.values()],215 );216if (this.editing) {217this.root.host.classList.add("editable");218for (const [selector, act] of [219 [".undo-action", () =>this.undoEdit()],220 [".reset-action", () =>this.startOver()],221 ] asconst) {222constbutton=this.get(selector);223button.addEventListener(224"click",225 () => {226constfocused=this.root.activeElement===button;227act();228// History becomes unavailable when nothing is left to do. Keep229// the reader in the editor when that happens to its focused button.230if (231this.editing!=="grouping"&&232focused&&233 (button.hidden||234 (buttoninstanceofHTMLButtonElement&&button.disabled))235 )236this.focusArrangement();237 },238 { signal },239 );240 }241 }242if (this.editing==="arrangement"||this.editing==="composition")243this.get(".arrangement").addEventListener(244"change",245 (event) => {246consttarget=arrangementTarget(this.model, this.chosen);247constkind= (event.targetasHTMLInputElement).value;248if (!target||!isArrangement(kind)) return;249constnext=arrangeGroup(this.model, target.path, kind);250// The strip is not rerendered, so focus stays on the chosen radio.251if (next!==this.model) this.commit(next, { chosen: [target.path] });252 },253 { signal },254 );255if (this.editing==="composition") {256this.get(".clear-action").addEventListener(257"click",258 () => {259constpath=this.chosen[0] ??"0";260this.chosen= [];261this.select(undefined);262this.updateAuthoring(263"Selection cleared. Choose a member or a group.",264 );265this.code266 .querySelector<HTMLElement>(`.code-name[data-path="${path}"]`)267 ?.focus({ preventScroll: true });268 },269 { signal },270 );271 }272if (this.editing==="grouping"||this.editing==="composition") {273this.get(".group-action").addEventListener(274"click",275 () => {276if (groupingReason(this.model, this.chosen)) return;277constpaths= [...this.chosen];278constfirst=Math.min(279...paths.map((path) =>Number(path.split(".").at(-1))),280 );281constgroup=`${parentPath(paths[0]!)}.${first}`;282this.commit(groupMembers(this.model, paths), {283message:284"Grouped. Neighbors outside this group remain separate members.",285focus: group,286chosen: [group],287 });288 },289 { signal },290 );291this.get(".ungroup-action").addEventListener(292"click",293 () => {294constpath=this.chosen[0];295if (!path||!this.canUngroup()) return;296constnode=atPath(this.model, path)!;297if (!("children"innode)) return;298constfirst=Number(path.split(".").at(-1));299this.commit(ungroupMembers(this.model, path), {300message: "Ungrouped. The members keep their reading order.",301focus: path,302chosen: node.children.map(303 (_, i) =>`${parentPath(path)}.${first+i}`,304 ),305 });306 },307 { signal },308 );309 }310this.get(".link").addEventListener(311"click",312 () => {313this.linked=!this.linked;314this.get(".link").setAttribute("aria-pressed", String(this.linked));315this.get(".link").textContent=this.linked?"Linked":"Independent";316if (this.linked) {317linkedExamples.add(this);318this.receiveWidth(sharedWidth);319this.setStructure(sharedStructure);320 } elselinkedExamples.delete(this);321 },322 { signal },323 );324this.get(".structure").addEventListener(325"click",326 () => {327constnext=!this.structure;328if (this.linked) {329sharedStructure=next;330for (constexampleoflinkedExamples) example.setStructure(next);331 } elsethis.setStructure(next);332 },333 { signal },334 );335this.widthControl=widthControl({336handle: this.handle,337viewport: this.viewport,338input: this.input,339limit: () =>this.limit(),340request: (width, settled, maximum) =>341this.setWidth(width, settled, maximum),342restore: () =>this.readouts?.refreshWidth(),343signal,344 });345this.root.querySelector<HTMLInputElement>(".edit input")?.addEventListener(346"input",347 (event) => {348this.model=example(349this.name,350 (event.targetasHTMLInputElement).value,351 );352this.render();353 },354 { signal },355 );356this.frame.addEventListener(357"pointermove",358 (event) => {359if (360this.widthControl?.dragging||361!this.structure||362!(event.targetinstanceofElement)363 )364return;365constnode=event.target.closest<HTMLElement>(".node,.leaf");366if (node?.dataset.path) this.select(node.dataset.path);367 },368 { signal },369 );370this.code.addEventListener(371"pointerover",372 (event) => {373if (this.structure&&event.targetinstanceofElement) {374constpath=375event.target.closest<HTMLElement>("[data-path]")?.dataset.path;376if (path) this.select(path);377 }378 },379 { signal },380 );381this.code.addEventListener(382"focusin",383 (event) => {384if (385this.structure&&386event.targetinstanceofHTMLElement&&387event.target.dataset.path388 )389this.select(event.target.dataset.path);390if (391event.targetinstanceofHTMLElement&&392event.target.classList.contains("code-name")393 )394this.rove(event.target.dataset.path!);395 },396 { signal },397 );398this.code.addEventListener(399"click",400 (event) => {401if (event.targetinstanceofElement) {402constpath=403event.target.closest<HTMLElement>("[data-path]")?.dataset.path;404if (path&&this.exercise) {405this.choose(path);406return;407 }408if (path) {409this.setStructure(true);410this.pinned=path;411this.select(path);412 }413 }414 },415 { signal },416 );417this.frame.addEventListener(418"click",419 (event) => {420if (421 (this.structure||this.exercise) &&422event.targetinstanceofElement423 ) {424constpath=425event.target.closest<HTMLElement>(".node,.leaf")?.dataset.path;426if (path&&this.exercise) {427this.choose(path);428return;429 }430if (path) {431this.pinned=path;432this.select(path);433 }434 }435 },436 { signal },437 );438this.frame.addEventListener(439"pointerleave",440 () =>this.select(this.inspectionFallback()),441 { signal },442 );443this.code.addEventListener(444"pointerleave",445 () =>this.select(this.inspectionFallback()),446 {447signal,448 },449 );450this.code.addEventListener(451"focusout",452 (event) => {453if (454!(event.relatedTargetinstanceofNode) ||455!this.code.contains(event.relatedTarget)456 )457this.select(this.inspectionFallback());458 },459 { signal },460 );461this.root.addEventListener(462"keydown",463 (event) => {464constkey=eventasKeyboardEvent;465if (key.key==="Escape") {466this.pinned=undefined;467this.select(undefined);468if (this.editing) {469constchoosing=470this.root.activeElement?.closest(471this.editing==="composition"?".authoring":".arrangement",472 ) !=null;473this.chosen= [];474this.updateAuthoring(475this.editing==="grouping"?"Selection cleared.":undefined,476 );477// With no group selected the choice is disabled; continue from478// the code, where a group can be selected.479if (choosing) this.focusArrangement();480 }481 }482if (483 (this.structure||this.exercise) &&484 (key.key==="ArrowUp"||key.key==="ArrowDown") &&485event.targetinstanceofHTMLElement&&486event.target.classList.contains("code-name")487 ) {488constnames= [489...this.code.querySelectorAll<HTMLButtonElement>(".code-name"),490 ];491constindex=names.indexOf(event.targetasHTMLButtonElement);492constnext=names[index+ (key.key==="ArrowDown"?1:-1)];493key.preventDefault();494if (next) {495next.focus();496 }497 }498 },499 { signal },500 );501this.sourceObservation=inlineObservation(this.get("pre"));502this.observer=newResizeObserver((entries) => {503for (constentryofentries) {504if (entry.target===this.sourceObservation?.target) {505this.sourceInlineSize=entry.contentBoxSize[0]!.inlineSize;506this.fitSource();507 }508 }509 });510this.observer.observe(this.sourceObservation.target);511this.modeObserver.observe(this.get(".rendered"), {512attributes: true,513subtree: true,514attributeFilter: [arrangementAttribute],515 });516if (this.linked) {517linkedExamples.add(this);518this.width=sharedWidth;519this.structure=sharedStructure;520 }521this.render();522this.setStructure(this.structure);523constrefreshSourceFont= () => {524if (signal.aborted) return;525constcontext=document.createElement("canvas").getContext("2d");526if (context) {527context.font=getComputedStyle(this.get("pre")).font;528this.characterWidth=context.measureText("0").width||7.2;529 }530this.fitSource();531 };532document.fonts.addEventListener("loadingdone", refreshSourceFont, {533signal,534 });535voiddocument.fonts.ready.then(refreshSourceFont);536 }537538disconnectedCallback() {539this.abort?.abort();540this.observer?.disconnect();541this.sourceObservation?.dispose();542this.readouts?.disconnect();543this.modeObserver.disconnect();544this.mounted?.dispose();545this.mounted=undefined;546this.captionObserver.disconnect();547this.inspected=undefined;548linkedExamples.delete(this);549this.widthControl?.cancel();550this.widthControl=undefined;551 }552privateget<TextendsElement=HTMLElement>(selector:string):T {553constelement=this.root.querySelector<T>(selector);554if (!element) thrownewError(`Missing ${selector}`);555returnelement;556 }557/**558 * The composition this example shows now, including its reader's edits.559 * A composition is an immutable value, so a caller may keep it: later560 * edits here produce a new one. A working copy starts from this.561 */562snapshot():Composition {563returnthis.model;564 }565receiveWidth(width:number) {566this.width=width;567this.viewport.style.inlineSize=`${width}px`;568 }569privatelimit() {570returnthis.readouts?.maximum??maximumWidth;571 }572privatesetWidth(width:number, persist=true, maximum=this.limit()) {573if (!Number.isFinite(width)) {574this.readouts?.refreshWidth();575return;576 }577this.width=clampWidth(width, maximum);578if (this.linked) publishWidth(this.width, persist);579elsethis.receiveWidth(this.width);580 }581privaterender() {582constrendered=this.get(".rendered");583if (this.mounted) this.mounted.update(this.model);584elsethis.mounted=mountComposition(rendered, this.model);585prepareInspection(rendered);586this.renderCode();587this.refreshModes();588this.readouts?.observeComposition(rendered);589if (this.exercise) this.updateAuthoring();590elsethis.updateInspection();591this.receiveWidth(this.width);592 }593privatefitSource() {594if (!this.sourceInlineSize) return;595constcolumns=Math.max(59616,597Math.min(80, Math.floor(this.sourceInlineSize/this.characterWidth)),598 );599if (columns===this.sourceColumns) return;600this.sourceColumns=columns;601constactive=this.root.activeElement;602constfocused=603activeinstanceofHTMLElement&&active.classList.contains("code-name")604?active.dataset.path605:undefined;606this.renderCode();607if (this.exercise) this.updateAuthoring();608if (focused) {609this.rove(focused);610this.code611 .querySelector<HTMLElement>(`.code-name[data-path="${focused}"]`)612 ?.focus({ preventScroll: true });613 }614 }615privaterenderCode() {616constlines=declaration(this.model, "0", 0, this.sourceColumns);617constfragment=document.createDocumentFragment();618for (constlineoflines) {619constrow=document.createElement("span");620row.className="code-line";621row.style.setProperty("--continuation", `${(line.depth+1) *2}ch`);622if (line.path) row.dataset.path=line.path;623for (consttokenofline.tokens) {624constspan=document.createElement(token.kind?"button":"span");625span.className=`token ${token.tone?? "plain"}${token.kind? " code-name" : ""}`;626span.textContent=token.text;627if (token.path) span.dataset.path=token.path;628if (token.kind) {629span.setAttribute("type", "button");630constnode=atPath(this.model, token.path!);631span.setAttribute(632"aria-label",633node&&!("children"innode)634?`${this.exercise? "Select" : "Inspect"} ${node.kind}: ${node.text}`635:`${this.exercise? "Select" : "Inspect"} ${token.kind} group`,636 );637span.tabIndex=this.structure||this.exercise?0:-1;638 }639row.append(span);640 }641fragment.append(row);642 }643this.code.replaceChildren(fragment);644if (this.exercise) this.rove("0");645highlightSource(this.code, this.structure, this.selected);646this.refreshAccessibleNames();647 }648privatecanUngroup() {649constnode=650this.chosen.length===1651?atPath(this.model, this.chosen[0]!)652:undefined;653return!!node&&"children"innode&&this.chosen[0] !=="0";654 }655privateinspectionFallback() {656returnthis.exercise657?this.chosen.length===1658?this.chosen[0]659:undefined660:this.pinned;661 }662privaterove(path:string) {663for (constnameofthis.code.querySelectorAll<HTMLElement>(".code-name"))664name.tabIndex=name.dataset.path===path?0:-1;665 }666privatechoose(path:string) {667if (!atPath(this.model, path)) return;668letnotice:string|undefined;669if (this.editing==="composition") {670this.chosen= [...chooseMember(this.model, this.chosen, path)];671 } elseif (this.editing==="arrangement") {672// One node at a time, at any level; Escape clears it. A fact can be673// selected, and then there is no group to arrange: it never stands for674// its parent.675this.chosen= [path];676 } elseif (path==="0") {677this.chosen= [];678notice=679"This Stack holds the whole example. Choose members inside it to make a group.";680 } elseif (this.chosen.includes(path)) {681this.chosen=this.chosen.filter((value) =>value!==path);682// Removing the middle of a run starts a fresh selection as well.683if (684this.chosen.length>1&&685!neighboringMembers(this.model, this.chosen)686 )687this.chosen= [this.chosen[0]!];688 } else {689constnext= [...this.chosen, path];690if (this.chosen.length&&!neighboringMembers(this.model, next)) {691this.chosen= [path];692notice="Only neighbors can be grouped here. Order stays as written.";693 } elsethis.chosen=next;694 }695this.rove(path);696this.select(this.inspectionFallback());697this.updateAuthoring(notice);698 }699/** Shows the grouping actions the selection permits; returns its status. */700privateupdateGrouping():string {701constreason=groupingReason(this.model, this.chosen);702constgroup=this.get<HTMLButtonElement>(".group-action");703group.hidden=!!reason;704group.textContent=`Group ${this.chosen.length} members`;705this.get<HTMLButtonElement>(".ungroup-action").hidden=!this.canUngroup();706returnthis.canUngroup()707?"Add a neighbor to compose a larger group."708:this.chosen.length===1709?"1 member selected. Select a neighbor to group them."710:this.chosen.length>=2711?reason||`${this.chosen.length} members selected. Ready to group.`712:"Choose two neighboring facts.";713 }714/** Points the arrangement choice at the selected group; returns its status. */715privateupdateArrangement():string {716consttarget=arrangementTarget(this.model, this.chosen);717constchoice=this.get(".arrangement");718choice.setAttribute("aria-disabled", String(!target));719constcount=target?.group.children.length;720this.get(".arrangement-label").textContent=!target721?"Arrange a group as"722:count===1723?"Arrange this member as"724:`Arrange these ${count} members as`;725for (constinputofchoice.querySelectorAll("input")) {726input.disabled=!target;727input.checked=input.value===target?.group.kind;728 }729if (target) returnarrangementContracts[target.group.kind];730const [path] =this.chosen;731constselected=path===undefined?undefined:atPath(this.model, path);732returnselected733?`${selected.kind} is content, with no members to arrange. Select a group's name in the code.`734:"Select a group's name in the code to arrange its members.";735 }736/** Returns focus to the arrangement choice, or to the code when no group737 * is selected and the choice is disabled. */738privatefocusArrangement() {739 (740this.root.querySelector<HTMLElement>(".arrangement input:checked") ??741this.code.querySelector<HTMLElement>('.code-name[tabindex="0"]')742 )?.focus({ preventScroll: true });743 }744privateupdateAuthoring(message?:string) {745letstatus:string;746if (this.editing==="composition") {747constarrangement=this.updateArrangement();748constselected=selectionOf(this.model, this.chosen);749constgroup=this.get<HTMLButtonElement>(".group-action");750group.hidden=false;751group.disabled=selected.selected!=="members"||!selected.canGroup;752group.textContent="Group";753constungroup=this.get<HTMLButtonElement>(".ungroup-action");754ungroup.hidden=false;755ungroup.disabled=selected.selected!=="group"||!selected.canUngroup;756constclear=this.get<HTMLButtonElement>(".clear-action");757clear.hidden=false;758clear.disabled=!this.chosen.length;759switch (selected.selected) {760case"group":761status=arrangement;762break;763case"members":764status=selected.canGroup765?`${this.chosen.length} members selected. Group them, or select one again to leave it out.`766:"These are all the members of one group. Select that group's name to arrange it.";767break;768case"content":769status="1 member selected. Select a neighbor to group them.";770break;771case"nothing":772status=773"Select neighboring facts to group them, or a group's name to arrange it.";774 }775 } else776status=777this.editing==="arrangement"778?this.updateArrangement()779:this.updateGrouping();780constundo=this.get<HTMLButtonElement>(".undo-action");781constreset=this.get<HTMLButtonElement>(".reset-action");782constinitial=783JSON.stringify(this.model) ===JSON.stringify(example(this.name));784undo.hidden=this.editing!=="composition"&&!this.undo.length;785reset.hidden=this.editing!=="composition"&&initial;786undo.disabled=!this.undo.length;787reset.disabled=initial;788this.get(".author-status").textContent=message??status;789for (constelementofthis.frame.querySelectorAll<HTMLElement>(790".node,.leaf",791 )) {792constchosen=this.chosen.includes(element.dataset.path!);793element.dataset.chosen=String(chosen);794 }795for (constelementofthis.code.querySelectorAll<HTMLElement>(796"[data-path]",797 )) {798constpath=element.dataset.path!;799element.dataset.chosen=String(800this.chosen.some(801 (choice) =>path===choice||path.startsWith(`${choice}.`),802 ),803 );804if (element.classList.contains("code-name"))805element.setAttribute(806"aria-pressed",807String(this.chosen.includes(path)),808 );809 }810this.updateInspection();811 }812privateundoEdit() {813constentry=this.undo.pop();814if (!entry) return;815constprevious=entry.model;816if (this.editing==="composition") {817this.applyEdit(previous, {818message: "Undid the last change. Restored its selection.",819chosen: entry.chosen,820 });821return;822 }823if (this.editing!=="arrangement") {824this.applyEdit(previous, {825message: "Undid the last change.",826focus: "0",827 });828return;829 }830// Arrangement edits keep every path, so the group whose arrangement comes831// back can be selected to show what was undone.832constchanged=changedArrangements(this.model, previous);833constrestored=834changed.length===1?arrangementTarget(previous, changed) :undefined;835this.applyEdit(previous, {836message: restored837?`Undid the last change. This group is a ${restored.group.kind} again.`838:"Undid the last change.",839chosen: restored? [restored.path] :this.chosen,840 });841 }842privatestartOver() {843if (this.editing==="composition") {844this.commit(example(this.name), {845message: "Returned to one sequence. Undo restores your composition.",846chosen: [],847 });848 } elseif (this.editing==="arrangement")849this.commit(example(this.name), {850message:851"Returned to the starting arrangement. Undo restores your choices.",852chosen: this.chosen,853 });854else855this.commit(example(this.name), {856message: "Returned to one sequence. Undo can restore your grouping.",857focus: "0",858 });859 }860privatecommit(next:Composition, edit:AppliedEdit) {861this.undo= [862...this.undo.slice(-24),863 { model: this.model, chosen: [...this.chosen] },864 ];865this.applyEdit(next, edit);866 }867privateapplyEdit(868next:Composition,869 { message, chosen= [], focus }:AppliedEdit,870 ) {871this.model=next;872this.chosen= [...chosen];873this.pinned=undefined;874this.selected=undefined;875this.render();876this.selected=this.inspectionFallback();877this.rove(focus??this.chosen[0] ??"0");878this.updateAuthoring(message);879try {880sessionStorage.setItem(881`axiomatic-exercise:v1:${this.exercise}`,882JSON.stringify({883model: this.model,884undo: this.undo,885chosen: this.chosen,886 }),887 );888 } catch {}889if (focus)890this.code891 .querySelector<HTMLButtonElement>(`.code-name[data-path="${focus}"]`)892 ?.focus({ preventScroll: true });893 }894privatesetStructure(value:boolean) {895this.structure=value;896this.get(".structure").setAttribute("aria-pressed", String(value));897this.get(".structure").textContent=value898?"Hide structure"899:"Show structure";900this.code.classList.toggle("inspecting", value);901if (!value) {902this.selected=undefined;903this.pinned=undefined;904 }905for (constbofthis.code.querySelectorAll<HTMLElement>(".code-name"))906b.tabIndex=value||this.exercise?0:-1;907if (this.exercise) {908this.rove(this.chosen[0] ??"0");909this.selected=this.inspectionFallback();910 }911this.updateInspection();912 }913privateselect(path:string|undefined) {914if (this.selected===path) return;915this.selected=path;916this.updateInspection();917 }918/** Effective modes can be derived from an ancestor's published arrangement.919 * Observe that semantic signal, then read CSS only for the teaching labels. */920privaterefreshModes() {921this.modes.clear();922for (constnodeofthis.get(".rendered").querySelectorAll<HTMLElement>(923'[data-kind="Switcher"]',924 )) {925this.modes.set(node.dataset.path!, getComputedStyle(node).flexDirection);926 }927this.readouts?.refreshModes();928this.refreshAccessibleNames();929this.refreshCaption();930 }931privaterefreshAccessibleNames() {932// Grouping exercises contain Stacks alone; their names say what a click does.933if (this.editing==="grouping") return;934for (constbuttonofthis.code.querySelectorAll<HTMLElement>(935".code-name",936 )) {937constpath=button.dataset.path!;938constnode=atPath(this.model, path);939if (!node||!("children"innode)) continue;940constdirection=941node.kind==="Stack"942?"column"943:node.kind==="Shelf"944?"row"945: (this.modes.get(path) ??"column");946constname=`${this.editing? "Select" : "Inspect"} ${node.kind}, ${currentArrangement(node.kind, direction=== "row")}, ${node.children.length} members`;947if (button.getAttribute("aria-label") !==name)948button.setAttribute("aria-label", name);949 }950 }951privateupdateInspection() {952highlightSource(this.code, this.structure, this.selected);953constselected=updateInspection(this.get(".rendered"), {954structure: this.structure,955selected:956this.structure||this.chosen.length?this.selected:undefined,957preview:958this.editing==="grouping"&&!groupingReason(this.model, this.chosen)959?this.chosen960: [],961 });962if (selected!==this.inspected) {963this.captionObserver.disconnect();964this.inspected=selected;965if (selected) {966// A primitive has one uniform gap: the first adjacent pair suffices.967for (constbandof [968...selected.querySelectorAll(969':scope > [data-decoration="gap"] [data-observation="gap"]',970 ),971 ].slice(0, 2))972this.captionObserver.observe(band);973 }974 }975this.refreshCaption();976 }977privaterefreshCaption() {978constcaption=this.get(".selection");979consttext=describeSelection(this.inspected);980if (caption.textContent!==text) caption.textContent=text;981 }982}983if (!customElements.get("axiomatic-example"))984customElements.define("axiomatic-example", AxiomaticExample);985986// The pinned reader emits this event when source inputs change. Until it exposes987// a component lifecycle hook, refresh only when this component's bundle changed.988if (989document990 .querySelector('meta[name="reader-sources"]')991 ?.getAttribute("content") !=="fixed"992) {993document.addEventListener("reader-sources-changed", () => {994voidfetch(import.meta.url, { cache: "no-store" })995 .then((response) => (response.ok?response.text() :""))996 .then((source) => {997constrevision=source.match(/axiomatic-revision:([a-f0-9]+)/)?.[1];998if (revision&&`axiomatic-revision:${revision}`!==componentRevision)999location.reload();1000 })1001 .catch(() => {1002/* Preserve the live example if the local reader is restarting. */1003 });1004 });1005}