@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
@@ -2,15 +2,79 @@
2
2
  import {Bag} from '@genrojs/bag';
3
3
  import {defineComponent} from './registry.js';
4
4
  import {Container} from './container.js';
5
+ import icons from '../../themes/gramlot-index/icons.json' with {type:'json'};
5
6
  import {UploadEngine, readUploadContext} from './upload-engine.js';
6
7
 
8
+ // Built-in texts by language of the page locale; English when the language has none.
9
+ const TEXTS = {
10
+ en: {drop:['Drag a file here or', 'Drag files here or'], choose:['choose it from your computer', 'choose them from your computer'],
11
+ accepted:'Accepted', limit:'Per file', tooLarge:(name, limit) => `${name}: exceeds the ${limit} limit`,
12
+ summary:'Upload summary', filePreview:'File preview', upload:'Upload', remove:'Remove', preview:'Preview', cancel:'Cancel', retry:'Retry',
13
+ check:'Check status', one:'Select one file', notAccepted:name => `${name}: file type is not accepted`,
14
+ files:count => `${count} file${count === 1 ? '' : 's'}`, select:name => `Select ${name}`,
15
+ noPreview:'No preview available', previewFailed:message => `Preview failed: ${message}`,
16
+ status:{queued:'queued', preparing:'preparing', uploading:'uploading', completed:'completed', failed:'failed',
17
+ cancelled:'cancelled', uncertain:'uncertain'}},
18
+ it: {drop:['Trascina qui il file oppure', 'Trascina qui i file oppure'], choose:['sceglilo dal computer', 'sceglili dal computer'],
19
+ accepted:'Formati accettati', limit:'Limite per file', tooLarge:(name, limit) => `${name}: supera il limite di ${limit}`,
20
+ summary:'Riepilogo caricamenti', filePreview:'Anteprima file', upload:'Carica', remove:'Rimuovi', preview:'Anteprima', cancel:'Annulla', retry:'Riprova',
21
+ check:'Verifica', one:'Scegli un solo file', notAccepted:name => `${name}: formato non accettato`,
22
+ files:count => `${count} file`, select:name => `Scegli ${name}`,
23
+ noPreview:'Anteprima non disponibile', previewFailed:message => `Anteprima non riuscita: ${message}`,
24
+ status:{queued:'in coda', preparing:'in preparazione', uploading:'in caricamento', completed:'caricato',
25
+ failed:'non riuscito', cancelled:'annullato', uncertain:'da verificare'}},
26
+ };
27
+ const STYLE = `
28
+ :host{display:block}
29
+ button,input{font:inherit}
30
+ .drop{display:grid;justify-items:center;gap:.3rem;padding:1.4rem 1rem;text-align:center;cursor:pointer;
31
+ color:var(--gramlot-ink,inherit);background:var(--gramlot-surface-subtle,transparent);
32
+ border:1.5px dashed var(--gramlot-border-control,#8a8a8a);border-radius:var(--gramlot-radius,4px);
33
+ transition:border-color .12s,background-color .12s}
34
+ .drop:hover,.drop[data-over]{border-color:var(--gramlot-action,#1a5fb4)}
35
+ .drop[data-over]{background:color-mix(in srgb,var(--gramlot-action,#1a5fb4) 9%,transparent)}
36
+ .drop[aria-disabled=true]{opacity:.55;cursor:default}
37
+ .icon{inline-size:1.9rem;block-size:1.9rem;background:var(--gramlot-text-secondary,currentColor);mask:url("${icons.upload}") center / contain no-repeat}
38
+ .choose{padding:0;border:0;background:none;color:var(--gramlot-action,#1a5fb4);font-weight:600;cursor:pointer;text-decoration:underline;text-underline-offset:.15em}
39
+ button:focus-visible{outline:1px solid var(--gramlot-focus-ring,Highlight);outline-offset:-1px}
40
+ .hint{color:var(--gramlot-text-secondary,inherit);font-size:.875em}
41
+ .message:empty,.summary:empty,.preview:empty,.files:empty{display:none}
42
+ .message{color:var(--gramlot-error,#b13d48)}
43
+ .summary{color:var(--gramlot-text-secondary,inherit);font-size:.875em}
44
+ .files{display:grid;gap:.4rem;margin:.6rem 0 0;padding:0;list-style:none}
45
+ .files li{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:.3rem .8rem;padding:.5rem .7rem;
46
+ background:var(--gramlot-surface,transparent);border:1px solid var(--gramlot-border,#d0d0d0);border-radius:var(--gramlot-radius,4px)}
47
+ .files li[data-selected]{border-color:var(--gramlot-action,#1a5fb4)}
48
+ .file{display:flex;flex-wrap:wrap;align-items:baseline;gap:.2rem .6rem;min-inline-size:0}
49
+ .name{padding:0;border:0;background:none;color:inherit;font-weight:600;cursor:pointer;text-align:start;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-inline-size:100%}
50
+ .meta{color:var(--gramlot-text-secondary,inherit);font-size:.875em}
51
+ .files li[data-state=failed] .meta,.error{color:var(--gramlot-error,#b13d48)}
52
+ .files li[data-state=completed] .meta{color:var(--gramlot-success,var(--gramlot-text-secondary,inherit))}
53
+ .actions{display:flex;gap:.4rem}
54
+ .actions button{padding:.2rem .6rem;border:0;border-radius:var(--gramlot-radius,4px);
55
+ background:var(--gramlot-button-background,ButtonFace);color:inherit;font-size:.875em;cursor:pointer}
56
+ .actions button:hover{background:var(--gramlot-button-hover,ButtonFace)}
57
+ progress{grid-column:1/-1;inline-size:100%;block-size:.3rem;accent-color:var(--gramlot-action,#1a5fb4)}
58
+ .error{grid-column:1/-1;font-size:.875em}
59
+ .start{justify-self:start}
60
+ .preview{margin-block-start:.5rem}`;
61
+ function sizeText(bytes, language) {
62
+ const units = [[1048576, 'MB'], [1024, 'kB']];
63
+ for (const [factor, unit] of units) {
64
+ if (bytes >= factor) return `${(bytes / factor).toLocaleString(language, {maximumFractionDigits:1})} ${unit}`;
65
+ }
66
+ return `${bytes} ${language === 'it' ? 'byte' : 'bytes'}`;
67
+ }
68
+
7
69
  export const Uploader = defineComponent({
8
70
  name:'uploader', tag:'gramlot-uploader', base:Container, sourceContext:true,
9
71
  parameters:{operation:{dtype:'T'}, storepath:{dtype:'T'}, contextPath:{dtype:'T',nullable:true,default:null}, accept:{dtype:'T', default:'', binding:'read'},
10
72
  multiple:{dtype:'B', default:false, binding:'read'}, autoUpload:{dtype:'B', default:true, binding:'read'},
11
73
  manualUpload:{dtype:'B', default:true, binding:'read'},
12
74
  disabled:{dtype:'B', default:false, binding:'read'},
13
- selectedPath:{dtype:'T', nullable:true, default:null, binding:'twoWay'}, onComplete:{dtype:'T', nullable:true, default:null}},
75
+ selectedPath:{dtype:'T', nullable:true, default:null, binding:'twoWay'}, onComplete:{dtype:'T', nullable:true, default:null},
76
+ caption:{dtype:'T', nullable:true, default:null, binding:'read'},
77
+ maxBytes:{dtype:'L', nullable:true, default:null, binding:'read'}},
14
78
  implementation: Base => class extends Base {
15
79
  #context; #engine; #draining = false; #previewUrl = null; #previewId = null;
16
80
  #requestedPath; #selectedPath = null;
@@ -19,25 +83,47 @@ export const Uploader = defineComponent({
19
83
  this.control.replaceChildren();
20
84
  const doc = this.ownerDocument;
21
85
  const style = doc.createElement('style');
22
- style.textContent = ':host{display:block} .drop{border:1px dashed currentColor;padding:1em;display:grid;gap:.5em} ul{padding-inline-start:1.2em} button,input{font:inherit}';
86
+ style.textContent = STYLE;
23
87
  this.drop = doc.createElement('div'); this.drop.className = 'drop';
24
- const label = doc.createElement('label'); label.textContent = 'Choose files or drop them here ';
25
- this.input = doc.createElement('input'); this.input.type = 'file';
26
- label.append(this.input);
27
- this.startButton = doc.createElement('button'); this.startButton.type = 'button'; this.startButton.textContent = 'Upload';
28
- this.message = doc.createElement('div'); this.message.setAttribute('role','status');
29
- this.summary = doc.createElement('div'); this.summary.setAttribute('aria-label', 'Upload summary');
88
+ const icon = doc.createElement('span'); icon.className = 'icon'; icon.setAttribute('aria-hidden', 'true');
89
+ this.lead = doc.createElement('div');
90
+ this.leadText = doc.createElement('span');
91
+ this.chooseButton = doc.createElement('button'); this.chooseButton.type = 'button'; this.chooseButton.className = 'choose';
92
+ this.lead.append(this.leadText, doc.createTextNode(' '), this.chooseButton);
93
+ this.hint = doc.createElement('div'); this.hint.className = 'hint';
94
+ this.input = doc.createElement('input'); this.input.type = 'file'; this.input.hidden = true;
95
+ this.drop.append(icon, this.lead, this.hint, this.input);
96
+ this.startButton = doc.createElement('button'); this.startButton.type = 'button'; this.startButton.className = 'start';
97
+ this.message = doc.createElement('div'); this.message.className = 'message'; this.message.setAttribute('role','status');
98
+ this.summary = doc.createElement('div'); this.summary.className = 'summary';
30
99
  this.summary.setAttribute('aria-live', 'polite');
31
- this.list = doc.createElement('ul');
32
- this.preview = doc.createElement('div'); this.preview.setAttribute('aria-label', 'File preview');
33
- this.drop.append(label, this.startButton, this.message, this.summary, this.list, this.preview); this.control.append(this.drop);
100
+ this.list = doc.createElement('ul'); this.list.className = 'files';
101
+ this.preview = doc.createElement('div'); this.preview.className = 'preview';
102
+ this.control.append(this.drop, this.startButton, this.message, this.summary, this.list, this.preview);
34
103
  this.shadowRoot.append(style);
104
+ this.chooseButton.addEventListener('click', event => { event.stopPropagation(); if (!this.parameters?.disabled) this.input.click(); });
105
+ this.drop.addEventListener('click', event => {
106
+ if (event.target !== this.input && !this.parameters?.disabled) this.input.click();
107
+ });
108
+ const over = event => {
109
+ if (!Array.from(event.dataTransfer.types).includes('Files')) return;
110
+ event.preventDefault(); event.stopPropagation();
111
+ event.dataTransfer.dropEffect = this.parameters.disabled ? 'none' : 'copy';
112
+ this.drop.toggleAttribute('data-over', !this.parameters.disabled);
113
+ };
114
+ this.drop.addEventListener('dragenter', over);
115
+ this.drop.addEventListener('dragover', over);
116
+ this.drop.addEventListener('dragleave', event => { if (!this.drop.contains(event.relatedTarget)) delete this.drop.dataset.over; });
35
117
  this.input.addEventListener('change', () => { this.#add(this.input.files); this.input.value = ''; });
36
118
  this.startButton.addEventListener('click', () => {
37
119
  if (this.parameters.manualUpload && !this.parameters.autoUpload) void this.#startAll();
38
120
  });
39
- this.drop.addEventListener('dragover', event => { if (!this.parameters?.disabled && [...event.dataTransfer.types].includes('Files')) { event.preventDefault(); event.stopPropagation(); event.dataTransfer.dropEffect = 'copy'; } });
40
- this.drop.addEventListener('drop', event => { if (!this.parameters?.disabled && [...event.dataTransfer.types].includes('Files')) { event.preventDefault(); event.stopPropagation(); this.#add(event.dataTransfer.files); } });
121
+ this.drop.addEventListener('drop', event => {
122
+ this.drop.removeAttribute('data-over');
123
+ if (!Array.from(event.dataTransfer.types).includes('Files')) return;
124
+ event.preventDefault(); event.stopPropagation();
125
+ this.#add(event.dataTransfer.files);
126
+ });
41
127
  }
42
128
  setSourceContext(context) { this.#context = context; }
43
129
  /** The queue Bag, read at the storepath address at each use; the uploader never keeps it. */
@@ -60,6 +146,22 @@ export const Uploader = defineComponent({
60
146
  this.input.disabled = Boolean(this.parameters.disabled);
61
147
  this.startButton.disabled = Boolean(this.parameters.disabled);
62
148
  this.startButton.hidden = Boolean(this.parameters.autoUpload || !this.parameters.manualUpload);
149
+ const texts = this.#texts(), many = this.parameters.multiple ? 1 : 0;
150
+ this.leadText.textContent = this.parameters.caption || texts.drop[many];
151
+ this.chooseButton.textContent = texts.choose[many];
152
+ this.chooseButton.disabled = Boolean(this.parameters.disabled);
153
+ this.drop.setAttribute('aria-disabled', String(Boolean(this.parameters.disabled)));
154
+ const {accept, maxBytes, disabled} = this.parameters;
155
+ if (maxBytes !== null && (!Number.isSafeInteger(maxBytes) || maxBytes < 0))
156
+ throw new TypeError('maxBytes must be a nonnegative safe integer');
157
+ const hints = [];
158
+ if (accept) hints.push(`${texts.accepted}: ${accept.split(',').map(value => value.trim()).join(', ')}`);
159
+ if (maxBytes !== null) hints.push(`${texts.limit}: ${sizeText(maxBytes, this.#language())}`);
160
+ this.hint.textContent = hints.join(' · ');
161
+ this.summary.setAttribute('aria-label', texts.summary);
162
+ this.preview.setAttribute('aria-label', texts.filePreview);
163
+ if (disabled) this.drop.removeAttribute('data-over');
164
+ this.startButton.textContent = texts.upload;
63
165
  if (this.parameters.selectedPath !== this.#requestedPath) {
64
166
  this.#requestedPath = this.parameters.selectedPath;
65
167
  this.#selectedPath = this.parameters.selectedPath;
@@ -74,6 +176,11 @@ export const Uploader = defineComponent({
74
176
  }
75
177
  return rest;
76
178
  }
179
+ #language() {
180
+ const language = this.#context.locale.split('-')[0].toLowerCase();
181
+ return TEXTS[language] ? language : 'en';
182
+ }
183
+ #texts() { return TEXTS[this.#language()]; }
77
184
  #ensureEngine() {
78
185
  if (!this.#engine && this.#context && this.parameters) {
79
186
  const {gramlot, window} = this.#context.upload();
@@ -94,13 +201,18 @@ export const Uploader = defineComponent({
94
201
  #add(files) {
95
202
  if (!this.#engine || this.parameters.disabled) return;
96
203
  const selected = [...files];
97
- if (!this.parameters.multiple && selected.length > 1) { this.message.textContent = 'Select one file'; return; }
204
+ this.message.textContent = '';
205
+ if (!this.parameters.multiple && selected.length > 1) { this.message.textContent = this.#texts().one; return; }
98
206
  const accepted = (this.parameters.accept || '').split(',').map(value => value.trim().toLowerCase()).filter(Boolean);
99
207
  for (const file of selected) {
100
208
  const filename = file.name.toLowerCase(), type = (file.type || '').toLowerCase();
101
209
  if (accepted.length && !accepted.some(rule => rule.startsWith('.') ? filename.endsWith(rule) :
102
210
  rule.endsWith('/*') ? type.startsWith(rule.slice(0, -1)) : type === rule)) {
103
- this.message.textContent = `${file.name}: file type is not accepted`; continue;
211
+ this.message.textContent = this.#texts().notAccepted(file.name); continue;
212
+ }
213
+ if (this.parameters.maxBytes !== null && file.size > this.parameters.maxBytes) {
214
+ this.message.textContent = this.#texts().tooLarge(file.name, sizeText(this.parameters.maxBytes, this.#language()));
215
+ continue;
104
216
  }
105
217
  this.#engine.add(file);
106
218
  }
@@ -144,14 +256,15 @@ export const Uploader = defineComponent({
144
256
  if (this.#previewId !== id || !this.isConnected) return;
145
257
  const pre = this.ownerDocument.createElement('pre'); pre.textContent = text;
146
258
  pre.style.maxHeight = '200px'; pre.style.overflow = 'auto'; this.preview.append(pre);
147
- } catch (error) { if (this.#previewId === id) this.preview.textContent = `Preview failed: ${error.message}`; }
259
+ } catch (error) { if (this.#previewId === id) this.preview.textContent = this.#texts().previewFailed(error.message); }
148
260
  return;
149
261
  }
150
- this.preview.textContent = 'No preview available';
262
+ this.preview.textContent = this.#texts().noPreview;
151
263
  }
152
264
  #render() {
153
265
  if (!this.list || !this.#context) return;
154
- const nodes = this.#storeBag().getNodes();
266
+ const nodes = this.#storeBag().getNodes(), texts = this.#texts(), language = this.#language();
267
+ const doc = this.ownerDocument;
155
268
  this.list.replaceChildren();
156
269
  const counts = new Map();
157
270
  let loaded = 0, size = 0;
@@ -160,51 +273,59 @@ export const Uploader = defineComponent({
160
273
  counts.set(state, (counts.get(state) ?? 0) + 1);
161
274
  loaded += row.getItem('loaded'); size += row.getItem('size');
162
275
  }
163
- this.summary.textContent = `${nodes.length} file${nodes.length === 1 ? '' : 's'} — ${loaded}/${size} bytes` +
164
- [...counts].map(([state, count]) => ` · ${count} ${state}`).join('');
276
+ this.summary.textContent = nodes.length < 2 ? '' : `${texts.files(nodes.length)} — ${sizeText(loaded, language)} / ${sizeText(size, language)}` +
277
+ [...counts].map(([state, count]) => ` · ${count} ${texts.status[state] ?? state}`).join('');
278
+ const action = (caption, handler, disabled = false) => {
279
+ const button = doc.createElement('button'); button.type = 'button'; button.textContent = caption;
280
+ button.disabled = disabled; button.addEventListener('click', handler); return button;
281
+ };
165
282
  for (const node of nodes) {
166
283
  // The listeners keep the row key only: the row is read at the queue address when they run.
167
- const row = node.value, label = node.label, item = this.ownerDocument.createElement('li');
168
- const select = this.ownerDocument.createElement('button');
169
- select.type = 'button'; select.textContent = row.getItem('name');
284
+ const row = node.value, label = node.label, state = row.getItem('status'), item = doc.createElement('li');
285
+ item.dataset.state = state;
286
+ if (label === this.#selectedPath) item.dataset.selected = '';
287
+ const file = doc.createElement('div'); file.className = 'file';
288
+ const select = doc.createElement('button');
289
+ select.type = 'button'; select.className = 'name'; select.textContent = row.getItem('name');
170
290
  select.disabled = Boolean(this.parameters.disabled);
171
291
  select.setAttribute('aria-pressed', String(label === this.#selectedPath));
172
- select.setAttribute('aria-label', `Select ${row.getItem('name')}`);
292
+ select.setAttribute('aria-label', texts.select(row.getItem('name')));
173
293
  select.addEventListener('click', () => {
174
294
  this.#select(label);
175
- const index = this.#storeBag().getNodes().findIndex(item => item.label === label);
176
- if (index >= 0) this.list.children[index].firstElementChild.focus();
295
+ const index = this.#storeBag().getNodes().findIndex(entry => entry.label === label);
296
+ if (index >= 0) this.list.children[index].querySelector('.name').focus();
177
297
  });
178
- item.append(select, this.ownerDocument.createTextNode(` — ${row.getItem('status')} (${row.getItem('loaded')}/${row.getItem('size')}) `));
179
- const state = row.getItem('status');
298
+ const meta = doc.createElement('span'); meta.className = 'meta';
299
+ meta.textContent = `${sizeText(row.getItem('size'), language)} · ${texts.status[state] ?? state}`;
300
+ file.append(select, meta);
301
+ const actions = doc.createElement('div'); actions.className = 'actions';
180
302
  if (['preparing','uploading'].includes(state)) {
181
- const button = this.ownerDocument.createElement('button'); button.textContent = 'Cancel'; button.type = 'button';
182
- button.addEventListener('click', () => this.#engine.cancel(label)); item.append(button);
303
+ actions.append(action(texts.cancel, () => this.#engine.cancel(label)));
183
304
  } else if (['failed','cancelled'].includes(state)) {
184
- const button = this.ownerDocument.createElement('button'); button.textContent = 'Retry'; button.type = 'button'; button.disabled = Boolean(this.parameters.disabled);
185
- button.addEventListener('click', () => { this.#engine.retry(label); if (this.parameters.autoUpload) void this.#startAll(); }); item.append(button);
186
- }
187
- if (state === 'uncertain') {
188
- const button = this.ownerDocument.createElement('button'); button.textContent = 'Check status'; button.type = 'button';
189
- button.addEventListener('click', () => void this.#engine.reconcile(label)); item.append(button);
305
+ actions.append(action(texts.retry, () => { this.#engine.retry(label); if (this.parameters.autoUpload) void this.#startAll(); },
306
+ Boolean(this.parameters.disabled)));
190
307
  }
308
+ if (state === 'uncertain') actions.append(action(texts.check, () => void this.#engine.reconcile(label)));
191
309
  if (['queued','completed','failed','cancelled'].includes(state)) {
192
- const file = this.#engine?.localFile(label);
193
- if (file) {
194
- const preview = this.ownerDocument.createElement('button'); preview.textContent = 'Preview'; preview.type = 'button';
195
- preview.addEventListener('click', () => void this.#showPreview(label, file)); item.append(preview);
196
- }
197
- const remove = this.ownerDocument.createElement('button'); remove.textContent = 'Remove'; remove.type = 'button';
198
- remove.disabled = Boolean(this.parameters.disabled);
199
- remove.addEventListener('click', () => {
310
+ const local = this.#engine?.localFile(label);
311
+ if (local) actions.append(action(texts.preview, () => void this.#showPreview(label, local)));
312
+ actions.append(action(texts.remove, () => {
200
313
  if (this.#engine.remove(label)) {
201
314
  if (this.#previewId === label) this.#clearPreview();
202
315
  if (this.#selectedPath === label) this.#select(null);
203
316
  }
204
- });
205
- item.append(remove);
317
+ }, Boolean(this.parameters.disabled)));
318
+ }
319
+ item.append(file, actions);
320
+ const progress = doc.createElement('progress');
321
+ progress.max = row.getItem('size') || 1;
322
+ progress.value = state === 'completed' ? progress.max : row.getItem('loaded');
323
+ progress.setAttribute('aria-label', row.getItem('name'));
324
+ item.append(progress);
325
+ if (row.getItem('error')) {
326
+ const error = doc.createElement('div'); error.className = 'error'; error.textContent = row.getItem('error');
327
+ item.append(error);
206
328
  }
207
- if (row.getItem('error')) item.append(this.ownerDocument.createTextNode(` ${row.getItem('error')}`));
208
329
  this.list.append(item);
209
330
  }
210
331
  }
package/src/gramlot.js CHANGED
@@ -1,3 +1,4 @@
1
+ import {IconRegistry} from './icons.js';
1
2
  /* @ts-self-types="./gramlot.d.ts" */
2
3
  /**
3
4
  * One Gramlot page in the browser.
@@ -12,6 +13,7 @@ import {FrameMessages} from './frame-messages.js';
12
13
  import {NAME_SYNTAX, NameSyntax} from './builder/name-syntax.js';
13
14
  import {SourceHandler} from './handlers/source-handler.js';
14
15
  import {RpcHandler} from './handlers/rpc-handler.js';
16
+ import {PageTheme} from './index-theme.js';
15
17
  import {DomHandler} from './handlers/dom-handler.js';
16
18
  import {SubscriptionsHandler} from './handlers/subscriptions-handler.js';
17
19
  import {DeviceHandler} from './handlers/device-handler.js';
@@ -36,6 +38,7 @@ export class Gramlot {
36
38
  this.#collections = [buttons, ...collections.filter(collection => collection instanceof ComponentCollection)];
37
39
  this.registerDocument(document);
38
40
  this.commands = new CommandRegistry();
41
+ Object.defineProperty(this, '_icons', {value:new IconRegistry()});
39
42
  this.pageId = pageId;
40
43
  this.uploadUrl = uploadUrl;
41
44
  const browserContext = locale == null || timeZone == null
@@ -50,11 +53,11 @@ export class Gramlot {
50
53
  subscriptions: this._subscriptions, nameSyntax: nameSyntax === null ? NAME_SYNTAX : NameSyntax.fromJSON(nameSyntax)});
51
54
  this.#mobileEnvironment = MobileEnvironment.install({document,root:this.src.renderer.destination});
52
55
  this.data = this.src.builder.data;
56
+ this.abort = new AbortController();
53
57
  this.dvc = new DeviceHandler(this);
54
- this.dom = new DomHandler(this);
58
+ this.dom = new DomHandler(this, new PageTheme(this));
55
59
  this.utl = new UtilitiesHandler(this, document);
56
60
  this.state = 'ready';
57
- this.abort = new AbortController();
58
61
  Object.defineProperty(this, '_frames', {value: new FrameMessages(this, document)});
59
62
  if (websocketUrl !== null) this._pageStore = new PageStoreConnection(this, websocketUrl, document);
60
63
  this.rpc = new RpcHandler(this, {rpcUrl, closeUrl, document, transport});
@@ -98,7 +101,7 @@ export class Gramlot {
98
101
  }
99
102
  if (this.state === 'disposed') throw new Error('Gramlot was disposed during main');
100
103
  try {
101
- return this.src.mountMainSource(wire.value, wire.data);
104
+ return this.src.mountMainSource(wire.value, wire.data, wire.sourceFormat);
102
105
  } catch (error) {
103
106
  if (this.state !== 'disposed') this.state = 'failed';
104
107
  throw error;
@@ -10,6 +10,8 @@ import {Handler} from './handler.js';
10
10
 
11
11
  /** The DOM and its correspondence with the Source. */
12
12
  export class DomHandler extends Handler {
13
+ setFrameAppearance(appearance: string): void;
14
+ mountIndexTheme(path: string): () => void;
13
15
  /** Navigate the current document to an absolute HTTP(S) URL without credentials. */
14
16
  navigate(url: string): void;
15
17
  setTouchMode(mode?: 'auto' | 'on' | 'off'): void;
@@ -8,6 +8,15 @@ import {Handler} from './handler.js';
8
8
 
9
9
  /** The DOM and its correspondence with the Source. */
10
10
  export class DomHandler extends Handler {
11
+ #theme;
12
+ constructor(gramlot, theme) {
13
+ super(gramlot);
14
+ this.#theme = theme;
15
+ }
16
+ setFrameAppearance(appearance) { this.#theme.setFrameAppearance(appearance); }
17
+ /** Connect the common index settings to this document and its owned pages. */
18
+ mountIndexTheme(path) { return this.#theme.mount(path); }
19
+
11
20
  /** Size controls for the input device without rebuilding the page. */
12
21
  setTouchMode(mode = 'auto') {
13
22
  if (!['auto', 'on', 'off'].includes(mode)) throw new TypeError(`Invalid touch mode: ${mode}`);
@@ -86,7 +86,7 @@ export class RpcHandler extends Handler {
86
86
  /** Return the checked response envelope, including optional initial-main Data. */
87
87
  callEnvelope(contentType: 'source' | 'data' | 'upload', name: string, params?: Record<string, unknown>,
88
88
  options?: {signal?: AbortSignal | null}): Promise<{
89
- id: string; contentType: string; value: unknown; data?: import('@genrojs/bag').Bag;
89
+ id: string; contentType: string; value: unknown; sourceFormat?: 'xml'; data?: import('@genrojs/bag').Bag; icons?: Record<string, string>;
90
90
  }>;
91
91
  /** Send one envelope synchronously; only with a transport that supports it. */
92
92
  callSync(contentType: 'source' | 'data' | 'upload', name: string, params?: Record<string, unknown>): unknown;
@@ -78,6 +78,7 @@ export class RpcHandler extends Handler {
78
78
  const response = fromTytx(this.transport.callSync(toTytx({id, pageId: this.gramlot.pageId, contentType, name, params})));
79
79
  if (response.id !== id) throw new Error('rpc response id mismatch');
80
80
  if (response.error) throw new RpcError(response.error);
81
+ if (contentType === "source" && response.icons) this.gramlot._icons.receive(response.icons);
81
82
  return response.value;
82
83
  }
83
84
 
@@ -109,6 +110,7 @@ export class RpcHandler extends Handler {
109
110
  const response = fromTytx(await Promise.race([this.transport.call(text, controller.signal), aborted]));
110
111
  if (response.id !== id) throw new Error('rpc response id mismatch');
111
112
  if (response.error) throw new RpcError(response.error);
113
+ if (contentType === "source" && response.icons) this.gramlot._icons.receive(response.icons);
112
114
  return response;
113
115
  } finally {
114
116
  this.remoteRequests.delete(id);
@@ -35,16 +35,18 @@ export class SourceHandler extends Handler {
35
35
  nameSyntax: NameSyntax});
36
36
  /** The builder of a page: the prepared grammar of the standard collections in one step when `collections`
37
37
  * start with them in its order, then the other collections one by one (GC-325 §165). */
38
+ createPageBuilder(): GramlotBuilder;
38
39
  static pageBuilder(collections: unknown[], nameSyntax: NameSyntax | undefined): GramlotBuilder;
39
40
  /** Start from an embedded typed Source, with the same observed insertion as `main`. */
40
41
  startSource(wire: SourceBag | string): Gramlot;
41
42
  /** Validate and insert `main` in the Source. */
42
- mountMainSource(wire: SourceBag | string, initialData?: Bag | null): Gramlot;
43
+ mountMainSource(wire: SourceBag | string, initialData?: Bag | null, sourceFormat?: 'xml'): Gramlot;
44
+ installInitialData(data: Bag, destination?: Bag): void;
43
45
  /**
44
- * A Source from a SourceBag or a TYTX wire; only Gramlot Source Bags are accepted, before any
46
+ * A typed Source from a SourceBag, a TYTX wire or an explicitly tagged XML recipe, before any
45
47
  * effect. The received Source activates its inline code.
46
48
  */
47
- prepareSource(wire: SourceBag | string, builder?: GramlotBuilder): SourceBag;
49
+ prepareSource(wire: SourceBag | string, builder?: GramlotBuilder, sourceFormat?: 'xml'): SourceBag;
48
50
  /**
49
51
  * Replace the children of one Source node with a remote Source, only after the incoming Source
50
52
  * validates. Resolves with true when mounted, false otherwise: the target left the Source, the page
@@ -9,6 +9,7 @@ import {SourceBag, sourceBagFromTytx} from '@genrojs/builders';
9
9
  import {Handler} from './handler.js';
10
10
  import {GramlotBuilder} from '../builder/gramlot-builder.js';
11
11
  import {GramlotBuilderBag} from '../builder/source.js';
12
+ import {readXmlRecipe, readXmlRecipeDocument} from '../builder/xml-recipe.js';
12
13
  import {GramlotRenderer} from '../renderer/gramlot-renderer.js';
13
14
  import {BindingRuntime} from '../binding/runtime.js';
14
15
  import {LogicRegistry} from '../binding/logic.js';
@@ -26,7 +27,8 @@ export class SourceHandler extends Handler {
26
27
  // The BindingRuntime reaches the builder through gramlot.src while it attaches.
27
28
  gramlot.src = this;
28
29
  this.logicRegistry = new LogicRegistry(gramlot);
29
- this.builder = SourceHandler.pageBuilder(collections, nameSyntax);
30
+ this.createPageBuilder = () => SourceHandler.pageBuilder(collections, nameSyntax);
31
+ this.builder = this.createPageBuilder();
30
32
  this.binding = new BindingRuntime(gramlot, {subscriptions});
31
33
  this.builder.binding = this.binding;
32
34
  this.binding.attach();
@@ -62,17 +64,21 @@ export class SourceHandler extends Handler {
62
64
  * new one; the Data is not rolled back. A later error (`_init`, DOM) keeps `main` and its
63
65
  * NodeBindings (P12, no rollback).
64
66
  */
65
- mountMainSource(wire, initialData = null) {
66
- const source = this.prepareSource(wire);
67
+ mountMainSource(wire, initialData = null, sourceFormat) {
68
+ let recipeData = null;
69
+ if (sourceFormat === 'xml') {
70
+ const recipe = readXmlRecipeDocument(wire, this.builder, this.renderer.destination.ownerDocument.defaultView.DOMParser);
71
+ wire = recipe.source;
72
+ recipeData = recipe.data;
73
+ sourceFormat = undefined;
74
+ }
75
+ const source = this.prepareSource(wire, this.builder, sourceFormat);
67
76
  this.renderer.validateCandidate(source);
68
- if (initialData !== null) {
69
- if (!(initialData instanceof Bag) || initialData instanceof SourceBag) {
70
- throw new TypeError('Initial page data must be a Data Bag');
71
- }
72
- for (const node of initialData.getNodes()) {
73
- this.builder.data.setItem([node.label], node.getValue(), node.attr, '>', false, false);
74
- }
77
+ if (initialData !== null && (!(initialData instanceof Bag) || initialData instanceof SourceBag)) {
78
+ throw new TypeError('Initial page data must be a Data Bag');
75
79
  }
80
+ if (recipeData) this.installInitialData(recipeData);
81
+ if (initialData) this.installInitialData(initialData);
76
82
  try {
77
83
  this.source.setItem('main', source);
78
84
  } catch (error) {
@@ -84,12 +90,24 @@ export class SourceHandler extends Handler {
84
90
  this.binding.subscriptions.ready();
85
91
  return this.gramlot;
86
92
  }
93
+ /** Apply the document's declared Data at the page root or at an editor's preview root. */
94
+ installInitialData(data, destination = this.builder.data) {
95
+ for (const node of data.getNodes()) {
96
+ destination.setItem([node.label], node.getValue(), node.attr, '>', false, false);
97
+ }
98
+ }
99
+
87
100
  /**
88
- * A Source from a SourceBag or a TYTX wire; only GramlotBuilderBag is accepted, before any effect (R07).
101
+ * Read an explicitly tagged XML recipe, a typed SourceBag or a TYTX wire into the target Builder.
89
102
  * The received Source activates its inline code: the only inline code the page runs. Activation is
90
103
  * here and not in the TYTX decoding, because a GramlotBuilderBag can also arrive inside Data.
91
104
  */
92
- prepareSource(wire, builder = this.builder) {
105
+ prepareSource(wire, builder = this.builder, sourceFormat) {
106
+ if (sourceFormat !== undefined) {
107
+ if (sourceFormat !== 'xml') throw new TypeError(`Unknown Source format: ${sourceFormat}`);
108
+ const {DOMParser} = this.renderer.destination.ownerDocument.defaultView;
109
+ wire = readXmlRecipe(wire, builder, DOMParser);
110
+ }
93
111
  if (wire instanceof SourceBag) {
94
112
  if (!(wire instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
95
113
  return wire.bindBuilder(builder).activateCode();
@@ -132,7 +150,7 @@ export class SourceHandler extends Handler {
132
150
  try {
133
151
  const wire = await binding.call('source', request);
134
152
  if (!current()) return false;
135
- const prepared = this.prepareSource(wire, target.builder);
153
+ const prepared = this.prepareSource(wire.value, target.builder, wire.sourceFormat);
136
154
  if (!current()) return false;
137
155
  this.renderer.validateCandidate(prepared, {replacingNode: target});
138
156
  applying = true;
package/src/icons.js ADDED
@@ -0,0 +1,84 @@
1
+ /** Page-owned icon names and image assets, shared by all presentations. */
2
+ import standardIcons from '../themes/gramlot-index/icons.json' with {type:'json'};
3
+
4
+ const namePattern = /^[A-Za-z][A-Za-z0-9_-]*$/;
5
+ const contexts = new WeakMap();
6
+ export function iconAsset(value) {
7
+ if (typeof value !== 'string' || !value || value !== value.trim()) throw new TypeError('An icon asset must be a nonempty URL or path');
8
+ if (/^(?:https?:|data:image\/|blob:)/i.test(value) || (!/^[a-z][a-z0-9+.-]*:/i.test(value) && /[/.]/.test(value))) return value;
9
+ throw new TypeError(`Invalid icon asset: ${value}`);
10
+ }
11
+ export class IconRegistry {
12
+ #custom = new Map();
13
+ add(name, asset) {
14
+ if (typeof name !== 'string' || !namePattern.test(name)) throw new TypeError(`Invalid icon name: ${name}`);
15
+ if (Object.hasOwn(standardIcons, name) || this.#custom.has(name)) throw new Error(`Duplicate icon: ${name}`);
16
+ this.#custom.set(name, iconAsset(asset));
17
+ }
18
+ resolve(value) {
19
+ if (value == null || value === '') return '';
20
+ if (typeof value !== 'string') throw new TypeError('icon must be a name or an asset URL');
21
+ if (namePattern.test(value)) {
22
+ const asset = this.#custom.get(value) ?? (Object.hasOwn(standardIcons, value) ? standardIcons[value] : null);
23
+ if (asset == null) throw new Error(`Unknown icon: ${value}`);
24
+ return asset;
25
+ }
26
+ return iconAsset(value);
27
+ }
28
+ definitions() { return Object.fromEntries(this.#custom); }
29
+ /** Repeated Source responses may carry the same declaration; conflicting definitions fail. */
30
+ receive(definitions) {
31
+ if (!definitions || typeof definitions !== 'object' || Array.isArray(definitions)) throw new TypeError('Invalid icon definitions');
32
+ for (const [name, asset] of Object.entries(definitions)) {
33
+ if (this.#custom.get(name) === asset) continue;
34
+ this.add(name, asset);
35
+ }
36
+ }
37
+ }
38
+ const defaults = new IconRegistry();
39
+ export function bindIcons(element, registry) { contexts.set(element, registry); }
40
+ export function iconSource(element, value) { return (contexts.get(element) ?? defaults).resolve(value); }
41
+ export function renderIcon(element, target, value) {
42
+ target.setAttribute('iconslot', '');
43
+ target.setAttribute('aria-hidden', 'true');
44
+ const asset = iconSource(element, value);
45
+ for (const name of ['size','color','opacity','original']) target.style.removeProperty(`--gramlot-icon-${name}`);
46
+ Object.assign(target.style, {position:'relative', display:'inline-block', flex:'none', verticalAlign:'middle',
47
+ width:'var(--gramlot-icon-size,var(--gramlot-toolbar-icon-size,1em))',
48
+ height:'var(--gramlot-icon-size,var(--gramlot-toolbar-icon-size,1em))'});
49
+ if (!asset) { target.replaceChildren(); target.style.display = 'none'; return; }
50
+ let image = target.querySelector('img');
51
+ if (!image) {
52
+ image = target.ownerDocument.createElement('img'); image.alt = ''; image.draggable = false;
53
+ const tint = target.ownerDocument.createElement('span');
54
+ tint.style.cssText = 'position:absolute;inset:0;background:var(--gramlot-icon-color,transparent);mask:var(--gramlot-icon-image) center / contain no-repeat;opacity:var(--gramlot-icon-opacity,1);pointer-events:none';
55
+ image.style.cssText = 'display:block;width:100%;height:100%;object-fit:contain;visibility:var(--gramlot-icon-original,visible);opacity:var(--gramlot-icon-opacity,1)';
56
+ target.replaceChildren(image, tint);
57
+ }
58
+ if (image.getAttribute('src') !== asset) image.setAttribute('src', asset);
59
+ target.style.setProperty('--gramlot-icon-image', 'url(' + JSON.stringify(asset) + ')');
60
+ }
61
+
62
+ /** Read resolved attributes, so normal Source bindings also drive icon presentation. */
63
+ export function projectIconAttributes(attrs, rest, document) {
64
+ if (!['icon_size','icon_color','icon_opacity'].some(key => attrs[key] != null)) return rest;
65
+ const style = document.createElement('span').style;
66
+ style.cssText = rest.style ?? '';
67
+ const {icon_size:size, icon_color:color, icon_opacity:opacity} = attrs;
68
+ if (size != null) {
69
+ if (typeof size === 'number' && (!Number.isFinite(size) || size <= 0)) throw new RangeError('icon_size must be positive');
70
+ style.setProperty('--gramlot-icon-size', typeof size === 'number' ? `${size}px` : size);
71
+ }
72
+ if (color != null && color !== '') {
73
+ style.setProperty('--gramlot-icon-color', color);
74
+ style.setProperty('--gramlot-icon-original', 'hidden');
75
+ }
76
+ if (opacity != null) {
77
+ if (typeof opacity !== 'number' || !Number.isFinite(opacity) || opacity < 0 || opacity > 1) throw new RangeError('icon_opacity must be between 0 and 1');
78
+ style.setProperty('--gramlot-icon-opacity', String(opacity));
79
+ }
80
+ const result = {...rest};
81
+ for (const key of ['icon_size','icon_color','icon_opacity']) delete result[key];
82
+ if (style.cssText || rest.style != null) result.style = style.cssText;
83
+ return result;
84
+ }