@gramlot/gramlot 0.3.20 → 0.3.26
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 +26 -120912
- package/dist/components/editors/assets/index.js +2 -1
- package/dist/components/editors/assets/modules/chunk-74O4WKIV.js +1 -0
- package/dist/components/editors/assets/modules/chunk-AU4HFPIY.js +1 -0
- package/dist/components/editors/assets/modules/chunk-YSGSC7KM.js +1 -0
- package/dist/components/editors/assets/modules/code-mirror-engine-RWQTR5G5.js +92 -0
- package/dist/components/editors/assets/modules/jodit-engine-MTSA4GZ3.js +1853 -0
- package/dist/components/editors/assets/modules/markdown-document-VFC23FAY.js +1 -0
- package/dist/components/editors/assets/modules/prose-mirror-engine-GMZPJPNN.js +24 -0
- package/dist/components/grid/__init__.py +14 -0
- package/dist/components/grid/assets/collection.js +262 -0
- package/dist/components/grid/assets/index.js +3 -0
- package/dist/components/grid/commands.json +7 -0
- package/dist/components/grid/grammar.json +770 -0
- package/dist/components/grouplets/__init__.py +13 -0
- package/dist/components/grouplets/assets/collection.js +185 -0
- package/dist/components/grouplets/assets/index.js +3 -0
- package/dist/components/grouplets/assets/modules/chunk-BLMUM44K.js +1 -0
- package/dist/components/grouplets/assets/modules/markdown-document-YWNZTOKK.js +1 -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 +65 -24511
- package/dist/components/inputs/assets/index.js +2 -1
- package/dist/components/inputs/grammar.json +278 -6
- package/dist/components/layout/__init__.py +1 -1
- package/dist/components/layout/assets/collection.js +68 -26732
- package/dist/components/layout/assets/index.js +2 -1
- package/dist/components/layout/grammar.json +39 -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 +587 -0
- package/dist/components/tree/__init__.py +1 -1
- package/dist/components/tree/assets/collection.js +27 -24612
- package/dist/components/tree/assets/index.js +2 -1
- package/dist/components/tree/grammar.json +341 -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/components/uploads/__init__.py +13 -0
- package/dist/components/uploads/assets/collection.js +67 -0
- package/dist/components/uploads/assets/index.js +3 -0
- package/dist/components/uploads/commands.json +7 -0
- package/dist/components/uploads/grammar.json +789 -0
- package/dist/gramlot-markdown.js +16 -0
- package/dist/gramlot.js +6861 -1395
- package/dist/gramlot.min.js +1595 -46
- package/dist/runtime-notices.json +28 -0
- package/package.json +10 -3
- package/src/binding/grid-struct.js +63 -0
- package/src/binding/installation.js +5 -2
- package/src/binding/providers.js +4 -1
- package/src/binding/remote-resolver.js +1 -8
- package/src/binding/runtime.js +90 -6
- package/src/binding/validation-context.js +40 -0
- package/src/browser-camera-provider.d.ts +8 -0
- package/src/browser-camera-provider.js +104 -0
- package/src/builder/gramlot-builder.d.ts +5 -0
- package/src/builder/gramlot-builder.js +16 -0
- package/src/builder/source.js +34 -0
- package/src/chat.d.ts +12 -0
- package/src/chat.js +198 -0
- package/src/collection-artifact.js +1 -1
- package/src/components/attachment-manager.js +160 -0
- package/src/components/bases.js +19 -6
- package/src/components/border-container.js +86 -8
- package/src/components/buttons.js +11 -1
- package/src/components/chat.js +28 -0
- package/src/components/choice-editor.js +106 -38
- package/src/components/database-choices.js +133 -9
- package/src/components/editing-status-styles.js +26 -0
- package/src/components/editing-status.js +115 -0
- package/src/components/field-state.js +42 -54
- package/src/components/grid-cell-editor.js +181 -0
- package/src/components/grid-grammar.json +258 -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 +85 -0
- package/src/components/grid-styles.js +201 -0
- package/src/components/grid.js +666 -0
- package/src/components/grouplet-card.js +445 -0
- package/src/components/grouplets.js +17 -0
- package/src/components/html-preview.js +17 -4
- package/src/components/image-crop-dialog.js +272 -0
- package/src/components/image-crop.js +79 -0
- package/src/components/image-uploader.js +252 -0
- package/src/components/inputs.js +2 -1
- package/src/components/jodit-engine.js +1 -1
- package/src/components/markdown-document.js +2 -2
- package/src/components/menus.js +1 -0
- package/src/components/registry.js +4 -3
- package/src/components/screen-capture.js +43 -0
- package/src/components/selected-container.js +6 -2
- package/src/components/tray-pane.js +32 -4
- package/src/components/tree.js +416 -17
- package/src/components/typed-editor.js +23 -11
- package/src/components/upload-engine.js +156 -0
- package/src/components/uploader.js +208 -0
- package/src/components/uploads.js +7 -0
- package/src/editing-session.d.ts +25 -0
- package/src/editing-session.js +396 -0
- package/src/experiments/selection-transfer.js +78 -0
- package/src/experiments/selection-trial.js +64 -0
- package/src/experiments/window-selection.js +124 -0
- package/src/format.js +22 -7
- package/src/gramlot.d.ts +2 -0
- package/src/gramlot.js +2 -1
- package/src/handlers/device-handler.d.ts +2 -1
- package/src/handlers/rpc-handler.d.ts +3 -3
- package/src/index-page-styles.js +2 -1
- package/src/index.d.ts +16 -1
- package/src/index.js +16 -1
- package/src/inout.d.ts +2 -0
- package/src/inout.js +6 -0
- package/src/markdown-loader.d.ts +1 -0
- package/src/markdown-loader.js +4 -0
- package/src/markdown.d.ts +1 -0
- package/src/markdown.js +2 -0
- package/src/media-frame.js +9 -0
- package/src/renderer/attributes.js +7 -1
- package/src/renderer/gramlot-renderer.d.ts +2 -0
- package/src/renderer/gramlot-renderer.js +39 -3
- package/src/server/assets.d.ts +1 -1
- package/src/server/assets.js +1 -1
- package/src/server/gramlot-server.d.ts +10 -1
- package/src/server/gramlot-server.js +96 -8
- package/src/server/index.d.ts +2 -0
- package/src/server/index.js +2 -0
- package/src/server/page-base.js +17 -4
- package/src/server/page.d.ts +13 -1
- package/src/server/page.js +6 -0
- package/src/server/source-import.d.ts +2 -0
- package/src/server/source-import.js +31 -0
- package/src/server/upload.d.ts +20 -0
- package/src/server/upload.js +142 -0
- package/src/server/visual-editor.d.ts +11 -0
- package/src/server/visual-editor.js +149 -0
- package/src/source-picker.d.ts +9 -0
- package/src/source-picker.js +57 -0
- 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/tree-store.d.ts +24 -0
- package/src/tree-store.js +193 -0
- package/src/validation-run.js +50 -0
- package/src/view/button.js +8 -5
- package/src/view/controls.js +31 -32
- package/src/view/grouplet-card.js +54 -0
- package/src/view/html.js +29 -4
- package/src/view/labelbox.js +7 -3
- package/src/visual-editor-icons.js +10 -0
- package/src/visual-editor.d.ts +56 -0
- package/src/visual-editor.js +844 -0
- package/themes/gramlot-base/theme.css +127 -0
- package/themes/gramlot-compact/theme.css +8 -0
- package/themes/joanna/theme.css +8 -0
- package/themes/mimi/theme.css +8 -0
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/** Application-owned destination for a single upload. */
|
|
2
|
+
export class UploadTarget {
|
|
3
|
+
constructor({maxBytes}) {
|
|
4
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
|
|
5
|
+
throw new TypeError('maxBytes must be a nonnegative safe integer');
|
|
6
|
+
}
|
|
7
|
+
this.maxBytes = maxBytes;
|
|
8
|
+
}
|
|
9
|
+
write(chunk) { throw new Error('UploadTarget.write must be implemented'); }
|
|
10
|
+
finish() { throw new Error('UploadTarget.finish must be implemented'); }
|
|
11
|
+
abort() { throw new Error('UploadTarget.abort must be implemented'); }
|
|
12
|
+
status() { throw new Error('UploadTarget.status must be implemented'); }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
import {toTytx} from '@genrojs/tytx';
|
|
16
|
+
|
|
17
|
+
function checkedOutcome(value) {
|
|
18
|
+
if (value === null || typeof value !== 'object' || Object.getPrototypeOf(value) !== Object.prototype ||
|
|
19
|
+
!['completed', 'unsaved', 'pending', 'uncertain'].includes(value.state)) {
|
|
20
|
+
throw new TypeError('Invalid upload outcome');
|
|
21
|
+
}
|
|
22
|
+
const keys = Object.keys(value).sort().join(',');
|
|
23
|
+
if (keys !== (value.state === 'completed' ? 'result,state' : 'state')) {
|
|
24
|
+
throw new TypeError('Invalid upload outcome fields');
|
|
25
|
+
}
|
|
26
|
+
if (value.state === 'completed') toTytx(value.result);
|
|
27
|
+
return {...value};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** A serialized operation on an application-owned upload target. */
|
|
31
|
+
export class UploadTransfer {
|
|
32
|
+
#tail = Promise.resolve();
|
|
33
|
+
#state = {state:'pending'};
|
|
34
|
+
#received = 0;
|
|
35
|
+
#sealed = false;
|
|
36
|
+
constructor(target, size, onOutcome = null) {
|
|
37
|
+
if (!(target instanceof UploadTarget)) throw new TypeError('Upload operation must return an UploadTarget');
|
|
38
|
+
if (!Number.isSafeInteger(size) || size < 0 || size > target.maxBytes) throw new RangeError('Invalid upload size');
|
|
39
|
+
this.target = target;
|
|
40
|
+
this.size = size;
|
|
41
|
+
this.onOutcome = onOutcome;
|
|
42
|
+
}
|
|
43
|
+
#run(action) {
|
|
44
|
+
const current = this.#tail.then(action);
|
|
45
|
+
this.#tail = current.catch(() => {});
|
|
46
|
+
return current;
|
|
47
|
+
}
|
|
48
|
+
#record(outcome) { this.#state = checkedOutcome(outcome); if (this.#state.state === 'completed') this.onOutcome?.(); return {...this.#state}; }
|
|
49
|
+
#terminal() { return ['completed', 'unsaved'].includes(this.#state.state); }
|
|
50
|
+
write(chunk) {
|
|
51
|
+
return this.#run(async () => {
|
|
52
|
+
if (!(chunk instanceof Uint8Array)) throw new TypeError('Upload chunks must be Uint8Array');
|
|
53
|
+
if (this.#state.state !== 'pending' || this.#sealed) throw new Error('Upload is not writable');
|
|
54
|
+
if (this.#received + chunk.byteLength > this.size) throw new RangeError('Upload exceeds declared size');
|
|
55
|
+
try { await this.target.write(chunk); }
|
|
56
|
+
catch (error) { this.#state = {state:'uncertain'}; this.#sealed = true; this.onOutcome?.(); throw error; }
|
|
57
|
+
this.#received += chunk.byteLength;
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
finish() {
|
|
61
|
+
return this.#run(async () => {
|
|
62
|
+
if (this.#state.state !== 'pending' || this.#sealed) throw new Error('Upload cannot be finished');
|
|
63
|
+
if (this.#received !== this.size) throw new RangeError('Upload size does not match declaration');
|
|
64
|
+
this.#sealed = true;
|
|
65
|
+
try { return this.#record(await this.target.finish()); }
|
|
66
|
+
catch (error) { this.#state = {state:'uncertain'}; this.onOutcome?.(); throw error; }
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
abort() {
|
|
70
|
+
return this.#run(async () => {
|
|
71
|
+
if (this.#terminal()) return {...this.#state};
|
|
72
|
+
this.#sealed = true;
|
|
73
|
+
try { return this.#record(await this.target.abort()); }
|
|
74
|
+
catch (error) { this.#state = {state:'uncertain'}; throw error; }
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
status() {
|
|
78
|
+
return this.#run(async () => {
|
|
79
|
+
if (this.#terminal()) return {...this.#state};
|
|
80
|
+
try { return this.#record(await this.target.status()); }
|
|
81
|
+
catch (error) { this.#state = {state:'uncertain'}; throw error; }
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Private server registry: grants are one-use and bound to a page and its owner. */
|
|
87
|
+
export class UploadRegistry {
|
|
88
|
+
constructor({capacity = 1000, grantTtl = 300000, retention = 1800000} = {}) {
|
|
89
|
+
this.records = new Map();
|
|
90
|
+
Object.assign(this, {capacity, grantTtl, retention});
|
|
91
|
+
}
|
|
92
|
+
async expire() {
|
|
93
|
+
const now = performance.now();
|
|
94
|
+
for (const [id, record] of this.records) {
|
|
95
|
+
if (record.expires <= now || (!record.started && record.grantExpires <= now)) {
|
|
96
|
+
const expires = record.expires;
|
|
97
|
+
try { await record.transfer.abort(); } catch {} // The outcome can remain uncertain.
|
|
98
|
+
if (record.expires === expires) this.records.delete(id);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
async prepare({pageId, owner, operation, target, size}) {
|
|
103
|
+
await this.expire();
|
|
104
|
+
if (this.records.size >= this.capacity) throw new Error('Upload registry capacity reached');
|
|
105
|
+
const transferId = crypto.randomUUID();
|
|
106
|
+
const transfer = new UploadTransfer(target, size, () => {
|
|
107
|
+
const record = this.records.get(transferId);
|
|
108
|
+
if (record) record.expires = performance.now() + this.retention;
|
|
109
|
+
});
|
|
110
|
+
const authorization = crypto.randomUUID() + crypto.randomUUID();
|
|
111
|
+
const now = performance.now();
|
|
112
|
+
this.records.set(transferId, {pageId, owner, operation, transfer, authorization,
|
|
113
|
+
started:false, grantExpires:now + this.grantTtl, expires:now + this.retention});
|
|
114
|
+
return {transferId, authorization};
|
|
115
|
+
}
|
|
116
|
+
record(transferId, pageId, owner) {
|
|
117
|
+
const record = this.records.get(transferId);
|
|
118
|
+
if (!record || record.pageId !== pageId || record.owner !== owner) throw new Error('Unknown or unauthorized upload');
|
|
119
|
+
return record;
|
|
120
|
+
}
|
|
121
|
+
admit(transferId, pageId, owner, authorization) {
|
|
122
|
+
const record = this.record(transferId, pageId, owner);
|
|
123
|
+
if (record.started || record.grantExpires <= performance.now() || record.authorization !== authorization) {
|
|
124
|
+
throw new Error('Invalid upload authorization');
|
|
125
|
+
}
|
|
126
|
+
record.started = true;
|
|
127
|
+
record.authorization = null;
|
|
128
|
+
record.expires = performance.now() + this.retention;
|
|
129
|
+
return record.transfer;
|
|
130
|
+
}
|
|
131
|
+
touch(transferId, pageId, owner) {
|
|
132
|
+
this.record(transferId, pageId, owner).expires = performance.now() + this.retention;
|
|
133
|
+
}
|
|
134
|
+
async closePage(pageId, owner) {
|
|
135
|
+
for (const [id, record] of this.records) {
|
|
136
|
+
if (record.pageId === pageId && record.owner === owner) {
|
|
137
|
+
this.records.delete(id);
|
|
138
|
+
try { await record.transfer.abort(); } catch {} // The page can no longer query this outcome.
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type {SourceBagNode} from '@genrojs/builders';
|
|
2
|
+
export interface PageCodeDocument {language:'python'|'javascript'; key:string; path:string; content:string; revision:string; writable:boolean;}
|
|
3
|
+
export class VisualEditor {
|
|
4
|
+
constructor(parent:SourceBagNode, options?:{datapath?:string; dataRoot?:string; editorId?:string; uploadOperation?:string; codeDocument?:PageCodeDocument; [attribute:string]:unknown});
|
|
5
|
+
pane:SourceBagNode;
|
|
6
|
+
frame:SourceBagNode;
|
|
7
|
+
toolbar:SourceBagNode;
|
|
8
|
+
rail:SourceBagNode;
|
|
9
|
+
design:SourceBagNode;
|
|
10
|
+
codeDocument(document:PageCodeDocument, frame?:SourceBagNode):void;
|
|
11
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import {Bag} from '@genrojs/bag';
|
|
2
|
+
import {sourceTarget} from '@genrojs/builders';
|
|
3
|
+
import {toolIcons} from '../visual-editor-icons.js';
|
|
4
|
+
|
|
5
|
+
export class VisualEditor {
|
|
6
|
+
constructor(root, {datapath = '__editor', dataRoot = '', editorId = 'visual', uploadOperation = 'import_source', codeDocument = null, ...attributes} = {}) {
|
|
7
|
+
if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(editorId)) throw new Error('editorId must be a literal identifier');
|
|
8
|
+
if (!dataRoot && datapath !== '__editor' && !datapath.startsWith('__editor.')) throw new Error('Root Data editing requires an __editor datapath');
|
|
9
|
+
this.dataRoot = dataRoot;
|
|
10
|
+
const pane = this.pane = root.main({node_label:editorId, datapath, visualEditorId:editorId, ...attributes, nodeId:`${editorId}Editor`, class:`visual-editor-shell ${attributes.class ?? ''}`, overflow:'hidden', tabindex:0, connect_onkeydown:'clipboardShortcut'});
|
|
11
|
+
pane.dataSetter({destination_path:'.uploadQueue', value:new Bag()});
|
|
12
|
+
pane.dataController({func:'initializeEditor', dataRoot:this.dataRoot, _init:true});
|
|
13
|
+
pane.dataController({func:'showProperties', path:'^.selection', _init:true});
|
|
14
|
+
pane.dataController({func:'initializeCanvasSelection', _onBuilt:true});
|
|
15
|
+
pane.dataController({func:'highlightSelection', path:'^.selection', _init:true});
|
|
16
|
+
pane.style('^.appearanceCss');
|
|
17
|
+
pane.dataController({func:'initializeEditorAppearance', _onBuilt:true});
|
|
18
|
+
pane.dataController({func:'applyEditorAppearance', profile:'^.appearanceProfile', palette:'^.appearancePalette', mode:'^.appearanceMode'});
|
|
19
|
+
const rail = this.rail = pane.menu({presentation:'bar', orientation:'vertical', aria_label:'Editor panels', class:'visual-editor-rail'});
|
|
20
|
+
this.toolButton(rail.menuline({group:true, overflowable:false}), 'Source / Data', 'toggleNavigation', toolIcons.navigation);
|
|
21
|
+
this.toolButton(rail.menuline({group:true, overflowable:false}), 'Catalogue', 'openCatalogue', toolIcons.catalogue);
|
|
22
|
+
this.toolButton(rail.menuline({group:true, overflowable:false}), 'Properties', 'openProperties', toolIcons.properties);
|
|
23
|
+
this.toolButton(rail.menuline({group:true, overflowable:false}), 'Clipboard', "this.SET('.clipboardVisible', !this.GET('.clipboardVisible'))", toolIcons.paste);
|
|
24
|
+
rail.spacer({flex:1});
|
|
25
|
+
this.toolButton(rail.menuline({group:true, overflowable:false}), 'Appearance', "this.SET('.appearanceOpen', !this.GET('.appearanceOpen'))", toolIcons.appearance);
|
|
26
|
+
const layoutRoot = pane.framePane({node_label:'layout', height:'100%', id:`${editorId}-editor-frame`, class:'visual-editor-layout'});
|
|
27
|
+
layoutRoot.top.setAttr({height:'38px'});
|
|
28
|
+
const toolbar = layoutRoot.top.menu({presentation:'bar', aria_label:'Editor tools', class:'visual-editor-toolbar'});
|
|
29
|
+
toolbar.menuline({group:true, overflowable:false}).span('Source editor', {class:'visual-editor-brand'});
|
|
30
|
+
const files = toolbar.menuline({group:true, overflowable:false, gap:'4px'});
|
|
31
|
+
for (const [caption,action,icon] of [['New','newPage','new'],['Open','openUpload','open'],['Download','downloadPage','download'],['Copy Source','copySource','copy']])
|
|
32
|
+
this.toolButton(files,caption,action,toolIcons[icon],{id:`${editorId}-${icon}`});
|
|
33
|
+
toolbar.menuline({group:true, overflowable:false}).span({class:'visual-toolbar-divider', aria_hidden:'true'});
|
|
34
|
+
const edit = toolbar.menuline({group:true, overflowable:false, gap:'2px'});
|
|
35
|
+
this.toolButton(edit,'Cut branch','cutBranch',toolIcons.cut,{title:'Cut branch (F8)'});
|
|
36
|
+
this.toolButton(edit,'Copy branch','copyBranch',toolIcons.copy);
|
|
37
|
+
this.toolButton(edit,'Paste branch','pasteBranch',toolIcons.paste,{title:'Paste branch (F9)'});
|
|
38
|
+
toolbar.spacer({flex:1});
|
|
39
|
+
toolbar.menuline({group:true, overflowable:false}).span('^.fileStatus', {role:'status', class:'visual-editor-file-status'});
|
|
40
|
+
toolbar.menuline({group:true, overflowable:false}).span('^.filename', {class:'visual-editor-filename'});
|
|
41
|
+
const left = layoutRoot.left;
|
|
42
|
+
left.setAttr({width:'min(260px, 34vw)', splitter:true,
|
|
43
|
+
drawer:'^.navigationOpen', default_drawer:true, drawer_label:'Source / Data',
|
|
44
|
+
drawer_onclick:"this.SET('.navigationOpen', show ? true : 'close')",
|
|
45
|
+
display:'flex', flex_direction:'column', min_height:0, class:'visual-editor-sidebar'});
|
|
46
|
+
const sidebar = left.borderContainer({height:'100%', flex:1, min_height:0});
|
|
47
|
+
const navigation = sidebar.contentPane({region:'center'}).borderContainer({height:'100%', min_height:0});
|
|
48
|
+
const sourceStack = navigation.contentPane({region:'center'}).borderContainer({height:'100%', min_height:0});
|
|
49
|
+
const source = sourceStack.contentPane({node_label:'source', region:'center', title:'Source', detachable:true,
|
|
50
|
+
display:'flex', flex_direction:'column', min_height:0, overflow:'hidden'});
|
|
51
|
+
this.search(source, 'sourceSearch', 'Search Source');
|
|
52
|
+
source.tree({storepath:`*S.${sourceTarget(pane).fullpath.split('.').slice(1).join('.')}.layout.center.design`, hideValues:true, getLabel:'sourceLabel', searchText:'^.sourceSearch', selectedPath:'^.selection',
|
|
53
|
+
draggable:true, dragTags:`${editorId}Source`, effectAllowed:'all', onDrag:'prepareSource', dropTarget:true,
|
|
54
|
+
dropTypes:'app/widget,app/source,app/clipboard', dropTags:`widget,${editorId}Source,${editorId}Clipboard`, dropEffect:'^.sourceDropEffect', onDrop:'dropNode',
|
|
55
|
+
id:`${editorId}-source-tree`, class:'visual-source-tree', flex:1, min_height:0});
|
|
56
|
+
const shelf = sourceStack.contentPane({node_label:'clipboard', region:'bottom', height:'112px', splitter:true, minSize:80, title:'Clipboard', detachable:true, hidden:'^.clipboardVisible:=!{}', display:'flex', flex_direction:'column',
|
|
57
|
+
min_height:0, overflow:'hidden', dropTarget:true, dropTypes:'app/source', dropTags:`${editorId}Source`,
|
|
58
|
+
dropEffect:'^.clipboardDropEffect', connect_ondragover:'clipboardModifiers', connect_ondrop:'clipboardModifiers',
|
|
59
|
+
onDrop:'dropClipboard', class:'visual-clipboard'});
|
|
60
|
+
shelf.span('Drop a branch here · Option to copy', {class:'visual-editor-hint'});
|
|
61
|
+
shelf.tree({storepath:'.clipboard', hideValues:true, labelAttribute:'name', selectedPath:'^.clipboardSelection',
|
|
62
|
+
draggable:true, dragTags:`${editorId}Clipboard`, effectAllowed:'copy', onDrag:'prepareClipboard',
|
|
63
|
+
id:`${editorId}-clipboard-tree`, class:'visual-clipboard-tree', flex:1, min_height:0});
|
|
64
|
+
shelf.p('^.error', {role:'alert', class:'visual-editor-hint'});
|
|
65
|
+
const data = navigation.contentPane({node_label:'data', region:'bottom', title:'Data', detachable:true, height:'108px', splitter:true, minSize:80, display:'flex', flex_direction:'column', min_height:0, overflow:'hidden'});
|
|
66
|
+
this.search(data, 'dataSearch', 'Search Data');
|
|
67
|
+
data.tree({storepath:this.dataRoot ? `*D.${this.dataRoot}` : '*D', excludeRoot:this.dataRoot ? null : '__editor', searchText:'^.dataSearch', id:`${editorId}-data-tree`, flex:1, min_height:0});
|
|
68
|
+
const center = layoutRoot.center;
|
|
69
|
+
center.setAttr({overflow:'auto', class:'visual-editor-workspace'});
|
|
70
|
+
const design = center.div({node_label:'design', class:'visual-editor-canvas'});
|
|
71
|
+
design.div({node_label:'pageRoot', ...(this.dataRoot ? {datapath:this.dataRoot} : {})});
|
|
72
|
+
const window = pane.floatingPane({title:'Widget catalogue', open:'^.catalogueOpen', default_open:false, width:'320px', height:'480px', movable:true, resizable:true});
|
|
73
|
+
this.search(window.frame.top, 'catalogueSearch', 'Search widgets');
|
|
74
|
+
window.frame.center.tree({storepath:'.catalogue', hideValues:true, labelAttribute:'caption', searchText:'^.catalogueSearch',
|
|
75
|
+
draggable:true, dragTags:'widget', effectAllowed:'all', onDrag:'prepareWidget', id:`${editorId}-widget-tree`});
|
|
76
|
+
const properties = sidebar.contentPane({region:'bottom', height:'^.propertiesHeight', default_height:'240px', minSize:140, splitter:true,
|
|
77
|
+
title:'^.propertiesTitle', detachable:true, hidden:'^.propertiesOpen:=!{}',
|
|
78
|
+
display:'flex', flex_direction:'column', overflow:'hidden', min_height:0});
|
|
79
|
+
properties.div({nodeId:`${editorId}EditorFields`, class:'visual-editor-fields', display:'flex', flex_direction:'column', flex:1, min_height:0}).span('');
|
|
80
|
+
properties.p('^.propertyError', {role:'alert', class:'visual-editor-hint', margin:'8px'});
|
|
81
|
+
const uploader = pane.dialog({title:'Open Source', open:'^.uploadOpen', width:'480px', height:'300px', movable:true, resizable:true});
|
|
82
|
+
uploader.frame.center.uploader({operation:uploadOperation, storepath:'.uploadQueue', accept:'.grmlt',
|
|
83
|
+
multiple:false, autoUpload:true, onComplete:'sourceUploaded', id:`${editorId}-uploader`});
|
|
84
|
+
const naming = pane.dialog({title:'Save branch to clipboard', open:'^.clipboardOpen', width:'380px', height:'210px'});
|
|
85
|
+
naming.frame.center.textbox({value:'^.clipboardDraft.name', lbl:'Name', margin:'12px'});
|
|
86
|
+
naming.frame.center.p('^.error', {role:'alert', margin:'12px'});
|
|
87
|
+
const namingBar = naming.frame.bottom.menu({presentation:'bar', aria_label:'Clipboard commands', padding:'8px 12px'});
|
|
88
|
+
namingBar.spacer({flex:1});
|
|
89
|
+
const namingButtons = namingBar.menuline({group:true, overflowable:false, gap:'8px'});
|
|
90
|
+
namingButtons.button('Cancel', {action:"this.SET('.clipboardOpen', false)"});
|
|
91
|
+
namingButtons.button('Save branch', {action:'saveClipboard'});
|
|
92
|
+
const dialog = pane.dialog({title:'Required parameters', open:'^.insertionOpen', width:'400px', height:'280px', movable:true, resizable:true});
|
|
93
|
+
dialog.frame.center.div({nodeId:`${editorId}InsertFields`, class:'visual-editor-fields', padding:'12px'}).span('');
|
|
94
|
+
dialog.frame.center.p('^.error', {role:'alert'});
|
|
95
|
+
const bar = dialog.frame.bottom.menu({presentation:'bar', aria_label:'Insertion commands', padding:'8px 12px', border_top:'1px solid var(--gramlot-border)'});
|
|
96
|
+
bar.spacer({flex:1});
|
|
97
|
+
const buttons = bar.menuline({group:true, overflowable:false, gap:'8px'});
|
|
98
|
+
buttons.button('Cancel', {action:"this.SET('.insertionOpen', false)"});
|
|
99
|
+
buttons.button('Insert', {action:'insertWidget'});
|
|
100
|
+
const settings = pane.floatingPane({title:'Appearance', open:'^.appearanceOpen', default_open:false, width:'280px', height:'260px', movable:true, resizable:true});
|
|
101
|
+
const form = settings.frame.center.formlet({columns:1, lbl_position:'TL', gap:'10px', padding:'12px'});
|
|
102
|
+
form.filteringSelect({validate_notnull:true, lbl:'Theme', value:'^.appearanceProfile', values:'base:Base,compact:Compact,mimi:Mimi,joanna:Joanna,mela:Mela'});
|
|
103
|
+
form.filteringSelect({validate_notnull:true, lbl:'Colors', value:'^.appearancePalette', values:'default:Theme default,compact:Blue & slate,mimi:Sage & green,joanna:Warm gray & blue'});
|
|
104
|
+
form.filteringSelect({validate_notnull:true, lbl:'Mode', value:'^.appearanceMode', values:'light:Light,dark:Dark'});
|
|
105
|
+
pane.p('^.error', {role:'alert', class:'visual-editor-error', hidden:'^.error:=!{}'});
|
|
106
|
+
this.frame = layoutRoot; this.toolbar = toolbar; this.design = design;
|
|
107
|
+
if (codeDocument !== null) this.codeDocument(codeDocument);
|
|
108
|
+
}
|
|
109
|
+
toolButton(parent, caption, action, icon, attributes = {}) {
|
|
110
|
+
const button = parent.button({aria_label:caption, title:caption, action, class:'button--quiet visual-editor-tool', ...attributes});
|
|
111
|
+
button.span({class:'visual-tool-icon', aria_hidden:'true', style:`mask-image:url("${icon}")`});
|
|
112
|
+
return button;
|
|
113
|
+
}
|
|
114
|
+
codeDocument(document, frame = this.frame) {
|
|
115
|
+
if (!['python', 'javascript'].includes(document.language)) throw new TypeError('Expected a Python or JavaScript page document');
|
|
116
|
+
const pane = this.pane;
|
|
117
|
+
pane.setAttr({codeDocumentKey:document.key});
|
|
118
|
+
pane.dataSetter({destination_path:'.codeDocument', value:new Bag({...document, saved:document.content, busy:false, status:''})});
|
|
119
|
+
const anchor = `#${pane.getAttr('visualEditorId')}Editor`;
|
|
120
|
+
const opener = frame === this.frame ? this.toolbar : frame.top.menu({presentation:'bar', aria_label:'Code drawer'});
|
|
121
|
+
opener.menuline({group:true, overflowable:false}).button('Code', {action:'openCode', class:'button--quiet'});
|
|
122
|
+
const drawer = frame.right;
|
|
123
|
+
drawer.setAttr({datapath:anchor, title:'Page code', detachable:true, width:'60%', minSize:240, splitter:true,
|
|
124
|
+
drawer:'^.codeOpen', default_drawer:'close', drawer_label:'Code', drawer_minimize:false,
|
|
125
|
+
drawer_onclick:"this.SET('.codeOpen', show ? true : 'close')", min_height:0, overflow:'hidden'});
|
|
126
|
+
const code = drawer.framePane({height:'100%', width:'100%', min_width:0, flex:1});
|
|
127
|
+
code.top.setAttr({height:'32px'}); code.bottom.setAttr({height:'58px'});
|
|
128
|
+
code.center.setAttr({display:'flex', flex_direction:'column', min_height:0, overflow:'hidden'});
|
|
129
|
+
code.top.div(document.path, {padding:'8px 12px', font_size:'12px', overflow:'hidden', text_overflow:'ellipsis', white_space:'nowrap'});
|
|
130
|
+
code.center.codeMirror({value:'^.codeDocument.content', language:document.language, live:true, readonly:'^.codeDocument.writable:=!{}', height:'100%', box_height:'100%', box_c_height:'100%', box_min_height:0, box_c_min_height:0, fontSize:13, flex:1, min_height:0});
|
|
131
|
+
code.bottom.div('^.codeDocument.status', {role:'status', font_size:'12px', padding:'4px 10px'});
|
|
132
|
+
const bar = code.bottom.menu({presentation:'bar', aria_label:'Page code commands', padding:'6px 10px'});
|
|
133
|
+
bar.spacer({flex:1});
|
|
134
|
+
const commands = bar.menuline({group:true, overflowable:false, gap:'6px'});
|
|
135
|
+
commands.button('Close', {action:"this.SET('.codeOpen', 'close')"});
|
|
136
|
+
commands.button('Preview saved', {action:'codePreview', disabled:'^.codeDocument.busy'});
|
|
137
|
+
commands.button('Save', {action:'codeSave', disabled:'^.codeSaveDisabled'});
|
|
138
|
+
pane.dataFormula({result_path:'.codeSaveDisabled', formula:'!writable || busy || content === saved',
|
|
139
|
+
writable:'^.codeDocument.writable', busy:'^.codeDocument.busy', content:'^.codeDocument.content', saved:'^.codeDocument.saved', _init:true});
|
|
140
|
+
}
|
|
141
|
+
search(pane, path, label) {
|
|
142
|
+
const bar = pane.menu({presentation:'bar', aria_label:label, class:'visual-search-toolbar'});
|
|
143
|
+
const field = bar.menuline({group:true, overflowable:false, flex:1, min_width:0}).div({class:'visual-search-field'});
|
|
144
|
+
field.span({class:'visual-search-icon', aria_hidden:'true'});
|
|
145
|
+
field.input({type:'search', value:`^.${path}`, default:'', live:true, placeholder:label, aria_label:label});
|
|
146
|
+
field.html_button({type:'button', class:'visual-search-clear', aria_label:`Clear ${label.toLowerCase()}`,
|
|
147
|
+
hidden:`^.${path}:={} === ''`, connect_onclick:`this.SET('.${path}', '')`});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type {SourceBagNode} from '@genrojs/builders';
|
|
2
|
+
import type {GramlotRenderer} from './renderer/gramlot-renderer.js';
|
|
3
|
+
|
|
4
|
+
/** Reusable, lifecycle-bound selection of rendered Source nodes in an editor preview. */
|
|
5
|
+
export class SourcePicker {
|
|
6
|
+
constructor(options: {renderer: GramlotRenderer; root: SourceBagNode; onSelect: (node: SourceBagNode) => void});
|
|
7
|
+
select(node: SourceBagNode | null): void;
|
|
8
|
+
dispose(): void;
|
|
9
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** Select rendered Source descendants in an editor preview without activating them. */
|
|
2
|
+
export class SourcePicker {
|
|
3
|
+
#renderer; #root; #canvas; #onSelect; #observer; #selectedPath = null;
|
|
4
|
+
#highlighted = null; #release = null; #disposed = false;
|
|
5
|
+
constructor({renderer, root, onSelect}) {
|
|
6
|
+
if (!root?.parentNode || typeof onSelect !== 'function') throw new TypeError('SourcePicker requires a mounted Source root and onSelect');
|
|
7
|
+
const canvas = renderer.records.get(root.parentNode)?.presentation;
|
|
8
|
+
if (!canvas || canvas.nodeType !== 1) throw new TypeError('SourcePicker requires a mounted preview');
|
|
9
|
+
this.#renderer = renderer; this.#root = root; this.#canvas = canvas; this.#onSelect = onSelect;
|
|
10
|
+
canvas.addEventListener('pointerdown', this, true);
|
|
11
|
+
canvas.addEventListener('click', this, true);
|
|
12
|
+
this.#observer = new canvas.ownerDocument.defaultView.MutationObserver(() => this.#paint());
|
|
13
|
+
this.#observer.observe(canvas, {subtree:true, childList:true, attributes:true, attributeFilter:['class']});
|
|
14
|
+
this.#release = renderer.onDispose(root.parentNode, () => this.dispose());
|
|
15
|
+
}
|
|
16
|
+
handleEvent(event) {
|
|
17
|
+
if (this.#disposed) return;
|
|
18
|
+
const prefix = this.#root.fullpath + '.';
|
|
19
|
+
const record = event.composedPath().map(element => this.#renderer.elements.get(element)).find(item =>
|
|
20
|
+
item?.node.fullpath.startsWith(prefix));
|
|
21
|
+
if (!record) return;
|
|
22
|
+
const editing = event.composedPath().some(element => element.nodeType === 1 && (
|
|
23
|
+
element.matches('input:not([type=button]):not([type=submit]):not([type=reset]):not([type=image]), textarea, select, label') ||
|
|
24
|
+
element.isContentEditable));
|
|
25
|
+
if (!editing) { event.preventDefault(); event.stopImmediatePropagation(); }
|
|
26
|
+
this.#onSelect(record.node);
|
|
27
|
+
}
|
|
28
|
+
select(node) {
|
|
29
|
+
if (this.#disposed) return;
|
|
30
|
+
if (node === null) this.#selectedPath = null;
|
|
31
|
+
else {
|
|
32
|
+
const prefix = this.#root.fullpath + '.';
|
|
33
|
+
if (!node.fullpath.startsWith(prefix)) throw new TypeError('Selected node must be inside the preview Source root');
|
|
34
|
+
this.#selectedPath = node.fullpath.slice(prefix.length);
|
|
35
|
+
}
|
|
36
|
+
this.#paint();
|
|
37
|
+
}
|
|
38
|
+
#paint() {
|
|
39
|
+
if (this.#disposed) return;
|
|
40
|
+
const node = this.#selectedPath ? this.#root.staticValue.getNode(this.#selectedPath) : null;
|
|
41
|
+
const element = node ? this.#renderer.records.get(node)?.presentation : null;
|
|
42
|
+
const next = element?.nodeType === 1 ? element : null;
|
|
43
|
+
if (this.#highlighted !== next) {
|
|
44
|
+
this.#highlighted?.classList.remove('gramlot-source-selected');
|
|
45
|
+
this.#highlighted = next;
|
|
46
|
+
}
|
|
47
|
+
if (next && !next.classList.contains('gramlot-source-selected')) next.classList.add('gramlot-source-selected');
|
|
48
|
+
}
|
|
49
|
+
dispose() {
|
|
50
|
+
if (this.#disposed) return;
|
|
51
|
+
this.#disposed = true; this.#observer.disconnect();
|
|
52
|
+
this.#canvas.removeEventListener('pointerdown', this, true);
|
|
53
|
+
this.#canvas.removeEventListener('click', this, true);
|
|
54
|
+
this.#highlighted?.classList.remove('gramlot-source-selected');
|
|
55
|
+
this.#release?.(); this.#release = null; this.#highlighted = null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import {Bag} from '@genrojs/bag';
|
|
2
|
+
|
|
3
|
+
/** Shared resident data. Ordering and filtering belong to each consuming view. */
|
|
4
|
+
export class BagCollectionStore {
|
|
5
|
+
#listeners = new Set();
|
|
6
|
+
constructor(bag, rowMode) {
|
|
7
|
+
if (!(bag instanceof Bag)) throw new TypeError('collection store requires a Bag');
|
|
8
|
+
if (!['values','attributes'].includes(rowMode)) throw new TypeError('collection store rowMode must explicitly be values or attributes');
|
|
9
|
+
if (!bag.parentNode) throw new TypeError('collection store requires a Bag attached to Data');
|
|
10
|
+
this.bag = bag;
|
|
11
|
+
this.rowMode = rowMode;
|
|
12
|
+
}
|
|
13
|
+
subscribe(listener) {
|
|
14
|
+
this.#listeners.add(listener);
|
|
15
|
+
return () => this.#listeners.delete(listener);
|
|
16
|
+
}
|
|
17
|
+
/** Called by the page's single Data subscription. Each view reconciles independently. */
|
|
18
|
+
receiveData(event, row = null) {
|
|
19
|
+
publishCollection(this.#listeners, {full:row === null, rows:row ? [row] : []});
|
|
20
|
+
}
|
|
21
|
+
getRows() {
|
|
22
|
+
const nodes = this.bag.getNodes();
|
|
23
|
+
for (const node of nodes) {
|
|
24
|
+
if (node.resolver) throw new TypeError('collection store requires loaded rows');
|
|
25
|
+
if (this.rowMode === 'values' && !(node.staticValue instanceof Bag)) {
|
|
26
|
+
throw new TypeError(`collection store row ${node.label} must contain a Bag`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return nodes;
|
|
30
|
+
}
|
|
31
|
+
value(node, field) {
|
|
32
|
+
if (node.resolver) throw new TypeError('collection store requires loaded rows');
|
|
33
|
+
if (this.rowMode === 'attributes') return node.getAttr(field);
|
|
34
|
+
const row = node.staticValue;
|
|
35
|
+
if (!(row instanceof Bag)) throw new TypeError(`collection store row ${node.label} must contain a Bag`);
|
|
36
|
+
const cell = row.getNode(field);
|
|
37
|
+
if (cell?.resolver) throw new TypeError('collection store requires loaded cells');
|
|
38
|
+
return cell?.staticValue;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One invalidation protocol at both collection levels; failures cannot skip siblings. */
|
|
43
|
+
export function publishCollection(listeners, change) {
|
|
44
|
+
const errors = [];
|
|
45
|
+
const notice = Object.freeze({full:change.full, rows:Object.freeze([...change.rows])});
|
|
46
|
+
for (const listener of [...listeners]) {
|
|
47
|
+
if (!listeners.has(listener)) continue;
|
|
48
|
+
try { listener(notice); } catch (error) { errors.push(error); }
|
|
49
|
+
}
|
|
50
|
+
if (errors.length) throw new AggregateError(errors, 'Collection notification failed');
|
|
51
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import {isDecimal} from '@genrojs/tytx';
|
|
2
|
+
import {compileFilter} from './collection-filter.js';
|
|
3
|
+
import {publishCollection} from './bag-collection-store.js';
|
|
4
|
+
|
|
5
|
+
/** Source-owned view: original BagNodes, independent indices and criteria. */
|
|
6
|
+
export class BagCollectionView {
|
|
7
|
+
#store;
|
|
8
|
+
#release = null;
|
|
9
|
+
#listeners = new Set();
|
|
10
|
+
#indices = new Map();
|
|
11
|
+
#sortedBy = '';
|
|
12
|
+
#filter = null;
|
|
13
|
+
#predicate = null;
|
|
14
|
+
#filtered = null;
|
|
15
|
+
constructor(store) { this.bindStore(store); }
|
|
16
|
+
get bag() { return this.#store.bag; }
|
|
17
|
+
get rowMode() { return this.#store.rowMode; }
|
|
18
|
+
get sortedBy() { return this.#sortedBy; }
|
|
19
|
+
get criteria() { return parseSort(this.#sortedBy); }
|
|
20
|
+
get filter() { return this.#filter; }
|
|
21
|
+
get filtered() { return this.#filtered === null ? null : [...this.#filtered]; }
|
|
22
|
+
isFiltered() { return this.#filtered !== null; }
|
|
23
|
+
value(node, field) { return this.#store.value(node, field); }
|
|
24
|
+
subscribe(listener) {
|
|
25
|
+
this.#listeners.add(listener);
|
|
26
|
+
return () => this.#listeners.delete(listener);
|
|
27
|
+
}
|
|
28
|
+
connect() {
|
|
29
|
+
if (this.#release) return;
|
|
30
|
+
this.synchronize();
|
|
31
|
+
this.#release = this.#store.subscribe(change => this.synchronize(change));
|
|
32
|
+
}
|
|
33
|
+
disconnect() { this.#release?.(); this.#release = null; }
|
|
34
|
+
bindStore(store) {
|
|
35
|
+
if (this.#store === store) return;
|
|
36
|
+
const connected = this.#release !== null;
|
|
37
|
+
this.disconnect();
|
|
38
|
+
this.#store = store;
|
|
39
|
+
// Only node identities are retained, never cell values. A replacement Bag
|
|
40
|
+
// keeps this widget's criteria but starts a fresh manual index.
|
|
41
|
+
this.#indices.clear();
|
|
42
|
+
if (connected) this.connect(); else this.synchronize();
|
|
43
|
+
}
|
|
44
|
+
getRows(filtered = true) {
|
|
45
|
+
const nodes = this.#orderedNodes();
|
|
46
|
+
return filtered && this.#filtered !== null ? this.#filtered.map(index => nodes[index]) : nodes;
|
|
47
|
+
}
|
|
48
|
+
#orderedNodes() {
|
|
49
|
+
return this.#store.getRows().toSorted((a,b) => (this.#indices.get(a) ?? Infinity) - (this.#indices.get(b) ?? Infinity));
|
|
50
|
+
}
|
|
51
|
+
synchronize(change = {full:true, rows:[]}) {
|
|
52
|
+
if (!change.full && !this.#sortedBy && !this.#predicate) {
|
|
53
|
+
publishCollection(this.#listeners,change);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
this.#commit(this.#sorted(this.#orderedNodes(),this.criteria),this.#sortedBy,this.#filter,this.#predicate,change);
|
|
57
|
+
}
|
|
58
|
+
sort(sortedBy) {
|
|
59
|
+
const nodes = this.#sorted(this.#orderedNodes(),parseSort(sortedBy));
|
|
60
|
+
this.#commit(nodes,sortedBy,this.#filter,this.#predicate);
|
|
61
|
+
}
|
|
62
|
+
moveRow(node, target, after = false) {
|
|
63
|
+
if (node === target || node.parentBag !== this.bag || target.parentBag !== this.bag) return;
|
|
64
|
+
const nodes = this.getRows(false);
|
|
65
|
+
nodes.splice(nodes.indexOf(node),1);
|
|
66
|
+
nodes.splice(nodes.indexOf(target)+Number(after),0,node);
|
|
67
|
+
this.#commit(nodes,'',this.#filter,this.#predicate);
|
|
68
|
+
}
|
|
69
|
+
applyFilter(filter) {
|
|
70
|
+
// The accepted definition is immutable Source-owned state. Invalid drafts
|
|
71
|
+
// cannot replace it, the predicate or the visible index.
|
|
72
|
+
const definition = filter === null ? null : Object.freeze({...filter,columns:Object.freeze([...filter.columns])});
|
|
73
|
+
const predicate = compileFilter(definition);
|
|
74
|
+
this.#commit(this.#orderedNodes(),this.#sortedBy,definition,predicate);
|
|
75
|
+
}
|
|
76
|
+
#commit(nodes, sortedBy, filter, predicate, change = {full:false, rows:[]}) {
|
|
77
|
+
const filtered = predicate ? nodes.flatMap((node,index) => predicate(field => this.value(node,field)) ? [index] : []) : null;
|
|
78
|
+
const full = change.full || sortedBy !== this.#sortedBy || JSON.stringify(filter) !== JSON.stringify(this.#filter) ||
|
|
79
|
+
nodes.length !== this.#indices.size || nodes.some((node,index) => this.#indices.get(node) !== index) ||
|
|
80
|
+
JSON.stringify(filtered) !== JSON.stringify(this.#filtered);
|
|
81
|
+
this.#indices = new Map(nodes.map((node,index) => [node,index]));
|
|
82
|
+
this.#sortedBy = sortedBy; this.#filter = filter; this.#predicate = predicate; this.#filtered = filtered;
|
|
83
|
+
const visible = filtered === null ? null : new Set(filtered);
|
|
84
|
+
const rows = full ? [] : change.rows.filter(node => this.#indices.has(node) && (visible === null || visible.has(this.#indices.get(node))));
|
|
85
|
+
if (full || rows.length) publishCollection(this.#listeners,{full,rows});
|
|
86
|
+
}
|
|
87
|
+
#sorted(nodes, criteria) {
|
|
88
|
+
if (!criteria.length) return nodes;
|
|
89
|
+
const keyed = nodes.map(node => ({node,keys:criteria.map(({field}) => this.value(node,field))}));
|
|
90
|
+
for (let index=0; index<criteria.length; index++) {
|
|
91
|
+
const kinds = new Set(keyed.map(row => scalarKind(row.keys[index])).filter(kind => kind !== null));
|
|
92
|
+
if (kinds.size > 1) throw new TypeError(`collection view cannot compare mixed types in ${criteria[index].field}`);
|
|
93
|
+
}
|
|
94
|
+
return keyed.sort((a,b) => {
|
|
95
|
+
for (const [index,{direction}] of criteria.entries()) {
|
|
96
|
+
const result = compare(a.keys[index],b.keys[index]);
|
|
97
|
+
if (result) return direction === 'a' ? result : -result;
|
|
98
|
+
}
|
|
99
|
+
return 0;
|
|
100
|
+
}).map(row => row.node);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function parseSort(sortedBy) {
|
|
105
|
+
if (typeof sortedBy !== 'string') throw new TypeError('collection view sortedBy must be a string');
|
|
106
|
+
if (sortedBy === '') return [];
|
|
107
|
+
const seen = new Set();
|
|
108
|
+
return sortedBy.split(',').map(item => {
|
|
109
|
+
const match = /^([^,:]+):([ad])$/.exec(item);
|
|
110
|
+
if (!match || seen.has(match[1])) throw new TypeError(`Invalid collection view sort criterion: ${item}`);
|
|
111
|
+
seen.add(match[1]);
|
|
112
|
+
return {field:match[1], direction:match[2]};
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
function scalarKind(value) {
|
|
116
|
+
if (value == null) return null;
|
|
117
|
+
if (typeof value === 'number' && Number.isFinite(value) || isDecimal(value) && value.isFinite()) return 'number';
|
|
118
|
+
if (value instanceof Date && Number.isFinite(value.getTime())) return 'date';
|
|
119
|
+
if (typeof value === 'string' || typeof value === 'boolean') return typeof value;
|
|
120
|
+
throw new TypeError('collection view sort requires loaded finite scalar values');
|
|
121
|
+
}
|
|
122
|
+
function compare(a, b) {
|
|
123
|
+
if (a == null || b == null) return a == null ? (b == null ? 0 : -1) : 1;
|
|
124
|
+
if (isDecimal(a)) return a.comparedTo(b);
|
|
125
|
+
if (isDecimal(b)) return -b.comparedTo(a);
|
|
126
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
127
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import {createDecimal, isDecimal} from '@genrojs/tytx';
|
|
2
|
+
import {parseDateExpression} from '@genrojs/toolbox';
|
|
3
|
+
import {formatValue} from '../format.js';
|
|
4
|
+
|
|
5
|
+
/** Legacy search syntax, independent of grid DOM and collection ordering. */
|
|
6
|
+
export function compileFilter(filter) {
|
|
7
|
+
if (filter === null) return null;
|
|
8
|
+
const {value, columns, dtype, locale} = filter;
|
|
9
|
+
if (typeof value !== 'string' || !Array.isArray(columns) || !columns.length ||
|
|
10
|
+
columns.some(field => typeof field !== 'string' || !field || field === 'rowidx') ||
|
|
11
|
+
!['T', 'L', 'R', 'N', 'D'].includes(dtype)) throw new TypeError('Invalid collection filter');
|
|
12
|
+
if (!value.trim()) return null;
|
|
13
|
+
if (dtype === 'T') {
|
|
14
|
+
const expression = new RegExp(value, 'i');
|
|
15
|
+
return read => expression.test(columns.map(field => searchText(read(field), locale, filter.timeZone)).join(' '));
|
|
16
|
+
}
|
|
17
|
+
if (columns.length !== 1) throw new TypeError('Typed filters require one column');
|
|
18
|
+
const match = /^\s*(<=|>=|==|!=|[<>=!#])\s*(.+?)\s*$/.exec(value);
|
|
19
|
+
if (!match) throw new Error('Enter a comparison, for example > 100 or = 12.');
|
|
20
|
+
const [, operator, text] = match;
|
|
21
|
+
let operand;
|
|
22
|
+
if (dtype === 'D') {
|
|
23
|
+
const now = new Date();
|
|
24
|
+
const workdate = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')}`;
|
|
25
|
+
const parsed = parseDateExpression(text, {locale, workdate});
|
|
26
|
+
if (!parsed.ok || parsed.kind !== 'date') throw new Error('Enter one complete date after the comparison.');
|
|
27
|
+
operand = new Date(`${parsed.date}T00:00:00Z`);
|
|
28
|
+
} else operand = parseNumber(text, locale);
|
|
29
|
+
return read => {
|
|
30
|
+
const actual = read(columns[0]);
|
|
31
|
+
if (actual == null) return false;
|
|
32
|
+
if (dtype === 'D' ? !(actual instanceof Date) || !Number.isFinite(actual.getTime())
|
|
33
|
+
: !(typeof actual === 'number' && Number.isFinite(actual) || isDecimal(actual) && actual.isFinite())) {
|
|
34
|
+
throw new TypeError(`Filter value does not match ${dtype}`);
|
|
35
|
+
}
|
|
36
|
+
const order = isDecimal(operand) ? -operand.comparedTo(actual) : actual < operand ? -1 : actual > operand ? 1 : 0;
|
|
37
|
+
switch (operator) {
|
|
38
|
+
case '=': case '==': return order === 0;
|
|
39
|
+
case '!': case '#': case '!=': return order !== 0;
|
|
40
|
+
case '<': return order < 0;
|
|
41
|
+
case '>': return order > 0;
|
|
42
|
+
case '<=': return order <= 0;
|
|
43
|
+
case '>=': return order >= 0;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function searchText(value, locale, timeZone) {
|
|
49
|
+
if (value == null) return '';
|
|
50
|
+
if (typeof value === 'string' || typeof value === 'boolean') return String(value);
|
|
51
|
+
return formatValue(value, {pattern:value instanceof Date ? 'short' : '#,##0.####################'}, {locale, timeZone});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function parseNumber(text, locale) {
|
|
55
|
+
const parts = new Intl.NumberFormat(locale).formatToParts(-12345.6);
|
|
56
|
+
const decimal = parts.find(part => part.type === 'decimal').value;
|
|
57
|
+
const group = parts.find(part => part.type === 'group')?.value;
|
|
58
|
+
const minus = parts.find(part => part.type === 'minusSign').value;
|
|
59
|
+
let number = text.replaceAll(minus, '-');
|
|
60
|
+
if (group && number.includes(group)) {
|
|
61
|
+
const integer = number.split(decimal)[0].replace(/^[+-]/, '');
|
|
62
|
+
const groups = integer.split(group);
|
|
63
|
+
const sizes = new Intl.NumberFormat(locale).formatToParts(1234567890123).filter(part => part.type === 'integer').map(part => part.value.length);
|
|
64
|
+
const last = sizes.at(-1), middle = sizes.at(-2);
|
|
65
|
+
if (number.split(decimal).slice(1).some(part => part.includes(group)) ||
|
|
66
|
+
!/^\d+$/.test(groups[0]) || groups[0].length > middle ||
|
|
67
|
+
groups.slice(1).some((item,index) => !/^\d+$/.test(item) || item.length !== (index === groups.length - 2 ? last : middle))) {
|
|
68
|
+
throw new Error('Invalid numeric grouping.');
|
|
69
|
+
}
|
|
70
|
+
number = number.replaceAll(group, '');
|
|
71
|
+
}
|
|
72
|
+
number = number.replace(decimal, '.');
|
|
73
|
+
if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(number)) throw new Error('Enter a complete number.');
|
|
74
|
+
const result = createDecimal(number);
|
|
75
|
+
if (!isDecimal(result) || !result.isFinite()) throw new Error('A finite Decimal backend is required.');
|
|
76
|
+
return result;
|
|
77
|
+
}
|