@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.
Files changed (172) hide show
  1. package/dist/components/chat/__init__.py +13 -0
  2. package/dist/components/chat/assets/collection.js +9 -0
  3. package/dist/components/chat/assets/index.js +3 -0
  4. package/dist/components/chat/commands.json +7 -0
  5. package/dist/components/chat/grammar.json +48 -0
  6. package/dist/components/editors/__init__.py +2 -2
  7. package/dist/components/editors/assets/collection.js +26 -120912
  8. package/dist/components/editors/assets/index.js +2 -1
  9. package/dist/components/editors/assets/modules/chunk-74O4WKIV.js +1 -0
  10. package/dist/components/editors/assets/modules/chunk-AU4HFPIY.js +1 -0
  11. package/dist/components/editors/assets/modules/chunk-YSGSC7KM.js +1 -0
  12. package/dist/components/editors/assets/modules/code-mirror-engine-RWQTR5G5.js +92 -0
  13. package/dist/components/editors/assets/modules/jodit-engine-MTSA4GZ3.js +1853 -0
  14. package/dist/components/editors/assets/modules/markdown-document-VFC23FAY.js +1 -0
  15. package/dist/components/editors/assets/modules/prose-mirror-engine-GMZPJPNN.js +24 -0
  16. package/dist/components/grid/__init__.py +14 -0
  17. package/dist/components/grid/assets/collection.js +262 -0
  18. package/dist/components/grid/assets/index.js +3 -0
  19. package/dist/components/grid/commands.json +7 -0
  20. package/dist/components/grid/grammar.json +770 -0
  21. package/dist/components/grouplets/__init__.py +13 -0
  22. package/dist/components/grouplets/assets/collection.js +185 -0
  23. package/dist/components/grouplets/assets/index.js +3 -0
  24. package/dist/components/grouplets/assets/modules/chunk-BLMUM44K.js +1 -0
  25. package/dist/components/grouplets/assets/modules/markdown-document-YWNZTOKK.js +1 -0
  26. package/dist/components/grouplets/commands.json +7 -0
  27. package/dist/components/grouplets/grammar.json +355 -0
  28. package/dist/components/inputs/__init__.py +1 -1
  29. package/dist/components/inputs/assets/collection.js +65 -24511
  30. package/dist/components/inputs/assets/index.js +2 -1
  31. package/dist/components/inputs/grammar.json +278 -6
  32. package/dist/components/layout/__init__.py +1 -1
  33. package/dist/components/layout/assets/collection.js +68 -26732
  34. package/dist/components/layout/assets/index.js +2 -1
  35. package/dist/components/layout/grammar.json +39 -0
  36. package/dist/components/selection_trial/__init__.py +13 -0
  37. package/dist/components/selection_trial/assets/collection.js +4 -0
  38. package/dist/components/selection_trial/assets/index.js +3 -0
  39. package/dist/components/selection_trial/commands.json +7 -0
  40. package/dist/components/selection_trial/grammar.json +587 -0
  41. package/dist/components/tree/__init__.py +1 -1
  42. package/dist/components/tree/assets/collection.js +27 -24612
  43. package/dist/components/tree/assets/index.js +2 -1
  44. package/dist/components/tree/grammar.json +341 -1
  45. package/dist/components/typst/__init__.py +2 -2
  46. package/dist/components/typst/assets/collection.js +12 -4
  47. package/dist/components/typst/assets/index.js +2 -1
  48. package/dist/components/typst/assets/modules/chunk-BLMUM44K.js +1 -0
  49. package/dist/components/typst/assets/modules/typst-client-JHC6UVYG.js +4 -0
  50. package/dist/components/uploads/__init__.py +13 -0
  51. package/dist/components/uploads/assets/collection.js +67 -0
  52. package/dist/components/uploads/assets/index.js +3 -0
  53. package/dist/components/uploads/commands.json +7 -0
  54. package/dist/components/uploads/grammar.json +789 -0
  55. package/dist/gramlot-markdown.js +16 -0
  56. package/dist/gramlot.js +6861 -1395
  57. package/dist/gramlot.min.js +1595 -46
  58. package/dist/runtime-notices.json +28 -0
  59. package/package.json +10 -3
  60. package/src/binding/grid-struct.js +63 -0
  61. package/src/binding/installation.js +5 -2
  62. package/src/binding/providers.js +4 -1
  63. package/src/binding/remote-resolver.js +1 -8
  64. package/src/binding/runtime.js +90 -6
  65. package/src/binding/validation-context.js +40 -0
  66. package/src/browser-camera-provider.d.ts +8 -0
  67. package/src/browser-camera-provider.js +104 -0
  68. package/src/builder/gramlot-builder.d.ts +5 -0
  69. package/src/builder/gramlot-builder.js +16 -0
  70. package/src/builder/source.js +34 -0
  71. package/src/chat.d.ts +12 -0
  72. package/src/chat.js +198 -0
  73. package/src/collection-artifact.js +1 -1
  74. package/src/components/attachment-manager.js +160 -0
  75. package/src/components/bases.js +19 -6
  76. package/src/components/border-container.js +86 -8
  77. package/src/components/buttons.js +11 -1
  78. package/src/components/chat.js +28 -0
  79. package/src/components/choice-editor.js +106 -38
  80. package/src/components/database-choices.js +133 -9
  81. package/src/components/editing-status-styles.js +26 -0
  82. package/src/components/editing-status.js +115 -0
  83. package/src/components/field-state.js +42 -54
  84. package/src/components/grid-cell-editor.js +181 -0
  85. package/src/components/grid-grammar.json +258 -0
  86. package/src/components/grid-header-interaction.js +196 -0
  87. package/src/components/grid-row-interaction.js +184 -0
  88. package/src/components/grid-row-layout.js +96 -0
  89. package/src/components/grid-rows.js +28 -0
  90. package/src/components/grid-search-box.js +142 -0
  91. package/src/components/grid-search-styles.js +42 -0
  92. package/src/components/grid-search.js +37 -0
  93. package/src/components/grid-structure.js +85 -0
  94. package/src/components/grid-styles.js +201 -0
  95. package/src/components/grid.js +666 -0
  96. package/src/components/grouplet-card.js +445 -0
  97. package/src/components/grouplets.js +17 -0
  98. package/src/components/html-preview.js +17 -4
  99. package/src/components/image-crop-dialog.js +272 -0
  100. package/src/components/image-crop.js +79 -0
  101. package/src/components/image-uploader.js +252 -0
  102. package/src/components/inputs.js +2 -1
  103. package/src/components/jodit-engine.js +1 -1
  104. package/src/components/markdown-document.js +2 -2
  105. package/src/components/menus.js +1 -0
  106. package/src/components/registry.js +4 -3
  107. package/src/components/screen-capture.js +43 -0
  108. package/src/components/selected-container.js +6 -2
  109. package/src/components/tray-pane.js +32 -4
  110. package/src/components/tree.js +416 -17
  111. package/src/components/typed-editor.js +23 -11
  112. package/src/components/upload-engine.js +156 -0
  113. package/src/components/uploader.js +208 -0
  114. package/src/components/uploads.js +7 -0
  115. package/src/editing-session.d.ts +25 -0
  116. package/src/editing-session.js +396 -0
  117. package/src/experiments/selection-transfer.js +78 -0
  118. package/src/experiments/selection-trial.js +64 -0
  119. package/src/experiments/window-selection.js +124 -0
  120. package/src/format.js +22 -7
  121. package/src/gramlot.d.ts +2 -0
  122. package/src/gramlot.js +2 -1
  123. package/src/handlers/device-handler.d.ts +2 -1
  124. package/src/handlers/rpc-handler.d.ts +3 -3
  125. package/src/index-page-styles.js +2 -1
  126. package/src/index.d.ts +16 -1
  127. package/src/index.js +16 -1
  128. package/src/inout.d.ts +2 -0
  129. package/src/inout.js +6 -0
  130. package/src/markdown-loader.d.ts +1 -0
  131. package/src/markdown-loader.js +4 -0
  132. package/src/markdown.d.ts +1 -0
  133. package/src/markdown.js +2 -0
  134. package/src/media-frame.js +9 -0
  135. package/src/renderer/attributes.js +7 -1
  136. package/src/renderer/gramlot-renderer.d.ts +2 -0
  137. package/src/renderer/gramlot-renderer.js +39 -3
  138. package/src/server/assets.d.ts +1 -1
  139. package/src/server/assets.js +1 -1
  140. package/src/server/gramlot-server.d.ts +10 -1
  141. package/src/server/gramlot-server.js +96 -8
  142. package/src/server/index.d.ts +2 -0
  143. package/src/server/index.js +2 -0
  144. package/src/server/page-base.js +17 -4
  145. package/src/server/page.d.ts +13 -1
  146. package/src/server/page.js +6 -0
  147. package/src/server/source-import.d.ts +2 -0
  148. package/src/server/source-import.js +31 -0
  149. package/src/server/upload.d.ts +20 -0
  150. package/src/server/upload.js +142 -0
  151. package/src/server/visual-editor.d.ts +11 -0
  152. package/src/server/visual-editor.js +149 -0
  153. package/src/source-picker.d.ts +9 -0
  154. package/src/source-picker.js +57 -0
  155. package/src/stores/bag-collection-store.js +51 -0
  156. package/src/stores/bag-collection-view.js +127 -0
  157. package/src/stores/collection-filter.js +77 -0
  158. package/src/tree-store.d.ts +24 -0
  159. package/src/tree-store.js +193 -0
  160. package/src/validation-run.js +50 -0
  161. package/src/view/button.js +8 -5
  162. package/src/view/controls.js +31 -32
  163. package/src/view/grouplet-card.js +54 -0
  164. package/src/view/html.js +29 -4
  165. package/src/view/labelbox.js +7 -3
  166. package/src/visual-editor-icons.js +10 -0
  167. package/src/visual-editor.d.ts +56 -0
  168. package/src/visual-editor.js +844 -0
  169. package/themes/gramlot-base/theme.css +127 -0
  170. package/themes/gramlot-compact/theme.css +8 -0
  171. package/themes/joanna/theme.css +8 -0
  172. package/themes/mimi/theme.css +8 -0
