@gjermundgaraba/clankermux 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +1,8 @@
1
1
  import { CanvasRenderer } from "../renderer/index.js";
2
- import { Typing } from "./keyboard.js";
2
+ import { Copier } from "./copy.js";
3
+ import { Typing, composing } from "./keyboard.js";
4
+ import { Listeners } from "./listeners.js";
3
5
  import { profileFrom, schemeOf } from "./profile.js";
4
- /** Listeners of one kind, and the latest value they were told. */
5
- class Listeners {
6
- all = new Set();
7
- latest;
8
- add(listener) {
9
- this.all.add(listener);
10
- if (this.latest)
11
- listener(this.latest.value);
12
- return () => void this.all.delete(listener);
13
- }
14
- emit(value) {
15
- this.latest = { value };
16
- for (const listener of this.all)
17
- listener(value);
18
- }
19
- clear() {
20
- this.all.clear();
21
- }
22
- }
23
6
  /** Cell metrics from the font. */
24
7
  function measure(font) {
25
8
  const ctx = document.createElement("canvas").getContext("2d");
@@ -38,7 +21,8 @@ function measure(font) {
38
21
  boldItalicFont: `bold italic ${font}`,
39
22
  };
40
23
  }
41
- /** Mounts a terminal as `id` of the client `host` serves. */
24
+ /** Mounts a terminal as `id` of the client `host` serves, and the
25
+ * handler of the worker's messages for it. */
42
26
  export function mountOn(host, id, options) {
43
27
  const { canvas, container, colors } = options;
44
28
  const light = matchMedia("(prefers-color-scheme: light)");
@@ -89,47 +73,53 @@ export function mountOn(host, id, options) {
89
73
  const links = new Listeners();
90
74
  const scrolls = new Listeners();
91
75
  const statuses = new Listeners();
76
+ const copies = new Set();
92
77
  /** The selection's text, for a copy. */
93
78
  let selected;
94
- /** The clipboard write a release started, waiting for the worker to say
95
- * what was selected. */
96
- let copying;
97
- /** Starts the copy of what a release selected. Safari writes to the
98
- * clipboard only within the user's gesture, which is over before the
99
- * worker answers: the write starts here with the text to come, and
100
- * fails, leaving the clipboard alone, when nothing was selected. */
101
- function startCopy() {
102
- copying?.reject();
103
- copying = undefined;
104
- if (typeof ClipboardItem === "undefined" || !navigator.clipboard?.write)
105
- return;
106
- let settle;
107
- const text = new Promise((resolve, reject) => {
108
- settle = {
109
- resolve: (value) => resolve(new Blob([value], { type: "text/plain" })),
110
- reject: () => reject(new Error("nothing selected")),
111
- };
112
- });
113
- // A browser that refuses the write never reads `text`, whose
114
- // rejection would then go unhandled.
115
- text.catch(() => { });
116
- navigator.clipboard.write([new ClipboardItem({ "text/plain": text })]).catch(() => { });
117
- const timer = setTimeout(() => settle.reject(), 2000);
118
- copying = {
119
- resolve: (value) => {
120
- clearTimeout(timer);
121
- settle.resolve(value);
122
- },
123
- reject: () => {
124
- clearTimeout(timer);
125
- settle.reject();
126
- },
127
- };
128
- }
79
+ const copier = new Copier({
80
+ clipboard: () => navigator.clipboard,
81
+ item: typeof ClipboardItem === "undefined" ? undefined : (text) => new ClipboardItem({ "text/plain": text }),
82
+ // Told from a promise's callback: a listener's throw is reported as
83
+ // a listener's throw is elsewhere, and the rest are told.
84
+ report: (copy) => {
85
+ for (const listener of copies) {
86
+ try {
87
+ listener(copy);
88
+ }
89
+ catch (err) {
90
+ queueMicrotask(() => {
91
+ throw err;
92
+ });
93
+ }
94
+ }
95
+ },
96
+ });
129
97
  /** Rows the view is scrolled back, as `onScroll` last reported;
130
98
  * undefined before the first frame. */
131
99
  let scrolled;
132
- host.receive((message) => {
100
+ const visible = () => document.visibilityState === "visible";
101
+ let pendingFrame;
102
+ let paintRequest = 0;
103
+ const paint = () => {
104
+ paintRequest = 0;
105
+ const frame = pendingFrame;
106
+ pendingFrame = undefined;
107
+ if (!frame || disposed)
108
+ return;
109
+ if (visible()) {
110
+ fitCanvas(frame.cols, frame.rows);
111
+ if (fullNext && !frame.full) {
112
+ // The backing store was recreated; a partial frame cannot fill it.
113
+ send({ type: "repaint" });
114
+ }
115
+ else {
116
+ fullNext = false;
117
+ renderer.draw(frame);
118
+ }
119
+ }
120
+ send({ type: "painted" });
121
+ };
122
+ const receive = (message) => {
133
123
  switch (message.type) {
134
124
  case "status":
135
125
  statuses.emit(message.text);
@@ -137,44 +127,35 @@ export function mountOn(host, id, options) {
137
127
  case "link":
138
128
  links.emit(message.link);
139
129
  break;
140
- case "frame": {
141
- if (message.frame.cursor)
142
- cursorAt = { x: message.frame.cursor.x, y: message.frame.cursor.y };
143
- const { total, offset, len } = message.frame.scrollbar;
144
- if (total - offset - len !== scrolled) {
145
- scrolled = total - offset - len;
146
- scrolls.emit(scrolled);
147
- }
148
- fitCanvas(message.frame.cols, message.frame.rows);
149
- if (fullNext && !message.frame.full) {
150
- // The backing store was recreated; a partial frame cannot fill it.
151
- send({ type: "repaint" });
130
+ case "frame":
131
+ if (disposed)
132
+ break;
133
+ if (!visible()) {
134
+ send({ type: "painted" });
152
135
  }
153
136
  else {
154
- fullNext = false;
155
- renderer.draw(message.frame);
137
+ const frame = message.frame;
138
+ if (frame.cursor)
139
+ cursorAt = { x: frame.cursor.x, y: frame.cursor.y };
140
+ const { total, offset, len } = frame.scrollbar;
141
+ if (total - offset - len !== scrolled) {
142
+ scrolled = total - offset - len;
143
+ scrolls.emit(scrolled);
144
+ }
145
+ pendingFrame = frame;
146
+ paintRequest = requestAnimationFrame(paint);
156
147
  }
157
148
  break;
158
- }
159
149
  case "clipboard":
160
- navigator.clipboard?.writeText(message.text).catch(() => { });
150
+ copier.write(message.text, "program");
161
151
  break;
162
- case "selection": {
152
+ case "selection":
163
153
  selected = message.text;
164
- if (!message.copy)
165
- break;
166
- const copy = copying;
167
- copying = undefined;
168
- if (message.text === undefined)
169
- copy?.reject();
170
- else if (copy)
171
- copy.resolve(message.text);
172
- else
173
- navigator.clipboard?.writeText(message.text).catch(() => { });
154
+ if (message.copy !== undefined)
155
+ copier.answer(message.copy, message.text);
174
156
  break;
175
- }
176
157
  }
177
- });
158
+ };
178
159
  /** Where the input element goes for a composition: the cursor's cell,
179
160
  * as the latest frame that had the cursor in view placed it. */
180
161
  let cursorAt = { x: 0, y: 0 };
@@ -255,7 +236,7 @@ export function mountOn(host, id, options) {
255
236
  // Ctrl+Shift+C copies a selection, where Ctrl+C is the terminal's;
256
237
  // without one it is a key.
257
238
  if (e.ctrlKey && e.shiftKey && !e.altKey && !e.metaKey && e.code === "KeyC" && selected) {
258
- navigator.clipboard?.writeText(selected).catch(() => { });
239
+ copier.write(selected, "keys");
259
240
  e.preventDefault();
260
241
  return;
261
242
  }
@@ -264,7 +245,7 @@ export function mountOn(host, id, options) {
264
245
  send({ type: "key", input: key });
265
246
  e.preventDefault();
266
247
  }
267
- else if (e.isComposing || e.key === "Dead" || e.keyCode === 229) {
248
+ else if (composing(e)) {
268
249
  // At the cursor before the input method opens its window; shown
269
250
  // once a composition starts.
270
251
  placeInput(false);
@@ -316,6 +297,7 @@ export function mountOn(host, id, options) {
316
297
  return;
317
298
  e.clipboardData.setData("text/plain", selected);
318
299
  e.preventDefault();
300
+ copier.copied(selected);
319
301
  }, { signal });
320
302
  /** The pointer in cells of the grid, fractions included, kept inside it. */
321
303
  function cellAt(e) {
@@ -352,8 +334,7 @@ export function mountOn(host, id, options) {
352
334
  window.removeEventListener("mousemove", move);
353
335
  window.removeEventListener("mouseup", up);
354
336
  endDrag = undefined;
355
- startCopy();
356
- send({ type: "select", action: "release", at, time });
337
+ send({ type: "select", action: "release", at, time, copy: copier.start() });
357
338
  };
358
339
  const move = (m) => {
359
340
  if ((m.buttons & 1) === 0)
@@ -398,14 +379,25 @@ export function mountOn(host, id, options) {
398
379
  /** Whether the user is looking at this page: it is visible and its
399
380
  * window has the focus. Only then does the session get its size, so
400
381
  * of several clients the one in use sets it. */
401
- const active = () => document.visibilityState === "visible" && document.hasFocus();
382
+ const active = () => visible() && document.hasFocus();
402
383
  const report = () => send({ type: "viewport", size: viewport(), profile: profile(), active: active() });
403
384
  const resizes = new ResizeObserver(report);
404
385
  resizes.observe(container);
405
386
  light.addEventListener("change", report, { signal });
406
387
  // Shown or focused: the session takes this page's size again; hidden or
407
388
  // blurred: the worker stops reporting.
408
- document.addEventListener("visibilitychange", report, { signal });
389
+ document.addEventListener("visibilitychange", () => {
390
+ send({ type: "visibility", visible: visible() });
391
+ if (!visible() && pendingFrame) {
392
+ cancelAnimationFrame(paintRequest);
393
+ paintRequest = 0;
394
+ pendingFrame = undefined;
395
+ // Hidden documents may never get another animation callback. Release
396
+ // the frame after hiding the worker; showing requests a full refresh.
397
+ send({ type: "painted" });
398
+ }
399
+ report();
400
+ }, { signal });
409
401
  window.addEventListener("focus", report, { signal });
410
402
  window.addEventListener("blur", report, { signal });
411
403
  // A page pins its scheme (and its colours with it) with an attribute or
@@ -433,10 +425,11 @@ export function mountOn(host, id, options) {
433
425
  viewport: viewport(),
434
426
  profile: profile(),
435
427
  active: active(),
428
+ visible: visible(),
436
429
  readOnly: options.readOnly ?? false,
437
430
  ackOnFocus: options.ackOnFocus ?? false,
438
431
  });
439
- return {
432
+ const terminal = {
440
433
  attach: (session) => send({ type: "attach", session }),
441
434
  detach: () => send({ type: "detach" }),
442
435
  focus: () => input.focus({ preventScroll: true }),
@@ -454,7 +447,9 @@ export function mountOn(host, id, options) {
454
447
  return;
455
448
  host.send({ type: "unmount", mount: id });
456
449
  disposed = true;
457
- host.receive(undefined);
450
+ cancelAnimationFrame(paintRequest);
451
+ pendingFrame = undefined;
452
+ host.disposed();
458
453
  listening.abort();
459
454
  resizes.disconnect();
460
455
  restyles.disconnect();
@@ -462,9 +457,16 @@ export function mountOn(host, id, options) {
462
457
  links.clear();
463
458
  scrolls.clear();
464
459
  statuses.clear();
460
+ copier.dispose();
461
+ copies.clear();
465
462
  },
466
463
  onLink: (listener) => links.add(listener),
467
464
  onScroll: (listener) => scrolls.add(listener),
468
465
  onStatus: (listener) => statuses.add(listener),
466
+ onCopy: (listener) => {
467
+ copies.add(listener);
468
+ return () => void copies.delete(listener);
469
+ },
469
470
  };
471
+ return { terminal, receive };
470
472
  }
@@ -27,11 +27,14 @@ export class Osc52Scanner {
27
27
  /** Feeds output bytes; returns the clipboard writes they completed. */
28
28
  feed(bytes) {
29
29
  const writes = [];
30
- for (const b of bytes) {
30
+ for (let at = 0; at < bytes.length; at++) {
31
+ const b = bytes[at];
31
32
  switch (this.state) {
32
33
  case "text":
33
- if (b === ESC)
34
- this.state = "esc";
34
+ at = bytes.indexOf(ESC, at);
35
+ if (at < 0)
36
+ return writes;
37
+ this.state = "esc";
35
38
  break;
36
39
  case "esc":
37
40
  // The payload is empty: every way out of an OSC clears it.
@@ -53,12 +56,14 @@ export class Osc52Scanner {
53
56
  this.reset();
54
57
  }
55
58
  else if (this.state === "osc") {
56
- this.payload.push(b);
57
- const head = String.fromCharCode(...this.payload.slice(0, PREFIX.length));
58
- if (!PREFIX.startsWith(head) || this.payload.length > MAX_OSC) {
59
+ const length = this.payload.length;
60
+ if ((length < PREFIX.length && b !== PREFIX.charCodeAt(length)) || length === MAX_OSC) {
59
61
  this.state = "skip";
60
62
  this.payload = [];
61
63
  }
64
+ else {
65
+ this.payload.push(b);
66
+ }
62
67
  }
63
68
  break;
64
69
  }
@@ -5,7 +5,7 @@
5
5
  * Imported as `@gjermundgaraba/clankermux/worker`, so a worker typechecked
6
6
  * without the DOM library does not see the page's types.
7
7
  */
8
- import { type CellPoint, type Frame, type KeyInput } from "../engine/index.ts";
8
+ import { type CellPoint, type PackedFrame, type KeyInput } from "../engine/index.ts";
9
9
  import { type ErrorCode, type ErrorMessage, type Event, type Exit, type Peer, type Profile, type Session, type Size } from "../proto/index.ts";
10
10
  import { type ErrorKind } from "./connection.ts";
11
11
  /** Why the link to the session ended. `closed`: the connection closed
@@ -57,6 +57,8 @@ export interface MountInit {
57
57
  viewport: Size;
58
58
  profile: Profile;
59
59
  active: boolean;
60
+ /** Whether the document is visible, independently of focus. */
61
+ visible: boolean;
60
62
  readOnly: boolean;
61
63
  ackOnFocus: boolean;
62
64
  }
@@ -103,13 +105,21 @@ export type ToWorker = {
103
105
  text: string;
104
106
  }
105
107
  /** The mouse on the canvas, `at` in cells of the viewport, fractions
106
- * included; `time` in ms, for double and triple clicks. */
108
+ * included; `time` in ms, for double and triple clicks. A release has
109
+ * the page's number for its copy, which the answer carries. */
107
110
  | {
108
111
  type: "select";
109
112
  mount: number;
110
- action: "press" | "drag" | "release";
113
+ action: "press" | "drag";
111
114
  at: CellPoint;
112
115
  time: number;
116
+ } | {
117
+ type: "select";
118
+ mount: number;
119
+ action: "release";
120
+ at: CellPoint;
121
+ time: number;
122
+ copy: number;
113
123
  }
114
124
  /** Text as typed, which no key sent: a composition's, the emoji picker's. */
115
125
  | {
@@ -147,6 +157,17 @@ export type ToWorker = {
147
157
  mount: number;
148
158
  focused: boolean;
149
159
  }
160
+ /** Visibility is independent of focus: visible, unfocused pages still paint. */
161
+ | {
162
+ type: "visibility";
163
+ mount: number;
164
+ visible: boolean;
165
+ }
166
+ /** The page painted its one outstanding frame, or discarded it while hidden. */
167
+ | {
168
+ type: "painted";
169
+ mount: number;
170
+ }
150
171
  /** The page lost its drawing: send the whole screen again. */
151
172
  | {
152
173
  type: "repaint";
@@ -198,23 +219,24 @@ export type ToPage =
198
219
  } | {
199
220
  type: "frame";
200
221
  mount: number;
201
- frame: Frame;
222
+ frame: PackedFrame;
202
223
  } | {
203
224
  type: "clipboard";
204
225
  mount: number;
205
226
  text: string;
206
227
  }
207
- /** The selection's text, or undefined once there is none; `copy`: the
208
- * answer to a release, so the text (if any) goes to the clipboard. */
228
+ /** The selection's text, or undefined once there is none; with `copy`,
229
+ * the answer to the release of that number, so the text (if any) goes
230
+ * to the clipboard. Every release is answered. */
209
231
  | {
210
232
  type: "selection";
211
233
  mount: number;
212
234
  text: string | undefined;
213
- copy: boolean;
235
+ copy?: number;
214
236
  };
215
237
  /** The worker's end of the page's messages: `self` in a dedicated worker. */
216
238
  export interface WorkerPort {
217
- postMessage(message: ToPage): void;
239
+ postMessage(message: ToPage, options?: StructuredSerializeOptions): void;
218
240
  onmessage: ((e: MessageEvent<ToWorker>) => void) | null;
219
241
  }
220
242
  /** Serves a page's `connect` on `port`: the worker module the page starts