@gramlot/gramlot 0.3.35 → 0.3.37

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 (117) hide show
  1. package/dist/components/charts/__init__.py +1 -1
  2. package/dist/components/charts/assets/collection.js +9 -9
  3. package/dist/components/charts/assets/index.js +1 -1
  4. package/dist/components/charts/grammar.json +0 -30
  5. package/dist/components/drawing/__init__.py +1 -1
  6. package/dist/components/drawing/assets/collection.js +3 -3
  7. package/dist/components/drawing/assets/index.js +1 -1
  8. package/dist/components/editors/__init__.py +2 -2
  9. package/dist/components/editors/assets/collection.js +4 -2
  10. package/dist/components/editors/assets/index.js +1 -1
  11. package/dist/components/editors/assets/modules/addon-fit-L6JK4OJX.js +12 -0
  12. package/dist/components/editors/assets/modules/xterm-BF3OSWRI.js +286 -0
  13. package/dist/components/editors/assets/modules/xterm-UBEXZEYY.js +47 -0
  14. package/dist/components/editors/grammar.json +207 -0
  15. package/dist/components/grid/__init__.py +1 -1
  16. package/dist/components/grid/assets/collection.js +6 -6
  17. package/dist/components/grid/assets/index.js +1 -1
  18. package/dist/components/grid/grammar.json +0 -2
  19. package/dist/components/inputs/__init__.py +1 -1
  20. package/dist/components/inputs/assets/collection.js +8 -8
  21. package/dist/components/inputs/assets/index.js +1 -1
  22. package/dist/components/inputs/grammar.json +2 -1
  23. package/dist/components/layout/__init__.py +1 -1
  24. package/dist/components/layout/assets/collection.js +9 -9
  25. package/dist/components/layout/assets/index.js +1 -1
  26. package/dist/components/layout/grammar.json +2 -2
  27. package/dist/components/selection_trial/__init__.py +1 -1
  28. package/dist/components/selection_trial/assets/collection.js +3 -3
  29. package/dist/components/selection_trial/assets/index.js +1 -1
  30. package/dist/components/tree/__init__.py +1 -1
  31. package/dist/components/tree/assets/collection.js +6 -6
  32. package/dist/components/tree/assets/index.js +1 -1
  33. package/dist/components/tree/grammar.json +0 -1
  34. package/dist/components/uploads/__init__.py +1 -1
  35. package/dist/components/uploads/assets/collection.js +3 -3
  36. package/dist/components/uploads/assets/index.js +1 -1
  37. package/dist/components/uploads/grammar.json +0 -3
  38. package/dist/gramlot.js +1238 -627
  39. package/dist/gramlot.min.js +45 -45
  40. package/dist/libraries.json +27 -0
  41. package/dist/standard-collections.js +1 -1
  42. package/package.json +4 -3
  43. package/src/binding/data-binder.js +11 -3
  44. package/src/binding/grid-struct.js +7 -4
  45. package/src/binding/runtime.js +203 -46
  46. package/src/builder/binding.json +23 -1
  47. package/src/builder/gramlot-builder.d.ts +1 -4
  48. package/src/builder/source.js +185 -29
  49. package/src/chat.js +26 -20
  50. package/src/components/attachment-manager.js +38 -34
  51. package/src/components/chart-data-view.js +4 -7
  52. package/src/components/chart-fields.js +18 -6
  53. package/src/components/chart-renderer.js +10 -3
  54. package/src/components/chart-timeline.js +7 -5
  55. package/src/components/charts.js +74 -67
  56. package/src/components/check-box-text-editor.js +3 -3
  57. package/src/components/check-box-text.js +7 -22
  58. package/src/components/check-box-tree.js +20 -16
  59. package/src/components/choice-editor.js +1 -1
  60. package/src/components/drawing.js +47 -34
  61. package/src/components/editors.js +3 -1
  62. package/src/components/grid-cell-editor.js +72 -29
  63. package/src/components/grid-column-filters.js +47 -40
  64. package/src/components/grid-formulas.js +22 -17
  65. package/src/components/grid-header-interaction.js +9 -11
  66. package/src/components/grid-row-interaction.js +25 -24
  67. package/src/components/grid-row-layout.js +28 -29
  68. package/src/components/grid-search-box.js +3 -3
  69. package/src/components/grid-search.js +3 -8
  70. package/src/components/grid-selection.js +33 -29
  71. package/src/components/grid-structure.js +48 -10
  72. package/src/components/grid-tools.js +14 -14
  73. package/src/components/grid.js +83 -79
  74. package/src/components/image-crop-dialog.js +2 -2
  75. package/src/components/image-crop.js +16 -9
  76. package/src/components/image-uploader.js +21 -28
  77. package/src/components/inputs.js +19 -1
  78. package/src/components/registry.js +3 -5
  79. package/src/components/terminal.js +158 -0
  80. package/src/components/tray-pane.js +85 -61
  81. package/src/components/tree.js +332 -239
  82. package/src/components/upload-engine.js +10 -2
  83. package/src/components/uploader.js +31 -27
  84. package/src/editing-session.d.ts +4 -1
  85. package/src/editing-session.js +120 -83
  86. package/src/experiments/window-selection.js +4 -6
  87. package/src/filesystem.js +2 -2
  88. package/src/gramlot.js +1 -0
  89. package/src/handlers/device-handler.js +219 -213
  90. package/src/handlers/rpc-handler.d.ts +17 -0
  91. package/src/handlers/rpc-handler.js +22 -0
  92. package/src/ide-documents.js +29 -11
  93. package/src/ide-runtime.js +33 -31
  94. package/src/index-page-runtime.d.ts +2 -2
  95. package/src/index-page-runtime.js +67 -48
  96. package/src/libraries.js +9 -0
  97. package/src/message-port-connection.js +100 -0
  98. package/src/message-port-store.js +158 -0
  99. package/src/page-store-connection.js +14 -1
  100. package/src/renderer/gramlot-renderer.js +21 -2
  101. package/src/source-picker.d.ts +2 -2
  102. package/src/source-picker.js +15 -6
  103. package/src/stores/bag-collection-store.js +25 -7
  104. package/src/stores/bag-collection-view.js +23 -22
  105. package/src/view/controls.js +1 -1
  106. package/src/view/html.js +45 -20
  107. package/src/visual-editor-canvas.js +1 -1
  108. package/src/visual-editor.js +18 -19
  109. package/tools/gramlot-tools-inspector.js +400 -374
  110. package/tools/inspector-agent.js +223 -49
  111. package/dist/components/vizabi/__init__.py +0 -13
  112. package/dist/components/vizabi/assets/collection.js +0 -4
  113. package/dist/components/vizabi/assets/index.js +0 -3
  114. package/dist/components/vizabi/commands.json +0 -7
  115. package/dist/components/vizabi/grammar.json +0 -128
  116. package/src/components/vizabi-session.js +0 -66
  117. package/src/components/vizabi.js +0 -66
@@ -2,6 +2,7 @@ import {defineComponent} from '@gramlot/gramlot/components';
2
2
  import {Container} from './container.js';
