@livenetworks/ashlar 2.1.12 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +25 -2
  2. package/components/COMPONENTS.md +29 -25
  3. package/components/ln-api-connector/ln-api-connector.schema.json +105 -105
  4. package/components/ln-chart/ln-chart-dev.scss +0 -4
  5. package/components/ln-core/README.md +16 -60
  6. package/components/ln-core/index.js +1 -1
  7. package/components/ln-core/ln-core.schema.json +120 -120
  8. package/components/ln-core/query.js +113 -113
  9. package/components/ln-core/reactive.js +0 -59
  10. package/components/ln-data-coordinator/README.md +2 -0
  11. package/components/ln-data-coordinator/ln-data-coordinator.js +1 -1
  12. package/components/ln-data-coordinator/ln-data-coordinator.schema.json +196 -196
  13. package/components/ln-data-coordinator/src/ln-data-coordinator.js +457 -432
  14. package/components/ln-data-store/ln-data-store.schema.json +92 -92
  15. package/components/ln-date/ln-date.js +1 -1
  16. package/components/ln-date/src/ln-date.js +1 -1
  17. package/components/ln-debug/ln-debug.js +1 -1
  18. package/components/ln-debug/ln-debug.schema.json +28 -28
  19. package/components/ln-debug/src/generated-attributes.js +304 -302
  20. package/components/ln-dropdown/ln-dropdown.schema.json +90 -90
  21. package/components/ln-external-links/README.md +19 -19
  22. package/components/ln-external-links/ln-external-links.js +1 -1
  23. package/components/ln-external-links/ln-external-links.schema.json +9 -0
  24. package/components/ln-external-links/ln-external-links.scss +12 -0
  25. package/components/ln-external-links/src/ln-external-links.js +3 -2
  26. package/components/ln-filter/README.md +2 -1
  27. package/components/ln-filter/ln-filter.js +1 -1
  28. package/components/ln-filter/ln-filter.schema.json +157 -169
  29. package/components/ln-filter/src/ln-filter.js +4 -4
  30. package/components/ln-form/ln-form.schema.json +57 -57
  31. package/components/ln-key/ln-key.js +1 -1
  32. package/components/ln-key/ln-key.schema.json +8 -0
  33. package/components/ln-key/src/ln-key.js +8 -5
  34. package/components/ln-obfuscator/ln-obfuscator.js +1 -1
  35. package/components/ln-obfuscator/ln-obfuscator.schema.json +6 -0
  36. package/components/ln-obfuscator/src/ln-obfuscator.js +2 -2
  37. package/components/ln-options/ln-options.schema.json +47 -47
  38. package/components/ln-popover/ln-popover.schema.json +82 -82
  39. package/components/ln-progress/ln-progress.schema.json +0 -13
  40. package/components/ln-search/ln-search.schema.json +111 -111
  41. package/components/ln-sort/README.md +1 -0
  42. package/components/ln-sort/ln-sort.js +1 -1
  43. package/components/ln-sort/ln-sort.schema.json +100 -112
  44. package/components/ln-sort/src/sort-model.js +1 -6
  45. package/components/ln-sortable/ln-sortable.schema.json +38 -38
  46. package/components/ln-sortable/ln-sortable.scss +25 -25
  47. package/components/ln-table/README.md +8 -1
  48. package/components/ln-table/ln-table.js +1 -1
  49. package/components/ln-table/ln-table.schema.json +195 -195
  50. package/components/ln-table/src/ln-table.js +43 -7
  51. package/components/ln-table-coordinator/ln-table-coordinator.js +1 -1
  52. package/components/ln-table-coordinator/ln-table-coordinator.schema.json +18 -0
  53. package/components/ln-table-coordinator/src/ln-table-coordinator.js +104 -2
  54. package/components/ln-toast/README.md +1 -1
  55. package/components/ln-toast/ln-toast.js +1 -1
  56. package/components/ln-toast/ln-toast.schema.json +6 -0
  57. package/components/ln-toast/src/ln-toast.js +1 -1
  58. package/components/ln-validate/README.md +6 -6
  59. package/components/ln-validate/ln-validate-dev.scss +0 -5
  60. package/components/ln-validate/ln-validate.js +1 -1
  61. package/components/ln-validate/ln-validate.schema.json +0 -6
  62. package/components/ln-validate/src/ln-validate.js +48 -29
  63. package/ln-ashlar.html-data.json +1824 -1814
  64. package/package.json +15 -5
  65. package/theme/README.md +74 -0
  66. package/theme/base/_global.scss +2 -2
  67. package/theme/base/_reset.scss +11 -0
  68. package/theme/components/_app-shell.scss +0 -8
  69. package/theme/components/_form.scss +6 -6
  70. package/theme/components/_ln-table.scss +6 -3
  71. package/theme/components/_scrollbar.scss +5 -4
  72. package/theme/components/_sortable.scss +19 -19
  73. package/theme/components/_stat-card.scss +1 -0
  74. package/theme/components/_table.scss +11 -35
  75. package/theme/config/_density.scss +110 -65
  76. package/theme/config/_palette.scss +71 -49
  77. package/theme/config/_theme.scss +27 -31
  78. package/theme/config/_tokens.scss +28 -26
  79. package/theme/config/mixins/_app-shell.scss +17 -21
  80. package/theme/config/mixins/_avatar.scss +2 -2
  81. package/theme/config/mixins/_btn.scss +4 -2
  82. package/theme/config/mixins/_card.scss +88 -71
  83. package/theme/config/mixins/_colors.scss +2 -1
  84. package/theme/config/mixins/_display.scss +12 -0
  85. package/theme/config/mixins/_footer.scss +3 -1
  86. package/theme/config/mixins/_form.scss +74 -55
  87. package/theme/config/mixins/_layout.scss +9 -0
  88. package/theme/config/mixins/_ln-table.scss +22 -15
  89. package/theme/config/mixins/_modal.scss +3 -0
  90. package/theme/config/mixins/_nav.scss +31 -8
  91. package/theme/config/mixins/_sidebar.scss +2 -1
  92. package/theme/config/mixins/_spacing.scss +4 -4
  93. package/theme/config/mixins/_stat-card.scss +33 -2
  94. package/theme/config/mixins/_status-badge.scss +1 -0
  95. package/theme/config/mixins/_table.scss +87 -69
  96. package/theme/config/mixins/_tabs.scss +31 -0
  97. package/theme/config/mixins/_toast.scss +0 -1
  98. package/theme/designs/relaxed/_card.scss +12 -0
  99. package/theme/designs/relaxed/_layout.scss +24 -0
  100. package/theme/ln-ashlar-core.scss +1 -0
  101. package/theme/ln-ashlar-dev.scss +0 -1
  102. package/theme/ln-ashlar-relaxed.scss +67 -0
  103. package/theme/tailwind/components.css +2198 -0
  104. package/theme/tailwind/entry.css +3 -0
  105. package/theme/tailwind/theme.css +23 -0
  106. package/theme/utilities/_utilities.scss +1 -11
  107. package/web-types.json +2351 -2337
  108. package/components/ln-progress/ln-progress-dev.scss +0 -8
