-
Notifications
You must be signed in to change notification settings - Fork 8
/
dsl.scala
383 lines (318 loc) · 13.1 KB
/
dsl.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
/*
* Copyright 2022 Arman Bilge
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package calico
package dsl
import calico.syntax.*
import calico.util.DomHotswap
import cats.Foldable
import cats.Hash
import cats.Monad
import cats.effect.IO
import cats.effect.kernel.Async
import cats.effect.kernel.Ref
import cats.effect.kernel.Resource
import cats.effect.kernel.Sync
import cats.effect.std.Dispatcher
import cats.effect.syntax.all.*
import cats.syntax.all.*
import com.raquo.domtypes.generic.builders.EventPropBuilder
import com.raquo.domtypes.generic.builders.HtmlAttrBuilder
import com.raquo.domtypes.generic.builders.HtmlTagBuilder
import com.raquo.domtypes.generic.builders.PropBuilder
import com.raquo.domtypes.generic.builders.ReflectedHtmlAttrBuilder
import com.raquo.domtypes.generic.codecs.Codec
import com.raquo.domtypes.generic.defs.attrs.*
import com.raquo.domtypes.generic.defs.complex.*
import com.raquo.domtypes.generic.defs.props.*
import com.raquo.domtypes.generic.defs.reflectedAttrs.*
import com.raquo.domtypes.jsdom.defs.eventProps.*
import com.raquo.domtypes.jsdom.defs.tags.*
import fs2.Pipe
import fs2.Stream
import fs2.concurrent.Channel
import fs2.concurrent.Signal
import org.scalajs.dom
import shapeless3.deriving.K0
import scala.collection.mutable
import scala.scalajs.js
object io extends Dsl[IO]
object Dsl:
def apply[F[_]: Async]: Dsl[F] = new Dsl[F] {}
trait Dsl[F[_]]
extends HtmlBuilders[F],
DocumentTags[HtmlTagT[F]],
GroupingTags[HtmlTagT[F]],
TextTags[HtmlTagT[F]],
FormTags[HtmlTagT[F]],
SectionTags[HtmlTagT[F]],
EmbedTags[HtmlTagT[F]],
TableTags[HtmlTagT[F]],
MiscTags[HtmlTagT[F]],
HtmlAttrs[HtmlAttr[F, _]],
ReflectedHtmlAttrs[Prop[F, _, _]],
Props[Prop[F, _, _]],
ClipboardEventProps[EventProp[F, _]],
ErrorEventProps[EventProp[F, _]],
FormEventProps[EventProp[F, _]],
KeyboardEventProps[EventProp[F, _]],
MediaEventProps[EventProp[F, _]],
MiscellaneousEventProps[EventProp[F, _]],
MouseEventProps[EventProp[F, _]],
PointerEventProps[EventProp[F, _]]
trait HtmlBuilders[F[_]](using F: Async[F])
extends HtmlTagBuilder[HtmlTagT[F], dom.HTMLElement],
HtmlAttrBuilder[HtmlAttr[F, _]],
ReflectedHtmlAttrBuilder[Prop[F, _, _]],
PropBuilder[Prop[F, _, _]],
EventPropBuilder[EventProp[F, _], dom.Event]:
protected def htmlTag[E <: dom.HTMLElement](tagName: String, void: Boolean) =
HtmlTag(tagName, void)
protected def htmlAttr[V](key: String, codec: Codec[V, String]) =
HtmlAttr(key, codec)
protected def reflectedAttr[V, J](
attrKey: String,
propKey: String,
attrCodec: Codec[V, String],
propCodec: Codec[V, J]) =
Prop(propKey, propCodec)
protected def prop[V, J](name: String, codec: Codec[V, J]) =
Prop(name, codec)
def eventProp[V <: dom.Event](key: String): EventProp[F, V] =
EventProp(key)
def cls: ClassAttr[F] = ClassAttr[F]
def children: Children[F] = Children[F]
def children[K](f: K => Resource[F, dom.Node]): KeyedChildren[F, K] =
KeyedChildren[F, K](f)
type HtmlTagT[F[_]] = [E <: dom.HTMLElement] =>> HtmlTag[F, E]
final class HtmlTag[F[_], E <: dom.HTMLElement] private[calico] (name: String, void: Boolean)(
using F: Async[F]):
def apply[M](modifier: M)(using Modifier[F, E, M]): Resource[F, E] =
apply(Tuple1(modifier))
def apply[M](mkModifier: E => M)(using Modifier[F, E, M]): Resource[F, E] =
apply(e => Tuple1(mkModifier(e)))
def apply[M <: Tuple](modifiers: M)(
using K0.ProductInstances[Modifier[F, E, _], M]): Resource[F, E] =
apply(_ => modifiers)
def apply[M <: Tuple](mkModifiers: E => M)(
using inst: K0.ProductInstances[Modifier[F, E, _], M]): Resource[F, E] =
build.toResource.flatMap { e =>
inst.foldLeft(mkModifiers(e))(Resource.pure(e)) {
[a] => (r: Resource[F, E], m: Modifier[F, E, a], a: a) => r.flatTap(m.modify(a, _))
}
}
private def build = F.delay(dom.document.createElement(name).asInstanceOf[E])
trait Modifier[F[_], E, A]:
outer =>
def modify(a: A, e: E): Resource[F, Unit]
final def contramap[B](f: B => A): Modifier[F, E, B] =
(b: B, e: E) => outer.modify(f(b), e)
object Modifier:
given forUnit[F[_], E]: Modifier[F, E, Unit] with
def modify(unit: Unit, e: E) = Resource.unit
given forString[F[_], E <: dom.Node](using F: Async[F]): Modifier[F, E, String] =
forStringStream.contramap(Stream.emit(_))
given forStringStream[F[_], E <: dom.Node](
using F: Async[F]): Modifier[F, E, Stream[F, String]] with
def modify(s: Stream[F, String], e: E) = for
n <- F
.delay(dom.document.createTextNode(""))
.flatTap(n => F.delay(e.appendChild(n)))
.toResource
_ <- s.foreach(t => F.delay(n.textContent = t)).compile.drain.background
yield ()
given forOptionStringStream[F[_], E <: dom.Node](
using F: Async[F]): Modifier[F, E, Stream[F, Option[String]]] with
def modify(s: Stream[F, Option[String]], e: E) = for
n <- F
.delay(dom.document.createTextNode(""))
.flatTap(n => F.delay(e.appendChild(n)))
.toResource
_ <- s.foreach(t => F.delay(n.textContent = t.getOrElse(""))).compile.drain.background
yield ()
given forResource[F[_], E <: dom.Node, A](
using M: Modifier[F, E, A]): Modifier[F, E, Resource[F, A]] with
def modify(a: Resource[F, A], e: E) = a.flatMap(M.modify(_, e))
given forSignal[F[_], E <: dom.Node, A](
using M: Modifier[F, E, Stream[F, A]]): Modifier[F, E, Signal[F, A]] =
M.contramap(_.discrete)
given forFoldable[F[_]: Monad, E <: dom.Node, G[_]: Foldable, A](
using M: Modifier[F, E, A]): Modifier[F, E, G[A]] with
def modify(ga: G[A], e: E) = ga.foldMapM(M.modify(_, e)).void
given forElement[F[_], E <: dom.Node, E2 <: dom.Node](
using F: Sync[F]): Modifier[F, E, Resource[F, E2]] with
def modify(e2: Resource[F, E2], e: E) =
e2.evalMap(e2 => F.delay(e.appendChild(e2)))
given forElementStream[F[_], E <: dom.Node, E2 <: dom.Node](
using F: Async[F]): Modifier[F, E, Stream[F, Resource[F, E2]]] =
forOptionElementStream.contramap(_.map(Some(_)))
given forOptionElementStream[F[_], E <: dom.Node, E2 <: dom.Node](
using F: Async[F]): Modifier[F, E, Stream[F, Option[Resource[F, E2]]]] with
def modify(e2s: Stream[F, Option[Resource[F, E2]]], e: E) =
for
sentinel <- Resource.eval(F.delay(dom.document.createComment("")))
hs <- DomHotswap[F, dom.Node](sentinel.pure)
_ <- F.delay(e.appendChild(sentinel)).toResource
_ <- e2s
.foreach { next =>
hs.swap(next.getOrElse(sentinel.pure)) { (p, n) => F.delay(e.replaceChild(n, p)) }
}
.compile
.drain
.background
yield ()
final class HtmlAttr[F[_], V] private[calico] (key: String, codec: Codec[V, String]):
def :=(v: V): HtmlAttr.Modified[F, V] =
this <-- Stream.emit(v)
def <--(vs: Signal[F, V]): HtmlAttr.Modified[F, V] =
this <-- vs.discrete
def <--(vs: Stream[F, V]): HtmlAttr.Modified[F, V] =
this <-- Resource.pure(vs)
def <--(vs: Resource[F, Stream[F, V]]): HtmlAttr.Modified[F, V] =
HtmlAttr.Modified(key, codec, vs)
object HtmlAttr:
final class Modified[F[_], V] private[HtmlAttr] (
val key: String,
val codec: Codec[V, String],
val values: Resource[F, Stream[F, V]]
)
given [F[_], E <: dom.Element, V](using F: Async[F]): Modifier[F, E, Modified[F, V]] with
def modify(attr: Modified[F, V], e: E) =
attr.values.flatMap { vs =>
vs.foreach(v => F.delay(e.setAttribute(attr.key, attr.codec.encode(v))))
.compile
.drain
.background
.void
}
sealed class Prop[F[_], V, J] private[calico] (name: String, codec: Codec[V, J]):
def :=(v: V): Prop.Modified[F, V, J] =
this <-- Stream.emit(v)
def <--(vs: Signal[F, V]): Prop.Modified[F, V, J] =
this <-- vs.discrete
def <--(vs: Stream[F, V]): Prop.Modified[F, V, J] =
this <-- Resource.pure(vs)
def <--(vs: Resource[F, Stream[F, V]]): Prop.Modified[F, V, J] =
Prop.Modified(name, codec, vs)
object Prop:
final class Modified[F[_], V, J] private[Prop] (
val name: String,
val codec: Codec[V, J],
val values: Resource[F, Stream[F, V]]
)
given [F[_], E, V, J](using F: Async[F]): Modifier[F, E, Modified[F, V, J]] with
def modify(prop: Modified[F, V, J], e: E) =
prop.values.flatMap { vs =>
vs.foreach { v =>
F.delay(e.asInstanceOf[js.Dictionary[J]](prop.name) = prop.codec.encode(v))
}.compile
.drain
.background
.void
}
final class EventProp[F[_], E] private[calico] (key: String):
def -->(sink: Pipe[F, E, Nothing]): EventProp.Modified[F, E] = EventProp.Modified(key, sink)
object EventProp:
final class Modified[F[_], E] private[calico] (val key: String, val sink: Pipe[F, E, Nothing])
given [F[_], E <: dom.EventTarget, V](using F: Async[F]): Modifier[F, E, Modified[F, V]] with
def modify(prop: Modified[F, V], e: E) =
fs2.dom.events(e, prop.key).through(prop.sink).compile.drain.background.void
final class ClassAttr[F[_]] private[calico]
extends Prop[F, List[String], String](
"className",
new:
def decode(domValue: String) = domValue.split(" ").toList
def encode(scalaValue: List[String]) = scalaValue.mkString(" ")
):
def :=(cls: String): Prop.Modified[F, List[String], String] =
this := List(cls)
final class Children[F[_]] private[calico]:
def <--(cs: Signal[F, List[Resource[F, dom.Node]]])(using Monad[F]): Children.Modified[F] =
this <-- cs.discrete
def <--(cs: Stream[F, List[Resource[F, dom.Node]]])(using Monad[F]): Children.Modified[F] =
this <-- cs.map(_.sequence)
def <--(cs: Signal[F, Resource[F, List[dom.Node]]]): Children.Modified[F] =
this <-- cs.discrete
def <--(cs: Stream[F, Resource[F, List[dom.Node]]]): Children.Modified[F] =
Children.Modified(cs)
object Children:
final class Modified[F[_]] private[calico] (val cs: Stream[F, Resource[F, List[dom.Node]]])
given [F[_], E <: dom.Element](using F: Async[F]): Modifier[F, E, Modified[F]] with
def modify(children: Modified[F], e: E) =
for
hs <- DomHotswap[F, List[dom.Node]](Resource.pure(Nil))
placeholder <- Resource.eval(
F.delay(e.appendChild(dom.document.createComment("")))
)
_ <- children
.cs
.foreach { children =>
hs.swap(children) { (prev, next) =>
F.delay {
prev.foreach(e.removeChild)
next.foreach(e.insertBefore(_, placeholder))
}
}
}
.compile
.drain
.background
.void
yield ()
final class KeyedChildren[F[_], K] private[calico] (f: K => Resource[F, dom.Node]):
def <--(ks: Signal[F, List[K]]): KeyedChildren.Modified[F, K] =
this <-- ks.discrete
def <--(ks: Stream[F, List[K]]): KeyedChildren.Modified[F, K] =
KeyedChildren.Modified(f, ks)
object KeyedChildren:
final class Modified[F[_], K] private[calico] (
val f: K => Resource[F, dom.Node],
val ks: Stream[F, List[K]])
given [F[_], E <: dom.Element, K: Hash](using F: Async[F]): Modifier[F, E, Modified[F, K]]
with
def modify(children: Modified[F, K], e: E) =
for
active <- Resource.make(Ref[F].of(mutable.Map.empty[K, (dom.Node, F[Unit])]))(
_.get.flatMap(_.values.toList.traverse_(_._2))
)
_ <- children
.ks
.foreach { ks =>
active.get.flatMap { currentNodes =>
F.uncancelable { poll =>
F.delay {
val nextNodes = mutable.Map[K, (dom.Node, F[Unit])]()
val newNodes = List.newBuilder[K]
ks.foreach { k =>
currentNodes.remove(k) match
case Some(v) => nextNodes += (k -> v)
case None => newNodes += k
}
val releaseOldNodes = currentNodes.values.toList.traverse_(_._2)
val acquireNewNodes = newNodes.result().traverse_ { k =>
poll(children.f(k).allocated).flatMap(x => F.delay(nextNodes += k -> x))
}
val renderNextNodes = F.delay(e.replaceChildren(ks.map(nextNodes(_)._1)*))
(active.set(nextNodes) *>
acquireNewNodes *>
renderNextNodes).guarantee(releaseOldNodes.evalOn(unsafe.MacrotaskExecutor))
}.flatten
}
}
}
.compile
.drain
.background
yield ()