UNPKG

@deckdeckgo/highlight-code

Version:

A Web Component to highlight your code

1,266 lines (1,263 loc) 57.2 kB
'use strict'; function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n['default'] = e; return Object.freeze(n); } const NAMESPACE = 'deckdeckgo-highlight-code'; let scopeId; let hostTagName; let isSvgMode = false; let queuePending = false; const win = typeof window !== 'undefined' ? window : {}; const doc = win.document || { head: {} }; const plt = { $flags$: 0, $resourcesUrl$: '', jmp: (h) => h(), raf: (h) => requestAnimationFrame(h), ael: (el, eventName, listener, opts) => el.addEventListener(eventName, listener, opts), rel: (el, eventName, listener, opts) => el.removeEventListener(eventName, listener, opts), ce: (eventName, opts) => new CustomEvent(eventName, opts), }; const promiseResolve = (v) => Promise.resolve(v); const supportsConstructableStylesheets = /*@__PURE__*/ (() => { try { new CSSStyleSheet(); return typeof new CSSStyleSheet().replaceSync === 'function'; } catch (e) { } return false; })() ; const addHostEventListeners = (elm, hostRef, listeners, attachParentListeners) => { if (listeners) { listeners.map(([flags, name, method]) => { const target = getHostListenerTarget(elm, flags) ; const handler = hostListenerProxy(hostRef, method); const opts = hostListenerOpts(flags); plt.ael(target, name, handler, opts); (hostRef.$rmListeners$ = hostRef.$rmListeners$ || []).push(() => plt.rel(target, name, handler, opts)); }); } }; const hostListenerProxy = (hostRef, methodName) => (ev) => { try { { if (hostRef.$flags$ & 256 /* isListenReady */) { // instance is ready, let's call it's member method for this event hostRef.$lazyInstance$[methodName](ev); } else { (hostRef.$queuedListeners$ = hostRef.$queuedListeners$ || []).push([methodName, ev]); } } } catch (e) { consoleError(e); } }; const getHostListenerTarget = (elm, flags) => { if (flags & 4 /* TargetDocument */) return doc; return elm; }; // prettier-ignore const hostListenerOpts = (flags) => (flags & 2 /* Capture */) !== 0; const HYDRATED_CSS = '{visibility:hidden}.hydrated{visibility:inherit}'; const XLINK_NS = 'http://www.w3.org/1999/xlink'; const createTime = (fnName, tagName = '') => { { return () => { return; }; } }; const uniqueTime = (key, measureText) => { { return () => { return; }; } }; const rootAppliedStyles = new WeakMap(); const registerStyle = (scopeId, cssText, allowCS) => { let style = styles.get(scopeId); if (supportsConstructableStylesheets && allowCS) { style = (style || new CSSStyleSheet()); if (typeof style === 'string') { style = cssText; } else { style.replaceSync(cssText); } } else { style = cssText; } styles.set(scopeId, style); }; const addStyle = (styleContainerNode, cmpMeta, mode, hostElm) => { let scopeId = getScopeId(cmpMeta); const style = styles.get(scopeId); // if an element is NOT connected then getRootNode() will return the wrong root node // so the fallback is to always use the document for the root node in those cases styleContainerNode = styleContainerNode.nodeType === 11 /* DocumentFragment */ ? styleContainerNode : doc; if (style) { if (typeof style === 'string') { styleContainerNode = styleContainerNode.head || styleContainerNode; let appliedStyles = rootAppliedStyles.get(styleContainerNode); let styleElm; if (!appliedStyles) { rootAppliedStyles.set(styleContainerNode, (appliedStyles = new Set())); } if (!appliedStyles.has(scopeId)) { { { styleElm = doc.createElement('style'); styleElm.innerHTML = style; } styleContainerNode.insertBefore(styleElm, styleContainerNode.querySelector('link')); } if (appliedStyles) { appliedStyles.add(scopeId); } } } else if (!styleContainerNode.adoptedStyleSheets.includes(style)) { styleContainerNode.adoptedStyleSheets = [...styleContainerNode.adoptedStyleSheets, style]; } } return scopeId; }; const attachStyles = (hostRef) => { const cmpMeta = hostRef.$cmpMeta$; const elm = hostRef.$hostElement$; const flags = cmpMeta.$flags$; const endAttachStyles = createTime('attachStyles', cmpMeta.$tagName$); const scopeId = addStyle(elm.shadowRoot ? elm.shadowRoot : elm.getRootNode(), cmpMeta); if (flags & 10 /* needsScopedEncapsulation */) { // only required when we're NOT using native shadow dom (slot) // or this browser doesn't support native shadow dom // and this host element was NOT created with SSR // let's pick out the inner content for slot projection // create a node to represent where the original // content was first placed, which is useful later on // DOM WRITE!! elm['s-sc'] = scopeId; elm.classList.add(scopeId + '-h'); } endAttachStyles(); }; const getScopeId = (cmp, mode) => 'sc-' + (cmp.$tagName$); /** * Default style mode id */ /** * Reusable empty obj/array * Don't add values to these!! */ const EMPTY_OBJ = {}; /** * Namespaces */ const SVG_NS = 'http://www.w3.org/2000/svg'; const HTML_NS = 'http://www.w3.org/1999/xhtml'; const isDef = (v) => v != null; const isComplexType = (o) => { // https://jsperf.com/typeof-fn-object/5 o = typeof o; return o === 'object' || o === 'function'; }; /** * Production h() function based on Preact by * Jason Miller (@developit) * Licensed under the MIT License * https://github.com/developit/preact/blob/master/LICENSE * * Modified for Stencil's compiler and vdom */ // const stack: any[] = []; // export function h(nodeName: string | d.FunctionalComponent, vnodeData: d.PropsType, child?: d.ChildType): d.VNode; // export function h(nodeName: string | d.FunctionalComponent, vnodeData: d.PropsType, ...children: d.ChildType[]): d.VNode; const h = (nodeName, vnodeData, ...children) => { let child = null; let key = null; let simple = false; let lastSimple = false; const vNodeChildren = []; const walk = (c) => { for (let i = 0; i < c.length; i++) { child = c[i]; if (Array.isArray(child)) { walk(child); } else if (child != null && typeof child !== 'boolean') { if ((simple = typeof nodeName !== 'function' && !isComplexType(child))) { child = String(child); } if (simple && lastSimple) { // If the previous child was simple (string), we merge both vNodeChildren[vNodeChildren.length - 1].$text$ += child; } else { // Append a new vNode, if it's text, we create a text vNode vNodeChildren.push(simple ? newVNode(null, child) : child); } lastSimple = simple; } } }; walk(children); if (vnodeData) { // normalize class / classname attributes if (vnodeData.key) { key = vnodeData.key; } { const classData = vnodeData.className || vnodeData.class; if (classData) { vnodeData.class = typeof classData !== 'object' ? classData : Object.keys(classData) .filter((k) => classData[k]) .join(' '); } } } if (typeof nodeName === 'function') { // nodeName is a functional component return nodeName(vnodeData === null ? {} : vnodeData, vNodeChildren, vdomFnUtils); } const vnode = newVNode(nodeName, null); vnode.$attrs$ = vnodeData; if (vNodeChildren.length > 0) { vnode.$children$ = vNodeChildren; } { vnode.$key$ = key; } return vnode; }; const newVNode = (tag, text) => { const vnode = { $flags$: 0, $tag$: tag, $text$: text, $elm$: null, $children$: null, }; { vnode.$attrs$ = null; } { vnode.$key$ = null; } return vnode; }; const Host = {}; const isHost = (node) => node && node.$tag$ === Host; const vdomFnUtils = { forEach: (children, cb) => children.map(convertToPublic).forEach(cb), map: (children, cb) => children.map(convertToPublic).map(cb).map(convertToPrivate), }; const convertToPublic = (node) => ({ vattrs: node.$attrs$, vchildren: node.$children$, vkey: node.$key$, vname: node.$name$, vtag: node.$tag$, vtext: node.$text$, }); const convertToPrivate = (node) => { if (typeof node.vtag === 'function') { const vnodeData = Object.assign({}, node.vattrs); if (node.vkey) { vnodeData.key = node.vkey; } if (node.vname) { vnodeData.name = node.vname; } return h(node.vtag, vnodeData, ...(node.vchildren || [])); } const vnode = newVNode(node.vtag, node.vtext); vnode.$attrs$ = node.vattrs; vnode.$children$ = node.vchildren; vnode.$key$ = node.vkey; vnode.$name$ = node.vname; return vnode; }; /** * Production setAccessor() function based on Preact by * Jason Miller (@developit) * Licensed under the MIT License * https://github.com/developit/preact/blob/master/LICENSE * * Modified for Stencil's compiler and vdom */ const setAccessor = (elm, memberName, oldValue, newValue, isSvg, flags) => { if (oldValue !== newValue) { let isProp = isMemberInElement(elm, memberName); let ln = memberName.toLowerCase(); if (memberName === 'class') { const classList = elm.classList; const oldClasses = parseClassList(oldValue); const newClasses = parseClassList(newValue); classList.remove(...oldClasses.filter((c) => c && !newClasses.includes(c))); classList.add(...newClasses.filter((c) => c && !oldClasses.includes(c))); } else if (memberName === 'style') { // update style attribute, css properties and values { for (const prop in oldValue) { if (!newValue || newValue[prop] == null) { if (prop.includes('-')) { elm.style.removeProperty(prop); } else { elm.style[prop] = ''; } } } } for (const prop in newValue) { if (!oldValue || newValue[prop] !== oldValue[prop]) { if (prop.includes('-')) { elm.style.setProperty(prop, newValue[prop]); } else { elm.style[prop] = newValue[prop]; } } } } else if (memberName === 'key') ; else if (memberName === 'ref') { // minifier will clean this up if (newValue) { newValue(elm); } } else if ((!isProp ) && memberName[0] === 'o' && memberName[1] === 'n') { // Event Handlers // so if the member name starts with "on" and the 3rd characters is // a capital letter, and it's not already a member on the element, // then we're assuming it's an event listener if (memberName[2] === '-') { // on- prefixed events // allows to be explicit about the dom event to listen without any magic // under the hood: // <my-cmp on-click> // listens for "click" // <my-cmp on-Click> // listens for "Click" // <my-cmp on-ionChange> // listens for "ionChange" // <my-cmp on-EVENTS> // listens for "EVENTS" memberName = memberName.slice(3); } else if (isMemberInElement(win, ln)) { // standard event // the JSX attribute could have been "onMouseOver" and the // member name "onmouseover" is on the window's prototype // so let's add the listener "mouseover", which is all lowercased memberName = ln.slice(2); } else { // custom event // the JSX attribute could have been "onMyCustomEvent" // so let's trim off the "on" prefix and lowercase the first character // and add the listener "myCustomEvent" // except for the first character, we keep the event name case memberName = ln[2] + memberName.slice(3); } if (oldValue) { plt.rel(elm, memberName, oldValue, false); } if (newValue) { plt.ael(elm, memberName, newValue, false); } } else { // Set property if it exists and it's not a SVG const isComplex = isComplexType(newValue); if ((isProp || (isComplex && newValue !== null)) && !isSvg) { try { if (!elm.tagName.includes('-')) { const n = newValue == null ? '' : newValue; // Workaround for Safari, moving the <input> caret when re-assigning the same valued if (memberName === 'list') { isProp = false; } else if (oldValue == null || elm[memberName] != n) { elm[memberName] = n; } } else { elm[memberName] = newValue; } } catch (e) { } } /** * Need to manually update attribute if: * - memberName is not an attribute * - if we are rendering the host element in order to reflect attribute * - if it's a SVG, since properties might not work in <svg> * - if the newValue is null/undefined or 'false'. */ let xlink = false; { if (ln !== (ln = ln.replace(/^xlink\:?/, ''))) { memberName = ln; xlink = true; } } if (newValue == null || newValue === false) { if (newValue !== false || elm.getAttribute(memberName) === '') { if (xlink) { elm.removeAttributeNS(XLINK_NS, memberName); } else { elm.removeAttribute(memberName); } } } else if ((!isProp || flags & 4 /* isHost */ || isSvg) && !isComplex) { newValue = newValue === true ? '' : newValue; if (xlink) { elm.setAttributeNS(XLINK_NS, memberName, newValue); } else { elm.setAttribute(memberName, newValue); } } } } }; const parseClassListRegex = /\s/; const parseClassList = (value) => (!value ? [] : value.split(parseClassListRegex)); const updateElement = (oldVnode, newVnode, isSvgMode, memberName) => { // if the element passed in is a shadow root, which is a document fragment // then we want to be adding attrs/props to the shadow root's "host" element // if it's not a shadow root, then we add attrs/props to the same element const elm = newVnode.$elm$.nodeType === 11 /* DocumentFragment */ && newVnode.$elm$.host ? newVnode.$elm$.host : newVnode.$elm$; const oldVnodeAttrs = (oldVnode && oldVnode.$attrs$) || EMPTY_OBJ; const newVnodeAttrs = newVnode.$attrs$ || EMPTY_OBJ; { // remove attributes no longer present on the vnode by setting them to undefined for (memberName in oldVnodeAttrs) { if (!(memberName in newVnodeAttrs)) { setAccessor(elm, memberName, oldVnodeAttrs[memberName], undefined, isSvgMode, newVnode.$flags$); } } } // add new & update changed attributes for (memberName in newVnodeAttrs) { setAccessor(elm, memberName, oldVnodeAttrs[memberName], newVnodeAttrs[memberName], isSvgMode, newVnode.$flags$); } }; const createElm = (oldParentVNode, newParentVNode, childIndex, parentElm) => { // tslint:disable-next-line: prefer-const const newVNode = newParentVNode.$children$[childIndex]; let i = 0; let elm; let childNode; if (newVNode.$text$ !== null) { // create text node elm = newVNode.$elm$ = doc.createTextNode(newVNode.$text$); } else { if (!isSvgMode) { isSvgMode = newVNode.$tag$ === 'svg'; } // create element elm = newVNode.$elm$ = (doc.createElementNS(isSvgMode ? SVG_NS : HTML_NS, newVNode.$tag$) ); if (isSvgMode && newVNode.$tag$ === 'foreignObject') { isSvgMode = false; } // add css classes, attrs, props, listeners, etc. { updateElement(null, newVNode, isSvgMode); } if (isDef(scopeId) && elm['s-si'] !== scopeId) { // if there is a scopeId and this is the initial render // then let's add the scopeId as a css class elm.classList.add((elm['s-si'] = scopeId)); } if (newVNode.$children$) { for (i = 0; i < newVNode.$children$.length; ++i) { // create the node childNode = createElm(oldParentVNode, newVNode, i); // return node could have been null if (childNode) { // append our new node elm.appendChild(childNode); } } } { if (newVNode.$tag$ === 'svg') { // Only reset the SVG context when we're exiting <svg> element isSvgMode = false; } else if (elm.tagName === 'foreignObject') { // Reenter SVG context when we're exiting <foreignObject> element isSvgMode = true; } } } return elm; }; const addVnodes = (parentElm, before, parentVNode, vnodes, startIdx, endIdx) => { let containerElm = (parentElm); let childNode; if (containerElm.shadowRoot && containerElm.tagName === hostTagName) { containerElm = containerElm.shadowRoot; } for (; startIdx <= endIdx; ++startIdx) { if (vnodes[startIdx]) { childNode = createElm(null, parentVNode, startIdx); if (childNode) { vnodes[startIdx].$elm$ = childNode; containerElm.insertBefore(childNode, before); } } } }; const removeVnodes = (vnodes, startIdx, endIdx, vnode, elm) => { for (; startIdx <= endIdx; ++startIdx) { if ((vnode = vnodes[startIdx])) { elm = vnode.$elm$; callNodeRefs(vnode); // remove the vnode's element from the dom elm.remove(); } } }; const updateChildren = (parentElm, oldCh, newVNode, newCh) => { let oldStartIdx = 0; let newStartIdx = 0; let idxInOld = 0; let i = 0; let oldEndIdx = oldCh.length - 1; let oldStartVnode = oldCh[0]; let oldEndVnode = oldCh[oldEndIdx]; let newEndIdx = newCh.length - 1; let newStartVnode = newCh[0]; let newEndVnode = newCh[newEndIdx]; let node; let elmToMove; while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (oldStartVnode == null) { // Vnode might have been moved left oldStartVnode = oldCh[++oldStartIdx]; } else if (oldEndVnode == null) { oldEndVnode = oldCh[--oldEndIdx]; } else if (newStartVnode == null) { newStartVnode = newCh[++newStartIdx]; } else if (newEndVnode == null) { newEndVnode = newCh[--newEndIdx]; } else if (isSameVnode(oldStartVnode, newStartVnode)) { patch(oldStartVnode, newStartVnode); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (isSameVnode(oldEndVnode, newEndVnode)) { patch(oldEndVnode, newEndVnode); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (isSameVnode(oldStartVnode, newEndVnode)) { patch(oldStartVnode, newEndVnode); parentElm.insertBefore(oldStartVnode.$elm$, oldEndVnode.$elm$.nextSibling); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (isSameVnode(oldEndVnode, newStartVnode)) { patch(oldEndVnode, newStartVnode); parentElm.insertBefore(oldEndVnode.$elm$, oldStartVnode.$elm$); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { // createKeyToOldIdx idxInOld = -1; { for (i = oldStartIdx; i <= oldEndIdx; ++i) { if (oldCh[i] && oldCh[i].$key$ !== null && oldCh[i].$key$ === newStartVnode.$key$) { idxInOld = i; break; } } } if (idxInOld >= 0) { elmToMove = oldCh[idxInOld]; if (elmToMove.$tag$ !== newStartVnode.$tag$) { node = createElm(oldCh && oldCh[newStartIdx], newVNode, idxInOld); } else { patch(elmToMove, newStartVnode); oldCh[idxInOld] = undefined; node = elmToMove.$elm$; } newStartVnode = newCh[++newStartIdx]; } else { // new element node = createElm(oldCh && oldCh[newStartIdx], newVNode, newStartIdx); newStartVnode = newCh[++newStartIdx]; } if (node) { { oldStartVnode.$elm$.parentNode.insertBefore(node, oldStartVnode.$elm$); } } } } if (oldStartIdx > oldEndIdx) { addVnodes(parentElm, newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].$elm$, newVNode, newCh, newStartIdx, newEndIdx); } else if (newStartIdx > newEndIdx) { removeVnodes(oldCh, oldStartIdx, oldEndIdx); } }; const isSameVnode = (vnode1, vnode2) => { // compare if two vnode to see if they're "technically" the same // need to have the same element tag, and same key to be the same if (vnode1.$tag$ === vnode2.$tag$) { { return vnode1.$key$ === vnode2.$key$; } } return false; }; const patch = (oldVNode, newVNode) => { const elm = (newVNode.$elm$ = oldVNode.$elm$); const oldChildren = oldVNode.$children$; const newChildren = newVNode.$children$; const tag = newVNode.$tag$; const text = newVNode.$text$; if (text === null) { { // test if we're rendering an svg element, or still rendering nodes inside of one // only add this to the when the compiler sees we're using an svg somewhere isSvgMode = tag === 'svg' ? true : tag === 'foreignObject' ? false : isSvgMode; } // element node { if (tag === 'slot') ; else { // either this is the first render of an element OR it's an update // AND we already know it's possible it could have changed // this updates the element's css classes, attrs, props, listeners, etc. updateElement(oldVNode, newVNode, isSvgMode); } } if (oldChildren !== null && newChildren !== null) { // looks like there's child vnodes for both the old and new vnodes updateChildren(elm, oldChildren, newVNode, newChildren); } else if (newChildren !== null) { // no old child vnodes, but there are new child vnodes to add if (oldVNode.$text$ !== null) { // the old vnode was text, so be sure to clear it out elm.textContent = ''; } // add the new vnode children addVnodes(elm, null, newVNode, newChildren, 0, newChildren.length - 1); } else if (oldChildren !== null) { // no new child vnodes, but there are old child vnodes to remove removeVnodes(oldChildren, 0, oldChildren.length - 1); } if (isSvgMode && tag === 'svg') { isSvgMode = false; } } else if (oldVNode.$text$ !== text) { // update the text content for the text only vnode // and also only if the text is different than before elm.data = text; } }; const callNodeRefs = (vNode) => { { vNode.$attrs$ && vNode.$attrs$.ref && vNode.$attrs$.ref(null); vNode.$children$ && vNode.$children$.map(callNodeRefs); } }; const renderVdom = (hostRef, renderFnResults) => { const hostElm = hostRef.$hostElement$; const cmpMeta = hostRef.$cmpMeta$; const oldVNode = hostRef.$vnode$ || newVNode(null, null); const rootVnode = isHost(renderFnResults) ? renderFnResults : h(null, null, renderFnResults); hostTagName = hostElm.tagName; if (cmpMeta.$attrsToReflect$) { rootVnode.$attrs$ = rootVnode.$attrs$ || {}; cmpMeta.$attrsToReflect$.map(([propName, attribute]) => (rootVnode.$attrs$[attribute] = hostElm[propName])); } rootVnode.$tag$ = null; rootVnode.$flags$ |= 4 /* isHost */; hostRef.$vnode$ = rootVnode; rootVnode.$elm$ = oldVNode.$elm$ = (hostElm.shadowRoot || hostElm ); { scopeId = hostElm['s-sc']; } // synchronous patch patch(oldVNode, rootVnode); }; const getElement = (ref) => (getHostRef(ref).$hostElement$ ); const createEvent = (ref, name, flags) => { const elm = getElement(ref); return { emit: (detail) => { return emitEvent(elm, name, { bubbles: !!(flags & 4 /* Bubbles */), composed: !!(flags & 2 /* Composed */), cancelable: !!(flags & 1 /* Cancellable */), detail, }); }, }; }; /** * Helper function to create & dispatch a custom Event on a provided target * @param elm the target of the Event * @param name the name to give the custom Event * @param opts options for configuring a custom Event * @returns the custom Event */ const emitEvent = (elm, name, opts) => { const ev = plt.ce(name, opts); elm.dispatchEvent(ev); return ev; }; const attachToAncestor = (hostRef, ancestorComponent) => { if (ancestorComponent && !hostRef.$onRenderResolve$ && ancestorComponent['s-p']) { ancestorComponent['s-p'].push(new Promise((r) => (hostRef.$onRenderResolve$ = r))); } }; const scheduleUpdate = (hostRef, isInitialLoad) => { { hostRef.$flags$ |= 16 /* isQueuedForUpdate */; } if (hostRef.$flags$ & 4 /* isWaitingForChildren */) { hostRef.$flags$ |= 512 /* needsRerender */; return; } attachToAncestor(hostRef, hostRef.$ancestorComponent$); // there is no ancestor component or the ancestor component // has already fired off its lifecycle update then // fire off the initial update const dispatch = () => dispatchHooks(hostRef, isInitialLoad); return writeTask(dispatch) ; }; const dispatchHooks = (hostRef, isInitialLoad) => { const endSchedule = createTime('scheduleUpdate', hostRef.$cmpMeta$.$tagName$); const instance = hostRef.$lazyInstance$ ; let promise; if (isInitialLoad) { { hostRef.$flags$ |= 256 /* isListenReady */; if (hostRef.$queuedListeners$) { hostRef.$queuedListeners$.map(([methodName, event]) => safeCall(instance, methodName, event)); hostRef.$queuedListeners$ = null; } } { promise = safeCall(instance, 'componentWillLoad'); } } endSchedule(); return then(promise, () => updateComponent(hostRef, instance, isInitialLoad)); }; const updateComponent = async (hostRef, instance, isInitialLoad) => { // updateComponent const elm = hostRef.$hostElement$; const endUpdate = createTime('update', hostRef.$cmpMeta$.$tagName$); const rc = elm['s-rc']; if (isInitialLoad) { // DOM WRITE! attachStyles(hostRef); } const endRender = createTime('render', hostRef.$cmpMeta$.$tagName$); { callRender(hostRef, instance); } if (rc) { // ok, so turns out there are some child host elements // waiting on this parent element to load // let's fire off all update callbacks waiting rc.map((cb) => cb()); elm['s-rc'] = undefined; } endRender(); endUpdate(); { const childrenPromises = elm['s-p']; const postUpdate = () => postUpdateComponent(hostRef); if (childrenPromises.length === 0) { postUpdate(); } else { Promise.all(childrenPromises).then(postUpdate); hostRef.$flags$ |= 4 /* isWaitingForChildren */; childrenPromises.length = 0; } } }; const callRender = (hostRef, instance, elm) => { try { instance = instance.render() ; { hostRef.$flags$ &= ~16 /* isQueuedForUpdate */; } { hostRef.$flags$ |= 2 /* hasRendered */; } { { // looks like we've got child nodes to render into this host element // or we need to update the css class/attrs on the host element // DOM WRITE! { renderVdom(hostRef, instance); } } } } catch (e) { consoleError(e, hostRef.$hostElement$); } return null; }; const postUpdateComponent = (hostRef) => { const tagName = hostRef.$cmpMeta$.$tagName$; const elm = hostRef.$hostElement$; const endPostUpdate = createTime('postUpdate', tagName); const instance = hostRef.$lazyInstance$ ; const ancestorComponent = hostRef.$ancestorComponent$; if (!(hostRef.$flags$ & 64 /* hasLoadedComponent */)) { hostRef.$flags$ |= 64 /* hasLoadedComponent */; { // DOM WRITE! addHydratedFlag(elm); } { safeCall(instance, 'componentDidLoad'); } endPostUpdate(); { hostRef.$onReadyResolve$(elm); if (!ancestorComponent) { appDidLoad(); } } } else { { safeCall(instance, 'componentDidUpdate'); } endPostUpdate(); } { hostRef.$onInstanceResolve$(elm); } // load events fire from bottom to top // the deepest elements load first then bubbles up { if (hostRef.$onRenderResolve$) { hostRef.$onRenderResolve$(); hostRef.$onRenderResolve$ = undefined; } if (hostRef.$flags$ & 512 /* needsRerender */) { nextTick(() => scheduleUpdate(hostRef, false)); } hostRef.$flags$ &= ~(4 /* isWaitingForChildren */ | 512 /* needsRerender */); } // ( •_•) // ( •_•)>⌐■-■ // (⌐■_■) }; const appDidLoad = (who) => { // on appload // we have finish the first big initial render { addHydratedFlag(doc.documentElement); } nextTick(() => emitEvent(win, 'appload', { detail: { namespace: NAMESPACE } })); }; const safeCall = (instance, method, arg) => { if (instance && instance[method]) { try { return instance[method](arg); } catch (e) { consoleError(e); } } return undefined; }; const then = (promise, thenFn) => { return promise && promise.then ? promise.then(thenFn) : thenFn(); }; const addHydratedFlag = (elm) => elm.classList.add('hydrated') ; /** * Parse a new property value for a given property type. * * While the prop value can reasonably be expected to be of `any` type as far as TypeScript's type checker is concerned, * it is not safe to assume that the string returned by evaluating `typeof propValue` matches: * 1. `any`, the type given to `propValue` in the function signature * 2. the type stored from `propType`. * * This function provides the capability to parse/coerce a property's value to potentially any other JavaScript type. * * Property values represented in TSX preserve their type information. In the example below, the number 0 is passed to * a component. This `propValue` will preserve its type information (`typeof propValue === 'number'`). Note that is * based on the type of the value being passed in, not the type declared of the class member decorated with `@Prop`. * ```tsx * <my-cmp prop-val={0}></my-cmp> * ``` * * HTML prop values on the other hand, will always a string * * @param propValue the new value to coerce to some type * @param propType the type of the prop, expressed as a binary number * @returns the parsed/coerced value */ const parsePropertyValue = (propValue, propType) => { // ensure this value is of the correct prop type if (propValue != null && !isComplexType(propValue)) { if (propType & 4 /* Boolean */) { // per the HTML spec, any string value means it is a boolean true value // but we'll cheat here and say that the string "false" is the boolean false return propValue === 'false' ? false : propValue === '' || !!propValue; } if (propType & 1 /* String */) { // could have been passed as a number or boolean // but we still want it as a string return String(propValue); } // redundant return here for better minification return propValue; } // not sure exactly what type we want // so no need to change to a different type return propValue; }; const getValue = (ref, propName) => getHostRef(ref).$instanceValues$.get(propName); const setValue = (ref, propName, newVal, cmpMeta) => { // check our new property value against our internal value const hostRef = getHostRef(ref); const elm = hostRef.$hostElement$ ; const oldVal = hostRef.$instanceValues$.get(propName); const flags = hostRef.$flags$; const instance = hostRef.$lazyInstance$ ; newVal = parsePropertyValue(newVal, cmpMeta.$members$[propName][0]); // explicitly check for NaN on both sides, as `NaN === NaN` is always false const areBothNaN = Number.isNaN(oldVal) && Number.isNaN(newVal); const didValueChange = newVal !== oldVal && !areBothNaN; if ((!(flags & 8 /* isConstructingInstance */) || oldVal === undefined) && didValueChange) { // gadzooks! the property's value has changed!! // set our new value! hostRef.$instanceValues$.set(propName, newVal); if (instance) { // get an array of method names of watch functions to call if (cmpMeta.$watchers$ && flags & 128 /* isWatchReady */) { const watchMethods = cmpMeta.$watchers$[propName]; if (watchMethods) { // this instance is watching for when this property changed watchMethods.map((watchMethodName) => { try { // fire off each of the watch methods that are watching this property instance[watchMethodName](newVal, oldVal, propName); } catch (e) { consoleError(e, elm); } }); } } if ((flags & (2 /* hasRendered */ | 16 /* isQueuedForUpdate */)) === 2 /* hasRendered */) { // looks like this value actually changed, so we've got work to do! // but only if we've already rendered, otherwise just chill out // queue that we need to do an update, but don't worry about queuing // up millions cuz this function ensures it only runs once scheduleUpdate(hostRef, false); } } } }; const proxyComponent = (Cstr, cmpMeta, flags) => { if (cmpMeta.$members$) { if (Cstr.watchers) { cmpMeta.$watchers$ = Cstr.watchers; } // It's better to have a const than two Object.entries() const members = Object.entries(cmpMeta.$members$); const prototype = Cstr.prototype; members.map(([memberName, [memberFlags]]) => { if ((memberFlags & 31 /* Prop */ || ((flags & 2 /* proxyState */) && memberFlags & 32 /* State */))) { // proxyComponent - prop Object.defineProperty(prototype, memberName, { get() { // proxyComponent, get value return getValue(this, memberName); }, set(newValue) { // proxyComponent, set value setValue(this, memberName, newValue, cmpMeta); }, configurable: true, enumerable: true, }); } else if (flags & 1 /* isElementConstructor */ && memberFlags & 64 /* Method */) { // proxyComponent - method Object.defineProperty(prototype, memberName, { value(...args) { const ref = getHostRef(this); return ref.$onInstancePromise$.then(() => ref.$lazyInstance$[memberName](...args)); }, }); } }); if ((flags & 1 /* isElementConstructor */)) { const attrNameToPropName = new Map(); prototype.attributeChangedCallback = function (attrName, _oldValue, newValue) { plt.jmp(() => { const propName = attrNameToPropName.get(attrName); // In a web component lifecycle the attributeChangedCallback runs prior to connectedCallback // in the case where an attribute was set inline. // ```html // <my-component some-attribute="some-value"></my-component> // ``` // // There is an edge case where a developer sets the attribute inline on a custom element and then // programmatically changes it before it has been upgraded as shown below: // // ```html // <!-- this component has _not_ been upgraded yet --> // <my-component id="test" some-attribute="some-value"></my-component> // <script> // // grab non-upgraded component // el = document.querySelector("#test"); // el.someAttribute = "another-value"; // // upgrade component // customElements.define('my-component', MyComponent); // </script> // ``` // In this case if we do not unshadow here and use the value of the shadowing property, attributeChangedCallback // will be called with `newValue = "some-value"` and will set the shadowed property (this.someAttribute = "another-value") // to the value that was set inline i.e. "some-value" from above example. When // the connectedCallback attempts to unshadow it will use "some-value" as the initial value rather than "another-value" // // The case where the attribute was NOT set inline but was not set programmatically shall be handled/unshadowed // by connectedCallback as this attributeChangedCallback will not fire. // // https://developers.google.com/web/fundamentals/web-components/best-practices#lazy-properties // // TODO(STENCIL-16) we should think about whether or not we actually want to be reflecting the attributes to // properties here given that this goes against best practices outlined here // https://developers.google.com/web/fundamentals/web-components/best-practices#avoid-reentrancy if (this.hasOwnProperty(propName)) { newValue = this[propName]; delete this[propName]; } else if (prototype.hasOwnProperty(propName) && typeof this[propName] === 'number' && this[propName] == newValue) { // if the propName exists on the prototype of `Cstr`, this update may be a result of Stencil using native // APIs to reflect props as attributes. Calls to `setAttribute(someElement, propName)` will result in // `propName` to be converted to a `DOMString`, which may not be what we want for other primitive props. return; } this[propName] = newValue === null && typeof this[propName] === 'boolean' ? false : newValue; }); }; // create an array of attributes to observe // and also create a map of html attribute name to js property name Cstr.observedAttributes = members .filter(([_, m]) => m[0] & 15 /* HasAttribute */) // filter to only keep props that should match attributes .map(([propName, m]) => { const attrName = m[1] || propName; attrNameToPropName.set(attrName, propName); if (m[0] & 512 /* ReflectAttr */) { cmpMeta.$attrsToReflect$.push([propName, attrName]); } return attrName; }); } } return Cstr; }; const initializeComponent = async (elm, hostRef, cmpMeta, hmrVersionId, Cstr) => { // initializeComponent if ((hostRef.$flags$ & 32 /* hasInitializedComponent */) === 0) { { // we haven't initialized this element yet hostRef.$flags$ |= 32 /* hasInitializedComponent */; // lazy loaded components // request the component's implementation to be // wired up with the host element Cstr = loadModule(cmpMeta); if (Cstr.then) { // Await creates a micro-task avoid if possible const endLoad = uniqueTime(); Cstr = await Cstr; endLoad(); } if (!Cstr.isProxied) { // we've never proxied this Constructor before // let's add the getters/setters to its prototype before // the first time we create an instance of the implementation { cmpMeta.$watchers$ = Cstr.watchers; } proxyComponent(Cstr, cmpMeta, 2 /* proxyState */); Cstr.isProxied = true; } const endNewInstance = createTime('createInstance', cmpMeta.$tagName$); // ok, time to construct the instance // but let's keep track of when we start and stop // so that the getters/setters don't incorrectly step on data { hostRef.$flags$ |= 8 /* isConstructingInstance */; } // construct the lazy-loaded component implementation // passing the hostRef is very important during // construction in order to directly wire together the // host element and the lazy-loaded instance try { new Cstr(hostRef); } catch (e) { consoleError(e); } { hostRef.$flags$ &= ~8 /* isConstructingInstance */; } { hostRef.$flags$ |= 128 /* isWatchReady */; } endNewInstance(); } if (Cstr.style) { // this component has styles but we haven't registered them yet let style = Cstr.style; const scopeId = getScopeId(cmpMeta); if (!styles.has(scopeId)) { const endRegisterStyles = createTime('registerStyles', cmpMeta.$tagName$); registerStyle(scopeId, style, !!(cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */)); endRegisterStyles(); } } } // we've successfully created a lazy instance const ancestorComponent = hostRef.$ancestorComponent$; const schedule = () => scheduleUpdate(hostRef, true); if (ancestorComponent && ancestorComponent['s-rc']) { // this is the initial load and this component it has an ancestor component // but the ancestor component has NOT fired its will update lifecycle yet // so let's just cool our jets and wait for the ancestor to continue first // this will get fired off when the ancestor component // finally gets around to rendering its lazy self // fire off the initial update ancestorComponent['s-rc'].push(schedule); } else { schedule(); } }; const connectedCallback = (elm) => { if ((plt.$flags$ & 1 /* isTmpDisconnected */) === 0) { const hostRef = getHostRef(elm); const cmpMeta = hostRef.$cmpMeta$; const endConnected = createTime('connectedCallback', cmpMeta.$tagName$); if (!(hostRef.$flags$ & 1 /* hasConnected */)) { // first time this component has connected hostRef.$flags$ |= 1 /* hasConnected */; { // find the first ancestor component (if there is one) and register // this component as one of the actively loading child components for its ancestor let ancestorComponent = elm; while ((ancestorComponent = ancestorComponent.parentNode || ancestorComponent.host)) { // climb up the ancestors looking for the first // component that hasn't finished its lifecycle update yet if (ancestorComponent['s-p']) { // we found this components first ancestor component // keep a reference to this component's ancestor component attachToAncestor(hostRef, (hostRef.$ancestorComponent$ = ancestorComponent)); break; } } } // Lazy properties // https://developers.google.com/web/fundamentals/web-components/best-practices#lazy-properties if (cmpMeta.$members$) { Object.entries(cmpMeta.$members$).map(([memberName, [memberFlags]]) => { if (memberFlags & 31 /* Prop */ && elm.hasOwnProperty(memberName)) { const value = elm[memberName]; delete elm[memberName]; elm[memberName] = value; } }); } { initializeComponent(elm, hostRef, cmpMeta); } } else { // not the first time this has connected // reattach any event listeners to the host // since they would have been removed when disconnected addHostEventListeners(elm, hostRef, cmpMeta.$listeners$); } endConnected(); } }; const disconnectedCallback = (elm) => { if ((plt.$flags$ & 1 /* isTmpDisconnected */) === 0) { const hostRef = getHostRef(elm); { if (hostRef.$rmListeners$) { hostRef.$rmListeners$.map((rmListener) => rmListener()); hostRef.$rmListeners$ = undefined; } } } }; const bootstrapLazy = (lazyBundles, options = {}) => { const endBootstrap = createTime(); const cmpTags = []; const exclude = options.exclude || []; const customElements = win.customElements; const head = doc.head; const metaCharset = /*@__PURE__*/ head.querySelector('meta[charset]'