@gramlot/gramlot 0.3.26 → 0.3.30

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 (213) hide show
  1. package/assets/icons/chart.svg +1 -0
  2. package/dist/components/audio/__init__.py +13 -0
  3. package/dist/components/audio/assets/collection.js +3 -0
  4. package/dist/components/audio/assets/index.js +3 -0
  5. package/dist/components/audio/commands.json +7 -0
  6. package/dist/components/audio/grammar.json +335 -0
  7. package/dist/components/charts/__init__.py +13 -0
  8. package/dist/components/charts/assets/collection.js +47 -0
  9. package/dist/components/charts/assets/files/55ea01207028f76d844678511f29fc800f8a1e67a8a0fe80470128677847ad32-echarts-gl.txt +29 -0
  10. package/dist/components/charts/assets/files/63727832aaf62004a2b249c933e327f3c90caf49e41a72f4bf436edf632cbda8-vega.txt +27 -0
  11. package/dist/components/charts/assets/files/8c45d9eaf50c2f72dd9c7ab9ef440788ba58a3538484b5c51c1f17d5128752e7-plotly.txt +21 -0
  12. package/dist/components/charts/assets/files/8f989229699b4fe2f1a0432d0e9edc338a8a911e250e2d1b01ecd770a5f5b1bd-uplot.txt +21 -0
  13. package/dist/components/charts/assets/files/c8fa058cba98f7f288b5d8fa4116f441d6dacb25b96da859e518c973fff41d0c-claygl.txt +23 -0
  14. package/dist/components/charts/assets/index.js +3 -0
  15. package/dist/components/charts/assets/modules/chunk-2CCTLZE7.js +76 -0
  16. package/dist/components/charts/assets/modules/chunk-RMRBEYTI.js +1 -0
  17. package/dist/components/charts/assets/modules/echarts-gl-CXVTZA6G.js +4409 -0
  18. package/dist/components/charts/assets/modules/plotly.min-4LB7HE7P.js +3596 -0
  19. package/dist/components/charts/assets/modules/uPlot.esm-5JJNHHRF.js +3 -0
  20. package/dist/components/charts/assets/modules/uPlot.min-N3E3FA74.js +1 -0
  21. package/dist/components/charts/assets/modules/vega.module-2QCOVQ3A.js +13 -0
  22. package/dist/components/charts/commands.json +7 -0
  23. package/dist/components/charts/grammar.json +1113 -0
  24. package/dist/components/chat/__init__.py +1 -1
  25. package/dist/components/chat/assets/collection.js +3 -3
  26. package/dist/components/chat/assets/index.js +1 -1
  27. package/dist/components/drawing/__init__.py +15 -0
  28. package/dist/components/drawing/assets/collection.js +28 -0
  29. package/dist/components/drawing/assets/index.js +3 -0
  30. package/dist/components/drawing/commands.json +7 -0
  31. package/dist/components/drawing/grammar.json +110 -0
  32. package/dist/components/editors/__init__.py +2 -2
  33. package/dist/components/editors/assets/collection.js +18 -18
  34. package/dist/components/editors/assets/index.js +1 -1
  35. package/dist/components/editors/assets/modules/{prose-mirror-engine-GMZPJPNN.js → prose-mirror-engine-DQEAEIMV.js} +2 -2
  36. package/dist/components/editors/grammar.json +150 -0
  37. package/dist/components/grid/__init__.py +1 -1
  38. package/dist/components/grid/assets/collection.js +63 -33
  39. package/dist/components/grid/assets/index.js +1 -1
  40. package/dist/components/grid/grammar.json +279 -0
  41. package/dist/components/grouplets/__init__.py +1 -1
  42. package/dist/components/grouplets/assets/collection.js +3 -3
  43. package/dist/components/grouplets/assets/index.js +1 -1
  44. package/dist/components/inputs/__init__.py +3 -2
  45. package/dist/components/inputs/assets/collection.js +38 -23
  46. package/dist/components/inputs/assets/index.js +1 -1
  47. package/dist/components/inputs/grammar.json +1533 -321
  48. package/dist/components/layout/__init__.py +1 -1
  49. package/dist/components/layout/assets/collection.js +27 -23
  50. package/dist/components/layout/assets/index.js +1 -1
  51. package/dist/components/layout/grammar.json +85 -0
  52. package/dist/components/selection_trial/__init__.py +1 -1
  53. package/dist/components/selection_trial/assets/collection.js +3 -3
  54. package/dist/components/selection_trial/assets/index.js +1 -1
  55. package/dist/components/tree/__init__.py +1 -1
  56. package/dist/components/tree/assets/collection.js +12 -12
  57. package/dist/components/tree/assets/index.js +1 -1
  58. package/dist/components/tree/grammar.json +126 -0
  59. package/dist/components/typst/__init__.py +1 -1
  60. package/dist/components/typst/assets/collection.js +3 -3
  61. package/dist/components/typst/assets/index.js +1 -1
  62. package/dist/components/uploads/__init__.py +1 -1
  63. package/dist/components/uploads/assets/collection.js +9 -9
  64. package/dist/components/uploads/assets/index.js +1 -1
  65. package/dist/components/vizabi/__init__.py +13 -0
  66. package/dist/components/vizabi/assets/collection.js +22 -0
  67. package/dist/components/vizabi/assets/index.js +3 -0
  68. package/dist/components/vizabi/commands.json +7 -0
  69. package/dist/components/vizabi/grammar.json +128 -0
  70. package/dist/gramlot.js +1190 -256
  71. package/dist/gramlot.min.js +85 -52
  72. package/dist/standard-collections.js +2 -0
  73. package/package.json +12 -4
  74. package/src/binding/grid-struct.js +2 -2
  75. package/src/binding/runtime.js +10 -0
  76. package/src/binding/validation-context.js +2 -1
  77. package/src/bootstrap.js +1 -1
  78. package/src/builder/gramlot-builder.d.ts +15 -2
  79. package/src/builder/gramlot-builder.js +22 -3
  80. package/src/builder/source.js +24 -1
  81. package/src/components/audio-analysis-session.js +65 -0
  82. package/src/components/audio.js +44 -0
  83. package/src/components/bases.js +11 -7
  84. package/src/components/border-container.js +6 -3
  85. package/src/components/buttons.js +47 -3
  86. package/src/components/chart-bar3d-options.js +30 -0
  87. package/src/components/chart-controls.js +83 -0
  88. package/src/components/chart-data-view.js +52 -0
  89. package/src/components/chart-data.js +42 -0
  90. package/src/components/chart-domains.js +46 -0
  91. package/src/components/chart-engines/echarts-options.js +50 -0
  92. package/src/components/chart-engines/echarts.js +82 -0
  93. package/src/components/chart-engines/index.js +22 -0
  94. package/src/components/chart-engines/plotly-map.js +34 -0
  95. package/src/components/chart-engines/plotly-spatial.js +35 -0
  96. package/src/components/chart-engines/plotly.js +138 -0
  97. package/src/components/chart-engines/uplot.js +57 -0
  98. package/src/components/chart-engines/vega.js +101 -0
  99. package/src/components/chart-fields.js +110 -0
  100. package/src/components/chart-geographic-options.js +47 -0
  101. package/src/components/chart-geojson.js +60 -0
  102. package/src/components/chart-geometry.js +11 -0
  103. package/src/components/chart-map-anchors.js +24 -0
  104. package/src/components/chart-map-bar3d-options.js +41 -0
  105. package/src/components/chart-map-data.js +25 -0
  106. package/src/components/chart-map-labels.js +8 -0
  107. package/src/components/chart-map-options.js +20 -0
  108. package/src/components/chart-pane.js +91 -0
  109. package/src/components/chart-renderer.js +58 -0
  110. package/src/components/chart-sample-view.js +32 -0
  111. package/src/components/chart-spatial-options.js +40 -0
  112. package/src/components/chart-time.js +84 -0
  113. package/src/components/chart-timeline.js +70 -0
  114. package/src/components/chart-types/area.js +2 -0
  115. package/src/components/chart-types/bar.js +2 -0
  116. package/src/components/chart-types/bar3D.js +2 -0
  117. package/src/components/chart-types/donut.js +2 -0
  118. package/src/components/chart-types/horizontalBar.js +2 -0
  119. package/src/components/chart-types/index.js +26 -0
  120. package/src/components/chart-types/line.js +2 -0
  121. package/src/components/chart-types/line3D.js +2 -0
  122. package/src/components/chart-types/lines3D.js +2 -0
  123. package/src/components/chart-types/map.js +2 -0
  124. package/src/components/chart-types/map3D.js +2 -0
  125. package/src/components/chart-types/mapBar3D.js +2 -0
  126. package/src/components/chart-types/pie.js +2 -0
  127. package/src/components/chart-types/polygons3D.js +2 -0
  128. package/src/components/chart-types/scatter.js +2 -0
  129. package/src/components/chart-types/scatter3D.js +2 -0
  130. package/src/components/chart-types/stackedArea.js +2 -0
  131. package/src/components/chart-types/stackedBar.js +2 -0
  132. package/src/components/chart-types/surface.js +2 -0
  133. package/src/components/charts.js +152 -0
  134. package/src/components/check-box-text-editor.js +88 -0
  135. package/src/components/check-box-text.js +193 -0
  136. package/src/components/check-box-tree.js +62 -0
  137. package/src/components/choice-editor.js +35 -18
  138. package/src/components/choice-field-styles.js +14 -0
  139. package/src/components/choices.js +5 -0
  140. package/src/components/database-choices.js +9 -6
  141. package/src/components/drawing.js +199 -0
  142. package/src/components/field-state.js +8 -1
  143. package/src/components/grid-cell-editor.js +83 -19
  144. package/src/components/grid-check-sets.js +98 -0
  145. package/src/components/grid-column-filters.js +198 -0
  146. package/src/components/grid-grammar.json +65 -0
  147. package/src/components/grid-header-interaction.js +3 -1
  148. package/src/components/grid-rows.js +2 -2
  149. package/src/components/grid-search-box.js +38 -22
  150. package/src/components/grid-search-styles.js +13 -14
  151. package/src/components/grid-search.js +8 -1
  152. package/src/components/grid-structure.js +13 -2
  153. package/src/components/grid-styles.js +34 -2
  154. package/src/components/grid.js +67 -10
  155. package/src/components/image-uploader.js +2 -2
  156. package/src/components/inputs.js +21 -12
  157. package/src/components/labelbox.js +5 -1
  158. package/src/components/licenses/claygl.txt +23 -0
  159. package/src/components/licenses/echarts-gl.txt +29 -0
  160. package/src/components/licenses/plotly.txt +21 -0
  161. package/src/components/licenses/uplot.txt +21 -0
  162. package/src/components/licenses/vega.txt +27 -0
  163. package/src/components/menus.js +19 -11
  164. package/src/components/parameters.js +6 -2
  165. package/src/components/toolbar-overflow.js +12 -8
  166. package/src/components/tree.js +31 -8
  167. package/src/components/typed-editor.js +18 -7
  168. package/src/components/validation.js +1 -1
  169. package/src/components/vizabi-session.js +66 -0
  170. package/src/components/vizabi.js +66 -0
  171. package/src/components/window-surface.js +20 -9
  172. package/src/components/windows.js +1 -1
  173. package/src/editing-session.d.ts +1 -0
  174. package/src/editing-session.js +113 -15
  175. package/src/editor-values.js +57 -0
  176. package/src/gramlot.d.ts +2 -0
  177. package/src/gramlot.js +9 -4
  178. package/src/handlers/device-handler.js +32 -32
  179. package/src/handlers/source-handler.d.ts +2 -2
  180. package/src/ide-documents.js +19 -3
  181. package/src/ide-runtime.d.ts +1 -0
  182. package/src/ide-runtime.js +45 -31
  183. package/src/index.d.ts +2 -1
  184. package/src/renderer/drag-drop.js +1 -0
  185. package/src/renderer/gramlot-renderer.d.ts +3 -0
  186. package/src/renderer/gramlot-renderer.js +16 -4
  187. package/src/server/assets.d.ts +3 -0
  188. package/src/server/assets.js +9 -0
  189. package/src/server/gramlot-server.d.ts +1 -1
  190. package/src/server/gramlot-server.js +2 -1
  191. package/src/server/index.d.ts +1 -1
  192. package/src/server/index.js +1 -1
  193. package/src/server/source-import.d.ts +1 -1
  194. package/src/server/source-import.js +5 -1
  195. package/src/server/visual-editor.d.ts +1 -1
  196. package/src/server/visual-editor.js +44 -34
  197. package/src/source-picker.d.ts +1 -1
  198. package/src/source-picker.js +1 -2
  199. package/src/stores/bag-collection-view.js +79 -17
  200. package/src/stores/collection-filter.js +2 -1
  201. package/src/stores/column-filter.js +49 -0
  202. package/src/stores/id-set.js +10 -0
  203. package/src/view/controls.js +8 -0
  204. package/src/view/html.js +10 -1
  205. package/src/view/label-menu.js +61 -0
  206. package/src/view/labelbox.js +15 -2
  207. package/src/visual-editor-canvas.js +29 -0
  208. package/src/visual-editor-catalogue.js +34 -0
  209. package/src/visual-editor.d.ts +5 -0
  210. package/src/visual-editor.js +244 -26
  211. package/themes/gramlot-base/theme.css +84 -36
  212. package/tools/gramlot-tools-inspector.js +170 -506
  213. package/tools/inspector-agent.js +1 -1
