tobogganSe connecter

library

Prebuilt pebble components: drop-in custom elements, no compiler needed

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

Dernier runAucun
0Étoiles
0Forks
2Issues
375 lignes · 15257 octetsBrut · Historique
1// The <pebble-sequence> element: a sequence of steps, linear runs that a
2// branching step splits into outcomes, edited as a tree of cards. The page
3// declares the kinds of step and their fields; the value is JSON in a
4// textarea, which stays the form field of record and the no-JS fallback:
5//
6// <form method="post" action="/campaigns/42/sequence">
7// <pebble-sequence>
8// <template data-kind="invite" data-label="Send an invitation"></template>
9// <template data-kind="wait" data-label="Wait" data-summary="{days} days">
10// <label>Days <input name="days" type="number" min="1" value="3" required></label>
11// </template>
12// <template data-kind="connected" data-label="Accepted?" data-branches="Yes|No">
13// <label>Give up after (days) <input name="days" type="number" min="1" value="7"></label>
14// </template>
15// <textarea name="sequence">{"root":null}</textarea>
16// </pebble-sequence>
17// <button>Save</button>
18// </form>
19//
20// The element hides the textarea and renders the tree after it: a "+" before
21// every step and at the end of every run opens a menu of the kinds; a card
22// shows a step's kind and a summary of its fields, with Edit (the kind's
23// controls, cloned from its template, Done / Cancel) and Remove. A new step
24// with fields opens its editor at once, and canceling that first edit takes
25// it back out. Removing a step puts its successor in its place (its next, or
26// its first non-empty branch); when that would discard other steps, the
27// first press asks and a second removes. One editor at a time: while it is
28// open the other controls wait.
29//
30// Every committed edit rewrites the textarea and emits "change" (bubbling,
31// detail { value }). The editor's own controls have no form owner, so they
32// are never posted and Enter in them does not submit; their input/change
33// events stay inside the element. If the form is serialized while an editor
34// is open (the page's Save pressed mid-edit), the open edit is included when
35// its controls are valid. A form reset restores the textarea and the tree.
36//
37// Words are the page's: the `label-*` attributes (add, edit, remove,
38// confirm, done, cancel, start, end), English by default. `readonly` renders
39// the tree without controls.
40
41import { computed, define, emit, For, fromSignal, keys, on, onCleanup, pipe, scan, Show, subject, subscribe, toSignal } from "@pebble/pebble";
42import { DEV } from "./dev";
43import { controlsOf, defaultsOf, readFields, readKinds, summarize, writeFields, type Kind } from "./kinds";
44import {
45 childAt,
46 freshId,
47 idsOf,
48 isBranching,
49 parse,
50 ROOT,
51 runOf,
52 serialize,
53 slotKey,
54 slotOf,
55 start,
56 step as reduce,
57 update,
58 type Action,
59 type Sequence,
60 type Slot,
61 type Step,
62} from "./model";
63import styles from "./sequence.css";
64
65export { parse, serialize, insert, remove, update, type Sequence, type Step, type Slot, type Fields, type Field } from "./model";
66export { readFields, writeFields, readKinds, type Kind } from "./kinds";
67
68/** The words the element shows, overridable with `label-<name>` attributes. */
69export const WORDS = {
70 add: "Add a step",
71 edit: "Edit",
72 remove: "Remove",
73 confirm: "Remove with the steps it leads to",
74 done: "Done",
75 cancel: "Cancel",
76 start: "Start",
77 end: "End",
78};
79
80/** An id no form has: the editor's controls point their `form` at it, so they have no form owner. */
81const NO_FORM = "pebble-sequence-no-form";
82
83define("pebble-sequence", { shadow: false, scoped: false, styles }, (_props, host) => {
84 const field = [...host.children].find((child): child is HTMLTextAreaElement => child instanceof HTMLTextAreaElement);
85 const kinds = readKinds(host);
86 if (!field || kinds.size === 0) {
87 if (DEV) console.warn("<pebble-sequence>: needs a <textarea> child (the value) and at least one <template data-kind>; the textarea is left as is");
88 return null;
89 }
90 const branchCounts = new Map([...kinds.values()].map(kind => [kind.name, kind.branches.length]));
91 let initial: Sequence;
92 try {
93 initial = parse(field.value, branchCounts);
94 } catch (error) {
95 if (DEV) console.warn(`<pebble-sequence>: the textarea's value is not a sequence (${(error as Error).message}); it is left as is`);
96 return null;
97 }
98 if (DEV) {
99 const unknown = new Set<string>();
100 const walk = (s: Step | null) => {
101 if (!s) return;
102 if (!kinds.has(s.kind)) unknown.add(s.kind);
103 (s.branches ?? [s.next ?? null]).forEach(walk);
104 };
105 walk(initial.root);
106 if (unknown.size) console.warn(`<pebble-sequence>: no <template data-kind> for ${[...unknown].join(", ")}; those steps can be removed, not edited`);
107 }
108
109 const words = Object.fromEntries(Object.entries(WORDS).map(([name, word]) => [name, host.getAttribute(`label-${name}`) ?? word])) as typeof WORDS;
110 const readonly = host.hasAttribute("readonly");
111 const menu = [...kinds.values()];
112
113 const wasHidden = field.hidden;
114 field.hidden = true;
115 onCleanup(() => {
116 field.hidden = wasHidden;
117 });
118
119 const actions = subject<Action>();
120 const model = toSignal(pipe(actions, scan(reduce, start(initial))), start(initial));
121 const busy = computed(() => model().editing !== null);
122 host.toggleAttribute("data-readonly", readonly);
123
124 // Outward: the field of record, then the event. The first value is the server's own text, left untouched.
125 const text = computed(() => serialize(model().value));
126 subscribe(fromSignal(text, { skipInitial: true }))(value => {
127 if (field.value === value) return;
128 field.value = value;
129 emit(host, "change", { value: model().value });
130 });
131 subscribe(fromSignal(busy))(open => host.toggleAttribute("data-editing", open));
132
133 const focus = (selector: string) =>
134 queueMicrotask(() => host.querySelector<HTMLElement>(selector)?.focus());
135 const stepSelector = (id: string) => `[data-step="${CSS.escape(id)}"]`;
136 const addSelector = (slot: Slot) => `button.add[data-slot="${CSS.escape(slotKey(slot))}"]`;
137
138 // The open editor, for the form's serialization mid-edit.
139 let editor: { id: string; root: HTMLElement } | null = null;
140
141 const add = (kind: Kind, slot: Slot) => {
142 const id = freshId(idsOf(model().value));
143 const step: Step = { id, kind: kind.name, fields: defaultsOf(kind) };
144 if (kind.branches.length) step.branches = kind.branches.map(() => null);
145 actions.next({ type: "insert", slot, step, edit: kind.editable });
146 focus(kind.editable ? `${stepSelector(id)} .editor :is(input, select, textarea)` : `${stepSelector(id)} .card button`);
147 };
148
149 const cancel = () => {
150 const { editing, fresh, adding, confirming, value } = model();
151 if (editing && fresh) {
152 const slot = slotOf(value, editing);
153 actions.next({ type: "cancel" });
154 if (slot) focus(addSelector(slot));
155 } else if (editing) {
156 actions.next({ type: "cancel" });
157 focus(`${stepSelector(editing)} .card button.edit`);
158 } else if (adding) {
159 actions.next({ type: "cancel" });
160 focus(`button.add[data-slot="${CSS.escape(adding)}"]`);
161 } else if (confirming) {
162 actions.next({ type: "cancel" });
163 focus(`${stepSelector(confirming)} .card button.remove`);
164 }
165 };
166
167 const removeStep = (id: string) => {
168 const before = model();
169 const slot = slotOf(before.value, id);
170 actions.next({ type: "remove", id });
171 if (model().confirming === id) return;
172 const next = slot ? childAt(model().value, slot) : null;
173 focus(next ? `${stepSelector(next.id)} .card button` : slot ? addSelector(slot) : "button.add");
174 };
175
176 subscribe(keys(host, { Escape: "cancel" }))(({ event }) => {
177 const { editing, adding, confirming } = model();
178 if (!editing && !adding && !confirming) return;
179 event.preventDefault();
180 cancel();
181 });
182
183 // The editor's controls are internal: their input/change events end here; the element's own "change" is the output.
184 for (const type of ["input", "change"]) {
185 subscribe(on(host, type))(event => {
186 if (event.target !== host && (event.target as Element).closest?.(".editor")) event.stopPropagation();
187 });
188 }
189
190 const form = field.form;
191 if (form) {
192 subscribe(on(form, "reset"))(() =>
193 setTimeout(() => {
194 try {
195 actions.next({ type: "load", value: parse(field.value, branchCounts) });
196 } catch {
197 // the server's default was valid at upgrade; a reset restores it
198 }
199 }),
200 );
201 subscribe(on(form, "formdata"))(event => {
202 const open = editor;
203 if (!open || !field.name) return;
204 if (!controlsOf(open.root).every(control => control.checkValidity())) return;
205 (event as FormDataEvent).formData.set(field.name, serialize(update(model().value, open.id, readFields(open.root))));
206 });
207 }
208
209 // ── Rendering ────────────────────────────────────────────────────────────
210
211 /** The "+" before a step or at a run's end, and its menu of kinds. */
212 const Adder = (props: { slot: () => Slot }) => {
213 const open = computed(() => model().adding === slotKey(props.slot()));
214 return (
215 <div class="adder" data-open={open() ? "" : undefined}>
216 <button
217 type="button"
218 class="add"
219 data-slot={slotKey(props.slot())}
220 aria-label={words.add}
221 title={words.add}
222 aria-expanded={open() ? "true" : "false"}
223 disabled={busy()}
224 onClick={() => {
225 actions.next({ type: "menu", slot: open() ? null : props.slot() });
226 if (model().adding) focus(`button.add[data-slot="${CSS.escape(model().adding!)}"] + .menu button`);
227 }}
228 >
229 <span aria-hidden="true">+</span>
230 </button>
231 <Show when={open()}>
232 <div class="menu" role="group" aria-label={words.add}>
233 {menu.map(kind => (
234 <button type="button" class="kind" data-kind={kind.name} onClick={() => add(kind, props.slot())}>
235 {kind.label}
236 </button>
237 ))}
238 </div>
239 </Show>
240 </div>
241 );
242 };
243
244 /** A step's editor: its kind's controls, filled from the step, with Done and Cancel. */
245 const Editor = (props: { step: () => Step; kind: Kind }) => {
246 const id = props.step().id;
247 const fields = document.importNode(props.kind.template.content, true);
248 const body = (<div class="fields" />) as HTMLElement;
249 body.append(fields);
250 const controls = controlsOf(body);
251 for (const control of controls) control.setAttribute("form", NO_FORM);
252 writeFields(body, props.step().fields);
253 editor = { id, root: body };
254 onCleanup(() => {
255 if (editor?.root === body) editor = null;
256 });
257 const done = () => {
258 if (!controls.every(control => control.reportValidity())) return;
259 actions.next({ type: "commit", id, fields: readFields(body) });
260 focus(`${stepSelector(id)} .card button.edit`);
261 };
262 subscribe(keys(body, { Enter: "done" }))(({ event }) => {
263 const target = event.target as Element;
264 if (target instanceof HTMLTextAreaElement || target instanceof HTMLButtonElement || target instanceof HTMLSelectElement) return;
265 event.preventDefault();
266 done();
267 });
268 return (
269 <div class="editor" role="group" aria-label={props.kind.label}>
270 <span class="label">{props.kind.label}</span>
271 {body}
272 <div class="editor-actions">
273 <button type="button" class="done" onClick={done}>
274 {words.done}
275 </button>
276 <button type="button" class="cancel" onClick={cancel}>
277 {words.cancel}
278 </button>
279 </div>
280 </div>
281 );
282 };
283
284 /** A step's card (or its editor), and a branching step's outcomes. */
285 const Card = (props: { step: () => Step }) => {
286 const id = props.step().id;
287 const kind = kinds.get(props.step().kind);
288 const label = kind?.label ?? props.step().kind;
289 const editing = computed(() => model().editing === id);
290 const confirming = computed(() => model().confirming === id);
291 const outcomes = isBranching(props.step()) ? props.step().branches!.map((_, i) => i) : [];
292 return (
293 <>
294 <Show
295 when={editing() && kind}
296 fallback={
297 <div class="card" data-unknown={kind ? undefined : ""} data-confirming={confirming() ? "" : undefined}>
298 <span class="text">
299 <span class="label">{label}</span>
300 <span class="summary">{summarize(kind, props.step().fields)}</span>
301 </span>
302 {readonly ? null : (
303 <span class="actions">
304 {kind?.editable ? (
305 <button type="button" class="edit" aria-label={`${words.edit}: ${label}`} disabled={busy()} onClick={() => actions.next({ type: "edit", id })}>
306 {words.edit}
307 </button>
308 ) : null}
309 <button
310 type="button"
311 class="remove"
312 aria-label={confirming() ? `${words.confirm}: ${label}` : `${words.remove}: ${label}`}
313 disabled={busy()}
314 onClick={() => removeStep(id)}
315 >
316 {confirming() ? words.confirm : words.remove}
317 </button>
318 </span>
319 )}
320 </div>
321 }
322 >
323 {() => <Editor step={props.step} kind={kind!} />}
324 </Show>
325 {outcomes.length ? (
326 <div class="branches">
327 {outcomes.map(i => (
328 <div class="branch" data-branch={i}>
329 <span class="outcome">{kind?.branches[i] ?? String(i + 1)}</span>
330 <Run slot={() => ({ parent: id, branch: i })} head={() => props.step().branches?.[i] ?? null} />
331 </div>
332 ))}
333 </div>
334 ) : null}
335 </>
336 );
337 };
338
339 /** A linear run: each step with its "+" before it, then the run's end. */
340 const Run = (props: { slot: () => Slot; head: () => Step | null }) => {
341 const steps = computed(() => runOf(props.head()));
342 const tail = computed<Slot | null>(() => {
343 const run = steps();
344 const last = run[run.length - 1];
345 return !last ? props.slot() : isBranching(last) ? null : { parent: last.id, branch: null };
346 });
347 return (
348 <ol class="run">
349 <For each={steps()} key={s => s.id}>
350 {(item, index) => (
351 <li class="item" data-step={item().id} data-kind={item().kind}>
352 {readonly ? null : <Adder slot={() => (index() === 0 ? props.slot() : { parent: steps()[index() - 1].id, branch: null })} />}
353 <Card step={item} />
354 </li>
355 )}
356 </For>
357 <Show when={tail()}>
358 {slot => (
359 <li class="item end">
360 {readonly ? null : <Adder slot={slot} />}
361 <span class="mark">{words.end}</span>
362 </li>
363 )}
364 </Show>
365 </ol>
366 );
367 };
368
369 return (
370 <div class="sequence" part="sequence">
371 <span class="mark start">{words.start}</span>
372 <Run slot={() => ROOT} head={() => model().value.root} />
373 </div>
374 );
375});