forked from vuejs/vue-web-component-wrapper
/
index.js
376 lines (325 loc) · 11.3 KB
/
index.js
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
import {
toVNodes,
camelize,
hyphenate,
callHooks,
injectHook,
getInitialProps,
createCustomEvent,
convertAttributeValue,
cloneElementsToShadowRoot,
getAllStyles,
observeStyleChanges
} from './utils.js'
export default function wrap(Vue, Component, wrapOptions = {}) {
const isAsync = typeof Component === 'function' && !Component.cid
let isInitialized = false
let hyphenatedPropsList
let camelizedPropsList
let camelizedPropsMap
if (wrapOptions.globalStyles) {
const defaults = {
target: document.head,
selector:
'style, link[rel="stylesheet"], link[rel="preload"][as="style"]',
filter: undefined,
observeOptions: { childList: true, subtree: true }
}
wrapOptions.globalStyles = {
...defaults,
...wrapOptions.globalStyles
}
}
function initialize(Component) {
if (isInitialized) return
const options =
typeof Component === 'function' ? Component.options : Component
// extract props info
let propsList = Array.isArray(options.props)
? options.props
: Object.keys(options.props || {})
if (wrapOptions.jsonMapping) {
// add the json props
const shouldBeSerializable = (type) => type === Array || type === Object
let jsonProps = {}
if (!Array.isArray(options.props || {})) {
// create -json serializable props based on existing props
jsonProps = Object.keys(options.props || {}).reduce(
(coll = {}, propName) => {
const sourceProp = (options.props || {})[propName]
if (sourceProp === undefined) {
return coll
}
const type = 'type' in sourceProp ? sourceProp.type : sourceProp
if (shouldBeSerializable(type)) {
coll[propName + 'Json'] = {
type: String
}
}
return coll
},
{}
)
}
propsList = propsList.concat(Object.keys(jsonProps))
}
hyphenatedPropsList = propsList.map(hyphenate)
camelizedPropsList = propsList.map(camelize)
const originalPropsAsObject = Array.isArray(options.props)
? {}
: options.props || {}
camelizedPropsMap = camelizedPropsList.reduce((map, key, i) => {
map[key] = originalPropsAsObject[propsList[i]]
return map
}, {})
// proxy $emit to native DOM events
injectHook(options, 'beforeCreate', function () {
const emit = this.$emit
this.$emit = (name, ...args) => {
this.$root.$options.customElement.dispatchEvent(
createCustomEvent(name, args)
)
return emit.call(this, name, ...args)
}
})
injectHook(options, 'created', function () {
// sync default props values to wrapper on created
camelizedPropsList.forEach((key) => {
this.$root.props[key] = this[key]
})
})
// proxy props as Element properties
camelizedPropsList.forEach((key) => {
Object.defineProperty(CustomElement.prototype, key, {
get() {
return this._wrapper.props[key]
},
set(newVal) {
this._wrapper.props[key] = newVal
},
enumerable: false,
configurable: true
})
})
isInitialized = true
}
function syncAttribute(el, key) {
const jsonSuffixed = key.endsWith('-json')
const camelized = camelize(key.replace(/-json$/, ''))
const value = el.hasAttribute(key) ? el.getAttribute(key) : undefined
// we don't want an undefined json suffix to override the normal prop value (if any)
if (!jsonSuffixed || value) {
el._wrapper.props[camelized] = convertAttributeValue(
value,
key,
camelizedPropsMap[camelized]
)
}
}
class CustomElement extends HTMLElement {
constructor() {
const self = super()
self.attachShadow({ mode: 'open' })
const wrapper = (self._wrapper = new Vue({
name: 'shadow-root',
customElement: self,
shadowRoot: self.shadowRoot,
data() {
return {
props: {},
slotChildren: [],
ShadyDOMSlotsHack_slotsPassedToWrapper: false,
ShadyDOMSlotsHack_deregisterSetIntervalListener: null
}
},
render(h) {
return h(
Component,
{
ref: 'inner',
props: this.props
},
this.slotChildren
)
}
}))
if (window.ShadyDOM) {
// MutationObserver does not work inside shadowRoot when polyfilled with ShadyDOM
// this makes slot changes go unrecognized by our usage of MutationObserver
// https://github.com/webcomponents/polyfills/issues/81
// ShadyDOM has a function called ShadyDOM.childrenObserver but it doesn't do the job very thoroughly, as it
// cannot recognize changes in slots when the slot count hasn't changed, and seemingly doesn't recognized removal of elements (https://github.com/webcomponents/polyfills/issues/82)
// .. what it can do for us however, is to observe whether slots are ever added.
// once a slot is added, we'll apply the hack to this wrapper.
// if slots are never used, we're saving ourselves some performance cost.
window.ShadyDOM.observeChildren(this, () => {
if (!wrapper.ShadyDOMSlotsHack_slotsPassedToWrapper) {
wrapper.ShadyDOMSlotsHack_slotsPassedToWrapper = true
}
})
// Here is the ugly fix to work around the core issue, basically setInterval, but shared across all vue wc wrappers for performance
// we preserve the original MutationObserver code further down, because it observes all other changes for us.
window.ShadyDOMSlotsHack_setInterval =
window.ShadyDOMSlotsHack_setInterval ||
// eslint-disable-next-line no-extra-parens
new (function () {
this.listeners = []
this.add = (handler) => {
const id = Math.floor(Math.random() * 1000000)
this.listeners.push({
handler,
id
})
if (this.listeners.length === 1) {
// first entry added, start setInterval
this.start()
}
return id
}
this.remove = (idToRemove) => {
this.listeners.splice(
this.listeners.findIndex(({ id }) => id === idToRemove),
1
)
if (this.listeners.length === 0) {
// no entries left, stop setInterval
this.stop()
}
}
this.start = () => {
if (this.intervalId === undefined || this.intervalId === null) {
this.intervalId = window.setInterval(() => {
this.listeners.forEach(({ handler }) => handler())
}, 100)
}
}
this.stop = () => {
if (this.intervalId) {
window.clearInterval(this.intervalId)
this.intervalId = null
}
}
})()
const id = window.ShadyDOMSlotsHack_setInterval.add(() => {
if (wrapper.ShadyDOMSlotsHack_slotsPassedToWrapper) {
// slots were added to the wrapper at some point, so update children at every interval
this.updateSlotChildren()
}
})
wrapper.ShadyDOMSlotsHack_deregisterSetIntervalListener = () =>
window.ShadyDOMSlotsHack_setInterval.remove(id)
}
// Use MutationObserver to react to future attribute & slot content change
const observer = new MutationObserver((mutations) => {
let hasChildrenChange = false
for (let i = 0; i < mutations.length; i++) {
const m = mutations[i]
if (isInitialized && m.type === 'attributes' && m.target === self) {
syncAttribute(self, m.attributeName)
} else {
hasChildrenChange = true
}
}
if (hasChildrenChange) {
this.updateSlotChildren()
}
})
observer.observe(self, {
childList: true,
subtree: true,
characterData: true,
attributes: true
})
}
get vueComponent() {
return this._wrapper.$refs.inner
}
updateSlotChildren() {
this._wrapper.slotChildren = Object.freeze(
toVNodes(this._wrapper.$createElement, this.childNodes)
)
if (this._wrapper.slotChildren.length === 0) {
// no slots present, revert the shadyDOM hack (if present)
this._wrapper.ShadyDOMSlotsHack_slotsPassedToWrapper = false
}
}
async connectedCallback() {
const wrapper = this._wrapper
// TODO: Vue's router will be instantiated immediately, before the router
// in `mover-app` has finished transitioning URLs, making the Vue router
// resolve the wrong URL. Wait one micro-task to allow `mover-app`'s
// router to finish transitioning.
await Promise.resolve()
if (!wrapper._isMounted) {
// initialize attributes
const syncInitialAttributes = () => {
wrapper.props = getInitialProps(camelizedPropsList)
hyphenatedPropsList.forEach((key) => {
syncAttribute(this, key)
})
}
if (isInitialized) {
syncInitialAttributes()
} else {
// async & unresolved
Component().then((resolved) => {
if (
resolved.__esModule ||
// assume userland has polyfilled this
// eslint-disable-next-line
resolved[Symbol.toStringTag] === 'Module'
) {
resolved = resolved.default
}
initialize(resolved)
syncInitialAttributes()
})
}
// initialize children
this.updateSlotChildren()
// doing this will let us access the shadow root via `this.$root.$el.getRootNode()`
// inside of the mounted hook, which is important for copying global styles to the shadow dom.
const tempContainer = document.createElement('div')
this.shadowRoot.appendChild(tempContainer)
if (wrapOptions.globalStyles) {
// all initial styles
cloneElementsToShadowRoot(
this.shadowRoot,
getAllStyles(
wrapOptions.globalStyles.target,
wrapOptions.globalStyles.selector,
wrapOptions.globalStyles.filter
)
)
// all added styles
observeStyleChanges(
(elements) => {
cloneElementsToShadowRoot(this.shadowRoot, elements)
},
wrapOptions.globalStyles.target,
wrapOptions.globalStyles.selector,
wrapOptions.globalStyles.filter,
wrapOptions.globalStyles.observeOptions
)
}
// tempContainer will be completely rewritten
wrapper.$mount(tempContainer)
} else {
callHooks(this.vueComponent, 'activated')
}
}
disconnectedCallback() {
if (
this._wrapper &&
this._wrapper.ShadyDOMSlotsHack_deregisterSetIntervalListener
) {
this._wrapper.ShadyDOMSlotsHack_deregisterSetIntervalListener()
}
callHooks(this.vueComponent, 'deactivated')
}
}
if (!isAsync) {
initialize(Component)
}
return CustomElement
}