package/src/index.d.ts CHANGED
@@ -16,6 +16,7 @@ export {PageBootstrap} from './bootstrap.js';
16
16
  export type {PageBootstrapOptions, PageResources} from './bootstrap.js';
17
17
  export {Exposed, Page, codeMirrorWithOptions} from './server/page.js';
18
18
  export {GramlotBuilder} from './builder/gramlot-builder.js';
19
+ export type {GramlotSourceNode, GramlotSourceBag} from './builder/gramlot-builder.js';
19
20
  export {GramlotRenderer} from './renderer/gramlot-renderer.js';
20
21
  export {GramlotHtmlRenderer} from './renderer/gramlot-html-renderer.js';
21
22
  export {GramlotSvgRenderer} from './renderer/gramlot-svg-renderer.js';
@@ -52,7 +53,7 @@ export {collectionBuildId, verifyCollectionArtifact} from './collection-artifact
52
53
 
53
54
  export {DeviceHandler} from './handlers/device-handler.js';
54
55
  export {BrowserCameraProvider} from './browser-camera-provider.js';
55
- export type {DeviceProvider, DeviceClipboard, DeviceName, DeviceAudio, DeviceAudioSession, DeviceNetwork, DeviceLifecycleEvent, DeviceHapticStyle, AppInfo, DeviceLocation, DevicePhoto, DeviceBarcode, DeviceBiometrics, DeviceNotificationRequest, DeviceNotificationSchedule, DeviceNotificationEvent, DevicePushRegistration, DevicePushEvent, DeviceShortcutRequest, DeviceLinkRequest} from './handlers/device-handler.js';
56
+ export type {DeviceDatabase, DeviceOrientation, DeviceMotionEvent, DeviceProvider, DeviceClipboard, DeviceName, DeviceAudio, DeviceAudioSession, DeviceNetwork, DeviceLifecycleEvent, DeviceHapticStyle, AppInfo, DeviceLocation, DevicePhoto, DeviceBarcode, DeviceBiometrics, DeviceNotificationRequest, DeviceNotificationSchedule, DeviceNotificationEvent, DevicePushRegistration, DevicePushEvent, DeviceShortcutRequest, DeviceLinkRequest} from './handlers/device-handler.js';
56
57
 
