@gramlot/gramlot 0.3.40 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/assets/icons/applications.svg +4 -0
  2. package/assets/icons/archive.svg +4 -0
  3. package/assets/icons/attachment.svg +4 -0
  4. package/assets/icons/book.svg +4 -0
  5. package/assets/icons/bookmark.svg +4 -0
  6. package/assets/icons/calendar.svg +4 -0
  7. package/assets/icons/cancel.svg +4 -0
  8. package/assets/icons/chart.svg +4 -1
  9. package/assets/icons/chat.svg +4 -0
  10. package/assets/icons/clock.svg +4 -0
  11. package/assets/icons/code.svg +4 -0
  12. package/assets/icons/collapse.svg +4 -0
  13. package/assets/icons/columns.svg +4 -0
  14. package/assets/icons/confirm.svg +4 -0
  15. package/assets/icons/copy.svg +4 -0
  16. package/assets/icons/cut.svg +4 -0
  17. package/assets/icons/database.svg +4 -0
  18. package/assets/icons/delete.svg +4 -0
  19. package/assets/icons/detach.svg +4 -0
  20. package/assets/icons/document.svg +4 -0
  21. package/assets/icons/download.svg +4 -0
  22. package/assets/icons/duplicate.svg +4 -0
  23. package/assets/icons/edit.svg +4 -0
  24. package/assets/icons/expand.svg +4 -0
  25. package/assets/icons/export.svg +4 -0
  26. package/assets/icons/eye.svg +4 -0
  27. package/assets/icons/filter.svg +4 -0
  28. package/assets/icons/first.svg +4 -0
  29. package/assets/icons/folder.svg +4 -0
  30. package/assets/icons/group.svg +4 -0
  31. package/assets/icons/help.svg +4 -0
  32. package/assets/icons/home.svg +4 -0
  33. package/assets/icons/import.svg +4 -0
  34. package/assets/icons/info.svg +4 -0
  35. package/assets/icons/inspector.svg +4 -0
  36. package/assets/icons/last.svg +4 -0
  37. package/assets/icons/layers.svg +4 -0
  38. package/assets/icons/link.svg +4 -0
  39. package/assets/icons/list.svg +4 -0
  40. package/assets/icons/lock.svg +4 -0
  41. package/assets/icons/logout.svg +4 -0
  42. package/assets/icons/navigation.svg +4 -0
  43. package/assets/icons/new.svg +4 -0
  44. package/assets/icons/next.svg +4 -0
  45. package/assets/icons/open.svg +4 -0
  46. package/assets/icons/palette.svg +4 -0
  47. package/assets/icons/panel-bottom.svg +4 -0
  48. package/assets/icons/panel-left.svg +4 -0
  49. package/assets/icons/panel-right.svg +4 -0
  50. package/assets/icons/panel-top.svg +4 -0
  51. package/assets/icons/paste.svg +4 -0
  52. package/assets/icons/pause.svg +4 -0
  53. package/assets/icons/pin.svg +4 -0
  54. package/assets/icons/play.svg +4 -0
  55. package/assets/icons/previous.svg +4 -0
  56. package/assets/icons/print.svg +4 -0
  57. package/assets/icons/redo.svg +4 -0
  58. package/assets/icons/refresh.svg +4 -0
  59. package/assets/icons/save.svg +4 -0
  60. package/assets/icons/search.svg +4 -0
  61. package/assets/icons/send.svg +4 -0
  62. package/assets/icons/settings.svg +4 -0
  63. package/assets/icons/sort-ascending.svg +4 -0
  64. package/assets/icons/sort-descending.svg +4 -0
  65. package/assets/icons/stop.svg +4 -0
  66. package/assets/icons/table.svg +4 -0
  67. package/assets/icons/tree.svg +4 -0
  68. package/assets/icons/undo.svg +4 -0
  69. package/assets/icons/unlock.svg +4 -0
  70. package/assets/icons/upload.svg +4 -0
  71. package/assets/icons/user.svg +4 -0
  72. package/assets/icons/warning.svg +4 -0
  73. package/assets/icons/zoom-in.svg +4 -0
  74. package/assets/icons/zoom-out.svg +4 -0
  75. package/dist/components/charts/__init__.py +1 -1
  76. package/dist/components/charts/assets/index.js +1 -1
  77. package/dist/components/charts/assets/libraries/vega.js +11 -11
  78. package/dist/components/editors/__init__.py +1 -1
  79. package/dist/components/editors/assets/index.js +1 -1
  80. package/dist/components/editors/assets/libraries/codemirror.js +30 -31
  81. package/dist/components/editors/assets/libraries/jodit.js +3 -1
  82. package/dist/components/editors/assets/libraries/prosemirror.js +1 -1
  83. package/dist/components/editors/grammar.json +6 -1
  84. package/dist/components/grid/__init__.py +1 -1
  85. package/dist/components/grid/assets/index.js +1 -1
  86. package/dist/components/grid/commands.json +4 -6
  87. package/dist/components/grid/grammar.json +51 -0
  88. package/dist/components/inputs/__init__.py +1 -1
  89. package/dist/components/inputs/assets/index.js +1 -1
  90. package/dist/components/inputs/grammar.json +4987 -216
  91. package/dist/components/layout/__init__.py +1 -1
  92. package/dist/components/layout/assets/index.js +1 -1
  93. package/dist/components/layout/grammar.json +69 -4
  94. package/dist/components/tree/__init__.py +1 -1
  95. package/dist/components/tree/assets/index.js +1 -1
  96. package/dist/components/tree/grammar.json +16 -0
  97. package/dist/components/typst/__init__.py +1 -1
  98. package/dist/components/typst/assets/collection.js +6 -6
  99. package/dist/components/typst/assets/index.js +1 -1
  100. package/dist/components/uploads/__init__.py +1 -1
  101. package/dist/components/uploads/assets/index.js +1 -1
  102. package/dist/components/uploads/grammar.json +66 -0
  103. package/dist/declared-collections.js +1 -1
  104. package/dist/gramlot.js +4007 -1256
  105. package/dist/gramlot.min.js +329 -131
  106. package/dist/libraries.json +1 -0
  107. package/dist/standard-collections.js +1 -1
  108. package/dist/standard-grammar.js +1 -1
  109. package/package.json +3 -1
  110. package/src/binding/ask-dialog.js +17 -3
  111. package/src/binding/data-binder.js +5 -0
  112. package/src/binding/providers.js +1 -1
  113. package/src/binding/runtime.js +6 -3
  114. package/src/builder/chart-icon.js +2 -0
  115. package/src/builder/gramlot-builder.d.ts +3 -1
  116. package/src/builder/gramlot-builder.js +26 -9
  117. package/src/builder/source.js +12 -3
  118. package/src/builder/xml-recipe.js +144 -0
  119. package/src/chat-file-types.js +13 -0
  120. package/src/chat.js +23 -25
  121. package/src/commands.d.ts +1 -1
  122. package/src/commands.js +1 -1
  123. package/src/components/border-container.js +64 -6
  124. package/src/components/buttons.js +26 -31
  125. package/src/components/chart-geographic-options.js +1 -1
  126. package/src/components/chart-pane.js +5 -5
  127. package/src/components/chart-spatial-options.js +5 -1
  128. package/src/components/check-box-text-editor.js +1 -0
  129. package/src/components/check-box-text.js +2 -0
  130. package/src/components/choice-editor.js +3 -2
  131. package/src/components/choice-field-styles.js +9 -1
  132. package/src/components/code-mirror-engine.js +18 -5
  133. package/src/components/code-mirror-gramlot.js +85 -0
  134. package/src/components/code-mirror.js +3 -2
  135. package/src/components/drawing.js +43 -14
  136. package/src/components/editor-options.js +1 -1
  137. package/src/components/graphical-ranges.js +177 -0
  138. package/src/components/grid-footer.js +6 -1
  139. package/src/components/grid-styles.js +11 -2
  140. package/src/components/grid-tools.js +15 -7
  141. package/src/components/grid.js +69 -8
  142. package/src/components/inputs.js +93 -23
  143. package/src/components/jodit-engine.js +3 -1
  144. package/src/components/menus.js +83 -25
  145. package/src/components/numeric-range.js +39 -0
  146. package/src/components/selected-container.js +109 -63
  147. package/src/components/tab-bar.js +371 -0
  148. package/src/components/toolbar-icon-style.js +22 -0
  149. package/src/components/toolbar-overflow.js +74 -12
  150. package/src/components/tree.js +12 -3
  151. package/src/components/typst-preview.js +3 -3
  152. package/src/components/upload-blocks.js +88 -0
  153. package/src/components/upload-engine.js +21 -31
  154. package/src/components/uploader.js +168 -47
  155. package/src/gramlot.js +6 -3
  156. package/src/handlers/dom-handler.d.ts +2 -0
  157. package/src/handlers/dom-handler.js +9 -0
  158. package/src/handlers/rpc-handler.d.ts +1 -1
  159. package/src/handlers/rpc-handler.js +2 -0
  160. package/src/handlers/source-handler.d.ts +5 -3
  161. package/src/handlers/source-handler.js +31 -13
  162. package/src/icons.js +84 -0
  163. package/src/index-page-runtime.js +9 -2
  164. package/src/index-page-styles.js +1 -1
  165. package/src/index-theme.js +210 -3
  166. package/src/index.d.ts +5 -1
  167. package/src/index.js +5 -1
  168. package/src/libraries.js +1 -1
  169. package/src/page-store-connection.js +44 -7
  170. package/src/renderer/gramlot-renderer.js +4 -1
  171. package/src/server/chat-attachments.js +139 -0
  172. package/src/server/chat.d.ts +31 -0
  173. package/src/server/chat.js +157 -0
  174. package/src/server/database-selectors.d.ts +6 -0
  175. package/src/server/database-selectors.js +13 -0
  176. package/src/server/gramlot-file-server.js +6 -1
  177. package/src/server/gramlot-server.d.ts +19 -3
  178. package/src/server/gramlot-server.js +144 -18
  179. package/src/server/index-page.d.ts +10 -0
  180. package/src/server/index-page.js +73 -8
  181. package/src/server/index.d.ts +1 -1
  182. package/src/server/index.js +1 -1
  183. package/src/server/page-base.js +4 -0
  184. package/src/server/page-store.d.ts +21 -0
  185. package/src/server/page-store.js +219 -0
  186. package/src/server/page.d.ts +6 -1
  187. package/src/server/page.js +5 -1
  188. package/src/server/store-recipe.js +102 -0
  189. package/src/server/toolbar-icon-name.d.ts +76 -0
  190. package/src/server/upload.d.ts +2 -0
  191. package/src/server/upload.js +36 -18
  192. package/src/server/visual-editor.js +4 -2
  193. package/src/tree-store.d.ts +5 -1
  194. package/src/tree-store.js +11 -2
  195. package/src/view/choice-focus.js +17 -0
  196. package/src/view/html.js +21 -1
  197. package/src/view/menu.js +9 -3
  198. package/src/visual-editor.js +6 -2
  199. package/themes/gramlot-base/theme.css +53 -28
  200. package/themes/gramlot-compact/theme.css +2 -0
  201. package/themes/gramlot-index/icons/applications.svg +4 -0
  202. package/themes/gramlot-index/icons/archive.svg +4 -0
  203. package/themes/gramlot-index/icons/attachment.svg +4 -0
  204. package/themes/gramlot-index/icons/book.svg +4 -0
  205. package/themes/gramlot-index/icons/bookmark.svg +4 -0
  206. package/themes/gramlot-index/icons/calendar.svg +4 -0
  207. package/themes/gramlot-index/icons/cancel.svg +4 -0
  208. package/themes/gramlot-index/icons/chart.svg +4 -0
  209. package/themes/gramlot-index/icons/chat.svg +4 -0
  210. package/themes/gramlot-index/icons/clock.svg +4 -0
  211. package/themes/gramlot-index/icons/code.svg +4 -0
  212. package/themes/gramlot-index/icons/collapse.svg +4 -0
  213. package/themes/gramlot-index/icons/columns.svg +4 -0
  214. package/themes/gramlot-index/icons/confirm.svg +4 -0
  215. package/themes/gramlot-index/icons/copy.svg +4 -0
  216. package/themes/gramlot-index/icons/cut.svg +4 -0
  217. package/themes/gramlot-index/icons/database.svg +4 -0
  218. package/themes/gramlot-index/icons/delete.svg +4 -0
  219. package/themes/gramlot-index/icons/detach.svg +4 -0
  220. package/themes/gramlot-index/icons/document.svg +4 -0
  221. package/themes/gramlot-index/icons/download.svg +4 -0
  222. package/themes/gramlot-index/icons/duplicate.svg +4 -0
  223. package/themes/gramlot-index/icons/edit.svg +4 -0
  224. package/themes/gramlot-index/icons/expand.svg +4 -0
  225. package/themes/gramlot-index/icons/export.svg +4 -0
  226. package/themes/gramlot-index/icons/eye.svg +4 -0
  227. package/themes/gramlot-index/icons/filter.svg +4 -0
  228. package/themes/gramlot-index/icons/first.svg +4 -0
  229. package/themes/gramlot-index/icons/folder.svg +4 -0
  230. package/themes/gramlot-index/icons/group.svg +4 -0
  231. package/themes/gramlot-index/icons/help.svg +4 -0
  232. package/themes/gramlot-index/icons/home.svg +4 -0
  233. package/themes/gramlot-index/icons/import.svg +4 -0
  234. package/themes/gramlot-index/icons/info.svg +4 -0
  235. package/themes/gramlot-index/icons/inspector.svg +4 -0
  236. package/themes/gramlot-index/icons/last.svg +4 -0
  237. package/themes/gramlot-index/icons/layers.svg +4 -0
  238. package/themes/gramlot-index/icons/link.svg +4 -0
  239. package/themes/gramlot-index/icons/list.svg +4 -0
  240. package/themes/gramlot-index/icons/lock.svg +4 -0
  241. package/themes/gramlot-index/icons/logout.svg +4 -0
  242. package/themes/gramlot-index/icons/navigation.svg +4 -0
  243. package/themes/gramlot-index/icons/new.svg +4 -0
  244. package/themes/gramlot-index/icons/next.svg +4 -0
  245. package/themes/gramlot-index/icons/open.svg +4 -0
  246. package/themes/gramlot-index/icons/palette.svg +4 -0
  247. package/themes/gramlot-index/icons/panel-bottom.svg +4 -0
  248. package/themes/gramlot-index/icons/panel-left.svg +4 -0
  249. package/themes/gramlot-index/icons/panel-right.svg +4 -0
  250. package/themes/gramlot-index/icons/panel-top.svg +4 -0
  251. package/themes/gramlot-index/icons/paste.svg +4 -0
  252. package/themes/gramlot-index/icons/pause.svg +4 -0
  253. package/themes/gramlot-index/icons/pin.svg +4 -0
  254. package/themes/gramlot-index/icons/play.svg +4 -0
  255. package/themes/gramlot-index/icons/previous.svg +4 -0
  256. package/themes/gramlot-index/icons/print.svg +4 -0
  257. package/themes/gramlot-index/icons/redo.svg +4 -0
  258. package/themes/gramlot-index/icons/refresh.svg +4 -0
  259. package/themes/gramlot-index/icons/save.svg +4 -0
  260. package/themes/gramlot-index/icons/search.svg +4 -0
  261. package/themes/gramlot-index/icons/send.svg +4 -0
  262. package/themes/gramlot-index/icons/settings.svg +4 -0
  263. package/themes/gramlot-index/icons/sort-ascending.svg +4 -0
  264. package/themes/gramlot-index/icons/sort-descending.svg +4 -0
  265. package/themes/gramlot-index/icons/stop.svg +4 -0
  266. package/themes/gramlot-index/icons/table.svg +4 -0
  267. package/themes/gramlot-index/icons/tree.svg +4 -0
  268. package/themes/gramlot-index/icons/undo.svg +4 -0
  269. package/themes/gramlot-index/icons/unlock.svg +4 -0
  270. package/themes/gramlot-index/icons/upload.svg +4 -0
  271. package/themes/gramlot-index/icons/user.svg +4 -0
  272. package/themes/gramlot-index/icons/warning.svg +4 -0
  273. package/themes/gramlot-index/icons/zoom-in.svg +4 -0
  274. package/themes/gramlot-index/icons/zoom-out.svg +4 -0
  275. package/themes/gramlot-index/icons.json +76 -0
  276. package/themes/gramlot-index/theme.css +21 -0
  277. package/themes/joanna/theme.css +2 -0
  278. package/themes/mela/theme.css +2 -0
  279. package/themes/mimi/theme.css +2 -0