3
3
  import {randomId} from '../random-id.js';
4
4
  import {timeProfile,timeLabel,timeDate,timePeriod} from './chart-time.js';
5
+ import {chartRows} from './chart-fields.js';
5
6
 
6
7
  const scripts=new WeakMap();
7
8
  export function chartTimeLogic(binding){
@@ -21,18 +22,17 @@ export function chartTimeLogic(binding){
21
22
  return scripts.get(binding);
22
23
  }
23
24
  export const ChartTimeline=defineComponent({
24
- name:'chartTimeline',tag:'gramlot-chart-timeline',base:Container,sourceContext:true,bagStore:true,
25
+ name:'chartTimeline',tag:'gramlot-chart-timeline',base:Container,sourceContext:true,
25
26
  parameters:{storepath:{dtype:'T'},rowMode:{dtype:'T'},configpath:{dtype:'T'},timeField:{dtype:'T',binding:'read'},timeStep:{dtype:'T',binding:'read'},timeIndex:{dtype:'R',binding:'read'}},
26
27
  implementation:Base=>class extends Base{
27
- #context;#bag;#store;#release;#active=false;#syncing=false;#selection;#minimum;#profile;#field;
28
+ #context;#store;#release;#active=false;#syncing=false;#selection;#minimum;#profile;#field;
28
29
  constructor(){super();const style=this.ownerDocument.createElement('style');style.textContent=':host{display:none}';this.shadowRoot.append(style);}
29
30
  setSourceContext(context){this.#context=context;}
30
- setStoreBag(bag){this.#bag=bag;}
31
31
  projectAttributes(attrs,adapt){const result=super.projectAttributes(attrs,adapt);if(this.#active)this.#connect();return result;}
32
32
  connectedCallback(){this.#active=true;this.#connect();}
33
33
  #connect(){
34
- const store=this.#context.sourceNode.rootBuilder.binding.collectionStore(this.#bag,this.parameters.rowMode);
35
- if(store!==this.#store){this.#release?.();this.#store=store;this.#profile=null;this.#release=store.subscribe(()=>{this.#profile=null;this.#sync();});}
34
+ const store=this.#context.sourceNode.rootBuilder.binding.collectionStore(this.#context.attrDatapath('storepath'),this.parameters.rowMode);
35
+ if(store.key!==this.#store?.key){this.#release?.();this.#store=store;this.#profile=null;this.#release=store.subscribe(()=>{this.#profile=null;this.#sync();});}
36
36
  this.#sync();
37
37
  }
38
38
  #sync(){
@@ -41,6 +41,8 @@ export const ChartTimeline=defineComponent({
41
41
  const node=this.#context.sourceNode,path=this.parameters.configpath,config=node.getRelativeData(path);
42
42
  const put=(key,value)=>{const old=config.getItem(key);if(old instanceof Date&&value instanceof Date?old.getTime()!==value.getTime():old!==value)node.setRelativeData(`${path}.${key}`,value);};
43
43
  const {timeField:field,timeStep:requested}=this.parameters;
44
+ // An address without a readable collection leaves the timeline as it is; the chart view shows the error.
45
+ if(chartRows(this.#store)===null)return;
44
46
  if(!this.#profile||field!==this.#field){this.#profile=timeProfile(this.#store,field);this.#field=field;}
45
47
  const profile=this.#profile,step=requested==='auto'?profile.suggested:requested;
46
48
  put('timeHasClock',profile.hasClock);put('timeUnit',step);
@@ -2,6 +2,7 @@ import {ChartTimeView,timeLabel} from './chart-time.js';
2
2
  import {ChartTimeline} from './chart-timeline.js';
3
3
  import {ChartPane} from './chart-pane.js';
4
4
  import {Bag} from '@gramlot/gramlot';
5
+ import {collectionKey} from '../stores/bag-collection-store.js';
5
6
  import {defineCollection, defineComponent} from '@gramlot/gramlot/components';
6
7
  import {Container} from './container.js';
7
8
  import {gridSearch} from './grid-search.js';
@@ -16,11 +17,11 @@ import {ChartSyntaxError} from './chart-syntax.js';
16
17
  import {chartTypes} from './chart-types/index.js';
17
18
 
18
19
  const ChartView = defineComponent({
19
- name:'chartView', tag:'gramlot-chart-view', base:Container, sourceContext:true, bagStore:true,
20
+ name:'chartView', tag:'gramlot-chart-view', base:Container, sourceContext:true,
20
21
  parameters:{sampleMin:{dtype:'R',nullable:true,binding:'read'},sampleMax:{dtype:'R',nullable:true,binding:'read'},sampleStep:{dtype:'R',default:1,binding:'read'},sampleStart:{dtype:'R',default:0,binding:'read'},mapLabelMode:{dtype:'T',default:'value',binding:'read'},mapBarScale:{dtype:'T',default:'zero',binding:'read'},selectedTerritory:{dtype:'T',default:'',binding:'twoWay'},configpath:{dtype:'T'},timeEmpty:{dtype:'T',default:'previous',binding:'read'},timeField:{dtype:'T',default:'',binding:'read'},timeValue:{dtype:'X',nullable:true,binding:'read'},timeStep:{dtype:'T',default:'month',binding:'read'},engine:{dtype:'T',default:'echarts',binding:'read'},mapValueField:{dtype:'T',binding:'read'},mapLabelField:{dtype:'T',binding:'read'},geoJSON:{dtype:'X',nullable:true,binding:'read'},geometryField:{dtype:'T',binding:'read'},secondCaptionField:{dtype:'T',binding:'read'},seriesOptions:{dtype:'X',binding:'read'},storepath:{dtype:'T'}, rowMode:{dtype:'T'}, gridId:{dtype:'T'},
21
22
  chartType:{dtype:'T',binding:'read'}, captionField:{dtype:'T',binding:'read'}, valueFields:{dtype:'T',nullable:true,binding:'read'}},
22
23
  implementation:Base => class extends Base {
23
- #sampleView; #timeView; #revision=0; #active=false; #notice; #context; #store; #grid; #releaseGrid; #view; #releaseView; #renderer; #resize; #options; #optionsSubscription = Symbol('chart-options');
24
+ #sampleView; #timeView; #revision=0; #active=false; #notice; #context; #grid; #releaseGrid; #view; #releaseView; #renderer; #resize;
24
25
  constructor() {
25
26
  super();
26
27
  this.control.replaceChildren();
@@ -35,85 +36,91 @@ const ChartView = defineComponent({
35
36
  this.#resize = new this.ownerDocument.defaultView.ResizeObserver(() => this.#renderer?.resize());
36
37
  }
37
38
  setSourceContext(context) { this.#context = context; }
38
- setStoreBag(bag) {
39
- if (bag != null && !(bag instanceof Bag) && !Array.isArray(bag)) throw new TypeError('Chart requires a Data Bag or sample array');
40
- this.#store = bag;
41
- }
39
+ // seriesOptions is a `^` parameter of dtype 'X': a change inside the options Bag or a replacement
40
+ // at its address projects the chart again, and the draw reads the options at that address.
42
41
  projectAttributes(attrs, adapt) {
43
42
  const rest = super.projectAttributes(attrs,adapt);
44
- this.#bindOptions();
45
- if (this.#active) { this.#connectStore(); this.#render(); }
43
+ if (this.#active) this.#render();
46
44
  return rest;
47
45
  }
48
- #bindOptions() {
49
- const options = this.parameters.seriesOptions;
50
- if (!(options instanceof Bag)) throw new TypeError('seriesOptions requires a Bag');
51
- if (options === this.#options) return;
52
- this.#options?.unsubscribe(this.#optionsSubscription,{any:true});
53
- this.#options = options;
54
- options.subscribe(this.#optionsSubscription,{any:() => this.#render()});
55
- }
56
46
  connectedCallback() {
57
47
  this.#active = true;
58
- this.#bindOptions();
59
- const binding = this.#context.sourceNode.rootBuilder.binding;
60
- if (this.parameters.gridId) {
61
- const target = binding.nodeIds.get(this.parameters.gridId);
62
- if (!target || target.nodeTag !== 'grid') throw new TypeError('gridId requires an existing grid nodeId');
63
- if (target.absDatapath(target.getAttr('storepath')) !== this.#context.sourceNode.absDatapath(this.parameters.storepath)) {
64
- throw new TypeError('Chart and grid must use the same storepath');
65
- }
66
- this.#grid = gridSearch(target);
67
- this.#releaseGrid = this.#grid.subscribe(() => this.#syncGrid());
68
- }
69
- this.#connectStore();
70
48
  this.#render();
71
49
  this.#resize.observe(this.control);
72
50
  }
73
- #connectStore() {
74
- if (this.parameters.rowMode === 'samples') {
75
- if (this.parameters.gridId || this.parameters.timeField) throw new TypeError('Sample charts do not use grid filters or temporal playback');
51
+ /**
52
+ * Connect the chart to the collection at its storepath and to the grid of gridId, at each draw.
53
+ * Every link error is thrown here, inside the draw, and shows in the chart notice.
54
+ */
55
+ #connect() {
56
+ const {rowMode,gridId,timeField} = this.parameters;
57
+ if (rowMode === 'samples') {
58
+ if (gridId || timeField) throw new TypeError('Sample charts do not use grid filters or temporal playback: remove gridId and timeField, or use rowMode values or attributes');
76
59
  if (!this.#sampleView) {
77
- this.#releaseView?.(); this.#releaseView = null;
78
- this.#view?.dispose(); this.#view = null;
79
- this.#renderer?.dispose(); this.#renderer = null;
60
+ this.#release();
80
61
  this.#sampleView = new ChartSampleView();
81
- }
82
- this.#sampleView.bind(this.#store ?? [], this.parameters.sampleStep, this.parameters.sampleStart,
83
- this.parameters.captionField, this.parameters.valueFields);
84
- if (!this.#renderer) {
85
62
  this.#timeView = new ChartTimeView(this.#sampleView);
86
63
  this.#renderer = new ChartRenderer(this.control, this.#timeView, {renderer:'svg', domains:context=>this.#sampleView.domains(context,this.parameters.sampleMin,this.parameters.sampleMax)});
87
64
  }
88
65
  return;
89
66
  }
90
- if (this.#sampleView) {
91
- this.#renderer.dispose(); this.#renderer = null; this.#sampleView = null;
92
- }
93
- const store = this.#context.sourceNode.rootBuilder.binding.collectionStore(this.#store,this.parameters.rowMode);
67
+ const path = this.#context.attrDatapath('storepath');
68
+ // The view follows the store address: a replacement at the address keeps it, a new address replaces it.
69
+ if (this.#sampleView || this.#view && this.#view.view.storeKey !== collectionKey(path,rowMode)) this.#release();
94
70
  if (!this.#view) {
95
- this.#view = new ChartDataView(store);
71
+ // The view reads the rows at the address when it is created: an address without rows
72
+ // shows in the notice, and the Data change that brings them projects the chart again.
73
+ this.#view = new ChartDataView(this.#context.sourceNode.rootBuilder.binding.collectionStore(path,rowMode));
96
74
  this.#timeView = new ChartTimeView(this.#view.view);
97
75
  this.#renderer = new ChartRenderer(this.control,this.#timeView,{renderer:'svg',domains:context=>this.#timeView.domains(context),onTerritorySelect:name=>this.#context.writeParameter('selectedTerritory',name)});
98
76
  this.#releaseView = this.#view.view.subscribe(() => {this.#timeView.invalidateDomains();this.#render();});
99
- } else if (this.#view.view.bag !== this.#store) this.#view.bindStore(store);
100
- if (this.#grid) this.#syncGrid();
77
+ }
78
+ this.#linkGrid();
101
79
  }
102
- #syncGrid() {
103
- const gridView = this.#grid.view;
104
- if (!gridView) { this.#view?.detach(); return; }
105
- // Grid and chart receive the same Data replacement independently.
106
- // Follow only once both consumers refer to that replacement Bag.
107
- if (!this.#view || gridView.bag !== this.#store) return;
108
- this.#view.follow(gridView);
109
- this.#render();
80
+ /**
81
+ * gridId names the grid by nodeId, in the page's nodeId map that `#<nodeId>` paths read. The chart
82
+ * and the grid reach the same store by path and rowMode; the chart view follows the filter of the
83
+ * grid view while the grid shows, and keeps the last filter when the grid closes or leaves the page.
84
+ * A gridId that never reached a grid is an error.
85
+ */
86
+ #linkGrid() {
87
+ const gridId = this.parameters.gridId;
88
+ if (!gridId) { this.#unlinkGrid(); this.#view.detach(); return; }
89
+ const target = this.#context.sourceNode.rootBuilder.binding.nodeIds.get(gridId);
90
+ if (!target && this.#grid) { this.#view.detach(); return; }
91
+ if (!target) throw new TypeError(`gridId '${gridId}': the page has no node with this nodeId`);
92
+ if (target.nodeTag !== 'grid') throw new TypeError(`gridId '${gridId}': the node is a ${target.nodeTag}, not a grid`);
93
+ const gridKey = collectionKey(target.absDatapath(target.getAttr('storepath')), target.getAttr('rowMode'));
94
+ if (gridKey !== this.#view.view.storeKey) {
95
+ throw new TypeError(`gridId '${gridId}': chart and grid must use the same storepath and rowMode; the grid reads ${gridKey}, the chart ${this.#view.view.storeKey}`);
96
+ }
97
+ const search = gridSearch(target);
98
+ if (search !== this.#grid) {
99
+ this.#unlinkGrid();
100
+ this.#grid = search;
101
+ this.#releaseGrid = search.subscribe(() => this.#render());
102
+ }
103
+ const gridView = search.view;
104
+ if (!gridView) this.#view.detach();
105
+ // The grid view reaches the new store when the grid draws; its notice draws the chart again.
106
+ else if (gridView.storeKey === this.#view.view.storeKey) this.#view.follow(gridView);
107
+ }
108
+ #unlinkGrid() { this.#releaseGrid?.(); this.#releaseGrid = this.#grid = null; }
109
+ /** Release the view and the engine of the current store, as a new store or the samples mode require. */
110
+ #release() {
111
+ this.#releaseView?.(); this.#view?.dispose(); this.#renderer?.dispose();
112
+ this.#releaseView = this.#view = this.#renderer = this.#timeView = this.#sampleView = null;
110
113
  }
111
114
  async #render() {
112
- if (!this.#renderer) return;
113
115
  const {engine,chartType:typeId,captionField,valueFields,secondCaptionField,geometryField,geoJSON,mapValueField,mapLabelField,mapLabelMode,mapBarScale} = this.parameters;
114
116
  const revision=++this.#revision;
115
- this.#renderer.invalidate();
116
117
  try {
118
+ this.#connect();
119
+ this.#renderer.invalidate();
120
+ // The samples are read at the store address when the chart draws: a value that is not
121
+ // an array of numbers shows in the notice, as a store address without rows.
122
+ if (this.#sampleView) this.#sampleView.bind(this.#context.getStaticData(this.#context.attrDatapath('storepath')) ?? [],
123
+ this.parameters.sampleStep, this.parameters.sampleStart, this.parameters.captionField, this.parameters.valueFields);
117
124
  this.#timeView.setPeriod(this.parameters.timeField,this.parameters.timeValue,this.parameters.timeStep,this.parameters.timeEmpty);
118
125
  const rows=this.#timeView.getRows(),snapshot=this.#timeView.snapshotDate;
119
126
  if(this.parameters.configpath){
@@ -131,19 +138,23 @@ const ChartView = defineComponent({
131
138
  this.control.hidden = false;
132
139
  const structure=new Bag({engine,chartType:typeId,captionField,valueFields,secondCaptionField,geometryField,mapValueField,mapLabelField,mapLabelMode,mapBarScale});
133
140
  structure.setItem('geoJSON',geoJSON);
134
- await this.#renderer.update(structure, this.#options);
141
+ // The final read: the renderer reads seriesOptions at its address where it hands the values to the engine.
142
+ await this.#renderer.update(structure, {data:this.#context.sourceNode.data, path:this.#context.attrDatapath('seriesOptions')});
135
143
  if(revision!==this.#revision || !this.#renderer)return;
136
144
  this.#notice.hide();
137
145
  this.#renderer.resize();
138
146
  }
139
147
  catch (error) {
140
- if(revision!==this.#revision || !this.#renderer)return;
141
- this.control.hidden = true;
142
- const type=chartTypes.find(item=>item.id===typeId) ?? null;
143
- const title=error instanceof ChartSyntaxError ? `${type.label}: the configuration does not match the chart type` : `${type?.label ?? 'Chart'}: the chart cannot be drawn`;
144
- this.#notice.error(error.message,title,chartErrorSections(error,type));
148
+ if(revision!==this.#revision)return;
149
+ this.#showError(error);
145
150
  }
146
151
  }
152
+ #showError(error) {
153
+ this.control.hidden = true;
154
+ const type=chartTypes.find(item=>item.id===this.parameters.chartType) ?? null;
155
+ const title=error instanceof ChartSyntaxError ? `${type.label}: the configuration does not match the chart type` : `${type?.label ?? 'Chart'}: the chart cannot be drawn`;
156
+ this.#notice.error(error.message,title,chartErrorSections(error,type));
157
+ }
147
158
  /** Why a chart has no rows to draw, from its own parameters. */
148
159
  #emptySections(typeId) {
149
160
  const {storepath,rowMode,gridId,timeField}=this.parameters;
@@ -158,11 +169,7 @@ const ChartView = defineComponent({
158
169
  disconnectedCallback() {
159
170
  this.#active = false;
160
171
  this.#revision++;
161
- this.#options?.unsubscribe(this.#optionsSubscription,{any:true}); this.#options = null;
162
- this.#resize.disconnect(); this.#releaseGrid?.(); this.#releaseView?.();
163
- this.#view?.dispose(); this.#renderer?.dispose();
164
- this.#sampleView = null;
165
- this.#grid = this.#view = this.#renderer = this.#releaseGrid = this.#releaseView = null;
172
+ this.#resize.disconnect(); this.#unlinkGrid(); this.#release();
166
173
  }
167
174
  }
168
175
  });
@@ -183,7 +190,7 @@ function chartTypeElement(type) {
183
190
  if(role.required)spec.required=true;
184
191
  parameters[role.parameter==='valueFields'?role.name:role.parameter]=spec;
185
192
  }
186
- return defineComponent({name,tag,base:ChartView.base,sourceContext:true,bagStore:true,parameters,
193
+ return defineComponent({name,tag,base:ChartView.base,sourceContext:true,parameters,
187
194
  doc:`${type.doc} chartView with chartType '${type.id}'.`,
188
195
  implementation:Base=>ChartView.implementation(class extends Base {
189
196
  projectAttributes(attrs,adapt) {
@@ -1,4 +1,4 @@
1
- /** Text projection for checkBoxText. Codes remain the field value; drafts belong to Source. */
1
+ /** Text projection for checkBoxText. Codes remain the field value; drafts belong to the Source node's `_internal`. */
2
2
  export class CheckBoxTextEditor {
3
3
  constructor(owner) {
4
4
  this.owner = owner;
@@ -32,9 +32,9 @@ export class CheckBoxTextEditor {
32
32
  if (event.target !== owner.control) this.clear();
33
33
  });
34
34
  }
35
- get state() { return this.source.checkBoxTextState; }
35
+ get state() { return this.source._internal; }
36
36
  get locked() { return this.input.disabled || this.input.readOnly || !this.owner.pageContext?.isActive(); }
37
- attach(source) { this.source = source; source.checkBoxTextState ??= {draft:null}; }
37
+ attach(source) { this.source = source; source._internal.draft ??= null; }
38
38
  clear() {
39
39
  if (this.source) this.state.draft = null;
40
40
  this.owner.pageContext?.formSelectionError('');
@@ -4,17 +4,13 @@ import {positionPopup} from './popup.js';
4
4
  import {CheckBoxTree} from './check-box-tree.js';
5
5
  import {CheckBoxTextEditor} from './check-box-text-editor.js';
6
6
  import {choiceFieldStyles} from './choice-field-styles.js';
7
- import {randomId} from '../random-id.js';
8
7
 
9
8
  /** Multiple choices keep the existing group's commit and validation lifecycle. */
10
9
  export function checkBoxChoices(Base) {
11
10
  return class extends Base {
12
- #store;
13
11
  #text;
14
12
  #sourceContext;
15
13
  #tree;
16
- #refreshScheduled = false;
17
- #subscription = `checkbox-options-${randomId()}`;
18
14
  #attrs;
19
15
  #request;
20
16
  #configuration;
@@ -58,9 +54,11 @@ export function checkBoxChoices(Base) {
58
54
  if (hierarchical) return [];
59
55
  if (dbtable || method) return this.#rows;
60
56
  if (typeof values === 'string') return parseChoices(values);
61
- if (!(values instanceof Bag)) throw new TypeError('values must be text or a Bag');
57
+ // Bag options are read at the address of the `values` pointer, never from the projected value.
58
+ const options = this.#sourceContext.getStaticData(this.#sourceContext.attrDatapath('values'));
59
+ if (!(options instanceof Bag)) throw new TypeError('values must be text or a Bag');
62
60
  const ids = new Set();
63
- return values.getNodes().map(node => {
61
+ return options.getNodes().map(node => {
64
62
  const read = key => node.staticValue instanceof Bag ? node.staticValue.getItem(key) : node.getAttr(key);
65
63
  const id = identifier ? read(identifier) : node.label;
66
64
  const caption = labelAttribute ? read(labelAttribute) : node.label;
@@ -77,21 +75,8 @@ export function checkBoxChoices(Base) {
77
75
  if (hierarchical && !this.#tree) this.#tree = new CheckBoxTree(this, this.#sourceContext);
78
76
  if (!hierarchical && this.#tree) { this.#tree.dispose(); this.#tree = null; }
79
77
  if ((dbtable || method) && values !== '') throw new TypeError('Remote choices and values are mutually exclusive');
80
- const store = values instanceof Bag ? values : null;
81
- if (store !== this.#store) {
82
- this.#store?.unsubscribe(this.#subscription, {any:true}); this.#store = store;
83
- store?.subscribe(this.#subscription, {any:() => {
84
- if (!this.parameters.hierarchical) {
85
- this.projectAttributes(this.#attrs); this.writeControlValue(this.readControlValue());
86
- } else if (!this.#refreshScheduled) {
87
- this.#refreshScheduled = true;
88
- queueMicrotask(() => {
89
- this.#refreshScheduled = false;
90
- if (this.isConnected && this.pageContext?.isActive()) this.projectAttributes(this.#attrs);
91
- });
92
- }
93
- }});
94
- }
78
+ // `values` is a `^` parameter of dtype 'X': a change inside the options Bag or a replacement at
79
+ // its address projects the control again, and the options are read at that address.
95
80
  this.summary.hidden = !popup; this.summary.disabled = Boolean(disabled || readonly || !this.#available);
96
81
  for (const input of this.control.querySelectorAll("input")) input.disabled = this.summary.disabled;
97
82
  if (!popup || this.summary.disabled) this.closeChoices();
@@ -185,7 +170,7 @@ export function checkBoxChoices(Base) {
185
170
  }
186
171
  focus(options) { if (this.parameters.popup) this.summary.focus(options); else if (this.#tree) this.#tree.focus(); else super.focus(options); }
187
172
  releaseControl() {
188
- this.closeChoices(); this.#request?.abort(); this.#store?.unsubscribe(this.#subscription,{any:true}); this.#store = null;
173
+ this.closeChoices(); this.#request?.abort();
189
174
  this.#tree?.dispose(); this.#tree = null;
190
175
  super.releaseControl();
191
176
  }
@@ -2,27 +2,34 @@ import {Bag} from '@gramlot/gramlot';
2
2
 
3
3
  /** Identity/caption projection only. The shared tree owns checks and lazy propagation. */
4
4
  export class CheckBoxTree {
5
- // Derived index from the last projection: newly loaded codes are still pending
6
- // until that projection has supplied their paths to the shared tree.
7
- #knownCodes = new Set();
5
+ // Paths of the loaded options at the last projection: a path the tree cannot reach is kept.
6
+ #knownPaths = new Set();
7
+ #context;
8
8
  constructor(owner, context) {
9
- this.owner = owner;
9
+ this.owner = owner; this.#context = context;
10
10
  this.element = owner.ownerDocument.createElement('gramlot-tree');
11
- this.element.setSourceContext({...context, writeParameter:(name, paths) => {
11
+ // The inner tree has no Source node: it reads the host's `values` address at each use. Its check
12
+ // list is the control value: the `checkedPaths` of the tree, or with an identifier its
13
+ // `checked_<identifier>`, which the tree reads and writes through the control at every draw.
14
+ this.element.setSourceContext({...context, treeStore:() => context.getStaticData(context.attrDatapath('values')), writeParameter:(name, paths) => {
12
15
  if (name !== 'checkedPaths' || !owner.pageContext?.isActive()) return;
13
- const rows = this.options(), byPath = new Map(rows.map(row => [row.path,row.id]));
14
- const known = this.#knownCodes;
15
- const selected = (paths || '').split(',').filter(Boolean).map(path => owner.parameters.identifier ? byPath.get(path) : path).filter(code => code !== undefined);
16
+ const selected = (paths || '').split(',').filter(Boolean);
16
17
  const old = (owner.readControlValue() || '').split(',').filter(Boolean);
17
- const codes = old.filter(code => !known.has(code) || selected.includes(code));
18
+ const codes = old.filter(code => !this.#knownPaths.has(code) || selected.includes(code));
18
19
  for (const code of selected) if (!codes.includes(code)) codes.push(code);
19
20
  const value = codes.join(',') || null;
20
21
  if (value !== owner.readControlValue()) owner.acceptTreeValue(value);
22
+ },
23
+ readRelativeData:() => owner.readControlValue(),
24
+ setRelativeData:(_path, codes) => {
25
+ if (owner.pageContext?.isActive() && (codes || null) !== owner.readControlValue()) owner.acceptTreeValue(codes || null);
21
26
  }});
22
27
  owner.control.append(this.element);
23
28
  }
24
29
  options() {
25
- const {values, identifier, labelAttribute} = this.owner.parameters;
30
+ const {identifier, labelAttribute} = this.owner.parameters;
31
+ // The options are read at the host's `values` address at each projection.
32
+ const values = this.#context.getStaticData(this.#context.attrDatapath('values'));
26
33
  if (!(values instanceof Bag)) throw new TypeError('hierarchical checkBoxText requires a Bag in values');
27
34
  const rows = [], ids = new Set(), ancestors = new Set();
28
35
  const visit = (bag, prefix) => {
@@ -47,14 +54,11 @@ export class CheckBoxTree {
47
54
  }
48
55
  project(value) {
49
56
  const p = this.owner.parameters;
50
- const byCode = new Map(this.options().map(row => [row.id,row.path]));
51
- this.#knownCodes = new Set(byCode.keys());
52
- const paths = value === null ? null : (value || '').split(',').filter(Boolean)
53
- .map(code => p.identifier ? byCode.get(code) : code).filter(Boolean).join(',');
57
+ this.#knownPaths = new Set(this.options().map(row => row.path));
54
58
  this.element.inert = Boolean(p.disabled || p.readonly);
55
59
  this.element.setAttribute('aria-disabled', String(this.element.inert));
56
- this.element.setStoreBag(p.values);
57
- this.element.projectAttributes({checkedPaths:paths, checkChildren:p.checkChildren,
60
+ const checks = p.identifier ? {[`checked_${p.identifier}`]:'value'} : {checkedPaths:value};
61
+ this.element.projectAttributes({...checks, checkChildren:p.checkChildren,
58
62
  labelAttribute:p.labelAttribute ?? null, hideValues:true});
59
63
  }
60
64
  focus() { this.element.shadowRoot.querySelector('[role=treeitem]')?.focus(); }
@@ -90,7 +90,7 @@ export function ChoiceEditor(HTMLElement) {
90
90
  get autoHighlight() { return true; }
91
91
  get matchTypedChoice() { return true; }
92
92
  get emptyChoice() { return null; }
93
- get choiceSource() { return this.parameters.store ?? this.parameters.callback ?? this.parameters.values; }
93
+ get choiceSource() { return this.parameters.callback ?? this.parameters.values; }
94
94
  get searchDelay() { return 0; }
95
95
  textValue(text) { return text; }
96
96
  selectionAccepted(row) {}
@@ -13,7 +13,9 @@ export const DrawingPane = defineComponent({
13
13
  parameters:{image:{dtype:'T',nullable:true,default:null,binding:'read'},
14
14
  annotations:{dtype:'X',binding:'read'}},
15
15
  implementation:Base => class extends Base {
16
- #svg; #image; #editor; #editing; #state; #statePath; #stateSubscription = `drawing-state-${randomId()}`; #syncing = false; #built = false; #lastColor; #lastSize; #bag; #subscription = `drawing-${randomId()}`;
16
+ // The annotations are read at the address of the `annotations` pointer at each use; the
17
+ // tool state lives in the node's private Data area and is observed through a router registration.
18
+ #svg; #image; #editor; #editing; #stateRegistration = null; #syncing = false; #built = false; #lastColor; #lastSize; #annotationsPath = null;
17
19
  #tool='select'; #selected=null; #gesture=null; #dimensions=[1000,1000]; #url=null; #events;
18
20
  constructor() {
19
21
  super();
@@ -33,6 +35,16 @@ export const DrawingPane = defineComponent({
33
35
  this.#image=d.createElement('img');
34
36
  }
35
37
  setSourceContext(context) { this.context=context; }
38
+ /** The tool state address: the private Data area of the drawingPane node (`workspaceDatapath`). */
39
+ get #statePath() { return this.context.sourceNode.workspaceDatapath; }
40
+ #state(key) { return this.context.getStaticData(`${this.#statePath}.${key}`); }
41
+ #setState(key,value) { this.context.sourceNode.data.setItem(`${this.#statePath}.${key}`,value); }
42
+ /** The annotations Bag, read at the address of the `annotations` pointer at each use; never kept. */
43
+ #annotations() {
44
+ const bag=this.context.getStaticData(this.#annotationsPath);
45
+ if(!(bag instanceof Bag))throw new TypeError('drawingPane annotations requires a Data Bag');
46
+ return bag;
47
+ }
36
48
  projectAttributes(attrs,adapt) {
37
49
  const rest=super.projectAttributes(attrs,adapt);
38
50
  if(this.isConnected)this.#connect();
@@ -42,21 +54,24 @@ export const DrawingPane = defineComponent({
42
54
  this.#events=new this.ownerDocument.defaultView.AbortController();const options={signal:this.#events.signal};
43
55
  this.#makeToolbar();
44
56
  if(!this.isConnected)return;
45
- this.#state.subscribe(this.#stateSubscription,{any:()=>this.#stateChanged()});
57
+ this.#stateRegistration=this.context.sourceNode.rootBuilder.binding.router.register({path:this.#statePath,subtree:true,
58
+ recipient:{receive:()=>this.#stateChanged()}});
46
59
  this.#svg.addEventListener('pointerdown',e=>this.#down(e),options);
47
60
  this.#svg.addEventListener('pointermove',e=>this.#move(e),options);
48
61
  this.#svg.addEventListener('pointerup',e=>this.#up(e),options);
49
62
  this.#svg.addEventListener('pointercancel',()=>{this.#gesture=null;this.#render();},options);
50
- this.#svg.addEventListener('dblclick',e=>{const id=e.target.closest('[data-id]')?.dataset.id;if(id&&this.#bag.getItem(id)?.getItem('type')==='text'){this.#gesture=null;this.#editText(id);e.preventDefault();}},options);
63
+ this.#svg.addEventListener('dblclick',e=>{const id=e.target.closest('[data-id]')?.dataset.id;if(id&&this.#annotations().getItem(id)?.getItem('type')==='text'){this.#gesture=null;this.#editText(id);e.preventDefault();}},options);
51
64
  this.#editor.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();this.#finishText(true);}else if(e.key==='Escape'){e.preventDefault();this.#finishText(false);}},options);
52
65
  this.#editor.addEventListener('blur',()=>this.#finishText(true),options);
53
66
  this.#connect();
54
67
  }
55
- disconnectedCallback() {this.#finishText(false);this.#events?.abort();this.#events=null;this.#state?.unsubscribe(this.#stateSubscription,{any:true});this.#bag?.unsubscribe(this.#subscription,{any:true});this.#bag=null;this.#image.onload=null;this.#image.onerror=null;this.#url=null;this.#gesture=null;}
68
+ disconnectedCallback() {this.#finishText(false);this.#events?.abort();this.#events=null;this.#stateRegistration?.close();this.#stateRegistration=null;this.#annotationsPath=null;this.#image.onload=null;this.#image.onerror=null;this.#url=null;this.#gesture=null;}
56
69
  #connect() {
57
- const bag=this.parameters.annotations;
58
- if(!(bag instanceof Bag))throw new TypeError('drawingPane annotations requires a Data Bag');
59
- if(bag!==this.#bag){this.#bag?.unsubscribe(this.#subscription,{any:true});this.#bag=bag;bag.subscribe(this.#subscription,{any:()=>this.#render()});this.#selected=null;}
70
+ // `annotations` is a `^` parameter of dtype 'X': a change inside the Bag or a replacement at its
71
+ // address projects the pane again. A new address ends the selection.
72
+ const path=this.context.attrDatapath('annotations');
73
+ if(path!==this.#annotationsPath){this.#annotationsPath=path;this.#selected=null;}
74
+ this.#annotations();
60
75
  const url=this.parameters.image;
61
76
  if(url!==this.#url){
62
77
  this.#url=url;this.#gesture=null;
@@ -74,20 +89,18 @@ export const DrawingPane = defineComponent({
74
89
  if(this.#built)return;
75
90
  const node=this.context.sourceNode,builder=node.rootBuilder;
76
91
  const existing=node.value?.getNode('bar');
77
- if(existing){this.#state=node.drawingState;this.#statePath=node.drawingStatePath;existing.drawingController=this;this.#built=true;this.#tool=this.#state.getItem('tool');this.#lastColor=this.#state.getItem('color');this.#lastSize=this.#state.getItem('size');return;}
78
- this.#statePath=`_gramlot.drawing.${randomId()}`;
79
- this.#state=new Bag({tool:'select',color:'#dd2222',size:3});
80
- node.setRelativeData(this.#statePath,this.#state);
81
- Object.defineProperty(node,'drawingState',{value:this.#state,configurable:true});
82
- Object.defineProperty(node,'drawingStatePath',{value:this.#statePath,configurable:true});
83
- this.#lastColor=this.#state.getItem('color');this.#lastSize=this.#state.getItem('size');
92
+ if(existing){existing._internal.drawingController=this;this.#built=true;this.#tool=this.#state('tool');this.#lastColor=this.#state('color');this.#lastSize=this.#state('size');return;}
93
+ // The private area keeps the tool state of an earlier build of the same node.
94
+ if(!(this.#state('tool')&&this.#state('color')&&this.#state('size')))
95
+ node.data.setItem(this.#statePath,new Bag({tool:'select',color:'#dd2222',size:3}));
96
+ this.#tool=this.#state('tool');this.#lastColor=this.#state('color');this.#lastSize=this.#state('size');
84
97
  const fragment=new builder.source.constructor(null,builder),root=builder.wrapSource(fragment);
85
98
  const bar=root.menu({node_label:'bar',presentation:'bar',orientation:'vertical',labelPosition:'tooltip',iconSize:20,aria_label:'Image annotations'});
86
- Object.defineProperty(sourceTarget(bar),'drawingController',{value:this,configurable:true,writable:true});
99
+ sourceTarget(bar)._internal.drawingController=this;
87
100
  const paths={select:'M5 3l13 11-6 .5-3 5z',freehand:'M4 20l3.5-.7L19 7.8 16.2 5 4.7 16.5z M14.7 6.5l2.8 2.8',arrow:'M4 19L19 4 M12 4h7v7',circle:'M20 12a8 8 0 1 1-16 0 8 8 0 0 1 16 0z',text:'M4 5h16 M12 5v14 M8 19h8',delete:'M4 7h16 M9 7V4h6v3 M7 7l1 13h8l1-13 M10 10v7 M14 10v7'};
88
101
  const icon=key=>'data:image/svg+xml,'+encodeURIComponent(`<svg xmlns="${SVG_NS}" viewBox="0 0 24 24" fill="none" stroke="#7e93ad" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="${paths[key]}"/></svg>`);
89
102
  for(const [tool,label] of [['select','Select'],['freehand','Draw'],['arrow','Arrow'],['circle','Circle'],['text','Text']]){
90
- bar.menuline({caption:label,tooltip:label,iconSrc:icon(tool),checked:`^${this.#statePath}.tool:={} === '${tool}'`,action:`this.parentBag.parentNode.drawingController.setTool('${tool}')`});
103
+ bar.menuline({caption:label,tooltip:label,iconSrc:icon(tool),checked:`^${this.#statePath}.tool:={} === '${tool}'`,action:`this.parentBag.parentNode._internal.drawingController.setTool('${tool}')`});
91
104
  }
92
105
  bar.contentPane({height:'1px',margin:'6px 4px',background:'var(--gramlot-border-control,#a8b2bf)'});
93
106
  const circleIcon=color=>'data:image/svg+xml,'+encodeURIComponent(`<svg xmlns="${SVG_NS}" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8" fill="${color}" stroke="#8793a3" stroke-width="1.5"/></svg>`);
@@ -102,15 +115,15 @@ export const DrawingPane = defineComponent({
102
115
  for(const size of [1,3,5,7,12,20])sizeMenu.menuline({caption:`${size} px`,iconSrc:strokeIcon(Math.min(size,12)),checked:`^${this.#statePath}.size:={} === ${size}`,action:`this.SET('${this.#statePath}.size', ${size});`});
103
116
  sizeMenu.contentPane({padding:'8px'}).numberTextBox({value:`^${this.#statePath}.size`,lbl:'Custom size',aria_label:'Pen size',dtype:'L',min:1,max:20,width:'140px'});
104
117
  bar.contentPane({flex:'1',min_height:'12px'});
105
- bar.menuline({caption:'Delete',tooltip:'Delete',iconSrc:icon('delete'),action:'this.parentBag.parentNode.drawingController.deleteSelection()'});
118
+ bar.menuline({caption:'Delete',tooltip:'Delete',iconSrc:icon('delete'),action:'this.parentBag.parentNode._internal.drawingController.deleteSelection()'});
106
119
  const app=builder.binding.gramlot,source=app.src.prepareSource(fragment);
107
120
  app.src.renderer.validateCandidate(source);this.#built=true;node.setValue(source);
108
121
  }
109
- setTool(tool){this.#finishText(true);this.#gesture=null;this.#state.setItem('tool',tool);}
110
- deleteSelection(){if(this.#selected){this.#bag.popNode(this.#selected);this.#selected=null;this.#render();}}
122
+ setTool(tool){this.#finishText(true);this.#gesture=null;this.#setState('tool',tool);}
123
+ deleteSelection(){if(this.#selected){this.#annotations().popNode(this.#selected);this.#selected=null;this.#render();}}
111
124
  #stateChanged(){
112
- const tool=this.#state.getItem('tool');this.#tool=tool;
113
- const color=this.#state.getItem('color'),size=this.#state.getItem('size');
125
+ const tool=this.#state('tool');this.#tool=tool;
126
+ const color=this.#state('color'),size=this.#state('size');
114
127
  const changed=color!==this.#lastColor||size!==this.#lastSize;this.#lastColor=color;this.#lastSize=size;
115
128
  if(changed&&!this.#syncing)this.#styleSelection();
116
129
  this.#render();
@@ -125,9 +138,9 @@ export const DrawingPane = defineComponent({
125
138
  const id=event.target.closest('[data-id]')?.getAttribute('data-id');
126
139
  if(this.#tool==='select'){
127
140
  this.#selected=id||null;
128
- if(id){const value=this.#bag.getItem(id);if(!(value instanceof Bag))throw new TypeError('Annotation must be a Bag');const row=this.#read(value);this.#syncing=true;try{this.#state.setItem('color',row.color);this.#state.setItem('size',row.width);}finally{this.#syncing=false;}this.#gesture={id,start:point,original:row};}
141
+ if(id){const value=this.#annotations().getItem(id);if(!(value instanceof Bag))throw new TypeError('Annotation must be a Bag');const row=this.#read(value);this.#syncing=true;try{this.#setState('color',row.color);this.#setState('size',row.width);}finally{this.#syncing=false;}this.#gesture={id,start:point,original:row};}
129
142
  }else if(this.#tool==='text'){
130
- const value=id?this.#bag.getItem(id):null;
143
+ const value=id?this.#annotations().getItem(id):null;
131
144
  this.#editText(value instanceof Bag&&value.getItem('type')==='text'?id:null,point);
132
145
  }else {this.#selected=null;this.#gesture={start:point,current:point,points:[point]};}
133
146
  if(this.#gesture)this.#svg.setPointerCapture(event.pointerId);this.#render();event.preventDefault();
@@ -135,20 +148,20 @@ export const DrawingPane = defineComponent({
135
148
  #move(event){if(!this.#gesture||!this.#dimensions)return;const point=this.#point(event);if(!point)return;this.#gesture.current=point;if(this.#tool==='freehand')this.#gesture.points.push(point);this.#render();}
136
149
  #up(event){
137
150
  if(!this.#gesture)return;this.#move(event);const gesture=this.#gesture;this.#gesture=null;
138
- if(gesture.id){const delta={x:gesture.current.x-gesture.start.x,y:gesture.current.y-gesture.start.y};const row=this.#translate(gesture.original,delta);this.#bag.setItem(gesture.id,new Bag(row));}
151
+ if(gesture.id){const delta={x:gesture.current.x-gesture.start.x,y:gesture.current.y-gesture.start.y};const row=this.#translate(gesture.original,delta);this.#annotations().setItem(gesture.id,new Bag(row));}
139
152
  else {const {start,current,points}=gesture;let row;
140
153
  if(this.#tool==='arrow')row={type:'arrow',x:start.x,y:start.y,x2:current.x,y2:current.y};
141
154
  else if(this.#tool==='circle')row={type:'circle',x:start.x,y:start.y,radius:Math.hypot(current.x-start.x,current.y-start.y)};
142
155
  else if(this.#tool==='freehand')row={type:'freehand',points};
143
- if(row)this.#insert({...row,color:this.#state.getItem('color'),width:this.#penSize()});
156
+ if(row)this.#insert({...row,color:this.#state('color'),width:this.#penSize()});
144
157
  }
145
158
  if(this.#svg.hasPointerCapture(event.pointerId))this.#svg.releasePointerCapture(event.pointerId);this.#render();
146
159
  }
147
- #insert(row){const id=`item_${randomId()}`;this.#bag.setItem(id,new Bag(row));this.#selected=id;}
148
- #penSize(){const value=this.#state.getItem('size');return Number.isFinite(value)?Math.max(1,Math.min(20,value)):3;}
149
- #styleSelection(){if(!this.#selected)return;const value=this.#bag.getItem(this.#selected);if(!(value instanceof Bag))return;const row=this.#read(value);row.color=this.#state.getItem('color');row.width=this.#penSize();this.#bag.setItem(this.#selected,new Bag(row));}
160
+ #insert(row){const id=`item_${randomId()}`;this.#annotations().setItem(id,new Bag(row));this.#selected=id;}
161
+ #penSize(){const value=this.#state('size');return Number.isFinite(value)?Math.max(1,Math.min(20,value)):3;}
162
+ #styleSelection(){if(!this.#selected)return;const value=this.#annotations().getItem(this.#selected);if(!(value instanceof Bag))return;const row=this.#read(value);row.color=this.#state('color');row.width=this.#penSize();this.#annotations().setItem(this.#selected,new Bag(row));}
150
163
  #editText(id,point){
151
- this.#finishText(true);const row=id?this.#read(this.#bag.getItem(id)):{type:'text',...point,text:'',color:this.#state.getItem('color'),width:this.#penSize()};
164
+ this.#finishText(true);const row=id?this.#read(this.#annotations().getItem(id)):{type:'text',...point,text:'',color:this.#state('color'),width:this.#penSize()};
152
165
  this.#selected=id;this.#editing={id,row};this.#editor.value=row.text;this.#editor.hidden=false;
153
166
  const svgPoint=this.#svg.createSVGPoint();svgPoint.x=row.x;svgPoint.y=row.y;const matrix=this.#svg.getScreenCTM();if(!matrix){this.#finishText(false);return;}
154
167
  const position=svgPoint.matrixTransform(matrix),box=this.controlBox.getBoundingClientRect();
@@ -158,8 +171,8 @@ export const DrawingPane = defineComponent({
158
171
  }
159
172
  #finishText(commit){
160
173
  if(!this.#editing)return;const {id,row}=this.#editing;this.#editing=null;const text=this.#editor.value.trim();this.#editor.hidden=true;
161
- if(commit&&text){row.text=text;if(id)this.#bag.setItem(id,new Bag(row));else this.#insert(row);}
162
- if(commit)this.#state.setItem('tool','select');
174
+ if(commit&&text){row.text=text;if(id)this.#annotations().setItem(id,new Bag(row));else this.#insert(row);}
175
+ if(commit)this.#setState('tool','select');
163
176
  this.#render();
164
177
  }
165
178
  #read(row){
@@ -183,16 +196,16 @@ export const DrawingPane = defineComponent({
183
196
  return g;
184
197
  }
185
198
  #render(){
186
- if(!this.#svg||!this.#bag)return;this.#svg.replaceChildren();if(!this.#dimensions)return;
199
+ if(!this.#svg||!this.#annotationsPath)return;this.#svg.replaceChildren();if(!this.#dimensions)return;
187
200
  const [width,height]=this.#dimensions;this.#svg.setAttribute('viewBox',`0 0 ${width} ${height}`);
188
201
  if(this.#url)this.#svg.append(this.#element('image',{href:this.#url,x:0,y:0,width,height,'pointer-events':'none'}));
189
- for(const node of this.#bag.getNodes()){
202
+ for(const node of this.#annotations().getNodes()){
190
203
  const value=node.getValue();if(!(value instanceof Bag))throw new TypeError('Annotation must be a Bag');let row=this.#read(value);
191
204
  if(this.#gesture?.id===node.label&&this.#gesture.current)row=this.#translate(this.#gesture.original,{x:this.#gesture.current.x-this.#gesture.start.x,y:this.#gesture.current.y-this.#gesture.start.y});
192
205
  const shape=this.#shape(row,node.label);this.#svg.append(shape);
193
206
  if(row.type==='text'){const bounds=shape.querySelector('text').getBBox(),hit=shape.querySelector('[data-text-hit]');for(const name of ['x','y','width','height'])hit.setAttribute(name,bounds[name]);}
194
207
  }
195
- const g=this.#gesture;if(g&&!g.id&&g.current){let row;if(this.#tool==='arrow')row={type:'arrow',x:g.start.x,y:g.start.y,x2:g.current.x,y2:g.current.y};if(this.#tool==='circle')row={type:'circle',x:g.start.x,y:g.start.y,radius:Math.hypot(g.current.x-g.start.x,g.current.y-g.start.y)};if(this.#tool==='freehand')row={type:'freehand',points:g.points};if(row)this.#svg.append(this.#shape({...row,color:this.#state.getItem('color'),width:this.#penSize()},''));}
208
+ const g=this.#gesture;if(g&&!g.id&&g.current){let row;if(this.#tool==='arrow')row={type:'arrow',x:g.start.x,y:g.start.y,x2:g.current.x,y2:g.current.y};if(this.#tool==='circle')row={type:'circle',x:g.start.x,y:g.start.y,radius:Math.hypot(g.current.x-g.start.x,g.current.y-g.start.y)};if(this.#tool==='freehand')row={type:'freehand',points:g.points};if(row)this.#svg.append(this.#shape({...row,color:this.#state('color'),width:this.#penSize()},''));}
196
209
  }
197
210
  }
198
211
  });