57
58
  export {MobileEnvironment} from './mobile-environment.js';
58
59
 
@@ -107,6 +107,7 @@ export class DragDrop {
107
107
  type.startsWith('text/') ? session.wires.get(type) : fromTytx(session.wires.get(type))]));
108
108
  const context = {dropValues, item: row.item, path: row.path, source: {...session.source},
109
109
  selfdrop: record === session.record, dropEffect: policy.dropEffect, dataAvailable: true};
110
+ if (row.placement !== undefined) context.placement = row.placement;
110
111
  const accepted = policy.accepted && this.#renderer.checkDropTarget(record.node, context)
111
112
  && this.#renderer.records.get(record.node) === record && row.element.isConnected;
112
113
  return {record, element: row.element, accepted, context};
@@ -41,12 +41,14 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
41
41
  dropValues: Record<string, unknown>; item: unknown; path: string | undefined;
42
42
  source: Record<string, unknown>; selfdrop: boolean;
43
43
  dropEffect: 'copy' | 'move' | 'link'; dataAvailable: boolean;
44
+ placement?: 'before' | 'inside' | 'after';
44
45
  }): boolean;
45
46
  /** Invoke the general onDrop action on already accepted data not consumed by typed actions. */
46
47
  invokeDrop(node: SourceBagNode, context: {
47
48
  dropValues: Record<string, unknown>; item: unknown; path: string | undefined;
48
49
  source: Record<string, unknown>; selfdrop: boolean;
49
50
  dropEffect: 'copy' | 'move' | 'link'; dataAvailable: boolean;
51
+ placement?: 'before' | 'inside' | 'after';
50
52
  }): Promise<void>;
51
53
  /** Origin callback, followed by local endDrag publication even if the callback fails. */
52
54
  endDrag(node: SourceBagNode, context: {source: Record<string, unknown>; dropEffect: string}, topic: string): Promise<void>;
@@ -88,6 +90,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
88
90
  end?: DomNode;
89
91
  };
90
92
  /** Set the container of a render record and of its children. */
93
+ mountDestination(node:SourceBagNode, destination:DomElement):unknown;
91
94
  assignContainer(record: unknown, container: DomNode): void;
92
95
  /** Apply a Source update event to the DOM of a node. */
93
96
  update(node: SourceBagNode, event: string): void;
@@ -78,21 +78,21 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
78
78
  /** Prepare a local payload snapshot: no DataTransfer writes or native gesture commit. */
79
79
  prepareDrag(node, event) { return this.dragPreparation.prepare(node, event); }
80
80
  /** Dynamic eligibility only; cannot replace the independent type/tag/effect policy. */
81
- checkDropTarget(node, {dropValues, item, path, source, selfdrop, dropEffect, dataAvailable}) {
81
+ checkDropTarget(node, {dropValues, item, path, source, selfdrop, dropEffect, dataAvailable, placement}) {
82
82
  const record = this.records.get(node);
83
83
  if (!record) return false;
84
84
  if (!record.resolved.dropTargetCb) return true;
85
85
  const allowed = this.html.callLogic(node, record.resolved.dropTargetCb,
86
- {dropValues, item, path, source, selfdrop, dropEffect, dataAvailable});
86
+ {dropValues, item, path, source, selfdrop, dropEffect, dataAvailable, ...(placement === undefined ? {} : {placement})});
87
87
  if (typeof allowed !== 'boolean') throw new TypeError('dropTargetCb must return a boolean synchronously');
88
88
  return allowed;
89
89
  }
90
90
  /** Invoke only the general action, after acceptance and removal of data handled by typed actions. */
91
- async invokeDrop(node, {dropValues, item, path, source, selfdrop, dropEffect, dataAvailable}) {
91
+ async invokeDrop(node, {dropValues, item, path, source, selfdrop, dropEffect, dataAvailable, placement}) {
92
92
  const record = this.records.get(node);
93
93
  if (!record || !record.resolved.onDrop || Object.keys(dropValues).length === 0) return;
94
94
  await this.html.callLogic(node, record.resolved.onDrop,
95
- {dropValues, item, path, source, selfdrop, dropEffect, dataAvailable});
95
+ {dropValues, item, path, source, selfdrop, dropEffect, dataAvailable, ...(placement === undefined ? {} : {placement})});
96
96
  }
97
97
  /** Notify origin completion independently of application-operation success. */
98
98
  async endDrag(node, {source, dropEffect}, topic) {
@@ -206,6 +206,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
206
206
  ...this.html.create(node, document, tag, attrs, resolved.visible ?? null),
207
207
  };
208
208
  this.html.compose(record, text, children);
209
+ if (record.labelbox) record.cleanup.push(() => record.labelbox.menu?.dispose());
209
210
  record.shape = ControlAdapter.shape(record.element, resolved);
210
211
  // Registered before any listener: a failed first projection leaves a record the failed-build
211
212
  // cleanup removes, listeners included (ASTRA-06).
@@ -524,6 +525,17 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
524
525
  throw errors.length === 1 ? error : new AggregateError(errors, 'Source build and cleanup failed');
525
526
  }
526
527
 
