tilia 5.2.0 → 6.0.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.
package/src/Tilia.res CHANGED
@@ -16,15 +16,14 @@ let reraise: 'a => 'b = %raw(`function (e) {
16
16
  throw e
17
17
  }`)
18
18
 
19
- /** Opaque handle for a [changing] subscriber stored in [meta.changes]. */
20
- type changeCb
21
- external makeCb: ((string, 'v) => unit) => changeCb = "%identity"
22
- let callCb: (changeCb, string, 'a) => unit = %raw(`function(cb, k, v) { cb(k, v) }`)
19
+ let rethrow: 'a => 'b = %raw(`function (e) {
20
+ throw e
21
+ }`)
23
22
 
24
23
  %%raw(`
25
24
  function cleanTrace(stack) {
26
25
  if (typeof stack !== "string") return stack;
27
-
26
+
28
27
  const cleaned = ["Exception thrown in computed or observe"];
29
28
  let collapsing = false;
30
29
 
@@ -102,6 +101,7 @@ function(v) {
102
101
  module Object = {
103
102
  type descriptor<'a> = {writable: bool, enumerable: bool, configurable: bool, value: 'a}
104
103
  external hasOwn: ('a, string) => bool = "Object.hasOwn"
104
+ external keys: 'a => array<string> = "Object.keys"
105
105
  external getOwnPropertyDescriptor: ('a, string) => nullable<descriptor<'b>> =
106
106
  "Object.getOwnPropertyDescriptor"
107
107
  let readonly: ('a, string) => bool = (o, k) => {
@@ -119,8 +119,6 @@ module Dict = {
119
119
  @send external get: (t<'a>, string) => nullable<'a> = "get"
120
120
  @send external set: (t<'a>, string, 'b) => unit = "set"
121
121
  @send external delete: (t<'a>, string) => unit = "delete"
122
- @get external size: t<'a> => int = "size"
123
- @send external forEach: (t<'a>, ('a, string) => unit) => unit = "forEach"
124
122
  }
125
123
 
126
124
  type dict<'a> = Dict.t<'a>
@@ -156,6 +154,10 @@ and watchers = {
156
154
  observed: observed,
157
155
  // Set of observers to notify on change.
158
156
  observers: observers,
157
+ // Per-key clear callbacks for installed computed values.
158
+ // Stored here so _clear can trigger back-propagation without
159
+ // creating a closure per computed.
160
+ computes: dict<bool => unit>,
159
161
  }
160
162
  and gc = {
161
163
  mutable active: Set.t<watchers>,
@@ -199,9 +201,7 @@ type rec meta<'a> = {
199
201
  /** Cached child branch meta (nested proxies keyed by property name). */
200
202
  proxied: dict<meta<'a>>,
201
203
  /** Per-key clear callbacks for installed computed values. */
202
- computes: dict<unit => unit>,
203
- /** Optional listeners for [changes]; each cb receives (key, value) from proxy handler. */
204
- mutable changes: nullable<Set.t<changeCb>>,
204
+ computes: dict<bool => unit>,
205
205
  /** The Proxy wrapping [target]. */
206
206
  mutable proxy: 'a,
207
207
  }
@@ -215,14 +215,16 @@ type node<'c> = {
215
215
  /** See [meta.proxied]. */
216
216
  proxied: dict<meta<'c>>,
217
217
  /** See [meta.computes]. */
218
- computes: dict<unit => unit>,
219
- /** See [meta.changes]. */
220
- mutable changes: nullable<Set.t<changeCb>>,
218
+ computes: dict<bool => unit>,
221
219
  }
222
220
 
223
221
  type signal<'a> = {mutable value: 'a}
224
222
  type readonly<'a> = {data: 'a}
225
223
  type setter<'a> = 'a => unit
224
+ type canopy = {
225
+ live: Set.t<string>,
226
+ idle: Set.t<string>,
227
+ }
226
228
  type deriver<'p> = {
227
229
  /**
228
230
  * Return a derived value to be inserted into a tilia object. This is like
@@ -235,8 +237,8 @@ type deriver<'p> = {
235
237
  type tilia = {
236
238
  tilia: 'a. 'a => 'a,
237
239
  carve: 'a. (deriver<'a> => 'a) => 'a,
238
- observe: (unit => unit) => unit,
239
- watch: 'a. (unit => 'a, 'a => unit) => unit,
240
+ observe: (unit => unit) => unit => unit,
241
+ watch: 'a. (unit => 'a, 'a => unit) => unit => unit,
240
242
  batch: (unit => unit) => unit,
241
243
  signal: 'a. 'a => (signal<'a>, setter<'a>),
242
244
  derived: 'a. (unit => 'a) => signal<'a>,
@@ -255,7 +257,7 @@ let _observe = (root, notify) => {
255
257
  observer
256
258
  }
257
259
 
258
- let observeKey = (observed, key) => {
260
+ let observeKey = (observed, key, computes) => {
259
261
  switch Dict.get(observed, key) {
260
262
  | Value(w) => w
261
263
  | _ => {
@@ -264,6 +266,7 @@ let observeKey = (observed, key) => {
264
266
  key,
265
267
  observed,
266
268
  observers: Set.make(),
269
+ computes,
267
270
  }
268
271
  Dict.set(observed, key, w)
269
272
  w
@@ -300,7 +303,7 @@ let flush = root => {
300
303
  }
301
304
  }
302
305
 
303
- let _clear = (observer: observer) => {
306
+ let unwatch = (observer: observer, prune: bool) => {
304
307
  let root = observer.root
305
308
  Array.forEach(observer.observing, watchers => {
306
309
  if (
@@ -311,6 +314,14 @@ let _clear = (observer: observer) => {
311
314
  ) {
312
315
  // Add to gc set
313
316
  Set.add(root.gc.active, watchers)
317
+
318
+ // Prune cold computed dependencies on disposal.
319
+ if prune {
320
+ switch Dict.get(watchers.computes, watchers.key) {
321
+ | Value(clear) => clear(true)
322
+ | _ => ()
323
+ }
324
+ }
314
325
  }
315
326
  })
316
327
  switch root.observer {
@@ -324,6 +335,8 @@ let _clear = (observer: observer) => {
324
335
  }
325
336
  }
326
337
 
338
+ let _clear = (observer: observer) => unwatch(observer, true)
339
+
327
340
  let _ready = (observer: observer, notifyIfChanged: bool) => {
328
341
  ignore(
329
342
  Array.findWithIndex(observer.observing, (w, idx) => {
@@ -333,14 +346,14 @@ let _ready = (observer: observer, notifyIfChanged: bool) => {
333
346
  false
334
347
  }
335
348
  | Changed | Cleared if notifyIfChanged => {
336
- _clear(observer)
349
+ unwatch(observer, false)
337
350
  observer.notify()
338
351
  true // abort find
339
352
  }
340
353
  | _ => {
341
354
  // Cleared or Changed, but without notifyIfChanged.
342
355
  // We need to re-subscribe to the key
343
- let w = observeKey(w.observed, w.key)
356
+ let w = observeKey(w.observed, w.key, w.computes)
344
357
  ignore(Set.add(w.observers, observer))
345
358
  observer.observing[idx] = w
346
359
  false
@@ -360,11 +373,16 @@ let _ready = (observer: observer, notifyIfChanged: bool) => {
360
373
  }
361
374
  }
362
375
 
363
- let ownKeys = (root: root, observed: dict<watchers>, target: 'a): 'b => {
376
+ let ownKeys = (
377
+ root: root,
378
+ observed: dict<watchers>,
379
+ computes: dict<bool => unit>,
380
+ target: 'a,
381
+ ): 'b => {
364
382
  let keys = Reflect.ownKeys(target)
365
383
  switch root.observer {
366
384
  | Value(o) => {
367
- let w = observeKey(observed, indexKey)
385
+ let w = observeKey(observed, indexKey, computes)
368
386
  Array.push(o.observing, w)
369
387
  }
370
388
  | _ => ()
@@ -383,7 +401,7 @@ let notify = (root, observed, key) => {
383
401
 
384
402
  // Notify
385
403
  Set.forEach(watchers.observers, observer => {
386
- _clear(observer)
404
+ unwatch(observer, false)
387
405
  Set.add(expired, observer)
388
406
  })
389
407
 
@@ -471,7 +489,6 @@ let rec set = (
471
489
  switch Reflect.set(target, key, value) {
472
490
  | false => false
473
491
  | true =>
474
- let writeKey = key
475
492
  let key = if isArray && key === "length" {
476
493
  indexKey
477
494
  } else {
@@ -486,19 +503,13 @@ let rec set = (
486
503
  switch Dict.get(node.computes, key) {
487
504
  | Value(clear) => {
488
505
  Dict.delete(node.computes, key)
489
- clear()
506
+ clear(false)
490
507
  }
491
508
  | _ => ()
492
509
  }
493
510
  }
494
511
  switch Typeof.dynamic(value) {
495
512
  | Undefined | Null => {
496
- if !fromComputed {
497
- switch node.changes {
498
- | Value(cbs) => Set.forEach(cbs, cb => callCb(cb, writeKey, value))
499
- | _ => ()
500
- }
501
- }
502
513
  notify(node.root, node.observed, key)
503
514
  if !hadKey {
504
515
  // new key: trigger index
@@ -584,13 +595,15 @@ and compile = (node: node<'c>, isArray: bool, target: 'a, key: string, callback:
584
595
  callback()
585
596
  } catch {
586
597
  | _e => {
587
- setError(node.root, %raw(`_e`))
588
598
  _clear(o)
589
- switch previous {
590
- | Value(previous) => _clear(previous)
591
- | _ => ()
592
- }
593
- lastValue.v
599
+ node.root.observer = previous
600
+ // A blown computed must never run again: replace its rebuild with a
601
+ // stub rethrowing the original error and keep the compiled marker in
602
+ // the slot so every read surfaces the error (writing the key clears
603
+ // the failure along with the compute).
604
+ compute.rebuild = () => rethrow(%raw(`_e`))
605
+ ignore(Reflect.set(target, key, compiled))
606
+ rethrow(%raw(`_e`))
594
607
  }
595
608
  }
596
609
 
@@ -611,14 +624,16 @@ and compile = (node: node<'c>, isArray: bool, target: 'a, key: string, callback:
611
624
  }
612
625
  compute.rebuild = rebuild
613
626
 
614
- let clear = () => {
615
- // Clear our cache clearing observer
627
+ let clear = reset => {
616
628
  switch observer.o {
617
629
  | Value(o) => {
618
630
  _clear(o)
619
- // Empty in case "ready" is called after clear (but we only
620
- // do this for computed).
621
631
  ignore(%raw(`o.observing.length = 0`))
632
+ if reset {
633
+ // Keep lastValue, but force the next read to rebuild.
634
+ ignore(Dict.delete(node.proxied, key))
635
+ ignore(Reflect.set(target, key, compiled))
636
+ }
622
637
  }
623
638
  | _ => ()
624
639
  }
@@ -633,14 +648,10 @@ let deleteProperty = (node: node<'c>, target: 'a, key: string) => {
633
648
  switch Dict.get(node.computes, key) {
634
649
  | Value(clear) => {
635
650
  Dict.delete(node.computes, key)
636
- clear()
651
+ clear(false)
637
652
  }
638
653
  | _ => ()
639
654
  }
640
- switch node.changes {
641
- | Value(cbs) => Set.forEach(cbs, cb => callCb(cb, key, %raw(`undefined`)))
642
- | _ => ()
643
- }
644
655
  notify(node.root, node.observed, key)
645
656
  res
646
657
  }
@@ -661,10 +672,10 @@ let rec get = (node: node<'c>, meta: meta<'a>, isArray: bool, target: 'a, key: s
661
672
  switch node.root.observer {
662
673
  | Value(o) =>
663
674
  if isArray && key == "length" {
664
- let w = observeKey(node.observed, indexKey)
675
+ let w = observeKey(node.observed, indexKey, node.computes)
665
676
  Array.push(o.observing, w)
666
677
  } else {
667
- let w = observeKey(node.observed, key)
678
+ let w = observeKey(node.observed, key, node.computes)
668
679
  Array.push(o.observing, w)
669
680
  }
670
681
  | _ => ()
@@ -708,7 +719,6 @@ and proxify = (root: root, target: 'a): meta<'a> => {
708
719
  observed: Dict.make(),
709
720
  proxied: Dict.make(),
710
721
  computes: Dict.make(),
711
- changes: Undefined,
712
722
  }
713
723
  let meta: meta<'a> = %raw(`(node.target = target, node)`)
714
724
  let isArray = Typeof.array(target)
@@ -718,7 +728,7 @@ and proxify = (root: root, target: 'a): meta<'a> => {
718
728
  "set": set(node, isArray, false, ...),
719
729
  "deleteProperty": deleteProperty(node, ...),
720
730
  "get": get(node, meta, isArray, ...),
721
- "ownKeys": ownKeys(node.root, node.observed, ...),
731
+ "ownKeys": ownKeys(node.root, node.observed, node.computes, ...),
722
732
  },
723
733
  )
724
734
  meta.proxy = proxy
@@ -769,8 +779,10 @@ let makeCarve = (root: root) =>
769
779
 
770
780
  let makeObserve = (root: root) =>
771
781
  (callback: unit => unit) => {
782
+ let clear = ref(() => ())
772
783
  let rec notify = () => {
773
784
  let o = _observe(root, notify)
785
+ clear := (() => _clear(o))
774
786
  try {
775
787
  callback()
776
788
  _ready(o, true)
@@ -782,12 +794,15 @@ let makeObserve = (root: root) =>
782
794
  }
783
795
  }
784
796
  notify()
797
+ () => clear.contents()
785
798
  }
786
799
 
787
800
  let makeWatch = (root, observe_) =>
788
801
  (callback: unit => 'a, effect: 'a => unit) => {
802
+ let clear = ref(() => ())
789
803
  let rec notify = () => {
790
804
  let o = observe_(notify)
805
+ clear := (() => _clear(o))
791
806
  let v = callback()
792
807
  _done(o)
793
808
  if root.lock {
@@ -801,8 +816,10 @@ let makeWatch = (root, observe_) =>
801
816
  }
802
817
  // First registration: effect not called
803
818
  let o = observe_(notify)
819
+ clear := (() => _clear(o))
804
820
  ignore(callback())
805
821
  _ready(o, false)
822
+ () => clear.contents()
806
823
  }
807
824
 
808
825
  let makeBatch = (root: root) =>
@@ -817,7 +834,7 @@ let makeBatch = (root: root) =>
817
834
  }
818
835
  }
819
836
 
820
- let orphanError = "Cannot modify or access the value of an orphan computation. See https://tiliajs.com/errors#orphan"
837
+ let orphanError = "Cannot modify or access the value of an orphan computation. See https://tiliajs.dev/errors#orphan"
821
838
 
822
839
  let warningHandler = () =>
823
840
  {
@@ -905,9 +922,9 @@ external connector: (
905
922
  // carve
906
923
  (deriver<'c> => 'c) => 'c,
907
924
  // observe
908
- (unit => unit) => unit,
925
+ (unit => unit) => unit => unit,
909
926
  // watch
910
- (unit => 'w, 'w => unit) => unit,
927
+ (unit => 'w, 'w => unit) => unit => unit,
911
928
  // batch
912
929
  (unit => unit) => unit,
913
930
  // extra
@@ -999,106 +1016,23 @@ let readonly = (data: 'a) => {
999
1016
 
1000
1017
  let lift = s => computed(() => s.value)
1001
1018
 
1002
- type changes<'a> = {upsert: array<'a>, remove: array<string>}
1003
- type changing<'a> = {changes: unit => changes<'a>, mute: (unit => unit) => unit}
1004
-
1005
- type changeCounter = {mutable changed: int}
1006
-
1007
- let _changing = (accessor: unit => 'a, guard: option<unit => bool>): changing<'a> => {
1008
- let empty: changes<'a> = {upsert: [], remove: []}
1009
- let meta = switch _meta(accessor()) {
1019
+ let _canopy = proxy => {
1020
+ let meta = switch _meta(proxy) {
1010
1021
  | Value(m) => m
1011
- | _ => raise("changing: argument is not a tilia proxy")
1022
+ | _ => raise("_canopy: argument is not a tilia proxy")
1012
1023
  }
1013
- let root = meta.root
1014
- let pending: dict<nullable<'a>> = Dict.make()
1015
- let counter = proxify(root, {changed: 0}).proxy
1016
- let currentMeta = ref(meta)
1017
-
1018
- let register = (m: meta<'a>, cb) => {
1019
- let cbs = switch m.changes {
1020
- | Value(cbs) => cbs
1021
- | _ => {
1022
- let cbs = Set.make()
1023
- m.changes = Value(cbs)
1024
- cbs
1025
- }
1024
+ flush(meta.root)
1025
+ let live = Set.make()
1026
+ let idle = Set.make()
1027
+ Object.keys(meta.target)->Array.forEach(key => {
1028
+ switch Dict.get(meta.observed, key) {
1029
+ | Value(w) if w.state === Pristine && Set.size(w.observers) > 0 => Set.add(live, key)
1030
+ | _ => Set.add(idle, key)
1026
1031
  }
1027
- Set.add(cbs, cb)
1028
- cbs
1029
- }
1030
-
1031
- let drain = () => {
1032
- let upsert = []
1033
- let remove = []
1034
- Dict.forEach(pending, (v, k) => {
1035
- switch v {
1036
- | Value(x) => Array.push(upsert, x)
1037
- | _ => Array.push(remove, k)
1038
- }
1039
- Dict.delete(pending, k)
1040
- })
1041
- {upsert, remove}
1042
- }
1043
-
1044
- let cb = makeCb((key, value) => {
1045
- Dict.set(pending, key, value)
1046
- counter.changed = counter.changed + 1
1047
1032
  })
1048
-
1049
- let currentCbs = ref(register(meta, cb))
1050
-
1051
- let reregister = () => {
1052
- switch _meta(accessor()) {
1053
- | Value(m) if m !== currentMeta.contents => {
1054
- ignore(Set.delete(currentCbs.contents, cb))
1055
- currentCbs := register(m, cb)
1056
- currentMeta := m
1057
- }
1058
- | _ => ()
1059
- }
1060
- }
1061
-
1062
- // Subscribe the current observer to [counter.changed] through the proxy.
1063
- let read = () => ignore((Reflect.get(counter, "changed"): int))
1064
-
1065
- let capture = switch guard {
1066
- | Some(g) => () => {
1067
- reregister()
1068
- if !g() {
1069
- empty
1070
- } else {
1071
- read()
1072
- Dict.size(pending) > 0 ? drain() : empty
1073
- }
1074
- }
1075
- | _ => () => {
1076
- reregister()
1077
- read()
1078
- Dict.size(pending) > 0 ? drain() : empty
1079
- }
1080
- }
1081
-
1082
- let mute = fn => {
1083
- reregister()
1084
- ignore(Set.delete(currentCbs.contents, cb))
1085
- if root.lock {
1086
- fn()
1087
- } else {
1088
- root.lock = true
1089
- fn()
1090
- root.lock = false
1091
- flush(root)
1092
- }
1093
- Set.add(currentCbs.contents, cb)
1094
- }
1095
-
1096
- {changes: capture, mute}
1033
+ {live, idle}
1097
1034
  }
1098
1035
 
1099
- external identity: 'a => 'b = "%identity"
1100
- let changing = (accessor, ~guard=?) => _changing(identity(accessor), guard)
1101
-
1102
1036
  let tilia = _ctx.tilia
1103
1037
  let carve = _ctx.carve
1104
1038
  let observe = _ctx.observe
package/src/Tilia.resi CHANGED
@@ -34,10 +34,12 @@ type tilia = {
34
34
  * default context.
35
35
  *
36
36
  * This uses a PUSH model: changes "push" the callback to run.
37
- *
37
+ *
38
38
  * For a PULL model (run only when a value is read), see `computed`.
39
+ *
40
+ * @return A function to stop observing.
39
41
  */
40
- observe: (unit => unit) => unit,
42
+ observe: (unit => unit) => unit => unit,
41
43
  /**
42
44
  * React to value changes.
43
45
  *
@@ -47,8 +49,9 @@ type tilia = {
47
49
  *
48
50
  * @param f The capture function.
49
51
  * @param m The effect function.
52
+ * @return A function to stop watching.
50
53
  */
51
- watch: 'a. (unit => 'a, 'a => unit) => unit,
54
+ watch: 'a. (unit => 'a, 'a => unit) => unit => unit,
52
55
  /**
53
56
  * Run a series of operations in a batch, blocking notifications until the
54
57
  * batch is complete.
@@ -139,8 +142,9 @@ let carve: (deriver<'a> => 'a) => 'a
139
142
  * (run only when a value is read), see `computed`.
140
143
  *
141
144
  * @param f The callback to run on changes.
145
+ * @return A function to stop observing.
142
146
  */
143
- let observe: (unit => unit) => unit
147
+ let observe: (unit => unit) => unit => unit
144
148
 
145
149
  /**
146
150
  * React to changes of captured values.
@@ -155,8 +159,9 @@ let observe: (unit => unit) => unit
155
159
  *
156
160
  * @param f1 The function that captures values to observe.
157
161
  * @param f2 The function called when the captured values change.
162
+ * @return A function to stop watching.
158
163
  */
159
- let watch: (unit => 'a, 'a => unit) => unit
164
+ let watch: (unit => 'a, 'a => unit) => unit => unit
160
165
 
161
166
  /**
162
167
  * Run a series of operations in a batch, blocking notifications until the batch
@@ -245,30 +250,6 @@ let source: ('a, ('a, 'a => unit) => 'ignored) => 'a
245
250
  */
246
251
  let store: (('a => unit) => 'a) => 'a
247
252
 
248
- /**
249
- * Track key-level writes on a tilia-proxied dict.
250
- *
251
- * Takes an accessor `() => dict<'a>` so the tracker can follow source swaps.
252
- *
253
- * Returns `{ changes, mute }`:
254
- * - `changes`: capture function for `watch`. Drains accumulated changes into
255
- * `{ upsert, remove }`. `upsert` contains objects captured at write time.
256
- * `remove` contains keys of deleted entries. Last write wins per key.
257
- * - `mute`: run a callback with this tracker's dirty tracking temporarily
258
- * removed. Writes inside `mute` are still reactive but not tracked.
259
- * Includes `batch` internally for atomicity.
260
- *
261
- * When a `guard` is provided and returns false, changes accumulate silently
262
- * without triggering the watcher. When the guard becomes true, the
263
- * effect fires with all accumulated changes.
264
- *
265
- * @param accessor Function returning the tilia-proxied dict to track.
266
- * @param ~guard Optional reactive guard function.
267
- */
268
- type changes<'a> = {upsert: array<'a>, remove: array<string>}
269
- type changing<'a> = {changes: unit => changes<'a>, mute: (unit => unit) => unit}
270
- let changing: (unit => dict<'a>, ~guard: unit => bool=?) => changing<'a>
271
-
272
253
  /** ---------- Internal types and functions for library developers ---------- */
273
254
  /**
274
255
  * Internal: Register an observer callback.
@@ -297,6 +278,20 @@ let _clear: observer => unit
297
278
  */
298
279
  let _meta: 'a => nullable<'b>
299
280
 
281
+ /**
282
+ * Internal: Type used by _canopy.
283
+ */
284
+ type canopy = {
285
+ live: Set.t<string>,
286
+ idle: Set.t<string>,
287
+ }
288
+
289
+ /**
290
+ * Internal: Inspect which keys have observers (live) versus
291
+ * the ones that are not observed (idle).
292
+ */
293
+ let _canopy: 'a => canopy
294
+
300
295
  /**
301
296
  * Internal: The default tilia context.
302
297
  */