@gramlot/gramlot 0.3.35 → 0.3.36

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gramlot/gramlot",
3
- "version": "0.3.35",
3
+ "version": "0.3.36",
4
4
  "description": "Declarative HTML/SVG interfaces with live data binding, authored in JavaScript or Python.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -39,6 +39,8 @@
39
39
  "@myriaddreamin/typst-ts-renderer": "0.7.0",
40
40
  "@myriaddreamin/typst-ts-web-compiler": "0.7.0",
41
41
  "@myriaddreamin/typst.ts": "0.7.0",
42
+ "@xterm/addon-fit": "0.11.0",
43
+ "@xterm/xterm": "6.0.0",
42
44
  "codemirror-lang-typst": "0.6.0",
43
45
  "dompurify": "3.4.17",
44
46
  "echarts": "6.1.0",
@@ -3,8 +3,10 @@ import {CodeMirror} from './code-mirror.js';
3
3
  import {HtmlEditor} from './html-editor.js';
4
4
  import {HtmlPreview,MarkdownPreview} from './html-preview.js';
5
5
  import {MarkdownEditor} from './markdown-editor.js';
6
+ import {Terminal} from './terminal.js';
6
7
  export {CodeMirror} from './code-mirror.js';
7
8
  export {HtmlEditor} from './html-editor.js';
8
9
  export {HtmlPreview,MarkdownPreview} from './html-preview.js';
9
10
  export {MarkdownEditor} from './markdown-editor.js';
