1/** Interaction study. Uses the real composition model and layout runtime;
2 * document persistence and move destinations stay in the established editor. */
3import base from "../../documentation/components/source/example.css";
4import primitive from "../../documentation/components/source/primitives.css";
5import inspection from "../../documentation/components/source/inspection.css";
6import palette from "../../documentation/components/source/composition-palette.generated.css";
7import styles from "./workbench.css";
8import {
9 Stack,
10 Switcher,
11 type Composition,
12} from "../../documentation/components/source/composition.ts";
13import { CompositionPreview } from "../../documentation/components/source/composition-preview.ts";
14import { SourcePanel } from "../../documentation/components/source/source-panel.ts";
15import {
16 atPath,
17 parentPath,
18} from "../../documentation/components/source/grouping.ts";
19import { chooseMember } from "../../documentation/components/source/composition-editing.ts";
20import {
21 arrangeGroup,
22 arrangementContracts,
23 arrangements,
24 isArrangement,
25} from "../../documentation/components/source/arrangement.ts";
26import {
27 addText,
28 addGroup,
29 editContentKind,
30 contentKinds,
31 isContentKind,
32 editsFor,
33 startWorkingCopy,
34 commitEdit,
35 undoEdit,
36 wrapMembers,
37 releaseGroup,
38 removeMember,
39 beginTextEdit,
40 typeText,
41 finishTextEdit,
42 cancelTextEdit,
43 type Edited,
44 type TextEdit,
45} from "../../documentation/components/source/working-copy.ts";
46
47const sample = Stack(
48 { kind: "Heading", text: "Investigation complete" },
49 Stack(
50 { kind: "Text", text: "Execution completed" },
51 { kind: "Meta", text: "Run lasted 4m 1s" },
52 ),
53 Switcher(
54 { kind: "Text", text: "Remediation plan proposed" },
55 { kind: "Text", text: "Review the changes" },
56 { kind: "Meta", text: "Awaiting approval" },
57 ),
58);
59const initial = Stack({ kind: "Text", text: "New text" });
60const rolePurpose = {
61 Text: "The main wording of your composition.",
62 Heading: "Names a section of your composition.",
63 Meta: "Supporting context, such as a time or a source.",
64};
65
66class WorkbenchStudy extends HTMLElement {
67 readonly root = this.attachShadow({ mode: "open" });
68 private copy = {
69 ...startWorkingCopy(initial),
70 chosen: ["0.0"] as readonly string[],
71 };
72 private edit: TextEdit | undefined;
73 private together = false;
74 private insertAfter = false;
75 private structure = false;
76 private views: CompositionPreview[] = [];
77 private source: SourcePanel | undefined;
78 private abort = new AbortController();
79
80 connectedCallback() {
81 this.root.innerHTML = `<style>${base}${primitive}${inspection}${palette}${styles}</style>
82 <div class="document-bar"><div><h1>Your composition</h1><p class="subtitle">Choose a part. Change its content or how its members belong together.</p></div><div class="document-actions"><button class="undo" disabled>Undo</button><details class="examples"><summary>Try a starting point</summary><div><button data-start="blank">Empty composition</button><button data-start="simple">One line of text</button><button data-start="investigation">Investigation</button></div></details></div></div>
83 <div class="workbench">
84 <aside class="editing" aria-label="Composition editor">
85 <section class="outline-section"><div class="section-head"><h2>Composition</h2><button class="together" aria-pressed="false">Select several</button></div><p class="select-help" hidden>Select neighboring items to group them.</p><div class="view-choice" role="group" aria-label="Composition view"><button class="show-outline" aria-pressed="true">Outline</button><button class="show-code" aria-pressed="false">Code</button></div><nav class="outline" aria-label="Composition outline"></nav><div class="source" hidden><pre aria-label="Composition code"><code></code></pre></div></section>
86 <section class="inspector" aria-label="Selected part"><div class="selection-context"><button class="parent"></button><h2 class="selected-title"></h2><span class="selected-detail"></span></div>
87 <label class="wording">Wording<input class="words" autocomplete="off"></label>
88 <fieldset class="roles"><legend>Content role</legend>${contentKinds.map((k) => `<label><input type="radio" name="role" value="${k}">${k}</label>`).join("")}<p class="role-purpose"></p></fieldset>
89 <fieldset class="arrangements"><legend>Arrangement</legend>${arrangements.map((k) => `<label><input type="radio" name="arrangement" value="${k}"><span>${k} <small>${k === "Stack" ? "One column" : k === "Shelf" ? "One row" : "Row when it fits"}</small></span></label>`).join("")}<p class="arrangement-purpose"></p></fieldset>
90 <div class="add-area"><p class="insertion-context"></p><button class="insert-after" hidden></button><div class="add-actions"><button class="add-text primary">+ Add text</button><details class="add-group"><summary>+ Add group</summary><div>${arrangements.map((k) => `<button data-add="${k}">${k} <small>${k === "Stack" ? "One column" : k === "Shelf" ? "One row" : "Row when it fits"}</small></button>`).join("")}</div></details></div></div>
91 <div class="selection-actions"><button class="group">Group in a Stack</button><button class="ungroup">Ungroup</button><button class="remove">Remove</button></div>
92 </section>
93 <p class="feedback" role="status" aria-live="polite"></p>
94 </aside>
95 <section class="results" aria-label="Composition results"><div class="result-heading"><div><h2>One composition, two spaces</h2><p>Select in either view. Drag the card’s edge to change its space.</p></div><button class="structure" aria-pressed="false">Show structure</button></div><div class="preview-limit" aria-hidden="true"></div><div class="previews"></div><p class="empty-hint" hidden>Your composition is empty. Add text or a group to begin.</p></section>
96 </div>`;
97 this.get(".workbench").prepend(this.get(".results"));
98 const signal = this.abort.signal;
99 const on = (selector: string, callback: () => void) =>
100 this.get(selector).addEventListener("click", callback, { signal });
101 for (const view of ["outline", "code"] as const)
102 on(`.show-${view}`, () => {
103 this.get(".outline").hidden = view !== "outline";
104 this.get(".source").hidden = view !== "code";
105 this.get(".show-outline").setAttribute(
106 "aria-pressed",
107 String(view === "outline"),
108 );
109 this.get(".show-code").setAttribute(
110 "aria-pressed",
111 String(view === "code"),
112 );
113 });
114 on(".undo", () => {
115 this.finish();
116 const before = undoEdit(this.copy);
117 if (before) {
118 this.copy = before;
119 this.insertAfter = false;
120 this.render("Undid the last change.");
121 if (this.get<HTMLButtonElement>(".undo").disabled) {
122 const path = this.copy.chosen[0] ?? "0";
123 if (this.get(".outline").hidden) this.source?.focus(path);
124 else
125 this.get<HTMLButtonElement>(
126 `[data-outline-path="${path}"]`,
127 )?.focus();
128 }
129 }
130 });
131 on(".together", () => {
132 this.finish();
133 this.together = !this.together;
134 if (!this.together)
135 this.copy = { ...this.copy, chosen: this.copy.chosen.slice(0, 1) };
136 this.refresh();
137 });
138 on(".parent", () => {
139 const path = parentPath(this.copy.chosen[0] ?? "0");
140 this.choose(path, true);
141 if (this.get(".outline").hidden) this.source?.focus(path);
142 else
143 this.get<HTMLButtonElement>(`[data-outline-path="${path}"]`)?.focus();
144 });
145 on(".structure", () => {
146 this.structure = !this.structure;
147 this.refresh();
148 });
149 on(".insert-after", () => {
150 this.insertAfter = !this.insertAfter;
151 this.refresh();
152 });
153 on(".add-text", () => this.add("Text"));
154 on(".group", () => {
155 const e = editsFor(this.copy.model, this.copy.chosen);
156 if (e.wrap) {
157 this.together = false;
158 this.apply(
159 wrapMembers(this.copy.model, e.wrap),
160 "Grouped the selection in a Stack.",
161 );
162 }
163 });
164 on(".ungroup", () => {
165 const e = editsFor(this.copy.model, this.copy.chosen);
166 if (e.release)
167 this.apply(
168 releaseGroup(this.copy.model, e.release),
169 "Ungrouped. The members keep their order.",
170 );
171 });
172 on(".remove", () => {
173 const e = editsFor(this.copy.model, this.copy.chosen);
174 if (e.remove)
175 this.apply(
176 removeMember(this.copy.model, e.remove),
177 "Removed. Undo restores it.",
178 );
179 });
180 this.root.addEventListener(
181 "click",
182 (event) => {
183 const target = event.target as Element;
184 const add = target.closest<HTMLElement>("[data-add]")?.dataset.add;
185 if (add && isArrangement(add)) this.add(add);
186 const start =
187 target.closest<HTMLElement>("[data-start]")?.dataset.start;
188 if (start) {
189 this.get<HTMLDetailsElement>(".examples").open = false;
190 this.together = false;
191 if (start === "investigation")
192 this.get(".preview[data-preview=wide] .viewport").style.inlineSize =
193 "600px";
194 this.apply(
195 {
196 tree:
197 start === "blank"
198 ? Stack()
199 : start === "simple"
200 ? initial
201 : sample,
202 chosen: ["0"],
203 },
204 "Loaded a starting point. Undo restores your previous work.",
205 );
206 }
207 },
208 { signal },
209 );
210 this.get(".outline").addEventListener(
211 "click",
212 (event) => {
213 const path = (event.target as Element).closest<HTMLElement>(
214 "[data-outline-path]",
215 )?.dataset.outlinePath;
216 if (path) this.choose(path, false, (event as MouseEvent).shiftKey);
217 },
218 { signal },
219 );
220 this.get(".outline").addEventListener(
221 "keydown",
222 (event) => {
223 const key = (event as KeyboardEvent).key;
224 if (!["ArrowUp", "ArrowDown", "Home", "End"].includes(key)) return;
225 const buttons = [
226 ...this.get(".outline").querySelectorAll<HTMLButtonElement>("button"),
227 ];
228 const i = buttons.indexOf(event.target as HTMLButtonElement);
229 const next =
230 key === "Home"
231 ? 0
232 : key === "End"
233 ? buttons.length - 1
234 : i + (key === "ArrowDown" ? 1 : -1);
235 event.preventDefault();
236 buttons[next]?.focus();
237 },
238 { signal },
239 );
240 this.get<HTMLInputElement>(".words").addEventListener(
241 "input",
242 () => {
243 const at = editsFor(this.copy.model, this.copy.chosen).text;
244 if (!at) return;
245 this.edit ??= beginTextEdit(this.copy, at.path);
246 this.copy = typeText(
247 this.copy,
248 this.edit,
249 this.get<HTMLInputElement>(".words").value,
250 );
251 this.render();
252 },
253 { signal },
254 );
255 this.get(".words").addEventListener(
256 "blur",
257 () => {
258 this.finish();
259 this.refresh();
260 },
261 { signal },
262 );
263 this.root.addEventListener(
264 "keydown",
265 (event) => {
266 const key = event as KeyboardEvent;
267 if (key.isComposing || key.keyCode === 229) return;
268 if (key.key === "Escape") {
269 if (event.target === this.get(".words") && this.edit) {
270 this.copy = cancelTextEdit(this.copy, this.edit);
271 this.edit = undefined;
272 this.render("Restored the wording before this edit.");
273 event.preventDefault();
274 return;
275 }
276 const details = (event.target as Element).closest("details[open]");
277 if (details instanceof HTMLDetailsElement) {
278 details.open = false;
279 details.querySelector("summary")?.focus();
280 event.preventDefault();
281 }
282 }
283 if (key.key === "Enter" && event.target === this.get(".words")) {
284 this.finish();
285 this.refresh();
286 }
287 },
288 { signal },
289 );
290 this.root.addEventListener(
291 "change",
292 (event) => {
293 const input = event.target as HTMLInputElement;
294 this.finish();
295 const e = editsFor(this.copy.model, this.copy.chosen);
296 if (input.name === "role" && isContentKind(input.value) && e.text)
297 this.apply({
298 tree: editContentKind(this.copy.model, e.text.path, input.value),
299 chosen: this.copy.chosen,
300 });
301 if (
302 input.name === "arrangement" &&
303 isArrangement(input.value) &&
304 e.arrange
305 )
306 this.apply({
307 tree: arrangeGroup(this.copy.model, e.arrange.path, input.value),
308 chosen: this.copy.chosen,
309 });
310 },
311 { signal },
312 );
313 this.views = [
314 new CompositionPreview(this.ownerDocument, {
315 label: "Resizable card",
316 slot: "wide",
317 width: {
318 initial: 445,
319 availableSpace: this.get(".preview-limit"),
320 changed: () => {},
321 },
322 choose: (path) => this.choose(path),
323 attend: () => {},
324 }),
325 new CompositionPreview(this.ownerDocument, {
326 label: "Narrow rail",
327 slot: "rail",
328 choose: (path) => this.choose(path),
329 attend: () => {},
330 }),
331 ];
332 this.get(".previews").append(...this.views.map((v) => v.element));
333 this.source = new SourcePanel(this.get("pre"), {
334 describe: (_path, node) =>
335 `Select ${node.kind}${"text" in node ? `: ${node.text}` : " group"}`,
336 choose: (path) => this.choose(path),
337 attend: () => {},
338 signal,
339 });
340 this.render();
341 }
342 private get<T extends HTMLElement = HTMLElement>(selector: string): T {
343 return this.root.querySelector<T>(selector)!;
344 }
345 private finish() {
346 if (this.edit) {
347 this.copy = finishTextEdit(this.copy, this.edit);
348 this.edit = undefined;
349 }
350 }
351 private choose(path: string, single = false, extend = false) {
352 this.finish();
353 const selected =
354 !single && (this.together || extend)
355 ? chooseMember(this.copy.model, this.copy.chosen, path)
356 : [path];
357 this.copy = { ...this.copy, chosen: selected.length ? selected : [path] };
358 this.insertAfter = false;
359 if (single) this.together = false;
360 this.refresh();
361 }
362 private apply(edited: Edited, message = "") {
363 this.finish();
364 if (JSON.stringify(edited.tree) === JSON.stringify(this.copy.model)) {
365 this.copy = { ...this.copy, chosen: edited.chosen };
366 this.refresh();
367 return;
368 }
369 this.insertAfter = false;
370 this.copy = commitEdit(this.copy, edited.tree, edited.chosen);
371 this.render(message);
372 const path = this.copy.chosen[0] ?? "0";
373 const active = this.root.activeElement as HTMLElement | null;
374 if (active?.matches("input[type=radio]")) return;
375 if (this.get(".outline").hidden) this.source?.focus(path);
376 else
377 this.get<HTMLButtonElement>(`[data-outline-path="${path}"]`)?.focus({
378 preventScroll: true,
379 });
380 }
381 private add(kind: "Text" | "Stack" | "Shelf" | "Switcher") {
382 this.finish();
383 const e = editsFor(this.copy.model, this.copy.chosen);
384 const place = this.insertAfter ? e.after : (e.inside ?? e.after);
385 if (!place) return;
386 this.get<HTMLDetailsElement>(".add-group").open = false;
387 this.together = false;
388 this.apply(
389 kind === "Text"
390 ? addText(this.copy.model, place)
391 : addGroup(this.copy.model, place, kind),
392 kind === "Text"
393 ? "Added text. You can write now."
394 : `Added an empty ${kind}. Add content inside it.`,
395 );
396 if (kind === "Text") {
397 const input = this.get<HTMLInputElement>(".words");
398 input.focus();
399 input.select();
400 } else this.get<HTMLButtonElement>(".add-text").focus();
401 }
402 private render(message = "") {
403 for (const view of this.views) view.render(this.copy.model, true);
404 this.source?.show(this.copy.model);
405 const focused = (this.root.activeElement as HTMLElement | null)?.dataset
406 .outlinePath;
407 const list = (node: Composition, path: string): HTMLLIElement => {
408 const li = document.createElement("li");
409 const button = document.createElement("button");
410 button.dataset.outlinePath = path;
411 const kind = document.createElement("span");
412 kind.className = "kind";
413 kind.textContent = node.kind;
414 const label = document.createElement("span");
415 label.className = "node-label";
416 label.textContent =
417 "children" in node
418 ? path === "0"
419 ? "Whole composition"
420 : node.children.length
421 ? `${node.children.length} ${node.children.length === 1 ? "member" : "members"}`
422 : "Empty group"
423 : node.text || "Empty text";
424 button.append(kind, label);
425 button.title = `${node.kind}: ${label.textContent}`;
426 li.append(button);
427 if ("children" in node && node.children.length) {
428 const ul = document.createElement("ul");
429 node.children.forEach((child, i) =>
430 ul.append(list(child, `${path}.${i}`)),
431 );
432 li.append(ul);
433 }
434 return li;
435 };
436 const ul = document.createElement("ul");
437 ul.append(list(this.copy.model, "0"));
438 this.get(".outline").replaceChildren(ul);
439 this.refresh();
440 if (focused)
441 this.get<HTMLButtonElement>(`[data-outline-path="${focused}"]`)?.focus({
442 preventScroll: true,
443 });
444 this.get(".feedback").textContent = message;
445 }
446 private refresh() {
447 const { model, chosen } = this.copy;
448 const e = editsFor(model, chosen);
449 const path = chosen[0] ?? "0";
450 const node = atPath(model, path)!;
451 const one = chosen.length < 2;
452 this.get(".inspector").toggleAttribute("data-multiple", !one);
453 this.get(".selected-title").textContent = one
454 ? node.kind
455 : `${chosen.length} members selected`;
456 this.get(".selected-detail").textContent =
457 one && "children" in node
458 ? `${node.children.length} ${node.children.length === 1 ? "member" : "members"}`
459 : "";
460 const parent = this.get(".parent");
461 parent.hidden = path === "0";
462 parent.textContent =
463 path === "0" ? "" : `↑ In ${atPath(model, parentPath(path))!.kind}`;
464 this.get(".wording").hidden = !e.text;
465 const words = this.get<HTMLInputElement>(".words");
466 if (words.value !== e.text?.content.text)
467 words.value = e.text?.content.text ?? "";
468 this.get(".roles").hidden = !e.text;
469 this.get(".arrangements").hidden = !e.arrange;
470 this.get(".role-purpose").textContent = e.text
471 ? rolePurpose[e.text.content.kind]
472 : "";
473 this.get(".arrangement-purpose").textContent = e.arrange
474 ? arrangementContracts[e.arrange.group.kind]
475 : "";
476 for (const input of this.root.querySelectorAll<HTMLInputElement>(
477 "input[type=radio]",
478 ))
479 input.checked =
480 input.name === "role"
481 ? input.value === e.text?.content.kind
482 : input.value === e.arrange?.group.kind;
483 this.get(".insert-after").hidden = !(e.inside && e.after);
484 this.get(".insert-after").textContent = this.insertAfter
485 ? "Add inside this group instead"
486 : "Add after this group instead";
487 this.get(".insertion-context").textContent =
488 e.inside && !this.insertAfter
489 ? `Add inside this ${e.inside.group.kind}`
490 : chosen.length > 1
491 ? "Add after these members"
492 : `Add after this ${node.kind}`;
493 this.get<HTMLButtonElement>(".add-text").disabled = !(e.inside || e.after);
494 this.get(".add-group").hidden = !(e.inside || e.after);
495 this.get(".group").hidden = !e.wrap;
496 this.get(".ungroup").hidden = !e.release;
497 this.get(".remove").hidden = !e.remove;
498 this.get<HTMLButtonElement>(".undo").disabled =
499 !this.edit && !this.copy.undo.length;
500 this.get(".together").textContent = this.together
501 ? "Done selecting"
502 : "Select several";
503 this.get(".together").setAttribute("aria-pressed", String(this.together));
504 this.get(".select-help").hidden = !this.together;
505 this.get(".structure").textContent = this.structure
506 ? "Hide structure"
507 : "Show structure";
508 this.get(".structure").setAttribute("aria-pressed", String(this.structure));
509 this.get(".empty-hint").hidden = !(
510 "children" in model && model.children.length === 0
511 );
512 for (const button of this.root.querySelectorAll<HTMLButtonElement>(
513 "[data-outline-path]",
514 )) {
515 button.setAttribute(
516 "aria-pressed",
517 String(chosen.includes(button.dataset.outlinePath!)),
518 );
519 button.tabIndex = button.dataset.outlinePath === path ? 0 : -1;
520 }
521 for (const view of this.views)
522 view.decorate({
523 chosen,
524 inspected: chosen.length === 1 ? chosen[0] : undefined,
525 structure: this.structure,
526 });
527 this.source?.mark(chosen);
528 this.source?.rove(path);
529 this.source?.inspect(
530 this.structure,
531 chosen.length === 1 ? chosen[0] : undefined,
532 );
533 }
534 disconnectedCallback() {
535 this.abort.abort();
536 for (const view of this.views) view.dispose();
537 this.source?.dispose();
538 }
539}
540customElements.define("axiomatic-workbench-study", WorkbenchStudy);