@farm.js/react 0.1.0-beta.0 → 0.1.0-beta.2

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.
@@ -1,36 +1,162 @@
1
1
  'use strict';
2
2
 
3
3
  var React = require('react');
4
+ var reactDom = require('react-dom');
4
5
 
5
6
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
7
 
7
8
  var React__default = /*#__PURE__*/_interopDefault(React);
8
9
 
9
10
  // src/compiler-runtime.tsx
11
+ var COMPILER_HMR_REGISTRY = /* @__PURE__ */ Symbol.for("@farm.js/react/compiler-hmr-registry");
12
+ function getCompilerHmrRegistry() {
13
+ const globalTarget = globalThis;
14
+ const existing = globalTarget[COMPILER_HMR_REGISTRY];
15
+ if (existing instanceof Map) return existing;
16
+ const registry = /* @__PURE__ */ new Map();
17
+ globalTarget[COMPILER_HMR_REGISTRY] = registry;
18
+ return registry;
19
+ }
10
20
  function renderTextValue(value) {
11
21
  if (Array.isArray(value)) return value.map(renderTextValue).join("");
12
22
  if (value === null || value === void 0 || typeof value === "boolean") return "";
13
23
  return String(value);
14
24
  }
15
- function findBindingTarget(root, path) {
25
+ function findBindingTarget(root, path, blockRoots) {
16
26
  let current = root;
17
27
  for (const index of path) {
18
- current = current?.children.item(index) || null;
28
+ if (!current) return null;
29
+ current = [...current.children].filter((child) => !blockRoots.has(child))[index] || null;
19
30
  }
20
31
  return current;
21
32
  }
33
+ var UNITLESS_STYLE_PROPERTIES = /* @__PURE__ */ new Set([
34
+ "animationIterationCount",
35
+ "aspectRatio",
36
+ "borderImageOutset",
37
+ "borderImageSlice",
38
+ "borderImageWidth",
39
+ "boxFlex",
40
+ "boxFlexGroup",
41
+ "boxOrdinalGroup",
42
+ "columnCount",
43
+ "columns",
44
+ "flex",
45
+ "flexGrow",
46
+ "flexNegative",
47
+ "flexOrder",
48
+ "flexPositive",
49
+ "flexShrink",
50
+ "fontWeight",
51
+ "gridArea",
52
+ "gridColumn",
53
+ "gridColumnEnd",
54
+ "gridColumnSpan",
55
+ "gridColumnStart",
56
+ "gridRow",
57
+ "gridRowEnd",
58
+ "gridRowSpan",
59
+ "gridRowStart",
60
+ "lineClamp",
61
+ "lineHeight",
62
+ "opacity",
63
+ "order",
64
+ "orphans",
65
+ "scale",
66
+ "tabSize",
67
+ "widows",
68
+ "zIndex",
69
+ "zoom",
70
+ "fillOpacity",
71
+ "floodOpacity",
72
+ "stopOpacity",
73
+ "strokeDasharray",
74
+ "strokeDashoffset",
75
+ "strokeMiterlimit",
76
+ "strokeOpacity",
77
+ "strokeWidth"
78
+ ]);
79
+ function unprefixedStyleName(name) {
80
+ const unprefixed = name.replace(/^(?:Webkit|Moz|ms|O)(?=[A-Z])/, "");
81
+ return unprefixed ? unprefixed[0].toLowerCase() + unprefixed.slice(1) : name;
82
+ }
83
+ function isHtmlOrSvgElement(element) {
84
+ const view = element.ownerDocument.defaultView;
85
+ return Boolean(
86
+ view && (element instanceof view.HTMLElement || element instanceof view.SVGElement)
87
+ );
88
+ }
89
+ function isInputElement(element) {
90
+ const view = element.ownerDocument.defaultView;
91
+ return Boolean(view && element instanceof view.HTMLInputElement);
92
+ }
93
+ function isTextAreaElement(element) {
94
+ const view = element.ownerDocument.defaultView;
95
+ return Boolean(view && element instanceof view.HTMLTextAreaElement);
96
+ }
97
+ function isSelectElement(element) {
98
+ const view = element.ownerDocument.defaultView;
99
+ return Boolean(view && element instanceof view.HTMLSelectElement);
100
+ }
101
+ function isOptionElement(element) {
102
+ const view = element.ownerDocument.defaultView;
103
+ return Boolean(view && element instanceof view.HTMLOptionElement);
104
+ }
105
+ function isSelectableTextControl(element) {
106
+ return Boolean(element && (isInputElement(element) || isTextAreaElement(element)));
107
+ }
108
+ function updateStyle(element, name, value) {
109
+ if (!isHtmlOrSvgElement(element)) return;
110
+ const customProperty = name.startsWith("--");
111
+ let nextValue = "";
112
+ if (value !== null && value !== void 0 && typeof value !== "boolean" && value !== "") {
113
+ nextValue = typeof value === "number" && value !== 0 && !customProperty && !UNITLESS_STYLE_PROPERTIES.has(unprefixedStyleName(name)) ? `${value}px` : String(value).trim();
114
+ }
115
+ if (customProperty || name.includes("-")) {
116
+ element.style.setProperty(name, nextValue);
117
+ } else {
118
+ element.style[name] = nextValue;
119
+ }
120
+ }
121
+ function updateSelectValue(element, value) {
122
+ const options = [...element.options];
123
+ if (element.multiple) {
124
+ const selected = new Set(
125
+ (Array.isArray(value) ? value : value === null || value === void 0 ? [] : [value]).map(
126
+ String
127
+ )
128
+ );
129
+ for (const option of options) option.selected = selected.has(option.value);
130
+ return;
131
+ }
132
+ const selectedValue = value === null || value === void 0 ? "" : String(value);
133
+ let fallback;
134
+ for (const option of options) {
135
+ if (!option.disabled && !fallback) fallback = option;
136
+ if (option.value === selectedValue) {
137
+ option.selected = true;
138
+ return;
139
+ }
140
+ }
141
+ if (fallback) fallback.selected = true;
142
+ }
22
143
  function updateAttribute(element, name, value) {
23
144
  const attributeName = name === "className" ? "class" : name === "htmlFor" ? "for" : name;
24
145
  const stringifiesBoolean = attributeName.startsWith("data-") || attributeName.startsWith("aria-");
25
- if (name === "value" && element instanceof HTMLInputElement) {
26
- element.value = value === null || value === void 0 ? "" : String(value);
146
+ if (name === "value" && (isInputElement(element) || isTextAreaElement(element))) {
147
+ const nextValue = value === null || value === void 0 ? "" : String(value);
148
+ if (element.value !== nextValue) element.value = nextValue;
27
149
  return;
28
150
  }
29
- if (name === "checked" && element instanceof HTMLInputElement) {
151
+ if (name === "value" && isSelectElement(element)) {
152
+ updateSelectValue(element, value);
153
+ return;
154
+ }
155
+ if (name === "checked" && isInputElement(element)) {
30
156
  element.checked = Boolean(value);
31
157
  return;
32
158
  }
33
- if (name === "selected" && element instanceof HTMLOptionElement) {
159
+ if (name === "selected" && isOptionElement(element)) {
34
160
  element.selected = Boolean(value);
35
161
  return;
36
162
  }
@@ -46,18 +172,1017 @@ function updateAttribute(element, name, value) {
46
172
  element.setAttribute(attributeName, String(value));
47
173
  }
48
174
  }
175
+ function createConditionalBlockComponent(owner) {
176
+ class FarmConditionalBlock extends React__default.default.Component {
177
+ constructor() {
178
+ super(...arguments);
179
+ this.captureRoot = (root) => {
180
+ owner.setRoot(this.props.id, root);
181
+ };
182
+ this.refresh = (afterCommit) => {
183
+ this.forceUpdate(afterCommit);
184
+ };
185
+ }
186
+ subscribe() {
187
+ this.unsubscribe = owner.subscribe(this.props.id, this.refresh);
188
+ }
189
+ componentDidMount() {
190
+ this.subscribe();
191
+ }
192
+ componentDidUpdate(previous) {
193
+ if (previous.id === this.props.id) return;
194
+ this.unsubscribe?.();
195
+ owner.setRoot(previous.id, null);
196
+ this.subscribe();
197
+ }
198
+ componentWillUnmount() {
199
+ this.unsubscribe?.();
200
+ owner.setRoot(this.props.id, null);
201
+ }
202
+ render() {
203
+ const node = this.props.render();
204
+ if (!React__default.default.isValidElement(node)) {
205
+ if (node === null || node === void 0 || typeof node === "boolean" || typeof node === "string" || typeof node === "number" || typeof node === "bigint") {
206
+ return node;
207
+ }
208
+ throw new TypeError(
209
+ `Compiled conditional block ${this.props.id} must return one host element or an empty value.`
210
+ );
211
+ }
212
+ if (typeof node.type !== "string") {
213
+ throw new TypeError(
214
+ `Compiled conditional block ${this.props.id} must return one host element.`
215
+ );
216
+ }
217
+ return React__default.default.cloneElement(node, {
218
+ ref: this.captureRoot
219
+ });
220
+ }
221
+ }
222
+ FarmConditionalBlock.displayName = "FarmCompiledConditionalBlock";
223
+ return FarmConditionalBlock;
224
+ }
225
+ function createKeyedListBlockComponent(owner) {
226
+ class FarmKeyedListBlock extends React__default.default.Component {
227
+ constructor() {
228
+ super(...arguments);
229
+ this.refresh = (afterCommit) => {
230
+ this.forceUpdate(afterCommit);
231
+ };
232
+ }
233
+ subscribe() {
234
+ this.unsubscribe = owner.subscribe(this.props.id, this.refresh);
235
+ }
236
+ componentDidMount() {
237
+ this.subscribe();
238
+ }
239
+ componentDidUpdate(previous) {
240
+ if (previous.id === this.props.id) return;
241
+ this.unsubscribe?.();
242
+ this.subscribe();
243
+ }
244
+ componentWillUnmount() {
245
+ this.unsubscribe?.();
246
+ }
247
+ render() {
248
+ return this.props.render();
249
+ }
250
+ }
251
+ FarmKeyedListBlock.displayName = "FarmCompiledKeyedListBlock";
252
+ return FarmKeyedListBlock;
253
+ }
254
+ function isCompilerHostElement(value) {
255
+ return typeof value === "object" && value !== null && value.kind === "element";
256
+ }
257
+ function createCompilerHostElement(document, descriptor) {
258
+ const element = document.createElement(descriptor.tag);
259
+ for (const attribute of descriptor.attributes) {
260
+ updateAttribute(element, attribute.name, attribute.value);
261
+ }
262
+ for (const style of descriptor.styles) updateStyle(element, style.name, style.value);
263
+ for (const child of descriptor.children) {
264
+ if (isCompilerHostElement(child)) {
265
+ element.append(createCompilerHostElement(document, child));
266
+ continue;
267
+ }
268
+ const text = renderTextValue(child);
269
+ if (text) element.append(document.createTextNode(text));
270
+ }
271
+ for (const attribute of descriptor.attributes) {
272
+ if (attribute.name === "value" && (isSelectElement(element) || isTextAreaElement(element))) {
273
+ updateAttribute(element, attribute.name, attribute.value);
274
+ }
275
+ }
276
+ return element;
277
+ }
278
+ function matchesCompilerHostElement(element, descriptor, opaquePaths = /* @__PURE__ */ new Set(), path = []) {
279
+ if (element.tagName.toLowerCase() !== descriptor.tag.toLowerCase()) return false;
280
+ if (opaquePaths.has(path.join("."))) return true;
281
+ const expectedChildren = descriptor.children.filter(isCompilerHostElement);
282
+ if (element.children.length !== expectedChildren.length) return false;
283
+ return expectedChildren.every(
284
+ (child, index) => matchesCompilerHostElement(element.children[index], child, opaquePaths, [...path, index])
285
+ );
286
+ }
287
+ function findCompilerHostTarget(root, path) {
288
+ let current = root;
289
+ for (const index of path) current = current?.children[index] || null;
290
+ return current;
291
+ }
292
+ var UNSET_KEYED_ROW_BINDING = /* @__PURE__ */ Symbol("unset interactive keyed-row binding");
293
+ function keyedRowIdentity(key) {
294
+ return String(key);
295
+ }
296
+ function normalizedKeyedRowBindingValue(binding, value) {
297
+ return binding.kind === "text" ? renderTextValue(value) : value;
298
+ }
299
+ function readKeyedRowBindingValues(props, item, index) {
300
+ return props.bindings.map(
301
+ (binding) => normalizedKeyedRowBindingValue(binding, binding.read(item, index))
302
+ );
303
+ }
304
+ function applyKeyedRowBindings(props, instance, item, index) {
305
+ for (let bindingIndex = 0; bindingIndex < props.bindings.length; bindingIndex += 1) {
306
+ const binding = props.bindings[bindingIndex];
307
+ const rawValue = binding.read(item, index);
308
+ const value = normalizedKeyedRowBindingValue(binding, rawValue);
309
+ if (Object.is(instance.values[bindingIndex], value)) continue;
310
+ instance.values[bindingIndex] = value;
311
+ const target = findCompilerHostTarget(instance.element, binding.path);
312
+ if (!target) continue;
313
+ if (binding.kind === "text") {
314
+ target.textContent = value;
315
+ } else if (binding.kind === "style" && binding.name) {
316
+ updateStyle(target, binding.name, rawValue);
317
+ } else if (binding.kind === "attribute" && binding.name) {
318
+ updateAttribute(target, binding.name, rawValue);
319
+ }
320
+ }
321
+ }
322
+ function keyedRowConditionalSnapshot(conditional, item, index) {
323
+ const test = conditional.test(item, index);
324
+ if (conditional.logical && !test) {
325
+ return typeof test === "number" || typeof test === "bigint" ? ["primitive", test] : ["empty"];
326
+ }
327
+ const key = test ? "truthy" : "falsy";
328
+ const branch = key === "truthy" ? conditional.truthy : conditional.falsy;
329
+ if (!branch) return ["empty"];
330
+ return [
331
+ key,
332
+ ...branch.bindings.map(
333
+ (binding) => normalizedKeyedRowBindingValue(binding, binding.read(item, index))
334
+ )
335
+ ];
336
+ }
337
+ function readKeyedRowConditionalValues(props, item, index) {
338
+ return new Map(
339
+ (props.conditionals || []).map((conditional) => [
340
+ conditional.id,
341
+ keyedRowConditionalSnapshot(conditional, item, index)
342
+ ])
343
+ );
344
+ }
345
+ function keyedRowConditionalChanged(previous, next) {
346
+ return !previous || previous.length !== next.length || next.some((value, index) => !Object.is(value, previous[index]));
347
+ }
348
+ function hostConditionalSelection(props) {
349
+ const test = props.test();
350
+ if (props.logical && !test) {
351
+ if (typeof test === "number" || typeof test === "bigint") return { kind: "fallback" };
352
+ return { kind: "empty" };
353
+ }
354
+ const key = test ? "truthy" : "falsy";
355
+ const branch = key === "truthy" ? props.truthy : props.falsy;
356
+ return branch ? { kind: "branch", key, branch } : { kind: "empty" };
357
+ }
358
+ function normalizedHostConditionalBindingValue(binding, value) {
359
+ return binding.kind === "text" ? renderTextValue(value) : value;
360
+ }
361
+ function readHostConditionalBindingValues(branch) {
362
+ return branch.bindings.map(
363
+ (binding) => normalizedHostConditionalBindingValue(binding, binding.read())
364
+ );
365
+ }
366
+ function applyHostConditionalBindings(branch, instance) {
367
+ for (let bindingIndex = 0; bindingIndex < branch.bindings.length; bindingIndex += 1) {
368
+ const binding = branch.bindings[bindingIndex];
369
+ const rawValue = binding.read();
370
+ const value = normalizedHostConditionalBindingValue(binding, rawValue);
371
+ if (Object.is(instance.values[bindingIndex], value)) continue;
372
+ instance.values[bindingIndex] = value;
373
+ const target = findCompilerHostTarget(instance.element, binding.path);
374
+ if (!target) continue;
375
+ if (binding.kind === "text") {
376
+ target.textContent = value;
377
+ } else if (binding.kind === "style" && binding.name) {
378
+ updateStyle(target, binding.name, rawValue);
379
+ } else if (binding.kind === "attribute" && binding.name) {
380
+ updateAttribute(target, binding.name, rawValue);
381
+ }
382
+ }
383
+ }
384
+ function createHostConditionalBlockComponent(owner) {
385
+ class FarmHostConditionalBlock extends React__default.default.Component {
386
+ constructor() {
387
+ super(...arguments);
388
+ this.state = { fallback: false };
389
+ this.root = null;
390
+ this.mounted = false;
391
+ this.fallbackRequested = false;
392
+ this.fallbackVersion = 0;
393
+ this.propSyncQueued = false;
394
+ this.currentProps = this.props;
395
+ this.activeBranch = null;
396
+ this.instance = null;
397
+ this.captureRoot = (root) => {
398
+ this.root = root;
399
+ };
400
+ this.refresh = (afterCommit) => {
401
+ this.reconcile(afterCommit);
402
+ };
403
+ }
404
+ adopt() {
405
+ if (!this.root) return false;
406
+ const selection = hostConditionalSelection(this.currentProps);
407
+ if (selection.kind === "fallback") return false;
408
+ if (selection.kind === "empty") {
409
+ if (this.root.childNodes.length !== 0) return false;
410
+ this.activeBranch = null;
411
+ this.instance = null;
412
+ return true;
413
+ }
414
+ if (this.root.childNodes.length !== 1 || this.root.firstElementChild === null || this.root.firstElementChild !== this.root.firstChild) {
415
+ return false;
416
+ }
417
+ const descriptor = selection.branch.create();
418
+ const element = this.root.firstElementChild;
419
+ if (!matchesCompilerHostElement(element, descriptor)) return false;
420
+ this.activeBranch = selection.key;
421
+ this.instance = {
422
+ element,
423
+ values: readHostConditionalBindingValues(selection.branch)
424
+ };
425
+ return true;
426
+ }
427
+ activateFallback(afterCommit) {
428
+ if (!this.mounted || this.state.fallback || this.fallbackRequested) {
429
+ afterCommit?.();
430
+ return;
431
+ }
432
+ this.fallbackRequested = true;
433
+ this.fallbackVersion += 1;
434
+ this.setState({ fallback: true }, afterCommit);
435
+ }
436
+ reconcile(afterCommit) {
437
+ if (!this.mounted || !this.root) {
438
+ afterCommit?.();
439
+ return;
440
+ }
441
+ if (this.state.fallback) {
442
+ this.forceUpdate(afterCommit);
443
+ return;
444
+ }
445
+ const selection = hostConditionalSelection(this.currentProps);
446
+ if (selection.kind === "fallback") {
447
+ this.activateFallback(afterCommit);
448
+ return;
449
+ }
450
+ if (selection.kind === "empty") {
451
+ if (this.instance) this.instance.element.remove();
452
+ this.activeBranch = null;
453
+ this.instance = null;
454
+ afterCommit?.();
455
+ return;
456
+ }
457
+ if (this.activeBranch === selection.key && this.instance) {
458
+ applyHostConditionalBindings(selection.branch, this.instance);
459
+ afterCommit?.();
460
+ return;
461
+ }
462
+ const element = createCompilerHostElement(this.root.ownerDocument, selection.branch.create());
463
+ this.root.replaceChildren(element);
464
+ this.activeBranch = selection.key;
465
+ this.instance = {
466
+ element,
467
+ values: readHostConditionalBindingValues(selection.branch)
468
+ };
469
+ afterCommit?.();
470
+ }
471
+ schedulePropSync() {
472
+ if (this.propSyncQueued) return;
473
+ this.propSyncQueued = true;
474
+ queueMicrotask(() => {
475
+ this.propSyncQueued = false;
476
+ if (this.mounted && !this.state.fallback) this.reconcile();
477
+ });
478
+ }
479
+ shouldComponentUpdate(nextProps, nextState) {
480
+ this.currentProps = nextProps;
481
+ if (nextState.fallback || this.state.fallback) return true;
482
+ this.schedulePropSync();
483
+ return false;
484
+ }
485
+ componentDidMount() {
486
+ this.mounted = true;
487
+ this.unsubscribe = owner.subscribe(this.props.id, this.refresh);
488
+ if (!this.adopt()) this.activateFallback();
489
+ }
490
+ componentWillUnmount() {
491
+ this.mounted = false;
492
+ this.unsubscribe?.();
493
+ this.root = null;
494
+ this.activeBranch = null;
495
+ this.instance = null;
496
+ }
497
+ render() {
498
+ const container = this.currentProps.render();
499
+ if (!React__default.default.isValidElement(container) || typeof container.type !== "string") {
500
+ throw new TypeError(
501
+ `Compiled host conditional ${this.currentProps.id} must own one host container.`
502
+ );
503
+ }
504
+ return React__default.default.cloneElement(container, {
505
+ key: this.state.fallback ? `react-${this.fallbackVersion}` : "compiled",
506
+ ref: this.captureRoot
507
+ });
508
+ }
509
+ }
510
+ FarmHostConditionalBlock.displayName = "FarmCompiledHostConditional";
511
+ return FarmHostConditionalBlock;
512
+ }
513
+ function longestIncreasingSubsequencePositions(sequence) {
514
+ const tails = [];
515
+ const previous = Array.from({ length: sequence.length }, () => -1);
516
+ for (let index = 0; index < sequence.length; index += 1) {
517
+ if (sequence[index] < 0) continue;
518
+ let low = 0;
519
+ let high = tails.length;
520
+ while (low < high) {
521
+ const middle = low + high >> 1;
522
+ if (sequence[tails[middle]] < sequence[index]) low = middle + 1;
523
+ else high = middle;
524
+ }
525
+ if (low > 0) previous[index] = tails[low - 1];
526
+ tails[low] = index;
527
+ }
528
+ const positions = /* @__PURE__ */ new Set();
529
+ let cursor = tails.at(-1) ?? -1;
530
+ while (cursor >= 0) {
531
+ positions.add(cursor);
532
+ cursor = previous[cursor];
533
+ }
534
+ return positions;
535
+ }
536
+ function createKeyedRowsBlockComponent(owner) {
537
+ class FarmKeyedRowConditional extends React__default.default.Component {
538
+ constructor() {
539
+ super(...arguments);
540
+ this.state = {
541
+ renderVersion: this.props.renderVersion,
542
+ item: this.props.item,
543
+ index: this.props.index
544
+ };
545
+ this.refresh = (item, index, afterCommit) => {
546
+ this.setState({ item, index }, afterCommit);
547
+ };
548
+ }
549
+ static getDerivedStateFromProps(props, state) {
550
+ if (props.renderVersion === state.renderVersion) return null;
551
+ return {
552
+ renderVersion: props.renderVersion,
553
+ item: props.item,
554
+ index: props.index
555
+ };
556
+ }
557
+ subscribe() {
558
+ this.unsubscribe = this.props.owner.subscribe(this.props.rowKey, this.props.id, this.refresh);
559
+ }
560
+ componentDidMount() {
561
+ this.subscribe();
562
+ }
563
+ componentDidUpdate(previous) {
564
+ if (previous.owner === this.props.owner && previous.rowKey === this.props.rowKey && previous.id === this.props.id) {
565
+ return;
566
+ }
567
+ this.unsubscribe?.();
568
+ this.subscribe();
569
+ }
570
+ componentWillUnmount() {
571
+ this.unsubscribe?.();
572
+ }
573
+ render() {
574
+ return this.props.render(this.state.item, this.state.index);
575
+ }
576
+ }
577
+ FarmKeyedRowConditional.displayName = "FarmCompiledKeyedRowConditional";
578
+ class FarmKeyedRowsBlock extends React__default.default.Component {
579
+ constructor() {
580
+ super(...arguments);
581
+ this.state = { fallback: false };
582
+ this.root = null;
583
+ this.mounted = false;
584
+ this.fallbackRequested = false;
585
+ this.fallbackVersion = 0;
586
+ this.fallbackKeysWereUnsafe = false;
587
+ this.propSyncQueued = false;
588
+ this.currentProps = this.props;
589
+ this.instances = /* @__PURE__ */ new Map();
590
+ this.renderVersion = 0;
591
+ this.eventHandlers = /* @__PURE__ */ new Map();
592
+ this.conditionalListeners = /* @__PURE__ */ new Map();
593
+ this.conditionalOwner = {
594
+ subscribe: (key, id, refresh) => this.subscribeToRowConditional(key, id, refresh)
595
+ };
596
+ this.captureRoot = (root) => {
597
+ this.root = root;
598
+ };
599
+ this.rowEvent = (item, index, eventId) => {
600
+ if (this.state.fallback) {
601
+ return (event) => this.currentProps.events?.[eventId]?.invoke(item, index, event);
602
+ }
603
+ const key = keyedRowIdentity(this.currentProps.rowKey(item, index));
604
+ let handlers = this.eventHandlers.get(key);
605
+ if (!handlers) {
606
+ handlers = /* @__PURE__ */ new Map();
607
+ this.eventHandlers.set(key, handlers);
608
+ }
609
+ const existing = handlers.get(eventId);
610
+ if (existing) return existing;
611
+ const handler = (event) => {
612
+ const instance = this.instances.get(key);
613
+ const descriptor = this.currentProps.events?.[eventId];
614
+ if (!instance || !descriptor) return;
615
+ return descriptor.invoke(instance.item, instance.index, event);
616
+ };
617
+ handlers.set(eventId, handler);
618
+ return handler;
619
+ };
620
+ this.rowConditional = (item, index, conditionalId, render) => {
621
+ if (this.state.fallback) return render(item, index);
622
+ const key = keyedRowIdentity(this.currentProps.rowKey(item, index));
623
+ return React__default.default.createElement(FarmKeyedRowConditional, {
624
+ key: `${key}:${conditionalId}`,
625
+ owner: this.conditionalOwner,
626
+ rowKey: key,
627
+ id: conditionalId,
628
+ renderVersion: this.renderVersion,
629
+ item,
630
+ index,
631
+ render
632
+ });
633
+ };
634
+ this.refresh = (afterCommit) => {
635
+ this.reconcile(afterCommit);
636
+ };
637
+ }
638
+ readRows(props) {
639
+ const source = props.items();
640
+ const items = source ? Array.from(source) : [];
641
+ const keys = items.map((item, index) => keyedRowIdentity(props.rowKey(item, index)));
642
+ if (new Set(keys).size !== keys.length) return null;
643
+ return { items, keys };
644
+ }
645
+ subscribeToRowConditional(key, id, refresh) {
646
+ let listeners = this.conditionalListeners.get(key);
647
+ if (!listeners) {
648
+ listeners = /* @__PURE__ */ new Map();
649
+ this.conditionalListeners.set(key, listeners);
650
+ }
651
+ listeners.set(id, refresh);
652
+ return () => {
653
+ const current = this.conditionalListeners.get(key);
654
+ if (current?.get(id) !== refresh) return;
655
+ current.delete(id);
656
+ if (current.size === 0) this.conditionalListeners.delete(key);
657
+ };
658
+ }
659
+ hasReactOwnedRows(props = this.currentProps) {
660
+ return Boolean(props.events?.length || props.conditionals?.length);
661
+ }
662
+ pruneEventHandlers(keys) {
663
+ const active = new Set(keys);
664
+ for (const key of this.eventHandlers.keys()) {
665
+ if (!active.has(key)) this.eventHandlers.delete(key);
666
+ }
667
+ }
668
+ pruneConditionalListeners(keys) {
669
+ const active = new Set(keys);
670
+ for (const key of this.conditionalListeners.keys()) {
671
+ if (!active.has(key)) this.conditionalListeners.delete(key);
672
+ }
673
+ }
674
+ adopt() {
675
+ if (!this.root) return false;
676
+ const rows = this.readRows(this.currentProps);
677
+ const elements = [...this.root.children];
678
+ if (!rows || rows.items.length !== elements.length) return false;
679
+ const opaqueConditionalPaths = new Set(
680
+ (this.currentProps.conditionals || []).map((conditional) => conditional.path.join("."))
681
+ );
682
+ const instances = /* @__PURE__ */ new Map();
683
+ for (let index = 0; index < rows.items.length; index += 1) {
684
+ if (this.hasReactOwnedRows() && !matchesCompilerHostElement(
685
+ elements[index],
686
+ this.currentProps.create(rows.items[index], index),
687
+ opaqueConditionalPaths
688
+ )) {
689
+ return false;
690
+ }
691
+ const instance = {
692
+ key: rows.keys[index],
693
+ element: elements[index],
694
+ values: this.hasReactOwnedRows() ? this.currentProps.bindings.map(() => UNSET_KEYED_ROW_BINDING) : readKeyedRowBindingValues(this.currentProps, rows.items[index], index),
695
+ item: rows.items[index],
696
+ index,
697
+ conditionalValues: readKeyedRowConditionalValues(
698
+ this.currentProps,
699
+ rows.items[index],
700
+ index
701
+ )
702
+ };
703
+ if (this.hasReactOwnedRows()) {
704
+ applyKeyedRowBindings(this.currentProps, instance, rows.items[index], index);
705
+ }
706
+ instances.set(rows.keys[index], instance);
707
+ }
708
+ this.instances = instances;
709
+ this.pruneEventHandlers(rows.keys);
710
+ this.pruneConditionalListeners(rows.keys);
711
+ return true;
712
+ }
713
+ hasUnsafeFallbackKeys() {
714
+ try {
715
+ return this.readRows(this.currentProps) === null;
716
+ } catch {
717
+ return true;
718
+ }
719
+ }
720
+ activateFallback(afterCommit) {
721
+ if (!this.mounted || this.state.fallback || this.fallbackRequested) {
722
+ afterCommit?.();
723
+ return;
724
+ }
725
+ this.fallbackRequested = true;
726
+ this.fallbackKeysWereUnsafe = this.hasUnsafeFallbackKeys();
727
+ this.fallbackVersion += 1;
728
+ this.setState({ fallback: true }, afterCommit);
729
+ }
730
+ synchronizeReactOwnedRows(afterCommit) {
731
+ this.forceUpdate(() => {
732
+ if (!this.mounted) {
733
+ afterCommit?.();
734
+ return;
735
+ }
736
+ if (!this.adopt()) {
737
+ this.activateFallback(afterCommit);
738
+ return;
739
+ }
740
+ afterCommit?.();
741
+ });
742
+ }
743
+ notifyConditionalChanges(changes, afterCommit) {
744
+ if (changes.length === 0) {
745
+ afterCommit?.();
746
+ return;
747
+ }
748
+ let pending = changes.length;
749
+ const committed = () => {
750
+ pending -= 1;
751
+ if (pending === 0) afterCommit?.();
752
+ };
753
+ reactDom.flushSync(() => {
754
+ for (const change of changes) {
755
+ const refresh = this.conditionalListeners.get(change.key)?.get(change.id);
756
+ if (refresh) refresh(change.item, change.index, committed);
757
+ else committed();
758
+ }
759
+ });
760
+ }
761
+ reconcile(afterCommit) {
762
+ if (!this.mounted || !this.root) {
763
+ afterCommit?.();
764
+ return;
765
+ }
766
+ if (this.state.fallback) {
767
+ const unsafeKeys = this.hasUnsafeFallbackKeys();
768
+ if (unsafeKeys || this.fallbackKeysWereUnsafe) {
769
+ this.fallbackVersion += 1;
770
+ }
771
+ this.fallbackKeysWereUnsafe = unsafeKeys;
772
+ this.forceUpdate(afterCommit);
773
+ return;
774
+ }
775
+ const rows = this.readRows(this.currentProps);
776
+ if (!rows) {
777
+ this.activateFallback(afterCommit);
778
+ return;
779
+ }
780
+ const previousKeys = [...this.instances.keys()];
781
+ if (this.hasReactOwnedRows() && (rows.keys.length !== previousKeys.length || rows.keys.some((key, index) => key !== previousKeys[index]))) {
782
+ this.synchronizeReactOwnedRows(afterCommit);
783
+ return;
784
+ }
785
+ const oldIndices = /* @__PURE__ */ new Map();
786
+ const activeElement = this.root.ownerDocument.activeElement;
787
+ const restoreFocus = Boolean(activeElement && this.root.contains(activeElement));
788
+ [...this.instances].forEach(([key], index) => oldIndices.set(key, index));
789
+ const nextKeys = new Set(rows.keys);
790
+ for (const [key, instance] of this.instances) {
791
+ if (!nextKeys.has(key)) instance.element.remove();
792
+ }
793
+ const sequence = rows.keys.map((key) => oldIndices.get(key) ?? -1);
794
+ const stablePositions = longestIncreasingSubsequencePositions(sequence);
795
+ const nextInstances = [];
796
+ const conditionalChanges = [];
797
+ for (let index = 0; index < rows.items.length; index += 1) {
798
+ const key = rows.keys[index];
799
+ const existing = this.instances.get(key);
800
+ if (existing) {
801
+ applyKeyedRowBindings(this.currentProps, existing, rows.items[index], index);
802
+ const conditionalValues = readKeyedRowConditionalValues(
803
+ this.currentProps,
804
+ rows.items[index],
805
+ index
806
+ );
807
+ for (const [id, values] of conditionalValues) {
808
+ if (keyedRowConditionalChanged(existing.conditionalValues.get(id), values)) {
809
+ conditionalChanges.push({ key, id, item: rows.items[index], index });
810
+ }
811
+ }
812
+ existing.conditionalValues = conditionalValues;
813
+ existing.item = rows.items[index];
814
+ existing.index = index;
815
+ nextInstances.push(existing);
816
+ continue;
817
+ }
818
+ const element = createCompilerHostElement(
819
+ this.root.ownerDocument,
820
+ this.currentProps.create(rows.items[index], index)
821
+ );
822
+ nextInstances.push({
823
+ key,
824
+ element,
825
+ values: readKeyedRowBindingValues(this.currentProps, rows.items[index], index),
826
+ item: rows.items[index],
827
+ index,
828
+ conditionalValues: readKeyedRowConditionalValues(
829
+ this.currentProps,
830
+ rows.items[index],
831
+ index
832
+ )
833
+ });
834
+ }
835
+ let anchor = null;
836
+ for (let index = nextInstances.length - 1; index >= 0; index -= 1) {
837
+ const instance = nextInstances[index];
838
+ if (sequence[index] < 0) {
839
+ this.root.insertBefore(instance.element, anchor);
840
+ } else if (!stablePositions.has(index) && instance.element.nextSibling !== anchor) {
841
+ this.root.insertBefore(instance.element, anchor);
842
+ }
843
+ anchor = instance.element;
844
+ }
845
+ this.instances = new Map(nextInstances.map((instance) => [instance.key, instance]));
846
+ this.pruneEventHandlers(rows.keys);
847
+ this.pruneConditionalListeners(rows.keys);
848
+ if (restoreFocus && activeElement?.isConnected && activeElement.ownerDocument.activeElement !== activeElement && "focus" in activeElement) {
849
+ activeElement.focus({ preventScroll: true });
850
+ }
851
+ this.notifyConditionalChanges(conditionalChanges, afterCommit);
852
+ }
853
+ schedulePropSync() {
854
+ if (this.propSyncQueued) return;
855
+ this.propSyncQueued = true;
856
+ queueMicrotask(() => {
857
+ this.propSyncQueued = false;
858
+ if (this.mounted && !this.state.fallback) this.reconcile();
859
+ });
860
+ }
861
+ shouldComponentUpdate(nextProps, nextState) {
862
+ const wasReactOwned = this.hasReactOwnedRows(this.currentProps);
863
+ const willBeReactOwned = this.hasReactOwnedRows(nextProps);
864
+ this.currentProps = nextProps;
865
+ if (nextState.fallback || this.state.fallback) return true;
866
+ if (wasReactOwned || willBeReactOwned) {
867
+ this.eventHandlers.clear();
868
+ return true;
869
+ }
870
+ this.schedulePropSync();
871
+ return false;
872
+ }
873
+ componentDidUpdate(previousProps) {
874
+ if (this.state.fallback || previousProps === this.props || !this.hasReactOwnedRows(previousProps) && !this.hasReactOwnedRows(this.props) || this.adopt()) {
875
+ return;
876
+ }
877
+ this.activateFallback();
878
+ }
879
+ componentDidMount() {
880
+ this.mounted = true;
881
+ this.unsubscribe = owner.subscribe(this.props.id, this.refresh);
882
+ if (!this.adopt()) this.activateFallback();
883
+ }
884
+ componentWillUnmount() {
885
+ this.mounted = false;
886
+ this.unsubscribe?.();
887
+ this.root = null;
888
+ this.instances.clear();
889
+ this.eventHandlers.clear();
890
+ this.conditionalListeners.clear();
891
+ }
892
+ render() {
893
+ this.renderVersion += 1;
894
+ const container = this.currentProps.render(this.rowEvent, this.rowConditional);
895
+ if (!React__default.default.isValidElement(container) || typeof container.type !== "string") {
896
+ throw new TypeError(
897
+ `Compiled keyed rows ${this.currentProps.id} must own one host container.`
898
+ );
899
+ }
900
+ return React__default.default.cloneElement(container, {
901
+ key: this.state.fallback ? `react-${this.fallbackVersion}` : "compiled",
902
+ ref: this.captureRoot
903
+ });
904
+ }
905
+ }
906
+ FarmKeyedRowsBlock.displayName = "FarmCompiledKeyedRows";
907
+ return FarmKeyedRowsBlock;
908
+ }
909
+ function createKeyedRangesBlockComponent(owner) {
910
+ class FarmKeyedRangesBlock extends React__default.default.Component {
911
+ constructor() {
912
+ super(...arguments);
913
+ this.state = { fallback: false };
914
+ this.root = null;
915
+ this.mounted = false;
916
+ this.fallbackRequested = false;
917
+ this.fallbackVersion = 0;
918
+ this.propFallbackQueued = false;
919
+ this.currentProps = this.props;
920
+ this.rangeInstances = [];
921
+ this.staticSegments = [];
922
+ this.captureRoot = (root) => {
923
+ this.root = root;
924
+ this.currentProps.rootRef?.(root);
925
+ };
926
+ this.refresh = (afterCommit) => {
927
+ this.reconcile(afterCommit);
928
+ };
929
+ }
930
+ readRange(range) {
931
+ const source = range.items();
932
+ const items = source ? Array.from(source) : [];
933
+ const keys = items.map((item, index) => keyedRowIdentity(range.rowKey(item, index)));
934
+ if (new Set(keys).size !== keys.length) return null;
935
+ return { items, keys };
936
+ }
937
+ readRanges(props) {
938
+ const ranges = [];
939
+ for (const range of props.ranges) {
940
+ const rows = this.readRange(range);
941
+ if (!rows) return null;
942
+ ranges.push(rows);
943
+ }
944
+ return ranges;
945
+ }
946
+ adopt(props = this.currentProps) {
947
+ if (!this.root || !Number.isSafeInteger(props.trailing) || props.trailing < 0) return false;
948
+ const rowsByRange = this.readRanges(props);
949
+ if (!rowsByRange) return false;
950
+ const elements = [...this.root.children];
951
+ const staticSegments = [];
952
+ const instancesByRange = [];
953
+ let cursor = 0;
954
+ for (let rangeIndex = 0; rangeIndex < props.ranges.length; rangeIndex += 1) {
955
+ const range = props.ranges[rangeIndex];
956
+ const rows = rowsByRange[rangeIndex];
957
+ if (!Number.isSafeInteger(range.before) || range.before < 0) return false;
958
+ const staticEnd = cursor + range.before;
959
+ if (staticEnd > elements.length) return false;
960
+ staticSegments.push(elements.slice(cursor, staticEnd));
961
+ cursor = staticEnd;
962
+ const rowEnd = cursor + rows.items.length;
963
+ if (rowEnd > elements.length) return false;
964
+ const instances = /* @__PURE__ */ new Map();
965
+ for (let index = 0; index < rows.items.length; index += 1) {
966
+ const element = elements[cursor + index];
967
+ if (!matchesCompilerHostElement(element, range.create(rows.items[index], index))) {
968
+ return false;
969
+ }
970
+ instances.set(rows.keys[index], {
971
+ key: rows.keys[index],
972
+ element,
973
+ values: readKeyedRowBindingValues(range, rows.items[index], index),
974
+ item: rows.items[index],
975
+ index,
976
+ conditionalValues: /* @__PURE__ */ new Map()
977
+ });
978
+ }
979
+ instancesByRange.push(instances);
980
+ cursor = rowEnd;
981
+ }
982
+ if (cursor + props.trailing !== elements.length) return false;
983
+ staticSegments.push(elements.slice(cursor));
984
+ this.staticSegments = staticSegments;
985
+ this.rangeInstances = instancesByRange;
986
+ return true;
987
+ }
988
+ anchorAfter(rangeIndex) {
989
+ for (let next = rangeIndex + 1; next < this.rangeInstances.length; next += 1) {
990
+ const staticAnchor = this.staticSegments[next]?.[0];
991
+ if (staticAnchor) return staticAnchor;
992
+ const rowAnchor = this.rangeInstances[next].values().next().value?.element;
993
+ if (rowAnchor) return rowAnchor;
994
+ }
995
+ return this.staticSegments[this.rangeInstances.length]?.[0] || null;
996
+ }
997
+ reconcileRange(rangeIndex, rows) {
998
+ if (!this.root) return;
999
+ const range = this.currentProps.ranges[rangeIndex];
1000
+ const previous = this.rangeInstances[rangeIndex];
1001
+ const oldIndices = /* @__PURE__ */ new Map();
1002
+ [...previous.keys()].forEach((key, index) => oldIndices.set(key, index));
1003
+ const nextKeys = new Set(rows.keys);
1004
+ for (const [key, instance] of previous) {
1005
+ if (!nextKeys.has(key)) instance.element.remove();
1006
+ }
1007
+ const sequence = rows.keys.map((key) => oldIndices.get(key) ?? -1);
1008
+ const stablePositions = longestIncreasingSubsequencePositions(sequence);
1009
+ const nextInstances = [];
1010
+ for (let index = 0; index < rows.items.length; index += 1) {
1011
+ const key = rows.keys[index];
1012
+ const existing = previous.get(key);
1013
+ if (existing) {
1014
+ applyKeyedRowBindings(range, existing, rows.items[index], index);
1015
+ existing.item = rows.items[index];
1016
+ existing.index = index;
1017
+ nextInstances.push(existing);
1018
+ continue;
1019
+ }
1020
+ const element = createCompilerHostElement(
1021
+ this.root.ownerDocument,
1022
+ range.create(rows.items[index], index)
1023
+ );
1024
+ nextInstances.push({
1025
+ key,
1026
+ element,
1027
+ values: readKeyedRowBindingValues(range, rows.items[index], index),
1028
+ item: rows.items[index],
1029
+ index,
1030
+ conditionalValues: /* @__PURE__ */ new Map()
1031
+ });
1032
+ }
1033
+ let anchor = this.anchorAfter(rangeIndex);
1034
+ for (let index = nextInstances.length - 1; index >= 0; index -= 1) {
1035
+ const instance = nextInstances[index];
1036
+ if (sequence[index] < 0) {
1037
+ this.root.insertBefore(instance.element, anchor);
1038
+ } else if (!stablePositions.has(index) && instance.element.nextSibling !== anchor) {
1039
+ this.root.insertBefore(instance.element, anchor);
1040
+ }
1041
+ anchor = instance.element;
1042
+ }
1043
+ this.rangeInstances[rangeIndex] = new Map(
1044
+ nextInstances.map((instance) => [instance.key, instance])
1045
+ );
1046
+ }
1047
+ reconcile(afterCommit) {
1048
+ if (!this.mounted || !this.root) {
1049
+ afterCommit?.();
1050
+ return;
1051
+ }
1052
+ if (this.state.fallback) {
1053
+ this.fallbackVersion += 1;
1054
+ this.forceUpdate(afterCommit);
1055
+ return;
1056
+ }
1057
+ const rowsByRange = this.readRanges(this.currentProps);
1058
+ if (!rowsByRange || rowsByRange.length !== this.rangeInstances.length) {
1059
+ this.activateFallback(afterCommit);
1060
+ return;
1061
+ }
1062
+ const activeElement = this.root.ownerDocument.activeElement;
1063
+ const restoreFocus = Boolean(activeElement && this.root.contains(activeElement));
1064
+ for (let rangeIndex = rowsByRange.length - 1; rangeIndex >= 0; rangeIndex -= 1) {
1065
+ this.reconcileRange(rangeIndex, rowsByRange[rangeIndex]);
1066
+ }
1067
+ if (restoreFocus && activeElement?.isConnected && activeElement.ownerDocument.activeElement !== activeElement && "focus" in activeElement) {
1068
+ activeElement.focus({ preventScroll: true });
1069
+ }
1070
+ afterCommit?.();
1071
+ }
1072
+ activateFallback(afterCommit) {
1073
+ if (!this.mounted || this.state.fallback || this.fallbackRequested) {
1074
+ afterCommit?.();
1075
+ return;
1076
+ }
1077
+ this.fallbackRequested = true;
1078
+ this.setState({ fallback: true }, afterCommit);
1079
+ }
1080
+ schedulePropFallback() {
1081
+ if (this.propFallbackQueued) return;
1082
+ this.propFallbackQueued = true;
1083
+ queueMicrotask(() => {
1084
+ this.propFallbackQueued = false;
1085
+ if (this.mounted && !this.state.fallback) this.activateFallback();
1086
+ });
1087
+ }
1088
+ shouldComponentUpdate(nextProps, nextState) {
1089
+ this.currentProps = nextProps;
1090
+ if (nextState.fallback || this.state.fallback) return true;
1091
+ this.schedulePropFallback();
1092
+ return false;
1093
+ }
1094
+ componentDidMount() {
1095
+ this.mounted = true;
1096
+ this.unsubscribe = owner.subscribe(this.props.id, this.refresh);
1097
+ if (!this.adopt()) this.activateFallback();
1098
+ }
1099
+ componentWillUnmount() {
1100
+ this.mounted = false;
1101
+ this.unsubscribe?.();
1102
+ this.root = null;
1103
+ this.rangeInstances = [];
1104
+ this.staticSegments = [];
1105
+ }
1106
+ render() {
1107
+ const container = this.currentProps.render();
1108
+ if (!React__default.default.isValidElement(container) || typeof container.type !== "string") {
1109
+ throw new TypeError(
1110
+ `Compiled keyed ranges ${this.currentProps.id} must own one host container.`
1111
+ );
1112
+ }
1113
+ return React__default.default.cloneElement(container, {
1114
+ key: this.state.fallback ? `react-${this.fallbackVersion}` : "compiled",
1115
+ ref: this.captureRoot
1116
+ });
1117
+ }
1118
+ }
1119
+ FarmKeyedRangesBlock.displayName = "FarmCompiledKeyedRanges";
1120
+ return FarmKeyedRangesBlock;
1121
+ }
1122
+ function createComponentBlockComponent(owner) {
1123
+ class FarmComponentBlock extends React__default.default.Component {
1124
+ constructor() {
1125
+ super(...arguments);
1126
+ this.refresh = (afterCommit) => {
1127
+ this.forceUpdate(afterCommit);
1128
+ };
1129
+ }
1130
+ subscribe() {
1131
+ this.unsubscribe = owner.subscribe(this.props.id, this.refresh);
1132
+ }
1133
+ componentDidMount() {
1134
+ this.subscribe();
1135
+ }
1136
+ componentDidUpdate(previous) {
1137
+ if (previous.id === this.props.id) return;
1138
+ this.unsubscribe?.();
1139
+ this.subscribe();
1140
+ }
1141
+ componentWillUnmount() {
1142
+ this.unsubscribe?.();
1143
+ }
1144
+ render() {
1145
+ return this.props.render();
1146
+ }
1147
+ }
1148
+ FarmComponentBlock.displayName = "FarmCompiledComponentIsland";
1149
+ return FarmComponentBlock;
1150
+ }
49
1151
  function createCompiledComponent(definition) {
1152
+ const stateSignature = definition.stateSignature || String(definition.initialize.length);
1153
+ if (definition.hmrId) {
1154
+ const registry = getCompilerHmrRegistry();
1155
+ const existing = registry.get(definition.hmrId);
1156
+ if (existing?.stateSignature === stateSignature) {
1157
+ existing.definition.current = definition;
1158
+ existing.component.displayName = `FarmCompiled(${definition.displayName})`;
1159
+ for (const refresh of existing.refreshListeners) refresh();
1160
+ return existing.component;
1161
+ }
1162
+ }
1163
+ const definitionReference = { current: definition };
1164
+ const refreshListeners = /* @__PURE__ */ new Set();
50
1165
  class FarmCompiledComponent extends React__default.default.Component {
51
1166
  constructor(props) {
52
1167
  super(props);
53
1168
  this.root = null;
54
1169
  this.mounted = false;
55
1170
  this.flushQueued = false;
1171
+ this.hasBindingError = false;
1172
+ this.inputSelection = null;
56
1173
  this.dirtyState = /* @__PURE__ */ new Set();
1174
+ this.blockRefreshListeners = /* @__PURE__ */ new Map();
1175
+ this.blockRoots = /* @__PURE__ */ new Map();
1176
+ this.blockRootElements = /* @__PURE__ */ new Set();
1177
+ this.bindingTargets = /* @__PURE__ */ new Map();
1178
+ this.bindingTargetRefs = /* @__PURE__ */ new Map();
57
1179
  this.captureRoot = (root) => {
58
1180
  this.root = root;
59
1181
  };
60
- this.cells = definition.initialize(props).map((initialValue, index) => {
1182
+ this.refreshDefinition = () => {
1183
+ if (this.mounted) this.forceUpdate();
1184
+ };
1185
+ this.cells = definitionReference.current.initialize(props).map((initialValue, index) => {
61
1186
  let value = initialValue;
62
1187
  const pending = [];
63
1188
  return {
@@ -76,13 +1201,87 @@ function createCompiledComponent(definition) {
76
1201
  }
77
1202
  };
78
1203
  });
1204
+ this.blockRuntime = {
1205
+ Conditional: createConditionalBlockComponent({
1206
+ setRoot: (id, root) => this.setBlockRoot(id, root),
1207
+ subscribe: (id, refresh) => this.subscribeToBlock(id, refresh)
1208
+ }),
1209
+ HostConditional: createHostConditionalBlockComponent({
1210
+ subscribe: (id, refresh) => this.subscribeToBlock(id, refresh)
1211
+ }),
1212
+ KeyedList: createKeyedListBlockComponent({
1213
+ subscribe: (id, refresh) => this.subscribeToBlock(id, refresh)
1214
+ }),
1215
+ KeyedRows: createKeyedRowsBlockComponent({
1216
+ subscribe: (id, refresh) => this.subscribeToBlock(id, refresh)
1217
+ }),
1218
+ KeyedRanges: createKeyedRangesBlockComponent({
1219
+ subscribe: (id, refresh) => this.subscribeToBlock(id, refresh)
1220
+ }),
1221
+ Component: createComponentBlockComponent({
1222
+ subscribe: (id, refresh) => this.subscribeToBlock(id, refresh)
1223
+ }),
1224
+ target: (id) => this.bindingTarget(id)
1225
+ };
1226
+ }
1227
+ bindingTarget(id) {
1228
+ const existing = this.bindingTargetRefs.get(id);
1229
+ if (existing) return existing;
1230
+ const capture = (element) => {
1231
+ if (element) {
1232
+ this.bindingTargets.set(id, element);
1233
+ } else {
1234
+ this.bindingTargets.delete(id);
1235
+ }
1236
+ };
1237
+ this.bindingTargetRefs.set(id, capture);
1238
+ return capture;
1239
+ }
1240
+ captureInputSelection() {
1241
+ const active = this.root?.ownerDocument.activeElement;
1242
+ if (!isSelectableTextControl(active) || !this.root?.contains(active) || active.selectionStart === null || active.selectionEnd === null) {
1243
+ return;
1244
+ }
1245
+ this.inputSelection = {
1246
+ element: active,
1247
+ start: active.selectionStart,
1248
+ end: active.selectionEnd,
1249
+ direction: active.selectionDirection || "none"
1250
+ };
1251
+ }
1252
+ restoreInputSelection(snapshot) {
1253
+ if (!snapshot || !snapshot.element.isConnected || snapshot.element.ownerDocument.activeElement !== snapshot.element) {
1254
+ return;
1255
+ }
1256
+ snapshot.element.setSelectionRange(snapshot.start, snapshot.end, snapshot.direction);
1257
+ }
1258
+ setBlockRoot(id, root) {
1259
+ const previous = this.blockRoots.get(id);
1260
+ if (previous) this.blockRootElements.delete(previous);
1261
+ if (root) {
1262
+ this.blockRoots.set(id, root);
1263
+ this.blockRootElements.add(root);
1264
+ } else {
1265
+ this.blockRoots.delete(id);
1266
+ }
1267
+ }
1268
+ subscribeToBlock(id, refresh) {
1269
+ this.blockRefreshListeners.set(id, refresh);
1270
+ return () => {
1271
+ if (this.blockRefreshListeners.get(id) === refresh) {
1272
+ this.blockRefreshListeners.delete(id);
1273
+ }
1274
+ };
79
1275
  }
80
1276
  scheduleBindingFlush(index) {
81
1277
  this.dirtyState.add(index);
1278
+ this.captureInputSelection();
82
1279
  if (!this.mounted || this.flushQueued) return;
83
1280
  this.flushQueued = true;
84
1281
  queueMicrotask(() => {
85
1282
  this.flushQueued = false;
1283
+ const inputSelection = this.inputSelection;
1284
+ this.inputSelection = null;
86
1285
  if (!this.mounted) return;
87
1286
  const dirty = /* @__PURE__ */ new Set();
88
1287
  for (const index2 of this.dirtyState) {
@@ -90,40 +1289,105 @@ function createCompiledComponent(definition) {
90
1289
  }
91
1290
  this.dirtyState.clear();
92
1291
  if (dirty.size === 0) return;
93
- for (const binding of definition.bindings) {
94
- if (binding.dependencies.some((dependency) => dirty.has(dependency))) {
95
- this.applyBinding(binding);
1292
+ try {
1293
+ const bindings = definitionReference.current.bindings;
1294
+ const blockBindings = /* @__PURE__ */ new Map();
1295
+ const affectedBlockIds = /* @__PURE__ */ new Set();
1296
+ for (const binding of bindings) {
1297
+ if (binding.kind !== "block") continue;
1298
+ blockBindings.set(binding.id, binding);
1299
+ if (binding.dependencies.some((dependency) => dirty.has(dependency))) {
1300
+ affectedBlockIds.add(binding.id);
1301
+ }
96
1302
  }
1303
+ const hasAffectedMountedAncestor = (binding) => {
1304
+ let parent = binding.parent;
1305
+ while (parent !== void 0) {
1306
+ if (affectedBlockIds.has(parent) && this.blockRefreshListeners.has(parent)) {
1307
+ return true;
1308
+ }
1309
+ parent = blockBindings.get(parent)?.parent;
1310
+ }
1311
+ return false;
1312
+ };
1313
+ const blockRefreshes = [...affectedBlockIds].map((id) => {
1314
+ const binding = blockBindings.get(id);
1315
+ const refresh = this.blockRefreshListeners.get(id);
1316
+ return binding && refresh && !hasAffectedMountedAncestor(binding) ? refresh : void 0;
1317
+ }).filter(
1318
+ (refresh) => refresh !== void 0
1319
+ );
1320
+ for (const binding of bindings) {
1321
+ if (binding.kind !== "block" && binding.dependencies.some((dependency) => dirty.has(dependency))) {
1322
+ this.applyBinding(binding);
1323
+ }
1324
+ }
1325
+ let pendingBlockCommits = blockRefreshes.length;
1326
+ for (const refresh of blockRefreshes) {
1327
+ refresh(() => {
1328
+ pendingBlockCommits -= 1;
1329
+ if (pendingBlockCommits === 0) this.restoreInputSelection(inputSelection);
1330
+ });
1331
+ }
1332
+ if (blockRefreshes.length === 0) this.restoreInputSelection(inputSelection);
1333
+ } catch (error) {
1334
+ this.bindingError = error;
1335
+ this.hasBindingError = true;
1336
+ this.forceUpdate();
97
1337
  }
98
1338
  });
99
1339
  }
100
1340
  applyBinding(binding) {
101
- if (!this.root) return;
102
- const target = findBindingTarget(this.root, binding.path);
1341
+ if (!this.root || binding.kind === "block") return;
1342
+ const target = binding.target === void 0 ? findBindingTarget(this.root, binding.path, this.blockRootElements) : binding.path.length === 0 ? this.root : this.bindingTargets.get(binding.target) || null;
103
1343
  if (!target) return;
104
1344
  const value = binding.read(this.props, this.cells);
105
1345
  if (binding.kind === "text") {
106
1346
  target.textContent = renderTextValue(value);
1347
+ } else if (binding.kind === "style") {
1348
+ updateStyle(target, binding.name, value);
107
1349
  } else {
108
1350
  updateAttribute(target, binding.name, value);
109
1351
  }
110
1352
  }
111
1353
  componentDidMount() {
112
1354
  this.mounted = true;
1355
+ refreshListeners.add(this.refreshDefinition);
113
1356
  }
114
1357
  componentDidUpdate() {
115
- for (const binding of definition.bindings) this.applyBinding(binding);
1358
+ for (const binding of definitionReference.current.bindings) {
1359
+ if (binding.kind !== "block") this.applyBinding(binding);
1360
+ }
116
1361
  }
117
1362
  componentWillUnmount() {
118
1363
  this.mounted = false;
119
1364
  this.root = null;
120
1365
  this.dirtyState.clear();
1366
+ this.inputSelection = null;
1367
+ this.blockRefreshListeners.clear();
1368
+ this.blockRoots.clear();
1369
+ this.blockRootElements.clear();
1370
+ this.bindingTargets.clear();
1371
+ this.bindingTargetRefs.clear();
1372
+ refreshListeners.delete(this.refreshDefinition);
121
1373
  }
122
1374
  render() {
123
- const element = definition.render(this.props, this.cells);
124
- if (!React__default.default.isValidElement(element) || typeof element.type !== "string") {
1375
+ if (this.hasBindingError) throw this.bindingError;
1376
+ const currentDefinition = definitionReference.current;
1377
+ const element = currentDefinition.render(this.props, this.cells, this.blockRuntime);
1378
+ if (!React__default.default.isValidElement(element)) {
125
1379
  throw new TypeError(
126
- `Compiled component ${definition.displayName} must return one host element.`
1380
+ `Compiled component ${currentDefinition.displayName} must return one host element.`
1381
+ );
1382
+ }
1383
+ if (element.type === this.blockRuntime.KeyedRanges) {
1384
+ return React__default.default.cloneElement(element, {
1385
+ rootRef: this.captureRoot
1386
+ });
1387
+ }
1388
+ if (typeof element.type !== "string") {
1389
+ throw new TypeError(
1390
+ `Compiled component ${currentDefinition.displayName} must return one host element.`
127
1391
  );
128
1392
  }
129
1393
  return React__default.default.cloneElement(element, {
@@ -132,7 +1396,16 @@ function createCompiledComponent(definition) {
132
1396
  }
133
1397
  }
134
1398
  FarmCompiledComponent.displayName = `FarmCompiled(${definition.displayName})`;
135
- return FarmCompiledComponent;
1399
+ const component = FarmCompiledComponent;
1400
+ if (definition.hmrId) {
1401
+ getCompilerHmrRegistry().set(definition.hmrId, {
1402
+ component,
1403
+ definition: definitionReference,
1404
+ refreshListeners,
1405
+ stateSignature
1406
+ });
1407
+ }
1408
+ return component;
136
1409
  }
137
1410
 
138
1411
  exports.createCompiledComponent = createCompiledComponent;