@@ -0,0 +1,104 @@
1
+ import {captureVideoFrame} from './media-frame.js';
2
+
3
+ /** Browser implementation of the existing device camera capability. */
4
+ function failure(code, message, cause) {
5
+ return Object.assign(new Error(message, cause ? {cause} : undefined), {code});
6
+ }
7
+ function cameraError(error) {
8
+ if (error.name === 'NotAllowedError' || error.name === 'SecurityError') return failure('PERMISSION_DENIED','Camera permission was denied',error);
9
+ if (error.name === 'NotFoundError' || error.name === 'OverconstrainedError') return failure('UNAVAILABLE','Camera is unavailable',error);
10
+ return failure('FAILED',error.message || 'Camera failed',error);
11
+ }
12
+ const cancelled = () => failure('CANCELLED','Photo capture cancelled');
13
+
14
+ export class BrowserCameraProvider {
15
+ constructor({document}) {
16
+ if (!document?.defaultView) throw new TypeError('BrowserCameraProvider requires a document');
17
+ this.document = document;
18
+ this.capabilities = Object.freeze(document.defaultView.navigator.mediaDevices?.getUserMedia ? ['camera'] : []);
19
+ }
20
+ takePhoto(signal) {
21
+ if (signal.aborted) return Promise.reject(cancelled());
22
+ if (!this.capabilities.includes('camera')) return Promise.reject(failure('UNAVAILABLE','Camera is unavailable'));
23
+ const doc=this.document, win=doc.defaultView;
24
+ return new Promise((resolve,reject) => {
25
+ let settled=false, stream=null;
26
+ const events=new win.AbortController(), listen={signal:events.signal};
27
+ const dialog=doc.createElement('dialog'); dialog.className='gramlot-camera-dialog'; dialog.setAttribute('aria-label','Take photo');
28
+ const style=doc.createElement('style'); style.textContent=`
29
+ .gramlot-camera-dialog{max-width:calc(100vw - 2rem);max-height:calc(100vh - 2rem);border:1px solid var(--gramlot-border,#d5dde6);
30
+ border-radius:14px;padding:20px;color:var(--gramlot-ink,#202a35);background:var(--gramlot-surface,#fff);
31
+ box-shadow:0 24px 64px #14243a42;font:14px/1.4 system-ui,sans-serif}
32
+ .gramlot-camera-dialog::backdrop{background:#152335a6}.gramlot-camera-dialog h2{margin:0 0 12px;font-size:1.15rem}
33
+ .gramlot-camera-dialog video{display:block;width:min(480px,calc(100vw - 5rem));max-height:55vh;background:#202a35;border-radius:8px}
34
+ .gramlot-camera-dialog [role=status]{margin:8px 0;color:var(--gramlot-text-secondary,#62748a)}
35
+ .gramlot-camera-dialog .actions{display:flex;gap:8px;justify-content:flex-end;margin-top:14px}
36
+ .gramlot-camera-dialog button{font:inherit;cursor:pointer;padding:.4em .8em;border:1px solid var(--gramlot-border-control,#aab4c0);border-radius:6px;background:var(--gramlot-button-background,#fff);color:var(--gramlot-button-color,#202a35)}
37
+ .gramlot-camera-dialog button.primary{background:var(--gramlot-action,#3766b5);color:#fff}.gramlot-camera-dialog button:disabled{opacity:.55}
38
+ `;
39
+ const heading=doc.createElement('h2'); heading.textContent='Take photo';
40
+ const video=doc.createElement('video'); video.muted=true; video.autoplay=true; video.playsInline=true;
41
+ const status=doc.createElement('p'); status.setAttribute('role','status'); status.textContent='Waiting for camera…';
42
+ const actions=doc.createElement('div'); actions.className='actions';
43
+ const cancel=doc.createElement('button');cancel.type='button';cancel.textContent='Cancel';
44
+ const capture=doc.createElement('button');capture.type='button';capture.textContent='Capture';capture.className='primary';capture.disabled=true;
45
+ actions.append(cancel,capture);dialog.append(style,heading,video,status,actions);
46
+ const stop = value => { for (const track of value.getTracks()) track.stop(); };
47
+ const finish = (error, photo) => {
48
+ if (settled) return; settled=true; events.abort(); signal.removeEventListener('abort',onAbort);
49
+ if (stream) {stop(stream);stream=null;} video.srcObject=null;
50
+ if (dialog.open) dialog.close();dialog.remove();
51
+ if (error) reject(error); else resolve(photo);
52
+ };
53
+ const onAbort=()=>finish(cancelled());
54
+ signal.addEventListener('abort',onAbort,{once:true});
55
+ cancel.addEventListener('click',onAbort,listen);
56
+ dialog.addEventListener('cancel',event=>{event.preventDefault();onAbort();},listen);
57
+ dialog.addEventListener('close',()=>{if (!settled) onAbort();},listen);
58
+ const ready=()=>{if (!settled && video.videoWidth > 0 && video.videoHeight > 0) {capture.disabled=false;status.textContent='';}};
59
+ video.addEventListener('loadedmetadata',ready,listen);
60
+ capture.addEventListener('click',()=>{
61
+ try {
62
+ const canvas=captureVideoFrame(doc,video);
63
+ const url=canvas.toDataURL('image/jpeg',0.9);
64
+ if (!url.startsWith('data:image/jpeg;')) throw new Error('Camera image encoding failed');
65
+ finish(null,{url,format:'jpeg'});
66
+ } catch (error) {finish(cameraError(error));}
67
+ },listen);
68
+ doc.body.append(dialog);
69
+ try {dialog.showModal();} catch (error) {finish(cameraError(error));return;}
70
+ if (signal.aborted) {onAbort();return;}
71
+ Promise.resolve().then(()=>settled ? null : win.navigator.mediaDevices.getUserMedia({video:true,audio:false})).then(async acquired=>{
72
+ if (!acquired) return;
73
+ if (settled) {stop(acquired);return;}
74
+ stream=acquired;video.srcObject=stream;
75
+ for (const track of stream.getTracks()) track.addEventListener('ended',()=>finish(failure('UNAVAILABLE','Camera stopped')),listen);
76
+ try {await video.play();ready();} catch (error) {finish(cameraError(error));}
77
+ },error=>finish(cameraError(error)));
78
+ });
79
+ }
80
+ choosePhoto(signal) {
81
+ if (signal.aborted) return Promise.reject(cancelled());
82
+ const doc=this.document, win=doc.defaultView;
83
+ return new Promise((resolve,reject)=>{
84
+ let settled=false,reader=null;
85
+ const events=new win.AbortController(), listen={signal:events.signal};
86
+ const input=doc.createElement('input');input.type='file';input.accept='image/png,image/jpeg,image/webp';input.hidden=true;
87
+ const finish=(error,photo)=>{if(settled)return;settled=true;events.abort();signal.removeEventListener('abort',onAbort);
88
+ if (reader && reader.readyState === 1) reader.abort();input.remove();if(error)reject(error);else resolve(photo);};
89
+ const onAbort=()=>finish(cancelled());
90
+ signal.addEventListener('abort',onAbort,{once:true});
91
+ input.addEventListener('cancel',onAbort,listen);
92
+ input.addEventListener('change',()=>{
93
+ const file=input.files[0];
94
+ if (!file || !['image/png','image/jpeg','image/webp'].includes(file.type)) {finish(failure('FAILED','Select a PNG, JPEG or WebP image'));return;}
95
+ reader=new win.FileReader();
96
+ reader.onload=()=>finish(null,{url:reader.result,format:file.type.slice('image/'.length)});
97
+ reader.onerror=()=>finish(failure('FAILED','Photo could not be read',reader.error));reader.readAsDataURL(file);
98
+ },listen);
99
+ doc.body.append(input);
100
+ if (signal.aborted) {onAbort();return;}
101
+ try {input.click();} catch (error) {finish(failure('FAILED','Photo selection failed',error));}
102
+ });
103
+ }
104
+ }
@@ -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 = [];
@@ -1,3 +1,4 @@
1
+ import {EditingSession} from '../editing-session.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,30 @@ 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.#formState && owner._getMeta('gramlot_component')?.bagStore) return owner.#formState;
186
+ if (owner.getAttr('formId') != null || owner.getAttr('form') === true) {
187
+ const state = owner.#formState ??= new EditingSession(owner, this.rootBuilder.binding);
188
+ state.rebind();
189
+ return state;
190
+ }
191
+ }
192
+ return null;
193
+ }
194
+
195
+ editCollection(path) {
196
+ const parent = this.parentNode?.formState;
197
+ if (parent) {
198
+ if (path !== parent.path && !path.startsWith(parent.path + '.')) throw new Error('An edited grid in a form must use data within that form.');
199
+ return parent;
200
+ }
201
+ if (this.#formState && this.#formState.path !== path) throw new Error('An active grid editing session cannot change its storepath.');
202
+ return this.#formState ??= new EditingSession(this, this.rootBuilder.binding, path);
203
+ }
204
+
180
205
  get frame() {
181
206
  if (!['dialog','floatingPane'].includes(this.nodeTag)) throw new TypeError('frame accessor requires a window');
182
207
  const children = this.value instanceof SourceBag ? this.value.getNodes() : [];
@@ -190,6 +215,15 @@ export class GramlotBuilderBagNode extends SourceBagNode {
190
215
  if (!['dialog','floatingPane'].includes(this.nodeTag)) throw new TypeError('requestClose requires a window');
191
216
  return this.rootBuilder.binding.gramlot.dom.getDomNode(this).requestClose(reason);
192
217
  }
218
+ /** frameGrid returns an ordinary frame; its grid remains an ordinary Source node. */
219
+ get grid() {
220
+ if (this.nodeTag === 'framePane') {
221
+ const grid = this.staticValue instanceof SourceBag ? this.staticValue.getNode('center.grid') : null;
222
+ if (!grid || grid.nodeTag !== 'grid') throw new TypeError('This frame has no central grid');
223
+ return this.builder.wrapSource(grid);
224
+ }
225
+ return (attrs = {}) => this.builder.wrapSource(this.builder.commandOnNode(this, 'grid', null, attrs));
226
+ }
193
227
  get top() { return this.frameRegion('top'); }
194
228
  get bottom() { return this.frameRegion('bottom'); }
195
229
  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) {
@@ -0,0 +1,160 @@
1
+ /** Application-owned attachment operations, composed with the shared upload queue. */
2
+ import {Bag} from '@gramlot/gramlot';
3
+ import {toTytx} from '@genrojs/tytx';
4
+ import {defineComponent} from './registry.js';
5
+ import {Container} from './container.js';
6
+ import {readUploadContext} from './upload-engine.js';
7
+ import {randomId} from '../random-id.js';
8
+
9
+ export const AttachmentManager = defineComponent({
10
+ name:'attachmentManager', tag:'gramlot-attachment-manager', base:Container, sourceContext:true, bagStore:true,
11
+ parameters:{operation:{dtype:'T'},storepath:{dtype:'T'},contextPath:{dtype:'T'},
12
+ ready:{dtype:'B',default:false,binding:'read'},listMethod:{dtype:'T'},readMethod:{dtype:'T'},removeMethod:{dtype:'T'},
13
+ accept:{dtype:'T',default:'',binding:'read'},disabled:{dtype:'B',default:false,binding:'read'},
14
+ selectedPath:{dtype:'T',nullable:true,default:null,binding:'twoWay'}},
15
+ implementation: Base => class extends Base {
16
+ #context; #store; #subscription; #generation=0; #listSequence=0; #previewSequence=0; #disposed=false; #removeToken=null;
17
+ get #state() { return this.#context.sourceNode.attachmentState; }
18
+ get #contextKey() { return this.#state.getItem('contextKey'); }
19
+ set #contextKey(value) { this.#state.setItem('contextKey', value); }
20
+ get #selected() { return this.#state.getItem('selected'); }
21
+ set #selected(value) { this.#state.setItem('selected', value); }
22
+ get #list() { return this.#state.getItem('items'); }
23
+ set #list(value) { this.#state.setItem('items', value); }
24
+ constructor() {
25
+ super(); this.control.replaceChildren(); const doc=this.ownerDocument;
26
+ const style=doc.createElement('style');
27
+ style.textContent=':host{display:block} .attachments{display:grid;gap:.75em} .attachment-list{padding-inline-start:1.2em} .preview img{max-width:100%;max-height:240px} button{font:inherit}';
28
+ const box=doc.createElement('div'); box.className='attachments';
29
+ this.uploader=doc.createElement('gramlot-uploader');
30
+ const heading=doc.createElement('strong'); heading.textContent='Attachments';
31
+ this.list=doc.createElement('ul'); this.list.className='attachment-list'; this.list.setAttribute('aria-label','Attachments');
32
+ this.preview=doc.createElement('div'); this.preview.className='preview'; this.preview.setAttribute('aria-label','Attachment preview');
33
+ this.removeButton=doc.createElement('button'); this.removeButton.type='button'; this.removeButton.textContent='Remove attachment';
34
+ this.message=doc.createElement('div'); this.message.setAttribute('role','status');
35
+ box.append(this.uploader,heading,this.list,this.preview,this.removeButton,this.message); this.control.append(box); this.shadowRoot.append(style);
36
+ this.removeButton.addEventListener('click',()=>void this.#remove());
37
+ }
38
+ setSourceContext(context) {
39
+ this.#context=context;
40
+ if (!context.sourceNode.attachmentState) {
41
+ Object.defineProperty(context.sourceNode, 'attachmentState', {value:new Bag({
42
+ contextKey:null, selected:null, items:new Bag(), preview:null, message:''
43
+ }), configurable:true});
44
+ }
45
+ this.#message(this.#state.getItem('message'));
46
+ this.#renderPreview();
47
+ this.uploader.setSourceContext({...context,callLogic:()=>this.#refresh()});
48
+ }
49
+ setStoreBag(store) {
50
+ if (!(store instanceof Bag)) throw new TypeError('attachmentManager storepath must resolve to a Bag');
51
+ this.#store=store; this.uploader.setStoreBag(store);
52
+ }
53
+ projectAttributes(attrs,adapt) {
54
+ const rest=super.projectAttributes(attrs,adapt), p=this.parameters;
55
+ for (const name of ['operation','contextPath','listMethod','readMethod','removeMethod']) {
56
+ if (typeof p[name] !== 'string' || !p[name]) throw new TypeError(`attachmentManager requires ${name}`);
57
+ }
58
+ this.uploader.projectAttributes({operation:p.operation,storepath:p.storepath,contextPath:p.contextPath,
59
+ accept:p.accept,multiple:true,autoUpload:Boolean(p.ready),manualUpload:false,disabled:p.disabled,
60
+ selectedPath:p.selectedPath,onComplete:'attachmentComplete'},adapt);
61
+ this.#syncContext(); this.#render(); return rest;
62
+ }
63
+ connectedCallback() {
64
+ this.#disposed=false;
65
+ if (this.#context && !this.#subscription) {
66
+ const {gramlot}=this.#context.upload(); this.#subscription=`attachment-manager-${randomId()}`;
67
+ gramlot.data.subscribe(this.#subscription,{any:()=>this.#syncContext()});
68
+ }
69
+ this.#syncContext();
70
+ }
71
+ disconnectedCallback() {
72
+ // DOM relocation into a floating keeps the same Source owner and resources.
73
+ this.ownerDocument.defaultView.queueMicrotask(() => {
74
+ if (this.isConnected) return;
75
+ this.#disposed=true; this.#generation++;
76
+ if (this.#subscription) { this.#context.upload().gramlot.data.unsubscribe(this.#subscription,{any:true}); this.#subscription=null; }
77
+ });
78
+ }
79
+ #message(value) { this.#state.setItem('message',value); this.message.textContent=value; }
80
+ #renderPreview() {
81
+ this.preview.replaceChildren();
82
+ const result=this.#state.getItem('preview');
83
+ if (!result) return;
84
+ if (result.getItem('kind') === 'image') {
85
+ const image=this.ownerDocument.createElement('img'); image.src=result.getItem('src');
86
+ image.alt='Attachment preview'; this.preview.append(image);
87
+ } else {
88
+ const pre=this.ownerDocument.createElement('pre'); pre.textContent=result.getItem('text'); this.preview.append(pre);
89
+ }
90
+ }
91
+ #value() { return readUploadContext(this.#context.sourceNode,this.parameters.contextPath); }
92
+ #syncContext() {
93
+ if (!this.parameters || !this.#context || !this.isConnected || this.#disposed) return;
94
+ if (!this.parameters.ready) {
95
+ if (this.#contextKey !== null) { this.#contextKey=null; this.#generation++; this.#removeToken=null; this.#selected=null; this.#list=new Bag(); this.#state.setItem('preview',null); this.#renderPreview(); this.#render(); }
96
+ return;
97
+ }
98
+ try {
99
+ const context=this.#value(), key=toTytx(context);
100
+ if (key !== this.#contextKey) { this.#contextKey=key; this.#generation++; this.#removeToken=null; this.#selected=null; this.#list=new Bag(); this.#state.setItem('preview',null); this.#renderPreview(); this.#render(); void this.#refresh(); }
101
+ } catch (error) {
102
+ if (this.#contextKey !== null) {
103
+ this.#contextKey=null; this.#generation++; this.#removeToken=null; this.#selected=null;
104
+ this.#list=new Bag(); this.#state.setItem('preview',null); this.#renderPreview(); this.#render();
105
+ }
106
+ this.#message(error.message);
107
+ }
108
+ }
109
+ async #refresh() {
110
+ if (!this.parameters.ready || this.#disposed || !this.isConnected) return;
111
+ const generation=this.#generation, sequence=++this.#listSequence;
112
+ try {
113
+ const result=await this.#context.upload().gramlot.rpc.call('data',this.parameters.listMethod,{context:this.#value()});
114
+ if (generation !== this.#generation || sequence !== this.#listSequence || this.#disposed) return;
115
+ if (!(result instanceof Bag)) throw new TypeError('Attachment list must be a Bag');
116
+ for (const node of result.getNodes()) if (typeof node.getAttr('caption') !== 'string') throw new TypeError('Attachment caption must be text');
117
+ this.#list=result;
118
+ if (this.#selected && !this.#list.getNode(this.#selected)) { this.#selected=null; this.#previewSequence++; this.#state.setItem('preview',null); this.#renderPreview(); }
119
+ this.#message(''); this.#render();
120
+ } catch (error) { if (generation === this.#generation && sequence === this.#listSequence && !this.#disposed) this.#message(`Attachments: ${error.message}`); }
121
+ }
122
+ #render() {
123
+ if (!this.parameters || !this.#context) return;
124
+ this.list.replaceChildren();
125
+ for (const node of this.#list.getNodes()) {
126
+ const item=this.ownerDocument.createElement('li'), button=this.ownerDocument.createElement('button');
127
+ button.type='button'; button.textContent=node.getAttr('caption'); button.setAttribute('aria-pressed',String(node.label===this.#selected));
128
+ button.disabled=Boolean(this.parameters.disabled || !this.parameters.ready || this.#removeToken);
129
+ button.addEventListener('click',()=>void this.#read(node.label)); item.append(button); this.list.append(item);
130
+ }
131
+ this.removeButton.disabled=Boolean(this.parameters.disabled || !this.parameters.ready || !this.#selected || this.#removeToken);
132
+ }
133
+ async #read(selected) {
134
+ if (!this.parameters.ready || this.parameters.disabled) return;
135
+ this.#selected=selected; this.#render(); this.#state.setItem('preview',null); this.#renderPreview(); const generation=this.#generation, sequence=++this.#previewSequence;
136
+ try {
137
+ const result=await this.#context.upload().gramlot.rpc.call('data',this.parameters.readMethod,{context:this.#value(),selected});
138
+ if (generation !== this.#generation || sequence !== this.#previewSequence || this.#disposed) return;
139
+ if (!(result instanceof Bag)) throw new TypeError('Attachment preview must be a Bag');
140
+ const kind=result.getItem('kind'), text=result.getItem('text'), src=result.getItem('src');
141
+ if (!((kind === 'image' && typeof src === 'string' && src) ||
142
+ (['text','message'].includes(kind) && typeof text === 'string'))) throw new TypeError('Invalid attachment preview');
143
+ this.#state.setItem('preview',result); this.#renderPreview();
144
+ this.#message('');
145
+ } catch (error) { if (generation === this.#generation && sequence === this.#previewSequence && !this.#disposed) this.#message(`Preview: ${error.message}`); }
146
+ }
147
+ async #remove() {
148
+ if (!this.#selected || !this.parameters.ready || this.parameters.disabled || this.#removeToken) return;
149
+ const selected=this.#selected, generation=this.#generation, token=this.#removeToken={};
150
+ this.#previewSequence++; this.#render();
151
+ try {
152
+ const removed=await this.#context.upload().gramlot.rpc.call('data',this.parameters.removeMethod,{context:this.#value(),selected});
153
+ if (generation !== this.#generation || this.#disposed) return;
154
+ if (removed !== true) throw new Error('Attachment was not removed');
155
+ this.#selected=null; this.#state.setItem('preview',null); this.#renderPreview(); await this.#refresh();
156
+ } catch (error) { if (generation === this.#generation && !this.#disposed) this.#message(`Remove: ${error.message}`); }
157
+ finally { if (this.#removeToken === token) { this.#removeToken=null; this.#render(); } }
158
+ }
159
+ }
160
+ });