@gjermundgaraba/clankermux 0.0.0-stage → 0.1.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.
@@ -0,0 +1,139 @@
1
+ import { CanvasRenderer } from "../renderer/index.js";
2
+ import { browserKeeps, keyInput } from "./keyboard.js";
3
+ import { profileFrom } from "./profile.js";
4
+ /** Cell metrics from the font. */
5
+ function measure(font) {
6
+ const ctx = document.createElement("canvas").getContext("2d");
7
+ ctx.font = font;
8
+ const m = ctx.measureText("M");
9
+ const size = Number(/(\d+(?:\.\d+)?)px/.exec(font)?.[1] ?? 14);
10
+ const ascent = m.fontBoundingBoxAscent || size * 0.8;
11
+ const descent = m.fontBoundingBoxDescent || size * 0.25;
12
+ return {
13
+ cellWidth: Math.ceil(m.width),
14
+ cellHeight: Math.ceil(ascent + descent),
15
+ baseline: Math.round(ascent),
16
+ font,
17
+ boldFont: `bold ${font}`,
18
+ italicFont: `italic ${font}`,
19
+ boldItalicFont: `bold italic ${font}`,
20
+ };
21
+ }
22
+ export function mountTerminal(options) {
23
+ const { worker, canvas, container, colors } = options;
24
+ const light = matchMedia("(prefers-color-scheme: light)");
25
+ const scheme = options.scheme ?? (() => (light.matches ? "light" : "dark"));
26
+ const metrics = measure(options.font);
27
+ const ctx = canvas.getContext("2d");
28
+ const renderer = new CanvasRenderer(ctx, metrics, { cursor: colors().cursor });
29
+ const dpr = () => window.devicePixelRatio || 1;
30
+ const listening = new AbortController();
31
+ const signal = listening.signal;
32
+ function viewport() {
33
+ const rect = container.getBoundingClientRect();
34
+ return {
35
+ cols: Math.max(1, Math.floor(rect.width / metrics.cellWidth)),
36
+ rows: Math.max(1, Math.floor(rect.height / metrics.cellHeight)),
37
+ cell_width: Math.round(metrics.cellWidth * dpr()),
38
+ cell_height: Math.round(metrics.cellHeight * dpr()),
39
+ };
40
+ }
41
+ /** The canvas backing store for the grid at the current pixel ratio;
42
+ * the next frame is drawn in full after a change. */
43
+ let grid = { cols: 0, rows: 0, dpr: 0 };
44
+ let fullNext = false;
45
+ function fitCanvas(cols, rows) {
46
+ const scale = dpr();
47
+ if (grid.cols === cols && grid.rows === rows && grid.dpr === scale)
48
+ return;
49
+ grid = { cols, rows, dpr: scale };
50
+ canvas.width = cols * metrics.cellWidth * scale;
51
+ canvas.height = rows * metrics.cellHeight * scale;
52
+ canvas.style.width = `${cols * metrics.cellWidth}px`;
53
+ canvas.style.height = `${rows * metrics.cellHeight}px`;
54
+ ctx.setTransform(scale, 0, 0, scale, 0, 0);
55
+ ctx.textBaseline = "alphabetic";
56
+ fullNext = true;
57
+ }
58
+ /** The keyboard layout, when the browser exposes it (Chromium does). */
59
+ const keyboard = { layout: undefined, mac: /Mac|iPhone|iPad/.test(navigator.platform) };
60
+ navigator.keyboard
61
+ ?.getLayoutMap()
62
+ .then((map) => (keyboard.layout = map))
63
+ .catch(() => { });
64
+ const send = (message) => worker.postMessage(message);
65
+ worker.onmessage = (e) => {
66
+ const message = e.data;
67
+ switch (message.type) {
68
+ case "status":
69
+ options.onStatus?.(message.text);
70
+ break;
71
+ case "frame":
72
+ fitCanvas(message.frame.cols, message.frame.rows);
73
+ if (fullNext && !message.frame.full) {
74
+ // The backing store was recreated; a partial frame cannot fill it.
75
+ send({ type: "repaint" });
76
+ }
77
+ else {
78
+ fullNext = false;
79
+ renderer.draw(message.frame);
80
+ }
81
+ break;
82
+ case "sessions":
83
+ options.onSessions?.(message.sessions, message.current);
84
+ break;
85
+ case "clipboard":
86
+ navigator.clipboard?.writeText(message.text).catch(() => { });
87
+ break;
88
+ }
89
+ };
90
+ for (const type of ["keydown", "keyup"]) {
91
+ canvas.addEventListener(type, (e) => {
92
+ if (browserKeeps(e))
93
+ return;
94
+ send({ type: "key", input: keyInput(e, keyboard) });
95
+ e.preventDefault();
96
+ }, { signal });
97
+ }
98
+ canvas.addEventListener("paste", (e) => {
99
+ const text = e.clipboardData?.getData("text");
100
+ if (text)
101
+ send({ type: "paste", text });
102
+ e.preventDefault();
103
+ }, { signal });
104
+ canvas.addEventListener("mousedown", () => canvas.focus(), { signal });
105
+ const report = () => send({ type: "viewport", size: viewport(), profile: profileFrom(colors(), scheme()) });
106
+ const resizes = new ResizeObserver(report);
107
+ resizes.observe(container);
108
+ light.addEventListener("change", report, { signal });
109
+ // Zoom or a move to another screen changes the pixel ratio: the canvas
110
+ // is refitted on the next frame; the cell size in pixels is re-reported.
111
+ const watchRatio = () => {
112
+ matchMedia(`(resolution: ${dpr()}dppx)`).addEventListener("change", () => {
113
+ send({ type: "repaint" });
114
+ report();
115
+ watchRatio();
116
+ }, { once: true, signal });
117
+ };
118
+ watchRatio();
119
+ send({
120
+ type: "init",
121
+ wasm: new URL(options.wasm, location.href).toString(),
122
+ url: options.url,
123
+ viewport: viewport(),
124
+ profile: profileFrom(colors(), scheme()),
125
+ session: options.session,
126
+ });
127
+ return {
128
+ attach: (session) => send({ type: "attach", session }),
129
+ create: () => send({ type: "create" }),
130
+ report,
131
+ paste: (text) => send({ type: "paste", text }),
132
+ dispose: () => {
133
+ listening.abort();
134
+ resizes.disconnect();
135
+ worker.onmessage = null;
136
+ worker.terminate();
137
+ },
138
+ };
139
+ }
@@ -0,0 +1,14 @@
1
+ export interface ClipboardWrite {
2
+ /** The selection parameter: `c` or empty for the clipboard, `p`, `s`, `q` otherwise. */
3
+ selection: string;
4
+ text: string;
5
+ }
6
+ export declare class Osc52Scanner {
7
+ private state;
8
+ private payload;
9
+ /** Forgets a sequence in progress: the stream it came from is gone. */
10
+ reset(): void;
11
+ /** Feeds output bytes; returns the clipboard writes they completed. */
12
+ feed(bytes: Uint8Array): ClipboardWrite[];
13
+ private finish;
14
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Finds OSC 52 clipboard writes in output bytes, across chunk boundaries,
3
+ * ending them as the engine's parser does: BEL or any byte after ESC
4
+ * dispatches the sequence (ESC `\` is the string terminator; ESC `]`
5
+ * begins the next one), CAN and SUB abandon it. The engine raises the
6
+ * clipboard effect through a callback, which from wasm would need a JS
7
+ * function in the module's function table (a generated wrapper per
8
+ * signature); the scan is less machinery. OSC 1337 and 5522 clipboard
9
+ * forms are not scanned for, and an OSC 52 inside another string (a DCS
10
+ * passthrough) is taken as one, where the engine would not.
11
+ */
12
+ const ESC = 0x1b;
13
+ const BEL = 0x07;
14
+ const CAN = 0x18;
15
+ const SUB = 0x1a;
16
+ /** Longer OSC 52 payloads are abandoned, not buffered. */
17
+ const MAX_OSC = 1 << 20;
18
+ const PREFIX = "52;";
19
+ export class Osc52Scanner {
20
+ state = "text";
21
+ payload = [];
22
+ /** Forgets a sequence in progress: the stream it came from is gone. */
23
+ reset() {
24
+ this.state = "text";
25
+ this.payload = [];
26
+ }
27
+ /** Feeds output bytes; returns the clipboard writes they completed. */
28
+ feed(bytes) {
29
+ const writes = [];
30
+ for (const b of bytes) {
31
+ switch (this.state) {
32
+ case "text":
33
+ if (b === ESC)
34
+ this.state = "esc";
35
+ break;
36
+ case "esc":
37
+ // The payload is empty: every way out of an OSC clears it.
38
+ if (b === 0x5d)
39
+ this.state = "osc";
40
+ else
41
+ this.state = b === ESC ? "esc" : "text";
42
+ break;
43
+ case "osc":
44
+ case "skip":
45
+ if (b === BEL) {
46
+ this.finish(writes);
47
+ }
48
+ else if (b === ESC) {
49
+ this.finish(writes);
50
+ this.state = "esc";
51
+ }
52
+ else if (b === CAN || b === SUB) {
53
+ this.reset();
54
+ }
55
+ 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
+ this.state = "skip";
60
+ this.payload = [];
61
+ }
62
+ }
63
+ break;
64
+ }
65
+ }
66
+ return writes;
67
+ }
68
+ finish(writes) {
69
+ const collected = this.state === "osc";
70
+ const payload = new TextDecoder().decode(Uint8Array.from(this.payload));
71
+ this.reset();
72
+ if (!collected)
73
+ return;
74
+ const match = /^52;([^;]*);(.*)$/s.exec(payload);
75
+ if (!match || match[2] === "?")
76
+ return;
77
+ try {
78
+ writes.push({ selection: match[1], text: new TextDecoder().decode(base64(match[2])) });
79
+ }
80
+ catch {
81
+ // Not base64: ignored, as a terminal would.
82
+ }
83
+ }
84
+ }
85
+ function base64(text) {
86
+ const binary = atob(text.replace(/\s+/g, ""));
87
+ return Uint8Array.from(binary, (c) => c.charCodeAt(0));
88
+ }
@@ -0,0 +1,10 @@
1
+ import type { Profile, Scheme } from "../proto/index.ts";
2
+ /** `#rrggbb` from a CSS colour as a custom property holds it (hex, or
3
+ * `rgb()` when the stylesheet writes it that way); undefined otherwise. */
4
+ export declare function hexColor(value: string): string | undefined;
5
+ /** The profile a page with these colours and scheme reports. */
6
+ export declare function profileFrom(colors: {
7
+ fg: string;
8
+ bg: string;
9
+ cursor: string;
10
+ }, scheme: Scheme): Profile;
@@ -0,0 +1,30 @@
1
+ /** `#rrggbb` from a CSS colour as a custom property holds it (hex, or
2
+ * `rgb()` when the stylesheet writes it that way); undefined otherwise. */
3
+ export function hexColor(value) {
4
+ const text = value.trim();
5
+ const hex = /^#([0-9a-f]{6})$/i.exec(text);
6
+ if (hex)
7
+ return `#${hex[1].toLowerCase()}`;
8
+ const short = /^#([0-9a-f]{3})$/i.exec(text);
9
+ if (short)
10
+ return `#${[...short[1]].map((c) => c + c).join("").toLowerCase()}`;
11
+ const rgb = /^rgba?\(\s*(\d+)\s*[, ]\s*(\d+)\s*[, ]\s*(\d+)/.exec(text);
12
+ if (!rgb)
13
+ return undefined;
14
+ const channel = (s) => Math.min(255, Number(s)).toString(16).padStart(2, "0");
15
+ return `#${channel(rgb[1])}${channel(rgb[2])}${channel(rgb[3])}`;
16
+ }
17
+ /** The profile a page with these colours and scheme reports. */
18
+ export function profileFrom(colors, scheme) {
19
+ const profile = { scheme };
20
+ const fg = hexColor(colors.fg);
21
+ const bg = hexColor(colors.bg);
22
+ const cursor = hexColor(colors.cursor);
23
+ if (fg)
24
+ profile.fg = fg;
25
+ if (bg)
26
+ profile.bg = bg;
27
+ if (cursor)
28
+ profile.cursor = cursor;
29
+ return profile;
30
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The engine side of a mounted terminal: the connection, the attachment
3
+ * and the render state live in a worker; the page draws frames and
4
+ * reports input. Imported as `@gjermundgaraba/clankermux/worker`, so a worker
5
+ * typechecked without the DOM library does not see the page's types.
6
+ */
7
+ import { type Frame, type KeyInput } from "../engine/index.ts";
8
+ import { type Profile, type Session, type Size } from "../proto/index.ts";
9
+ /** Messages from the page to the worker. */
10
+ export type ToWorker = {
11
+ type: "init";
12
+ wasm: string;
13
+ url: string;
14
+ viewport: Size;
15
+ profile: Profile;
16
+ session: string | undefined;
17
+ } | {
18
+ type: "attach";
19
+ session: string;
20
+ } | {
21
+ type: "create";
22
+ } | {
23
+ type: "key";
24
+ input: KeyInput;
25
+ } | {
26
+ type: "paste";
27
+ text: string;
28
+ } | {
29
+ type: "viewport";
30
+ size: Size;
31
+ profile: Profile;
32
+ }
33
+ /** The page lost its drawing: send the whole screen again. */
34
+ | {
35
+ type: "repaint";
36
+ };
37
+ /** Messages from the worker to the page. */
38
+ export type ToPage = {
39
+ type: "status";
40
+ text: string;
41
+ } | {
42
+ type: "frame";
43
+ frame: Frame;
44
+ } | {
45
+ type: "sessions";
46
+ sessions: Session[];
47
+ current: string | undefined;
48
+ } | {
49
+ type: "clipboard";
50
+ text: string;
51
+ };
52
+ /** The worker's end of the page's messages: `self` in a dedicated worker. */
53
+ export interface WorkerPort {
54
+ postMessage(message: ToPage): void;
55
+ onmessage: ((e: MessageEvent<ToWorker>) => void) | null;
56
+ }
57
+ /** Serves a page's `mountTerminal` on `port`: the worker module the page
58
+ * starts calls `runWorker(self)`. */
59
+ export declare function runWorker(port: WorkerPort): void;