-
Notifications
You must be signed in to change notification settings - Fork 442
/
Copy pathstream_element.ts
80 lines (66 loc) · 1.82 KB
/
stream_element.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
import { StreamActions } from "../core/streams/stream_actions"
import { nextAnimationFrame } from "../util"
// <turbo-stream action=replace target=id><template>...
export class StreamElement extends HTMLElement {
async connectedCallback() {
try {
await this.render()
} catch (error) {
console.error(error)
} finally {
this.disconnect()
}
}
private renderPromise?: Promise<void>
async render() {
return this.renderPromise ??= (async () => {
if (this.dispatchEvent(this.beforeRenderEvent)) {
await nextAnimationFrame()
this.performAction()
}
})()
}
disconnect() {
try { this.remove() } catch {}
}
get performAction() {
if (this.action) {
const actionFunction = StreamActions[this.action]
if (actionFunction) {
return actionFunction
}
this.raise("unknown action")
}
this.raise("action attribute is missing")
}
get targetElement() {
if (this.target) {
return this.ownerDocument?.getElementById(this.target)
}
this.raise("target attribute is missing")
}
get templateContent() {
return this.templateElement.content
}
get templateElement() {
if (this.firstElementChild instanceof HTMLTemplateElement) {
return this.firstElementChild
}
this.raise("first child element must be a <template> element")
}
get action() {
return this.getAttribute("action")
}
get target() {
return this.getAttribute("target")
}
private raise(message: string): never {
throw new Error(`${this.description}: ${message}`)
}
private get description() {
return (this.outerHTML.match(/<[^>]+>/) ?? [])[0] ?? "<turbo-stream>"
}
private get beforeRenderEvent() {
return new CustomEvent("turbo:before-stream-render", { bubbles: true, cancelable: true })
}
}