@gramlot/gramlot 0.3.20 → 0.3.24
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/dist/components/chat/__init__.py +13 -0
- package/dist/components/chat/assets/collection.js +9 -0
- package/dist/components/chat/assets/index.js +3 -0
- package/dist/components/chat/commands.json +7 -0
- package/dist/components/chat/grammar.json +48 -0
- package/dist/components/editors/__init__.py +2 -2
- package/dist/components/editors/assets/collection.js +22 -120909
- package/dist/components/editors/assets/index.js +2 -1
- package/dist/components/editors/assets/modules/chunk-AU4HFPIY.js +1 -0
- package/dist/components/editors/assets/modules/chunk-MMJXUHRQ.js +3 -0
- package/dist/components/editors/assets/modules/chunk-OCFLP2K4.js +16 -0
- package/dist/components/editors/assets/modules/chunk-YSGSC7KM.js +1 -0
- package/dist/components/editors/assets/modules/code-mirror-engine-QX4A5FVO.js +92 -0
- package/dist/components/editors/assets/modules/jodit-engine-MMSPIWM7.js +1853 -0
- package/dist/components/editors/assets/modules/prose-mirror-engine-IXTRTG6B.js +24 -0
- package/dist/components/grid/__init__.py +13 -0
- package/dist/components/grid/assets/collection.js +211 -0
- package/dist/components/grid/assets/index.js +3 -0
- package/dist/components/grid/commands.json +7 -0
- package/dist/components/grid/grammar.json +714 -0
- package/dist/components/grouplets/__init__.py +13 -0
- package/dist/components/grouplets/assets/collection.js +202 -0
- package/dist/components/grouplets/assets/index.js +3 -0
- package/dist/components/grouplets/commands.json +7 -0
- package/dist/components/grouplets/grammar.json +355 -0
- package/dist/components/inputs/__init__.py +1 -1
- package/dist/components/inputs/assets/collection.js +32 -24503
- package/dist/components/inputs/assets/index.js +2 -1
- package/dist/components/inputs/grammar.json +214 -6
- package/dist/components/layout/__init__.py +1 -1
- package/dist/components/layout/assets/collection.js +27 -26701
- package/dist/components/layout/assets/index.js +2 -1
- package/dist/components/layout/grammar.json +4 -0
- package/dist/components/selection_trial/__init__.py +13 -0
- package/dist/components/selection_trial/assets/collection.js +4 -0
- package/dist/components/selection_trial/assets/index.js +3 -0
- package/dist/components/selection_trial/commands.json +7 -0
- package/dist/components/selection_trial/grammar.json +552 -0
- package/dist/components/tree/__init__.py +1 -1
- package/dist/components/tree/assets/collection.js +24 -24612
- package/dist/components/tree/assets/index.js +2 -1
- package/dist/components/typst/__init__.py +2 -2
- package/dist/components/typst/assets/collection.js +12 -4
- package/dist/components/typst/assets/index.js +2 -1
- package/dist/components/typst/assets/modules/chunk-BLMUM44K.js +1 -0
- package/dist/components/typst/assets/modules/typst-client-JHC6UVYG.js +4 -0
- package/dist/gramlot.js +2749 -1627
- package/dist/gramlot.min.js +46 -41
- package/package.json +7 -2
- package/src/binding/grid-struct.js +63 -0
- package/src/binding/installation.js +5 -2
- package/src/binding/runtime.js +51 -6
- package/src/builder/gramlot-builder.d.ts +5 -0
- package/src/builder/gramlot-builder.js +16 -0
- package/src/builder/source.js +23 -0
- package/src/chat.d.ts +12 -0
- package/src/chat.js +198 -0
- package/src/collection-artifact.js +1 -1
- package/src/components/bases.js +2 -0
- package/src/components/chat.js +28 -0
- package/src/components/choice-editor.js +89 -34
- package/src/components/database-choices.js +131 -9
- package/src/components/field-state.js +10 -1
- package/src/components/grid-grammar.json +237 -0
- package/src/components/grid-header-interaction.js +196 -0
- package/src/components/grid-row-interaction.js +184 -0
- package/src/components/grid-row-layout.js +96 -0
- package/src/components/grid-rows.js +28 -0
- package/src/components/grid-search-box.js +142 -0
- package/src/components/grid-search-styles.js +42 -0
- package/src/components/grid-search.js +37 -0
- package/src/components/grid-structure.js +84 -0
- package/src/components/grid-styles.js +151 -0
- package/src/components/grid.js +589 -0
- package/src/components/grouplet-card.js +437 -0
- package/src/components/grouplets.js +17 -0
- package/src/components/menus.js +1 -0
- package/src/components/registry.js +4 -3
- package/src/components/tray-pane.js +32 -4
- package/src/components/typed-editor.js +4 -2
- package/src/experiments/selection-transfer.js +78 -0
- package/src/experiments/selection-trial.js +48 -0
- package/src/experiments/window-selection.js +124 -0
- package/src/form-state.d.ts +20 -0
- package/src/form-state.js +198 -0
- package/src/index-page-styles.js +1 -1
- package/src/index.d.ts +3 -1
- package/src/index.js +3 -1
- package/src/renderer/gramlot-renderer.js +8 -1
- package/src/server/gramlot-server.d.ts +2 -0
- package/src/server/gramlot-server.js +13 -1
- package/src/stores/bag-collection-store.js +51 -0
- package/src/stores/bag-collection-view.js +127 -0
- package/src/stores/collection-filter.js +77 -0
- package/src/view/controls.js +33 -1
- package/src/view/grouplet-card.js +54 -0
- package/src/view/html.js +20 -3
- package/src/view/labelbox.js +7 -3
- package/themes/gramlot-base/theme.css +28 -0
- package/themes/gramlot-compact/theme.css +8 -0
- package/themes/joanna/theme.css +8 -0
- package/themes/mimi/theme.css +8 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gramlot/gramlot",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.24",
|
|
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": {
|
|
@@ -71,11 +71,16 @@
|
|
|
71
71
|
"./components": "./src/components/index.js",
|
|
72
72
|
"./components/inputs": "./src/components/inputs.js",
|
|
73
73
|
"./components/layout": "./src/components/layout.js",
|
|
74
|
+
"./components/grid": "./src/components/grid.js",
|
|
74
75
|
"./components/tree": "./src/components/tree.js",
|
|
75
76
|
"./components/editors": "./src/components/editors.js",
|
|
76
77
|
"./components/typst": "./src/components/typst.js",
|
|
78
|
+
"./components/grouplets": "./src/components/grouplets.js",
|
|
77
79
|
"./device-frames": "./src/device-frames.js",
|
|
78
|
-
"./mobile-environment": "./src/mobile-environment.js"
|
|
80
|
+
"./mobile-environment": "./src/mobile-environment.js",
|
|
81
|
+
"./chat": "./src/chat.js",
|
|
82
|
+
"./components/chat": "./src/components/chat.js",
|
|
83
|
+
"./components/selection_trial": "./src/experiments/selection-trial.js"
|
|
79
84
|
},
|
|
80
85
|
"files": [
|
|
81
86
|
"LICENSE",
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import {Bag} from '@genrojs/bag';
|
|
2
|
+
import {SourceBag} from '@genrojs/builders';
|
|
3
|
+
import {GridStructure} from '../components/grid-structure.js';
|
|
4
|
+
|
|
5
|
+
/** Convert declarative Source into the one ordinary-Data structure schema. */
|
|
6
|
+
function structureData(source) {
|
|
7
|
+
const data = new Bag(), cells = new Bag(), groups = new Bag();
|
|
8
|
+
data.setItem('view_0', new Bag(), {tag:'view'});
|
|
9
|
+
data.getItem('view_0').setItem('rows_0', cells, {tag:'rows'});
|
|
10
|
+
data.setItem('info', new Bag());
|
|
11
|
+
data.getItem('info').setItem('columnsets', groups);
|
|
12
|
+
const addColumn = (node, group = null) => {
|
|
13
|
+
node.builder.validateNode(node);
|
|
14
|
+
if (node.nodeTag !== 'column' || node.staticValue != null) throw new TypeError('grid column must be a scalar declaration');
|
|
15
|
+
const attrs = {tag:'cell'};
|
|
16
|
+
for (const key of ['field', 'name', 'dtype', 'width', 'align', 'format', 'white_space']) {
|
|
17
|
+
if (node.getAttr(key) != null) attrs[key] = node.getAttr(key);
|
|
18
|
+
}
|
|
19
|
+
const label = `cell_${attrs.field}`;
|
|
20
|
+
if (cells.getNode(label)) throw new TypeError(`Duplicate grid field: ${attrs.field}`);
|
|
21
|
+
if (group !== null) attrs.columnset = group;
|
|
22
|
+
cells.setItem(label, null, attrs);
|
|
23
|
+
};
|
|
24
|
+
for (const node of source.getNodes()) {
|
|
25
|
+
if (node.nodeTag === 'column') addColumn(node);
|
|
26
|
+
else if (node.nodeTag === 'colgroup') {
|
|
27
|
+
node.builder.validateNode(node);
|
|
28
|
+
if (!(node.staticValue instanceof SourceBag)) throw new TypeError('grid colgroup requires column declarations');
|
|
29
|
+
const code = node.getAttr('code');
|
|
30
|
+
if (groups.getNode(code)) throw new TypeError(`Duplicate grid colgroup: ${code}`);
|
|
31
|
+
const attrs = {tag:'columnset', code, name:node.getAttr('name') ?? code};
|
|
32
|
+
for (const key of ['background','color']) if (node.getAttr(key) != null) attrs[key] = node.getAttr(key);
|
|
33
|
+
groups.setItem(code, null, attrs);
|
|
34
|
+
for (const column of node.staticValue.getNodes()) addColumn(column, code);
|
|
35
|
+
} else throw new TypeError('grid struct accepts column and colgroup only');
|
|
36
|
+
}
|
|
37
|
+
return data;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Validate before DataInstaller writes any setters in the incoming branch. */
|
|
41
|
+
export function validateGridDeclaration(node) {
|
|
42
|
+
if (node._getMeta('gramlot_component')?.bagStruct) {
|
|
43
|
+
const children = node.staticValue instanceof SourceBag ? node.staticValue.getNodes() : [];
|
|
44
|
+
if (children.some(child => !child._getMeta('gridStruct')) || children.length > 1) throw new TypeError('grid accepts one struct declaration');
|
|
45
|
+
if (children.length && node.getAttr('structpath') != null) throw new TypeError('grid requires structpath or nested struct, not both');
|
|
46
|
+
if (!children.length && !node.getAttr('structpath')) throw new TypeError('grid requires structpath or nested struct');
|
|
47
|
+
if (!['values', 'attributes'].includes(node.getAttr('rowMode'))) throw new TypeError('grid rowMode must explicitly be values or attributes');
|
|
48
|
+
}
|
|
49
|
+
if (!node._getMeta('gridStruct')) return;
|
|
50
|
+
if (!node.parentNode?._getMeta('gramlot_component')?.bagStruct) throw new TypeError('struct requires a grid parent');
|
|
51
|
+
if (!(node.staticValue instanceof SourceBag)) throw new TypeError('grid struct requires column declarations');
|
|
52
|
+
new GridStructure(structureData(node.staticValue));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** DataInstaller consumes this declaration after its one ordinary Data write. */
|
|
56
|
+
export function installGridStruct(node, data) {
|
|
57
|
+
const value = structureData(node.staticValue);
|
|
58
|
+
new GridStructure(value);
|
|
59
|
+
const path = `gramlot.grid.${crypto.randomUUID().replaceAll('-', '')}.struct`;
|
|
60
|
+
data.setItem(path, value, null, '>', false, true, node);
|
|
61
|
+
node.parentNode.setAttr({structpath: path}, false);
|
|
62
|
+
node.setValue(null, false);
|
|
63
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {validateGridDeclaration, installGridStruct} from './grid-struct.js';
|
|
1
2
|
import {Bag} from '@genrojs/bag';
|
|
2
3
|
import {META_ATTRS, SourceBag} from '@genrojs/builders';
|
|
3
4
|
import {isExpression, withoutBindingAttributes} from '../renderer/attributes.js';
|
|
@@ -35,7 +36,8 @@ export class DataInstaller {
|
|
|
35
36
|
const setters = this.setterNodes(branch);
|
|
36
37
|
requireInstallable(branch);
|
|
37
38
|
for (const node of setters) {
|
|
38
|
-
|
|
39
|
+
if (node._getMeta('gridStruct')) installGridStruct(node, this.runtime.data);
|
|
40
|
+
else this.applySetter(node);
|
|
39
41
|
this.runtime.closeBranch(node);
|
|
40
42
|
if (node.parentBag) node.parentBag.popNode(node.label);
|
|
41
43
|
}
|
|
@@ -44,7 +46,7 @@ export class DataInstaller {
|
|
|
44
46
|
|
|
45
47
|
/** The `dataSetter` nodes of `branch`, in document order, parent before children. */
|
|
46
48
|
setterNodes(branch) {
|
|
47
|
-
return branchNodes(branch).filter(node => node.nodeTag === 'dataSetter');
|
|
49
|
+
return branchNodes(branch).filter(node => node.nodeTag === 'dataSetter' || node._getMeta('gridStruct'));
|
|
48
50
|
}
|
|
49
51
|
|
|
50
52
|
/**
|
|
@@ -166,6 +168,7 @@ function requireGramlotSetter(node) {
|
|
|
166
168
|
*/
|
|
167
169
|
export function requireInstallable(branch) {
|
|
168
170
|
for (const node of branchNodes(branch)) {
|
|
171
|
+
validateGridDeclaration(node);
|
|
169
172
|
if (node.nodeTag === 'dataSetter') requireGramlotSetter(node);
|
|
170
173
|
requireProviderAttributes(node);
|
|
171
174
|
}
|
package/src/binding/runtime.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {Bag} from '@genrojs/bag';
|
|
2
|
+
import {BagCollectionView} from '../stores/bag-collection-view.js';
|
|
3
|
+
import {BagCollectionStore} from '../stores/bag-collection-store.js';
|
|
1
4
|
import {SourceBag} from '@genrojs/builders';
|
|
2
5
|
import {DataRouter} from './router.js';
|
|
3
6
|
import {DataInstaller} from './installation.js';
|
|
@@ -42,6 +45,7 @@ export class BindingRuntime {
|
|
|
42
45
|
#subscriptions;
|
|
43
46
|
#subscription = `gramlot-data-${randomId()}`;
|
|
44
47
|
#disposed = false;
|
|
48
|
+
#collectionStores = new WeakMap();
|
|
45
49
|
|
|
46
50
|
constructor(gramlot, {subscriptions}) {
|
|
47
51
|
this.#gramlot = gramlot;
|
|
@@ -76,6 +80,26 @@ export class BindingRuntime {
|
|
|
76
80
|
/** `nodeId → node` of the Source nodes with an open NodeBinding (R06). */
|
|
77
81
|
get nodeIds() { return this.#nodeIds; }
|
|
78
82
|
|
|
83
|
+
/** One shared resident data resource per Bag; presentation state belongs to views. */
|
|
84
|
+
collectionStore(bag, rowMode) {
|
|
85
|
+
if (this.disposed) throw new Error('BindingRuntime is disposed');
|
|
86
|
+
let store = this.#collectionStores.get(bag);
|
|
87
|
+
if (!store) {
|
|
88
|
+
store = new BagCollectionStore(bag, rowMode);
|
|
89
|
+
this.#collectionStores.set(bag, store);
|
|
90
|
+
} else if (store.rowMode !== rowMode) throw new TypeError('A shared collection store requires one rowMode');
|
|
91
|
+
return store;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Each grid Source owns one view; only the underlying Bag access is shared. */
|
|
95
|
+
collectionView(node, bag, rowMode) {
|
|
96
|
+
const store = this.collectionStore(bag,rowMode);
|
|
97
|
+
if (!Object.hasOwn(node,'gridCollectionView')) {
|
|
98
|
+
Object.defineProperty(node,'gridCollectionView',{value:new BagCollectionView(store),configurable:true});
|
|
99
|
+
} else node.gridCollectionView.bindStore(store);
|
|
100
|
+
return node.gridCollectionView;
|
|
101
|
+
}
|
|
102
|
+
|
|
79
103
|
/** Subscribe once on Builder's Data wrapper; nothing is created. */
|
|
80
104
|
attach() {
|
|
81
105
|
this.root.subscribe(this.#subscription, {any: event => this.receiveData(event)});
|
|
@@ -83,6 +107,16 @@ export class BindingRuntime {
|
|
|
83
107
|
|
|
84
108
|
/** Callback of the one Data subscription. */
|
|
85
109
|
receiveData(event) {
|
|
110
|
+
// Visit resident stores along the affected Data path before their consumers.
|
|
111
|
+
// Static values avoid invoking resolvers; deletion paths still reach the containing Bag.
|
|
112
|
+
let bag = this.root;
|
|
113
|
+
for (const [index, segment] of (event.pathlist ?? []).entries()) {
|
|
114
|
+
const value = bag.node(segment)?.staticValue;
|
|
115
|
+
if (!(value instanceof Bag)) break;
|
|
116
|
+
const store = this.#collectionStores.get(value);
|
|
117
|
+
store?.receiveData(event, index + 1 < event.pathlist.length ? value.node(event.pathlist[index + 1]) : null);
|
|
118
|
+
bag = value;
|
|
119
|
+
}
|
|
86
120
|
this.router.deliver(event);
|
|
87
121
|
}
|
|
88
122
|
|
|
@@ -212,6 +246,7 @@ export class BindingRuntime {
|
|
|
212
246
|
this.#disposed = true;
|
|
213
247
|
this.root.unsubscribe(this.#subscription, {any: true});
|
|
214
248
|
this.nodeIds.clear();
|
|
249
|
+
this.#collectionStores = new WeakMap();
|
|
215
250
|
const errors = [];
|
|
216
251
|
for (const [node, binding] of [...this.#bindings.entries()].reverse()) {
|
|
217
252
|
this.#bindings.delete(node);
|
|
@@ -368,6 +403,7 @@ export class NodeBinding {
|
|
|
368
403
|
#clickCount = 0;
|
|
369
404
|
// The registration of the node's own variable datapath, read in the parent's context.
|
|
370
405
|
#datapathRegistrations = new Set();
|
|
406
|
+
#storeRegistration = null;
|
|
371
407
|
|
|
372
408
|
constructor(runtime, node) {
|
|
373
409
|
this.#runtime = runtime;
|
|
@@ -425,13 +461,19 @@ export class NodeBinding {
|
|
|
425
461
|
this.#remote = null;
|
|
426
462
|
}
|
|
427
463
|
const remoteDependencies = new Set();
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
if (
|
|
431
|
-
|
|
464
|
+
const component = node._getMeta('gramlot_component');
|
|
465
|
+
for (const [capability, attribute] of [['bagStore', 'storepath'], ['bagStruct', 'structpath']]) {
|
|
466
|
+
if (!component?.[capability]) continue;
|
|
467
|
+
const value = node.getAttr(attribute);
|
|
468
|
+
if (typeof value !== 'string' || !value || /^[\^=]/.test(value) || value.includes('?')) {
|
|
469
|
+
throw new TypeError(`${attribute} requires a plain Bag data path`);
|
|
432
470
|
}
|
|
433
|
-
const path = node.absDatapath(
|
|
434
|
-
this
|
|
471
|
+
const path = node.absDatapath(value);
|
|
472
|
+
const registration = this.runtime.router.register({path, recipient: this, subtree: true});
|
|
473
|
+
this.#registrations.push(registration);
|
|
474
|
+
// Grid receives store invalidations separately. Other Bag consumers
|
|
475
|
+
// (such as tree) continue to receive every ordinary Data event.
|
|
476
|
+
if (capability === 'bagStore' && component.bagStruct) this.#storeRegistration = registration;
|
|
435
477
|
}
|
|
436
478
|
const timingDependencies = this.remote ? pointerDependencies(node, node.getAttr('_timing')) : new Set();
|
|
437
479
|
if (this.remote) for (const [name, raw] of Object.entries(node.getAttr())) {
|
|
@@ -492,6 +534,8 @@ export class NodeBinding {
|
|
|
492
534
|
* registration of its `_timing` restarted the timer.
|
|
493
535
|
*/
|
|
494
536
|
receive(change) {
|
|
537
|
+
if (change.registration === this.#storeRegistration &&
|
|
538
|
+
(change.level === 'child' || change.evt === 'upd_attrs')) return;
|
|
495
539
|
if (this.#datapathRegistrations.has(change.registration)) {
|
|
496
540
|
this.runtime.rebindBranch(this.node);
|
|
497
541
|
return;
|
|
@@ -557,6 +601,7 @@ export class NodeBinding {
|
|
|
557
601
|
#closeRegistrations() {
|
|
558
602
|
this.#binder?.unregister();
|
|
559
603
|
for (const registration of this.#registrations.splice(0)) registration.close();
|
|
604
|
+
this.#storeRegistration = null;
|
|
560
605
|
this.#datapathRegistrations.clear();
|
|
561
606
|
this.#remoteRegistrations.clear();
|
|
562
607
|
this.#remoteTimingRegistrations.clear();
|
|
@@ -13,6 +13,11 @@ import type {NameSyntax} from './name-syntax.js';
|
|
|
13
13
|
export class GramlotBuilder extends HtmlBuilder {
|
|
14
14
|
/** The dialect name, `'gramlot'`. */
|
|
15
15
|
static _name: string;
|
|
16
|
+
static containers: string[];
|
|
17
|
+
/** Build an ordinary framePane containing center.grid; requires layout and grid. */
|
|
18
|
+
frameGrid(parent: SourceBag | SourceBagNode, options: SourceAttributes & {
|
|
19
|
+
storepath: string; rowMode: 'values' | 'attributes'; structpath?: string; searchOn?: boolean | string;
|
|
20
|
+
}): SourceBagNode;
|
|
16
21
|
/** Tag prefixes of the parent dialects, from the names of the classes above `GramlotBuilder`. */
|
|
17
22
|
static get dialectPrefixes(): string[];
|
|
18
23
|
/** Create a builder; `collections` are grammar documents loaded into it; `auth` evaluates the `auth` rules of the elements when the Source is serialised; `nameSyntax` checks the method names of `remote` (default `NAME_SYNTAX`). */
|
|
@@ -72,12 +72,28 @@ function excludedAttribute(attrs) {
|
|
|
72
72
|
/** Gramlot vocabulary and inert authoring on the shared builder grammar. */
|
|
73
73
|
export class GramlotBuilder extends HtmlBuilder {
|
|
74
74
|
static _name = 'gramlot';
|
|
75
|
+
static containers = ['frameGrid'];
|
|
75
76
|
static _sourceClass = GramlotBuilderBag;
|
|
76
77
|
// Composed on the inherited HtmlBuilder grammar; its data-elements replace Builder's.
|
|
77
78
|
static { this.defineGrammar(BINDING); }
|
|
78
79
|
static { this.defineGrammar(WEBCOMPONENT); }
|
|
79
80
|
static { this.defineGrammar(buttons.toDocument()); }
|
|
80
81
|
|
|
82
|
+
/** Compose real Source nodes; frame/grid/menu retain their existing runtime owners. */
|
|
83
|
+
frameGrid(parent, {storepath, rowMode, structpath, searchOn = false, ...attrs} = {}) {
|
|
84
|
+
for (const tag of ['framePane', 'grid']) {
|
|
85
|
+
if (!this.schemaTag(tag)) throw new TypeError(`frameGrid requires the ${tag} collection`);
|
|
86
|
+
}
|
|
87
|
+
const gridAttrs = {storepath, rowMode, ...(structpath == null ? {} : {structpath}),
|
|
88
|
+
node_label: 'grid', frameTarget: true, height: '100%', width: '100%'};
|
|
89
|
+
this.validateNodeValues('grid', null, gridAttrs);
|
|
90
|
+
if (searchOn !== false) this.validateNodeValues('searchBox', null, {searchOn});
|
|
91
|
+
const frame = parent.framePane(attrs);
|
|
92
|
+
frame.center.grid(gridAttrs);
|
|
93
|
+
if (searchOn !== false) frame.top.menu({presentation:'bar', node_label:'search', aria_label:'Grid search', padding:'4px 8px', background:'var(--gramlot-surface-subtle)'}).menuline({group:true}).searchBox({searchOn});
|
|
94
|
+
return frame;
|
|
95
|
+
}
|
|
96
|
+
|
|
81
97
|
/** Tag prefixes of the parent dialects, from the `_name` of the classes above GramlotBuilder. */
|
|
82
98
|
static get dialectPrefixes() {
|
|
83
99
|
const prefixes = [];
|
package/src/builder/source.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {FormState} from '../form-state.js';
|
|
1
2
|
import {BagCbResolver} from '@genrojs/bag';
|
|
2
3
|
import {SourceBag, SourceBagNode, sourceAttributeItems, wrapSource} from '@genrojs/builders';
|
|
3
4
|
import {fromTytx, getSubtypeDict, setSubtypeDict, toTytx} from '@genrojs/tytx';
|
|
@@ -177,6 +178,19 @@ function isExpression(value) {
|
|
|
177
178
|
* setRelativeData too, with the Gramlot reset rules.
|
|
178
179
|
*/
|
|
179
180
|
export class GramlotBuilderBagNode extends SourceBagNode {
|
|
181
|
+
#formState = null;
|
|
182
|
+
/** The local form lifecycle owned by the nearest marked Source ancestor. */
|
|
183
|
+
get formState() {
|
|
184
|
+
for (let owner = this; owner; owner = owner.parentNode) {
|
|
185
|
+
if (owner.getAttr('formId') != null || owner.getAttr('form') === true) {
|
|
186
|
+
const state = owner.#formState ??= new FormState(owner, this.rootBuilder.binding);
|
|
187
|
+
state.rebind();
|
|
188
|
+
return state;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
|
|
180
194
|
get frame() {
|
|
181
195
|
if (!['dialog','floatingPane'].includes(this.nodeTag)) throw new TypeError('frame accessor requires a window');
|
|
182
196
|
const children = this.value instanceof SourceBag ? this.value.getNodes() : [];
|
|
@@ -190,6 +204,15 @@ export class GramlotBuilderBagNode extends SourceBagNode {
|
|
|
190
204
|
if (!['dialog','floatingPane'].includes(this.nodeTag)) throw new TypeError('requestClose requires a window');
|
|
191
205
|
return this.rootBuilder.binding.gramlot.dom.getDomNode(this).requestClose(reason);
|
|
192
206
|
}
|
|
207
|
+
/** frameGrid returns an ordinary frame; its grid remains an ordinary Source node. */
|
|
208
|
+
get grid() {
|
|
209
|
+
if (this.nodeTag === 'framePane') {
|
|
210
|
+
const grid = this.staticValue instanceof SourceBag ? this.staticValue.getNode('center.grid') : null;
|
|
211
|
+
if (!grid || grid.nodeTag !== 'grid') throw new TypeError('This frame has no central grid');
|
|
212
|
+
return this.builder.wrapSource(grid);
|
|
213
|
+
}
|
|
214
|
+
return (attrs = {}) => this.builder.wrapSource(this.builder.commandOnNode(this, 'grid', null, attrs));
|
|
215
|
+
}
|
|
193
216
|
get top() { return this.frameRegion('top'); }
|
|
194
217
|
get bottom() { return this.frameRegion('bottom'); }
|
|
195
218
|
get left() { return this.frameRegion('left'); }
|
package/src/chat.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type {Gramlot} from './gramlot.js';
|
|
2
|
+
import type {SourceBagNode} from '@genrojs/builders';
|
|
3
|
+
import type {Bag} from '@genrojs/bag';
|
|
4
|
+
export function chatRender(page: Gramlot, node: SourceBagNode, params: {messages: Bag}): void;
|
|
5
|
+
export function chatSend(page: Gramlot, node: SourceBagNode): void;
|
|
6
|
+
export function chatReset(page: Gramlot, node: SourceBagNode): void;
|
|
7
|
+
export function chatCompleted(page: Gramlot, node: SourceBagNode, params: {response: Bag | null}): void;
|
|
8
|
+
|
|
9
|
+
export function chatResize(page: Gramlot, node: SourceBagNode): void;
|
|
10
|
+
export function chatPickAttachments(page: Gramlot, node: SourceBagNode): Promise<void>;
|
|
11
|
+
export function chatRemoveAttachment(page: Gramlot, node: SourceBagNode): void;
|
|
12
|
+
export function chatRenderAttachments(page: Gramlot, node: SourceBagNode, params: {attachments: Bag}): void;
|
package/src/chat.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/** Shared chat behavior. Pages delegate their named Logic methods here. */
|
|
2
|
+
import {Bag} from '@genrojs/bag';
|
|
3
|
+
import {SourceBag, sourceTarget} from '@genrojs/builders';
|
|
4
|
+
import {GramlotBuilderBag} from './builder/source.js';
|
|
5
|
+
import {GramlotBuilder} from './builder/gramlot-builder.js';
|
|
6
|
+
import {fromTytx, toTytx} from '@genrojs/tytx';
|
|
7
|
+
import {randomId} from './random-id.js';
|
|
8
|
+
|
|
9
|
+
const projections = new WeakMap();
|
|
10
|
+
const LABEL = /^m_[a-f0-9]+$/;
|
|
11
|
+
|
|
12
|
+
/** Reconcile message Source, preserving older fragments and their interactive Data. */
|
|
13
|
+
export function chatRender(page, node, {messages}) {
|
|
14
|
+
if (!(messages instanceof Bag) || messages instanceof SourceBag) throw new TypeError('Chat messages require a Data Bag');
|
|
15
|
+
const target = node.parentNode;
|
|
16
|
+
const viewport = page.dom.getDomNode(target);
|
|
17
|
+
if (!viewport) return;
|
|
18
|
+
let state = projections.get(target);
|
|
19
|
+
if (!state) {
|
|
20
|
+
state = {rows:new Map(), active:true}; projections.set(target,state);
|
|
21
|
+
page.src.renderer.onDispose(target, () => {
|
|
22
|
+
state.active=false;
|
|
23
|
+
for (const label of state.rows.keys()) target.getRelativeData('.messageData').popNode(label);
|
|
24
|
+
state.rows.clear(); projections.delete(target);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
// Prepare all incoming content before changing the mounted conversation.
|
|
28
|
+
const incoming = messages.getNodes();
|
|
29
|
+
for (const message of incoming) {
|
|
30
|
+
if (!LABEL.test(message.label) || !['user','assistant'].includes(message.attr.role)
|
|
31
|
+
|| typeof message.attr.author !== 'string'
|
|
32
|
+
|| !(typeof message.staticValue === 'string' || message.staticValue instanceof GramlotBuilderBag)) {
|
|
33
|
+
throw new TypeError('Chat messages require a stable label, role, author and string or Gramlot Source');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const follow = viewport.scrollHeight-viewport.clientHeight-viewport.scrollTop < 48;
|
|
37
|
+
const plans = [];
|
|
38
|
+
for (const message of incoming) {
|
|
39
|
+
const old = state.rows.get(message.label);
|
|
40
|
+
if (old && old.value === message.staticValue && old.role === message.attr.role && old.author === message.attr.author) continue;
|
|
41
|
+
const fragment = new GramlotBuilder();
|
|
42
|
+
const article = fragment.root.article({node_label:message.label,
|
|
43
|
+
datapath:target.absDatapath('.messageData.'+message.label),'data-role':message.attr.role,
|
|
44
|
+
'aria-label':message.attr.author});
|
|
45
|
+
const body = sourceTarget(article.div());
|
|
46
|
+
if (typeof message.staticValue === 'string') {
|
|
47
|
+
fragment.wrapSource(body).div('=='+JSON.stringify(message.staticValue), {white_space:'pre-wrap'});
|
|
48
|
+
} else {
|
|
49
|
+
// Clone the typed fragment: never bind/move Source owned by the server Data Bag.
|
|
50
|
+
body.setValue(page.src.prepareSource(message.staticValue.toTytx()));
|
|
51
|
+
}
|
|
52
|
+
const prepared = page.src.prepareSource(fragment.source);
|
|
53
|
+
page.src.renderer.validateCandidate(prepared);
|
|
54
|
+
plans.push({message,old,child:prepared.getNode(message.label)});
|
|
55
|
+
}
|
|
56
|
+
const labels = new Set(incoming.map(message=>message.label));
|
|
57
|
+
for (const [label] of state.rows) if (!labels.has(label)) {
|
|
58
|
+
target.value.popNode(label);
|
|
59
|
+
target.getRelativeData('.messageData').popNode(label);
|
|
60
|
+
state.rows.delete(label);
|
|
61
|
+
}
|
|
62
|
+
for (const {message,old,child} of plans) {
|
|
63
|
+
if (old) target.value.popNode(message.label);
|
|
64
|
+
if (!old) target.setRelativeData('.messageData.'+message.label,new Bag());
|
|
65
|
+
// SourceBag insertion retains the same page renderer, bindings and Logic registry.
|
|
66
|
+
page.src.builder.setChild(target.value,child.nodeTag,child.value,{...child.attr,node_label:message.label});
|
|
67
|
+
state.rows.set(message.label,{value:message.staticValue,role:message.attr.role,author:message.attr.author});
|
|
68
|
+
}
|
|
69
|
+
if (follow) queueMicrotask(()=>{if(state.active) viewport.scrollTop=viewport.scrollHeight;});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function send(node, action, text=null) {
|
|
73
|
+
if (node.getRelativeData('.pending') || node.getRelativeData('.picking') || !node.getRelativeData('.conversation.ready')) return;
|
|
74
|
+
const id=randomId();
|
|
75
|
+
node.SET('.requestId',id); node.SET('.pending',true); node.SET('.error','');
|
|
76
|
+
// One atomic Data write; the normal binder carries it to the PageStore recipe.
|
|
77
|
+
node.SET('.conversation.request',new Bag({id,action,text,attachments:fromTytx(toTytx(node.getRelativeData('.attachments')))}));
|
|
78
|
+
}
|
|
79
|
+
export function chatSend(page,node) {
|
|
80
|
+
const text=node.getRelativeData('.draft');
|
|
81
|
+
if(typeof text !== 'string' || (!text.trim() && !node.getRelativeData('.attachments').length)) return;
|
|
82
|
+
send(node,'send',text);
|
|
83
|
+
}
|
|
84
|
+
export function chatReset(page,node) {send(node,'reset');}
|
|
85
|
+
export function chatCompleted(page,node,{response}) {
|
|
86
|
+
if(response === null) return;
|
|
87
|
+
if(!(response instanceof Bag)) throw new TypeError('Chat response requires a Data Bag');
|
|
88
|
+
if(response.getItem('id') !== node.getRelativeData('.requestId')) return;
|
|
89
|
+
if(response.getItem('accepted') && response.getItem('submitted') === node.getRelativeData('.draft')) node.SET('.draft','');
|
|
90
|
+
if(response.getItem('accepted') && response.getItem('submitted') !== null) node.SET('.attachments',new Bag());
|
|
91
|
+
node.SET('.pending',false);node.SET('.error',response.getItem('error'));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
const composerLayouts = new WeakMap();
|
|
96
|
+
/** Shared geometry: grow with wrapped text and content, cap the editor, release observers. */
|
|
97
|
+
export function chatResize(page,node) {
|
|
98
|
+
const source=node.parentNode;
|
|
99
|
+
let layout=composerLayouts.get(source);
|
|
100
|
+
if(!layout) {
|
|
101
|
+
const body=page.dom.getDomNode(source);
|
|
102
|
+
// Data setters can notify before mounting; _onBuilt installs the layout.
|
|
103
|
+
if(!body)return;
|
|
104
|
+
const composer=body.closest('[data-chat-composer]');
|
|
105
|
+
const editor=body.querySelector('textarea');
|
|
106
|
+
const top=composer.querySelector('[data-chat-top]');
|
|
107
|
+
const toolbar=composer.querySelector('[data-chat-toolbar]');
|
|
108
|
+
const win=body.ownerDocument.defaultView;
|
|
109
|
+
let frame=0,active=true;
|
|
110
|
+
const measure=()=>{
|
|
111
|
+
frame=0;if(!active)return;
|
|
112
|
+
editor.style.height='0px';
|
|
113
|
+
const css=win.getComputedStyle(editor);
|
|
114
|
+
const border=parseFloat(css.borderTopWidth)+parseFloat(css.borderBottomWidth);
|
|
115
|
+
const height=Math.max(44,Math.min(180,editor.scrollHeight+border));
|
|
116
|
+
editor.style.height=height+'px';
|
|
117
|
+
editor.style.overflowY=editor.scrollHeight+border>height?'auto':'hidden';
|
|
118
|
+
const total=Math.ceil(body.getBoundingClientRect().height+top.getBoundingClientRect().height+toolbar.getBoundingClientRect().height+2);
|
|
119
|
+
if(node.getRelativeData('.composerHeight')!==total) node.SET('.composerHeight',total);
|
|
120
|
+
};
|
|
121
|
+
const schedule=()=>{if(active&&!frame)frame=win.requestAnimationFrame(measure);};
|
|
122
|
+
const observer=new win.ResizeObserver(schedule);
|
|
123
|
+
for(const element of [body,top,toolbar]) observer.observe(element);
|
|
124
|
+
page.src.renderer.onDispose(source,()=>{active=false;observer.disconnect();if(frame)win.cancelAnimationFrame(frame);composerLayouts.delete(source);});
|
|
125
|
+
layout={schedule};composerLayouts.set(source,layout);
|
|
126
|
+
}
|
|
127
|
+
layout.schedule();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const textExtensions=['txt','md','csv','json','py','js','ts','jsx','tsx','html','css','sql','yaml','yml','xml','sh','toml','log'];
|
|
131
|
+
const fileTypes={png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',webp:'image/webp',pdf:'application/pdf',...Object.fromEntries(textExtensions.map(ext=>[ext,'text/plain']))};
|
|
132
|
+
function readFile(file,win) {
|
|
133
|
+
return new Promise((resolve,reject)=>{
|
|
134
|
+
const reader=new win.FileReader();
|
|
135
|
+
reader.onload=()=>resolve(reader.result.slice(reader.result.indexOf(',')+1));
|
|
136
|
+
reader.onerror=()=>reject(new Error('Could not read the selected file.'));
|
|
137
|
+
reader.readAsDataURL(file);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
export async function chatPickAttachments(page,node) {
|
|
141
|
+
if(node.getRelativeData('.pending')||node.getRelativeData('.picking'))return;
|
|
142
|
+
const doc=page.dom.getDomNode(node.parentNode).ownerDocument;
|
|
143
|
+
const input=doc.createElement('input');input.type='file';input.multiple=true;
|
|
144
|
+
input.accept=Object.keys(fileTypes).map(ext=>'.'+ext).join(',');
|
|
145
|
+
input.style.display='none';doc.body.append(input);
|
|
146
|
+
let active=true,finish;
|
|
147
|
+
const release=page.src.renderer.onDispose(node.parentNode,()=>{active=false;input.remove();finish([]);});
|
|
148
|
+
node.SET('.picking',true);node.SET('.error','');
|
|
149
|
+
try {
|
|
150
|
+
const files=await new Promise(resolve=>{
|
|
151
|
+
finish=resolve;
|
|
152
|
+
input.addEventListener('cancel',()=>resolve([]),{once:true});
|
|
153
|
+
input.addEventListener('change',()=>resolve([...input.files]),{once:true});
|
|
154
|
+
input.click();
|
|
155
|
+
});
|
|
156
|
+
if(!active||!files.length)return;
|
|
157
|
+
const attachments=fromTytx(toTytx(node.getRelativeData('.attachments')));
|
|
158
|
+
if(attachments.length+files.length>5)throw new Error('Choose at most 5 files.');
|
|
159
|
+
let total=attachments.getNodes().reduce((n,file)=>n+file.staticValue.getItem('size'),0);
|
|
160
|
+
for(const file of files) {
|
|
161
|
+
const mediaType=fileTypes[file.name.split('.').pop().toLowerCase()];
|
|
162
|
+
if(!mediaType)throw new Error('Supported files: PNG, JPEG, WebP, PDF and UTF-8 text/code.');
|
|
163
|
+
const limit=mediaType==='text/plain'?1024*1024:2*1024*1024;
|
|
164
|
+
total+=file.size;
|
|
165
|
+
if(!file.size||file.size>limit||total>4*1024*1024)throw new Error('Limits: 2 MiB per file, 1 MiB for text, 4 MiB total.');
|
|
166
|
+
const data=await readFile(file,doc.defaultView);
|
|
167
|
+
if(mediaType==='text/plain') {
|
|
168
|
+
const bytes=Uint8Array.from(atob(data),c=>c.charCodeAt(0));
|
|
169
|
+
new TextDecoder('utf-8',{fatal:true}).decode(bytes);
|
|
170
|
+
if(bytes.includes(0))throw new Error('The selected file is not UTF-8 text.');
|
|
171
|
+
}
|
|
172
|
+
attachments.setItem('a_'+randomId(),new Bag({name:file.name,mediaType,size:file.size,data}));
|
|
173
|
+
}
|
|
174
|
+
if(active)node.SET('.attachments',attachments);
|
|
175
|
+
} catch(error) {if(active)node.SET('.error',error.message);}
|
|
176
|
+
finally {release();input.remove();if(active)node.SET('.picking',false);}
|
|
177
|
+
}
|
|
178
|
+
export function chatRemoveAttachment(page,node) {
|
|
179
|
+
if(!node.getRelativeData('.pending'))node.getRelativeData('.attachments').popNode(node.getAttr('attachment_id'));
|
|
180
|
+
}
|
|
181
|
+
export function chatRenderAttachments(page,node,{attachments}) {
|
|
182
|
+
const target=node.parentNode;
|
|
183
|
+
for(const child of [...target.value.getNodes()])if(child.label.startsWith('a_'))target.value.popNode(child.label);
|
|
184
|
+
const builder=new GramlotBuilder();
|
|
185
|
+
for(const attachment of attachments.getNodes()) {
|
|
186
|
+
const file=attachment.staticValue;
|
|
187
|
+
const item=builder.root.div({node_label:attachment.label,display:'flex',align_items:'center',gap:'6px',
|
|
188
|
+
padding:'4px 8px',border:'1px solid var(--gramlot-border-control,#aaa)',border_radius:'10px',flex_shrink:0});
|
|
189
|
+
if(file.getItem('mediaType').startsWith('image/')) item.img({src:'data:'+file.getItem('mediaType')+';base64,'+file.getItem('data'),
|
|
190
|
+
alt:'Attachment preview',width:'36px',height:'36px',object_fit:'cover',border_radius:'6px'});
|
|
191
|
+
item.span('=='+JSON.stringify(file.getItem('name')),{font_size:'12px',max_width:'180px',overflow:'hidden',text_overflow:'ellipsis',white_space:'nowrap'});
|
|
192
|
+
item.button({icon:'×','aria-label':'Remove '+file.getItem('name'),disabled:'^.pending',class:'button--quiet'})
|
|
193
|
+
.dataController({func:'chatRemoveAttachment',attachment_id:attachment.label});
|
|
194
|
+
}
|
|
195
|
+
const prepared=page.src.prepareSource(builder.source);
|
|
196
|
+
page.src.renderer.validateCandidate(prepared);
|
|
197
|
+
for(const child of prepared.getNodes())page.src.builder.setChild(target.value,child.nodeTag,child.value,{...child.attr,node_label:child.label});
|
|
198
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Portable prepared-artifact integrity; hosts provide bytes, never filesystem paths. */
|
|
2
2
|
const encoder = new TextEncoder();
|
|
3
|
-
const wrapper = id => `export {default} from "./collection.js";\nexport const buildId = "${id}";\n`;
|
|
3
|
+
const wrapper = id => `export {default} from "./collection.js";\nexport * from "./collection.js";\nexport const buildId = "${id}";\n`;
|
|
4
4
|
const pathValid = value => typeof value === 'string' && value.length > 0 &&
|
|
5
5
|
!/[\\\x00-\x1f:?#%]/.test(value) && !value.split('/').some(part => !part || part === '.' || part === '..');
|
|
6
6
|
function validate(metadata, files) {
|
package/src/components/bases.js
CHANGED
|
@@ -32,6 +32,7 @@ export function controlElement(HTMLElement) {
|
|
|
32
32
|
return projectParameters(this, attrs);
|
|
33
33
|
}
|
|
34
34
|
setPageContext(context) { this.pageContext = context; }
|
|
35
|
+
connectedCallback() {}
|
|
35
36
|
releaseControl() {}
|
|
36
37
|
get liveWrites() { return this.control.localName === 'textarea' || ['text', 'password', 'range', 'color'].includes(this.control.type); }
|
|
37
38
|
validateCandidate(value, accept) {
|
|
@@ -49,6 +50,7 @@ export function controlElement(HTMLElement) {
|
|
|
49
50
|
if (!this.sameControlValue(value, accepted)) this.writeControlValue(accepted);
|
|
50
51
|
});
|
|
51
52
|
}
|
|
53
|
+
restoreFormValue(value) { this.writeControlValue(value); }
|
|
52
54
|
sameControlValue(a, b) { return Object.is(a, b); }
|
|
53
55
|
focus(options) { this.control.focus(options); }
|
|
54
56
|
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Optional chat viewport; interactive contents are ordinary live Source children. */
|
|
2
|
+
import {defineCollection, defineComponent} from './registry.js';
|
|
3
|
+
import {Container} from './container.js';
|
|
4
|
+
|
|
5
|
+
export const ChatMessages = defineComponent({
|
|
6
|
+
name: 'chatMessages', tag: 'gramlot-chat-messages', base: Container, subTags: '*',
|
|
7
|
+
implementation: Base => class extends Base {
|
|
8
|
+
constructor() {
|
|
9
|
+
super();
|
|
10
|
+
const style = this.ownerDocument.createElement('style');
|
|
11
|
+
style.textContent = `:host{height:100%;min-height:0;overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable}
|
|
12
|
+
.control-box{padding:20px max(20px,calc((100% - 880px)/2))}
|
|
13
|
+
::slotted(article){box-sizing:border-box;margin:0 0 24px;padding:16px 20px;border-radius:18px;
|
|
14
|
+
line-height:1.6;overflow-wrap:anywhere;background:var(--gramlot-chat-assistant-background,
|
|
15
|
+
color-mix(in srgb,var(--gramlot-surface-subtle,#eee) 88%,#628099))}
|
|
16
|
+
::slotted(article[data-role=user]){width:fit-content;max-width:85%;margin-left:auto;padding:12px 18px;
|
|
17
|
+
border-radius:20px;background:var(--gramlot-chat-bubble,var(--gramlot-surface-subtle,#eee))}`;
|
|
18
|
+
this.shadowRoot.append(style);
|
|
19
|
+
}
|
|
20
|
+
connectedCallback() {
|
|
21
|
+
this.setAttribute('role','log');
|
|
22
|
+
this.setAttribute('aria-label','Conversation messages');
|
|
23
|
+
this.setAttribute('aria-live','polite');
|
|
24
|
+
this.tabIndex=0;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
export default defineCollection({name:'chat', components:[ChatMessages]});
|