-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
439 lines (407 loc) · 11 KB
/
mod.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
435
436
437
438
439
/*! Cell v0.7.6 | Copyright 2022-2024 Yoshiya Hinosawa and Capsule contributors | MIT license */
import type { GroupSignal, Signal } from "@kt3k/signal"
import { documentReady, logEvent } from "./util.ts"
export { GroupSignal, Signal } from "@kt3k/signal"
interface Initializer {
// deno-lint-ignore no-explicit-any
(el: any): void
/** The elector for the component */
sel: string
}
interface RegistryType {
[key: string]: Initializer
}
/** The DOM Event types */
export type EventType =
| "click"
| "dblclick"
| "mousedown"
| "mouseup"
| "mouseover"
| "mousemove"
| "mouseout"
| "dragstart"
| "drag"
| "dragenter"
| "dragleave"
| "dragover"
| "drop"
| "dragend"
| "keydown"
| "keypress"
| "keyup"
| "load"
| "unload"
| "abort"
| "error"
| "resize"
| "scroll"
| "select"
| "change"
| "submit"
| "reset"
| "focus"
| "blur"
| "change"
| "input"
| "submit"
| "load"
| "unload"
| "resize"
| "scroll"
| "select"
| "error"
| "contextmenu"
| "touchstart"
| "touchend"
| "touchmove"
| "touchenter"
| "touchleave"
| "touchcancel"
/** The type mapping of {@linkcode EventType} to Event object */
export type EventMap = {
click: MouseEvent
dblclick: MouseEvent
mousedown: MouseEvent
mouseup: MouseEvent
mousemove: MouseEvent
mouseover: MouseEvent
mouseout: MouseEvent
dragstart: DragEvent
drag: DragEvent
dragenter: DragEvent
dragleave: DragEvent
dragover: DragEvent
drop: DragEvent
dragend: DragEvent
keydown: KeyboardEvent
keyup: KeyboardEvent
keypress: KeyboardEvent
load: Event
unload: Event
abort: Event
error: ErrorEvent
resize: Event
scroll: Event
select: Event
change: Event
submit: Event
reset: Event
focus: FocusEvent
blur: FocusEvent
input: InputEvent
contextmenu: MouseEvent
touchstart: TouchEvent
touchend: TouchEvent
touchmove: TouchEvent
touchenter: TouchEvent
touchleave: TouchEvent
touchcancel: TouchEvent
}
/** The type of the event handler */
export type EventHandler<T extends EventType | string> = (
e: T extends EventType ? EventMap[T] : CustomEvent,
) => void
/**
* The context of the component. This context is passed as the first argument to the component function for each mount.
*
* @typeParam EL The element type of the component
*/
export interface Context<EL = HTMLElement> {
/** The element */
el: EL
/** Registers the event listener */
on<T extends EventType | string>(type: T, handler: EventHandler<T>): void
/** Registers the event listener */
on<T extends EventType | string>(
type: T,
selector: string,
handler: EventHandler<T>,
): void
/** Registers the event listener */
on<T extends EventType | string>(
type: T,
options: AddEventListenerOptions,
handler: EventHandler<T>,
): void
/** Registers the event listener */
on<T extends EventType | string>(
type: T,
selector: string,
options: AddEventListenerOptions,
handler: EventHandler<T>,
): void
/** Registers the event listener for the outside of the element */
onOutside<T extends EventType | string>(
type: T,
handler: EventHandler<T>,
): void
/** Registers the unmount event listner */
onUnmount(handler: () => void): void
/** Queries elements by the given selector under the component dom */
query<T extends HTMLElement = HTMLElement>(selector: string): T | null
/** Queries all elements by the given selector under the component dom */
queryAll<T extends HTMLElement = HTMLElement>(
selector: string,
): NodeListOf<T>
/** Subscribe to the signal. Unsubscribe it when the component unmounted */
subscribe<T>(signal: Signal<T>, handler: (value: T) => void): void
/** Subscribe to the group signal. Unsubscribe it when the component unmounted */
subscribe<T>(signal: GroupSignal<T>, handler: (value: T) => void): void
}
/** The component type */
export type Component<EL extends HTMLElement> = (
ctx: Context<EL>,
) => string | undefined | void | PromiseLike<void | string>
/** The registry of component initializers. */
const registry: RegistryType = {}
/**
* Asserts the given condition holds, otherwise throws.
* @param assertion The assertion expression
* @param message The assertion message
*/
function assert(assertion: boolean, message: string): void {
if (!assertion) {
throw new Error(message)
}
}
/**
* Asserts the given name is a valid component name.
* @param name The component name
*/
function assertComponentNameIsValid(name: unknown): void {
assert(typeof name === "string", "The name should be a string")
assert(
!!registry[name as string],
`The component of the given name is not registered: ${name}`,
)
}
/**
* Register the component with the given name
*
* @example Usage
* ```ts
* import { register } from "@kt3k/cell";
*
* function Component({ on }) {
* on.click = (e) => {
* console.log("clicked");
* };
* }
*
* register(Component, "my-component");
* ```
*
* @param component The component function
* @param name The component name
*/
export function register<EL extends HTMLElement>(
component: Component<EL>,
name: string,
) {
assert(
typeof name === "string" && !!name,
"Component name must be a non-empty string",
)
assert(
!registry[name],
`The component of the given name is already registered: ${name}`,
)
const initClass = `${name}-💊`
/** Initializes the html element by the given configuration. */
const initializer = (el: EL) => {
if (!el.classList.contains(initClass)) {
const onUnmount = (handler: () => void) => {
el.addEventListener(`__unmount__:${name}`, handler, { once: true })
}
// FIXME(kt3k): the below can be written as .add(name, initClass)
// when deno_dom fixes add class.
el.classList.add(name)
el.classList.add(initClass)
onUnmount(() => el.classList.remove(initClass))
const on = (
type: string,
// deno-lint-ignore no-explicit-any
selector: any,
// deno-lint-ignore no-explicit-any
options?: any,
// deno-lint-ignore no-explicit-any
handler?: (e: any) => void,
) => {
// normailize arguments
if (typeof selector === "function") {
handler = selector
selector = undefined
options = undefined
} else if (
typeof options === "function" && typeof selector === "string"
) {
handler = options
options = undefined
} else if (
typeof options === "function" && typeof selector === "object"
) {
handler = options
options = selector
selector = undefined
}
if (typeof handler !== "function") {
throw new Error(
`Cannot add event listener: The handler must be a function, but ${typeof handler} is given`,
)
}
addEventListener(name, el, type, handler, selector, options)
}
// deno-lint-ignore no-explicit-any
const onOutside = (type: string, handler: (e: any) => void) => {
assertEventType(type)
assertEventHandler(handler)
const listener = (e: Event) => {
// deno-lint-ignore no-explicit-any
if (el !== e.target && !el.contains(e.target as any)) {
logEvent({
module: "outside",
color: "#39cccc",
e,
component: name,
})
handler(e)
}
}
document.addEventListener(type, listener)
onUnmount(() => document.removeEventListener(type, listener))
}
const subscribe = <T>(
signal: Signal<unknown> | GroupSignal<unknown>,
handler: (value: unknown) => void,
) => {
onUnmount(signal.subscribe(handler))
}
const context = {
el,
on,
onOutside,
onUnmount,
query: <T extends HTMLElement = HTMLElement>(s: string) =>
el.querySelector(s) as T | null,
queryAll: <T extends HTMLElement = HTMLElement>(s: string) =>
el.querySelectorAll(s) as NodeListOf<T>,
subscribe,
}
const html = component(context)
if (typeof html === "string") {
el.innerHTML = html
} else if (html && typeof html.then === "function") {
html.then((html) => {
if (typeof html === "string") {
el.innerHTML = html
}
})
}
}
}
// The selector
initializer.sel = `.${name}:not(.${initClass})`
registry[name] = initializer
if (!globalThis.document) return
if (document.readyState === "complete") {
mount()
} else {
documentReady().then(() => {
mount(name)
})
}
}
// deno-lint-ignore ban-types
function assertEventHandler(handler: unknown): asserts handler is Function {
assert(
typeof handler === "function",
`Cannot add an event listener: The event handler must be a function, ${typeof handler} (${handler}) is given`,
)
}
function assertEventType(type: unknown): asserts type is string {
assert(
typeof type === "string",
`Cannot add an event listener: The event type must be a string, ${typeof type} (${type}) is given`,
)
}
function addEventListener(
name: string,
el: HTMLElement,
type: string,
handler: (e: Event) => void,
selector?: string,
options?: AddEventListenerOptions,
) {
assertEventType(type)
assertEventHandler(handler)
const listener = (e: Event) => {
if (
!selector ||
[].some.call(
el.querySelectorAll(selector),
(node: Node) => node === e.target || node.contains(e.target as Node),
)
) {
logEvent({
module: "💊",
color: "#e0407b",
e,
component: name,
})
handler(e)
}
}
el.addEventListener(`__unmount__:${name}`, () => {
el.removeEventListener(type, listener, options)
}, { once: true })
el.addEventListener(type, listener, options)
}
/**
* Mount the components to the doms.
*
* @example Usage
* ```ts
* import { mount } from "@kt3k/cell";
*
* mount();
* ```
*
* @param name The component name to mount. If not given, all components are mounted.
* @param el The elements of the children of this element will be initialied. If not given, the whole document is used.
*/
export function mount(name?: string | null, el?: HTMLElement) {
let classNames: string[]
if (!name) {
classNames = Object.keys(registry)
} else {
assertComponentNameIsValid(name)
classNames = [name]
}
classNames.map((className) => {
;[].map.call(
(el || document).querySelectorAll(registry[className].sel),
registry[className],
)
})
}
/**
* Unmount the component from the dom.
*
* @example Usage
* ```ts
* import { unmount } from "@kt3k/cell";
*
* unmount("my-component", document.querySelector(".my-component"));
* ```
*
* @param name The component name to unmount.
* @param el The element of the component to unmount.
*/
export function unmount(name: string, el: EventTarget) {
assert(
!!registry[name],
`The component of the given name is not registered: ${name}`,
)
el.dispatchEvent(new CustomEvent(`__unmount__:${name}`))
}