| @@ -1,56 +1,65 @@ |
| 1 | 1 | /** |
| 2 | | − * <pebble-tablet> — a CodeMirror-6 plain-text notes editor. |
| 2 | + * <pebble-tablet> — a plain-text notes editor on its own engine. |
| 3 | 3 | * |
| 4 | 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 form field of record after |
| 6 | | − * the upgrade — hidden, kept equal to the document, so a plain form post |
| 7 | | − * sends what was typed and nothing about the form changes. With no textarea |
| 8 | | − * child the element renders an empty one (taking the host's `name`, if any); |
| 9 | | − * with no JS the markup works as it always did. |
| 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. |
| 10 | 13 | * |
| 11 | | − * Streams own time, signals own derivation (pebble's docs/paradigm.md). The |
| 12 | | − * document text is one signal, written by CodeMirror's update listener. From |
| 13 | | − * there: |
| 14 | | − * - the textarea follows the signal through `mirror` (doc → field, so the |
| 15 | | − * form field of record is never stale); |
| 16 | | − * - an "input" on the textarea flows back into the document (field → doc: |
| 17 | | − * a programmatic `field.value = …` + dispatch, a form reset, a server |
| 18 | | − * morph all stay true); |
| 19 | | − * - the outward "change" event is the signal differentiated and debounced |
| 20 | | − * (fromSignal → debounce → emit, the drag-handle precedent); |
| 21 | | − * - Mod+S is a "save" chord through keys(), which resolves nothing while |
| 22 | | − * an IME composition is in progress (the keys() contract), so the chord |
| 23 | | − * never steals a composing keystroke. |
| 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). |
| 24 | 23 | * |
| 25 | | − * Minimal CodeMirror: history, the default keymap, drawn selection, soft |
| 26 | | − * wrapping, the textarea's placeholder. No language pack — these are |
| 27 | | − * plain-text notes. readonly/disabled on the textarea pass through to the |
| 28 | | − * editor at upgrade time. |
| 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. |
| 29 | 31 | * |
| 30 | 32 | * Outward events (bubbles + composed, detail carries the text): |
| 31 | 33 | * "change" { value } — debounced, after CHANGE_DEBOUNCE ms of silence |
| 32 | 34 | * "save" { value } — Mod+S inside the editor |
| 33 | 35 | * |
| 34 | | − * The instance's CodeMirror view is readable as `element.editor` — an |
| 35 | | − * escape hatch for focus() and dispatch(), not the API. |
| 36 | + * The engine's read-only view is readable as `element.editor` — { doc, |
| 37 | + * selection } live getters, an escape hatch, not the API. |
| 36 | 38 | */ |
| 37 | | −import { EditorState } from "@codemirror/state"; |
| 38 | | −import { EditorView, drawSelection, keymap, placeholder } from "@codemirror/view"; |
| 39 | | −import { defaultKeymap, history, historyKeymap } from "@codemirror/commands"; |
| 40 | 39 | import { |
| 40 | + afterRender, |
| 41 | + computed, |
| 41 | 42 | debounce, |
| 42 | 43 | define, |
| 44 | + effect, |
| 43 | 45 | emit, |
| 46 | + filter, |
| 44 | 47 | fromSignal, |
| 45 | 48 | keys, |
| 49 | + map, |
| 50 | + merge, |
| 46 | 51 | mirror, |
| 47 | 52 | on, |
| 48 | 53 | onCleanup, |
| 49 | 54 | pipe, |
| 50 | | − signal, |
| 55 | + scan, |
| 56 | + subject, |
| 51 | 57 | subscribe, |
| 58 | + toSignal, |
| 52 | 59 | } from "@pebble/pebble"; |
| 53 | 60 | import { DEV } from "./dev"; |
| 61 | +import { carriesText, handlesInputType, keymap, startModel, step, type Action, type Model } from "./engine/model"; |
| 62 | +import { selected, type Selection } from "./engine/state"; |
| 54 | 63 | import styles from "./tablet.css"; |
| 55 | 64 | |
| 56 | 65 | /** Silence before a "change" leaves the element, ms. */ |
| @@ -59,63 +68,168 @@ export const CHANGE_DEBOUNCE = 300; |
| 59 | 68 | /** The chords this element resolves; Mod+S saves. */ |
| 60 | 69 | const CHORDS = { "Mod+S": "save" } as const; |
| 61 | 70 | |
| 62 | | −/** Each instance's CodeMirror view, for the `editor` accessor below. */ |
| 63 | | −const views = new WeakMap<HTMLElement, EditorView>(); |
| 71 | +/** A read-only view of an instance's engine, for the `editor` accessor below. */ |
| 72 | +export interface TabletEngineView { |
| 73 | + readonly doc: string; |
| 74 | + readonly selection: Selection; |
| 75 | +} |
| 76 | + |
| 77 | +/** Each instance's engine view, for the `editor` accessor below. */ |
| 78 | +const views = new WeakMap<HTMLElement, TabletEngineView>(); |
| 79 | + |
| 80 | +/** The text a beforeinput carries, when it carries any. */ |
| 81 | +function textOf(event: InputEvent): string | null { |
| 82 | + const transferred = event.dataTransfer?.getData("text/plain"); |
| 83 | + if (transferred !== undefined && transferred !== null && transferred !== "") return transferred; |
| 84 | + return event.data; |
| 85 | +} |
| 64 | 86 | |
| 65 | 87 | const Tablet = define("pebble-tablet", { shadow: false, styles }, (_, host) => { |
| 66 | 88 | // The server-rendered textarea is the field of record; absent, an empty |
| 67 | 89 | // one takes the role (and the host's name, so the form still has its key). |
| 68 | 90 | const server = host.querySelector("textarea"); |
| 69 | | − const field = server ?? (<textarea part="field" />) as HTMLTextAreaElement; |
| 91 | + const field = server ?? (<textarea />) as HTMLTextAreaElement; |
| 70 | 92 | if (server === null) { |
| 71 | 93 | const name = host.getAttribute("name"); |
| 72 | 94 | if (name !== null) field.name = name; |
| 73 | 95 | } else if (DEV && host.querySelectorAll("textarea").length > 1) { |
| 74 | 96 | console.warn("<pebble-tablet>: one textarea child is the field of record; the rest are ignored."); |
| 75 | 97 | } |
| 76 | | − field.setAttribute("part", "field"); |
| 77 | | − |
| 78 | | − const surface = (<div part="editor" />) as HTMLDivElement; |
| 79 | | − |
| 80 | | − // The document text as state. CodeMirror owns the editing surface; this |
| 81 | | − // signal is what the rest of the element derives from. |
| 82 | | − const doc = signal(field.value); |
| 83 | | − |
| 84 | | − const view = new EditorView({ |
| 85 | | − parent: surface, |
| 86 | | − state: EditorState.create({ |
| 87 | | − doc: field.value, |
| 88 | | − extensions: [ |
| 89 | | − history(), |
| 90 | | − drawSelection(), |
| 91 | | − EditorView.lineWrapping, |
| 92 | | − keymap.of([...defaultKeymap, ...historyKeymap]), |
| 93 | | − EditorView.updateListener.of(update => { |
| 94 | | − if (update.docChanged) doc(update.state.doc.toString()); |
| 95 | | − }), |
| 96 | | − ...(field.placeholder ? [placeholder(field.placeholder)] : []), |
| 97 | | − ...(field.readOnly || field.disabled ? [EditorState.readOnly.of(true)] : []), |
| 98 | | − ...(field.disabled ? [EditorView.editable.of(false)] : []), |
| 99 | | − ...(field.hasAttribute("aria-label") |
| 100 | | − ? [EditorView.contentAttributes.of({ "aria-label": field.getAttribute("aria-label")! })] |
| 101 | | − : []), |
| 102 | | − ], |
| 103 | | − }), |
| 98 | + // One element, two roles: it is the editing surface and the form field. |
| 99 | + field.setAttribute("part", "editor field"); |
| 100 | + |
| 101 | + /** The field's selection as the engine sees it, at event time. */ |
| 102 | + const at = (): Selection => { |
| 103 | + const { selectionStart: from, selectionEnd: to, selectionDirection: direction } = field; |
| 104 | + return direction === "backward" ? { anchor: to, head: from } : { anchor: from, head: to }; |
| 105 | + }; |
| 106 | + |
| 107 | + // True while an IME composition owns the field: the model stands still, |
| 108 | + // the caret is not tracked, nothing is projected back. |
| 109 | + let writing = false; |
| 110 | + subscribe(on(field, "compositionstart"))(() => (writing = true)); |
| 111 | + subscribe(on(field, "compositionend"))(() => (writing = false)); |
| 112 | + |
| 113 | + // What the field allows right now; readonly/disabled block edits natively, |
| 114 | + // and the engine agrees — undo/redo are edits too. |
| 115 | + const editable = () => !field.readOnly && !field.disabled; |
| 116 | + |
| 117 | + // The event streams, mapped to what they MEAN. beforeinput is canceled |
| 118 | + // exactly when the engine handles it (synchronously, in the listener's |
| 119 | + // task); the cancel and the action hang off the same filtered stream. An |
| 120 | + // insert whose text is missing or empty is the browser's to make, not |
| 121 | + // ours (an empty insert is a native no-op, never a selection delete). |
| 122 | + const edits = pipe( |
| 123 | + on<InputEvent>(field, "beforeinput"), |
| 124 | + filter( |
| 125 | + event => |
| 126 | + !event.isComposing && |
| 127 | + event.inputType !== "insertCompositionText" && |
| 128 | + editable() && |
| 129 | + handlesInputType(event.inputType) && |
| 130 | + (!carriesText(event.inputType) || (textOf(event) ?? "") !== ""), |
| 131 | + ), |
| 132 | + ); |
| 133 | + subscribe(edits)(event => event.preventDefault()); |
| 134 | + |
| 135 | + const pastes = pipe( |
| 136 | + on(field, "paste"), |
| 137 | + filter(event => (event.clipboardData?.getData("text/plain") ?? "") !== ""), |
| 138 | + ); |
| 139 | + subscribe(pastes)(event => event.preventDefault()); |
| 140 | + |
| 141 | + const cuts = pipe( |
| 142 | + on(field, "cut"), |
| 143 | + filter(event => event.clipboardData !== null && field.selectionStart !== field.selectionEnd && editable()), |
| 144 | + ); |
| 145 | + subscribe(cuts)(event => { |
| 146 | + event.clipboardData!.setData("text/plain", field.value.slice(field.selectionStart, field.selectionEnd)); |
| 147 | + event.preventDefault(); |
| 104 | 148 | }); |
| 105 | | − views.set(host, view); |
| 106 | 149 | |
| 107 | | − // doc → field: the form field of record stays current. Verbatim even if |
| 108 | | − // the field somehow has focus — a difference then is the document's own |
| 109 | | − // decision (a programmatic doc write), and it must show. |
| 150 | + // A form reset restores defaultValue without an "input" event; read the |
| 151 | + // field back once the browser has settled it, and push that in as a set. |
| 152 | + const poked = subject<Action>(); |
| 153 | + if (field.form !== null) { |
| 154 | + subscribe(on(field.form, "reset"))(() => { |
| 155 | + setTimeout(() => { |
| 156 | + if (field.isConnected) poked.next({ kind: "set", doc: field.value, selection: null, at: 0 }); |
| 157 | + }, 0); |
| 158 | + }); |
| 159 | + } |
| 160 | + |
| 161 | + const actions = merge( |
| 162 | + pipe( |
| 163 | + edits, |
| 164 | + map((event): Action => ({ kind: "edit", inputType: event.inputType, text: textOf(event) ?? "", selection: at(), at: event.timeStamp })), |
| 165 | + ), |
| 166 | + pipe( |
| 167 | + pastes, |
| 168 | + map((event): Action => ({ |
| 169 | + kind: "edit", |
| 170 | + inputType: "insertFromPaste", |
| 171 | + text: event.clipboardData!.getData("text/plain"), |
| 172 | + selection: at(), |
| 173 | + at: event.timeStamp, |
| 174 | + })), |
| 175 | + ), |
| 176 | + pipe( |
| 177 | + cuts, |
| 178 | + map((event): Action => ({ kind: "edit", inputType: "deleteByCut", text: "", selection: at(), at: event.timeStamp })), |
| 179 | + ), |
| 180 | + pipe( |
| 181 | + keys(host, keymap), |
| 182 | + filter(({ name }) => name === "all" || editable()), |
| 183 | + map(({ name, event }): Action => ({ kind: "key", name, selection: at(), at: event.timeStamp })), |
| 184 | + ), |
| 185 | + // The user moved the caret; tracked (not while composing) so edits land |
| 186 | + // where the caret is and undo restores it. |
| 187 | + pipe( |
| 188 | + on(document, "selectionchange"), |
| 189 | + filter(() => !writing && document.activeElement === field), |
| 190 | + map((): Action => ({ kind: "select", selection: at() })), |
| 191 | + ), |
| 192 | + // An IME composition ended: its text folds in as one step. |
| 193 | + pipe( |
| 194 | + on(field, "compositionend"), |
| 195 | + map((event): Action => ({ kind: "compose", doc: field.value, selection: at(), at: event.timeStamp })), |
| 196 | + ), |
| 197 | + // The safety net: any input that reached the field natively (a |
| 198 | + // programmatic write, an inputType the engine declines) reconciles by |
| 199 | + // diff. Mid-composition inputs are not finalized text; they wait. |
| 200 | + pipe( |
| 201 | + on<InputEvent>(field, "input"), |
| 202 | + filter(event => !event.isComposing), |
| 203 | + map((event): Action => ({ kind: "set", doc: field.value, selection: at(), at: event.timeStamp })), |
| 204 | + ), |
| 205 | + // The delayed form-reset read, pushed from the subscribe above. |
| 206 | + poked, |
| 207 | + ); |
| 208 | + |
| 209 | + // The one crossing: actions fold into the model; the model is a signal. |
| 210 | + const initial = startModel(field.value); |
| 211 | + const model = toSignal(pipe(actions, scan(step, initial)), initial, { equals: (a: Model, b: Model) => a === b }); |
| 212 | + const doc = computed(() => model().state.doc); |
| 213 | + |
| 214 | + // doc → field: the form field of record stays current, verbatim, even |
| 215 | + // while focused — the engine canceled the native edit, so the mirror's |
| 216 | + // write IS the text appearing. During a composition the model stands |
| 217 | + // still, so the mirror never writes over composed text. |
| 110 | 218 | mirror(field, doc, { evenWhileFocused: true }); |
| 111 | 219 | |
| 112 | | − // field → doc: a programmatic write (field.value = …, then "input") flows |
| 113 | | − // back into the document. The guard keeps the mirror's own writes from |
| 114 | | − // round-tripping (they dispatch no event; an equal value dispatches nothing). |
| 115 | | − subscribe(on(field, "input"))(() => { |
| 116 | | − const text = field.value; |
| 117 | | − if (text === doc()) return; |
| 118 | | − view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text } }); |
| 220 | + // field ← selection: the caret is the model's, projected once the |
| 221 | + // synchronous writes of the edit have settled. Writing `value` moves the |
| 222 | + // caret; this puts it back before the browser handles the next event. |
| 223 | + effect(() => { |
| 224 | + const { selection } = model().state; |
| 225 | + afterRender(field, () => { |
| 226 | + if (writing || document.activeElement !== field) return; |
| 227 | + const { from, to } = selected(selection); |
| 228 | + const direction = selection.anchor <= selection.head ? "forward" : "backward"; |
| 229 | + const current = field.selectionDirection === "backward" ? "backward" : "forward"; |
| 230 | + if (field.selectionStart === from && field.selectionEnd === to && current === direction) return; |
| 231 | + field.setSelectionRange(from, to, direction); |
| 232 | + }); |
| 119 | 233 | }); |
| 120 | 234 | |
| 121 | 235 | // "change" leaves debounced: the state differentiated back into time. |
| @@ -124,27 +238,35 @@ const Tablet = define("pebble-tablet", { shadow: false, styles }, (_, host) => { |
| 124 | 238 | ); |
| 125 | 239 | |
| 126 | 240 | // Mod+S saves. preventDefault stays synchronous, inside the listener's |
| 127 | | − // task — the browser's own Save dialog never opens. |
| 241 | + // task — the browser's own Save dialog never opens. keys() resolves |
| 242 | + // nothing while an IME composition is in progress (its contract), so the |
| 243 | + // chord never steals a composing keystroke. |
| 128 | 244 | subscribe(keys(host, CHORDS))(({ event }) => { |
| 129 | 245 | event.preventDefault(); |
| 130 | 246 | emit(host, "save", { value: doc() }); |
| 131 | 247 | }); |
| 132 | 248 | |
| 249 | + views.set(host, { |
| 250 | + get doc() { |
| 251 | + return model().state.doc; |
| 252 | + }, |
| 253 | + get selection() { |
| 254 | + return model().state.selection; |
| 255 | + }, |
| 256 | + }); |
| 257 | + |
| 133 | 258 | host.setAttribute("data-enhanced", ""); |
| 134 | | − field.hidden = true; |
| 135 | 259 | onCleanup(() => { |
| 136 | 260 | views.delete(host); |
| 137 | | − view.destroy(); |
| 138 | | − field.hidden = false; |
| 139 | 261 | host.removeAttribute("data-enhanced"); |
| 140 | 262 | }); |
| 141 | 263 | |
| 142 | | − return server === null ? <>{field}{surface}</> : surface; |
| 264 | + return server === null ? field : null; |
| 143 | 265 | }); |
| 144 | 266 | |
| 145 | | −/** A <pebble-tablet> element. `editor` is the CodeMirror view (escape hatch). */ |
| 267 | +/** A <pebble-tablet> element. `editor` is the engine's read-only view (escape hatch). */ |
| 146 | 268 | export interface TabletElement extends HTMLElement { |
| 147 | | − readonly editor?: EditorView; |
| 269 | + readonly editor?: TabletEngineView; |
| 148 | 270 | } |
| 149 | 271 | |
| 150 | 272 | // The view as a read-only accessor. Guarded: a second bundle carrying this |