-
Notifications
You must be signed in to change notification settings - Fork 108
/
Binding.scala
1388 lines (1132 loc) · 40.6 KB
/
Binding.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
The MIT License (MIT)
Copyright (c) 2016 Yang Bo & REA Group Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thoughtworks.binding
import java.util.EventObject
import com.thoughtworks.sde.core.MonadicFactory._
import com.thoughtworks.enableMembersIf
import com.thoughtworks.sde.core.MonadicFactory
import macrocompat.bundle
import scala.annotation.tailrec
import scala.concurrent.{ExecutionContext, Future}
import scala.language.implicitConversions
import scala.language.higherKinds
import scala.collection.GenSeq
import scala.collection.mutable.Buffer
import scala.util.Try
import scalaz.{Monad, MonadPlus}
import scala.language.experimental.macros
/**
* @groupname typeClasses Type class instance
* @groupname implicits Implicits Conversions
* @groupname expressions Binding Expressions
* @groupdesc expressions AST nodes of binding expressions
* @author 杨博 (Yang Bo) <pop.atry@gmail.com>
*/
object Binding extends MonadicFactory.WithTypeClass[Monad, Binding] {
override val typeClass = BindingInstances
@enableMembersIf(c => !c.compilerSettings.exists(_.matches("""^-Xplugin:.*scalajs-compiler_[0-9\.\-]*\.jar$""")))
private[Binding] object Jvm {
def newBuffer[A] = collection.mutable.ArrayBuffer.empty[A]
def toCacheData[A](seq: Seq[A]) = seq.toVector
def emptyCacheData[A]: HasCache[A]#Cache = Vector.empty
trait HasCache[A] {
private[Binding] type Cache = Vector[A]
private[Binding] var cacheData: Cache
@inline
private[Binding] final def getCache(n:Int): A = cacheData(n)
@inline
private[Binding] final def updateCache(n:Int, newelem: A): Unit = {
cacheData = cacheData.updated(n, newelem)
}
@inline
private[Binding] final def cacheLength: Int = cacheData.length
@inline
private[Binding] final def clearCache(): Unit = {
cacheData = Vector.empty
}
private[Binding] final def removeCache(n: Int): A = {
val result = cacheData(n)
cacheData = cacheData.patch(n, Nil, 1)
result
}
private[Binding] final def appendCache(elements: TraversableOnce[A]): GenSeq[A] = {
val seq = elements.toVector
cacheData = cacheData ++ seq
seq
}
private[Binding] final def appendCache(elem: A): Unit = {
cacheData = cacheData :+ elem
}
private[Binding] final def prependCache(elem: A): Unit = {
cacheData = elem +: cacheData
}
private[Binding] final def insertCache(n: Int, elems: Traversable[A]): GenSeq[A] = {
val seq = elems.toSeq
cacheData = cacheData.patch(n, seq, 0)
seq
}
private[Binding] final def cacheIterator: Iterator[A] = {
cacheData.iterator
}
private[Binding] final def spliceCache(from: Int, mappedNewChildren: Cache, replaced: Int):TraversableOnce[A] = {
val oldCache = cacheData
if (from == 0) {
cacheData = mappedNewChildren ++ oldCache.drop(replaced)
} else {
cacheData = oldCache.patch(from, mappedNewChildren, replaced)
}
oldCache.view(from, replaced)
}
private[Binding] final def indexOfCache[B >: A](a: B): Int = {
cacheData.indexOf(a)
}
}
}
@enableMembersIf(c => c.compilerSettings.exists(_.matches("""^-Xplugin:.*scalajs-compiler_[0-9\.\-]*\.jar$""")))
private[Binding] object Js {
@inline
def newBuffer[A] = new scalajs.js.Array[A]
@inline
implicit final class ReduceToSizeOps[A] @inline()(array: scalajs.js.Array[A]) {
@inline def reduceToSize(newSize: Int) = array.length = newSize
}
@inline
def toCacheData[A](seq: Seq[A]) = {
import scalajs.js.JSConverters._
seq.toJSArray
}
@inline
def emptyCacheData[A]: HasCache[A]#Cache = scalajs.js.Array()
trait HasCache[A] {
private[Binding] type Cache = scalajs.js.Array[A]
private[Binding] def cacheData: Cache
@inline
private[Binding] final def getCache(n: Int): A = cacheData(n)
@inline
private[Binding] final def updateCache(n:Int, newelem: A): Unit = {
cacheData(n) = newelem
}
@inline
private[Binding] final def cacheLength: Int = cacheData.length
@inline
private[Binding] final def clearCache(): Unit = {
cacheData.length = 0
}
@inline
private[Binding] final def removeCache(n: Int): A = {
cacheData.remove(n)
}
@inline
private[Binding] final def appendCache(elements: TraversableOnce[A]): GenSeq[A] = {
val seq = elements.toSeq
cacheData ++= seq
seq
}
@inline
private[Binding] final def appendCache(elem: A): Unit = {
cacheData += elem
}
@inline
private[Binding] final def prependCache(elem: A): Unit = {
cacheData.unshift(elem)
}
@inline
private[Binding] final def insertCache(n: Int, elems: Traversable[A]): GenSeq[A] = {
val seq = elems.toSeq
cacheData.insertAll(n, elems)
seq
}
@inline
private[Binding] final def cacheIterator: Iterator[A] = {
cacheData.iterator
}
@inline
private[Binding] final def spliceCache(from: Int, mappedNewChildren: Cache, replaced: Int):TraversableOnce[A] = {
cacheData.splice(from, replaced, mappedNewChildren: _*)
}
@inline
private[Binding] final def indexOfCache[B >: A](a: B): Int = {
cacheData.indexOf(a)
}
}
}
import Js._
import Jvm._
private object Publisher {
private[Publisher] sealed trait State
case object Idle extends State
case object CleanForeach extends State
case object DirtyForeach extends State
}
private[binding] final class Publisher[Subscriber >: Null] {
import Publisher._
private val subscribers = newBuffer[Subscriber]
@volatile
private var state: State = Idle
@inline
def nonEmpty = !isEmpty
@inline
def isEmpty = subscribers.forall(_ == null)
def foreach[U](f: Subscriber => U): Unit = {
state match {
case Idle =>
state = CleanForeach
subscribers.withFilter(_ != null).foreach(f)
state match {
case DirtyForeach => {
@tailrec
def compact(i: Int, j: Int): Unit = {
if (i < subscribers.length) {
val subscriber = subscribers(i)
if (subscriber == null) {
compact(i + 1, j)
} else {
subscribers(j) = subscriber
compact(i + 1, j + 1)
}
} else {
subscribers.reduceToSize(j)
}
}
compact(0, 0)
state = Idle
}
case CleanForeach =>
state = Idle
case Idle =>
throw new IllegalStateException("Expect CleanForeach or DirtyForeach")
}
case CleanForeach | DirtyForeach =>
subscribers.withFilter(_ != null).foreach(f)
}
}
@inline
def subscribe(subscriber: Subscriber): Unit = {
subscribers += subscriber
}
@inline
def unsubscribe(subscriber: Subscriber): Unit = {
state match {
case Idle =>
subscribers -= subscriber
case CleanForeach =>
subscribers(subscribers.indexOf(subscriber)) = null
state = DirtyForeach
case DirtyForeach =>
subscribers(subscribers.indexOf(subscriber)) = null
}
}
}
private[binding] final class ChangedEvent[+Value](source: AnyRef,
val newValue: Value) extends EventObject(source) {
override def toString = raw"""ChangedEvent[source=$source newValue=$newValue]"""
}
private[binding] final class PatchedEvent[+Element](source: AnyRef,
val from: Int,
val that: GenSeq[Element],
val replaced: Int) extends EventObject(source) {
override def toString = raw"""PatchedEvent[source=$source from=$from that=$that replaced=$replaced]"""
}
private[binding] trait ChangedListener[-Value] {
private[binding] def changed(event: ChangedEvent[Value]): Unit
}
private[binding] trait PatchedListener[-Element] {
private[binding] def patched(event: PatchedEvent[Element]): Unit
}
/**
* A data binding expression that never changes.
*
* @group expressions
*/
final case class Constant[+A](override val get: A) extends AnyVal with Binding[A] {
@inline
override private[binding] def removeChangedListener(listener: ChangedListener[A]): Unit = {
// Do nothing because this Constant never changes
}
@inline
override private[binding] def addChangedListener(listener: ChangedListener[A]): Unit = {
// Do nothing because this Constant never changes
}
}
/**
* @group expressions
*/
object Var {
@inline
def apply[A](initialValue: A) = new Var(initialValue)
}
/**
* Source variable of data binding expression.
*
* You can manually change the value:
*
* {{{
* val bindingVar = Var("initial value")
* bindingVar := "changed value"
* }}}
*
* Then, any data binding expressions that depend on this [[Var]] will be changed automatically.
*
* @group expressions
*/
final class Var[A](private var value: A) extends Binding[A] {
private val publisher = new Publisher[ChangedListener[A]]
@inline
override def get: A = {
value
}
/**
* Changes the current value of this [[Var]], and reevaluates any expressions that depends on this [[Var]].
*
* @note This method must not be invoked inside a `@dom` method body.
*/
def :=(newValue: A): Unit = {
if (value != newValue) {
value = newValue
val event = new ChangedEvent(this, newValue)
for (listener <- publisher) {
listener.changed(event)
}
}
}
@inline
override private[binding] def removeChangedListener(listener: ChangedListener[A]): Unit = {
publisher.unsubscribe(listener)
}
@inline
override private[binding] def addChangedListener(listener: ChangedListener[A]): Unit = {
publisher.subscribe(listener)
}
}
private final class Map[A, B](upstream: Binding[A], f: A => B)
extends Binding[B] with ChangedListener[A] {
private val publisher = new Publisher[ChangedListener[B]]
private var cache: B = f(upstream.get)
@inline
override private[binding] def get: B = {
cache
}
@inline
override private[binding] def addChangedListener(listener: ChangedListener[B]): Unit = {
if (publisher.isEmpty) {
upstream.addChangedListener(this)
}
publisher.subscribe(listener)
}
@inline
override private[binding] def removeChangedListener(listener: ChangedListener[B]): Unit = {
publisher.unsubscribe(listener)
if (publisher.isEmpty) {
upstream.removeChangedListener(this)
}
}
override final def changed(upstreamEvent: ChangedEvent[A]): Unit = {
val oldCache = cache
val newCache = f(upstreamEvent.newValue)
cache = newCache
if (oldCache != newCache) {
val event = new ChangedEvent(Map.this, newCache)
for (listener <- publisher) {
listener.changed(event)
}
}
}
}
private final class FlatMap[A, B](upstream: Binding[A], f: A => Binding[B])
extends Binding[B] with ChangedListener[B] {
private val publisher = new Publisher[ChangedListener[B]]
private val forwarder = new ChangedListener[A] {
override final def changed(upstreamEvent: ChangedEvent[A]): Unit = {
val oldCache = cache
oldCache.removeChangedListener(FlatMap.this)
val newCache = f(upstreamEvent.newValue)
cache = newCache
newCache.addChangedListener(FlatMap.this)
if (oldCache.get != newCache.get) {
val event = new ChangedEvent(FlatMap.this, newCache.get)
for (listener <- publisher) {
listener.changed(event)
}
}
}
}
@inline
override private[binding] def changed(upstreamEvent: ChangedEvent[B]) = {
val event = new ChangedEvent(FlatMap.this, upstreamEvent.newValue)
for (listener <- publisher) {
listener.changed(event)
}
}
@inline
override private[binding] def addChangedListener(listener: ChangedListener[B]): Unit = {
if (publisher.isEmpty) {
upstream.addChangedListener(forwarder)
cache.addChangedListener(this)
}
publisher.subscribe(listener)
}
private var cache: Binding[B] = f(upstream.get)
override private[binding] def get: B = {
@tailrec
@inline
def tailrecGetValue(binding: Binding[B]): B = {
binding match {
case flatMap: FlatMap[_, B] => tailrecGetValue(flatMap.cache)
case _ => binding.get
}
}
tailrecGetValue(cache)
}
override private[binding] def removeChangedListener(listener: ChangedListener[B]): Unit = {
publisher.unsubscribe(listener)
if (publisher.isEmpty) {
upstream.removeChangedListener(forwarder)
cache.removeChangedListener(this)
}
}
}
/**
* Monad instances for [[Binding]].
*
* @group typeClasses
*/
implicit object BindingInstances extends Monad[Binding] {
@inline
override def map[A, B](fa: Binding[A])(f: A => B): Binding[B] = {
fa match {
case Constant(a) =>
Constant(f(a))
case _ =>
new Map[A, B](fa, f)
}
}
@inline
override def bind[A, B](fa: Binding[A])(f: A => Binding[B]): Binding[B] = {
fa match {
case Constant(a) =>
f(a)
case _ =>
new FlatMap[A, B](fa, f)
}
}
@inline
override def point[A](a: => A): Binding[A] = Constant(a)
@inline
override def ifM[B](value: Binding[Boolean], ifTrue: => Binding[B], ifFalse: => Binding[B]): Binding[B] = {
bind(value)(if (_) ifTrue else ifFalse)
}
@inline
override def whileM[G[_], A](p: Binding[Boolean], body: => Binding[A])(implicit G: MonadPlus[G]): Binding[G[A]] = {
ifM(p, bind(body)(x => map(whileM(p, body))(xs => G.plus(G.point(x), xs))), point(G.empty))
}
@inline
override def whileM_[A](p: Binding[Boolean], body: => Binding[A]): Binding[Unit] = {
ifM(p, bind(body)(_ => whileM_(p, body)), point(()))
}
@inline
override def untilM[G[_], A](f: Binding[A], cond: => Binding[Boolean])(implicit G: MonadPlus[G]): Binding[G[A]] = {
bind(f)(x => map(whileM(map(cond)(!_), f))(xs => G.plus(G.point(x), xs)))
}
@inline
override def untilM_[A](f: Binding[A], cond: => Binding[Boolean]): Binding[Unit] = {
bind(f)(_ => whileM_(map(cond)(!_), f))
}
}
@bundle
private[Binding] class Macros(val c: scala.reflect.macros.blackbox.Context) {
import c.universe._
final def map(f: Tree): Tree = {
val apply@Apply(TypeApply(Select(self, TermName("map")), List(b)), List(f@Function(vparams, body))) = c.macroApplication
val monadicBody =
q"""_root_.com.thoughtworks.binding.Binding.apply[$b]($body)"""
val monadicFunction = atPos(f.pos)(Function(vparams, monadicBody))
atPos(apply.pos)(q"""$self.mapBinding[$b]($monadicFunction)""")
}
final def flatMap(f: Tree): Tree = {
val apply@Apply(TypeApply(Select(self, TermName("flatMap")), List(b)), List(f@Function(vparams, body))) = c.macroApplication
val monadicBody =
q"""_root_.com.thoughtworks.binding.Binding.apply[_root_.com.thoughtworks.binding.Binding.BindingSeq[$b]]($body)"""
val monadicFunction = atPos(f.pos)(Function(vparams, monadicBody))
atPos(apply.pos)(q"""$self.flatMapBinding[$b]($monadicFunction)""")
}
final def withFilter(condition: Tree): Tree = {
val apply@Apply(Select(self, TermName("withFilter")), List(f@Function(vparams, body))) = c.macroApplication
val monadicBody =
q"""_root_.com.thoughtworks.binding.Binding.apply[_root_.scala.Boolean]($body)"""
val monadicFunction = atPos(f.pos)(Function(vparams, monadicBody))
atPos(apply.pos)(q"""$self.withFilterBinding($monadicFunction)""")
}
final def bind: Tree = {
val q"$binding.$methodName" = c.macroApplication
q"""_root_.com.thoughtworks.sde.core.MonadicFactory.Instructions.each[
_root_.com.thoughtworks.binding.Binding,
${TypeTree(c.macroApplication.tpe)}
]($binding)"""
}
}
private[binding] final case class Length(bindingSeq: BindingSeq[_]) extends Binding[Int] with PatchedListener[Any] {
private val publisher = new Publisher[ChangedListener[Int]]
@inline
override private[binding] def get: Int = bindingSeq.get.length
@inline
override private[binding] def removeChangedListener(listener: ChangedListener[Int]): Unit = {
publisher.unsubscribe(listener)
if (publisher.isEmpty) {
bindingSeq.removePatchedListener(this)
}
}
@inline
override private[binding] def addChangedListener(listener: ChangedListener[Int]): Unit = {
if (publisher.isEmpty) {
bindingSeq.addPatchedListener(this)
}
publisher.subscribe(listener)
}
@inline
override private[binding] def patched(upstreamEvent: PatchedEvent[Any]): Unit = {
val event = new ChangedEvent[Int](this, bindingSeq.get.length)
for (subscriber <- publisher) {
subscriber.changed(event)
}
}
}
private[binding] case class SingleSeq[+A](element: A) extends collection.immutable.IndexedSeq[A] {
@inline
override final def length: Int = 1
@inline
override final def apply(idx: Int) = {
if (idx == 0) {
element
} else {
throw new IndexOutOfBoundsException
}
}
@inline
override final def iterator = Iterator.single(element)
}
private[binding] object Empty extends BindingSeq[Nothing] {
@inline
override private[binding] def removePatchedListener(listener: PatchedListener[Nothing]): Unit = {}
@inline
override private[binding] def addPatchedListener(listener: PatchedListener[Nothing]): Unit = {}
@inline
override private[binding] def get = Nil
}
private[Binding] final class ValueProxy[B](underlying: Seq[Binding[B]]) extends Seq[B] {
@inline
override def length: Int = {
underlying.length
}
@inline
override def apply(idx: Int): B = {
underlying(idx).get
}
@inline
override def iterator: Iterator[B] = {
underlying.iterator.map(_.get)
}
}
private[binding] final class MapBinding[A, B](upstream: BindingSeq[A], f: A => Binding[B]) extends BindingSeq[B] with HasCache[Binding[B]] {
private[Binding] var cacheData: Cache = {
(for {
a <- upstream.get
} yield f(a))(collection.breakOut)
}
override private[binding] def get: Seq[B] with ValueProxy[B] = new ValueProxy(cacheData)
private val upstreamListener = new PatchedListener[A] {
override def patched(upstreamEvent: PatchedEvent[A]): Unit = {
val mappedNewChildren: HasCache[Binding[B]]#Cache = (for {
child <- upstreamEvent.that
} yield f(child))(collection.breakOut)
val oldChildren = spliceCache(upstreamEvent.from, mappedNewChildren, upstreamEvent.replaced)
val event = new PatchedEvent(MapBinding.this, upstreamEvent.from, new ValueProxy(mappedNewChildren), upstreamEvent.replaced)
for (listener <- publisher) {
listener.patched(event)
}
for (oldChild <- oldChildren) {
oldChild.removeChangedListener(childListener)
}
for (newChild <- mappedNewChildren) {
newChild.addChangedListener(childListener)
}
}
}
private[binding] val publisher = new Publisher[PatchedListener[B]]
private val childListener = new ChangedListener[B] {
override def changed(event: ChangedEvent[B]): Unit = {
val index = indexOfCache(event.getSource)
for (listener <- publisher) {
listener.patched(new PatchedEvent(MapBinding.this, index, SingleSeq(event.newValue), 1))
}
}
}
override private[binding] def removePatchedListener(listener: PatchedListener[B]): Unit = {
publisher.unsubscribe(listener)
if (publisher.isEmpty) {
upstream.removePatchedListener(upstreamListener)
for (child <- cacheData) {
child.removeChangedListener(childListener)
}
}
}
override private[binding] def addPatchedListener(listener: PatchedListener[B]): Unit = {
if (publisher.isEmpty) {
upstream.addPatchedListener(upstreamListener)
for (child <- cacheData) {
child.addChangedListener(childListener)
}
}
publisher.subscribe(listener)
}
}
private[binding] final class FlatProxy[B](underlying: Seq[BindingSeq[B]]) extends Seq[B] {
@inline
override def length: Int = {
underlying.view.map(_.get.length).sum
}
@inline
override def apply(idx: Int): B = {
val i = underlying.iterator
@tailrec
def findIndex(restIndex: Int): B = {
if (i.hasNext) {
val subSeq = i.next().get
val currentLength = subSeq.length
if (currentLength > restIndex) {
subSeq(restIndex)
} else {
findIndex(restIndex - currentLength)
}
} else {
throw new IndexOutOfBoundsException()
}
}
findIndex(idx)
}
@inline
override def iterator: Iterator[B] = {
for {
subSeq <- underlying.iterator
element <- subSeq.get.iterator
} yield element
}
}
private[binding] final class FlatMapBinding[A, B](upstream: BindingSeq[A], f: A => BindingSeq[B]) extends BindingSeq[B] with HasCache[BindingSeq[B]] {
private[Binding] var cacheData: Cache = {
(for {
a <- upstream.get
} yield f(a))(collection.breakOut)
}
@inline
override private[binding] def get = new FlatProxy(cacheData)
@inline
private def flatIndex(oldCache: Cache, upstreamBegin: Int, upstreamEnd: Int): Int = {
oldCache.view(upstreamBegin, upstreamEnd).map(_.get.length).sum
}
private val upstreamListener = new PatchedListener[A] {
override private[binding] def patched(upstreamEvent: PatchedEvent[A]): Unit = {
val mappedNewChildren: Cache = (for {
child <- upstreamEvent.that
} yield f(child))(collection.breakOut)
val flatNewChildren = new FlatProxy(mappedNewChildren)
if (upstreamEvent.replaced != 0 || flatNewChildren.nonEmpty) {
val flattenFrom = flatIndex(cacheData, 0, upstreamEvent.from)
val flattenReplaced = flatIndex(cacheData, upstreamEvent.from, upstreamEvent.from + upstreamEvent.replaced)
val oldChilden = spliceCache(upstreamEvent.from, mappedNewChildren, upstreamEvent.replaced)
val event = new PatchedEvent(FlatMapBinding.this, flattenFrom, flatNewChildren, flattenReplaced)
for (listener <- publisher) {
listener.patched(event)
}
for (oldChild <- oldChilden) {
oldChild.removePatchedListener(childListener)
}
for (newChild <- mappedNewChildren) {
newChild.addPatchedListener(childListener)
}
} else {
spliceCache(upstreamEvent.from, mappedNewChildren, upstreamEvent.replaced)
}
}
}
private[binding] val publisher = new Publisher[PatchedListener[B]]
private val childListener = new PatchedListener[B] {
override private[binding] def patched(upstreamEvent: PatchedEvent[B]): Unit = {
val source = upstreamEvent.getSource.asInstanceOf[BindingSeq[B]]
val index = flatIndex(cacheData, 0, indexOfCache(source)) + upstreamEvent.from
val event = new PatchedEvent(FlatMapBinding.this, index, upstreamEvent.that, upstreamEvent.replaced)
for (listener <- publisher) {
listener.patched(event)
}
}
}
override private[binding] def removePatchedListener(listener: PatchedListener[B]): Unit = {
publisher.unsubscribe(listener)
if (publisher.isEmpty) {
upstream.removePatchedListener(upstreamListener)
for (child <- cacheData) {
child.removePatchedListener(childListener)
}
}
}
override private[binding] def addPatchedListener(listener: PatchedListener[B]): Unit = {
if (publisher.isEmpty) {
upstream.addPatchedListener(upstreamListener)
for (child <- cacheData) {
child.addPatchedListener(childListener)
}
}
publisher.subscribe(listener)
}
}
/**
* The companion of a data binding expression of a sequence
*
* @group expressions
*/
object BindingSeq {
implicit final class AsBinding[Element](upstream: BindingSeq[Element]) extends Binding[Seq[Element]] with PatchedListener[Element] {
private val publisher = new Publisher[ChangedListener[Seq[Element]]]
@inline
override private[binding] def get: Seq[Element] = upstream.get
@inline
override private[binding] def removeChangedListener(listener: ChangedListener[Seq[Element]]): Unit = {
publisher.unsubscribe(listener)
if (publisher.isEmpty) {
upstream.removePatchedListener(this)
}
}
@inline
override private[binding] def addChangedListener(listener: ChangedListener[Seq[Element]]): Unit = {
if (publisher.isEmpty) {
upstream.addPatchedListener(this)
}
publisher.subscribe(listener)
}
@inline
private[binding] def patched(upstreamEvent: PatchedEvent[Element]): Unit = {
val event = new ChangedEvent[Seq[Element]](AsBinding.this, upstream.get)
for (listener <- publisher) {
listener.changed(event)
}
}
}
}
/**
* Data binding expression of a sequence
*
* @group expressions
*/
sealed trait BindingSeq[+A] extends Any {
/**
* Enables automatic recalculation.
*
* You may invoke this method more than once.
* Then, when you want to disable automatic recalculation,
* you must invoke [[#unwatch]] same times as the number of calls to this method.
*
* @note This method is recursive, which means that the dependencies of this [[BindingSeq]] will be watched as well.
*/
@inline
final def watch(): Unit = {
addPatchedListener(Binding.DummyPatchedListener)
}
/**
* Disables automatic recalculation.
*
* @note This method is recursive, which means that the dependencies of this [[BindingSeq]] will be unwatched as well.
*/
@inline
final def unwatch(): Unit = {
removePatchedListener(Binding.DummyPatchedListener)
}
private[binding] def get: Seq[A]
private[binding] def removePatchedListener(listener: PatchedListener[A]): Unit
private[binding] def addPatchedListener(listener: PatchedListener[A]): Unit
@inline
final def length: Binding[Int] = Length(this)
/**
* Returns a [[BindingSeq]] that maps each element of this [[BindingSeq]] via `f`
*
* @note This method is only available in a `Binding { ??? }` block or a `@dom` method.
*/
def map[B](f: A => B): BindingSeq[B] = macro Macros.map
/**
* Returns a [[BindingSeq]] that flat-maps each element of this [[BindingSeq]] via `f`
*
* @note This method is only available in a `Binding { ??? }` block or a `@dom` method.
*/
def flatMap[B](f: A => BindingSeq[B]): BindingSeq[B] = macro Macros.flatMap
/**
* Underlying implementation of [[#map]].
*
* @note Don't use this method in user code.
*/
@inline
final def mapBinding[B](f: A => Binding[B]): BindingSeq[B] = new MapBinding[A, B](this, f)
/**
* Underlying implementation of [[#flatMap]].
*
* @note Don't use this method in user code.
*/
@inline
final def flatMapBinding[B](f: A => Binding[BindingSeq[B]]): BindingSeq[B] = {
new FlatMapBinding[BindingSeq[B], B](new MapBinding[A, BindingSeq[B]](this, f), locally)
}
/**
* Returns a view of this [[BindingSeq]] that applied a filter of `condition`
*/
def withFilter(condition: A => Boolean): BindingSeq[A]#WithFilter = macro Macros.withFilter
/**
* Underlying implementation of [[#withFilter]].
*
* @note Don't use this method in user code.
*/
@inline
final def withFilterBinding(condition: A => Binding[Boolean]): BindingSeq[A]#WithFilter = {
new WithFilter(condition)
}
/**
* A helper to build complicated comprehension expressions for [[BindingSeq]]
*/
final class WithFilter(condition: A => Binding[Boolean]) {
/**
* Returns a [[BindingSeq]] that maps each element of this [[BindingSeq]] via `f`
*/
def map[B](f: A => B): BindingSeq[B] = macro Macros.map