-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinding.ts
434 lines (409 loc) · 11.3 KB
/
binding.ts
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
import {
type Observable,
type Subscription,
animationFrameScheduler,
bufferTime,
combineLatest,
filter,
map,
merge,
scan,
switchMap,
} from 'rxjs'
import type { ElementDescription, FragmentDescription } from './component.js'
import type { EventBinder } from './events.js'
import type {
ComponentRunner,
ComponentWirer,
ObservableComponent,
WiringContext,
} from './wiring-context.js'
type ObservableEntry = [string | number | symbol, Observable<unknown>]
type Entry = [string | number | symbol, unknown]
type Entries = Entry[]
export interface BindingContext extends WiringContext {
error: (error: unknown) => void
complete: () => void
eventBinder: EventBinder
componentRunner: ComponentRunner
componentWirer: ComponentWirer
subscription: Subscription
}
export function bindObjectKey(
// intentional metaprogramming
// eslint-disable-next-line @typescript-eslint/no-explicit-any
item: any,
key: string | number | symbol,
observable: Observable<unknown>,
error: (error: unknown) => void,
complete: () => void,
) {
return observable.subscribe({
next: (value) => {
item[key] = value
},
error,
complete: () => {
console.debug(`${key.toString()} binding completed`, item)
complete()
},
})
}
export function bindObjectChanges(
item: object,
observable: Observable<object>,
error: (error: unknown) => void,
complete: () => void,
) {
return observable.subscribe({
next: (changes) => {
Object.assign(item, changes)
},
error,
complete: () => {
console.debug(`Change binding completed`, item)
complete()
},
})
}
export function bindClassListKey(
item: Element,
key: string,
observable: Observable<boolean>,
error: (error: unknown) => void,
complete: () => void,
) {
return observable.subscribe({
next: (value) => {
if (value) {
item.classList.add(key)
} else {
item.classList.remove(key)
}
},
error,
complete: () => {
console.debug(`${key.toString()} classList binding completed`, item)
complete()
},
})
}
export function bindClassListChanges(
item: Element,
observable: Observable<Record<string, boolean>>,
error: (error: unknown) => void,
complete: () => void,
) {
return observable.subscribe({
next: (changes) => {
const adds: string[] = []
const removes: string[] = []
for (const [key, add] of Object.entries(changes)) {
if (add) {
adds.push(key)
} else {
removes.push(key)
}
}
if (adds.length > 0) {
item.classList.add(...adds)
}
if (removes.length > 0) {
item.classList.remove(...removes)
}
},
error,
complete: () => {
console.debug(`classList changes binding completed`, item)
complete()
},
})
}
export function bufferEntries(
observable: Observable<Entry>,
suspense?: Observable<boolean>,
) {
if (suspense) {
return combineLatest([suspense, observable]).pipe(
bufferTime(0, animationFrameScheduler),
map((states) =>
states.reduce(
(acc, [suspend, entry]) => ({
suspend,
entries: [...acc.entries, entry],
}),
{ suspend: false, entries: [] as Entries },
),
),
scan(
(acc, cur) => ({
changes:
acc.suspend && cur.suspend
? Object.assign(acc.changes, Object.fromEntries(cur.entries))
: Object.fromEntries(cur.entries),
suspend: cur.suspend,
}),
{ suspend: false, changes: {} as object },
),
filter(({ suspend }) => !suspend),
map(({ changes }) => changes),
)
}
return observable.pipe(
bufferTime(0, animationFrameScheduler),
map((entries) => Object.fromEntries(entries)),
)
}
export function schedulable(key: string | number | symbol, immediate: boolean) {
// value usually means user-interaction surfaces such as HTML input elements, so don't schedule it
return !(immediate || key === 'value')
}
export function scheduledKey(key: string | number | symbol) {
if (key === 'bfDelayValue') {
return 'value'
}
return key
}
export function makeEntries(
key: string | number | symbol,
observable: Observable<unknown>,
) {
return observable.pipe(map((value) => [key, value] as Entry))
}
function bindElementBinds(
element: Element,
description: ElementDescription,
{ complete, error, suspense, subscription }: BindingContext,
) {
const schedulables: ObservableEntry[] = []
const binds = [
...Object.entries(description.bind).map(
([key, observable]) => [key, observable, false] as const,
),
...Object.entries(description.immediateBind).map(
([key, observable]) => [key, observable, true] as const,
),
]
for (const [key, observable, immediate] of binds) {
if (schedulable(key, immediate)) {
schedulables.push([scheduledKey(key), observable] as ObservableEntry)
} else {
subscription.add(bindObjectKey(element, key, observable, error, complete))
}
}
if (schedulables.length) {
const scheduled = schedulables.map(([key, observable]) =>
makeEntries(key, observable),
)
subscription.add(
bindObjectChanges(
element,
bufferEntries(merge(...scheduled), suspense),
error,
complete,
),
)
}
}
function bindElementEvents(
element: Element,
description: ElementDescription,
{ eventBinder, subscription }: BindingContext,
) {
for (const [key, event] of Object.entries(description.events)) {
subscription.add(eventBinder.applyEvent(event, element, key))
}
}
function bindElementChildren(
element: Element,
description: ElementDescription,
context: BindingContext,
document = globalThis.document,
) {
const { complete, componentRunner, componentWirer, error, subscription } =
context
if (description.childrenBind) {
if (description.childrenBindMode === 'replace') {
const placeholder = document.createComment(`replaceable child component`)
element.append(placeholder)
const activeChild = description.childrenBind.pipe(
switchMap((child) =>
componentWirer(child, context, undefined, document),
),
)
const childComponent = activeChild as ObservableComponent
childComponent.name = `${element.nodeName} replaceable child`
subscription.add(
componentRunner(
element,
childComponent,
context,
placeholder,
document,
),
)
} else {
subscription.add(
description.childrenBind.subscribe({
next(child) {
const placeholder = document.createComment(
`${child.name} component`,
)
if (description.childrenBindMode === 'prepend') {
element.prepend(placeholder)
} else {
element.append(placeholder)
}
subscription.add(
componentRunner(element, child, context, placeholder, document),
)
},
error,
complete: () => {
console.debug(`Children binding completed`, element)
complete()
},
}),
)
}
}
}
function bindElementClasses(
element: Element,
description: ElementDescription,
{ complete, error, subscription, suspense }: BindingContext,
) {
if (Object.keys(description.classBind).length > 0) {
const entries: Observable<Entry>[] = []
for (const [key, observable] of Object.entries(description.classBind)) {
entries.push(makeEntries(key, observable))
}
subscription.add(
bindClassListChanges(
element,
bufferEntries(merge(...entries), suspense) as Observable<
Record<string, boolean>
>,
error,
complete,
),
)
}
for (const [key, observable] of Object.entries(
description.immediateClassBind,
)) {
subscription.add(
bindClassListKey(element, key, observable, error, complete),
)
}
}
function bindElementStyles(
element: HTMLElement,
description: ElementDescription,
{ complete, error, subscription, suspense }: BindingContext,
) {
if (Object.keys(description.styleBind).length > 0) {
const entries: Observable<Entry>[] = []
for (const [key, observable] of Object.entries(description.styleBind)) {
entries.push(makeEntries(key, observable))
}
subscription.add(
bindObjectChanges(
element.style,
bufferEntries(merge(...entries), suspense),
error,
complete,
),
)
}
for (const [key, observable] of Object.entries(
description.immediateStyleBind,
)) {
subscription.add(
bindObjectKey(element.style, key, observable, error, complete),
)
}
}
export function bindElement(
element: Element,
description: ElementDescription,
context: BindingContext,
document = globalThis.document,
) {
const { subscription } = context
bindElementBinds(element, description, context)
bindElementEvents(element, description, context)
bindElementChildren(element, description, context, document)
bindElementClasses(element, description, context)
// TODO: Should we test this assumption somehow that style bindings only apply to HTMLElement and not Element in general?
bindElementStyles(element as HTMLElement, description, context)
return subscription
}
export function bindFragmentChildren(
nodeDescription: FragmentDescription,
node: Element | CharacterData,
subscription: Subscription,
context: BindingContext,
document = globalThis.document,
) {
const { complete, error, componentRunner, componentWirer } = context
if (nodeDescription.childrenBind) {
const parent = node.parentElement
if (!parent) {
throw new Error('Attempted to bind children to an unattached fragment')
}
if (nodeDescription.childrenBindMode === 'replace') {
const activeChild = nodeDescription.childrenBind.pipe(
switchMap((child) =>
componentWirer(child, context, undefined, document),
),
)
const childComponent = activeChild as ObservableComponent
childComponent.name = `${node.nodeName} replaceable child`
subscription.add(
componentRunner(
node.parentElement,
childComponent,
context,
node,
document,
),
)
} else {
subscription.add(
nodeDescription.childrenBind.subscribe({
next(child) {
const placeholder = document.createComment(
`${child.name} component`,
)
if (nodeDescription.childrenBindMode === 'prepend') {
parent.insertBefore(node, placeholder)
} else {
const next = node.nextSibling
if (next) {
parent.insertBefore(next, placeholder)
} else {
parent.append(placeholder)
}
}
subscription.add(
componentRunner(
parent,
{
type: 'component',
component: child,
properties: {},
children: [],
},
context,
placeholder,
),
)
},
error,
complete,
}),
)
}
}
}