/
idom.ts
305 lines (268 loc) · 7.41 KB
/
idom.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
import {render, createContext} from 'preact';
import {useState, useEffect, useContext, useRef, useCallback} from 'preact/hooks';
import {html} from 'htm/preact';
import {applyPatch, getValueByPointer} from 'fast-json-patch';
import * as p from "@bokehjs/core/properties"
import {HTMLBox} from "@bokehjs/models/layouts/html_box"
import {PanelHTMLBoxView, set_size} from "./layout"
import {serializeEvent} from "./event-to-object"
const LayoutConfigContext = createContext({});
export function mountLayout(
mountElement: any,
saveUpdateHook: any,
sendEvent: any,
importSourceUrl: string
) {
render(
html`
<${Layout}
saveUpdateHook=${saveUpdateHook}
sendEvent=${sendEvent}
importSourceUrl=${importSourceUrl}
/>
`,
mountElement
)
}
export default function Layout({ saveUpdateHook, sendEvent, importSourceUrl }: { saveUpdateHook: any, sendEvent: any, importSourceUrl: string } ) {
const [model, patchModel] = useInplaceJsonPatch({});
useEffect(() => saveUpdateHook(patchModel), [patchModel]);
if (model.tagName) {
return html`
<${LayoutConfigContext.Provider}
value=${{
sendEvent: sendEvent,
importSourceUrl: importSourceUrl,
}}
>
<${Element} model=${model} />
<//>
`
} else
return html`<div />`
}
function Element({ model }: { model: any }) {
if (model.importSource)
return html`<${ImportedElement} model=${model} />`
else
return html`<${StandardElement} model=${model} />`
}
function ImportedElement({ model }: { model: any }) {
const config: any = useContext(LayoutConfigContext);
const module = useLazyModule(
model.importSource.source,
config.importSourceUrl
)
if (module) {
const cmpt = getPathProperty(module, model.tagName);
const children = elementChildren(model);
const attributes = elementAttributes(model, config.sendEvent);
return html`<${cmpt} ...${attributes}>${children}<//>`;
} else {
const fallback = model.importSource.fallback;
if (!fallback)
return html`<div />`
switch (typeof fallback) {
case "object":
return html`<${Element} model=${fallback} />`
case "string":
return html`<div>${fallback}</div>`
default:
return null
}
}
}
function StandardElement({ model }: { model: any }) {
const config: any = useContext(LayoutConfigContext);
const children = elementChildren(model);
const attributes = elementAttributes(model, config.sendEvent);
if (model.children && model.children.length)
return html`<${model.tagName} ...${attributes}>${children}<//>`
else
return html`<${model.tagName} ...${attributes} />`
}
function elementChildren(model: any) {
if (!model.children)
return []
else {
return model.children.map((child: any) => {
switch (typeof child) {
case "object":
return html`<${Element} model=${child} />`
case "string":
return child
default:
return null
}
});
}
}
function elementAttributes(model: any, sendEvent: any) {
const attributes = Object.assign({}, model.attributes)
if (model.eventHandlers) {
Object.keys(model.eventHandlers).forEach((eventName) => {
const eventSpec = model.eventHandlers[eventName]
attributes[eventName] = eventHandler(sendEvent, eventSpec)
})
}
return attributes
}
function eventHandler(sendEvent: any, eventSpec: any) {
return function (): Promise<void> {
const data = Array.from(arguments).map((value) => {
if (typeof value === "object") {
if (eventSpec["preventDefault"])
value.preventDefault();
if (eventSpec["stopPropagation"])
value.stopPropagation()
return serializeEvent(value)
} else
return value
});
return new Promise((resolve: any) => {
const msg = {
data: data,
target: eventSpec["target"],
}
sendEvent(msg)
resolve(msg)
})
}
}
function useLazyModule(source: string, sourceUrlBase: string = "") {
const [module, setModule] = useState(null);
// use eval() to avoid weird build behavior by bundlers like Webpack
if (!module)
eval(`import('${joinUrl(sourceUrlBase, source)}')`).then(setModule)
return module
}
function getPathProperty(obj: any, prop: string) {
// properties may be dot seperated strings
const path = prop.split(".")
const firstProp: any = path.shift()
let value = obj[firstProp]
for (let i = 0; i < path.length; i++)
value = value[path[i]]
return value
}
function useInplaceJsonPatch(doc: any) {
const ref = useRef(doc);
const forceUpdate = useForceUpdate();
const applyPatch = useCallback(
(path: any, patch: any) => {
applyPatchInplace(ref.current, path, patch)
forceUpdate()
},
[ref, forceUpdate]
)
return [ref.current, applyPatch];
}
function applyPatchInplace(doc: any, path: any, patch: any) {
if (!path)
applyPatch(doc, patch)
else {
applyPatch(doc, [
{
op: "replace",
path: path,
value: applyPatch(
getValueByPointer(doc, path),
patch,
false,
false
).newDocument,
},
])
}
}
function useForceUpdate() {
const [, updateState] = useState({})
return useCallback(() => updateState({}), [])
}
function joinUrl(base: string, tail: string) {
return tail.startsWith("./")
? (base.endsWith("/") ? base.slice(0, -1) : base) + tail.slice(1)
: tail;
}
export class IDOMView extends PanelHTMLBoxView {
model: IDOM
_update: any
connect_signals(): void {
super.connect_signals()
this.connect(this.model.properties.event.change, () => {
this._update(...this.model.event)
setTimeout(() => { requestAnimationFrame(() => this.fix_layout()) })
})
}
fix_layout(): void {
this.update_layout()
this.compute_layout()
this.invalidate_layout()
set_size(this.el, this.model)
}
initialize(): void {
super.initialize()
mountLayout(
this.el,
(update: any) => this._save_update(update),
(event: any) => this._send(event),
this.model.importSourceUrl
)
}
async lazy_initialize(): Promise<void> {
await super.lazy_initialize()
await new Promise((resolve) => {
const check_update = () => {
if (this._update)
resolve(null)
else
setTimeout(check_update, 100);
}
check_update()
})
}
_save_update(update: any): any {
this._update = update
}
async render(): Promise<void> {
super.render()
this._update(...this.model.event)
await new Promise((resolve) => {
const check_update = () => {
if (this.el.children.length) {
this.fix_layout()
resolve(null)
} else
setTimeout(check_update, 50)
}
check_update()
})
}
_send(event: any): any {
this.model.msg = event
}
}
export namespace IDOM {
export type Attrs = p.AttrsOf<Props>
export type Props = HTMLBox.Props & {
event: p.Property<any>
importSourceUrl: p.Property<string>
msg: p.Property<any>
}
}
export interface IDOM extends IDOM.Attrs {}
export class IDOM extends HTMLBox {
properties: IDOM.Props
constructor(attrs?: Partial<IDOM.Attrs>) {
super(attrs)
}
static __module__ = "panel.models.idom"
static init_IDOM(): void {
this.prototype.default_view = IDOMView
this.define<IDOM.Props>(({Any, String}) => ({
event: [ Any, [] ],
importSourceUrl: [ String, '' ],
msg: [ Any, {} ],
}))
}
}