@@ -7,6 +7,7 @@ import {RpcError} from './handlers/rpc-handler.js';
7
7
  export class PageStoreConnection {
8
8
  constructor(gramlot, url, document) {
9
9
  this.gramlot = gramlot;
10
+ this.canReconnect = gramlot.capabilities.includes('pageStoreReconnect');
10
11
  this.window = document.defaultView;
11
12
  this.frames = gramlot._frames;
12
13
  this.binders = new Map();
@@ -17,6 +18,9 @@ export class PageStoreConnection {
17
18
  this.closed = false;
18
19
  this.ready = false;
19
20
  this.socket = null;
21
+ this.reconnecting = false;
22
+ this.retryTimer = null;
23
+ this.retryDelay = 250;
20
24
  const address = new URL(url, document.baseURI);
21
25
  address.protocol = address.protocol === 'https:' ? 'wss:' : 'ws:';
22
26
  this.endpoint = address.href;
@@ -49,18 +53,46 @@ export class PageStoreConnection {
49
53
  open() {
50
54
  const address = this.address;
51
55
  address.searchParams.set('pageId', this.gramlot.pageId);
52
- this.socket = new this.window.WebSocket(address.href);
53
- this.socket.addEventListener('open', () => this.connected());
54
- this.socket.addEventListener('message', event => {
56
+ const socket = this.socket = new this.window.WebSocket(address.href);
57
+ socket.addEventListener('open', () => {
58
+ if (this.socket === socket) this.connected();
59
+ });
60
+ socket.addEventListener('message', event => {
61
+ if (this.socket !== socket) return;
55
62
  try { this.deliver(event.data); }
56
63
  catch (error) { this.fail(error); }
57
64
  });
58
- this.socket.addEventListener('error', () => this.fail(new Error('PageStore WebSocket failed')));
59
- this.socket.addEventListener('close', event => {
60
- if (!this.closed) this.fail(new Error('PageStore disconnected (' + event.code + ')'));
65
+ socket.addEventListener('error', () => {
66
+ // A browser connection error also dispatches close, which schedules the retry.
67
+ if (this.socket === socket && !this.canReconnect) this.fail(new Error('PageStore WebSocket failed'));
68
+ });
69
+ socket.addEventListener('close', event => {
70
+ if (this.closed || this.socket !== socket) return;
71
+ const error = new Error('PageStore disconnected (' + event.code + ')');
72
+ if (!this.canReconnect || (!this.ready && !this.reconnecting)) {
73
+ this.fail(error);
74
+ return;
75
+ }
76
+ this.socket = null;
77
+ this.suspend(error);
78
+ this.retryTimer = this.window.setTimeout(() => {
79
+ this.retryTimer = null;
80
+ this.open();
81
+ }, this.retryDelay);
82
+ this.retryDelay = Math.min(this.retryDelay * 2, 10000);
61
83
  });
62
84
  }
63
85
 
86
+ suspend(error) {
87
+ if (this.reconnecting) return;
88
+ this.ready = false;
89
+ this.reconnecting = true;
90
+ this.routes.clear();
91
+ for (const call of this.calls.values()) call.finish(error);
92
+ for (const binder of this.binders.values()) binder.suspend();
93
+ this.frames.setChannelState('server', {endpoint: this.endpoint, ready: false, reconnecting: true});
94
+ }
95
+
64
96
  peerChanged(peer) {
65
97
  if (this.closed || !peer.parent || !this.parent) return;
66
98
  const state = peer.channels.server;
@@ -71,12 +103,15 @@ export class PageStoreConnection {
71
103
  } else if (peer.origin !== this.origin || state?.endpoint !== this.endpoint) {
72
104
  this.fail(new Error('Parent does not provide the same PageStore endpoint'));
73
105
  } else if (state.ready) this.connected();
106
+ else if (state.reconnecting && this.canReconnect) this.suspend(new Error('PageStore parent disconnected'));
74
107
  else if (this.ready) this.fail(new Error('PageStore parent channel closed'));
75
108
  }
76
109
 
77
110
  connected() {
78
111
  if (this.closed || this.ready) return;
79
112
  this.ready = true;
113
+ this.reconnecting = false;
114
+ this.retryDelay = 250;
80
115
  if (this.parent) this.upstream({op: 'attach', pageId: this.gramlot.pageId});
81
116
  for (const binder of this.binders.values()) this.subscribe(binder);
82
117
  for (const call of this.calls.values()) this.sendCall(call);
@@ -115,7 +150,7 @@ export class PageStoreConnection {
115
150
  }
116
151
 
117
152
  deliver(wire) {
118
- if (this.closed) return;
153
+ if (this.closed || this.reconnecting) return;
119
154
  const message = fromTytx(wire);
120
155
  if (message.pageId === this.gramlot.pageId) {
121
156
  if (message.op === 'closed') {
@@ -175,6 +210,7 @@ export class PageStoreConnection {
175
210
  /** Queue until attached, then pair responses by id independently of binder changes. */
176
211
  call(text, signal) {
177
212
  if (this.closed) return Promise.reject(this.error ?? new Error('PageStore connection is closed'));
213
+ if (this.reconnecting) return Promise.reject(new Error('PageStore is reconnecting'));
178
214
  if (signal?.aborted) return Promise.reject(signal.reason);
179
215
  const message = fromTytx(text);
180
216
  if (message.pageId !== this.gramlot.pageId || typeof message.id !== 'string'
@@ -225,6 +261,7 @@ export class PageStoreConnection {
225
261
  close() {
226
262
  if (this.closed) return;
227
263
  this.closed = true;
264
+ if (this.retryTimer !== null) this.window.clearTimeout(this.retryTimer);
228
265
  if (this.parent && this.ready && this.frames.isConnected(this.parent)) {
229
266
  for (const pageId of [...this.routes.keys(), this.gramlot.pageId]) {
230
267
  this.frames.send(this.parent, 'server', {op: 'detach', pageId});
@@ -1,3 +1,4 @@
1
+ import {trackChoiceFocus} from '../view/choice-focus.js';
1
2
  import {callLogic, invokeHook} from '../binding/hooks.js';
2
3
  /* @ts-self-types="./gramlot-renderer.d.ts" */
3
4
  /**
@@ -51,7 +52,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
51
52
  this._binding = binding;
52
53
  this.source = source;
53
54
  this.destination = destination;
54
- this.html = new HtmlElement({uploadContext: () => ({gramlot: binding.gramlot, window: destination.ownerDocument.defaultView}), metadataAttributes: ['__ref', ...SYMBOLIC_ATTRIBUTES],
55
+ this.html = new HtmlElement({icons: binding.gramlot._icons, uploadContext: () => ({gramlot: binding.gramlot, window: destination.ownerDocument.defaultView}), metadataAttributes: ['__ref', ...SYMBOLIC_ATTRIBUTES],
55
56
  format: (value, options) => binding.gramlot.format(value, options),
56
57
  reportError: (node, error, title) => { if (this.records.has(node)) binding.reportError(error, title); },
57
58
  callLogic: (node, name, keywords) => {
@@ -232,6 +233,8 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
232
233
  this.records.set(node, record);
233
234
  this.elements.set(record.element, record);
234
235
  this.elements.set(record.presentation, record);
236
+ if (record.element.namespaceURI === XHTML_NS && record.element.localName === 'select')
237
+ record.cleanup.push(trackChoiceFocus(record.element));
235
238
  const control = ControlAdapter.for(record.binding, record);
236
239
  // An input can acquire/change its adapter through type while its DOM record survives.
237
240
  if (control || (record.element.namespaceURI === XHTML_NS && record.element.localName === 'input'))
@@ -0,0 +1,139 @@
1
+ import {Bag} from '@genrojs/bag';
2
+ import {fileTypes} from '../chat-file-types.js';
3
+ import {Exposed} from './page-base.js';
4
+ import {UploadTarget} from './upload.js';
5
+
6
+ // Files are owned by the page. Browser imports of the authoring API never open a filesystem.
7
+ const FS = 'node:fs';
8
+ const OS = 'node:os';
9
+ const PATH = 'node:path';
10
+ const BUFFER = 'node:buffer';
11
+
12
+ export class ChatAttachments extends Exposed {
13
+ #files = new Map();
14
+ #directory = null;
15
+ #fs = null;
16
+ #closed = false;
17
+ url = '';
18
+
19
+ async receive({name, mediaType, size}) {
20
+ if (typeof name !== 'string' || !name.includes('.') || /[/\\]/.test(name) || name.length > 255 ||
21
+ fileTypes[name.split('.').at(-1).toLowerCase()] !== mediaType || !Number.isSafeInteger(size) || size <= 0) {
22
+ throw new TypeError('Invalid chat attachment');
23
+ }
24
+ const [fs, os, path] = await Promise.all([import(FS), import(OS), import(PATH)]);
25
+ if (this.#closed) throw new Error('Closed chat');
26
+ this.#fs = fs;
27
+ this.#directory ??= fs.mkdtempSync(path.join(os.tmpdir(), 'gramlot-chat-'));
28
+ const ref = crypto.randomUUID().replaceAll('-', '');
29
+ const filename = path.join(this.#directory, ref);
30
+ const record = {name, mediaType, size, ref};
31
+ if (mediaType.startsWith('image/')) record.url = this.url + ref;
32
+ return new ChatFile(fs, filename, record, () => {
33
+ if (this.#closed) throw new Error('Closed chat');
34
+ this.#files.set(ref, {record, filename});
35
+ });
36
+ }
37
+
38
+ references(refs) {
39
+ const records = new Bag();
40
+ for (const node of refs.getNodes()) {
41
+ const {record} = this.#files.get(node.value.getItem('ref'));
42
+ records.setItem(node.label, new Bag(record));
43
+ }
44
+ return records;
45
+ }
46
+
47
+ async contents(refs) {
48
+ const result = new Bag();
49
+ for (const node of refs.getNodes()) {
50
+ const {record, filename} = this.#files.get(node.value.getItem('ref'));
51
+ const data = await this.#fs.promises.readFile(filename, 'base64');
52
+ result.setItem(node.label, new Bag({...record, data}));
53
+ }
54
+ return result;
55
+ }
56
+
57
+ async imageUrl(png) {
58
+ const {Buffer} = await import(BUFFER);
59
+ const bytes = Buffer.from(png, 'base64');
60
+ const file = await this.receive({name:'image.png', mediaType:'image/png', size:bytes.length});
61
+ try {
62
+ file.write(bytes);
63
+ return file.finish().result.url;
64
+ } catch (error) { file.abort(); throw error; }
65
+ }
66
+
67
+ async openImage(ref) {
68
+ const file = this.#files.get(ref);
69
+ if (!file || !file.record.mediaType.startsWith('image/')) return null;
70
+ return {type:file.record.mediaType, bytes:await this.#fs.promises.readFile(file.filename)};
71
+ }
72
+
73
+ close() {
74
+ this.#closed = true;
75
+ this.#files.clear();
76
+ if (this.#directory) this.#fs.rmSync(this.#directory, {recursive:true, force:true});
77
+ this.#directory = null;
78
+ }
79
+ }
80
+ ChatAttachments.registerUpload('receive');
81
+
82
+ class ChatFile extends UploadTarget {
83
+ #fs;
84
+ #filename;
85
+ #record;
86
+ #commit;
87
+ #fd;
88
+ #size = 0;
89
+ #decoder;
90
+ #header = [];
91
+ #outcome = {state:'pending'};
92
+
93
+ constructor(fs, filename, record, commit) {
94
+ super({maxBytes:record.size});
95
+ this.#fs = fs;
96
+ this.#filename = filename;
97
+ this.#record = record;
98
+ this.#commit = commit;
99
+ this.#fd = fs.openSync(filename, 'wx', 0o600);
100
+ if (record.mediaType === 'text/plain') this.#decoder = new TextDecoder('utf-8', {fatal:true});
101
+ }
102
+
103
+ write(bytes) {
104
+ if (this.#size + bytes.length > this.maxBytes) throw new RangeError('Upload exceeds declared size');
105
+ this.#decoder?.decode(bytes, {stream:true});
106
+ if (this.#decoder && bytes.includes(0)) throw new TypeError('Invalid text attachment');
107
+ this.#header.push(...bytes.subarray(0, 12 - this.#header.length));
108
+ let written = 0;
109
+ while (written < bytes.length) written += this.#fs.writeSync(this.#fd, bytes, written, bytes.length - written);
110
+ this.#size += written;
111
+ }
112
+
113
+ finish() {
114
+ if (this.#size !== this.maxBytes) throw new RangeError('Incomplete attachment');
115
+ const header = String.fromCharCode(...this.#header);
116
+ const signatures = {'image/png':'\x89PNG\r\n\x1a\n', 'image/jpeg':'\xff\xd8\xff', 'image/webp':'RIFF', 'application/pdf':'%PDF-'};
117
+ if (this.#decoder) this.#decoder.decode();
118
+ else if (!header.startsWith(signatures[this.#record.mediaType]) ||
119
+ (this.#record.mediaType === 'image/webp' && header.slice(8, 12) !== 'WEBP')) {
120
+ throw new TypeError('Invalid attachment content');
121
+ }
122
+ this.#fs.closeSync(this.#fd);
123
+ this.#fd = null;
124
+ this.#commit();
125
+ this.#outcome = {state:'completed', result:this.#record};
126
+ return this.#outcome;
127
+ }
128
+
129
+ abort() {
130
+ if (this.#outcome.state === 'pending') {
131
+ if (this.#fd !== null) this.#fs.closeSync(this.#fd);
132
+ this.#fs.rmSync(this.#filename, {force:true});
133
+ this.#outcome = {state:'unsaved'};
134
+ }
135
+ return this.#outcome;
136
+ }
137
+
138
+ status() { return this.#outcome; }
139
+ }
@@ -0,0 +1,31 @@
1
+ import type {Bag} from '@genrojs/bag';
2
+ import {PageStore} from './page-store.js';
3
+ import type {GramlotBuilder} from '../builder/gramlot-builder.js';
4
+
5
+ type Pane = GramlotBuilder['root'];
6
+ export class ChatPane {
7
+ constructor(parent: Pane, options: {datapath: string; chat_id?: string; [attribute: string]: unknown});
8
+ frame: Pane;
9
+ composer: Pane;
10
+ messages: Pane;
11
+ editor: Pane;
12
+ toolbar: Pane;
13
+ sendButton: Pane;
14
+ attachmentButton: Pane;
15
+ }
16
+
17
+ export interface ChatRequestContext {
18
+ chatId: string;
19
+ attachments: Bag;
20
+ feedback: (text: string) => void;
21
+ }
22
+
23
+ export class ChatPageStore extends PageStore {
24
+ static chatIds: string[];
25
+ processMessage(text: string, context: ChatRequestContext): string | GramlotBuilder['source'] | Promise<string | GramlotBuilder['source']>;
26
+ resetConversation(chatId: string): void;
27
+ conversationMessages(chatId: string): Bag;
28
+ conversationAuthors(): [string, string];
29
+ attachmentContents(refs: Bag): Promise<Bag>;
30
+ imageUrl(base64Png: string): Promise<string>;
31
+ }
@@ -0,0 +1,157 @@
1
+ import {Bag} from '@genrojs/bag';
2
+ import {GramlotBuilderBag} from '../builder/source.js';
3
+ import {PageStore} from './page-store.js';
4
+ import {ChatAttachments} from './chat-attachments.js';
5
+
6
+ const identifier = /^[A-Za-z][A-Za-z0-9_]*$/;
7
+ const conversation = ready => new Bag({messages: new Bag(), ready, request: null, response: null, feedback: ''});
8
+
9
+ export class ChatPane {
10
+ constructor(parent, {datapath, chat_id = 'main', ...attributes}) {
11
+ if (typeof chat_id !== 'string' || !identifier.test(chat_id)) throw new TypeError('Invalid chat_id');
12
+ const frame = this.frame = parent.framePane({datapath, ...attributes});
13
+ const defaults = {
14
+ conversation: conversation(false), messageData: new Bag(), draft: '', pending: false,
15
+ requestId: '', error: '', attachments: new Bag(), picking: false, composerHeight: 96,
16
+ };
17
+ for (const [name, value] of Object.entries(defaults)) {
18
+ frame.dataSetter({destination_path: '.' + name, value});
19
+ }
20
+ frame.dataBinder({destination_path: '.conversation', server_path: 'chats.' + chat_id});
21
+ frame.dataController({func:'chatCompleted', response:'^.conversation.response'});
22
+ frame.top.setAttr({height:'44px'});
23
+ this.messages = frame.center.chatMessages({height:'100%', min_height:0});
24
+ this.messages.dataController({func:'chatRender', messages:'^.conversation.messages', _onBuilt:true});
25
+ frame.bottom.setAttr({height:'^.composerHeight', splitter:false});
26
+ this.composer = frame.bottom.framePane({height:'100%', 'data-chat-composer':true});
27
+ this.composer.top.setAttr({height:'2px', 'data-chat-top':true});
28
+ this.composer.bottom.setAttr({height:'44px'});
29
+ const pane = this.composer.center.contentPane({overflow:'hidden'});
30
+ const center = pane.div({display:'flex', flex_direction:'column', padding:'4px 10px', gap:'4px'});
31
+ center.dataFormula({result_path:'.status', formula:'pending ? (feedback || "Sending to the server…") : ""',
32
+ pending:'^.pending', feedback:'^.conversation.feedback', _init:true});
33
+ center.div('^.status', {node_label:'chatFeedback', class:'gramlot-chat-status', role:'status',
34
+ aria_live:'polite', display:'^.status:={} ? "flex" : "none"', 'data-pending':'^.pending',
35
+ height:'22px', min_height:'22px', overflow:'hidden', white_space:'nowrap',
36
+ text_overflow:'ellipsis', font_size:'13px'});
37
+ this.editor = center.textarea({value:'^.draft', live:true, aria_label:'Message', placeholder:'Write a message…',
38
+ class:'gramlot-chat-editor', rows:1, min_height:'44px', height:'44px', line_height:'20px',
39
+ resize:'none', width:'100%', box_sizing:'border-box', border_radius:'18px', padding:'10px 14px'});
40
+ const previews = center.div({display:'flex', gap:'6px', overflow_x:'auto', max_height:'76px'});
41
+ previews.dataController({func:'chatRenderAttachments', attachments:'^.attachments', _onBuilt:true});
42
+ center.dataController({func:'chatResize', draft:'^.draft', status:'^.status', error:'^.error',
43
+ attachments:'^.attachments', _onBuilt:true});
44
+ center.span('^.error', {role:'alert', hidden:'^.error:=!{}', font_size:'12px'});
45
+ const actions = this.composer.bottom.div({class:'gramlot-chat-toolbar', role:'toolbar',
46
+ 'data-chat-toolbar':true, aria_label:'Chat controls', display:'flex', align_items:'center',
47
+ gap:'8px', height:'44px', padding:'0 14px', box_sizing:'border-box'});
48
+ this.attachmentButton = actions.button({icon:'new', aria_label:'Add files or images', title:'Add files or images',
49
+ class:'button--quiet', font_size:'24px', width:'36px', height:'36px',
50
+ style:'--gramlot-touch-target:36px;--gramlot-button-padding:0;--gramlot-field-height:36px;',
51
+ picking:'^.picking', disabled:'^.pending:={} || {picking}'});
52
+ this.attachmentButton.dataController({func:'chatPickAttachments'});
53
+ this.toolbar = actions.div({display:'flex', align_items:'center', gap:'10px', flex:1, min_width:0, overflow_x:'auto'});
54
+ this.sendButton = actions.button({aria_label:'Send', title:'Send message', class:'gramlot-chat-send',
55
+ font_size:'16px', flex_shrink:0, width:'36px', height:'36px', chat_id,
56
+ style:'--gramlot-radius-sm:50%;--gramlot-button-padding:9px;--gramlot-button-gap:0px;--gramlot-field-height:36px;--gramlot-touch-target:36px;',
57
+ ready:'^.conversation.ready', draft:'^.draft', attachments:'^.attachments', picking:'^.picking',
58
+ disabled:'^.pending:={} || {picking} || !{ready} || (!{draft}.trim() && !{attachments}.length)'});
59
+ this.sendButton.span({class:'gramlot-chat-send-icon', aria_hidden:'true'});
60
+ this.sendButton.dataController({func:'chatSend', chat_id});
61
+ }
62
+ }
63
+
64
+ export class ChatPageStore extends PageStore {
65
+ static chatIds = ['main'];
66
+ #queues = new Map();
67
+ attachments = new ChatAttachments();
68
+
69
+ main(root) {
70
+ for (const chatId of this.constructor.chatIds) {
71
+ if (typeof chatId !== 'string' || !identifier.test(chatId)) throw new TypeError('Invalid chatId');
72
+ this.data.setItem('chats.' + chatId, conversation(true));
73
+ root.dataController({func:'chatRequest', chatId, request:'^chats.' + chatId + '.request'});
74
+ }
75
+ }
76
+
77
+ close() {
78
+ super.close();
79
+ this.attachments.close();
80
+ this.#queues.clear();
81
+ }
82
+
83
+ attachmentContents(refs) { return this.attachments.contents(refs); }
84
+ imageUrl(png) { return this.attachments.imageUrl(png); }
85
+ conversationMessages(chatId) { return this.data.getItem('chats.' + chatId + '.messages'); }
86
+ resetConversation(chatId) { this.data.setItem('chats.' + chatId + '.messages', new Bag()); }
87
+ conversationAuthors() { return ['You', 'Assistant']; }
88
+ processMessage(text, context) { return text; }
89
+
90
+ chatRequest(node, {chatId, request}) {
91
+ if (!(request instanceof Bag)) return;
92
+ const previous = this.#queues.get(chatId) ?? Promise.resolve();
93
+ const next = previous.then(() => this.#handle(chatId, request));
94
+ this.#queues.set(chatId, next);
95
+ next.finally(() => { if (this.#queues.get(chatId) === next) this.#queues.delete(chatId); });
96
+ }
97
+
98
+ async #handle(chatId, request) {
99
+ if (this.closed) return;
100
+ const base = 'chats.' + chatId;
101
+ const id = request.getItem('id');
102
+ const text = request.getItem('text');
103
+ if (typeof id !== 'string' || !id || this.data.getItem(base + '.response.id') === id) return;
104
+ let accepted = false;
105
+ let error = '';
106
+ try {
107
+ const action = request.getItem('action');
108
+ if (action === 'reset') {
109
+ await this.resetConversation(chatId);
110
+ accepted = true;
111
+ } else if (action !== 'send') {
112
+ error = 'Unknown chat action.';
113
+ } else {
114
+ const refs = request.getItem('attachments');
115
+ if (!(refs instanceof Bag) || refs.length > 5) throw new TypeError('Invalid attachments');
116
+ if (typeof text !== 'string' || (!text.trim() && !refs.length)) {
117
+ error = 'Enter a message.';
118
+ } else {
119
+ const attachments = this.attachments.references(refs);
120
+ const feedback = status => {
121
+ if (typeof status !== 'string') throw new TypeError('Feedback must be text');
122
+ if (!this.closed) this.data.setItem(base + '.feedback', status);
123
+ };
124
+ const result = await this.processMessage(text, {chatId, attachments, feedback});
125
+ if (this.closed) return;
126
+ if (typeof result !== 'string' && !(result instanceof GramlotBuilderBag)) throw new TypeError('Invalid reply');
127
+ const messages = this.conversationMessages(chatId);
128
+ const [user, assistant] = this.conversationAuthors();
129
+ const label = () => 'm_' + crypto.randomUUID().replaceAll('-', '');
130
+ messages.setItem(label(), this.#attachmentMessage(text, attachments), {role:'user', author:user});
131
+ messages.setItem(label(), result, {role:'assistant', author:assistant});
132
+ accepted = true;
133
+ }
134
+ }
135
+ } catch {
136
+ error = 'The server could not process the message. Your draft has been kept.';
137
+ }
138
+ if (this.closed) return;
139
+ this.data.setItem(base + '.feedback', '');
140
+ this.data.setItem(base + '.response', new Bag({id, submitted:text, accepted, error}));
141
+ }
142
+
143
+ #attachmentMessage(text, attachments) {
144
+ if (!attachments.length) return text;
145
+ const builder = this.sourceBuilder();
146
+ builder.root.div('==' + JSON.stringify(text), {white_space:'pre-wrap'});
147
+ for (const node of attachments.getNodes()) {
148
+ const file = node.value;
149
+ const name = '==' + JSON.stringify(file.getItem('name'));
150
+ builder.root.div(name, {font_size:'13px'});
151
+ if (file.getItem('mediaType').startsWith('image/')) {
152
+ builder.root.img({src:file.getItem('url'), alt:name, max_width:'240px', max_height:'160px'});
153
+ }
154
+ }
155
+ return builder.source;
156
+ }
157
+ }
@@ -0,0 +1,6 @@
1
+ import {Page} from './page.js';
2
+
3
+ export class DatabaseSelectors extends Page {
4
+ database: {select(parameters: Record<string, unknown>): unknown};
5
+ dbSelect(parameters: Record<string, unknown>): unknown;
6
+ }
@@ -0,0 +1,13 @@
1
+ import {Page} from './page-base.js';
2
+
3
+ /** Serve native dbSelect and dbComboBox from the selector service configured by the host. */
4
+ export class DatabaseSelectors extends Page {
5
+ dbSelect(parameters) {
6
+ if (Object.hasOwn(parameters, 'where')) {
7
+ throw new Error('SQL predicates belong in a dedicated server endpoint');
8
+ }
9
+ return this.database.select(parameters);
10
+ }
11
+ }
12
+
13
+ DatabaseSelectors.registerEndpoint('dbSelect');
@@ -12,7 +12,7 @@ import {basename, dirname, extname, join, relative, resolve, sep} from 'node:pat
12
12
  import {pathToFileURL} from 'node:url';
13
13
  import {gramlotDev} from './assets.js';
14
14
  import {fileBelow, inside, realFile} from './files.js';
15
- import {Page} from './page.js';
15
+ import {Page, PageStore} from './page.js';
16
16
  import {GramlotServer, PageNotFound} from './gramlot-server.js';
17
17
  import {InvalidResourceName, SEGMENT, parseRequires} from './resources.js';
18
18
 
@@ -84,6 +84,11 @@ export class GramlotFileServer extends GramlotServer {
84
84
  return (await import(await this._moduleUrl(await this.locatePage(path)))).Page;
85
85
  }
86
86
 
87
+ async resolvePageStore(PageClass, path) {
88
+ const module = await import(await this._moduleUrl(await this.locatePage(path)));
89
+ return Object.hasOwn(module, 'PageStore') ? module.PageStore : PageStore;
90
+ }
91
+
87
92
  /** Import route-eligible page modules at startup, without calling their methods. */
88
93
  async *iterPageClasses() {
89
94
  const seenFiles = new Set(), seenClasses = new Set();
@@ -60,12 +60,16 @@ export interface PreparedCollection {
60
60
  libraries?: Record<string, string>;
61
61
  }
62
62
 
63
+ import type {PageStore} from './page-store.js';
64
+
63
65
  /** The options of a `GramlotServer`. */
64
66
  export interface GramlotServerOptions {
65
67
  /** URL of the runtime bundle. */
66
68
  runtimeUrl?: string;
67
69
  /** URL of the request envelopes. */
68
70
  rpcUrl?: string;
71
+ websocketUrl?: string | null;
72
+ uploadUrl?: string | null;
69
73
  /** URL of the page close endpoint. */
70
74
  closeUrl?: string;
71
75
  /** Id of the root element of the page. */
@@ -120,6 +124,8 @@ export class GramlotServer {
120
124
  readonly markdownUrl: string;
121
125
  /** URL of the request envelopes. */
122
126
  rpcUrl: string;
127
+ websocketUrl: string | null;
128
+ uploadUrl: string | null;
123
129
  /** URL of the page close endpoint. */
124
130
  closeUrl: string;
125
131
  /** Id of the root element of the page. */
@@ -170,14 +176,15 @@ export class GramlotServer {
170
176
  /** The file of a `/themes/<path>` URL path whose real path is a file of the core themes, or null. Node.js and Bun only. */
171
177
  themeFile(path: string): Promise<string | null>;
172
178
  /** Register a page independently of its HTTP or Worker transport; `<path>/index.html` registers `<path>/`. */
173
- registerPage(path: string, options?: {owner?: unknown}): Promise<RegisteredPage>;
179
+ openChatImage(pageId: string, ref: string, options: {owner: unknown}): Promise<{bytes: Uint8Array; type: string} | null>;
180
+ registerPage(path: string, options?: {owner?: unknown; prefix?: string; websocketUrl?: string | null}): Promise<RegisteredPage>;
174
181
  /** Register the page and return its bootstrap; `prefix` is the mount prefix added to root-relative URLs. */
175
- openPage(path: string, options?: {owner?: unknown; prefix?: string}): Promise<OpenedPage>;
182
+ openPage(path: string, options?: {owner?: unknown; prefix?: string; websocketUrl?: string | null}): Promise<OpenedPage>;
176
183
  /** The text of a request body: UTF-8, a leading byte order mark removed; other bytes throw `InvalidRequest`. */
177
184
  decodeBody(data: ArrayBuffer | ArrayBufferView): string;
178
185
  /** Answer the request envelope `text` (TYTX) with the response envelope (TYTX); throws only `InvalidRequest`. `identity` is the trusted identity of this call, supplied to the fresh Page and `evaluateAuth`. */
179
186
  call(text: string, options?: {owner?: unknown; identity?: unknown}): Promise<string>;
180
- /** Admit a one-use upload after owner and operation authorization checks. */
187
+ /** Admit the next block after owner and operation authorization checks. */
181
188
  admitUpload(options: {pageId: string; transferId: string; authorization: string; owner?: unknown; identity?: unknown}): UploadTransfer;
182
189
  /** Close the page named by the close message `text` (`{"pageId": string}` as JSON) when `owner` owns it; throws `InvalidRequest`. */
183
190
  close(text: string, options?: {owner?: unknown}): void;
@@ -185,4 +192,13 @@ export class GramlotServer {
185
192
  closePage(pageId: string, options?: {owner?: unknown}): void;
186
193
  /** Forget every registered page; adapters call it on shutdown. */
187
194
  closeAll(): void;
195
+ resolvePageStore(PageClass: typeof Page, path: string): typeof PageStore | Promise<typeof PageStore>;
196
+ createPageStore(StoreClass: typeof PageStore, context: {pageId: string; owner: unknown}): PageStore;
197
+ pageStore(pageId: string, context: {owner: unknown}): PageStore;
198
+ connectPageChannel(pageId: string, send: (wire: string) => void, context: {owner: unknown}): void;
199
+ disconnectPageChannel(pageId: string, context: {owner: unknown}): void;
200
+ sharedStore<T extends PageStore>(key: string[], factory: () => T): T;
201
+ closeSharedStore(key: string[]): void;
202
+ preparePublish(text: string, context: {owner: unknown}): [string, (() => void) | null];
203
+ publishToPage(topic: string, payload: Record<string, unknown>, context: {sourcePageId: string; pageId: string; owner: unknown}): void;
188
204
  }