1/**2 * "Compose your own": an empty composition or a working copy of an exercise3 * that its author can rewrite, add to, rearrange and move members within.4 *5 * There is one composition, one selection, one declaration and one history.6 * Two previews show that composition at once, each in a host of its own7 * size. The hosts are demonstration slots sized by CSS; nothing in the8 * composition knows their widths.9 *10 * The editor has two faces over that one working copy. The same edits,11 * rewording and moves are behind both.12 *13 * - In a lesson (`source-exercise`) it is the strip the lesson teaches. Every14 * control stays in place, each click builds on the selection, and the15 * declaration is where a group is chosen. The first composition is empty16 * or copied, on request, from the live exercise. After that it is saved on17 * its own and is replaced only when its author asks, as one undoable edit.18 * - On its own page (`standalone`) it is a workbench for someone who has not19 * read the lesson. A click selects one thing. An outline, or the20 * declaration in its place, lists every node. An inspector names the21 * selection and offers what applies to it. The page supplies the working22 * copy and saves it.23 */24importstylesfrom"./example.css";25import { encodeSnapshot } from"./snapshot.ts";26import { playgroundURL } from"./playground-link.ts";27importprimitiveStylesfrom"./primitives.css";28importinspectionStylesfrom"./inspection.css";29importpalettefrom"./composition-palette.generated.css";30importplaygroundStylesfrom"./playground.css";31importoutlineStylesfrom"./outline-panel.css";32import {33arrangeGroup,34arrangementContracts,35arrangements,36isArrangement,37} from"./arrangement.ts";38import {39example,40exampleNames,41Stack,42typeComposition,43typePrimitive,44} from"./composition.ts";45import { chooseMember } from"./composition-editing.ts";46import { CompositionPreview } from"./composition-preview.ts";47import { atPath, parentPath } from"./grouping.ts";48import { OutlinePanel } from"./outline-panel.ts";49import { SourcePanel } from"./source-panel.ts";50import { selectionAfter, subjectOf } from"./workbench-selection.ts";51import {52moveMembers,53moveObstacle,54moveObstacles,55movesFor,56placeBefore,57placeAfter,58placeAtEnd,59} from"./movement.ts";60import { clampWidth, maximumWidth } from"./width-control.ts";61import {62addText,63addGroup,64blankComposition,65contentKinds,66editContentKind,67isContentKind,68beginTextEdit,69cancelTextEdit,70commitEdit,71editsFor,72finishTextEdit,73releaseGroup,74removeMember,75restoreWorkingCopy,76restoreWorkingTree,77startWorkingCopy,78typeText,79undoEdit,80wrapMembers,81typeEdited,82typeInsertion,83typeTextEdit,84typeWorkingCopy,85typeWorkingEdits,86} from"./working-copy.ts";8788constmembers= (count:number) =>89count===1?"1 member":`${count} members`;9091typePlacement="before"|"inside"|"after";92constplacements:readonlyPlacement[] = ["before", "inside", "after"];93constplacementLabels= {94before: "Before",95inside: "Inside at end",96after: "After",97};9899constroleDescriptions= {100Text: "Text carries the main wording.",101Heading: "Heading names a section of the composition.",102Meta: "Meta supplies supporting context, such as an update time.",103};104105/** What each arrangement does, in a few words beside its name. */106constarrangementHints:Record<Primitive, string> = {107Stack: "one column",108Shelf: "one row",109Switcher: "a row when it fits",110};111112/** A name grounded in the content, while the highlighted box/code gives its location. */113functiondescribeMember(node:Composition):string {114constshort= (text:string) => {115constwords=text.replace(/\s+/g, " ").trim();116returnwords.length>64?`${words.slice(0, 63)}…`:words;117 };118if (!("children"innode))119return`${node.kind}: “${short(node.text) || "empty text"}”`;120if (!node.children.length) return`empty ${node.kind}`;121constfirstText= (member:Composition):string=>122"children"inmember123? (member.children.map(firstText).find(Boolean) ??"")124:short(member.text);125consttext=firstText(node);126return`${node.kind}, ${members(node.children.length)}${text? `, starting with “${short(text)}”` : ""}`;127}128129/** Choosing where a move goes. Both faces show it in place of their controls. */130constmoveMarkup=`<div class="move-controls" hidden><span class="move-source"></span><span class="move-destination"></span><div class="move-placements" role="group" aria-label="Place the moving members">${placements.map((placement) => `<button class="place-${placement}" type="button">${placementLabels[placement]}</button>`).join("")}<button class="cancel-move" type="button">Cancel</button></div></div>`;131132/** The lesson's strip: every control in its place, enabled when it applies. */133conststripMarkup=`134<div class="starter">135 <button class="start-action" type="button">Copy investigation</button>136 <button class="start-blank" type="button">Start blank</button>137 <span class="starter-note"></span>138</div>139<div class="workspace" hidden>140 <div class="bar"><button class="structure" type="button" aria-pressed="false">Show structure</button><button class="open-playground" type="button">Open in playground ↗</button></div>141 <div class="previews"></div>142 <div class="editor-panel">143 <div class="authoring combined working" role="group" aria-label="Edit your composition">144 <label class="edit text-edit">Wording<input class="text-field" type="text" autocomplete="off" spellcheck="true" disabled></label>145 <div class="content-role arrangement" role="radiogroup" aria-labelledby="role-label" aria-describedby="author-status" hidden>146 <span class="arrangement-label" id="role-label">Content role</span>147 <span class="arrangement-options">${contentKinds.map((kind) => `<label><input type="radio" name="content-role" value="${kind}">${kind}</label>`).join("")}</span>148 </div>149 <div class="group-arrangement arrangement" role="radiogroup" aria-labelledby="arrangement-label">150 <span class="arrangement-label" id="arrangement-label"></span>151 <span class="arrangement-options">${arrangements.map((kind) => `<label><input type="radio" name="arrangement" value="${kind}">${kind}</label>`).join("")}</span>152 </div>153 <div class="creation">154 <label>Add <select class="new-member" aria-label="Kind of new member"><option value="Text">Text</option>${arrangements.map((kind) => `<option value="${kind}">Empty ${kind}</option>`).join("")}</select></label>155 <button class="inside-action" type="button"></button>156 <button class="after-action" type="button"></button>157 </div>158 <div class="composition-actions">159 <button class="group-action" type="button">Group</button><button class="ungroup-action" type="button">Ungroup</button><button class="move-action" type="button">Move</button><button class="remove-action" type="button">Remove</button><button class="clear-action" type="button">Clear selection</button>160 </div>161 ${moveMarkup}162 <span class="author-status" id="author-status" role="status" aria-live="polite"></span>163 <span class="history"><button class="undo-action" type="button">Undo</button><button class="blank-action" type="button">Start blank</button><button class="copy-action" type="button"></button></span>164 </div>165 <pre aria-label="Your composition"><code></code></pre>166 </div>167</div>`;168169/**170 * The workbench: the result in two spaces above; below, the hierarchy beside171 * an inspector for whatever is selected in it. Undo and the blank start act172 * on the whole composition, so they sit apart from the inspector.173 */174constworkbenchMarkup=`175<div class="workspace workbench" hidden>176 <section class="results" aria-labelledby="results-title">177 <div class="results-head">178 <div><h2 id="results-title">One composition, two spaces</h2><p class="results-hint">Select a part in either view. Drag the wide card’s edge to change its space.</p></div>179 <div class="document-actions"><button class="undo-action" type="button">Undo</button><button class="blank-action" type="button" title="Replace this composition with an empty one. Undo restores it.">Start blank</button><button class="structure" type="button" aria-pressed="false">Show structure</button></div>180 </div>181 <div class="result-views" role="group" aria-label="Wide card and narrow rail" tabindex="0">182 <div class="preview-limit" aria-hidden="true"></div>183 <div class="previews"></div>184 <p class="empty-hint" hidden>This composition is empty. Add text or an empty group below.</p>185 </div>186 </section>187 <div class="editing" role="group" aria-label="Edit your composition">188 <section class="hierarchy" aria-labelledby="hierarchy-title">189 <div class="hierarchy-head"><h2 id="hierarchy-title">Composition</h2><button class="several" type="button" aria-pressed="false">Select several</button></div>190 <div class="view-choice" role="group" aria-label="Show the composition as"><button class="show-outline" type="button" aria-pressed="true">Outline</button><button class="show-code" type="button" aria-pressed="false">Code</button></div>191 <p class="select-help" hidden>Choose neighboring members to group or move them together.</p>192 <div class="outline" role="group" aria-label="Composition outline"></div>193 <div class="source" hidden><pre aria-label="Composition code"><code></code></pre></div>194 </section>195 <section class="inspector" aria-label="Selected part">196 <div class="inspector-body">197 <div class="selection-context"><button class="parent" type="button" hidden></button><h2 class="selected-title"></h2><span class="selected-detail"></span></div>198 <label class="wording">Wording<input class="text-field" type="text" autocomplete="off" spellcheck="true" disabled></label>199 <fieldset class="content-role choice" aria-describedby="role-purpose" hidden>200 <legend>Content role</legend>201 ${contentKinds.map((kind) => `<label><input type="radio" name="content-role" value="${kind}">${kind}</label>`).join("")}202 <p class="role-purpose" id="role-purpose"></p>203 </fieldset>204 <fieldset class="group-arrangement choice" aria-describedby="arrangement-purpose" hidden>205 <legend>Arrangement</legend>206 ${arrangements.map((kind) => `<label><input type="radio" name="arrangement" value="${kind}"><span>${kind} <small>${arrangementHints[kind]}</small></span></label>`).join("")}207 <p class="arrangement-purpose" id="arrangement-purpose"></p>208 </fieldset>209 <div class="add-area">210 <span class="insertion-context"></span><button class="place-toggle" type="button" hidden></button>211 <div class="add-actions"><button class="add-text" type="button">Add text</button><span class="add-groups" role="group" aria-label="Add an empty group"><span>or an empty group</span>${arrangements.map((kind) => `<button type="button" data-add="${kind}" title="Arranged as ${arrangementHints[kind]}">${kind}</button>`).join("")}</span></div>212 </div>213 <div class="selection-actions"><button class="group-action" type="button">Group in a Stack</button><button class="ungroup-action" type="button">Ungroup</button><button class="move-action" type="button">Move</button><button class="remove-action" type="button">Remove</button></div>214 </div>215 ${moveMarkup}216 <p class="author-status" id="author-status" role="status" aria-live="polite"></p>217 </section>218 </div>219</div>`;220221/** Where keyboard focus belongs after an edit. */222typeFocus=223/** The name of the node at this path in the hierarchy. */224| { readonlyname:string }225/** The text field, with its text selected for replacement. */226|"text"227/** Ready to fill a just-created empty group. */228|"inside"229/** A completed move returns directly to its controls. */230|"move"231/** Where the author put it, unless that control is now unavailable. */232|"stay";233234/**235 * A view of the hierarchy in which any node can be chosen, including a group236 * with no members: the declaration, or the outline.237 */238interfaceHierarchyView {239show(model:Composition):void;240mark(chosen:readonlystring[]):void;241destination(path:string|undefined, moving:boolean):void;242inspect(structure:boolean, path:string|undefined):void;243rove(path:string):void;244focus(path:string):void;245}246247/** Which hierarchy a workbench shows. It outlasts one draft's editor. */248letpreferredHierarchy:"outline"|"code"="outline";249250exportinterfacePlaygroundState {251readonlycopy:WorkingCopy;252readonlywidth:number;253}254255exportclassAxiomaticPlaygroundextendsHTMLElement {256/** The standalone host supplies and persists editor state. */257initialState:PlaygroundState|undefined;258getisMoving():boolean {259return!!this.moving;260 }261finishEditing():PlaygroundState|undefined {262this.finishText();263returnthis.workingState;264 }265prepareToLeave():PlaygroundState|undefined {266if (this.moving) this.cancelMove(false);267if (this.several) {268this.several=false;269this.refresh();270 }271returnthis.finishEditing();272 }273getworkingState():PlaygroundState|undefined {274if (!this.copy) returnundefined;275return {276copy: this.textEdit277?finishTextEdit(this.copy, this.textEdit)278:this.copy,279width: this.width,280 };281 }282readonlyroot=this.attachShadow({ mode: "open" });283/** The exercise whose composition this working copy starts from. */284privatesource="";285/** On its own page: the workbench, with state held by the page. */286privatestandalone=false;287privatecopy:WorkingCopy|undefined;288/** The rewording in progress. Typing changes the copy; history waits. */289privatetextEdit:TextEdit|undefined;290/** A proposed destination; the authored model and source selection stay put. */291privatemoving:292 { readonlymembers:readonlystring[]; target?:string } |undefined;293/** Workbench: the author asked for clicks to build on the selection. */294privateseveral=false;295/** Workbench: add after the selected group, where inside is the default. */296privateaddAfter=false;297privatestructure=false;298/** The node under the pointer or focus, shown while structure is on. */299privateattended:string|undefined;300privatewidth=600;301privatepreviews:CompositionPreview[] = [];302privatecode:SourcePanel|undefined;303privateoutline:OutlinePanel|undefined;304privateabort:AbortController|undefined;305306connectedCallback() {307constsource=this.getAttribute("source-exercise");308this.standalone=this.hasAttribute("standalone");309if (!source&&!this.standalone)310thrownewError("A playground needs a source-exercise");311this.source=source??"investigation";312this.abort=newAbortController();313constsignal=this.abort.signal;314this.root.innerHTML=`<style>${styles}${primitiveStyles}${palette}${inspectionStyles}${playgroundStyles}${this.standalone?outlineStyles: ""}</style>${this.standalone?workbenchMarkup:stripMarkup}`;315this.classList.add("editable");316this.wireEditing(signal);317if (this.standalone) this.wireWorkbench(signal);318elsethis.wireStrip(signal);319320if (this.standalone) {321this.copy=this.withSubject(322this.initialState?.copy??startWorkingCopy(Stack()),323 );324this.width=this.initialState?.width??600;325 } elsethis.copy=this.load();326this.previews= [327newCompositionPreview(this.ownerDocument, {328label: "Wide card",329slot: "wide",330width: {331initial: this.width,332// The workbench's card is as wide as it was asked to be, so it333// cannot say how wide it may become. An independent box does.334...(this.standalone335? { availableSpace: this.get(".preview-limit") }336: {}),337changed: (width, settled) => {338this.width=width;339if (settled) this.save();340 },341 },342choose: (path) =>this.choose(path),343attend: (path) =>this.attend(path),344 }),345newCompositionPreview(this.ownerDocument, {346label: "Narrow rail",347slot: "rail",348choose: (path) =>this.choose(path),349attend: (path) =>this.attend(path),350 }),351 ];352this.get(".previews").append(353...this.previews.map((preview) =>preview.element),354 );355this.code=newSourcePanel(this.get("pre"), {356describe: (path, node) =>this.describe(path, node),357choose: (path, extend) =>this.choose(path, extend),358attend: (path) =>this.attend(path),359// The workbench's declaration scrolls in a box of its own.360revealFocus: this.standalone,361signal,362 });363364if (this.copy) this.open();365 }366367disconnectedCallback() {368this.finishText();369this.abort?.abort();370this.abort=undefined;371for (constpreviewofthis.previews) preview.dispose();372this.previews= [];373this.code?.dispose();374this.code=undefined;375this.outline=undefined;376this.copy=undefined;377this.moving=undefined;378this.several=false;379this.addAfter=false;380this.attended=undefined;381 }382383privateget<TextendsElement=HTMLElement>(selector:string):T {384constelement=this.root.querySelector<T>(selector);385if (!element) thrownewError(`Missing ${selector}`);386returnelement;387 }388privateon(selector:string, type:string, listener: () =>void) {389this.get(selector).addEventListener(type, listener, {390signal: this.abort!.signal,391 });392 }393privategetstorageKey() {394return`axiomatic-playground:v1:${this.source}`;395 }396397/** The hierarchy on screen: the declaration, or the workbench's outline. */398privategethierarchy():HierarchyView|undefined {399returnthis.standalone&&preferredHierarchy==="outline"400?this.outline401:this.code;402 }403404/** A working copy as this face shows it. The workbench always has a405 * subject; a lesson's strip may have nothing selected. */406privatewithSubject(copy:WorkingCopy):WorkingCopy {407returnthis.standalone? { ...copy, chosen: subjectOf(copy.chosen) } :copy;408 }409410/** The accessible name of a node in the hierarchy. */411privatedescribe(path:string, node:Composition):string {412if (this.moving)413return`${this.moving.members.includes(path) ? (path===this.moving.target? "Moving member, chosen as destination" : "Moving member") :path===this.moving.target? "Destination" : "Choose destination"}: ${describeMember(node)}`;414if (this.standalone)415return`${path=== "0" ? "Whole composition: " : ""}${describeMember(node)}`;416return"children"innode417?`Select ${node.kind} group, ${node.children.length?members(node.children.length) : "empty"}`418:`Select ${node.kind}: ${node.text|| "empty"}`;419 }420421/** The controls both faces have: one composition, edited the same way. */422privatewireEditing(signal:AbortSignal) {423this.on(".blank-action", "click", () =>this.startBlank());424this.on(".structure", "click", () => {425this.structure=!this.structure;426if (!this.structure) this.attended=undefined;427this.refresh();428 });429this.on(".text-field", "input", () =>this.typeText());430this.on(".text-field", "blur", () => {431if (this.finishText()) this.refresh();432 });433this.get(".text-field").addEventListener(434"keydown",435 (event) => {436// Enter and Escape that confirm or cancel an input method's437// composition belong to it, not to this edit.438if (event.isComposing||event.keyCode===229) {439event.stopPropagation();440return;441 }442if (event.key==="Enter") {443if (this.finishText()) this.refresh();444 } elseif (event.key==="Escape"&&this.textEdit) {445// The first Escape abandons the rewording; the selection stays.446event.stopPropagation();447this.cancelText();448 }449 },450 { signal },451 );452this.get(".group-arrangement").addEventListener(453"change",454 (event) => {455if (this.moving) return;456constkind= (event.targetasHTMLInputElement).value;457consttarget=this.edits()?.arrange;458if (!this.copy||!target||!isArrangement(kind)) return;459consttree=arrangeGroup(this.copy.model, target.path, kind);460// The controls are not rerendered, so focus stays on the chosen radio.461if (tree!==this.copy.model)462this.apply({ tree, chosen: [target.path] });463 },464 { signal },465 );466this.get(".content-role").addEventListener(467"change",468 (event) => {469if (this.moving) return;470this.finishText();471constkind= (event.targetasHTMLInputElement).value;472consttarget=this.edits()?.text;473if (!this.copy||!target||!isContentKind(kind)) return;474consttree=editContentKind(this.copy.model, target.path, kind);475// The workbench keeps each role's purpose beside the choice.476if (tree!==this.copy.model)477this.apply(478 { tree, chosen: [target.path] },479this.standalone?undefined:roleDescriptions[kind],480 );481 },482 { signal },483 );484this.act(".group-action", (model, edits) => {485if (!edits.wrap) returnundefined;486constedited=wrapMembers(model, edits.wrap);487return [488edited,489`Grouped ${members(edits.wrap.length)} in a new Stack.`,490 { name: edited.chosen[0]! },491 ];492 });493this.act(".ungroup-action", (model, edits) => {494if (!edits.release) returnundefined;495constedited=releaseGroup(model, edits.release);496return [497edited,498"Ungrouped. The members keep their reading order.",499 { name: edited.chosen[0]! },500 ];501 });502this.act(".remove-action", (model, edits) => {503if (!edits.remove) returnundefined;504constremoved=atPath(model, edits.remove)!;505constedited=removeMember(model, edits.remove);506constparent=atPath(edited.tree, parentPath(edits.remove))!;507constleft=508"children"inparent&&!parent.children.length509?`This ${parent.kind} is now empty and keeps its place.`510:"Undo restores it.";511return [512edited,513"children"inremoved514?`Removed the ${removed.kind} and its ${members(removed.children.length)}. ${left}`515:`Removed. ${left}`,516"stay",517 ];518 });519this.on(".move-action", "click", () =>this.beginMove());520this.on(".cancel-move", "click", () =>this.cancelMove());521for (constplacementofplacements)522this.on(`.place-${placement}`, "click", () =>this.placeMove(placement));523this.on(".undo-action", "click", () => {524if (this.moving) return;525this.finishText();526constbefore=this.copy&&undoEdit(this.copy);527if (!before) return;528this.copy=this.withSubject(before);529this.show("Undid the last change. Restored its selection.", "stay");530 });531this.root.addEventListener(532"keydown",533 (event) => {534if ((eventasKeyboardEvent).key!=="Escape"||!this.copy) return;535if (this.moving) {536event.preventDefault();537this.cancelMove();538return;539 }540if (this.standalone) {541// Something is always selected here; Escape only ends a mode.542if (this.several) {543this.several=false;544this.refresh();545 }546return;547 }548constediting=this.root.activeElement?.closest(".authoring") !=null;549constpath=this.copy.chosen[0] ??"0";550this.finishText();551this.attended=undefined;552this.select([]);553// The controls for a selection are now unavailable; continue from554// the declaration, where something can be selected.555if (editing) this.hierarchy?.focus(path);556 },557 { signal },558 );559 }560561/** The strip's own controls: its starting choices, its kind-and-place562 * additions, and clearing the selection its clicks build up. */563privatewireStrip(signal:AbortSignal) {564this.get(".starter-note").textContent=565`Starts from the ${this.source} composition as it is now.`;566this.get(".copy-action").textContent=`Copy ${this.source}`;567this.get(".start-action").textContent=`Copy ${this.source}`;568this.on(".open-playground", "click", () => {569if (!this.copy||this.moving) return;570this.finishText();571try {572location.assign(573playgroundURL("edit", encodeSnapshot(this.copy.model)).href,574 );575 } catch (error) {576this.status(577errorinstanceofError578?error.message579:"This composition could not be opened.",580 );581 }582 });583this.on(".start-action", "click", () =>this.start());584this.on(".start-blank", "click", () =>this.startBlank());585this.get(".new-member").addEventListener(586"keydown",587 (event) => {588// Dismissing the native picker should preserve the insertion target.589if (event.key==="Escape") event.stopPropagation();590 },591 { signal },592 );593this.act(".inside-action", (model, edits) =>594edits.inside?this.createMember(model, edits.inside) :undefined,595 );596this.act(".after-action", (model, edits) =>597edits.after?this.createMember(model, edits.after) :undefined,598 );599this.on(".clear-action", "click", () => {600if (!this.copy||this.moving) return;601constpath=this.copy.chosen[0] ??"0";602this.finishText();603this.select([]);604this.status("Selection cleared. Choose a member or a group.");605this.hierarchy?.focus(path);606 });607this.on(".copy-action", "click", () => {608if (this.moving) return;609consttree=this.sourceComposition();610if (!tree) {611this.status(`The ${this.source} exercise is not on this page.`);612return;613 }614this.apply(615 { tree, chosen: [] },616`Copied the ${this.source} composition as it is now. Undo restores your working copy.`,617"stay",618 );619 });620 }621622/** The workbench's own controls: the outline, the choice of hierarchy,623 * asking for several, the way to a parent, and adding by name. */624privatewireWorkbench(signal:AbortSignal) {625this.outline=newOutlinePanel(this.get(".outline"), {626describe: (path, node) =>this.describe(path, node),627choose: (path, extend) =>this.choose(path, extend),628attend: (path) =>this.attend(path),629signal,630 });631this.showHierarchy(preferredHierarchy);632this.on(".show-outline", "click", () =>this.showHierarchy("outline"));633this.on(".show-code", "click", () =>this.showHierarchy("code"));634this.on(".several", "click", () => {635if (this.moving) return;636this.several=!this.several;637this.refresh();638 });639this.on(".parent", "click", () => {640constpath=parentPath(this.copy?.chosen[0] ??"0");641if (!path||this.moving) return;642this.finishText();643this.several=false;644this.select([path]);645this.hierarchy?.focus(path);646 });647this.on(".place-toggle", "click", () => {648this.addAfter=!this.addAfter;649this.refresh();650 });651this.act(".add-text", (model, edits) => {652constat=this.insertion(edits);653return (654at&& [655addText(model, at),656"Added text. Type to replace its wording.",657"text",658 ]659 );660 });661for (constkindofarrangements)662this.act(`[data-add="${kind}"]`, (model, edits) => {663constat=this.insertion(edits);664if (!at) return;665constadded=addGroup(model, at, kind);666constcanFill=!!editsFor(added.tree, added.chosen).inside;667return [668added,669canFill670?`Added an empty ${kind}. Add text inside it to begin filling it.`671:`Added an empty ${kind} at the nesting limit. You can change its arrangement or move it to a shallower group.`,672"inside",673 ];674 });675 }676677/** Shows the composition as an outline or as its declaration. Focus stays678 * on the choice; the hierarchy that appears is brought up to date. */679privateshowHierarchy(view:"outline"|"code") {680preferredHierarchy=view;681this.get(".outline").hidden=view!=="outline";682this.get(".source").hidden=view!=="code";683for (constnameof ["outline", "code"])684this.get(`.show-${name}`).setAttribute(685"aria-pressed",686String(name===view),687 );688if (!this.copy) return;689this.hierarchy?.show(this.copy.model);690this.hierarchy?.rove(this.moving?.target??this.copy.chosen[0] ??"0");691this.decorate();692 }693694/** The source exercise's composition now, or its starting composition when695 * that exercise is not on the page. */696privatesourceComposition():Composition|undefined {697constscope=this.getRootNode() asDocument|ShadowRoot;698constlive:unknown=scope.querySelector(699`axiomatic-example[exercise="${CSS.escape(this.source)}"]`,700 );701if (702live&&703typeoflive==="object"&&704"snapshot"inlive&&705typeoflive.snapshot==="function"706 )707returnrestoreWorkingTree(live.snapshot());708constknown=exampleNames.find((name) =>name===this.source);709returnknown?restoreWorkingTree(example(known)) :undefined;710 }711712privateload():WorkingCopy|undefined {713try {714constsaved:unknown=JSON.parse(715sessionStorage.getItem(this.storageKey) ||"null",716 );717constcopy=restoreWorkingCopy(saved);718constwidth=719saved&&typeofsaved==="object"&&"width"insaved720?saved.width721:undefined;722if (copy&&typeofwidth==="number"&&Number.isFinite(width))723this.width=clampWidth(width, maximumWidth);724returncopy;725 } catch {726/* A working copy also starts without storage. */727returnundefined;728 }729 }730/** Saves the working copy. A rewording in progress is saved as finished,731 * so reopening mid-edit keeps the words and can still undo them. */732privatesave() {733if (!this.copy) return;734if (this.standalone) {735this.dispatchEvent(736newCustomEvent<PlaygroundState>("composition-change", {737detail: this.workingState!,738 }),739 );740return;741 }742constcopy=this.textEdit743?finishTextEdit(this.copy, this.textEdit)744:this.copy;745try {746sessionStorage.setItem(747this.storageKey,748JSON.stringify({ ...copy, width: this.width }),749 );750 } catch {}751 }752753privatestart() {754consttree=this.sourceComposition();755if (!tree) {756this.get(".starter-note").textContent=757`The ${this.source} exercise is not on this page.`;758return;759 }760this.copy=startWorkingCopy(tree);761this.save();762this.open();763this.status(764"This copy is yours. Select a fact to reword it, or a group to add to it.",765 );766this.hierarchy?.focus("0");767 }768/** An empty root is a place to compose; replacing work is one Undo step. */769privatestartBlank() {770if (this.moving) return;771this.finishText();772this.several=false;773letreplaced=false;774if (!this.copy) {775this.copy= { ...startWorkingCopy(Stack()), chosen: ["0"] };776this.open();777 } else {778constedited=blankComposition(this.copy.model);779if (edited.tree!==this.copy.model) {780replaced=true;781this.apply(edited);782 } elsethis.select(["0"]);783 }784this.status(785`An empty Stack. Add content or an empty group inside it.${replaced? " Undo restores your previous composition." : ""}`,786 );787this.get<HTMLElement>(788this.standalone?".add-text":".new-member",789 ).focus();790 }791792/** The strip's addition: the kind its picker shows, at the place asked for. */793privatecreateMember(794model:Composition,795at:Insertion,796 ): [Edited, string, Focus] {797constkind=this.get<HTMLSelectElement>(".new-member").value;798if (isArrangement(kind)) {799constedited=addGroup(model, at, kind);800this.get<HTMLSelectElement>(".new-member").value="Text";801return [802edited,803`Added an empty ${kind}. Add Text inside it to begin filling the group.`,804"inside",805 ];806 }807return [808addText(model, at),809"Added Text. Type to replace its wording, then choose its content role.",810"text",811 ];812 }813814/**815 * Where the workbench's additions go. A selected group takes them inside816 * unless its author asked for after it; anything else takes them after.817 */818privateinsertion(edits:WorkingEdits):Insertion|undefined {819returnthis.addAfter?edits.after: (edits.inside??edits.after);820 }821822privateopen() {823if (!this.standalone) this.get(".starter").hidden=true;824this.get(".workspace").hidden=false;825this.show();826 }827828privateedits():WorkingEdits|undefined {829returnthis.copy&&editsFor(this.copy.model, this.copy.chosen);830 }831832/** Wires an edit button: the edit its selection permits, a message, and833 * where focus goes. */834privateact(835selector:string,836edit: (837model:Composition,838edits:WorkingEdits,839 ) => [Edited, string, Focus] |undefined,840 ) {841this.on(selector, "click", () => {842if (this.moving) return;843// A click may not blur the text field, so end its edit here.844this.finishText();845constedits=this.edits();846constapplied=this.copy&&edits&&edit(this.copy.model, edits);847if (applied) this.apply(...applied);848 });849 }850851/** Makes one undoable edit. */852privateapply(edited:Edited, message?:string, focus:Focus="stay") {853if (!this.copy) return;854this.finishText();855this.copy=commitEdit(this.copy, edited.tree, edited.chosen);856this.show(message, focus);857 }858859/** Shows a changed composition everywhere, then saves it. */860privateshow(861message?:string,862focus:Focus="stay",863preserveScroll=false,864 ) {865if (!this.copy) return;866// Read before the controls change: one that disappears loses focus.867constfocused=this.root.activeElement;868this.attended=undefined;869// A changed composition ends the modes that referred to the old one.870this.several=false;871this.addAfter=false;872for (constpreviewofthis.previews)873preview.render(this.copy.model, preserveScroll);874this.hierarchy?.show(this.copy.model);875this.hierarchy?.rove(this.copy.chosen[0] ??"0");876this.refresh(message);877this.save();878constfield=this.get<HTMLInputElement>(".text-field");879if (focus==="text"&&!field.disabled) {880field.focus({ preventScroll: true });881field.select();882 } elseif (focus==="inside") {883constfill=this.get<HTMLButtonElement>(884this.standalone?".add-text":".inside-action",885 );886// At the node/depth limit the empty group is still authored and can887// change arrangement. Keep focus on a usable, visible control.888constnext=889fill.disabled||!this.edits()?.inside890?this.get<HTMLInputElement>(".group-arrangement input:checked")891:fill;892next.focus({ preventScroll: true });893 } elseif (focus==="move") {894constmove=this.get<HTMLButtonElement>(".move-action");895constnext=move.disabled896?this.get<HTMLButtonElement>(".undo-action")897:move;898next.focus({ preventScroll: true });899 } elseif (typeoffocus==="object") this.hierarchy?.focus(focus.name);900elsethis.keepFocus(focused);901 }902903/** A focused control that became unavailable hands focus to the selected904 * node's name, so the keyboard stays inside the editor. */905privatekeepFocus(focused:Element|null) {906constunavailable=907 ((focusedinstanceofHTMLButtonElement||908focusedinstanceofHTMLInputElement) &&909focused.disabled) ||910focused?.closest("[hidden]") !=null;911if (unavailable) this.hierarchy?.focus(this.copy?.chosen[0] ??"0");912 }913914/**915 * The author chose a node in a preview or the hierarchy. A lesson teaches916 * that each choice builds on the selection, so there it always does. The917 * workbench selects the one thing chosen unless its author asked for918 * several, by mode or, with `extend`, for this one choice.919 */920privatechoose(path:string, extend=false) {921if (!this.copy) return;922if (this.moving) {923this.moving= { ...this.moving, target: path };924this.attended=undefined;925this.refresh();926this.hierarchy?.rove(path);927return;928 }929this.finishText();930const { model, chosen } =this.copy;931this.select(932this.standalone933?selectionAfter(model, chosen, path, this.several||extend)934:chooseMember(model, chosen, path),935 );936this.hierarchy?.rove(path);937 }938privateselect(chosen:readonlystring[]) {939if (!this.copy) return;940this.copy= { ...this.copy, chosen };941this.addAfter=false;942this.refresh();943this.save();944 }945privateattend(path:string|undefined) {946constnext=this.structure&&!this.moving?path:undefined;947if (next===this.attended) return;948this.attended=next;949this.decorate();950 }951952privatetypeText() {953if (this.moving) return;954consttarget=this.edits()?.text;955if (!this.copy||!target) return;956this.textEdit??=beginTextEdit(this.copy, target.path);957this.copy=typeText(958this.copy,959this.textEdit,960this.get<HTMLInputElement>(".text-field").value,961 );962// The field is outside everything this replaces, so the caret stays.963for (constpreviewofthis.previews) preview.render(this.copy.model, true);964this.hierarchy?.show(this.copy.model);965this.refresh();966this.save();967 }968/** Ends a rewording in progress as one undoable step. Returns whether969 * there was one. */970privatefinishText():boolean {971if (!this.copy||!this.textEdit) returnfalse;972this.copy=finishTextEdit(this.copy, this.textEdit);973this.textEdit=undefined;974this.save();975returntrue;976 }977privatecancelText() {978if (!this.copy||!this.textEdit) return;979this.copy=cancelTextEdit(this.copy, this.textEdit);980this.textEdit=undefined;981this.show("Restored the text from before this edit.", "stay", true);982 }983984privatebeginMove() {985if (!this.copy||this.moving) return;986this.finishText();987constmoves=movesFor(this.copy.model, this.copy.chosen);988if (!moves?.places.length) return;989this.moving= { members: moves.members };990this.several=false;991this.attended=undefined;992this.refresh();993// A visible escape route keeps focus with the controls. Names in the994// hierarchy keep their keyboard order for choosing a destination.995this.get<HTMLButtonElement>(".cancel-move").focus({ preventScroll: true });996 }997998privatecancelMove(restoreFocus=true) {999if (!this.moving) return;1000this.moving=undefined;1001this.attended=undefined;1002this.hierarchy?.rove(this.copy?.chosen[0] ??"0");1003this.refresh("Move cancelled. Your composition is unchanged.");1004// Escape may come from far down a long declaration. Native focus scrolling1005// brings the controls back into view without measuring their rectangles.1006if (restoreFocus) this.get<HTMLButtonElement>(".move-action").focus();1007 }10081009privatemovePlace(placement:Placement):Insertion|undefined {1010if (!this.copy||!this.moving?.target) returnundefined;1011consttarget=this.moving.target;1012constnode=atPath(this.copy.model, target);1013if (!node) returnundefined;1014if (placement==="inside")1015return"children"innode1016?placeAtEnd(this.copy.model, target)1017:undefined;1018if (target==="0") returnundefined;1019returnplacement==="before"?placeBefore(target) :placeAfter(target);1020 }10211022privatemovingName():string {1023constmoving=this.moving;1024if (!moving||!this.copy) return"";1025returnmoving.members.length===11026?describeMember(atPath(this.copy.model, moving.members[0]!)!)1027:`${members(moving.members.length)} together`;1028 }10291030privaterefreshMove() {1031if (!this.copy||!this.moving) return;1032const { model } =this.copy;1033consttarget=this.moving.target&&atPath(model, this.moving.target);1034this.get(".move-source").textContent=`Moving ${this.movingName()}`;1035constparent=1036this.moving.target&&this.moving.target!=="0"1037?atPath(model, parentPath(this.moving.target))1038:undefined;1039constcontext=parent1040?` in the surrounding ${parent.kind}`1041:" in the whole composition";1042this.get(".move-destination").textContent=target1043?`Destination: ${describeMember(target)}${parent? ` · inside ${parent.kind}` : " · whole composition"}`1044:"Choose a destination in either view or the composition.";1045constreasons=newSet<string>();1046constavailable:Placement[] = [];1047for (constplacementofplacements) {1048constbutton=this.get<HTMLButtonElement>(`.place-${placement}`);1049constplace=this.movePlace(placement);1050constobstacle=place&&moveObstacle(model, this.moving.members, place);1051constunavailable=!place||!!obstacle;1052button.disabled=unavailable;1053button.setAttribute(1054"aria-label",1055target1056?`Move ${placement=== "inside" ? "inside at end of" :placement} ${describeMember(target)}`1057:placementLabels[placement],1058 );1059constreason=obstacle1060?moveObstacles[obstacle]1061:!place1062?placement==="inside"1063?"Choose a group to move inside."1064:"The whole composition has no surrounding group."1065:"";1066button.title=target?reason:"Choose a destination first.";1067if (obstacle) reasons.add(moveObstacles[obstacle]);1068if (!unavailable) available.push(placement);1069 }1070constbeside=available.filter((placement) =>placement!=="inside");1071constguidance= [1072beside.length&&target1073?`${beside.map((placement) =>placementLabels[placement]).join(" or ")} places the moving members${context}, alongside this ${target.kind}.`1074:"",1075available.includes("inside") &&target1076?`Inside at end adds them to ${this.moving.target=== "0" ? "the whole composition" : `this ${target.kind}`}.`1077:"",1078 ]1079 .filter(Boolean)1080 .join(" ");1081this.status(1082!target1083?"The solid selection is what travels. Choosing a destination does not move it yet."1084:guidance|| [...reasons].join(" ") ||"Choose another destination.",1085 );1086 }10871088privateplaceMove(placement:Placement) {1089if (!this.copy||!this.moving?.target) return;1090constplace=this.movePlace(placement);1091if (!place||moveObstacle(this.copy.model, this.moving.members, place))1092return;1093constname=this.movingName();1094consttarget=describeMember(atPath(this.copy.model, this.moving.target)!);1095constedited=moveMembers(this.copy.model, this.moving.members, place);1096if (edited.tree===this.copy.model) return;1097constformer=atPath(edited.tree, edited.from);1098constemptied=1099former&&"children"informer&&!former.children.length1100?` The ${former.kind} it left is empty and keeps its arrangement.`1101:"";1102this.moving=undefined;1103this.apply(1104edited,1105`Moved ${name} ${placement=== "inside" ? "inside, at the end of" :placement} ${target}.${emptied} Undo restores the previous composition.`,1106"move",1107 );1108 }11091110privatestatus(message:string) {1111this.get(".author-status").textContent=message;1112 }11131114/** Shows the selection in every view. */1115privatedecorate() {1116if (!this.copy) return;1117const { chosen } =this.copy;1118constinspected=1119this.attended?? (chosen.length===1?chosen[0] :undefined);1120for (constpreviewofthis.previews)1121preview.decorate({1122structure: this.structure,1123inspected,1124chosen,1125destination: this.moving?.target,1126 });1127this.hierarchy?.destination(this.moving?.target, !!this.moving);1128this.hierarchy?.mark(chosen);1129this.hierarchy?.inspect(this.structure, inspected);1130 }11311132/** Brings the controls and every view up to date with the selection. */1133privaterefresh(message?:string) {1134constedits=this.edits();1135if (!this.copy||!edits) return;1136if (this.standalone)1137this.dispatchEvent(1138newCustomEvent("composition-interaction", {1139detail: { moving: !!this.moving },1140 }),1141 );1142const { model, chosen } =this.copy;1143conststructure=this.get(".structure");1144structure.setAttribute("aria-pressed", String(this.structure));1145structure.textContent=this.structure1146?"Hide structure"1147:"Show structure";11481149constfield=this.get<HTMLInputElement>(".text-field");1150field.disabled=!edits.text;1151// Writing an unchanged value would move the caret while typing.1152consttext=edits.text?.content.text??"";1153if (field.value!==text) field.value=text;1154for (constinputofthis.root.querySelectorAll<HTMLInputElement>(1155".content-role input",1156 )) {1157input.disabled=!edits.text;1158input.checked=input.value===edits.text?.content.kind;1159 }1160for (constinputofthis.root.querySelectorAll<HTMLInputElement>(1161".group-arrangement input",1162 )) {1163input.disabled=!edits.arrange;1164input.checked=input.value===edits.arrange?.group.kind;1165 }1166this.enable(".group-action", !!edits.wrap);1167this.enable(".ungroup-action", !!edits.release);1168this.enable(".move-action", !!movesFor(model, chosen)?.places.length);1169this.enable(".remove-action", !!edits.remove);1170// A rewording in progress is undone as the step it is about to become.1171this.enable(1172".undo-action",1173!this.moving&& (this.copy.undo.length>0||!!this.textEdit),1174 );1175this.enable(".blank-action", !this.moving);11761177conststatus=this.standalone1178?this.refreshInspector(edits, message)1179:this.refreshStrip(edits, message);1180this.get(".workspace").toggleAttribute("data-moving", !!this.moving);1181this.get(".move-controls").hidden=!this.moving;1182if (this.moving) this.refreshMove();1183elsethis.status(status);1184this.decorate();1185 }11861187privateenable(selector:string, available:boolean, label?:string) {1188constbutton=this.get<HTMLButtonElement>(selector);1189button.disabled=!available;1190if (label!==undefined) button.textContent=label;1191 }11921193/** The strip keeps every control in place and says what each needs.1194 * Returns what its status line should say. */1195privaterefreshStrip(edits:WorkingEdits, message?:string):string {1196const { model, chosen } =this.copy!;1197this.get<HTMLInputElement>(".text-field").placeholder=edits.text1198?""1199:"Select one fact to edit its text";1200this.get(".content-role").hidden=!edits.text;1201constchoice=this.get(".group-arrangement");1202choice.hidden=!!edits.text;1203consttarget=edits.arrange;1204choice.setAttribute("aria-disabled", String(!target));1205constcount=target?.group.children.length;1206this.get(".group-arrangement .arrangement-label").textContent=!target1207?"Arrange a group as"1208:count===01209?"Arrange this empty group as"1210:count===11211?"Arrange this group as"1212:`Arrange these ${count} members as`;12131214constselected=1215chosen[0] ===undefined?undefined:atPath(model, chosen[0]);1216this.enable(1217".inside-action",1218!!edits.inside,1219edits.arrange1220?`Inside ${edits.arrange.group.kind}`1221:edits.inside1222?"Inside composition"1223:"Inside group",1224 );1225this.enable(1226".after-action",1227!!edits.after,1228chosen.length>11229?"After selection"1230:`After ${edits.remove&&selected?selected.kind: "member"}`,1231 );1232this.enable(".open-playground", !this.moving);1233this.enable(".clear-action", chosen.length>0);12341235if (edits.full)1236return"This selection reaches a size or nesting limit. You can still use the enabled actions.";1237if (message!==undefined) returnmessage;1238if (target)1239returntarget.group.children.length1240?arrangementContracts[target.group.kind]1241:`This ${target.group.kind} is empty and keeps its arrangement. Add a member inside it${edits.remove? ", or remove it" : ""}.`;1242if (edits.text)1243return`${roleDescriptions[edits.text.content.kind]} Changing its role keeps its wording and membership.`;1244if (chosen.length>1)1245return`${members(chosen.length)} selected. Group them, move them, or add a member after them.`;1246return"Select a fact to reword it, or a group's name in the code to arrange or add to it.";1247 }12481249/** The inspector names what is selected and shows what applies to it.1250 * Returns what its status line should say. */1251privaterefreshInspector(edits:WorkingEdits, message?:string):string {1252const { model, chosen } =this.copy!;1253constpath=chosen[0] ??"0";1254constnode=atPath(model, path) ??model;1255constsingle=chosen.length<2;1256this.get(".inspector").toggleAttribute("data-multiple", !single);1257this.get(".selected-title").textContent=single1258?node.kind1259:`${chosen.length} members selected`;1260this.get(".selected-detail").textContent=1261single&&"children"innode1262?`${path=== "0" ? "the whole composition · " : ""}${node.children.length?members(node.children.length) : "empty"}`1263:"";1264constparent=path==="0"?undefined:atPath(model, parentPath(path));1265constup=this.get<HTMLButtonElement>(".parent");1266up.hidden=!parent;1267if (parent) {1268up.textContent=`↑ In ${parent.kind}`;1269up.setAttribute(1270"aria-label",1271`Select the ${parent.kind} ${single? "this is" : "these are"} in`,1272 );1273 }12741275this.get(".wording").hidden=!edits.text;1276this.get(".content-role").hidden=!edits.text;1277this.get(".role-purpose").textContent=edits.text1278?roleDescriptions[edits.text.content.kind]1279:"";1280this.get(".group-arrangement").hidden=!edits.arrange;1281this.get(".arrangement-purpose").textContent=edits.arrange1282?arrangementContracts[edits.arrange.group.kind]1283:"";12841285constplace=this.insertion(edits);1286constinside=edits.inside&&place===edits.inside?edits.inside:null;1287this.get(".insertion-context").textContent=!place1288?"Nothing more can be added here."1289:inside1290?`Add inside this ${inside.group.kind}`1291:single1292?`Add after this ${node.kind}`1293:"Add after these members";1294consttoggle=this.get<HTMLButtonElement>(".place-toggle");1295toggle.hidden=!(edits.inside&&edits.after);1296toggle.textContent=inside1297?"Add after it instead"1298:"Add inside it instead";1299for (constbuttonofthis.root.querySelectorAll<HTMLButtonElement>(1300".add-text, [data-add]",1301 ))1302button.disabled=!place;13031304constseveral=this.get<HTMLButtonElement>(".several");1305several.disabled=!!this.moving;1306several.setAttribute("aria-pressed", String(this.several));1307several.textContent=this.several?"Done selecting":"Select several";1308this.get(".select-help").hidden=!this.several;1309this.get(".empty-hint").hidden=1310!("children"inmodel) ||model.children.length>0;13111312return [1313message,1314edits.full1315?"This selection is at a size or nesting limit, so some actions are unavailable."1316:"",1317 ]1318 .filter(Boolean)1319 .join(" ");1320 }1321}13221323if (!customElements.get("axiomatic-playground"))1324customElements.define("axiomatic-playground", AxiomaticPlayground);