1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | import * as dom from './dom.js'
|
10 | import * as diff from './diff.js'
|
11 | import * as object from './object.js'
|
12 | import * as json from './json.js'
|
13 | import * as string from './string.js'
|
14 | import * as array from './array.js'
|
15 | import * as number from './number.js'
|
16 | import * as func from './function.js'
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | export const registry = customElements
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 | export const define = (name, constr, opts) => registry.define(name, constr, opts)
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | export const whenDefined = name => registry.whenDefined(name)
|
35 |
|
36 | const upgradedEventName = 'upgraded'
|
37 | const connectedEventName = 'connected'
|
38 | const disconnectedEventName = 'disconnected'
|
39 |
|
40 |
|
41 |
|
42 |
|
43 | export class Lib0Component extends HTMLElement {
|
44 | |
45 |
|
46 |
|
47 | constructor (state) {
|
48 | super()
|
49 | |
50 |
|
51 |
|
52 | this.state = (state)
|
53 | |
54 |
|
55 |
|
56 | this._internal = {}
|
57 | }
|
58 |
|
59 | |
60 |
|
61 |
|
62 |
|
63 | setState (state, forceStateUpdate = true) {}
|
64 | |
65 |
|
66 |
|
67 | updateState (stateUpdate) { }
|
68 | }
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 | const encodeAttrVal = (val, type) => {
|
76 | if (type === 'json') {
|
77 | val = json.stringify(val)
|
78 | }
|
79 | return val + ''
|
80 | }
|
81 |
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 | const parseAttrVal = (val, type) => {
|
88 | switch (type) {
|
89 | case 'json':
|
90 | return json.parse(val)
|
91 | case 'number':
|
92 | return Number.parseFloat(val)
|
93 | case 'string':
|
94 | return val
|
95 | case 'bool':
|
96 | return val != null
|
97 | default:
|
98 | return null
|
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 | export const createComponent = (name, { template, style = '', state: defaultState, onStateChange = () => {}, childStates = { }, attrs = {}, listeners = {}, slots = () => ({}) }) => {
|
130 | |
131 |
|
132 |
|
133 |
|
134 | const normalizedAttrs = {}
|
135 | for (const key in attrs) {
|
136 | normalizedAttrs[string.fromCamelCase(key, '-')] = key
|
137 | }
|
138 | const templateElement = template ? (dom.parseElement(`
|
139 | <template>
|
140 | <style>${style}</style>
|
141 | ${template}
|
142 | </template>
|
143 | `)) : null
|
144 |
|
145 | class _Lib0Component extends HTMLElement {
|
146 | |
147 |
|
148 |
|
149 | constructor (state) {
|
150 | super()
|
151 | |
152 |
|
153 |
|
154 | this._childStates = []
|
155 | |
156 |
|
157 |
|
158 | this._slots = {}
|
159 | this._init = false
|
160 | |
161 |
|
162 |
|
163 | this._internal = {}
|
164 | |
165 |
|
166 |
|
167 | this.state = state || null
|
168 | this.connected = false
|
169 |
|
170 | if (templateElement) {
|
171 | const shadow = (this.attachShadow({ mode: 'open' }))
|
172 | shadow.appendChild(templateElement.content.cloneNode(true))
|
173 |
|
174 | for (const key in childStates) {
|
175 | this._childStates.push({
|
176 | d: (dom.querySelector( (shadow), key)),
|
177 | s: childStates[key]
|
178 | })
|
179 | }
|
180 | }
|
181 | dom.emitCustomEvent(this, upgradedEventName, { bubbles: true })
|
182 | }
|
183 |
|
184 | connectedCallback () {
|
185 | this.connected = true
|
186 | if (!this._init) {
|
187 | this._init = true
|
188 | const shadow = this.shadowRoot
|
189 | if (shadow) {
|
190 | dom.addEventListener(shadow, upgradedEventName, event => {
|
191 | this.setState(this.state, true)
|
192 | event.stopPropagation()
|
193 | })
|
194 | }
|
195 | |
196 |
|
197 |
|
198 | const startState = this.state || object.assign({}, defaultState)
|
199 | if (attrs) {
|
200 | for (const key in attrs) {
|
201 | const normalizedKey = string.fromCamelCase(key, '-')
|
202 | const val = parseAttrVal(this.getAttribute(normalizedKey), attrs[key])
|
203 | if (val) {
|
204 | startState[key] = val
|
205 | }
|
206 | }
|
207 | }
|
208 |
|
209 | for (const key in listeners) {
|
210 | dom.addEventListener(shadow || this, key, event => {
|
211 | if (listeners[key]( (event), this) !== false) {
|
212 | event.stopPropagation()
|
213 | event.preventDefault()
|
214 | return false
|
215 | }
|
216 | })
|
217 | }
|
218 |
|
219 | this.state = null
|
220 | this.setState(startState)
|
221 | }
|
222 | dom.emitCustomEvent( (this.shadowRoot || this), connectedEventName, { bubbles: true })
|
223 | }
|
224 |
|
225 | disconnectedCallback () {
|
226 | this.connected = false
|
227 | dom.emitCustomEvent( (this.shadowRoot || this), disconnectedEventName, { bubbles: true })
|
228 | this.setState(null)
|
229 | }
|
230 |
|
231 | static get observedAttributes () {
|
232 | return object.keys(normalizedAttrs)
|
233 | }
|
234 |
|
235 | |
236 |
|
237 |
|
238 |
|
239 |
|
240 |
|
241 |
|
242 | attributeChangedCallback (name, oldVal, newVal) {
|
243 | const curState = (this.state)
|
244 | const camelAttrName = normalizedAttrs[name]
|
245 | const type = attrs[camelAttrName]
|
246 | const parsedVal = parseAttrVal(newVal, type)
|
247 | if (curState && (type !== 'json' || json.stringify(curState[camelAttrName]) !== newVal) && curState[camelAttrName] !== parsedVal && !number.isNaN(parsedVal)) {
|
248 | this.updateState({ [camelAttrName]: parsedVal })
|
249 | }
|
250 | }
|
251 |
|
252 | |
253 |
|
254 |
|
255 | updateState (stateUpdate) {
|
256 | this.setState(object.assign({}, this.state, stateUpdate))
|
257 | }
|
258 |
|
259 | |
260 |
|
261 |
|
262 | setState (state, forceStateUpdates = false) {
|
263 | const prevState = this.state
|
264 | this.state = state
|
265 | if (this._init && (!func.equalityFlat(state, prevState) || forceStateUpdates)) {
|
266 |
|
267 | if (state) {
|
268 | const slotElems = slots(state, prevState, this)
|
269 | for (const key in slotElems) {
|
270 | const slotContent = slotElems[key]
|
271 | if (this._slots[key] !== slotContent) {
|
272 | this._slots[key] = slotContent
|
273 | const currentSlots = (key !== 'default' ? array.from(dom.querySelectorAll(this, `[slot="${key}"]`)) : array.from(this.childNodes).filter( child => !dom.checkNodeType(child, dom.ELEMENT_NODE) || !child.hasAttribute('slot')))
|
274 | currentSlots.slice(1).map(dom.remove)
|
275 | const nextSlot = dom.parseFragment(slotContent)
|
276 | if (key !== 'default') {
|
277 | array.from(nextSlot.children).forEach(c => c.setAttribute('slot', key))
|
278 | }
|
279 | if (currentSlots.length > 0) {
|
280 | dom.replaceWith(currentSlots[0], nextSlot)
|
281 | } else {
|
282 | dom.appendChild(this, nextSlot)
|
283 | }
|
284 | }
|
285 | }
|
286 | }
|
287 | onStateChange(state, prevState, this)
|
288 | if (state != null) {
|
289 | this._childStates.forEach(cnf => {
|
290 | const d = cnf.d
|
291 | if (d.updateState) {
|
292 | d.updateState(cnf.s(state, this))
|
293 | }
|
294 | })
|
295 | }
|
296 | for (const key in attrs) {
|
297 | const normalizedKey = string.fromCamelCase(key, '-')
|
298 | if (state == null) {
|
299 | this.removeAttribute(normalizedKey)
|
300 | } else {
|
301 | const stateVal = state[key]
|
302 | const attrsType = attrs[key]
|
303 | if (!prevState || prevState[key] !== stateVal) {
|
304 | if (attrsType === 'bool') {
|
305 | if (stateVal) {
|
306 | this.setAttribute(normalizedKey, '')
|
307 | } else {
|
308 | this.removeAttribute(normalizedKey)
|
309 | }
|
310 | } else if (stateVal == null && (attrsType === 'string' || attrsType === 'number')) {
|
311 | this.removeAttribute(normalizedKey)
|
312 | } else {
|
313 | this.setAttribute(normalizedKey, encodeAttrVal(stateVal, attrsType))
|
314 | }
|
315 | }
|
316 | }
|
317 | }
|
318 | }
|
319 | }
|
320 | }
|
321 | define(name, _Lib0Component)
|
322 |
|
323 | return _Lib0Component
|
324 | }
|
325 |
|
326 |
|
327 |
|
328 |
|
329 | export const createComponentDefiner = definer => {
|
330 | |
331 |
|
332 |
|
333 | let defined = null
|
334 | return () => {
|
335 | if (!defined) {
|
336 | defined = definer()
|
337 | }
|
338 | return defined
|
339 | }
|
340 | }
|
341 |
|
342 | export const defineListComponent = createComponentDefiner(() => {
|
343 | const ListItem = createComponent('lib0-list-item', {
|
344 | template: '<slot name="content"></slot>',
|
345 | slots: state => ({
|
346 | content: `<div>${state}</div>`
|
347 | })
|
348 | })
|
349 | return createComponent('lib0-list', {
|
350 | state: { list: ([]), Item: ListItem },
|
351 | onStateChange: (state, prevState, component) => {
|
352 | if (state == null) {
|
353 | return
|
354 | }
|
355 | const { list = ([]), Item = ListItem } = state
|
356 |
|
357 | let { index, remove, insert } = diff.simpleDiffArray(prevState ? prevState.list : [], list, func.equalityFlat)
|
358 | if (remove === 0 && insert.length === 0) {
|
359 | return
|
360 | }
|
361 | let child = (component.firstChild)
|
362 | while (index-- > 0) {
|
363 | child = (child.nextElementSibling)
|
364 | }
|
365 | let insertStart = 0
|
366 | while (insertStart < insert.length && remove-- > 0) {
|
367 |
|
368 | child.setState(insert[insertStart++])
|
369 | child = (child.nextElementSibling)
|
370 | }
|
371 | while (remove-- > 0) {
|
372 |
|
373 | const prevChild = child
|
374 | child = (child.nextElementSibling)
|
375 | component.removeChild(prevChild)
|
376 | }
|
377 |
|
378 | component.insertBefore(dom.fragment(insert.slice(insertStart).map(insState => {
|
379 | const el = new Item()
|
380 | el.setState(insState)
|
381 | return el
|
382 | })), child)
|
383 | }
|
384 | })
|
385 | })
|
386 |
|
387 | export const defineLazyLoadingComponent = createComponentDefiner(() => createComponent('lib0-lazy', {
|
388 | state: ({
|
389 | component: null, import: null, state: null
|
390 | }),
|
391 | attrs: {
|
392 | component: 'string'
|
393 | },
|
394 | onStateChange: ({ component, state, import: getImport }, prevState, componentEl) => {
|
395 | if (component !== null) {
|
396 | if (getImport) {
|
397 | getImport()
|
398 | }
|
399 | if (!prevState || component !== prevState.component) {
|
400 | const el = (dom.createElement(component))
|
401 | componentEl.innerHTML = ''
|
402 | componentEl.insertBefore(el, null)
|
403 | }
|
404 | const el = (componentEl.firstElementChild)
|
405 |
|
406 | if (el.setState) {
|
407 | el.setState(state)
|
408 | }
|
409 | }
|
410 | }
|
411 | }))
|