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
| 1 | /** |
| 2 | * <pebble-tablet> — a plain-text notes editor on its own engine. |
| 3 | * |
| 4 | * The HTML contract is a server-rendered <textarea> child: it is the initial |
| 5 | * value and the no-JS fallback, and it STAYS the editing surface after the |
| 6 | * upgrade — visible, focused, typed in. Enhancement changes what an edit |
| 7 | * MEANS, not what the user sees: the textarea is the platform's plain-text |
| 8 | * editor (IME, selection, a11y, mobile keyboards — all free, all correct) |
| 9 | * while the DOCUMENT is the engine's: a pure-value model { doc, selection }, |
| 10 | * actions as data, a step reducer, and the element's own history. Native |
| 11 | * textarea undo dies at the first programmatic `value =` write; this |
| 12 | * element's does not. That is the engine's reason to exist. |
| 13 | * |
| 14 | * Streams own time, signals own derivation (pebble's docs/paradigm.md), one |
| 15 | * crossing between them: |
| 16 | * - beforeinput/paste/cut/keydown/selectionchange/compositionend are |
| 17 | * streams of what happened; each maps to an Action (what the event |
| 18 | * MEANT, read off the DOM at event time); |
| 19 | * - `scan(step, …)` folds actions into the model; ONE `toSignal` crosses; |
| 20 | * - effects only write outward: the field via `mirror` (doc → field, so |
| 21 | * the form field of record is never stale), the caret via afterRender, |
| 22 | * "change" via fromSignal → debounce → emit (the drag-handle precedent). |
| 23 | * |
| 24 | * Edits the engine handles are canceled at beforeinput and applied as exact |
| 25 | * transactions; anything it declines (an exotic inputType, a programmatic |
| 26 | * `value =` write, a form reset) reaches the field natively and reconciles |
| 27 | * by diff through the "input" event — the two paths are mutually exclusive |
| 28 | * per edit because preventDefault decides which one runs. IME composition |
| 29 | * is never canceled: the composed text is not finalized text, and it folds |
| 30 | * into the model as ONE step at compositionend. |
| 31 | * |
| 32 | * Outward events (bubbles + composed, detail carries the text): |
| 33 | * "change" { value } — debounced, after CHANGE_DEBOUNCE ms of silence |
| 34 | * "save" { value } — Mod+S inside the editor |
| 35 | * |
| 36 | * The engine's read-only view is readable as `element.editor` — { doc, |
| 37 | * selection } live getters, an escape hatch, not the API. |
| 38 | * |
| 39 | * Dialects (engine/dialect.ts): `defineDialect(name, dialect)` registers one |
| 40 | * and `<pebble-tablet dialect="name">` uses it — its commands and chords, and, |
| 41 | * when it decorates, a BACKDROP: an aria-hidden layer laid over the field's box, |
| 42 | * spelling the same text in the same font and wrap, while |
| 43 | * the field's own glyphs turn transparent. The field stays the surface (caret, |
| 44 | * selection, IME, a11y); the backdrop only paints, and its task boxes are the |
| 45 | * only thing in it that takes a click. A dialect defined after the element |
| 46 | * upgraded (the usual order: importing this module upgrades the page at once) |
| 47 | * applies from the moment it is defined. The registry is global, so a second |
| 48 | * bundle carrying this module shares it. |
| 49 | */ |
| 50 | import { |
| 51 | afterRender, |
| 52 | computed, |
| 53 | debounce, |
| 54 | define, |
| 55 | effect, |
| 56 | emit, |
| 57 | filter, |
| 58 | fromSignal, |
| 59 | keys, |
| 60 | map, |
| 61 | merge, |
| 62 | mirror, |
| 63 | on, |
| 64 | onCleanup, |
| 65 | pipe, |
| 66 | scan, |
| 67 | Show, |
| 68 | For, |
| 69 | subject, |
| 70 | subscribe, |
| 71 | switchMap, |
| 72 | toSignal, |
| 73 | untrack, |
| 74 | } from "@pebble/pebble"; |
| 75 | import { DEV } from "./dev"; |
| 76 | import { plain, type Decorated, type Dialect } from "./engine/dialect"; |
| 77 | import { carriesText, handlesInputType, keymap, startModel, stepWith, type Action, type Model } from "./engine/model"; |
| 78 | import { selected, type Selection } from "./engine/state"; |
| 79 | import styles from "./tablet.css"; |
| 80 | |
| 81 | /** Silence before a "change" leaves the element, ms. */ |
| 82 | export const CHANGE_DEBOUNCE = 300; |
| 83 | |
| 84 | /** The chords this element resolves; Mod+S saves. */ |
| 85 | const CHORDS = { "Mod+S": "save" } as const; |
| 86 | |
| 87 | /** A read-only view of an instance's engine, for the `editor` accessor below. */ |
| 88 | export interface TabletEngineView { |
| 89 | readonly doc: string; |
| 90 | readonly selection: Selection; |
| 91 | } |
| 92 | |
| 93 | /** Each instance's engine view, for the `editor` accessor below. */ |
| 94 | const views = new WeakMap<HTMLElement, TabletEngineView>(); |
| 95 | |
| 96 | /** The text a beforeinput carries, when it carries any. */ |
| 97 | function textOf(event: InputEvent): string | null { |
| 98 | const transferred = event.dataTransfer?.getData("text/plain"); |
| 99 | if (transferred !== undefined && transferred !== null && transferred !== "") return transferred; |
| 100 | return event.data; |
| 101 | } |
| 102 | |
| 103 | /** The dialect registry, global so every bundle carrying this module shares it. */ |
| 104 | const DIALECTS = Symbol.for("pebble.tablet.dialects"); |
| 105 | /** Fired on window when a dialect is defined; elements waiting for it pick it up. */ |
| 106 | const DIALECT_DEFINED = "pebble-tablet:dialect"; |
| 107 | |
| 108 | function dialects(): Map<string, Dialect> { |
| 109 | const scope = globalThis as { [DIALECTS]?: Map<string, Dialect> }; |
| 110 | return (scope[DIALECTS] ??= new Map()); |
| 111 | } |
| 112 | |
| 113 | /** Register a dialect under `name`, for `<pebble-tablet dialect="name">`. */ |
| 114 | export function defineDialect(name: string, dialect: Dialect): void { |
| 115 | if (DEV && dialects().has(name)) console.warn(`<pebble-tablet>: dialect "${name}" is defined twice; the later one wins.`); |
| 116 | dialects().set(name, dialect); |
| 117 | window.dispatchEvent(new CustomEvent(DIALECT_DEFINED, { detail: { name } })); |
| 118 | } |
| 119 | |
| 120 | /** A line with no dialect decoration: one plain segment. */ |
| 121 | const undecorated = (line: string): Decorated => ({ kind: "plain", segments: [{ text: line, classes: [] }] }); |
| 122 | |
| 123 | const Tablet = define("pebble-tablet", { shadow: false, styles, props: { dialect: String } }, (props, host) => { |
| 124 | // The server-rendered textarea is the field of record; absent, an empty |
| 125 | // one takes the role (and the host's name, so the form still has its key). |
| 126 | const server = host.querySelector("textarea"); |
| 127 | const field = server ?? (<textarea />) as HTMLTextAreaElement; |
| 128 | if (server === null) { |
| 129 | const name = host.getAttribute("name"); |
| 130 | if (name !== null) field.name = name; |
| 131 | } else if (DEV && host.querySelectorAll("textarea").length > 1) { |
| 132 | console.warn("<pebble-tablet>: one textarea child is the field of record; the rest are ignored."); |
| 133 | } |
| 134 | // One element, two roles: it is the editing surface and the form field. |
| 135 | field.setAttribute("part", "editor field"); |
| 136 | |
| 137 | /** The field's selection as the engine sees it, at event time. */ |
| 138 | const at = (): Selection => { |
| 139 | const { selectionStart: from, selectionEnd: to, selectionDirection: direction } = field; |
| 140 | return direction === "backward" ? { anchor: to, head: from } : { anchor: from, head: to }; |
| 141 | }; |
| 142 | |
| 143 | // True while an IME composition owns the field: the model stands still, |
| 144 | // the caret is not tracked, nothing is projected back. |
| 145 | let writing = false; |
| 146 | subscribe(on(field, "compositionstart"))(() => (writing = true)); |
| 147 | subscribe(on(field, "compositionend"))(() => (writing = false)); |
| 148 | |
| 149 | // What the field allows right now; readonly/disabled block edits natively, |
| 150 | // and the engine agrees — undo/redo are edits too. |
| 151 | const editable = () => !field.readOnly && !field.disabled; |
| 152 | |
| 153 | // The dialect by name, picked up whenever one is defined after the upgrade. |
| 154 | const defined = toSignal(on(window, DIALECT_DEFINED), null, { equals: () => false }); |
| 155 | const dialect = computed((): Dialect => { |
| 156 | defined(); |
| 157 | const name = props.dialect(); |
| 158 | return (name !== undefined && dialects().get(name)) || plain; |
| 159 | }); |
| 160 | const reduce = computed(() => stepWith(dialect())); |
| 161 | |
| 162 | // The event streams, mapped to what they MEAN. beforeinput is canceled |
| 163 | // exactly when the engine handles it (synchronously, in the listener's |
| 164 | // task); the cancel and the action hang off the same filtered stream. An |
| 165 | // insert whose text is missing or empty is the browser's to make, not |
| 166 | // ours (an empty insert is a native no-op, never a selection delete). |
| 167 | const edits = pipe( |
| 168 | on<InputEvent>(field, "beforeinput"), |
| 169 | filter( |
| 170 | event => |
| 171 | !event.isComposing && |
| 172 | event.inputType !== "insertCompositionText" && |
| 173 | editable() && |
| 174 | handlesInputType(event.inputType, untrack(dialect)) && |
| 175 | (!carriesText(event.inputType) || (textOf(event) ?? "") !== ""), |
| 176 | ), |
| 177 | ); |
| 178 | subscribe(edits)(event => event.preventDefault()); |
| 179 | |
| 180 | const pastes = pipe( |
| 181 | on(field, "paste"), |
| 182 | filter(event => (event.clipboardData?.getData("text/plain") ?? "") !== ""), |
| 183 | ); |
| 184 | subscribe(pastes)(event => event.preventDefault()); |
| 185 | |
| 186 | const cuts = pipe( |
| 187 | on(field, "cut"), |
| 188 | filter(event => event.clipboardData !== null && field.selectionStart !== field.selectionEnd && editable()), |
| 189 | ); |
| 190 | subscribe(cuts)(event => { |
| 191 | event.clipboardData!.setData("text/plain", field.value.slice(field.selectionStart, field.selectionEnd)); |
| 192 | event.preventDefault(); |
| 193 | }); |
| 194 | |
| 195 | // A form reset restores defaultValue without an "input" event; read the |
| 196 | // field back once the browser has settled it, and push that in as a set. |
| 197 | const poked = subject<Action>(); |
| 198 | if (field.form !== null) { |
| 199 | subscribe(on(field.form, "reset"))(() => { |
| 200 | setTimeout(() => { |
| 201 | if (field.isConnected) poked.next({ kind: "set", doc: field.value, selection: null, at: 0 }); |
| 202 | }, 0); |
| 203 | }); |
| 204 | } |
| 205 | |
| 206 | // Task boxes: the only part of the backdrop that takes the pointer. The |
| 207 | // press must not move focus off the field; the click is the tick. |
| 208 | const box = (event: Event) => (event.target instanceof Element ? event.target.closest("[part~=box]") : null); |
| 209 | const lineOf = (event: Event) => Number(box(event)?.closest("[data-line]")?.getAttribute("data-line") ?? -1); |
| 210 | subscribe(pipe(on(host, "mousedown"), filter(event => box(event) !== null)))(event => event.preventDefault()); |
| 211 | const boxClicks = pipe( |
| 212 | on(host, "click"), |
| 213 | filter(event => box(event) !== null && editable()), |
| 214 | ); |
| 215 | |
| 216 | const actions = merge( |
| 217 | pipe( |
| 218 | edits, |
| 219 | map((event): Action => ({ kind: "edit", inputType: event.inputType, text: textOf(event) ?? "", selection: at(), at: event.timeStamp })), |
| 220 | ), |
| 221 | pipe( |
| 222 | pastes, |
| 223 | map((event): Action => ({ |
| 224 | kind: "edit", |
| 225 | inputType: "insertFromPaste", |
| 226 | text: event.clipboardData!.getData("text/plain"), |
| 227 | selection: at(), |
| 228 | at: event.timeStamp, |
| 229 | })), |
| 230 | ), |
| 231 | pipe( |
| 232 | cuts, |
| 233 | map((event): Action => ({ kind: "edit", inputType: "deleteByCut", text: "", selection: at(), at: event.timeStamp })), |
| 234 | ), |
| 235 | pipe( |
| 236 | fromSignal(dialect), |
| 237 | switchMap(current => keys(host, { ...keymap, ...current.keymap })), |
| 238 | filter(({ name }) => name === "all" || editable()), |
| 239 | map(({ name, event }): Action => ({ kind: "key", name, selection: at(), at: event.timeStamp })), |
| 240 | ), |
| 241 | // The user moved the caret; tracked (not while composing) so edits land |
| 242 | // where the caret is and undo restores it. |
| 243 | pipe( |
| 244 | on(document, "selectionchange"), |
| 245 | filter(() => !writing && document.activeElement === field), |
| 246 | map((): Action => ({ kind: "select", selection: at() })), |
| 247 | ), |
| 248 | // An IME composition ended: its text folds in as one step. |
| 249 | pipe( |
| 250 | on(field, "compositionend"), |
| 251 | map((event): Action => ({ kind: "compose", doc: field.value, selection: at(), at: event.timeStamp })), |
| 252 | ), |
| 253 | // The safety net: any input that reached the field natively (a |
| 254 | // programmatic write, an inputType the engine declines) reconciles by |
| 255 | // diff. Mid-composition inputs are not finalized text; they wait. |
| 256 | pipe( |
| 257 | on<InputEvent>(field, "input"), |
| 258 | filter(event => !event.isComposing), |
| 259 | map((event): Action => ({ kind: "set", doc: field.value, selection: at(), at: event.timeStamp })), |
| 260 | ), |
| 261 | // A task box in the backdrop was clicked: the dialect's tick decides. |
| 262 | pipe( |
| 263 | boxClicks, |
| 264 | map((event): Action => ({ kind: "tick", line: lineOf(event), at: event.timeStamp })), |
| 265 | ), |
| 266 | // The delayed form-reset read, pushed from the subscribe above. |
| 267 | poked, |
| 268 | ); |
| 269 | |
| 270 | // The one crossing: actions fold into the model; the model is a signal. |
| 271 | const initial = startModel(field.value); |
| 272 | const model = toSignal( |
| 273 | pipe( |
| 274 | actions, |
| 275 | scan((current: Model, action: Action) => untrack(reduce)(current, action), initial), |
| 276 | ), |
| 277 | initial, |
| 278 | { equals: (a: Model, b: Model) => a === b }, |
| 279 | ); |
| 280 | const doc = computed(() => model().state.doc); |
| 281 | |
| 282 | // doc → field: the form field of record stays current, verbatim, even |
| 283 | // while focused — the engine canceled the native edit, so the mirror's |
| 284 | // write IS the text appearing. During a composition the model stands |
| 285 | // still, so the mirror never writes over composed text. |
| 286 | mirror(field, doc, { evenWhileFocused: true }); |
| 287 | |
| 288 | // field ← selection: the caret is the model's, projected once the |
| 289 | // synchronous writes of the edit have settled. Writing `value` moves the |
| 290 | // caret; this puts it back before the browser handles the next event. |
| 291 | effect(() => { |
| 292 | const { selection } = model().state; |
| 293 | afterRender(field, () => { |
| 294 | if (writing || document.activeElement !== field) return; |
| 295 | const { from, to } = selected(selection); |
| 296 | const direction = selection.anchor <= selection.head ? "forward" : "backward"; |
| 297 | const current = field.selectionDirection === "backward" ? "backward" : "forward"; |
| 298 | if (field.selectionStart === from && field.selectionEnd === to && current === direction) return; |
| 299 | field.setSelectionRange(from, to, direction); |
| 300 | }); |
| 301 | }); |
| 302 | |
| 303 | // "change" leaves debounced: the state differentiated back into time. |
| 304 | subscribe(pipe(fromSignal(doc, { skipInitial: true }), debounce(CHANGE_DEBOUNCE)))(value => |
| 305 | emit(host, "change", { value }), |
| 306 | ); |
| 307 | |
| 308 | // Mod+S saves. preventDefault stays synchronous, inside the listener's |
| 309 | // task — the browser's own Save dialog never opens. keys() resolves |
| 310 | // nothing while an IME composition is in progress (its contract), so the |
| 311 | // chord never steals a composing keystroke. |
| 312 | subscribe(keys(host, CHORDS))(({ event }) => { |
| 313 | event.preventDefault(); |
| 314 | emit(host, "save", { value: doc() }); |
| 315 | }); |
| 316 | |
| 317 | // The backdrop: drawn only when the dialect decorates. It spells the same |
| 318 | // lines as the field, so it must scroll with it. |
| 319 | const decorate = computed(() => dialect().decorate); |
| 320 | const rows = computed(() => doc().split("\n")); |
| 321 | effect(() => host.toggleAttribute("data-decorated", decorate() !== undefined)); |
| 322 | const follow = () => { |
| 323 | const backdrop = host.querySelector<HTMLElement>(":scope > [part~=backdrop]"); |
| 324 | if (backdrop !== null) backdrop.scrollTop = field.scrollTop; |
| 325 | }; |
| 326 | subscribe(on(field, "scroll"))(follow); |
| 327 | effect(() => { |
| 328 | rows(); |
| 329 | afterRender(field, follow); |
| 330 | }); |
| 331 | |
| 332 | const line = (text: string, index: () => number) => { |
| 333 | const decorated = computed(() => (decorate() ?? undecorated)(text)); |
| 334 | return ( |
| 335 | <div class={`line line-${decorated().kind}`} data-line={index()}> |
| 336 | {decorated().segments.map(segment => |
| 337 | segment.box === undefined ? ( |
| 338 | <span class={segment.classes.join(" ")}>{segment.text}</span> |
| 339 | ) : ( |
| 340 | <span class={segment.classes.join(" ")} part="box" data-checked={segment.box.checked ? "" : undefined}> |
| 341 | {segment.text} |
| 342 | </span> |
| 343 | ), |
| 344 | )} |
| 345 | </div> |
| 346 | ); |
| 347 | }; |
| 348 | |
| 349 | const drawn = ( |
| 350 | <Show when={decorate()}> |
| 351 | <div part="backdrop" aria-hidden="true"> |
| 352 | <For each={rows()}>{line}</For> |
| 353 | </div> |
| 354 | </Show> |
| 355 | ); |
| 356 | |
| 357 | views.set(host, { |
| 358 | get doc() { |
| 359 | return model().state.doc; |
| 360 | }, |
| 361 | get selection() { |
| 362 | return model().state.selection; |
| 363 | }, |
| 364 | }); |
| 365 | |
| 366 | host.setAttribute("data-enhanced", ""); |
| 367 | onCleanup(() => { |
| 368 | views.delete(host); |
| 369 | host.removeAttribute("data-enhanced"); |
| 370 | }); |
| 371 | |
| 372 | return ( |
| 373 | <> |
| 374 | {server === null ? field : null} |
| 375 | {drawn} |
| 376 | </> |
| 377 | ); |
| 378 | }); |
| 379 | |
| 380 | /** A <pebble-tablet> element. `editor` is the engine's read-only view (escape hatch). */ |
| 381 | export interface TabletElement extends HTMLElement { |
| 382 | readonly editor?: TabletEngineView; |
| 383 | } |
| 384 | |
| 385 | // The view as a read-only accessor. Guarded: a second bundle carrying this |
| 386 | // module gets the first bundle's constructor from define(), and must not |
| 387 | // shadow its getter with one reading this copy's empty WeakMap. |
| 388 | if (!("editor" in Tablet.prototype)) { |
| 389 | Object.defineProperty(Tablet.prototype, "editor", { |
| 390 | get(this: HTMLElement) { |
| 391 | return views.get(this); |
| 392 | }, |
| 393 | }); |
| 394 | } |
| 395 | |
| 396 | export { Tablet }; |
| 397 | export type { Command, Decorated, Dialect, Segment } from "./engine/dialect"; |
| 398 | export type { Change, EditorState, Selection, Transaction } from "./engine/state"; |