528
+ /** Mount the same Source and bindings in a new document's element realm. */
529
+ mountDestination(node, destination) {
530
+ const record = this.records.get(node);
531
+ if (!record?.presentation || destination?.nodeType !== 1)
532
+ throw new TypeError('mountDestination requires a mounted element and an HTML destination');
533
+ if (record.presentation.contains(destination)) throw new Error('Destination cannot be inside the moved presentation');
534
+ const parent = record.parent;
535
+ this.remove(node);
536
+ return this.buildNode(node, destination, null, parent);
537
+ }
538
+
527
539
  assignContainer(record, container) {
528
540
  record.container = container;
529
541
  const childContainer = record.element ?? container;
@@ -10,3 +10,6 @@ export function gramlotDev(): 'YES' | 'DEBUG' | null;
10
10
  * URL from JSR (read with `fetch`). Without a name, the runtime to serve at the runtime URL: `gramlot.js`
11
11
  * when `GRAMLOT_DEV=DEBUG`, `gramlot.min.js` otherwise. Another name throws a `TypeError`. */
12
12
  export function runtimeAsset(name?: 'gramlot.js' | 'gramlot.min.js' | 'gramlot-markdown.js' | 'runtime-notices.json' | null): URL;
13
+
14
+ /** Packaged standard collection entry points for host artifact verification. */
15
+ export function standardCollectionAssets(): Array<{url: string; file: URL}>;
@@ -1,4 +1,5 @@
1
1
  /* @ts-self-types="./assets.d.ts" */
2
+ import {standardCollections} from '../../dist/standard-collections.js';
2
3
  /**
3
4
  * Development mode and the runtime file to serve. `gramlotDev` imports nothing from Node.js, so the
4
5
  * neutral `GramlotServer` can read it in a serverless Worker, where it is null without `process`.
@@ -28,3 +29,11 @@ export function runtimeAsset(name = null) {
28
29
  if (!RUNTIME_ASSETS.includes(name)) throw new TypeError(`Unknown Gramlot runtime asset: ${name}`);
29
30
  return new URL(`../../dist/${name}`, import.meta.url);
30
31
  }
32
+
33
+ /** Standard collection entry points; hosts verify their complete artifact inventories. */
34
+ export function standardCollectionAssets() {
35
+ return standardCollections.map(collection => ({
36
+ url: collection.module,
37
+ file: new URL(`../../dist/components/${collection.name}/assets/index.js`, import.meta.url),
38
+ }));
39
+ }
@@ -72,7 +72,7 @@ export interface GramlotServerOptions {
72
72
  pageTtl?: number;
73
73
  /** Maximum number of registered pages. */
74
74
  maxPages?: number;
75
- /** Application collections: generated Builder grammar and root-relative browser module URL. */
75
+ /** Custom collections added to the packaged standards: Builder grammar and root-relative module URL. */
76
76
  collections?: PreparedCollection[];
77
77
  /** Enable upload control only when the adapter provides a binary transport. */
78
78
  uploadsEnabled?: boolean;
@@ -1,4 +1,5 @@
1
1
  /* @ts-self-types="./gramlot-server.d.ts" */
2
+ import {standardCollections} from '../../dist/standard-collections.js';
2
3
  /**
3
4
  * The neutral server: registers pages and builds their Sources, with no HTTP engine.
4
5
  *
@@ -122,7 +123,7 @@ export class GramlotServer {
122
123
  Object.assign(this, {runtimeUrl, rpcUrl, closeUrl, rootId, pageTtl, maxPages, cssTheme});
123
124
  this.pages = new Map();
124
125
  this.uploads = uploadsEnabled ? new UploadRegistry() : null;
125
- this.collections = [...collections];
126
+ this.collections = this.collectionGraph([...standardCollections, ...collections]);
126
127
  this.preparedGrammars = new WeakMap();
127
128
  this.environmentPages = new WeakMap();
128
129
  }
@@ -11,7 +11,7 @@ export type {GramlotServerOptions, OpenedPage, RegisteredPage} from './gramlot-s
11
11
  export {GramlotBuilder} from '../builder/gramlot-builder.js';
12
12
  export {GramlotFileServer} from './gramlot-file-server.js';
13
13
  export type {GramlotFileServerOptions} from './gramlot-file-server.js';
14
- export {gramlotDev, runtimeAsset} from './assets.js';
14
+ export {gramlotDev, runtimeAsset, standardCollectionAssets} from './assets.js';
15
15
  export {checkProtocol} from './conformance.js';
16
16
  export {InvalidResourceName, parseRequires} from './resources.js';
17
17
  export type {Resources} from './resources.js';
@@ -11,7 +11,7 @@ export {GramlotServer, EndpointNotFound, InvalidRequest, NotAuthenticated, NotAu
11
11
  SourceNotFound, ServerCapacity} from './gramlot-server.js';
12
12
  export {GramlotBuilder} from '../builder/gramlot-builder.js';
13
13
  export {GramlotFileServer} from './gramlot-file-server.js';
14
- export {gramlotDev, runtimeAsset} from './assets.js';
14
+ export {gramlotDev, runtimeAsset, standardCollectionAssets} from './assets.js';
15
15
  export {checkProtocol} from './conformance.js';
16
16
  export {InvalidResourceName, parseRequires} from './resources.js';
17
17
  export {NAME_SYNTAX, NameSyntax} from '../builder/name-syntax.js';
@@ -1,2 +1,2 @@
1
1
  import {UploadTarget} from './upload.js';
2
- export class SourceImport extends UploadTarget { constructor(); }
2
+ export class SourceImport extends UploadTarget { constructor(options?:{catalogue?:"html"|string[]}); }
@@ -1,9 +1,12 @@
1
+ import {validateCatalogue, validateCatalogueSource} from '../visual-editor-catalogue.js';
1
2
  import {fromTytx} from '@genrojs/tytx';
2
3
  import {SourceBag} from '@genrojs/builders';
3
4
  import {UploadTarget} from './upload.js';
4
5
  export class SourceImport extends UploadTarget {
5
- constructor() {
6
+ constructor({catalogue = null} = {}) {
6
7
  super({maxBytes:5 * 1024 * 1024});
8
+ validateCatalogue(catalogue);
9
+ this.catalogue = catalogue;
7
10
  this.decoder = new TextDecoder('utf-8', {fatal:true});
8
11
  this.parts = [];
9
12
  this.outcome = {state:'pending'};
@@ -17,6 +20,7 @@ export class SourceImport extends UploadTarget {
17
20
  if (!(source instanceof SourceBag) || source.length !== 1 || source.getNodes()[0].label !== 'pageRoot') {
18
21
  throw new TypeError('Expected one pageRoot Source');
19
22
  }
23
+ validateCatalogueSource(this.catalogue, source);
20
24
  this.outcome = {state:'completed', result:wire};
21
25
  return this.outcome;
22
26
  }
@@ -1,7 +1,7 @@
1
1
  import type {SourceBagNode} from '@genrojs/builders';
2
2
  export interface PageCodeDocument {language:'python'|'javascript'; key:string; path:string; content:string; revision:string; writable:boolean;}
3
3
  export class VisualEditor {
4
- constructor(parent:SourceBagNode, options?:{datapath?:string; dataRoot?:string; editorId?:string; uploadOperation?:string; codeDocument?:PageCodeDocument; [attribute:string]:unknown});
4
+ constructor(parent:SourceBagNode, options?:{datapath?:string; dataRoot?:string; editorId?:string; uploadOperation?:string; codeDocument?:PageCodeDocument; catalogue?:"html"|string[]; fileCommands?:boolean; canvasCss?:string[]; [attribute:string]:unknown});
5
5
  pane:SourceBagNode;
6
6
  frame:SourceBagNode;
7
7
  toolbar:SourceBagNode;
@@ -1,45 +1,55 @@
1
+ import {validateCatalogue} from '../visual-editor-catalogue.js';
1
2
  import {Bag} from '@genrojs/bag';
2
3
  import {sourceTarget} from '@genrojs/builders';
3
4
  import {toolIcons} from '../visual-editor-icons.js';
4
5
 
5
6
  export class VisualEditor {
6
- constructor(root, {datapath = '__editor', dataRoot = '', editorId = 'visual', uploadOperation = 'import_source', codeDocument = null, ...attributes} = {}) {
7
+ constructor(root, {datapath = '__editor', dataRoot = '', editorId = 'visual', uploadOperation = 'import_source', codeDocument = null, catalogue = null, fileCommands = true, canvasCss = null, ...attributes} = {}) {
7
8
  if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(editorId)) throw new Error('editorId must be a literal identifier');
8
9
  if (!dataRoot && datapath !== '__editor' && !datapath.startsWith('__editor.')) throw new Error('Root Data editing requires an __editor datapath');
10
+ validateCatalogue(catalogue);
11
+ if (canvasCss != null && (!Array.isArray(canvasCss) || canvasCss.some(text => typeof text !== 'string')))
12
+ throw new TypeError('canvasCss must be a list of CSS texts');
9
13
  this.dataRoot = dataRoot;
10
14
  const pane = this.pane = root.main({node_label:editorId, datapath, visualEditorId:editorId, ...attributes, nodeId:`${editorId}Editor`, class:`visual-editor-shell ${attributes.class ?? ''}`, overflow:'hidden', tabindex:0, connect_onkeydown:'clipboardShortcut'});
15
+ pane.dataSetter({destination_path:'.catalogueScope', value:catalogue});
16
+ pane.dataSetter({destination_path:'.canvasCss', value:canvasCss});
11
17
  pane.dataSetter({destination_path:'.uploadQueue', value:new Bag()});
12
18
  pane.dataController({func:'initializeEditor', dataRoot:this.dataRoot, _init:true});
13
19
  pane.dataController({func:'showProperties', path:'^.selection', _init:true});
14
20
  pane.dataController({func:'initializeCanvasSelection', _onBuilt:true});
21
+ pane.dataController({func:'initializeDocument', _onBuilt:true});
15
22
  pane.dataController({func:'highlightSelection', path:'^.selection', _init:true});
16
23
  pane.style('^.appearanceCss');
17
24
  pane.dataController({func:'initializeEditorAppearance', _onBuilt:true});
18
25
  pane.dataController({func:'applyEditorAppearance', profile:'^.appearanceProfile', palette:'^.appearancePalette', mode:'^.appearanceMode'});
19
26
  const rail = this.rail = pane.menu({presentation:'bar', orientation:'vertical', aria_label:'Editor panels', class:'visual-editor-rail'});
20
- this.toolButton(rail.menuline({group:true, overflowable:false}), 'Source / Data', 'toggleNavigation', toolIcons.navigation);
21
- this.toolButton(rail.menuline({group:true, overflowable:false}), 'Catalogue', 'openCatalogue', toolIcons.catalogue);
22
- this.toolButton(rail.menuline({group:true, overflowable:false}), 'Properties', 'openProperties', toolIcons.properties);
23
- this.toolButton(rail.menuline({group:true, overflowable:false}), 'Clipboard', "this.SET('.clipboardVisible', !this.GET('.clipboardVisible'))", toolIcons.paste);
27
+ this.toolButton(rail.menuline({group:true}), 'Source / Data', 'toggleNavigation', toolIcons.navigation);
28
+ this.toolButton(rail.menuline({group:true}), 'Catalogue', 'openCatalogue', toolIcons.catalogue);
29
+ this.toolButton(rail.menuline({group:true}), 'Properties', 'openProperties', toolIcons.properties);
30
+ this.toolButton(rail.menuline({group:true}), 'Clipboard', "this.SET('.clipboardVisible', !this.GET('.clipboardVisible'))", toolIcons.paste,
31
+ {dropTarget:true, dropTypes:'app/source', dropTags:`${editorId}Source`, dropEffect:'^.clipboardDropEffect',
32
+ connect_ondragover:'clipboardModifiers', connect_ondrop:'clipboardModifiers', onDrop:'dropClipboard'});
24
33
  rail.spacer({flex:1});
25
- this.toolButton(rail.menuline({group:true, overflowable:false}), 'Appearance', "this.SET('.appearanceOpen', !this.GET('.appearanceOpen'))", toolIcons.appearance);
34
+ this.toolButton(rail.menuline({group:true}), 'Appearance', "this.SET('.appearanceOpen', !this.GET('.appearanceOpen'))", toolIcons.appearance);
26
35
  const layoutRoot = pane.framePane({node_label:'layout', height:'100%', id:`${editorId}-editor-frame`, class:'visual-editor-layout'});
27
- layoutRoot.top.setAttr({height:'38px'});
36
+ layoutRoot.top.setAttr({height:'30px'});
28
37
  const toolbar = layoutRoot.top.menu({presentation:'bar', aria_label:'Editor tools', class:'visual-editor-toolbar'});
29
- toolbar.menuline({group:true, overflowable:false}).span('Source editor', {class:'visual-editor-brand'});
30
- const files = toolbar.menuline({group:true, overflowable:false, gap:'4px'});
38
+ toolbar.menuline({group:true}).span('Source editor', {class:'visual-editor-brand'});
39
+ const files = toolbar.menuline({group:true, gap:'4px', hidden:!fileCommands});
31
40
  for (const [caption,action,icon] of [['New','newPage','new'],['Open','openUpload','open'],['Download','downloadPage','download'],['Copy Source','copySource','copy']])
32
41
  this.toolButton(files,caption,action,toolIcons[icon],{id:`${editorId}-${icon}`});
33
- toolbar.menuline({group:true, overflowable:false}).span({class:'visual-toolbar-divider', aria_hidden:'true'});
34
- const edit = toolbar.menuline({group:true, overflowable:false, gap:'2px'});
42
+ toolbar.menuline({group:true}).span({class:'visual-toolbar-divider', aria_hidden:'true'});
43
+ const edit = toolbar.menuline({group:true, gap:'2px'});
35
44
  this.toolButton(edit,'Cut branch','cutBranch',toolIcons.cut,{title:'Cut branch (F8)'});
36
45
  this.toolButton(edit,'Copy branch','copyBranch',toolIcons.copy);
37
46
  this.toolButton(edit,'Paste branch','pasteBranch',toolIcons.paste,{title:'Paste branch (F9)'});
38
47
  toolbar.spacer({flex:1});
39
- toolbar.menuline({group:true, overflowable:false}).span('^.fileStatus', {role:'status', class:'visual-editor-file-status'});
40
- toolbar.menuline({group:true, overflowable:false}).span('^.filename', {class:'visual-editor-filename'});
48
+ toolbar.menuline({group:true, hidden:'^.modified:=!{}'}).span('Unsaved changes', {role:'status', class:'visual-editor-hint'});
49
+ toolbar.menuline({group:true}).span('^.fileStatus', {role:'status', class:'visual-editor-file-status'});
50
+ toolbar.menuline({group:true}).span('^.filename', {class:'visual-editor-filename'});
41
51
  const left = layoutRoot.left;
42
- left.setAttr({width:'min(260px, 34vw)', splitter:true,
52
+ left.setAttr({width:'min(240px, 34vw)', splitter:true,
43
53
  drawer:'^.navigationOpen', default_drawer:true, drawer_label:'Source / Data',
44
54
  drawer_onclick:"this.SET('.navigationOpen', show ? true : 'close')",
45
55
  display:'flex', flex_direction:'column', min_height:0, class:'visual-editor-sidebar'});
@@ -69,36 +79,36 @@ export class VisualEditor {
69
79
  center.setAttr({overflow:'auto', class:'visual-editor-workspace'});
70
80
  const design = center.div({node_label:'design', class:'visual-editor-canvas'});
71
81
  design.div({node_label:'pageRoot', ...(this.dataRoot ? {datapath:this.dataRoot} : {})});
72
- const window = pane.floatingPane({title:'Widget catalogue', open:'^.catalogueOpen', default_open:false, width:'320px', height:'480px', movable:true, resizable:true});
82
+ const window = pane.floatingPane({title:'Widget catalogue', open:'^.catalogueOpen', default_open:false, width:'280px', height:'400px', class:'visual-editor-popup', movable:true, resizable:true});
73
83
  this.search(window.frame.top, 'catalogueSearch', 'Search widgets');
74
84
  window.frame.center.tree({storepath:'.catalogue', hideValues:true, labelAttribute:'caption', searchText:'^.catalogueSearch',
75
85
  draggable:true, dragTags:'widget', effectAllowed:'all', onDrag:'prepareWidget', id:`${editorId}-widget-tree`});
76
- const properties = sidebar.contentPane({region:'bottom', height:'^.propertiesHeight', default_height:'240px', minSize:140, splitter:true,
86
+ const properties = sidebar.contentPane({region:'bottom', height:'^.propertiesHeight', default_height:'200px', minSize:140, splitter:true,
77
87
  title:'^.propertiesTitle', detachable:true, hidden:'^.propertiesOpen:=!{}',
78
88
  display:'flex', flex_direction:'column', overflow:'hidden', min_height:0});
79
89
  properties.div({nodeId:`${editorId}EditorFields`, class:'visual-editor-fields', display:'flex', flex_direction:'column', flex:1, min_height:0}).span('');
80
- properties.p('^.propertyError', {role:'alert', class:'visual-editor-hint', margin:'8px'});
81
- const uploader = pane.dialog({title:'Open Source', open:'^.uploadOpen', width:'480px', height:'300px', movable:true, resizable:true});
90
+ properties.p('^.propertyError', {role:'alert', class:'visual-editor-hint', margin:'3px'});
91
+ const uploader = pane.dialog({class:'visual-editor-popup', title:'Open Source', open:'^.uploadOpen', width:'480px', height:'300px', movable:true, resizable:true});
82
92
  uploader.frame.center.uploader({operation:uploadOperation, storepath:'.uploadQueue', accept:'.grmlt',
83
93
  multiple:false, autoUpload:true, onComplete:'sourceUploaded', id:`${editorId}-uploader`});
84
- const naming = pane.dialog({title:'Save branch to clipboard', open:'^.clipboardOpen', width:'380px', height:'210px'});
94
+ const naming = pane.dialog({class:'visual-editor-popup', title:'Save branch to clipboard', open:'^.clipboardOpen', width:'380px', height:'210px'});
85
95
  naming.frame.center.textbox({value:'^.clipboardDraft.name', lbl:'Name', margin:'12px'});
86
96
  naming.frame.center.p('^.error', {role:'alert', margin:'12px'});
87
- const namingBar = naming.frame.bottom.menu({presentation:'bar', aria_label:'Clipboard commands', padding:'8px 12px'});
97
+ const namingBar = naming.frame.bottom.menu({presentation:'bar', aria_label:'Clipboard commands', padding:'3px 6px'});
88
98
  namingBar.spacer({flex:1});
89
- const namingButtons = namingBar.menuline({group:true, overflowable:false, gap:'8px'});
99
+ const namingButtons = namingBar.menuline({group:true, gap:'8px'});
90
100
  namingButtons.button('Cancel', {action:"this.SET('.clipboardOpen', false)"});
91
101
  namingButtons.button('Save branch', {action:'saveClipboard'});
92
- const dialog = pane.dialog({title:'Required parameters', open:'^.insertionOpen', width:'400px', height:'280px', movable:true, resizable:true});
93
- dialog.frame.center.div({nodeId:`${editorId}InsertFields`, class:'visual-editor-fields', padding:'12px'}).span('');
102
+ const dialog = pane.dialog({class:'visual-editor-popup', title:'Required parameters', open:'^.insertionOpen', width:'400px', height:'280px', movable:true, resizable:true});
103
+ dialog.frame.center.div({nodeId:`${editorId}InsertFields`, class:'visual-editor-fields', padding:'6px'}).span('');
94
104
  dialog.frame.center.p('^.error', {role:'alert'});
95
- const bar = dialog.frame.bottom.menu({presentation:'bar', aria_label:'Insertion commands', padding:'8px 12px', border_top:'1px solid var(--gramlot-border)'});
105
+ const bar = dialog.frame.bottom.menu({presentation:'bar', aria_label:'Insertion commands', padding:'3px 6px', border_top:'1px solid var(--gramlot-border)'});
96
106
  bar.spacer({flex:1});
97
- const buttons = bar.menuline({group:true, overflowable:false, gap:'8px'});
107
+ const buttons = bar.menuline({group:true, gap:'8px'});
98
108
  buttons.button('Cancel', {action:"this.SET('.insertionOpen', false)"});
99
109
  buttons.button('Insert', {action:'insertWidget'});
100
- const settings = pane.floatingPane({title:'Appearance', open:'^.appearanceOpen', default_open:false, width:'280px', height:'260px', movable:true, resizable:true});
101
- const form = settings.frame.center.formlet({columns:1, lbl_position:'TL', gap:'10px', padding:'12px'});
110
+ const settings = pane.floatingPane({class:'visual-editor-popup', title:'Appearance', open:'^.appearanceOpen', default_open:false, width:'280px', height:'260px', movable:true, resizable:true});
111
+ const form = settings.frame.center.formlet({columns:1, lbl_position:'TL', gap:'4px', padding:'6px'});
102
112
  form.filteringSelect({validate_notnull:true, lbl:'Theme', value:'^.appearanceProfile', values:'base:Base,compact:Compact,mimi:Mimi,joanna:Joanna,mela:Mela'});
103
113
  form.filteringSelect({validate_notnull:true, lbl:'Colors', value:'^.appearancePalette', values:'default:Theme default,compact:Blue & slate,mimi:Sage & green,joanna:Warm gray & blue'});
104
114
  form.filteringSelect({validate_notnull:true, lbl:'Mode', value:'^.appearanceMode', values:'light:Light,dark:Dark'});
@@ -118,20 +128,20 @@ export class VisualEditor {
118
128
  pane.dataSetter({destination_path:'.codeDocument', value:new Bag({...document, saved:document.content, busy:false, status:''})});
119
129
  const anchor = `#${pane.getAttr('visualEditorId')}Editor`;
120
130
  const opener = frame === this.frame ? this.toolbar : frame.top.menu({presentation:'bar', aria_label:'Code drawer'});
121
- opener.menuline({group:true, overflowable:false}).button('Code', {action:'openCode', class:'button--quiet'});
131
+ opener.menuline({group:true}).button('Code', {action:'openCode', class:'button--quiet'});
122
132
  const drawer = frame.right;
123
- drawer.setAttr({datapath:anchor, title:'Page code', detachable:true, width:'60%', minSize:240, splitter:true,
133
+ drawer.setAttr({class:'visual-editor-code', datapath:anchor, title:'Page code', detachable:true, width:'60%', minSize:240, splitter:true,
124
134
  drawer:'^.codeOpen', default_drawer:'close', drawer_label:'Code', drawer_minimize:false,
125
135
  drawer_onclick:"this.SET('.codeOpen', show ? true : 'close')", min_height:0, overflow:'hidden'});
126
136
  const code = drawer.framePane({height:'100%', width:'100%', min_width:0, flex:1});
127
- code.top.setAttr({height:'32px'}); code.bottom.setAttr({height:'58px'});
137
+ code.top.setAttr({height:'26px'}); code.bottom.setAttr({height:'48px'});
128
138
  code.center.setAttr({display:'flex', flex_direction:'column', min_height:0, overflow:'hidden'});
129
- code.top.div(document.path, {padding:'8px 12px', font_size:'12px', overflow:'hidden', text_overflow:'ellipsis', white_space:'nowrap'});
139
+ code.top.div(document.path, {padding:'3px 6px', font_size:'12px', overflow:'hidden', text_overflow:'ellipsis', white_space:'nowrap'});
130
140
  code.center.codeMirror({value:'^.codeDocument.content', language:document.language, live:true, readonly:'^.codeDocument.writable:=!{}', height:'100%', box_height:'100%', box_c_height:'100%', box_min_height:0, box_c_min_height:0, fontSize:13, flex:1, min_height:0});
131
141
  code.bottom.div('^.codeDocument.status', {role:'status', font_size:'12px', padding:'4px 10px'});
132
- const bar = code.bottom.menu({presentation:'bar', aria_label:'Page code commands', padding:'6px 10px'});
142
+ const bar = code.bottom.menu({presentation:'bar', aria_label:'Page code commands', padding:'3px 6px'});
133
143
  bar.spacer({flex:1});
134
- const commands = bar.menuline({group:true, overflowable:false, gap:'6px'});
144
+ const commands = bar.menuline({group:true, gap:'6px'});
135
145
  commands.button('Close', {action:"this.SET('.codeOpen', 'close')"});
136
146
  commands.button('Preview saved', {action:'codePreview', disabled:'^.codeDocument.busy'});
137
147
  commands.button('Save', {action:'codeSave', disabled:'^.codeSaveDisabled'});
@@ -140,7 +150,7 @@ export class VisualEditor {
140
150
  }
141
151
  search(pane, path, label) {
142
152
  const bar = pane.menu({presentation:'bar', aria_label:label, class:'visual-search-toolbar'});
143
- const field = bar.menuline({group:true, overflowable:false, flex:1, min_width:0}).div({class:'visual-search-field'});
153
+ const field = bar.menuline({group:true, flex:1, min_width:0}).div({class:'visual-search-field'});
144
154
  field.span({class:'visual-search-icon', aria_hidden:'true'});
145
155
  field.input({type:'search', value:`^.${path}`, default:'', live:true, placeholder:label, aria_label:label});
146
156
  field.html_button({type:'button', class:'visual-search-clear', aria_label:`Clear ${label.toLowerCase()}`,
@@ -3,7 +3,7 @@ import type {GramlotRenderer} from './renderer/gramlot-renderer.js';
3
3
 
4
4
  /** Reusable, lifecycle-bound selection of rendered Source nodes in an editor preview. */
5
5
  export class SourcePicker {
6
- constructor(options: {renderer: GramlotRenderer; root: SourceBagNode; onSelect: (node: SourceBagNode) => void});
6
+ constructor(options: {renderer: GramlotRenderer; root: SourceBagNode; canvas?:Element; onSelect: (node: SourceBagNode) => void});
7
7
  select(node: SourceBagNode | null): void;
8
8
  dispose(): void;
9
9
  }
@@ -2,9 +2,8 @@
2
2
  export class SourcePicker {
3
3
  #renderer; #root; #canvas; #onSelect; #observer; #selectedPath = null;
4
4
  #highlighted = null; #release = null; #disposed = false;
5
- constructor({renderer, root, onSelect}) {
5
+ constructor({renderer, root, onSelect, canvas = renderer.records.get(root.parentNode)?.presentation}) {
6
6
  if (!root?.parentNode || typeof onSelect !== 'function') throw new TypeError('SourcePicker requires a mounted Source root and onSelect');
7
- const canvas = renderer.records.get(root.parentNode)?.presentation;
8
7
  if (!canvas || canvas.nodeType !== 1) throw new TypeError('SourcePicker requires a mounted preview');
9
8
  this.#renderer = renderer; this.#root = root; this.#canvas = canvas; this.#onSelect = onSelect;
10
9
  canvas.addEventListener('pointerdown', this, true);
@@ -1,5 +1,7 @@
1
+ import {columnValue, columnValueKey, columnSelection, columnDateRange, columnDateMatches} from './column-filter.js';
1
2
  import {isDecimal} from '@genrojs/tytx';
2
3
  import {compileFilter} from './collection-filter.js';
4
+ import {containsId, requireId, requireIdSet} from './id-set.js';
3
5
  import {publishCollection} from './bag-collection-store.js';
4
6
 
5
7
  /** Source-owned view: original BagNodes, independent indices and criteria. */
@@ -9,15 +11,25 @@ export class BagCollectionView {
9
11
  #listeners = new Set();
10
12
  #indices = new Map();
11
13
  #sortedBy = '';
12
- #filter = null;
13
- #predicate = null;
14
+ #filters = new Map();
14
15
  #filtered = null;
15
16
  constructor(store) { this.bindStore(store); }
16
17
  get bag() { return this.#store.bag; }
17
18
  get rowMode() { return this.#store.rowMode; }
18
19
  get sortedBy() { return this.#sortedBy; }
19
20
  get criteria() { return parseSort(this.#sortedBy); }
20
- get filter() { return this.#filter; }
21
+ get filter() { return this.#filters.get('search')?.definition ?? null; }
22
+ get filterSignature() { return JSON.stringify([...this.#filters].map(([name,{definition}]) => [name,definition])); }
23
+ /** Immutable accepted entries cross runtime/collection bundle boundaries. */
24
+ get filterContributions() {
25
+ return Object.freeze([...this.#filters].map(([name, entry]) =>
26
+ Object.freeze([name, Object.freeze({...entry})])));
27
+ }
28
+ /** Copy immutable accepted criteria into another Source-owned view, never rows. */
29
+ copyFiltersFrom(view) {
30
+ if (this.filterSignature === view.filterSignature) return;
31
+ this.#commit(this.#orderedNodes(),this.#sortedBy,new Map(view.filterContributions));
32
+ }
21
33
  get filtered() { return this.#filtered === null ? null : [...this.#filtered]; }
22
34
  isFiltered() { return this.#filtered !== null; }
23
35
  value(node, field) { return this.#store.value(node, field); }
@@ -49,40 +61,90 @@ export class BagCollectionView {
49
61
  return this.#store.getRows().toSorted((a,b) => (this.#indices.get(a) ?? Infinity) - (this.#indices.get(b) ?? Infinity));
50
62
  }
51
63
  synchronize(change = {full:true, rows:[]}) {
52
- if (!change.full && !this.#sortedBy && !this.#predicate) {
64
+ if (!change.full && !this.#sortedBy && !this.#filters.size) {
53
65
  publishCollection(this.#listeners,change);
54
66
  return;
55
67
  }
56
- this.#commit(this.#sorted(this.#orderedNodes(),this.criteria),this.#sortedBy,this.#filter,this.#predicate,change);
68
+ this.#commit(this.#sorted(this.#orderedNodes(),this.criteria),this.#sortedBy,this.#filters,change);
57
69
  }
58
70
  sort(sortedBy) {
59
71
  const nodes = this.#sorted(this.#orderedNodes(),parseSort(sortedBy));
60
- this.#commit(nodes,sortedBy,this.#filter,this.#predicate);
72
+ this.#commit(nodes,sortedBy,this.#filters);
61
73
  }
62
74
  moveRow(node, target, after = false) {
63
75
  if (node === target || node.parentBag !== this.bag || target.parentBag !== this.bag) return;
64
76
  const nodes = this.getRows(false);
65
77
  nodes.splice(nodes.indexOf(node),1);
66
78
  nodes.splice(nodes.indexOf(target)+Number(after),0,node);
67
- this.#commit(nodes,'',this.#filter,this.#predicate);
79
+ this.#commit(nodes,'',this.#filters);
68
80
  }
69
- applyFilter(filter) {
70
- // The accepted definition is immutable Source-owned state. Invalid drafts
71
- // cannot replace it, the predicate or the visible index.
81
+ applyFilter(filter, contribution = 'search') {
82
+ if (!['base','search'].includes(contribution)) throw new TypeError('Unknown collection filter contribution');
72
83
  const definition = filter === null ? null : Object.freeze({...filter,columns:Object.freeze([...filter.columns])});
73
- const predicate = compileFilter(definition);
74
- this.#commit(this.#orderedNodes(),this.#sortedBy,definition,predicate);
84
+ this.#applyContribution(contribution, definition, compileFilter(definition));
85
+ }
86
+ applySetFilter(sets) {
87
+ const definition = sets === null ? null : Object.freeze(sets.map(({field,value}) => {
88
+ if (typeof field !== 'string' || !field) throw new TypeError('Set filter requires an identity field');
89
+ requireIdSet(value);
90
+ return Object.freeze({field,value});
91
+ }));
92
+ const predicate = definition === null ? null : read => definition.every(({field,value}) =>
93
+ containsId(value,requireId(read(field))));
94
+ this.#applyContribution('sets',definition,predicate);
95
+ }
96
+ columnFilter(field) { return this.#filters.get(`column:${field}`)?.definition.values ?? null; }
97
+ columnRange(field) {
98
+ const range = this.#filters.get(`column:${field}`)?.definition.range;
99
+ return range ? {...range,from:range.from && new Date(range.from+'T00:00:00Z'),to:range.to && new Date(range.to+'T00:00:00Z')} : null;
100
+ }
101
+ applyColumnFilter(field, values, range = this.columnRange(field)) {
102
+ range = columnDateRange(range);
103
+ if (typeof field !== 'string' || !field) throw new TypeError('Column filter requires a field');
104
+ const selected = values === null ? null : columnSelection(values);
105
+ const keys = selected?.map(columnValueKey);
106
+ const definition = selected === null && range === null ? null : Object.freeze({field,values:selected,keys:keys && Object.freeze(keys),range});
107
+ const predicate = definition === null ? null : read => columnDateMatches(read(field),range) && (keys === undefined || keys.includes(columnValueKey(read(field))));
108
+ this.#applyContribution(`column:${field}`,definition,predicate);
109
+ }
110
+ columnFacets(field) {
111
+ const facets = new Map();
112
+ const range = this.#filters.get(`column:${field}`)?.definition.range ?? null;
113
+ const selected = this.columnFilter(field);
114
+ const keys = selected?.map(columnValueKey);
115
+ const predicates = [...this.#filters].filter(([name]) => name !== `column:${field}`)
116
+ .map(([,entry]) => entry.predicate).filter(predicate => predicate !== null);
117
+ for (const node of this.#orderedNodes()) {
118
+ const value = columnValue(this.value(node,field)), key = columnValueKey(value);
119
+ if (!facets.has(key)) facets.set(key,{key,value,count:0,selected:columnDateMatches(value,range) && (keys === undefined || keys.includes(key))});
120
+ if (predicates.every(predicate => predicate(field => this.value(node,field)))) facets.get(key).count++;
121
+ }
122
+ // Selections absent from the current Bag remain visible and removable.
123
+ for (const value of selected ?? []) {
124
+ const key = columnValueKey(value);
125
+ if (!facets.has(key)) facets.set(key,{key,value,count:0,selected:true});
126
+ }
127
+ return [...facets.values()].filter(entry => columnDateMatches(entry.value,range));
128
+ }
129
+ #applyContribution(name, definition, predicate) {
130
+ if (JSON.stringify(this.#filters.get(name)?.definition ?? null) === JSON.stringify(definition)) return;
131
+ const filters = new Map(this.#filters);
132
+ if (definition === null) filters.delete(name);
133
+ else filters.set(name,{definition,predicate});
134
+ this.#commit(this.#orderedNodes(),this.#sortedBy,filters);
75
135
  }
76
- #commit(nodes, sortedBy, filter, predicate, change = {full:false, rows:[]}) {
77
- const filtered = predicate ? nodes.flatMap((node,index) => predicate(field => this.value(node,field)) ? [index] : []) : null;
78
- const full = change.full || sortedBy !== this.#sortedBy || JSON.stringify(filter) !== JSON.stringify(this.#filter) ||
136
+ #commit(nodes, sortedBy, filters, change = {full:false, rows:[]}) {
137
+ const predicates = [...filters.values()].map(entry => entry.predicate).filter(predicate => predicate !== null);
138
+ const filtered = predicates.length ? nodes.flatMap((node,index) =>
139
+ predicates.every(predicate => predicate(field => this.value(node,field))) ? [index] : []) : null;
140
+ const full = change.full || sortedBy !== this.#sortedBy || filters !== this.#filters ||
79
141
  nodes.length !== this.#indices.size || nodes.some((node,index) => this.#indices.get(node) !== index) ||
80
142
  JSON.stringify(filtered) !== JSON.stringify(this.#filtered);
81
143
  this.#indices = new Map(nodes.map((node,index) => [node,index]));
82
- this.#sortedBy = sortedBy; this.#filter = filter; this.#predicate = predicate; this.#filtered = filtered;
144
+ this.#sortedBy = sortedBy; this.#filters = filters; this.#filtered = filtered;
83
145
  const visible = filtered === null ? null : new Set(filtered);
84
146
  const rows = full ? [] : change.rows.filter(node => this.#indices.has(node) && (visible === null || visible.has(this.#indices.get(node))));
85
- if (full || rows.length) publishCollection(this.#listeners,{full,rows});
147
+ if (full || rows.length || change.rows.length) publishCollection(this.#listeners,{full,rows});
86
148
  }
87
149
  #sorted(nodes, criteria) {
88
150
  if (!criteria.length) return nodes;
@@ -11,7 +11,8 @@ export function compileFilter(filter) {
11
11
  !['T', 'L', 'R', 'N', 'D'].includes(dtype)) throw new TypeError('Invalid collection filter');
12
12
  if (!value.trim()) return null;
13
13
  if (dtype === 'T') {
14
- const expression = new RegExp(value, 'i');
14
+ const pattern = filter.literal === true ? value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') : value;
15
+ const expression = new RegExp(pattern, 'i');
15
16
  return read => expression.test(columns.map(field => searchText(read(field), locale, filter.timeZone)).join(' '));
16
17
  }
17
18
  if (columns.length !== 1) throw new TypeError('Typed filters require one column');
@@ -0,0 +1,49 @@
1
+ import {isDecimal, toTytx, fromTytx} from '@genrojs/tytx';
2
+
3
+ /** Typed identities: captions never determine membership. Blank values share one bucket. */
4
+ export function columnValue(value) {
5
+ if (value == null || value === '') return null;
6
+ if (typeof value === 'string' || typeof value === 'boolean' ||
7
+ typeof value === 'number' && Number.isFinite(value) ||
8
+ value instanceof Date && Number.isFinite(value.getTime()) ||
9
+ isDecimal(value) && value.isFinite()) return value;
10
+ throw new TypeError('Column filters require loaded scalar values');
11
+ }
12
+ export function columnValueKey(value) { return toTytx(columnValue(value)); }
13
+ export function columnSelection(values) {
14
+ if (!Array.isArray(values)) throw new TypeError('Column selection requires an array or null');
15
+ return Object.freeze([...new Map(values.map(value => {
16
+ const key = columnValueKey(value);
17
+ return [key, fromTytx(key)];
18
+ })).values()]);
19
+ }
20
+
21
+ /** Civil bounds; datetime values use the same day convention as their display. */
22
+ export function columnDateRange(range) {
23
+ if (range === null) return null;
24
+ const {from, to, dtype, timeZone} = range;
25
+ if (!['D','DH','DHZ'].includes(dtype)) throw new TypeError('Date range requires a date column');
26
+ for (const value of [from,to]) {
27
+ if (value !== null && (!(value instanceof Date) || !Number.isFinite(value.getTime()) ||
28
+ value.getUTCHours() || value.getUTCMinutes() || value.getUTCSeconds() || value.getUTCMilliseconds())) {
29
+ throw new TypeError('Date bounds require civil dates');
30
+ }
31
+ }
32
+ if (from && to && from > to) throw new RangeError('From must not be after To.');
33
+ if (dtype === 'DHZ' && !timeZone) throw new TypeError('DHZ requires a timeZone');
34
+ return from || to ? Object.freeze({from:from?.toISOString().slice(0,10) ?? null,
35
+ to:to?.toISOString().slice(0,10) ?? null,dtype,timeZone}) : null;
36
+ }
37
+
38
+ export function columnDateMatches(value, range) {
39
+ if (!range) return true;
40
+ if (value == null || value === '') return false;
41
+ if (!(value instanceof Date) || !Number.isFinite(value.getTime())) throw new TypeError('Date range requires date values');
42
+ let day;
43
+ if (range.dtype === 'DHZ') {
44
+ const parts = new Intl.DateTimeFormat('en', {timeZone:range.timeZone,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(value);
45
+ const part = type => parts.find(item=>item.type===type).value;
46
+ day = `${part('year')}-${part('month')}-${part('day')}`;
47
+ } else day = value.toISOString().slice(0,10);
48
+ return (!range.from || day >= range.from) && (!range.to || day <= range.to);
49
+ }