10
- export default defineCollection({name:'editors', components:[CodeMirror,HtmlEditor,HtmlPreview,MarkdownEditor,MarkdownPreview]});
11
+ export {Terminal} from './terminal.js';
12
+ export default defineCollection({name:'editors', components:[CodeMirror,HtmlEditor,HtmlPreview,MarkdownEditor,MarkdownPreview,Terminal]});
@@ -0,0 +1,158 @@
1
+ import {loadLibrary} from '../libraries.js';
2
+ import {defineComponent} from './registry.js';
3
+ import {projectParameters} from './parameters.js';
4
+
5
+ /**
6
+ * The frames of a terminal session (#87), the same as `gramlot.server.terminal`: one binary WebSocket message,
7
+ * first byte the channel. `INPUT` (0) carries the keys, `OUTPUT` (1) the bytes to write, `RESIZE` (4) the JSON
8
+ * `{"Width": columns, "Height": rows}` of the Kubernetes exec protocol (1 to 65535), `ACK` (5) a 32-bit big-endian count of
9
+ * output bytes the terminal has written. The server stops sending output while 1 MB is unacknowledged.
10
+ */
11
+ export const INPUT = 0, OUTPUT = 1, RESIZE = 4, ACK = 5;
12
+
13
+ function frame(channel, payload) {
14
+ const bytes = new Uint8Array(payload.length + 1);
15
+ bytes[0] = channel; bytes.set(payload, 1);
16
+ return bytes;
17
+ }
18
+
19
+ export function inputFrame(text) { return frame(INPUT, new TextEncoder().encode(text)); }
20
+ export function binaryInputFrame(text) { return frame(INPUT, Uint8Array.from(text, character => character.charCodeAt(0) & 255)); }
21
+ export function resizeFrame(rows, columns) {
22
+ for (const value of [rows, columns]) if (!Number.isInteger(value) || value < 1 || value > 65535) throw new RangeError('A terminal size is 1 to 65535');
23
+ return frame(RESIZE, new TextEncoder().encode(JSON.stringify({Width: columns, Height: rows}))); }
24
+ export function ackFrame(count) {
25
+ if (!Number.isInteger(count) || count < 0 || count > 0xffffffff) throw new RangeError('An acknowledgement counts 0 to 2^32-1 bytes');
26
+ const payload = new Uint8Array(4); new DataView(payload.buffer).setUint32(0, count);
27
+ return frame(ACK, payload);
28
+ }
29
+
30
+ /** The output bytes of a server frame; a frame on another channel is an error. */
31
+ export function outputPayload(data) {
32
+ const bytes = new Uint8Array(data);
33
+ if (bytes.length === 0 || bytes[0] !== OUTPUT) throw new Error(`Unexpected terminal frame on channel ${bytes[0]}`);
34
+ return bytes.subarray(1);
35
+ }
36
+
37
+ let engineModules;
38
+
39
+ /**
40
+ * xterm.js, its fit addon and its style for a terminal of `document`, loaded once on first use. Resolves with
41
+ * `{Terminal, FitAddon, style}`.
42
+ */
43
+ export function loadTerminalEngine(document) {
44
+ return engineModules ??= Promise.all([
45
+ loadLibrary('xterm', document, () => import('@xterm/xterm/lib/xterm.mjs')),
46
+ loadLibrary('xtermFit', document, () => import('@xterm/addon-fit/lib/addon-fit.mjs')),
47
+ loadLibrary('xtermStyle', document, () => import('@xterm/xterm/css/xterm.css')),
48
+ ]).then(([xterm, fit, style]) => ({Terminal: xterm.Terminal, FitAddon: fit.FitAddon, style}));
49
+ }
50
+
51
+ function TerminalElement(HTMLElement) {
52
+ return class extends HTMLElement {
53
+ constructor() {
54
+ super();
55
+ const shadow = this.attachShadow({mode: 'open'});
56
+ this.engineStyle = this.ownerDocument.createElement('style');
57
+ const style = this.ownerDocument.createElement('style');
58
+ style.textContent = `:host{display:block;height:300px;min-height:0;min-width:0}
59
+ .terminal-control{height:100%;min-height:0;padding:4px;background:#000;box-sizing:border-box}
60
+ .terminal-status{padding:1em;color:var(--gramlot-text-secondary,GrayText)}`;
61
+ this.control = this.ownerDocument.createElement('div');
62
+ this.control.className = 'terminal-control';
63
+ shadow.append(this.engineStyle, style, this.control);
64
+ }
65
+ projectAttributes(attrs) { return projectParameters(this, attrs); }
66
+ };
67
+ }
68
+
69
+ export const Terminal = defineComponent({name: 'terminal', tag: 'gramlot-terminal', base: TerminalElement, sourceContext: true,
70
+ doc: 'An interactive terminal connected to the @terminal method `session` of the page store.',
71
+ parameters: {session: {dtype: 'T', default: '', binding: 'read'},
72
+ fontSize: {dtype: 'L', default: 14, binding: 'read'}, fontFamily: {dtype: 'T', default: 'monospace', binding: 'read'},
73
+ connected: {dtype: 'B', default: false, binding: 'write'},
74
+ rows: {dtype: 'L', default: 0, binding: 'write'}, columns: {dtype: 'L', default: 0, binding: 'write'}},
75
+ implementation: Base => class extends Base {
76
+ #context; #generation = 0; #session = null; #socket = null; #terminal = null; #fit = null; #observer = null;
77
+ setSourceContext(context) { this.#context = context; }
78
+ connectedCallback() { this.#start(); }
79
+ disconnectedCallback() { this.#stop(); }
80
+ projectAttributes(attrs) {
81
+ const rest = super.projectAttributes(attrs), p = this.parameters;
82
+ if (typeof p.session !== 'string' || !p.session) throw new TypeError('terminal requires a session name');
83
+ if (!Number.isInteger(p.fontSize) || p.fontSize < 8 || p.fontSize > 48) throw new TypeError('fontSize must be from 8 to 48');
84
+ if (this.#terminal) {
85
+ this.#terminal.options.fontSize = p.fontSize; this.#terminal.options.fontFamily = p.fontFamily;
86
+ this.#fit.fit();
87
+ }
88
+ if (this.isConnected && this.#session !== null && this.#session !== p.session) { this.#stop(); this.#start(); }
89
+ return rest;
90
+ }
91
+ /** Send keys to the session as if typed. */
92
+ input(text) { this.#send(inputFrame(text)); }
93
+ focus() { this.#terminal?.focus(); }
94
+ #write(name, value) { if (this.#context) this.#context.writeParameter(name, value); }
95
+ #send(bytes) { if (this.#socket?.readyState === 1) this.#socket.send(bytes); }
96
+ #start() {
97
+ const generation = ++this.#generation, document = this.ownerDocument;
98
+ this.#session = this.parameters.session;
99
+ this.control.textContent = 'Loading terminal…'; this.control.classList.add('terminal-status');
100
+ this.ready = loadTerminalEngine(document).then(({Terminal, FitAddon, style}) => {
101
+ if (generation !== this.#generation || !this.isConnected) return;
102
+ this.control.textContent = ''; this.control.classList.remove('terminal-status');
103
+ this.engineStyle.textContent = style;
104
+ const p = this.parameters;
105
+ const terminal = this.#terminal = new Terminal({fontSize: p.fontSize, fontFamily: p.fontFamily, convertEol: false});
106
+ const fit = this.#fit = new FitAddon();
107
+ terminal.loadAddon(fit);
108
+ terminal.open(this.control);
109
+ const socket = this.#socket = new document.defaultView.WebSocket(this.#context.terminalUrl(this.#session));
110
+ socket.binaryType = 'arraybuffer';
111
+ terminal.onData(text => this.#send(inputFrame(text)));
112
+ terminal.onBinary(text => this.#send(binaryInputFrame(text)));
113
+ terminal.onResize(({rows, cols}) => {
114
+ this.#send(resizeFrame(rows, cols));
115
+ this.#write('rows', rows); this.#write('columns', cols);
116
+ });
117
+ socket.addEventListener('open', () => {
118
+ if (generation !== this.#generation) return;
119
+ this.#write('connected', true);
120
+ this.#send(resizeFrame(terminal.rows, terminal.cols));
121
+ this.#write('rows', terminal.rows); this.#write('columns', terminal.cols);
122
+ });
123
+ socket.addEventListener('message', event => {
124
+ if (generation !== this.#generation) return;
125
+ let payload;
126
+ try { payload = outputPayload(event.data); }
127
+ catch (error) {
128
+ // A frame the terminal cannot read ends the session, as on the server side.
129
+ socket.close();
130
+ this.#context ? this.#context.reportError(error, 'Terminal') : console.error(error);
131
+ return;
132
+ }
133
+ // The acknowledgement follows xterm's parsing: a slow screen slows the server.
134
+ terminal.write(payload, () => this.#send(ackFrame(payload.length)));
135
+ });
136
+ socket.addEventListener('close', () => {
137
+ if (generation === this.#generation) this.#write('connected', false);
138
+ });
139
+ this.#observer = new document.defaultView.ResizeObserver(() => { if (this.#terminal === terminal) fit.fit(); });
140
+ this.#observer.observe(this);
141
+ fit.fit();
142
+ }).catch(error => {
143
+ if (generation !== this.#generation) return;
144
+ this.control.textContent = `The terminal could not start: ${error.message}`;
145
+ this.control.setAttribute('role', 'alert');
146
+ throw error;
147
+ });
148
+ this.ready.catch(error => this.#context ? this.#context.reportError(error, 'Terminal') : console.error(error));
149
+ }
150
+ #stop() {
151
+ ++this.#generation;
152
+ this.#observer?.disconnect(); this.#observer = null;
153
+ if (this.#socket) { this.#socket.close(1000); this.#socket = null; this.#write('connected', false); }
154
+ this.#terminal?.dispose(); this.#terminal = null; this.#fit = null;
155
+ this.#session = null;
156
+ }
157
+ }
158
+ });
package/src/libraries.js CHANGED
@@ -35,6 +35,15 @@ export const libraries = Object.freeze({
35
35
  uplotStyle: Object.freeze({packages: {uplot: '1.6.32'}, local: 'uplot/dist/uPlot.min.css',
36
36
  url: jsdelivr('uplot', '1.6.32', 'dist/uPlot.min.css'),
37
37
  integrity: 'sha384-IfV0B7MIOYuO95kO9G5ySKPz/85zqFNOAs8iy4tkK5zd9izhJAB8b7lHrwYqqmYE', format: 'style'}),
38
+ xterm: Object.freeze({packages: {'@xterm/xterm': '6.0.0'}, local: '@xterm/xterm/lib/xterm.mjs',
39
+ url: jsdelivr('@xterm/xterm', '6.0.0', 'lib/xterm.mjs'),
40
+ integrity: 'sha384-8Xik+BkzF4UFDtZa8HkUiQ0FE/Xl+03xMuv69uQB3ichDzm8dWs4kPRihQxSZDiY', format: 'module'}),
41
+ xtermFit: Object.freeze({packages: {'@xterm/addon-fit': '0.11.0'}, local: '@xterm/addon-fit/lib/addon-fit.mjs',
42
+ url: jsdelivr('@xterm/addon-fit', '0.11.0', 'lib/addon-fit.mjs'),
43
+ integrity: 'sha384-0/1EW6dUPoaun7dgdlOtb5Wk8x5UQRW6hYM3ihuCCnaA2Xd4HwMFcn378RpxmoAc', format: 'module'}),
44
+ xtermStyle: Object.freeze({packages: {'@xterm/xterm': '6.0.0'}, local: '@xterm/xterm/css/xterm.css',
45
+ url: jsdelivr('@xterm/xterm', '6.0.0', 'css/xterm.css'),
46
+ integrity: 'sha384-n2n7twoohnW+d3myBKaUgl7DSiwidw6MkQy9oesGzkPpMjejKRR3XlnD+5yCdtBD', format: 'style'}),
38
47
  plotly: Object.freeze({packages: {'plotly.js-dist-min': '4.2.0'}, local: 'plotly.js-dist-min',
39
48
  url: null, integrity: null, format: 'module'}),
40
49
  vega: Object.freeze({packages: {vega: '6.4.0'}, local: 'vega', url: null, integrity: null, format: 'module'}),
@@ -37,6 +37,14 @@ export class PageStoreConnection {
37
37
  if (!this.parent) this.open();
38
38
  }
39
39
 
40
+ /** The address of the terminal socket of `session` for this page: `terminal` beside the store route. */
41
+ terminalUrl(session) {
42
+ const address = new URL('terminal', this.endpoint);
43
+ address.searchParams.set('pageId', this.gramlot.pageId);
44
+ address.searchParams.set('session', session);
45
+ return address.href;
46
+ }
47
+
40
48
  /** Opens this page's own WebSocket: the page is the root of its family channel. */
41
49
  open() {
42
50
  const address = this.address;
package/src/view/html.js CHANGED
@@ -133,6 +133,11 @@ export class HtmlElement {
133
133
  collectionView: (bag, rowMode) => node.rootBuilder.binding.collectionView(node, bag, rowMode),
134
134
  format: this.format,
135
135
  upload: () => this.uploadContext(),
136
+ terminalUrl: session => {
137
+ const store = node.rootBuilder.binding.gramlot._pageStore;
138
+ if (!store) throw new Error('A terminal requires a server with a PageStore channel (websocket)');
139
+ return store.terminalUrl(session);
140
+ },
136
141
  reportError: (error, title) => this.reportError(node, error, title),
137
142
  publish: (topic, payload) => node.publish(topic, payload),
138
143
  writeParameter: (name, value) => this.writeParameter(node, name, value),