@@ -1,432 +1,457 @@
1
- import { registerComponent, dispatch, serializeForm, resolveFormMethod, createBatcher, attrSpec, defineAttrs, uuid } from '../../ln-core';
2
- import { normalizeDataQuery, selectDataSource, composeQuery } from './data-read-policy';
3
- import { MutationReceipts } from './mutation-receipts';
4
-
5
- (function () {
6
- const DOM_SELECTOR = 'data-ln-data-coordinator';
7
- const DOM_ATTRIBUTE = 'lnDataCoordinator';
8
- const SCOPE_ATTR = 'data-ln-data-coordinator-scope';
9
-
10
- if (window[DOM_ATTRIBUTE] !== undefined) return;
11
-
12
- const SEARCH_ATTR = 'data-ln-data-coordinator-search';
13
- const FILTERS_ATTR = 'data-ln-data-coordinator-filters';
14
- const SORT_FIELD_ATTR = 'data-ln-data-coordinator-sort-field';
15
- const SORT_DIR_ATTR = 'data-ln-data-coordinator-sort-direction';
16
-
17
- const ATTRIBUTES = {
18
- 'data-ln-data-coordinator': { prop: '_name', type: 'string', description: 'Coordinator name or identifier for data routing' },
19
- 'data-ln-data-coordinator-scope': { type: 'string', description: 'Scope name addressing the bound data store and connector' },
20
- 'data-ln-data-coordinator-connector': { type: 'string', description: 'Selector, identifier, or namespace of the bound connector' },
21
- 'data-ln-data-coordinator-mapper': { type: 'string', description: 'Name of the registered data mapper transform' },
22
- 'data-ln-data-coordinator-search': { prop: '_searchAttr', type: 'string', description: 'Active search query term' },
23
- 'data-ln-data-coordinator-filters': { prop: '_filtersAttr', type: 'string', description: 'Active encoded filter parameters' },
24
- 'data-ln-data-coordinator-sort-field': { prop: '_sortFieldAttr', type: 'string', description: 'Sort field name' },
25
- 'data-ln-data-coordinator-sort-direction': { prop: '_sortDirAttr', type: 'enum', values: ['asc', 'desc'], fallback: 'asc', description: 'Sort direction' },
26
- 'data-ln-data-coordinator-stale': { type: 'marker', description: 'Flag indicating data needs re-synchronization' },
27
- 'data-ln-data-coordinator-no-autosync': { type: 'boolean', description: 'Disables automatic synchronization upon state changes' }
28
- };
29
-
30
- const ATTR_SPEC = attrSpec(ATTRIBUTES);
31
- const VIEW_TARGETS = [
32
- ['[data-ln-table-source]', 'data-ln-table-source', 'table'],
33
- ['[data-ln-list-source]', 'data-ln-list-source', 'list'],
34
- ['[data-ln-chart-source]', 'data-ln-chart-source', 'chart'],
35
- ['[data-ln-options]', 'data-ln-options', 'options'],
36
- ['[data-ln-stat]', 'data-ln-stat', 'stat']
37
- ];
38
-
39
- function _findConnectorEl(dom) {
40
- const target = dom.getAttribute('data-ln-data-coordinator-connector');
41
- if (target) return dom.querySelector(target) || document.querySelector(target) || document.getElementById(target);
42
- const standard = dom.querySelector('[data-ln-connector], [data-ln-api-connector], [data-ln-couchdb-connector], [data-ln-websocket-connector]');
43
- if (standard) return standard;
44
- for (const el of dom.querySelectorAll('*')) {
45
- if (el.lnConnector) return el;
46
- for (const a of el.attributes) if (a.name.startsWith('data-ln-') && a.name.endsWith('-connector')) return el;
47
- }
48
- return null;
49
- }
50
-
51
- function _connNs(el) {
52
- if (!el) return 'ln-connector';
53
- if (el.lnConnector?.namespace) return el.lnConnector.namespace;
54
- const exp = el.getAttribute('data-ln-connector');
55
- if (exp && exp !== 'true') return exp.startsWith('ln-') ? exp : ('ln-' + exp + (exp.endsWith('-connector') ? '' : '-connector'));
56
- for (const a of el.attributes) if (a.name.startsWith('data-ln-') && a.name.endsWith('-connector')) return a.name.replace(/^data-/, '');
57
- return 'ln-connector';
58
- }
59
-
60
- // ─── Component Constructor ─────────────────────────────
61
- function _component(dom) {
62
- const self = this;
63
- this.dom = dom;
64
- defineAttrs(this, dom, ATTR_SPEC);
65
- if (!this._name) console.warn('[ln-data-coordinator] missing id — the coordinator cannot be addressed', dom);
66
- dom[DOM_ATTRIBUTE] = this;
67
-
68
- this._destroyed = false;
69
- this.mapper = null;
70
- this._unsubs = [];
71
- this._boundQueries = new WeakMap();
72
- this._boundDelivered = new WeakMap();
73
- this._mutationReceipts = new MutationReceipts();
74
-
75
- this._queueQueryRefresh = createBatcher(() => { if (!self._destroyed) self._refreshAll(null, true); });
76
- this.refreshMapper();
77
- _bindEvents(this);
78
- this._checkInitialSync();
79
- return this;
80
- }
81
-
82
- _component.prototype._noAutosync = function (c) {
83
- return this.dom.hasAttribute('data-ln-data-coordinator-no-autosync') || !!(c.storeEl?.hasAttribute('data-ln-data-store-no-autosync'));
84
- };
85
-
86
- _component.prototype._isStale = function (c) {
87
- const s = this.dom.getAttribute('data-ln-data-coordinator-stale') || c.storeEl?.getAttribute('data-ln-data-store-stale');
88
- if (s === 'never' || s === '-1') return false;
89
- return !c.store?.lastSyncedAt || ((Date.now() / 1000) - c.store.lastSyncedAt) > (parseInt(s, 10) || 300);
90
- };
91
-
92
- _component.prototype._checkInitialSync = function () {
93
- const self = this, c = this.findChildren();
94
- if (!c.store) return;
95
- Promise.resolve(c.store.ready).then(() => {
96
- if (self._destroyed) return;
97
- const cur = self.findChildren();
98
- if (cur.store && cur.connector && !self._noAutosync(cur) && !cur.store.isSyncing && (!cur.store.hasCache || self._isStale(cur))) {
99
- cur.store.forceSync();
100
- }
101
- }).catch(err => self._reportError('store-initialize', err, null));
102
- };
103
-
104
- _component.prototype.refreshMapper = function () {
105
- const name = this.dom.getAttribute('data-ln-data-coordinator-mapper') || this.dom.id;
106
- const m = (name && window.lnCore?.getDataMapper?.(name)) || null;
107
- this.mapper = { ingress: m?.ingress || (r => r), egress: m?.egress || (r => r) };
108
- };
109
-
110
- _component.prototype.findChildren = function () {
111
- const s = this.dom.querySelector('[data-ln-data-store]'), c = _findConnectorEl(this.dom), q = this.dom.querySelector('[data-ln-api-queue]');
112
- return { storeEl: s, connectorEl: c, queueEl: q, store: s?.lnDataStore || null, connector: c?.lnConnector || c?.lnApiConnector || c?.lnCouchDbConnector || c?.lnWebsocketConnector || null, queue: q?.lnApiQueue || null };
113
- };
114
-
115
- // ─── CRUD Intake & Fan-Out ───────────────────────────────
116
- _component.prototype._fanOutRemote = function (c, op, qPayload, cPayload) {
117
- this.refreshMapper();
118
- if (c.queue) dispatch(c.queueEl, 'ln-api-queue:request-enqueue', qPayload);
119
- else if (c.connector) dispatch(c.connectorEl, _connNs(c.connectorEl) + ':request-' + op, cPayload);
120
- };
121
-
122
- _component.prototype._fanOutCreate = function (c, data, action) {
123
- const tempId = '_temp_' + uuid(), payload = this.mapper.egress(data);
124
- if (c.storeEl) dispatch(c.storeEl, 'ln-data-store:request-create', { tempId, data: payload });
125
- this._fanOutRemote(c, 'create', { chainKey: tempId, op: 'create', targetId: null, payload, expectedVersion: null, meta: { tempId, action } }, { data: payload, url: action, meta: { entryId: uuid(), queued: false, op: 'create', tempId } });
126
- };
127
-
128
- _component.prototype._fanOutUpdate = function (c, id, data, v, action) {
129
- const payload = this.mapper.egress(data);
130
- if (c.storeEl) dispatch(c.storeEl, 'ln-data-store:request-update', { id, data: payload });
131
- this._fanOutRemote(c, 'update', { chainKey: id, op: 'update', targetId: id, payload, expectedVersion: v, meta: { id, action } }, { id, data: payload, expected_version: v, url: action, meta: { entryId: uuid(), queued: false, op: 'update', id } });
132
- };
133
-
134
- _component.prototype._fanOutDelete = function (c, id) {
135
- if (c.storeEl) dispatch(c.storeEl, 'ln-data-store:request-delete', { id });
136
- this._fanOutRemote(c, 'delete', { chainKey: id, op: 'delete', targetId: id, payload: null, expectedVersion: null, meta: { id } }, { id, meta: { entryId: uuid(), queued: false, op: 'delete', id } });
137
- };
138
-
139
- _component.prototype._fanOutBulkDelete = function (c, ids) {
140
- const bulkKey = ids.join(',');
141
- if (c.storeEl) dispatch(c.storeEl, 'ln-data-store:request-bulk-delete', { ids });
142
- this._fanOutRemote(c, 'bulk-delete', { chainKey: bulkKey, op: 'bulk-delete', targetId: null, payload: { ids }, expectedVersion: null, meta: { bulkKey, ids } }, { ids, meta: { entryId: uuid(), queued: false, op: 'bulk-delete', bulkKey } });
143
- };
144
-
145
- _component.prototype._requestStoreMutation = function (c, action, detail) {
146
- if (!c.storeEl) return Promise.reject(new Error('Store element not found'));
147
- const requestId = uuid(), receipt = this._mutationReceipts.wait(requestId);
148
- dispatch(c.storeEl, 'ln-data-store:request-' + action, Object.assign({}, detail, { requestId }));
149
- return receipt;
150
- };
151
-
152
- _component.prototype._reportError = function (operation, error, meta) {
153
- if (!this._destroyed) dispatch(this.dom, 'ln-data-coordinator:error', { operation, error, meta: meta || null });
154
- };
155
-
156
- // ─── Query State & View Serving ──────────────────────────
157
- _component.prototype._owns = function (name) {
158
- const target = this._name || this.findChildren().storeEl?.id;
159
- return !!name && name === target;
160
- };
161
-
162
- _component.prototype._currentQuery = function () {
163
- const field = this.dom.getAttribute(SORT_FIELD_ATTR), direction = this.dom.getAttribute(SORT_DIR_ATTR);
164
- const params = new URLSearchParams(this.dom.getAttribute(FILTERS_ATTR) || ''), filters = {};
165
- for (const key of new Set(params.keys())) filters[key] = params.getAll(key);
166
- return { search: this.dom.getAttribute(SEARCH_ATTR) || '', filters, sort: (field && direction) ? { field, direction } : null };
167
- };
168
-
169
- _component.prototype._refreshAll = function (syncMeta, isQueryChange) {
170
- for (const [sel, attr, kind] of VIEW_TARGETS) {
171
- for (const el of this.dom.ownerDocument.querySelectorAll(sel)) {
172
- if (!this._owns(el.getAttribute(attr))) continue;
173
- if ((kind === 'table' || kind === 'list') && el.hasAttribute(kind === 'table' ? 'data-ln-table-window' : 'data-ln-list-window')) {
174
- dispatch(el, 'ln-' + kind + (isQueryChange ? ':request-invalidate' : ':request-revalidate'), { query: this._currentQuery() });
175
- continue;
176
- }
177
- this._serveElement(el, kind, null, syncMeta);
178
- }
179
- }
180
- };
181
-
182
- _component.prototype._serveElement = function (el, kind, reqQuery, syncMeta) {
183
- const c = this.findChildren(), store = c.store;
184
- if (!store) return;
185
- if (reqQuery) this._boundQueries.set(el, reqQuery);
186
- const cached = this._boundQueries.get(el) || { sort: null, filters: {}, search: '' };
187
- const effective = composeQuery(cached, this._currentQuery());
188
-
189
- const self = this;
190
- return Promise.resolve(store.ready).then(() => {
191
- if (self._destroyed) return;
192
- const source = selectDataSource(store, c.connector);
193
- if (kind === 'table' || kind === 'list' || kind === 'chart') {
194
- if (source === 'remote') {
195
- dispatch(el, 'ln-' + kind + ':set-loading', { loading: true });
196
- return dispatch(c.connectorEl, _connNs(c.connectorEl) + ':request-query', { query: effective, meta: { targetEl: el, kind, offset: effective.offset, limit: effective.limit, queryGen: cached.queryGen } });
197
- }
198
- if (source !== 'store') return dispatch(el, 'ln-' + kind + ':set-loading', { loading: false });
199
- return store.getAll(effective).then(r => {
200
- if (self._destroyed || !self._boundDelivered) return;
201
- dispatch(el, 'ln-' + kind + ':set-loading', { loading: false });
202
- dispatch(el, 'ln-' + kind + ':set-data', { data: r.data, total: syncMeta?.total ?? r.total, filtered: syncMeta?.filtered ?? r.filtered, offset: r.offset ?? syncMeta?.offset ?? cached.offset, queryGen: cached.queryGen !== undefined ? cached.queryGen : (syncMeta?.queryGen ?? r.queryGen), provisional: r.provisional === true });
203
- self._boundDelivered.set(el, true);
204
- });
205
- }
206
- if (kind === 'options') {
207
- if (source === 'remote') return dispatch(c.connectorEl, _connNs(c.connectorEl) + ':request-query', { query: {}, meta: { targetEl: el, kind } });
208
- if (source === 'store') return store.getAll({}).then(r => !self._destroyed && dispatch(el, 'ln-options:set-data', { data: r.data }));
209
- }
210
- if (kind === 'stat') {
211
- let filters = reqQuery?.filters;
212
- if (!filters) {
213
- const raw = el.getAttribute('data-ln-stat-filter');
214
- if (raw?.includes(':')) { const p = raw.split(':'); filters = { [p[0].trim()]: [p.slice(1).join(':').trim()] }; }
215
- }
216
- const statSource = (c.connector && store && ((store.windowed && filters && Object.keys(filters).length) || store.noLocalQuery)) ? 'remote' : source;
217
- if (statSource === 'remote') return dispatch(c.connectorEl, _connNs(c.connectorEl) + ':request-query', { query: { filters }, meta: { targetEl: el, kind } });
218
- if (statSource === 'store') return store.count(filters).then(n => !self._destroyed && dispatch(el, 'ln-stat:set-count', { count: n }));
219
- }
220
- }).catch(err => {
221
- if (self._destroyed) return;
222
- if (kind === 'table' || kind === 'list' || kind === 'chart') dispatch(el, 'ln-' + kind + ':set-loading', { loading: false });
223
- self._reportError(kind + '-query', err, { targetEl: el, kind });
224
- });
225
- };
226
-
227
- // ─── Event Binding & Handlers ─────────────────────────────
228
- function _bindEvents(self) {
229
- const unsubs = self._unsubs = [];
230
- const addEventListener = (target, type, fn) => { target.addEventListener(type, fn); unsubs.push(() => target.removeEventListener(type, fn)); };
231
-
232
- addEventListener(self.dom, 'ln-data-store:request-remote-sync', e => {
233
- self.refreshMapper();
234
- const c = self.findChildren();
235
- if (c.store && c.connector) dispatch(c.connectorEl, _connNs(c.connectorEl) + ':request-sync', { since: e.detail.since, meta: { op: 'sync' } });
236
- });
237
-
238
- addEventListener(self.dom, 'ln-data-store:request-page', e => {
239
- const c = self.findChildren(), d = e.detail || {};
240
- if (!c.connectorEl) return;
241
- const effective = composeQuery(d.query || {}, self._currentQuery());
242
- dispatch(c.connectorEl, _connNs(c.connectorEl) + ':request-query', {
243
- query: Object.assign({}, effective, { offset: d.offset, limit: d.limit, queryGen: d.queryGen })
244
- });
245
- });
246
-
247
- addEventListener(self.dom, 'ln-data-coordinator:request-create', e => self._fanOutCreate(self.findChildren(), e.detail.data || {}, e.detail.action));
248
- addEventListener(self.dom, 'ln-data-coordinator:request-update', e => self._fanOutUpdate(self.findChildren(), e.detail.id, e.detail.data || {}, e.detail.expected_version, e.detail.action));
249
- addEventListener(self.dom, 'ln-data-coordinator:request-delete', e => self._fanOutDelete(self.findChildren(), e.detail.id));
250
- addEventListener(self.dom, 'ln-data-coordinator:request-bulk-delete', e => self._fanOutBulkDelete(self.findChildren(), e.detail.ids || []));
251
- addEventListener(self.dom, 'ln-api-queue:send', e => self._onQueueSend(e.detail || {}));
252
- addEventListener(self.dom, 'ln-api-queue:failed', e => self._reportError('queue-failed', e?.detail?.error || new Error('Queue failed'), e?.detail || null));
253
-
254
- addEventListener(self.dom, 'ln-data-store:initialized', e => {
255
- const c = self.findChildren();
256
- if (c.store && !c.store.initializationError && c.connector && !self._noAutosync(c) && !c.store.isSyncing && (!e.detail?.hasCache || self._isStale(c))) c.store.forceSync();
257
- });
258
-
259
- const onConnected = () => {
260
- const c = self.findChildren();
261
- if (c.store && !c.store.initializationError && c.connector && !self._noAutosync(c) && c.store.isInitialized && !c.store.isSyncing) c.store.forceSync();
262
- };
263
- addEventListener(self.dom, 'ln-websocket-connector:connected', onConnected);
264
-
265
- addEventListener(document, 'submit', e => self._onFormSubmit(e));
266
- const serve = (e, kind, attr) => {
267
- if (self._owns(e.target.getAttribute(attr))) self._serveElement(e.target, kind, kind === 'stat' ? { filters: e.detail?.filters || null } : (kind === 'options' ? null : normalizeDataQuery(e.detail || {})), null);
268
- };
269
- addEventListener(document, 'ln-table:request-data', e => serve(e, 'table', 'data-ln-table-source'));
270
- addEventListener(document, 'ln-list:request-data', e => serve(e, 'list', 'data-ln-list-source'));
271
- addEventListener(document, 'ln-chart:request-data', e => serve(e, 'chart', 'data-ln-chart-source'));
272
- addEventListener(document, 'ln-options:request-data', e => serve(e, 'options', 'data-ln-options'));
273
- addEventListener(document, 'ln-stat:request-count', e => serve(e, 'stat', 'data-ln-stat'));
274
-
275
- const refresh = e => { self._mutationReceipts.resolve(e.detail); self._refreshAll(null, false); };
276
- addEventListener(self.dom, 'ln-data-store:ready', refresh);
277
- addEventListener(self.dom, 'ln-data-store:created', refresh);
278
- addEventListener(self.dom, 'ln-data-store:updated', refresh);
279
- addEventListener(self.dom, 'ln-data-store:deleted', refresh);
280
- addEventListener(self.dom, 'ln-data-store:mutation-error', e => self._mutationReceipts.reject(e.detail));
281
- addEventListener(self.dom, 'ln-data-store:synced', e => { if (e.detail?.changed) self._refreshAll(e.detail.meta, false); });
282
- addEventListener(self.dom, 'ln-data-store:query-changed', () => self._refreshAll(null, true));
283
-
284
- addEventListener(self.dom, 'ln-search:change', e => {
285
- e.preventDefault();
286
- const term = e.detail?.term != null ? e.detail.term : '';
287
- if (term !== (self.dom.getAttribute(SEARCH_ATTR) || '')) self.dom.setAttribute(SEARCH_ATTR, term);
288
- });
289
-
290
- addEventListener(self.dom, 'ln-filter:change', e => {
291
- e.preventDefault();
292
- const key = e.detail?.key;
293
- if (!key) return;
294
- const values = (e.detail.values || []).slice(), filters = self._currentQuery().filters, prev = filters[key];
295
- if (prev ? (prev.length === values.length && prev.every((v, i) => v === values[i])) : !values.length) return;
296
- if (values.length) filters[key] = values; else delete filters[key];
297
- const p = new URLSearchParams();
298
- Object.keys(filters).forEach(k => filters[k].forEach(v => p.append(k, v)));
299
- const next = p.toString();
300
- if (next) self.dom.setAttribute(FILTERS_ATTR, next); else self.dom.removeAttribute(FILTERS_ATTR);
301
- });
302
-
303
- addEventListener(self.dom, 'ln-sort:change', e => {
304
- e.preventDefault();
305
- const f = e.detail?.field, d = e.detail?.direction;
306
- const next = (f && d && d !== 'none') ? { field: f, direction: d } : null, prev = self._currentQuery().sort;
307
- if ((!prev && !next) || (prev && next && prev.field === next.field && prev.direction === next.direction)) return;
308
- if (next) { self.dom.setAttribute(SORT_FIELD_ATTR, next.field); self.dom.setAttribute(SORT_DIR_ATTR, next.direction); }
309
- else { self.dom.removeAttribute(SORT_FIELD_ATTR); self.dom.removeAttribute(SORT_DIR_ATTR); }
310
- });
311
-
312
- const connNamespaces = new Set(['ln-api-connector', 'ln-couchdb-connector', 'ln-websocket-connector', 'ln-connector']);
313
- const childConn = self.findChildren().connectorEl;
314
- if (childConn) { const customNs = _connNs(childConn); connNamespaces.add(customNs); addEventListener(self.dom, customNs + ':connected', onConnected); }
315
- connNamespaces.forEach(ns => {
316
- addEventListener(self.dom, ns + ':fetched', e => self._reconcileServerFetch(e.detail));
317
- addEventListener(self.dom, ns + ':created', e => self._reconcileServerMutation('create', e.detail));
318
- addEventListener(self.dom, ns + ':updated', e => self._reconcileServerMutation('update', e.detail));
319
- addEventListener(self.dom, ns + ':deleted', e => self._reconcileServerMutation('ack', e.detail));
320
- addEventListener(self.dom, ns + ':bulk-deleted', e => self._reconcileServerMutation('ack', e.detail));
321
- addEventListener(self.dom, ns + ':error', e => self._reconcileServerMutation('error', e.detail));
322
- });
323
- }
324
-
325
- _component.prototype._onQueueSend = function (d) {
326
- this.refreshMapper();
327
- const c = this.findChildren();
328
- if (!c.store || !c.connector || !c.queue) return;
329
- const m = d.meta || {}, ns = _connNs(c.connectorEl), key = d.idempotencyKey || d.entryId;
330
- const actions = {
331
- create: () => dispatch(c.connectorEl, ns + ':request-create', { data: d.payload, url: m.action || null, idempotencyKey: key, meta: { entryId: d.entryId, queued: true, op: 'create', tempId: m.tempId } }),
332
- update: () => dispatch(c.connectorEl, ns + ':request-update', { id: d.targetId, data: d.payload, expected_version: d.expectedVersion, url: m.action || null, idempotencyKey: key, meta: { entryId: d.entryId, queued: true, op: 'update', id: d.targetId } }),
333
- delete: () => dispatch(c.connectorEl, ns + ':request-delete', { id: d.targetId, idempotencyKey: key, meta: { entryId: d.entryId, queued: true, op: 'delete', id: d.targetId } }),
334
- 'bulk-delete': () => dispatch(c.connectorEl, ns + ':request-bulk-delete', { ids: d.payload?.ids || [], idempotencyKey: key, meta: { entryId: d.entryId, queued: true, op: 'bulk-delete', bulkKey: m.bulkKey } })
335
- };
336
- if (actions[d.op]) actions[d.op]();
337
- };
338
-
339
- _component.prototype._onFormSubmit = function (e) {
340
- const form = e.target;
341
- if (e.defaultPrevented) return;
342
- const scope = form.hasAttribute(SCOPE_ATTR) ? form.getAttribute(SCOPE_ATTR) : null;
343
- if (scope === null || (scope ? !this._owns(scope) : form.closest('[' + DOM_SELECTOR + ']') !== this.dom)) return;
344
- const method = resolveFormMethod(form);
345
- if (method !== 'POST' && method !== 'PUT' && method !== 'PATCH') return;
346
- e.preventDefault();
347
- const raw = serializeForm(form);
348
- delete raw._method; delete raw._token;
349
- const id = raw.id, v = raw.expected_version, action = form.getAttribute('action') || '', c = this.findChildren();
350
- delete raw.id; delete raw.expected_version;
351
- if (method === 'POST') this._fanOutCreate(c, raw, action);
352
- else this._fanOutUpdate(c, id, raw, v, action);
353
- };
354
-
355
- _component.prototype._reconcileServerFetch = function (d) {
356
- if (!d) return;
357
- const meta = d.meta || {}, c = this.findChildren(), raw = d.data;
358
- this.refreshMapper();
359
- const fetched = Array.isArray(raw) ? raw : (raw?.data || []);
360
- const deleted = Array.isArray(raw?.deleted) ? raw.deleted : [];
361
- const syncedAt = Array.isArray(raw) ? Math.floor(Date.now() / 1000) : (raw?.synced_at ?? raw?.since ?? Math.floor(Date.now() / 1000));
362
- const records = fetched.map(r => this.mapper.ingress(r));
363
- if (!c.store || c.store.initializationError) return;
364
-
365
- if (!meta.kind) return c.store.applySync(records, deleted, syncedAt, { total: d.total, filtered: d.filtered, offset: d.offset, queryGen: d.queryGen, targetEl: meta.targetEl });
366
- c.store.applyQuery(records, { total: d.total }).then(dec => {
367
- const k = meta.kind;
368
- if (k === 'table' || k === 'list' || k === 'chart') {
369
- dispatch(meta.targetEl, 'ln-' + k + ':set-loading', { loading: false });
370
- dispatch(meta.targetEl, 'ln-' + k + ':set-data', { data: dec, total: d.total ?? dec.length, filtered: d.filtered ?? dec.length, offset: d.offset, queryGen: meta.queryGen });
371
- this._boundDelivered.set(meta.targetEl, true);
372
- } else if (k === 'options') {
373
- c.store.getAll({}).then(r => dispatch(meta.targetEl, 'ln-options:set-data', { data: r.data }));
374
- } else if (k === 'stat') {
375
- dispatch(meta.targetEl, 'ln-stat:set-count', { count: d.filtered ?? d.total ?? records.length });
376
- }
377
- });
378
- };
379
-
380
- _component.prototype._reconcileServerMutation = function (type, d) {
381
- if (!d) return;
382
- const c = this.findChildren(), meta = d.meta || {};
383
- if (type === 'create') {
384
- if (!d.record) return this._reportError('create-empty-response', new Error('Create response missing record payload'), meta);
385
- const rec = this.mapper.ingress(d.record);
386
- (c.storeEl ? this._requestStoreMutation(c, 'update', { id: meta.tempId, data: rec }) : Promise.resolve()).then(() => {
387
- if (meta.queued && c.queue) dispatch(c.queueEl, 'ln-api-queue:resolve-create', { entryId: meta.entryId, oldKey: meta.tempId, newId: rec.id });
388
- }).catch(err => this._reportError('create-reconcile', err, meta));
389
- } else if (type === 'update') {
390
- const rec = d.record ? this.mapper.ingress(d.record) : null;
391
- (c.storeEl && rec ? this._requestStoreMutation(c, 'update', { id: meta.id, data: rec }) : Promise.resolve()).then(() => {
392
- if (meta.queued && c.queue) dispatch(c.queueEl, 'ln-api-queue:ack', { entryId: meta.entryId });
393
- }).catch(err => this._reportError('update-reconcile', err, meta));
394
- } else if (type === 'ack') {
395
- if (meta.queued && c.queue) dispatch(c.queueEl, 'ln-api-queue:ack', { entryId: meta.entryId });
396
- } else if (type === 'error') {
397
- const status = d.status || d.error?.status || 0;
398
- if (meta.queued && c.queue) {
399
- dispatch(c.queueEl, 'ln-api-queue:nack', { entryId: meta.entryId, reason: (status === 401 || status === 419) ? 'auth' : ((status === 0 || status >= 500) ? 'retry' : 'drop') });
400
- }
401
- if (c.storeEl) {
402
- dispatch(c.storeEl, 'ln-data-store:request-sync-failed', { error: d.error || d, status });
403
- }
404
- this._reportError('connector-error', d.error || d, meta);
405
- }
406
- };
407
-
408
- // ─── Destroy and Cleanup ──────────────────────────────────
409
- _component.prototype.destroy = function () {
410
- if (!this.dom[DOM_ATTRIBUTE]) return;
411
- this._destroyed = true;
412
- while (this._unsubs?.length) this._unsubs.pop()();
413
- this._unsubs = this._boundQueries = this._boundDelivered = this._queueQueryRefresh = null;
414
- this._mutationReceipts.close(new Error('Data coordinator destroyed'));
415
- this._mutationReceipts = null;
416
- delete this.dom[DOM_ATTRIBUTE];
417
- };
418
-
419
- function _syncAttribute(el, attrName) {
420
- const inst = el[DOM_ATTRIBUTE];
421
- if (!inst) return;
422
- if (attrName === 'data-ln-data-coordinator-mapper') inst.refreshMapper();
423
- else if (attrName === SEARCH_ATTR || attrName === FILTERS_ATTR || attrName === SORT_FIELD_ATTR || attrName === SORT_DIR_ATTR) inst._queueQueryRefresh();
424
- }
425
-
426
- registerComponent(DOM_SELECTOR, DOM_ATTRIBUTE, _component, 'ln-data-coordinator', {
427
- extraAttributes: ['data-ln-data-coordinator-mapper', SEARCH_ATTR, FILTERS_ATTR, SORT_FIELD_ATTR, SORT_DIR_ATTR],
428
- onAttributeChange: _syncAttribute
429
- });
430
-
431
- window[DOM_ATTRIBUTE].init = window[DOM_ATTRIBUTE];
432
- })();
1
+ import { registerComponent, dispatch, serializeForm, resolveFormMethod, createBatcher, attrSpec, defineAttrs, uuid } from '../../ln-core';
2
+ import { normalizeDataQuery, selectDataSource, composeQuery } from './data-read-policy';
3
+ import { MutationReceipts } from './mutation-receipts';
4
+
5
+ (function () {
6
+ const DOM_SELECTOR = 'data-ln-data-coordinator';
7
+ const DOM_ATTRIBUTE = 'lnDataCoordinator';
8
+ const SCOPE_ATTR = 'data-ln-data-coordinator-scope';
9
+
10
+ if (window[DOM_ATTRIBUTE] !== undefined) return;
11
+
12
+ const SEARCH_ATTR = 'data-ln-data-coordinator-search';
13
+ const FILTERS_ATTR = 'data-ln-data-coordinator-filters';
14
+ const SORT_FIELD_ATTR = 'data-ln-data-coordinator-sort-field';
15
+ const SORT_DIR_ATTR = 'data-ln-data-coordinator-sort-direction';
16
+
17
+ const ATTRIBUTES = {
18
+ 'data-ln-data-coordinator': { prop: '_name', type: 'string', description: 'Coordinator name or identifier for data routing' },
19
+ 'data-ln-data-coordinator-scope': { type: 'string', description: 'Scope name addressing the bound data store and connector' },
20
+ 'data-ln-data-coordinator-connector': { type: 'string', description: 'Selector, identifier, or namespace of the bound connector' },
21
+ 'data-ln-data-coordinator-mapper': { type: 'string', description: 'Name of the registered data mapper transform' },
22
+ 'data-ln-data-coordinator-search': { prop: '_searchAttr', type: 'string', description: 'Active search query term' },
23
+ 'data-ln-data-coordinator-filters': { prop: '_filtersAttr', type: 'string', description: 'Active encoded filter parameters' },
24
+ 'data-ln-data-coordinator-sort-field': { prop: '_sortFieldAttr', type: 'string', description: 'Sort field name' },
25
+ 'data-ln-data-coordinator-sort-direction': { prop: '_sortDirAttr', type: 'enum', values: ['asc', 'desc'], fallback: 'asc', description: 'Sort direction' },
26
+ 'data-ln-data-coordinator-stale': { type: 'marker', description: 'Flag indicating data needs re-synchronization' },
27
+ 'data-ln-data-coordinator-no-autosync': { type: 'boolean', description: 'Disables automatic synchronization upon state changes' }
28
+ };
29
+
30
+ const ATTR_SPEC = attrSpec(ATTRIBUTES);
31
+ const VIEW_TARGETS = [
32
+ ['[data-ln-table-source]', 'data-ln-table-source', 'table'],
33
+ ['[data-ln-list-source]', 'data-ln-list-source', 'list'],
34
+ ['[data-ln-chart-source]', 'data-ln-chart-source', 'chart'],
35
+ ['[data-ln-options]', 'data-ln-options', 'options'],
36
+ ['[data-ln-stat]', 'data-ln-stat', 'stat']
37
+ ];
38
+
39
+ function _findConnectorEl(dom) {
40
+ const target = dom.getAttribute('data-ln-data-coordinator-connector');
41
+ if (target) return dom.querySelector(target) || document.querySelector(target) || document.getElementById(target);
42
+ const standard = dom.querySelector('[data-ln-connector], [data-ln-api-connector], [data-ln-couchdb-connector], [data-ln-websocket-connector]');
43
+ if (standard) return standard;
44
+ for (const el of dom.querySelectorAll('*')) {
45
+ if (el.lnConnector) return el;
46
+ for (const a of el.attributes) if (a.name.startsWith('data-ln-') && a.name.endsWith('-connector')) return el;
47
+ }
48
+ return null;
49
+ }
50
+
51
+ function _connNs(el) {
52
+ if (!el) return 'ln-connector';
53
+ if (el.lnConnector?.namespace) return el.lnConnector.namespace;
54
+ const exp = el.getAttribute('data-ln-connector');
55
+ if (exp && exp !== 'true') return exp.startsWith('ln-') ? exp : ('ln-' + exp + (exp.endsWith('-connector') ? '' : '-connector'));
56
+ for (const a of el.attributes) if (a.name.startsWith('data-ln-') && a.name.endsWith('-connector')) return a.name.replace(/^data-/, '');
57
+ return 'ln-connector';
58
+ }
59
+
60
+ // ─── Component Constructor ─────────────────────────────
61
+ function _component(dom) {
62
+ const self = this;
63
+ this.dom = dom;
64
+ defineAttrs(this, dom, ATTR_SPEC);
65
+ if (!this._name) console.warn('[ln-data-coordinator] missing id — the coordinator cannot be addressed', dom);
66
+ dom[DOM_ATTRIBUTE] = this;
67
+
68
+ this._destroyed = false;
69
+ this.mapper = null;
70
+ this._unsubs = [];
71
+ this._boundQueries = new WeakMap();
72
+ this._boundDelivered = new WeakMap();
73
+ this._mutationReceipts = new MutationReceipts();
74
+
75
+ this._queueQueryRefresh = createBatcher(() => { if (!self._destroyed) self._refreshAll(null, true); });
76
+ this.refreshMapper();
77
+ _bindEvents(this);
78
+ this._checkInitialSync();
79
+ return this;
80
+ }
81
+
82
+ _component.prototype._noAutosync = function (c) {
83
+ return this.dom.hasAttribute('data-ln-data-coordinator-no-autosync') || !!(c.storeEl?.hasAttribute('data-ln-data-store-no-autosync'));
84
+ };
85
+
86
+ _component.prototype._isStale = function (c) {
87
+ const s = this.dom.getAttribute('data-ln-data-coordinator-stale') || c.storeEl?.getAttribute('data-ln-data-store-stale');
88
+ if (s === 'never' || s === '-1') return false;
89
+ return !c.store?.lastSyncedAt || ((Date.now() / 1000) - c.store.lastSyncedAt) > (parseInt(s, 10) || 300);
90
+ };
91
+
92
+ _component.prototype._checkInitialSync = function () {
93
+ const self = this, c = this.findChildren();
94
+ if (!c.store) return;
95
+ Promise.resolve(c.store.ready).then(() => {
96
+ if (self._destroyed) return;
97
+ const cur = self.findChildren();
98
+ if (cur.store && cur.connector && !self._noAutosync(cur) && !cur.store.isSyncing && (!cur.store.hasCache || self._isStale(cur))) {
99
+ cur.store.forceSync();
100
+ }
101
+ }).catch(err => self._reportError('store-initialize', err, null));
102
+ };
103
+
104
+ _component.prototype.refreshMapper = function () {
105
+ const name = this.dom.getAttribute('data-ln-data-coordinator-mapper') || this.dom.id;
106
+ const m = (name && window.lnCore?.getDataMapper?.(name)) || null;
107
+ this.mapper = { ingress: m?.ingress || (r => r), egress: m?.egress || (r => r) };
108
+ };
109
+
110
+ _component.prototype.findChildren = function () {
111
+ const s = this.dom.querySelector('[data-ln-data-store]'), c = _findConnectorEl(this.dom), q = this.dom.querySelector('[data-ln-api-queue]');
112
+ return { storeEl: s, connectorEl: c, queueEl: q, store: s?.lnDataStore || null, connector: c?.lnConnector || c?.lnApiConnector || c?.lnCouchDbConnector || c?.lnWebsocketConnector || null, queue: q?.lnApiQueue || null };
113
+ };
114
+
115
+ // ─── CRUD Intake & Fan-Out ───────────────────────────────
116
+ _component.prototype._fanOutRemote = function (c, op, qPayload, cPayload) {
117
+ this.refreshMapper();
118
+ if (c.queue) dispatch(c.queueEl, 'ln-api-queue:request-enqueue', qPayload);
119
+ else if (c.connector) dispatch(c.connectorEl, _connNs(c.connectorEl) + ':request-' + op, cPayload);
120
+ };
121
+
122
+ _component.prototype._fanOutCreate = function (c, data, action) {
123
+ const tempId = '_temp_' + uuid(), payload = this.mapper.egress(data);
124
+ if (c.storeEl) dispatch(c.storeEl, 'ln-data-store:request-create', { tempId, data: payload });
125
+ this._fanOutRemote(c, 'create', { chainKey: tempId, op: 'create', targetId: null, payload, expectedVersion: null, meta: { tempId, action } }, { data: payload, url: action, meta: { entryId: uuid(), queued: false, op: 'create', tempId } });
126
+ };
127
+
128
+ _component.prototype._fanOutUpdate = function (c, id, data, v, action) {
129
+ const self = this;
130
+ const apply = snapshot => {
131
+ const payload = self.mapper.egress(data);
132
+ if (c.storeEl) dispatch(c.storeEl, 'ln-data-store:request-update', { id, data: payload });
133
+ self._fanOutRemote(c, 'update', { chainKey: id, op: 'update', targetId: id, payload, expectedVersion: v, meta: { id, action, snapshot } }, { id, data: payload, expected_version: v, url: action, meta: { entryId: uuid(), queued: false, op: 'update', id, snapshot } });
134
+ };
135
+ if (c.store && typeof c.store.getById === 'function') {
136
+ c.store.getById(id).then(rec => apply(rec ? Object.assign({}, rec) : null)).catch(() => apply(null));
137
+ } else {
138
+ apply(null);
139
+ }
140
+ };
141
+
142
+ _component.prototype._fanOutDelete = function (c, id) {
143
+ const self = this;
144
+ const apply = snapshot => {
145
+ if (c.storeEl) dispatch(c.storeEl, 'ln-data-store:request-delete', { id });
146
+ self._fanOutRemote(c, 'delete', { chainKey: id, op: 'delete', targetId: id, payload: null, expectedVersion: null, meta: { id, snapshot } }, { id, meta: { entryId: uuid(), queued: false, op: 'delete', id, snapshot } });
147
+ };
148
+ if (c.store && typeof c.store.getById === 'function') {
149
+ c.store.getById(id).then(rec => apply(rec ? Object.assign({}, rec) : null)).catch(() => apply(null));
150
+ } else {
151
+ apply(null);
152
+ }
153
+ };
154
+
155
+ _component.prototype._fanOutBulkDelete = function (c, ids) {
156
+ const bulkKey = ids.join(',');
157
+ if (c.storeEl) dispatch(c.storeEl, 'ln-data-store:request-bulk-delete', { ids });
158
+ this._fanOutRemote(c, 'bulk-delete', { chainKey: bulkKey, op: 'bulk-delete', targetId: null, payload: { ids }, expectedVersion: null, meta: { bulkKey, ids } }, { ids, meta: { entryId: uuid(), queued: false, op: 'bulk-delete', bulkKey } });
159
+ };
160
+
161
+ _component.prototype._requestStoreMutation = function (c, action, detail) {
162
+ if (!c.storeEl) return Promise.reject(new Error('Store element not found'));
163
+ const requestId = uuid(), receipt = this._mutationReceipts.wait(requestId);
164
+ dispatch(c.storeEl, 'ln-data-store:request-' + action, Object.assign({}, detail, { requestId }));
165
+ return receipt;
166
+ };
167
+
168
+ _component.prototype._reportError = function (operation, error, meta) {
169
+ if (!this._destroyed) dispatch(this.dom, 'ln-data-coordinator:error', { operation, error, meta: meta || null });
170
+ };
171
+
172
+ // ─── Query State & View Serving ──────────────────────────
173
+ _component.prototype._owns = function (name) {
174
+ const target = this._name || this.findChildren().storeEl?.id;
175
+ return !!name && name === target;
176
+ };
177
+
178
+ _component.prototype._currentQuery = function () {
179
+ const field = this.dom.getAttribute(SORT_FIELD_ATTR), direction = this.dom.getAttribute(SORT_DIR_ATTR);
180
+ const params = new URLSearchParams(this.dom.getAttribute(FILTERS_ATTR) || ''), filters = {};
181
+ for (const key of new Set(params.keys())) filters[key] = params.getAll(key);
182
+ return { search: this.dom.getAttribute(SEARCH_ATTR) || '', filters, sort: (field && direction) ? { field, direction } : null };
183
+ };
184
+
185
+ _component.prototype._refreshAll = function (syncMeta, isQueryChange) {
186
+ for (const [sel, attr, kind] of VIEW_TARGETS) {
187
+ for (const el of this.dom.ownerDocument.querySelectorAll(sel)) {
188
+ if (!this._owns(el.getAttribute(attr))) continue;
189
+ if ((kind === 'table' || kind === 'list') && el.hasAttribute(kind === 'table' ? 'data-ln-table-window' : 'data-ln-list-window')) {
190
+ dispatch(el, 'ln-' + kind + (isQueryChange ? ':request-invalidate' : ':request-revalidate'), { query: this._currentQuery() });
191
+ continue;
192
+ }
193
+ this._serveElement(el, kind, null, syncMeta);
194
+ }
195
+ }
196
+ };
197
+
198
+ _component.prototype._serveElement = function (el, kind, reqQuery, syncMeta) {
199
+ const c = this.findChildren(), store = c.store;
200
+ if (!store) return;
201
+ if (reqQuery) this._boundQueries.set(el, reqQuery);
202
+ const cached = this._boundQueries.get(el) || { sort: null, filters: {}, search: '' };
203
+ const effective = composeQuery(cached, this._currentQuery());
204
+
205
+ const self = this;
206
+ return Promise.resolve(store.ready).then(() => {
207
+ if (self._destroyed) return;
208
+ const source = selectDataSource(store, c.connector);
209
+ if (kind === 'table' || kind === 'list' || kind === 'chart') {
210
+ if (source === 'remote') {
211
+ dispatch(el, 'ln-' + kind + ':set-loading', { loading: true });
212
+ return dispatch(c.connectorEl, _connNs(c.connectorEl) + ':request-query', { query: effective, meta: { targetEl: el, kind, offset: effective.offset, limit: effective.limit, queryGen: cached.queryGen } });
213
+ }
214
+ if (source !== 'store') return dispatch(el, 'ln-' + kind + ':set-loading', { loading: false });
215
+ return store.getAll(effective).then(r => {
216
+ if (self._destroyed || !self._boundDelivered) return;
217
+ dispatch(el, 'ln-' + kind + ':set-loading', { loading: false });
218
+ dispatch(el, 'ln-' + kind + ':set-data', { data: r.data, total: syncMeta?.total ?? r.total, filtered: syncMeta?.filtered ?? r.filtered, offset: r.offset ?? syncMeta?.offset ?? cached.offset, queryGen: cached.queryGen !== undefined ? cached.queryGen : (syncMeta?.queryGen ?? r.queryGen), provisional: r.provisional === true });
219
+ self._boundDelivered.set(el, true);
220
+ });
221
+ }
222
+ if (kind === 'options') {
223
+ if (source === 'remote') return dispatch(c.connectorEl, _connNs(c.connectorEl) + ':request-query', { query: {}, meta: { targetEl: el, kind } });
224
+ if (source === 'store') return store.getAll({}).then(r => !self._destroyed && dispatch(el, 'ln-options:set-data', { data: r.data }));
225
+ }
226
+ if (kind === 'stat') {
227
+ let filters = reqQuery?.filters;
228
+ if (!filters) {
229
+ const raw = el.getAttribute('data-ln-stat-filter');
230
+ if (raw?.includes(':')) { const p = raw.split(':'); filters = { [p[0].trim()]: [p.slice(1).join(':').trim()] }; }
231
+ }
232
+ const statSource = (c.connector && store && ((store.windowed && filters && Object.keys(filters).length) || store.noLocalQuery)) ? 'remote' : source;
233
+ if (statSource === 'remote') return dispatch(c.connectorEl, _connNs(c.connectorEl) + ':request-query', { query: { filters }, meta: { targetEl: el, kind } });
234
+ if (statSource === 'store') return store.count(filters).then(n => !self._destroyed && dispatch(el, 'ln-stat:set-count', { count: n }));
235
+ }
236
+ }).catch(err => {
237
+ if (self._destroyed) return;
238
+ if (kind === 'table' || kind === 'list' || kind === 'chart') dispatch(el, 'ln-' + kind + ':set-loading', { loading: false });
239
+ self._reportError(kind + '-query', err, { targetEl: el, kind });
240
+ });
241
+ };
242
+
243
+ // ─── Event Binding & Handlers ─────────────────────────────
244
+ function _bindEvents(self) {
245
+ const unsubs = self._unsubs = [];
246
+ const addEventListener = (target, type, fn) => { target.addEventListener(type, fn); unsubs.push(() => target.removeEventListener(type, fn)); };
247
+
248
+ addEventListener(self.dom, 'ln-data-store:request-remote-sync', e => {
249
+ self.refreshMapper();
250
+ const c = self.findChildren();
251
+ if (c.store && c.connector) dispatch(c.connectorEl, _connNs(c.connectorEl) + ':request-sync', { since: e.detail.since, meta: { op: 'sync' } });
252
+ });
253
+
254
+ addEventListener(self.dom, 'ln-data-store:request-page', e => {
255
+ const c = self.findChildren(), d = e.detail || {};
256
+ if (!c.connectorEl) return;
257
+ const effective = composeQuery(d.query || {}, self._currentQuery());
258
+ dispatch(c.connectorEl, _connNs(c.connectorEl) + ':request-query', {
259
+ query: Object.assign({}, effective, { offset: d.offset, limit: d.limit, queryGen: d.queryGen })
260
+ });
261
+ });
262
+
263
+ addEventListener(self.dom, 'ln-data-coordinator:request-create', e => self._fanOutCreate(self.findChildren(), e.detail.data || {}, e.detail.action));
264
+ addEventListener(self.dom, 'ln-data-coordinator:request-update', e => self._fanOutUpdate(self.findChildren(), e.detail.id, e.detail.data || {}, e.detail.expected_version, e.detail.action));
265
+ addEventListener(self.dom, 'ln-data-coordinator:request-delete', e => self._fanOutDelete(self.findChildren(), e.detail.id));
266
+ addEventListener(self.dom, 'ln-data-coordinator:request-bulk-delete', e => self._fanOutBulkDelete(self.findChildren(), e.detail.ids || []));
267
+ addEventListener(self.dom, 'ln-api-queue:send', e => self._onQueueSend(e.detail || {}));
268
+ addEventListener(self.dom, 'ln-api-queue:failed', e => self._reportError('queue-failed', e?.detail?.error || new Error('Queue failed'), e?.detail || null));
269
+
270
+ addEventListener(self.dom, 'ln-data-store:initialized', e => {
271
+ const c = self.findChildren();
272
+ if (c.store && !c.store.initializationError && c.connector && !self._noAutosync(c) && !c.store.isSyncing && (!e.detail?.hasCache || self._isStale(c))) c.store.forceSync();
273
+ });
274
+
275
+ const onConnected = () => {
276
+ const c = self.findChildren();
277
+ if (c.store && !c.store.initializationError && c.connector && !self._noAutosync(c) && c.store.isInitialized && !c.store.isSyncing) c.store.forceSync();
278
+ };
279
+ addEventListener(self.dom, 'ln-websocket-connector:connected', onConnected);
280
+
281
+ addEventListener(document, 'submit', e => self._onFormSubmit(e));
282
+ const serve = (e, kind, attr) => {
283
+ if (self._owns(e.target.getAttribute(attr))) self._serveElement(e.target, kind, kind === 'stat' ? { filters: e.detail?.filters || null } : (kind === 'options' ? null : normalizeDataQuery(e.detail || {})), null);
284
+ };
285
+ addEventListener(document, 'ln-table:request-data', e => serve(e, 'table', 'data-ln-table-source'));
286
+ addEventListener(document, 'ln-list:request-data', e => serve(e, 'list', 'data-ln-list-source'));
287
+ addEventListener(document, 'ln-chart:request-data', e => serve(e, 'chart', 'data-ln-chart-source'));
288
+ addEventListener(document, 'ln-options:request-data', e => serve(e, 'options', 'data-ln-options'));
289
+ addEventListener(document, 'ln-stat:request-count', e => serve(e, 'stat', 'data-ln-stat'));
290
+
291
+ const refresh = e => { self._mutationReceipts.resolve(e.detail); self._refreshAll(null, false); };
292
+ addEventListener(self.dom, 'ln-data-store:ready', refresh);
293
+ addEventListener(self.dom, 'ln-data-store:created', refresh);
294
+ addEventListener(self.dom, 'ln-data-store:updated', refresh);
295
+ addEventListener(self.dom, 'ln-data-store:deleted', refresh);
296
+ addEventListener(self.dom, 'ln-data-store:mutation-error', e => self._mutationReceipts.reject(e.detail));
297
+ addEventListener(self.dom, 'ln-data-store:synced', e => { if (e.detail?.changed) self._refreshAll(e.detail.meta, false); });
298
+ addEventListener(self.dom, 'ln-data-store:query-changed', () => self._refreshAll(null, true));
299
+
300
+ addEventListener(self.dom, 'ln-search:change', e => {
301
+ e.preventDefault();
302
+ const term = e.detail?.term != null ? e.detail.term : '';
303
+ if (term !== (self.dom.getAttribute(SEARCH_ATTR) || '')) self.dom.setAttribute(SEARCH_ATTR, term);
304
+ });
305
+
306
+ addEventListener(self.dom, 'ln-filter:change', e => {
307
+ e.preventDefault();
308
+ const key = e.detail?.key;
309
+ if (!key) return;
310
+ const values = (e.detail.values || []).slice(), filters = self._currentQuery().filters, prev = filters[key];
311
+ if (prev ? (prev.length === values.length && prev.every((v, i) => v === values[i])) : !values.length) return;
312
+ if (values.length) filters[key] = values; else delete filters[key];
313
+ const p = new URLSearchParams();
314
+ Object.keys(filters).forEach(k => filters[k].forEach(v => p.append(k, v)));
315
+ const next = p.toString();
316
+ if (next) self.dom.setAttribute(FILTERS_ATTR, next); else self.dom.removeAttribute(FILTERS_ATTR);
317
+ });
318
+
319
+ addEventListener(self.dom, 'ln-sort:change', e => {
320
+ e.preventDefault();
321
+ const f = e.detail?.field, d = e.detail?.direction;
322
+ const next = (f && d && d !== 'none') ? { field: f, direction: d } : null, prev = self._currentQuery().sort;
323
+ if ((!prev && !next) || (prev && next && prev.field === next.field && prev.direction === next.direction)) return;
324
+ if (next) { self.dom.setAttribute(SORT_FIELD_ATTR, next.field); self.dom.setAttribute(SORT_DIR_ATTR, next.direction); }
325
+ else { self.dom.removeAttribute(SORT_FIELD_ATTR); self.dom.removeAttribute(SORT_DIR_ATTR); }
326
+ });
327
+
328
+ const connNamespaces = new Set(['ln-api-connector', 'ln-couchdb-connector', 'ln-websocket-connector', 'ln-connector']);
329
+ const childConn = self.findChildren().connectorEl;
330
+ if (childConn) { const customNs = _connNs(childConn); connNamespaces.add(customNs); addEventListener(self.dom, customNs + ':connected', onConnected); }
331
+ connNamespaces.forEach(ns => {
332
+ addEventListener(self.dom, ns + ':fetched', e => self._reconcileServerFetch(e.detail));
333
+ addEventListener(self.dom, ns + ':created', e => self._reconcileServerMutation('create', e.detail));
334
+ addEventListener(self.dom, ns + ':updated', e => self._reconcileServerMutation('update', e.detail));
335
+ addEventListener(self.dom, ns + ':deleted', e => self._reconcileServerMutation('ack', e.detail));
336
+ addEventListener(self.dom, ns + ':bulk-deleted', e => self._reconcileServerMutation('ack', e.detail));
337
+ addEventListener(self.dom, ns + ':error', e => self._reconcileServerMutation('error', e.detail));
338
+ });
339
+ }
340
+
341
+ _component.prototype._onQueueSend = function (d) {
342
+ this.refreshMapper();
343
+ const c = this.findChildren();
344
+ if (!c.store || !c.connector || !c.queue) return;
345
+ const m = d.meta || {}, ns = _connNs(c.connectorEl), key = d.idempotencyKey || d.entryId;
346
+ const actions = {
347
+ create: () => dispatch(c.connectorEl, ns + ':request-create', { data: d.payload, url: m.action || null, idempotencyKey: key, meta: { entryId: d.entryId, queued: true, op: 'create', tempId: m.tempId } }),
348
+ update: () => dispatch(c.connectorEl, ns + ':request-update', { id: d.targetId, data: d.payload, expected_version: d.expectedVersion, url: m.action || null, idempotencyKey: key, meta: { entryId: d.entryId, queued: true, op: 'update', id: d.targetId } }),
349
+ delete: () => dispatch(c.connectorEl, ns + ':request-delete', { id: d.targetId, idempotencyKey: key, meta: { entryId: d.entryId, queued: true, op: 'delete', id: d.targetId } }),
350
+ 'bulk-delete': () => dispatch(c.connectorEl, ns + ':request-bulk-delete', { ids: d.payload?.ids || [], idempotencyKey: key, meta: { entryId: d.entryId, queued: true, op: 'bulk-delete', bulkKey: m.bulkKey } })
351
+ };
352
+ if (actions[d.op]) actions[d.op]();
353
+ };
354
+
355
+ _component.prototype._onFormSubmit = function (e) {
356
+ const form = e.target;
357
+ if (e.defaultPrevented) return;
358
+ const scope = form.hasAttribute(SCOPE_ATTR) ? form.getAttribute(SCOPE_ATTR) : null;
359
+ if (scope === null || (scope ? !this._owns(scope) : form.closest('[' + DOM_SELECTOR + ']') !== this.dom)) return;
360
+ const method = resolveFormMethod(form);
361
+ if (method !== 'POST' && method !== 'PUT' && method !== 'PATCH') return;
362
+ e.preventDefault();
363
+ const raw = serializeForm(form);
364
+ delete raw._method; delete raw._token;
365
+ const id = raw.id, v = raw.expected_version, action = form.getAttribute('action') || '', c = this.findChildren();
366
+ delete raw.id; delete raw.expected_version;
367
+ if (method === 'POST') this._fanOutCreate(c, raw, action);
368
+ else this._fanOutUpdate(c, id, raw, v, action);
369
+ };
370
+
371
+ _component.prototype._reconcileServerFetch = function (d) {
372
+ if (!d) return;
373
+ const meta = d.meta || {}, c = this.findChildren(), raw = d.data;
374
+ this.refreshMapper();
375
+ const fetched = Array.isArray(raw) ? raw : (raw?.data || []);
376
+ const deleted = Array.isArray(raw?.deleted) ? raw.deleted : [];
377
+ const syncedAt = Array.isArray(raw) ? Math.floor(Date.now() / 1000) : (raw?.synced_at ?? raw?.since ?? Math.floor(Date.now() / 1000));
378
+ const records = fetched.map(r => this.mapper.ingress(r));
379
+ if (!c.store || c.store.initializationError) return;
380
+
381
+ if (!meta.kind) return c.store.applySync(records, deleted, syncedAt, { total: d.total, filtered: d.filtered, offset: d.offset, queryGen: d.queryGen, targetEl: meta.targetEl });
382
+ c.store.applyQuery(records, { total: d.total }).then(dec => {
383
+ const k = meta.kind;
384
+ if (k === 'table' || k === 'list' || k === 'chart') {
385
+ dispatch(meta.targetEl, 'ln-' + k + ':set-loading', { loading: false });
386
+ dispatch(meta.targetEl, 'ln-' + k + ':set-data', { data: dec, total: d.total ?? dec.length, filtered: d.filtered ?? dec.length, offset: d.offset, queryGen: meta.queryGen });
387
+ this._boundDelivered.set(meta.targetEl, true);
388
+ } else if (k === 'options') {
389
+ c.store.getAll({}).then(r => dispatch(meta.targetEl, 'ln-options:set-data', { data: r.data }));
390
+ } else if (k === 'stat') {
391
+ dispatch(meta.targetEl, 'ln-stat:set-count', { count: d.filtered ?? d.total ?? records.length });
392
+ }
393
+ });
394
+ };
395
+
396
+ _component.prototype._reconcileServerMutation = function (type, d) {
397
+ if (!d) return;
398
+ const c = this.findChildren(), meta = d.meta || {};
399
+ if (type === 'create') {
400
+ if (!d.record) return this._reportError('create-empty-response', new Error('Create response missing record payload'), meta);
401
+ const rec = this.mapper.ingress(d.record);
402
+ (c.storeEl ? this._requestStoreMutation(c, 'update', { id: meta.tempId, data: rec }) : Promise.resolve()).then(() => {
403
+ if (meta.queued && c.queue) dispatch(c.queueEl, 'ln-api-queue:resolve-create', { entryId: meta.entryId, oldKey: meta.tempId, newId: rec.id });
404
+ }).catch(err => this._reportError('create-reconcile', err, meta));
405
+ } else if (type === 'update') {
406
+ const rec = d.record ? this.mapper.ingress(d.record) : null;
407
+ (c.storeEl && rec ? this._requestStoreMutation(c, 'update', { id: meta.id, data: rec }) : Promise.resolve()).then(() => {
408
+ if (meta.queued && c.queue) dispatch(c.queueEl, 'ln-api-queue:ack', { entryId: meta.entryId });
409
+ }).catch(err => this._reportError('update-reconcile', err, meta));
410
+ } else if (type === 'ack') {
411
+ if (meta.queued && c.queue) dispatch(c.queueEl, 'ln-api-queue:ack', { entryId: meta.entryId });
412
+ } else if (type === 'error') {
413
+ const status = d.status || d.error?.status || 0;
414
+ if (meta.queued && c.queue) {
415
+ dispatch(c.queueEl, 'ln-api-queue:nack', { entryId: meta.entryId, reason: (status === 401 || status === 419) ? 'auth' : ((status === 0 || status >= 500) ? 'retry' : 'drop') });
416
+ }
417
+ if (c.storeEl) {
418
+ dispatch(c.storeEl, 'ln-data-store:request-sync-failed', { error: d.error || d, status });
419
+ if (!meta.queued) {
420
+ if (meta.op === 'update' && meta.snapshot) {
421
+ dispatch(c.storeEl, 'ln-data-store:request-update', { id: meta.id, data: meta.snapshot });
422
+ } else if (meta.op === 'create' && meta.tempId) {
423
+ dispatch(c.storeEl, 'ln-data-store:request-delete', { id: meta.tempId });
424
+ } else if (meta.op === 'delete' && meta.snapshot) {
425
+ dispatch(c.storeEl, 'ln-data-store:request-create', { tempId: meta.id, data: meta.snapshot });
426
+ }
427
+ }
428
+ }
429
+ this._reportError('connector-error', d.error || d, meta);
430
+ }
431
+ };
432
+
433
+ // ─── Destroy and Cleanup ──────────────────────────────────
434
+ _component.prototype.destroy = function () {
435
+ if (!this.dom[DOM_ATTRIBUTE]) return;
436
+ this._destroyed = true;
437
+ while (this._unsubs?.length) this._unsubs.pop()();
438
+ this._unsubs = this._boundQueries = this._boundDelivered = this._queueQueryRefresh = null;
439
+ this._mutationReceipts.close(new Error('Data coordinator destroyed'));
440
+ this._mutationReceipts = null;
441
+ delete this.dom[DOM_ATTRIBUTE];
442
+ };
443
+
444
+ function _syncAttribute(el, attrName) {
445
+ const inst = el[DOM_ATTRIBUTE];
446
+ if (!inst) return;
447
+ if (attrName === 'data-ln-data-coordinator-mapper') inst.refreshMapper();
448
+ else if (attrName === SEARCH_ATTR || attrName === FILTERS_ATTR || attrName === SORT_FIELD_ATTR || attrName === SORT_DIR_ATTR) inst._queueQueryRefresh();
449
+ }
450
+
451
+ registerComponent(DOM_SELECTOR, DOM_ATTRIBUTE, _component, 'ln-data-coordinator', {
452
+ extraAttributes: ['data-ln-data-coordinator-mapper', SEARCH_ATTR, FILTERS_ATTR, SORT_FIELD_ATTR, SORT_DIR_ATTR],
453
+ onAttributeChange: _syncAttribute
454
+ });
455
+
456
+ window[DOM_ATTRIBUTE].init = window[DOM_ATTRIBUTE];
457
+ })();