index.js 142 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262
  1. /**
  2. * Virtual DOM patching algorithm based on Snabbdom by
  3. * Simon Friis Vindum (@paldepind)
  4. * Licensed under the MIT License
  5. * https://github.com/snabbdom/snabbdom/blob/master/LICENSE
  6. *
  7. * Modified for Stencil's renderer and slot projection
  8. */
  9. let scopeId;
  10. let contentRef;
  11. let hostTagName;
  12. let customError;
  13. let i = 0;
  14. let useNativeShadowDom = false;
  15. let checkSlotFallbackVisibility = false;
  16. let checkSlotRelocate = false;
  17. let isSvgMode = false;
  18. let renderingRef = null;
  19. let queueCongestion = 0;
  20. let queuePending = false;
  21. /*
  22. Stencil Client Platform v2.18.1 | MIT Licensed | https://stenciljs.com
  23. */
  24. import { BUILD, NAMESPACE } from '@stencil/core/internal/app-data';
  25. const Build = {
  26. isDev: BUILD.isDev ? true : false,
  27. isBrowser: true,
  28. isServer: false,
  29. isTesting: BUILD.isTesting ? true : false,
  30. };
  31. const Context = {};
  32. const getAssetPath = (path) => {
  33. const assetUrl = new URL(path, plt.$resourcesUrl$);
  34. return assetUrl.origin !== win.location.origin ? assetUrl.href : assetUrl.pathname;
  35. };
  36. const setAssetPath = (path) => (plt.$resourcesUrl$ = path);
  37. const createTime = (fnName, tagName = '') => {
  38. if (BUILD.profile && performance.mark) {
  39. const key = `st:${fnName}:${tagName}:${i++}`;
  40. // Start
  41. performance.mark(key);
  42. // End
  43. return () => performance.measure(`[Stencil] ${fnName}() <${tagName}>`, key);
  44. }
  45. else {
  46. return () => {
  47. return;
  48. };
  49. }
  50. };
  51. const uniqueTime = (key, measureText) => {
  52. if (BUILD.profile && performance.mark) {
  53. if (performance.getEntriesByName(key).length === 0) {
  54. performance.mark(key);
  55. }
  56. return () => {
  57. if (performance.getEntriesByName(measureText).length === 0) {
  58. performance.measure(measureText, key);
  59. }
  60. };
  61. }
  62. else {
  63. return () => {
  64. return;
  65. };
  66. }
  67. };
  68. const inspect = (ref) => {
  69. const hostRef = getHostRef(ref);
  70. if (!hostRef) {
  71. return undefined;
  72. }
  73. const flags = hostRef.$flags$;
  74. const hostElement = hostRef.$hostElement$;
  75. return {
  76. renderCount: hostRef.$renderCount$,
  77. flags: {
  78. hasRendered: !!(flags & 2 /* HOST_FLAGS.hasRendered */),
  79. hasConnected: !!(flags & 1 /* HOST_FLAGS.hasConnected */),
  80. isWaitingForChildren: !!(flags & 4 /* HOST_FLAGS.isWaitingForChildren */),
  81. isConstructingInstance: !!(flags & 8 /* HOST_FLAGS.isConstructingInstance */),
  82. isQueuedForUpdate: !!(flags & 16 /* HOST_FLAGS.isQueuedForUpdate */),
  83. hasInitializedComponent: !!(flags & 32 /* HOST_FLAGS.hasInitializedComponent */),
  84. hasLoadedComponent: !!(flags & 64 /* HOST_FLAGS.hasLoadedComponent */),
  85. isWatchReady: !!(flags & 128 /* HOST_FLAGS.isWatchReady */),
  86. isListenReady: !!(flags & 256 /* HOST_FLAGS.isListenReady */),
  87. needsRerender: !!(flags & 512 /* HOST_FLAGS.needsRerender */),
  88. },
  89. instanceValues: hostRef.$instanceValues$,
  90. ancestorComponent: hostRef.$ancestorComponent$,
  91. hostElement,
  92. lazyInstance: hostRef.$lazyInstance$,
  93. vnode: hostRef.$vnode$,
  94. modeName: hostRef.$modeName$,
  95. onReadyPromise: hostRef.$onReadyPromise$,
  96. onReadyResolve: hostRef.$onReadyResolve$,
  97. onInstancePromise: hostRef.$onInstancePromise$,
  98. onInstanceResolve: hostRef.$onInstanceResolve$,
  99. onRenderResolve: hostRef.$onRenderResolve$,
  100. queuedListeners: hostRef.$queuedListeners$,
  101. rmListeners: hostRef.$rmListeners$,
  102. ['s-id']: hostElement['s-id'],
  103. ['s-cr']: hostElement['s-cr'],
  104. ['s-lr']: hostElement['s-lr'],
  105. ['s-p']: hostElement['s-p'],
  106. ['s-rc']: hostElement['s-rc'],
  107. ['s-sc']: hostElement['s-sc'],
  108. };
  109. };
  110. const installDevTools = () => {
  111. if (BUILD.devTools) {
  112. const stencil = (win.stencil = win.stencil || {});
  113. const originalInspect = stencil.inspect;
  114. stencil.inspect = (ref) => {
  115. let result = inspect(ref);
  116. if (!result && typeof originalInspect === 'function') {
  117. result = originalInspect(ref);
  118. }
  119. return result;
  120. };
  121. }
  122. };
  123. const CONTENT_REF_ID = 'r';
  124. const ORG_LOCATION_ID = 'o';
  125. const SLOT_NODE_ID = 's';
  126. const TEXT_NODE_ID = 't';
  127. const HYDRATE_ID = 's-id';
  128. const HYDRATED_STYLE_ID = 'sty-id';
  129. const HYDRATE_CHILD_ID = 'c-id';
  130. const HYDRATED_CSS = '{visibility:hidden}.hydrated{visibility:inherit}';
  131. const XLINK_NS = 'http://www.w3.org/1999/xlink';
  132. /**
  133. * Default style mode id
  134. */
  135. /**
  136. * Reusable empty obj/array
  137. * Don't add values to these!!
  138. */
  139. const EMPTY_OBJ = {};
  140. /**
  141. * Namespaces
  142. */
  143. const SVG_NS = 'http://www.w3.org/2000/svg';
  144. const HTML_NS = 'http://www.w3.org/1999/xhtml';
  145. const isDef = (v) => v != null;
  146. const isComplexType = (o) => {
  147. // https://jsperf.com/typeof-fn-object/5
  148. o = typeof o;
  149. return o === 'object' || o === 'function';
  150. };
  151. /**
  152. * Production h() function based on Preact by
  153. * Jason Miller (@developit)
  154. * Licensed under the MIT License
  155. * https://github.com/developit/preact/blob/master/LICENSE
  156. *
  157. * Modified for Stencil's compiler and vdom
  158. */
  159. // const stack: any[] = [];
  160. // export function h(nodeName: string | d.FunctionalComponent, vnodeData: d.PropsType, child?: d.ChildType): d.VNode;
  161. // export function h(nodeName: string | d.FunctionalComponent, vnodeData: d.PropsType, ...children: d.ChildType[]): d.VNode;
  162. const h = (nodeName, vnodeData, ...children) => {
  163. let child = null;
  164. let key = null;
  165. let slotName = null;
  166. let simple = false;
  167. let lastSimple = false;
  168. const vNodeChildren = [];
  169. const walk = (c) => {
  170. for (let i = 0; i < c.length; i++) {
  171. child = c[i];
  172. if (Array.isArray(child)) {
  173. walk(child);
  174. }
  175. else if (child != null && typeof child !== 'boolean') {
  176. if ((simple = typeof nodeName !== 'function' && !isComplexType(child))) {
  177. child = String(child);
  178. }
  179. else if (BUILD.isDev && typeof nodeName !== 'function' && child.$flags$ === undefined) {
  180. consoleDevError(`vNode passed as children has unexpected type.
  181. Make sure it's using the correct h() function.
  182. Empty objects can also be the cause, look for JSX comments that became objects.`);
  183. }
  184. if (simple && lastSimple) {
  185. // If the previous child was simple (string), we merge both
  186. vNodeChildren[vNodeChildren.length - 1].$text$ += child;
  187. }
  188. else {
  189. // Append a new vNode, if it's text, we create a text vNode
  190. vNodeChildren.push(simple ? newVNode(null, child) : child);
  191. }
  192. lastSimple = simple;
  193. }
  194. }
  195. };
  196. walk(children);
  197. if (vnodeData) {
  198. if (BUILD.isDev && nodeName === 'input') {
  199. validateInputProperties(vnodeData);
  200. }
  201. // normalize class / classname attributes
  202. if (BUILD.vdomKey && vnodeData.key) {
  203. key = vnodeData.key;
  204. }
  205. if (BUILD.slotRelocation && vnodeData.name) {
  206. slotName = vnodeData.name;
  207. }
  208. if (BUILD.vdomClass) {
  209. const classData = vnodeData.className || vnodeData.class;
  210. if (classData) {
  211. vnodeData.class =
  212. typeof classData !== 'object'
  213. ? classData
  214. : Object.keys(classData)
  215. .filter((k) => classData[k])
  216. .join(' ');
  217. }
  218. }
  219. }
  220. if (BUILD.isDev && vNodeChildren.some(isHost)) {
  221. consoleDevError(`The <Host> must be the single root component. Make sure:
  222. - You are NOT using hostData() and <Host> in the same component.
  223. - <Host> is used once, and it's the single root component of the render() function.`);
  224. }
  225. if (BUILD.vdomFunctional && typeof nodeName === 'function') {
  226. // nodeName is a functional component
  227. return nodeName(vnodeData === null ? {} : vnodeData, vNodeChildren, vdomFnUtils);
  228. }
  229. const vnode = newVNode(nodeName, null);
  230. vnode.$attrs$ = vnodeData;
  231. if (vNodeChildren.length > 0) {
  232. vnode.$children$ = vNodeChildren;
  233. }
  234. if (BUILD.vdomKey) {
  235. vnode.$key$ = key;
  236. }
  237. if (BUILD.slotRelocation) {
  238. vnode.$name$ = slotName;
  239. }
  240. return vnode;
  241. };
  242. const newVNode = (tag, text) => {
  243. const vnode = {
  244. $flags$: 0,
  245. $tag$: tag,
  246. $text$: text,
  247. $elm$: null,
  248. $children$: null,
  249. };
  250. if (BUILD.vdomAttribute) {
  251. vnode.$attrs$ = null;
  252. }
  253. if (BUILD.vdomKey) {
  254. vnode.$key$ = null;
  255. }
  256. if (BUILD.slotRelocation) {
  257. vnode.$name$ = null;
  258. }
  259. return vnode;
  260. };
  261. const Host = {};
  262. const isHost = (node) => node && node.$tag$ === Host;
  263. const vdomFnUtils = {
  264. forEach: (children, cb) => children.map(convertToPublic).forEach(cb),
  265. map: (children, cb) => children.map(convertToPublic).map(cb).map(convertToPrivate),
  266. };
  267. const convertToPublic = (node) => ({
  268. vattrs: node.$attrs$,
  269. vchildren: node.$children$,
  270. vkey: node.$key$,
  271. vname: node.$name$,
  272. vtag: node.$tag$,
  273. vtext: node.$text$,
  274. });
  275. const convertToPrivate = (node) => {
  276. if (typeof node.vtag === 'function') {
  277. const vnodeData = Object.assign({}, node.vattrs);
  278. if (node.vkey) {
  279. vnodeData.key = node.vkey;
  280. }
  281. if (node.vname) {
  282. vnodeData.name = node.vname;
  283. }
  284. return h(node.vtag, vnodeData, ...(node.vchildren || []));
  285. }
  286. const vnode = newVNode(node.vtag, node.vtext);
  287. vnode.$attrs$ = node.vattrs;
  288. vnode.$children$ = node.vchildren;
  289. vnode.$key$ = node.vkey;
  290. vnode.$name$ = node.vname;
  291. return vnode;
  292. };
  293. /**
  294. * Validates the ordering of attributes on an input element
  295. * @param inputElm the element to validate
  296. */
  297. const validateInputProperties = (inputElm) => {
  298. const props = Object.keys(inputElm);
  299. const value = props.indexOf('value');
  300. if (value === -1) {
  301. return;
  302. }
  303. const typeIndex = props.indexOf('type');
  304. const minIndex = props.indexOf('min');
  305. const maxIndex = props.indexOf('max');
  306. const stepIndex = props.indexOf('step');
  307. if (value < typeIndex || value < minIndex || value < maxIndex || value < stepIndex) {
  308. consoleDevWarn(`The "value" prop of <input> should be set after "min", "max", "type" and "step"`);
  309. }
  310. };
  311. const initializeClientHydrate = (hostElm, tagName, hostId, hostRef) => {
  312. const endHydrate = createTime('hydrateClient', tagName);
  313. const shadowRoot = hostElm.shadowRoot;
  314. const childRenderNodes = [];
  315. const slotNodes = [];
  316. const shadowRootNodes = BUILD.shadowDom && shadowRoot ? [] : null;
  317. const vnode = (hostRef.$vnode$ = newVNode(tagName, null));
  318. if (!plt.$orgLocNodes$) {
  319. initializeDocumentHydrate(doc.body, (plt.$orgLocNodes$ = new Map()));
  320. }
  321. hostElm[HYDRATE_ID] = hostId;
  322. hostElm.removeAttribute(HYDRATE_ID);
  323. clientHydrate(vnode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, hostElm, hostId);
  324. childRenderNodes.map((c) => {
  325. const orgLocationId = c.$hostId$ + '.' + c.$nodeId$;
  326. const orgLocationNode = plt.$orgLocNodes$.get(orgLocationId);
  327. const node = c.$elm$;
  328. if (orgLocationNode && supportsShadow && orgLocationNode['s-en'] === '') {
  329. orgLocationNode.parentNode.insertBefore(node, orgLocationNode.nextSibling);
  330. }
  331. if (!shadowRoot) {
  332. node['s-hn'] = tagName;
  333. if (orgLocationNode) {
  334. node['s-ol'] = orgLocationNode;
  335. node['s-ol']['s-nr'] = node;
  336. }
  337. }
  338. plt.$orgLocNodes$.delete(orgLocationId);
  339. });
  340. if (BUILD.shadowDom && shadowRoot) {
  341. shadowRootNodes.map((shadowRootNode) => {
  342. if (shadowRootNode) {
  343. shadowRoot.appendChild(shadowRootNode);
  344. }
  345. });
  346. }
  347. endHydrate();
  348. };
  349. const clientHydrate = (parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, node, hostId) => {
  350. let childNodeType;
  351. let childIdSplt;
  352. let childVNode;
  353. let i;
  354. if (node.nodeType === 1 /* NODE_TYPE.ElementNode */) {
  355. childNodeType = node.getAttribute(HYDRATE_CHILD_ID);
  356. if (childNodeType) {
  357. // got the node data from the element's attribute
  358. // `${hostId}.${nodeId}.${depth}.${index}`
  359. childIdSplt = childNodeType.split('.');
  360. if (childIdSplt[0] === hostId || childIdSplt[0] === '0') {
  361. childVNode = {
  362. $flags$: 0,
  363. $hostId$: childIdSplt[0],
  364. $nodeId$: childIdSplt[1],
  365. $depth$: childIdSplt[2],
  366. $index$: childIdSplt[3],
  367. $tag$: node.tagName.toLowerCase(),
  368. $elm$: node,
  369. $attrs$: null,
  370. $children$: null,
  371. $key$: null,
  372. $name$: null,
  373. $text$: null,
  374. };
  375. childRenderNodes.push(childVNode);
  376. node.removeAttribute(HYDRATE_CHILD_ID);
  377. // this is a new child vnode
  378. // so ensure its parent vnode has the vchildren array
  379. if (!parentVNode.$children$) {
  380. parentVNode.$children$ = [];
  381. }
  382. // add our child vnode to a specific index of the vnode's children
  383. parentVNode.$children$[childVNode.$index$] = childVNode;
  384. // this is now the new parent vnode for all the next child checks
  385. parentVNode = childVNode;
  386. if (shadowRootNodes && childVNode.$depth$ === '0') {
  387. shadowRootNodes[childVNode.$index$] = childVNode.$elm$;
  388. }
  389. }
  390. }
  391. // recursively drill down, end to start so we can remove nodes
  392. for (i = node.childNodes.length - 1; i >= 0; i--) {
  393. clientHydrate(parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, node.childNodes[i], hostId);
  394. }
  395. if (node.shadowRoot) {
  396. // keep drilling down through the shadow root nodes
  397. for (i = node.shadowRoot.childNodes.length - 1; i >= 0; i--) {
  398. clientHydrate(parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, node.shadowRoot.childNodes[i], hostId);
  399. }
  400. }
  401. }
  402. else if (node.nodeType === 8 /* NODE_TYPE.CommentNode */) {
  403. // `${COMMENT_TYPE}.${hostId}.${nodeId}.${depth}.${index}`
  404. childIdSplt = node.nodeValue.split('.');
  405. if (childIdSplt[1] === hostId || childIdSplt[1] === '0') {
  406. // comment node for either the host id or a 0 host id
  407. childNodeType = childIdSplt[0];
  408. childVNode = {
  409. $flags$: 0,
  410. $hostId$: childIdSplt[1],
  411. $nodeId$: childIdSplt[2],
  412. $depth$: childIdSplt[3],
  413. $index$: childIdSplt[4],
  414. $elm$: node,
  415. $attrs$: null,
  416. $children$: null,
  417. $key$: null,
  418. $name$: null,
  419. $tag$: null,
  420. $text$: null,
  421. };
  422. if (childNodeType === TEXT_NODE_ID) {
  423. childVNode.$elm$ = node.nextSibling;
  424. if (childVNode.$elm$ && childVNode.$elm$.nodeType === 3 /* NODE_TYPE.TextNode */) {
  425. childVNode.$text$ = childVNode.$elm$.textContent;
  426. childRenderNodes.push(childVNode);
  427. // remove the text comment since it's no longer needed
  428. node.remove();
  429. if (!parentVNode.$children$) {
  430. parentVNode.$children$ = [];
  431. }
  432. parentVNode.$children$[childVNode.$index$] = childVNode;
  433. if (shadowRootNodes && childVNode.$depth$ === '0') {
  434. shadowRootNodes[childVNode.$index$] = childVNode.$elm$;
  435. }
  436. }
  437. }
  438. else if (childVNode.$hostId$ === hostId) {
  439. // this comment node is specifcally for this host id
  440. if (childNodeType === SLOT_NODE_ID) {
  441. // `${SLOT_NODE_ID}.${hostId}.${nodeId}.${depth}.${index}.${slotName}`;
  442. childVNode.$tag$ = 'slot';
  443. if (childIdSplt[5]) {
  444. node['s-sn'] = childVNode.$name$ = childIdSplt[5];
  445. }
  446. else {
  447. node['s-sn'] = '';
  448. }
  449. node['s-sr'] = true;
  450. if (BUILD.shadowDom && shadowRootNodes) {
  451. // browser support shadowRoot and this is a shadow dom component
  452. // create an actual slot element
  453. childVNode.$elm$ = doc.createElement(childVNode.$tag$);
  454. if (childVNode.$name$) {
  455. // add the slot name attribute
  456. childVNode.$elm$.setAttribute('name', childVNode.$name$);
  457. }
  458. // insert the new slot element before the slot comment
  459. node.parentNode.insertBefore(childVNode.$elm$, node);
  460. // remove the slot comment since it's not needed for shadow
  461. node.remove();
  462. if (childVNode.$depth$ === '0') {
  463. shadowRootNodes[childVNode.$index$] = childVNode.$elm$;
  464. }
  465. }
  466. slotNodes.push(childVNode);
  467. if (!parentVNode.$children$) {
  468. parentVNode.$children$ = [];
  469. }
  470. parentVNode.$children$[childVNode.$index$] = childVNode;
  471. }
  472. else if (childNodeType === CONTENT_REF_ID) {
  473. // `${CONTENT_REF_ID}.${hostId}`;
  474. if (BUILD.shadowDom && shadowRootNodes) {
  475. // remove the content ref comment since it's not needed for shadow
  476. node.remove();
  477. }
  478. else if (BUILD.slotRelocation) {
  479. hostElm['s-cr'] = node;
  480. node['s-cn'] = true;
  481. }
  482. }
  483. }
  484. }
  485. }
  486. else if (parentVNode && parentVNode.$tag$ === 'style') {
  487. const vnode = newVNode(null, node.textContent);
  488. vnode.$elm$ = node;
  489. vnode.$index$ = '0';
  490. parentVNode.$children$ = [vnode];
  491. }
  492. };
  493. const initializeDocumentHydrate = (node, orgLocNodes) => {
  494. if (node.nodeType === 1 /* NODE_TYPE.ElementNode */) {
  495. let i = 0;
  496. for (; i < node.childNodes.length; i++) {
  497. initializeDocumentHydrate(node.childNodes[i], orgLocNodes);
  498. }
  499. if (node.shadowRoot) {
  500. for (i = 0; i < node.shadowRoot.childNodes.length; i++) {
  501. initializeDocumentHydrate(node.shadowRoot.childNodes[i], orgLocNodes);
  502. }
  503. }
  504. }
  505. else if (node.nodeType === 8 /* NODE_TYPE.CommentNode */) {
  506. const childIdSplt = node.nodeValue.split('.');
  507. if (childIdSplt[0] === ORG_LOCATION_ID) {
  508. orgLocNodes.set(childIdSplt[1] + '.' + childIdSplt[2], node);
  509. node.nodeValue = '';
  510. // useful to know if the original location is
  511. // the root light-dom of a shadow dom component
  512. node['s-en'] = childIdSplt[3];
  513. }
  514. }
  515. };
  516. // Private
  517. const computeMode = (elm) => modeResolutionChain.map((h) => h(elm)).find((m) => !!m);
  518. // Public
  519. const setMode = (handler) => modeResolutionChain.push(handler);
  520. const getMode = (ref) => getHostRef(ref).$modeName$;
  521. /**
  522. * Parse a new property value for a given property type.
  523. *
  524. * While the prop value can reasonably be expected to be of `any` type as far as TypeScript's type checker is concerned,
  525. * it is not safe to assume that the string returned by evaluating `typeof propValue` matches:
  526. * 1. `any`, the type given to `propValue` in the function signature
  527. * 2. the type stored from `propType`.
  528. *
  529. * This function provides the capability to parse/coerce a property's value to potentially any other JavaScript type.
  530. *
  531. * Property values represented in TSX preserve their type information. In the example below, the number 0 is passed to
  532. * a component. This `propValue` will preserve its type information (`typeof propValue === 'number'`). Note that is
  533. * based on the type of the value being passed in, not the type declared of the class member decorated with `@Prop`.
  534. * ```tsx
  535. * <my-cmp prop-val={0}></my-cmp>
  536. * ```
  537. *
  538. * HTML prop values on the other hand, will always a string
  539. *
  540. * @param propValue the new value to coerce to some type
  541. * @param propType the type of the prop, expressed as a binary number
  542. * @returns the parsed/coerced value
  543. */
  544. const parsePropertyValue = (propValue, propType) => {
  545. // ensure this value is of the correct prop type
  546. if (propValue != null && !isComplexType(propValue)) {
  547. if (BUILD.propBoolean && propType & 4 /* MEMBER_FLAGS.Boolean */) {
  548. // per the HTML spec, any string value means it is a boolean true value
  549. // but we'll cheat here and say that the string "false" is the boolean false
  550. return propValue === 'false' ? false : propValue === '' || !!propValue;
  551. }
  552. if (BUILD.propNumber && propType & 2 /* MEMBER_FLAGS.Number */) {
  553. // force it to be a number
  554. return parseFloat(propValue);
  555. }
  556. if (BUILD.propString && propType & 1 /* MEMBER_FLAGS.String */) {
  557. // could have been passed as a number or boolean
  558. // but we still want it as a string
  559. return String(propValue);
  560. }
  561. // redundant return here for better minification
  562. return propValue;
  563. }
  564. // not sure exactly what type we want
  565. // so no need to change to a different type
  566. return propValue;
  567. };
  568. const getElement = (ref) => (BUILD.lazyLoad ? getHostRef(ref).$hostElement$ : ref);
  569. const createEvent = (ref, name, flags) => {
  570. const elm = getElement(ref);
  571. return {
  572. emit: (detail) => {
  573. if (BUILD.isDev && !elm.isConnected) {
  574. consoleDevWarn(`The "${name}" event was emitted, but the dispatcher node is no longer connected to the dom.`);
  575. }
  576. return emitEvent(elm, name, {
  577. bubbles: !!(flags & 4 /* EVENT_FLAGS.Bubbles */),
  578. composed: !!(flags & 2 /* EVENT_FLAGS.Composed */),
  579. cancelable: !!(flags & 1 /* EVENT_FLAGS.Cancellable */),
  580. detail,
  581. });
  582. },
  583. };
  584. };
  585. /**
  586. * Helper function to create & dispatch a custom Event on a provided target
  587. * @param elm the target of the Event
  588. * @param name the name to give the custom Event
  589. * @param opts options for configuring a custom Event
  590. * @returns the custom Event
  591. */
  592. const emitEvent = (elm, name, opts) => {
  593. const ev = plt.ce(name, opts);
  594. elm.dispatchEvent(ev);
  595. return ev;
  596. };
  597. const rootAppliedStyles = /*@__PURE__*/ new WeakMap();
  598. const registerStyle = (scopeId, cssText, allowCS) => {
  599. let style = styles.get(scopeId);
  600. if (supportsConstructableStylesheets && allowCS) {
  601. style = (style || new CSSStyleSheet());
  602. if (typeof style === 'string') {
  603. style = cssText;
  604. }
  605. else {
  606. style.replaceSync(cssText);
  607. }
  608. }
  609. else {
  610. style = cssText;
  611. }
  612. styles.set(scopeId, style);
  613. };
  614. const addStyle = (styleContainerNode, cmpMeta, mode, hostElm) => {
  615. let scopeId = getScopeId(cmpMeta, mode);
  616. const style = styles.get(scopeId);
  617. if (!BUILD.attachStyles) {
  618. return scopeId;
  619. }
  620. // if an element is NOT connected then getRootNode() will return the wrong root node
  621. // so the fallback is to always use the document for the root node in those cases
  622. styleContainerNode = styleContainerNode.nodeType === 11 /* NODE_TYPE.DocumentFragment */ ? styleContainerNode : doc;
  623. if (style) {
  624. if (typeof style === 'string') {
  625. styleContainerNode = styleContainerNode.head || styleContainerNode;
  626. let appliedStyles = rootAppliedStyles.get(styleContainerNode);
  627. let styleElm;
  628. if (!appliedStyles) {
  629. rootAppliedStyles.set(styleContainerNode, (appliedStyles = new Set()));
  630. }
  631. if (!appliedStyles.has(scopeId)) {
  632. if (BUILD.hydrateClientSide &&
  633. styleContainerNode.host &&
  634. (styleElm = styleContainerNode.querySelector(`[${HYDRATED_STYLE_ID}="${scopeId}"]`))) {
  635. // This is only happening on native shadow-dom, do not needs CSS var shim
  636. styleElm.innerHTML = style;
  637. }
  638. else {
  639. if (BUILD.cssVarShim && plt.$cssShim$) {
  640. styleElm = plt.$cssShim$.createHostStyle(hostElm, scopeId, style, !!(cmpMeta.$flags$ & 10 /* CMP_FLAGS.needsScopedEncapsulation */));
  641. const newScopeId = styleElm['s-sc'];
  642. if (newScopeId) {
  643. scopeId = newScopeId;
  644. // we don't want to add this styleID to the appliedStyles Set
  645. // since the cssVarShim might need to apply several different
  646. // stylesheets for the same component
  647. appliedStyles = null;
  648. }
  649. }
  650. else {
  651. styleElm = doc.createElement('style');
  652. styleElm.innerHTML = style;
  653. }
  654. if (BUILD.hydrateServerSide || BUILD.hotModuleReplacement) {
  655. styleElm.setAttribute(HYDRATED_STYLE_ID, scopeId);
  656. }
  657. styleContainerNode.insertBefore(styleElm, styleContainerNode.querySelector('link'));
  658. }
  659. if (appliedStyles) {
  660. appliedStyles.add(scopeId);
  661. }
  662. }
  663. }
  664. else if (BUILD.constructableCSS && !styleContainerNode.adoptedStyleSheets.includes(style)) {
  665. styleContainerNode.adoptedStyleSheets = [...styleContainerNode.adoptedStyleSheets, style];
  666. }
  667. }
  668. return scopeId;
  669. };
  670. const attachStyles = (hostRef) => {
  671. const cmpMeta = hostRef.$cmpMeta$;
  672. const elm = hostRef.$hostElement$;
  673. const flags = cmpMeta.$flags$;
  674. const endAttachStyles = createTime('attachStyles', cmpMeta.$tagName$);
  675. const scopeId = addStyle(BUILD.shadowDom && supportsShadow && elm.shadowRoot ? elm.shadowRoot : elm.getRootNode(), cmpMeta, hostRef.$modeName$, elm);
  676. if ((BUILD.shadowDom || BUILD.scoped) && BUILD.cssAnnotations && flags & 10 /* CMP_FLAGS.needsScopedEncapsulation */) {
  677. // only required when we're NOT using native shadow dom (slot)
  678. // or this browser doesn't support native shadow dom
  679. // and this host element was NOT created with SSR
  680. // let's pick out the inner content for slot projection
  681. // create a node to represent where the original
  682. // content was first placed, which is useful later on
  683. // DOM WRITE!!
  684. elm['s-sc'] = scopeId;
  685. elm.classList.add(scopeId + '-h');
  686. if (BUILD.scoped && flags & 2 /* CMP_FLAGS.scopedCssEncapsulation */) {
  687. elm.classList.add(scopeId + '-s');
  688. }
  689. }
  690. endAttachStyles();
  691. };
  692. const getScopeId = (cmp, mode) => 'sc-' + (BUILD.mode && mode && cmp.$flags$ & 32 /* CMP_FLAGS.hasMode */ ? cmp.$tagName$ + '-' + mode : cmp.$tagName$);
  693. const convertScopedToShadow = (css) => css.replace(/\/\*!@([^\/]+)\*\/[^\{]+\{/g, '$1{');
  694. /**
  695. * Production setAccessor() function based on Preact by
  696. * Jason Miller (@developit)
  697. * Licensed under the MIT License
  698. * https://github.com/developit/preact/blob/master/LICENSE
  699. *
  700. * Modified for Stencil's compiler and vdom
  701. */
  702. const setAccessor = (elm, memberName, oldValue, newValue, isSvg, flags) => {
  703. if (oldValue !== newValue) {
  704. let isProp = isMemberInElement(elm, memberName);
  705. let ln = memberName.toLowerCase();
  706. if (BUILD.vdomClass && memberName === 'class') {
  707. const classList = elm.classList;
  708. const oldClasses = parseClassList(oldValue);
  709. const newClasses = parseClassList(newValue);
  710. classList.remove(...oldClasses.filter((c) => c && !newClasses.includes(c)));
  711. classList.add(...newClasses.filter((c) => c && !oldClasses.includes(c)));
  712. }
  713. else if (BUILD.vdomStyle && memberName === 'style') {
  714. // update style attribute, css properties and values
  715. if (BUILD.updatable) {
  716. for (const prop in oldValue) {
  717. if (!newValue || newValue[prop] == null) {
  718. if (!BUILD.hydrateServerSide && prop.includes('-')) {
  719. elm.style.removeProperty(prop);
  720. }
  721. else {
  722. elm.style[prop] = '';
  723. }
  724. }
  725. }
  726. }
  727. for (const prop in newValue) {
  728. if (!oldValue || newValue[prop] !== oldValue[prop]) {
  729. if (!BUILD.hydrateServerSide && prop.includes('-')) {
  730. elm.style.setProperty(prop, newValue[prop]);
  731. }
  732. else {
  733. elm.style[prop] = newValue[prop];
  734. }
  735. }
  736. }
  737. }
  738. else if (BUILD.vdomKey && memberName === 'key')
  739. ;
  740. else if (BUILD.vdomRef && memberName === 'ref') {
  741. // minifier will clean this up
  742. if (newValue) {
  743. newValue(elm);
  744. }
  745. }
  746. else if (BUILD.vdomListener &&
  747. (BUILD.lazyLoad ? !isProp : !elm.__lookupSetter__(memberName)) &&
  748. memberName[0] === 'o' &&
  749. memberName[1] === 'n') {
  750. // Event Handlers
  751. // so if the member name starts with "on" and the 3rd characters is
  752. // a capital letter, and it's not already a member on the element,
  753. // then we're assuming it's an event listener
  754. if (memberName[2] === '-') {
  755. // on- prefixed events
  756. // allows to be explicit about the dom event to listen without any magic
  757. // under the hood:
  758. // <my-cmp on-click> // listens for "click"
  759. // <my-cmp on-Click> // listens for "Click"
  760. // <my-cmp on-ionChange> // listens for "ionChange"
  761. // <my-cmp on-EVENTS> // listens for "EVENTS"
  762. memberName = memberName.slice(3);
  763. }
  764. else if (isMemberInElement(win, ln)) {
  765. // standard event
  766. // the JSX attribute could have been "onMouseOver" and the
  767. // member name "onmouseover" is on the window's prototype
  768. // so let's add the listener "mouseover", which is all lowercased
  769. memberName = ln.slice(2);
  770. }
  771. else {
  772. // custom event
  773. // the JSX attribute could have been "onMyCustomEvent"
  774. // so let's trim off the "on" prefix and lowercase the first character
  775. // and add the listener "myCustomEvent"
  776. // except for the first character, we keep the event name case
  777. memberName = ln[2] + memberName.slice(3);
  778. }
  779. if (oldValue) {
  780. plt.rel(elm, memberName, oldValue, false);
  781. }
  782. if (newValue) {
  783. plt.ael(elm, memberName, newValue, false);
  784. }
  785. }
  786. else if (BUILD.vdomPropOrAttr) {
  787. // Set property if it exists and it's not a SVG
  788. const isComplex = isComplexType(newValue);
  789. if ((isProp || (isComplex && newValue !== null)) && !isSvg) {
  790. try {
  791. if (!elm.tagName.includes('-')) {
  792. const n = newValue == null ? '' : newValue;
  793. // Workaround for Safari, moving the <input> caret when re-assigning the same valued
  794. if (memberName === 'list') {
  795. isProp = false;
  796. }
  797. else if (oldValue == null || elm[memberName] != n) {
  798. elm[memberName] = n;
  799. }
  800. }
  801. else {
  802. elm[memberName] = newValue;
  803. }
  804. }
  805. catch (e) { }
  806. }
  807. /**
  808. * Need to manually update attribute if:
  809. * - memberName is not an attribute
  810. * - if we are rendering the host element in order to reflect attribute
  811. * - if it's a SVG, since properties might not work in <svg>
  812. * - if the newValue is null/undefined or 'false'.
  813. */
  814. let xlink = false;
  815. if (BUILD.vdomXlink) {
  816. if (ln !== (ln = ln.replace(/^xlink\:?/, ''))) {
  817. memberName = ln;
  818. xlink = true;
  819. }
  820. }
  821. if (newValue == null || newValue === false) {
  822. if (newValue !== false || elm.getAttribute(memberName) === '') {
  823. if (BUILD.vdomXlink && xlink) {
  824. elm.removeAttributeNS(XLINK_NS, memberName);
  825. }
  826. else {
  827. elm.removeAttribute(memberName);
  828. }
  829. }
  830. }
  831. else if ((!isProp || flags & 4 /* VNODE_FLAGS.isHost */ || isSvg) && !isComplex) {
  832. newValue = newValue === true ? '' : newValue;
  833. if (BUILD.vdomXlink && xlink) {
  834. elm.setAttributeNS(XLINK_NS, memberName, newValue);
  835. }
  836. else {
  837. elm.setAttribute(memberName, newValue);
  838. }
  839. }
  840. }
  841. }
  842. };
  843. const parseClassListRegex = /\s/;
  844. const parseClassList = (value) => (!value ? [] : value.split(parseClassListRegex));
  845. const updateElement = (oldVnode, newVnode, isSvgMode, memberName) => {
  846. // if the element passed in is a shadow root, which is a document fragment
  847. // then we want to be adding attrs/props to the shadow root's "host" element
  848. // if it's not a shadow root, then we add attrs/props to the same element
  849. const elm = newVnode.$elm$.nodeType === 11 /* NODE_TYPE.DocumentFragment */ && newVnode.$elm$.host
  850. ? newVnode.$elm$.host
  851. : newVnode.$elm$;
  852. const oldVnodeAttrs = (oldVnode && oldVnode.$attrs$) || EMPTY_OBJ;
  853. const newVnodeAttrs = newVnode.$attrs$ || EMPTY_OBJ;
  854. if (BUILD.updatable) {
  855. // remove attributes no longer present on the vnode by setting them to undefined
  856. for (memberName in oldVnodeAttrs) {
  857. if (!(memberName in newVnodeAttrs)) {
  858. setAccessor(elm, memberName, oldVnodeAttrs[memberName], undefined, isSvgMode, newVnode.$flags$);
  859. }
  860. }
  861. }
  862. // add new & update changed attributes
  863. for (memberName in newVnodeAttrs) {
  864. setAccessor(elm, memberName, oldVnodeAttrs[memberName], newVnodeAttrs[memberName], isSvgMode, newVnode.$flags$);
  865. }
  866. };
  867. /**
  868. * Create a DOM Node corresponding to one of the children of a given VNode.
  869. *
  870. * @param oldParentVNode the parent VNode from the previous render
  871. * @param newParentVNode the parent VNode from the current render
  872. * @param childIndex the index of the VNode, in the _new_ parent node's
  873. * children, for which we will create a new DOM node
  874. * @param parentElm the parent DOM node which our new node will be a child of
  875. * @returns the newly created node
  876. */
  877. const createElm = (oldParentVNode, newParentVNode, childIndex, parentElm) => {
  878. // tslint:disable-next-line: prefer-const
  879. const newVNode = newParentVNode.$children$[childIndex];
  880. let i = 0;
  881. let elm;
  882. let childNode;
  883. let oldVNode;
  884. if (BUILD.slotRelocation && !useNativeShadowDom) {
  885. // remember for later we need to check to relocate nodes
  886. checkSlotRelocate = true;
  887. if (newVNode.$tag$ === 'slot') {
  888. if (scopeId) {
  889. // scoped css needs to add its scoped id to the parent element
  890. parentElm.classList.add(scopeId + '-s');
  891. }
  892. newVNode.$flags$ |= newVNode.$children$
  893. ? // slot element has fallback content
  894. 2 /* VNODE_FLAGS.isSlotFallback */
  895. : // slot element does not have fallback content
  896. 1 /* VNODE_FLAGS.isSlotReference */;
  897. }
  898. }
  899. if (BUILD.isDev && newVNode.$elm$) {
  900. consoleDevError(`The JSX ${newVNode.$text$ !== null ? `"${newVNode.$text$}" text` : `"${newVNode.$tag$}" element`} node should not be shared within the same renderer. The renderer caches element lookups in order to improve performance. However, a side effect from this is that the exact same JSX node should not be reused. For more information please see https://stenciljs.com/docs/templating-jsx#avoid-shared-jsx-nodes`);
  901. }
  902. if (BUILD.vdomText && newVNode.$text$ !== null) {
  903. // create text node
  904. elm = newVNode.$elm$ = doc.createTextNode(newVNode.$text$);
  905. }
  906. else if (BUILD.slotRelocation && newVNode.$flags$ & 1 /* VNODE_FLAGS.isSlotReference */) {
  907. // create a slot reference node
  908. elm = newVNode.$elm$ =
  909. BUILD.isDebug || BUILD.hydrateServerSide ? slotReferenceDebugNode(newVNode) : doc.createTextNode('');
  910. }
  911. else {
  912. if (BUILD.svg && !isSvgMode) {
  913. isSvgMode = newVNode.$tag$ === 'svg';
  914. }
  915. // create element
  916. elm = newVNode.$elm$ = (BUILD.svg
  917. ? doc.createElementNS(isSvgMode ? SVG_NS : HTML_NS, BUILD.slotRelocation && newVNode.$flags$ & 2 /* VNODE_FLAGS.isSlotFallback */
  918. ? 'slot-fb'
  919. : newVNode.$tag$)
  920. : doc.createElement(BUILD.slotRelocation && newVNode.$flags$ & 2 /* VNODE_FLAGS.isSlotFallback */
  921. ? 'slot-fb'
  922. : newVNode.$tag$));
  923. if (BUILD.svg && isSvgMode && newVNode.$tag$ === 'foreignObject') {
  924. isSvgMode = false;
  925. }
  926. // add css classes, attrs, props, listeners, etc.
  927. if (BUILD.vdomAttribute) {
  928. updateElement(null, newVNode, isSvgMode);
  929. }
  930. if ((BUILD.shadowDom || BUILD.scoped) && isDef(scopeId) && elm['s-si'] !== scopeId) {
  931. // if there is a scopeId and this is the initial render
  932. // then let's add the scopeId as a css class
  933. elm.classList.add((elm['s-si'] = scopeId));
  934. }
  935. if (newVNode.$children$) {
  936. for (i = 0; i < newVNode.$children$.length; ++i) {
  937. // create the node
  938. childNode = createElm(oldParentVNode, newVNode, i, elm);
  939. // return node could have been null
  940. if (childNode) {
  941. // append our new node
  942. elm.appendChild(childNode);
  943. }
  944. }
  945. }
  946. if (BUILD.svg) {
  947. if (newVNode.$tag$ === 'svg') {
  948. // Only reset the SVG context when we're exiting <svg> element
  949. isSvgMode = false;
  950. }
  951. else if (elm.tagName === 'foreignObject') {
  952. // Reenter SVG context when we're exiting <foreignObject> element
  953. isSvgMode = true;
  954. }
  955. }
  956. }
  957. if (BUILD.slotRelocation) {
  958. elm['s-hn'] = hostTagName;
  959. if (newVNode.$flags$ & (2 /* VNODE_FLAGS.isSlotFallback */ | 1 /* VNODE_FLAGS.isSlotReference */)) {
  960. // remember the content reference comment
  961. elm['s-sr'] = true;
  962. // remember the content reference comment
  963. elm['s-cr'] = contentRef;
  964. // remember the slot name, or empty string for default slot
  965. elm['s-sn'] = newVNode.$name$ || '';
  966. // check if we've got an old vnode for this slot
  967. oldVNode = oldParentVNode && oldParentVNode.$children$ && oldParentVNode.$children$[childIndex];
  968. if (oldVNode && oldVNode.$tag$ === newVNode.$tag$ && oldParentVNode.$elm$) {
  969. // we've got an old slot vnode and the wrapper is being replaced
  970. // so let's move the old slot content back to it's original location
  971. putBackInOriginalLocation(oldParentVNode.$elm$, false);
  972. }
  973. }
  974. }
  975. return elm;
  976. };
  977. const putBackInOriginalLocation = (parentElm, recursive) => {
  978. plt.$flags$ |= 1 /* PLATFORM_FLAGS.isTmpDisconnected */;
  979. const oldSlotChildNodes = parentElm.childNodes;
  980. for (let i = oldSlotChildNodes.length - 1; i >= 0; i--) {
  981. const childNode = oldSlotChildNodes[i];
  982. if (childNode['s-hn'] !== hostTagName && childNode['s-ol']) {
  983. // // this child node in the old element is from another component
  984. // // remove this node from the old slot's parent
  985. // childNode.remove();
  986. // and relocate it back to it's original location
  987. parentReferenceNode(childNode).insertBefore(childNode, referenceNode(childNode));
  988. // remove the old original location comment entirely
  989. // later on the patch function will know what to do
  990. // and move this to the correct spot in need be
  991. childNode['s-ol'].remove();
  992. childNode['s-ol'] = undefined;
  993. checkSlotRelocate = true;
  994. }
  995. if (recursive) {
  996. putBackInOriginalLocation(childNode, recursive);
  997. }
  998. }
  999. plt.$flags$ &= ~1 /* PLATFORM_FLAGS.isTmpDisconnected */;
  1000. };
  1001. const addVnodes = (parentElm, before, parentVNode, vnodes, startIdx, endIdx) => {
  1002. let containerElm = ((BUILD.slotRelocation && parentElm['s-cr'] && parentElm['s-cr'].parentNode) || parentElm);
  1003. let childNode;
  1004. if (BUILD.shadowDom && containerElm.shadowRoot && containerElm.tagName === hostTagName) {
  1005. containerElm = containerElm.shadowRoot;
  1006. }
  1007. for (; startIdx <= endIdx; ++startIdx) {
  1008. if (vnodes[startIdx]) {
  1009. childNode = createElm(null, parentVNode, startIdx, parentElm);
  1010. if (childNode) {
  1011. vnodes[startIdx].$elm$ = childNode;
  1012. containerElm.insertBefore(childNode, BUILD.slotRelocation ? referenceNode(before) : before);
  1013. }
  1014. }
  1015. }
  1016. };
  1017. const removeVnodes = (vnodes, startIdx, endIdx, vnode, elm) => {
  1018. for (; startIdx <= endIdx; ++startIdx) {
  1019. if ((vnode = vnodes[startIdx])) {
  1020. elm = vnode.$elm$;
  1021. callNodeRefs(vnode);
  1022. if (BUILD.slotRelocation) {
  1023. // we're removing this element
  1024. // so it's possible we need to show slot fallback content now
  1025. checkSlotFallbackVisibility = true;
  1026. if (elm['s-ol']) {
  1027. // remove the original location comment
  1028. elm['s-ol'].remove();
  1029. }
  1030. else {
  1031. // it's possible that child nodes of the node
  1032. // that's being removed are slot nodes
  1033. putBackInOriginalLocation(elm, true);
  1034. }
  1035. }
  1036. // remove the vnode's element from the dom
  1037. elm.remove();
  1038. }
  1039. }
  1040. };
  1041. /**
  1042. * Reconcile the children of a new VNode with the children of an old VNode by
  1043. * traversing the two collections of children, identifying nodes that are
  1044. * conserved or changed, calling out to `patch` to make any necessary
  1045. * updates to the DOM, and rearranging DOM nodes as needed.
  1046. *
  1047. * The algorithm for reconciling children works by analyzing two 'windows' onto
  1048. * the two arrays of children (`oldCh` and `newCh`). We keep track of the
  1049. * 'windows' by storing start and end indices and references to the
  1050. * corresponding array entries. Initially the two 'windows' are basically equal
  1051. * to the entire array, but we progressively narrow the windows until there are
  1052. * no children left to update by doing the following:
  1053. *
  1054. * 1. Skip any `null` entries at the beginning or end of the two arrays, so
  1055. * that if we have an initial array like the following we'll end up dealing
  1056. * only with a window bounded by the highlighted elements:
  1057. *
  1058. * [null, null, VNode1 , ... , VNode2, null, null]
  1059. * ^^^^^^ ^^^^^^
  1060. *
  1061. * 2. Check to see if the elements at the head and tail positions are equal
  1062. * across the windows. This will basically detect elements which haven't
  1063. * been added, removed, or changed position, i.e. if you had the following
  1064. * VNode elements (represented as HTML):
  1065. *
  1066. * oldVNode: `<div><p><span>HEY</span></p></div>`
  1067. * newVNode: `<div><p><span>THERE</span></p></div>`
  1068. *
  1069. * Then when comparing the children of the `<div>` tag we check the equality
  1070. * of the VNodes corresponding to the `<p>` tags and, since they are the
  1071. * same tag in the same position, we'd be able to avoid completely
  1072. * re-rendering the subtree under them with a new DOM element and would just
  1073. * call out to `patch` to handle reconciling their children and so on.
  1074. *
  1075. * 3. Check, for both windows, to see if the element at the beginning of the
  1076. * window corresponds to the element at the end of the other window. This is
  1077. * a heuristic which will let us identify _some_ situations in which
  1078. * elements have changed position, for instance it _should_ detect that the
  1079. * children nodes themselves have not changed but merely moved in the
  1080. * following example:
  1081. *
  1082. * oldVNode: `<div><element-one /><element-two /></div>`
  1083. * newVNode: `<div><element-two /><element-one /></div>`
  1084. *
  1085. * If we find cases like this then we also need to move the concrete DOM
  1086. * elements corresponding to the moved children to write the re-order to the
  1087. * DOM.
  1088. *
  1089. * 4. Finally, if VNodes have the `key` attribute set on them we check for any
  1090. * nodes in the old children which have the same key as the first element in
  1091. * our window on the new children. If we find such a node we handle calling
  1092. * out to `patch`, moving relevant DOM nodes, and so on, in accordance with
  1093. * what we find.
  1094. *
  1095. * Finally, once we've narrowed our 'windows' to the point that either of them
  1096. * collapse (i.e. they have length 0) we then handle any remaining VNode
  1097. * insertion or deletion that needs to happen to get a DOM state that correctly
  1098. * reflects the new child VNodes. If, for instance, after our window on the old
  1099. * children has collapsed we still have more nodes on the new children that
  1100. * we haven't dealt with yet then we need to add them, or if the new children
  1101. * collapse but we still have unhandled _old_ children then we need to make
  1102. * sure the corresponding DOM nodes are removed.
  1103. *
  1104. * @param parentElm the node into which the parent VNode is rendered
  1105. * @param oldCh the old children of the parent node
  1106. * @param newVNode the new VNode which will replace the parent
  1107. * @param newCh the new children of the parent node
  1108. */
  1109. const updateChildren = (parentElm, oldCh, newVNode, newCh) => {
  1110. let oldStartIdx = 0;
  1111. let newStartIdx = 0;
  1112. let idxInOld = 0;
  1113. let i = 0;
  1114. let oldEndIdx = oldCh.length - 1;
  1115. let oldStartVnode = oldCh[0];
  1116. let oldEndVnode = oldCh[oldEndIdx];
  1117. let newEndIdx = newCh.length - 1;
  1118. let newStartVnode = newCh[0];
  1119. let newEndVnode = newCh[newEndIdx];
  1120. let node;
  1121. let elmToMove;
  1122. while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
  1123. if (oldStartVnode == null) {
  1124. // VNode might have been moved left
  1125. oldStartVnode = oldCh[++oldStartIdx];
  1126. }
  1127. else if (oldEndVnode == null) {
  1128. oldEndVnode = oldCh[--oldEndIdx];
  1129. }
  1130. else if (newStartVnode == null) {
  1131. newStartVnode = newCh[++newStartIdx];
  1132. }
  1133. else if (newEndVnode == null) {
  1134. newEndVnode = newCh[--newEndIdx];
  1135. }
  1136. else if (isSameVnode(oldStartVnode, newStartVnode)) {
  1137. // if the start nodes are the same then we should patch the new VNode
  1138. // onto the old one, and increment our `newStartIdx` and `oldStartIdx`
  1139. // indices to reflect that. We don't need to move any DOM Nodes around
  1140. // since things are matched up in order.
  1141. patch(oldStartVnode, newStartVnode);
  1142. oldStartVnode = oldCh[++oldStartIdx];
  1143. newStartVnode = newCh[++newStartIdx];
  1144. }
  1145. else if (isSameVnode(oldEndVnode, newEndVnode)) {
  1146. // likewise, if the end nodes are the same we patch new onto old and
  1147. // decrement our end indices, and also likewise in this case we don't
  1148. // need to move any DOM Nodes.
  1149. patch(oldEndVnode, newEndVnode);
  1150. oldEndVnode = oldCh[--oldEndIdx];
  1151. newEndVnode = newCh[--newEndIdx];
  1152. }
  1153. else if (isSameVnode(oldStartVnode, newEndVnode)) {
  1154. // case: "Vnode moved right"
  1155. //
  1156. // We've found that the last node in our window on the new children is
  1157. // the same VNode as the _first_ node in our window on the old children
  1158. // we're dealing with now. Visually, this is the layout of these two
  1159. // nodes:
  1160. //
  1161. // newCh: [..., newStartVnode , ... , newEndVnode , ...]
  1162. // ^^^^^^^^^^^
  1163. // oldCh: [..., oldStartVnode , ... , oldEndVnode , ...]
  1164. // ^^^^^^^^^^^^^
  1165. //
  1166. // In this situation we need to patch `newEndVnode` onto `oldStartVnode`
  1167. // and move the DOM element for `oldStartVnode`.
  1168. if (BUILD.slotRelocation && (oldStartVnode.$tag$ === 'slot' || newEndVnode.$tag$ === 'slot')) {
  1169. putBackInOriginalLocation(oldStartVnode.$elm$.parentNode, false);
  1170. }
  1171. patch(oldStartVnode, newEndVnode);
  1172. // We need to move the element for `oldStartVnode` into a position which
  1173. // will be appropriate for `newEndVnode`. For this we can use
  1174. // `.insertBefore` and `oldEndVnode.$elm$.nextSibling`. If there is a
  1175. // sibling for `oldEndVnode.$elm$` then we want to move the DOM node for
  1176. // `oldStartVnode` between `oldEndVnode` and it's sibling, like so:
  1177. //
  1178. // <old-start-node />
  1179. // <some-intervening-node />
  1180. // <old-end-node />
  1181. // <!-- -> <-- `oldStartVnode.$elm$` should be inserted here
  1182. // <next-sibling />
  1183. //
  1184. // If instead `oldEndVnode.$elm$` has no sibling then we just want to put
  1185. // the node for `oldStartVnode` at the end of the children of
  1186. // `parentElm`. Luckily, `Node.nextSibling` will return `null` if there
  1187. // aren't any siblings, and passing `null` to `Node.insertBefore` will
  1188. // append it to the children of the parent element.
  1189. parentElm.insertBefore(oldStartVnode.$elm$, oldEndVnode.$elm$.nextSibling);
  1190. oldStartVnode = oldCh[++oldStartIdx];
  1191. newEndVnode = newCh[--newEndIdx];
  1192. }
  1193. else if (isSameVnode(oldEndVnode, newStartVnode)) {
  1194. // case: "Vnode moved left"
  1195. //
  1196. // We've found that the first node in our window on the new children is
  1197. // the same VNode as the _last_ node in our window on the old children.
  1198. // Visually, this is the layout of these two nodes:
  1199. //
  1200. // newCh: [..., newStartVnode , ... , newEndVnode , ...]
  1201. // ^^^^^^^^^^^^^
  1202. // oldCh: [..., oldStartVnode , ... , oldEndVnode , ...]
  1203. // ^^^^^^^^^^^
  1204. //
  1205. // In this situation we need to patch `newStartVnode` onto `oldEndVnode`
  1206. // (which will handle updating any changed attributes, reconciling their
  1207. // children etc) but we also need to move the DOM node to which
  1208. // `oldEndVnode` corresponds.
  1209. if (BUILD.slotRelocation && (oldStartVnode.$tag$ === 'slot' || newEndVnode.$tag$ === 'slot')) {
  1210. putBackInOriginalLocation(oldEndVnode.$elm$.parentNode, false);
  1211. }
  1212. patch(oldEndVnode, newStartVnode);
  1213. // We've already checked above if `oldStartVnode` and `newStartVnode` are
  1214. // the same node, so since we're here we know that they are not. Thus we
  1215. // can move the element for `oldEndVnode` _before_ the element for
  1216. // `oldStartVnode`, leaving `oldStartVnode` to be reconciled in the
  1217. // future.
  1218. parentElm.insertBefore(oldEndVnode.$elm$, oldStartVnode.$elm$);
  1219. oldEndVnode = oldCh[--oldEndIdx];
  1220. newStartVnode = newCh[++newStartIdx];
  1221. }
  1222. else {
  1223. // Here we do some checks to match up old and new nodes based on the
  1224. // `$key$` attribute, which is set by putting a `key="my-key"` attribute
  1225. // in the JSX for a DOM element in the implementation of a Stencil
  1226. // component.
  1227. //
  1228. // First we check to see if there are any nodes in the array of old
  1229. // children which have the same key as the first node in the new
  1230. // children.
  1231. idxInOld = -1;
  1232. if (BUILD.vdomKey) {
  1233. for (i = oldStartIdx; i <= oldEndIdx; ++i) {
  1234. if (oldCh[i] && oldCh[i].$key$ !== null && oldCh[i].$key$ === newStartVnode.$key$) {
  1235. idxInOld = i;
  1236. break;
  1237. }
  1238. }
  1239. }
  1240. if (BUILD.vdomKey && idxInOld >= 0) {
  1241. // We found a node in the old children which matches up with the first
  1242. // node in the new children! So let's deal with that
  1243. elmToMove = oldCh[idxInOld];
  1244. if (elmToMove.$tag$ !== newStartVnode.$tag$) {
  1245. // the tag doesn't match so we'll need a new DOM element
  1246. node = createElm(oldCh && oldCh[newStartIdx], newVNode, idxInOld, parentElm);
  1247. }
  1248. else {
  1249. patch(elmToMove, newStartVnode);
  1250. // invalidate the matching old node so that we won't try to update it
  1251. // again later on
  1252. oldCh[idxInOld] = undefined;
  1253. node = elmToMove.$elm$;
  1254. }
  1255. newStartVnode = newCh[++newStartIdx];
  1256. }
  1257. else {
  1258. // We either didn't find an element in the old children that matches
  1259. // the key of the first new child OR the build is not using `key`
  1260. // attributes at all. In either case we need to create a new element
  1261. // for the new node.
  1262. node = createElm(oldCh && oldCh[newStartIdx], newVNode, newStartIdx, parentElm);
  1263. newStartVnode = newCh[++newStartIdx];
  1264. }
  1265. if (node) {
  1266. // if we created a new node then handle inserting it to the DOM
  1267. if (BUILD.slotRelocation) {
  1268. parentReferenceNode(oldStartVnode.$elm$).insertBefore(node, referenceNode(oldStartVnode.$elm$));
  1269. }
  1270. else {
  1271. oldStartVnode.$elm$.parentNode.insertBefore(node, oldStartVnode.$elm$);
  1272. }
  1273. }
  1274. }
  1275. }
  1276. if (oldStartIdx > oldEndIdx) {
  1277. // we have some more new nodes to add which don't match up with old nodes
  1278. addVnodes(parentElm, newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].$elm$, newVNode, newCh, newStartIdx, newEndIdx);
  1279. }
  1280. else if (BUILD.updatable && newStartIdx > newEndIdx) {
  1281. // there are nodes in the `oldCh` array which no longer correspond to nodes
  1282. // in the new array, so lets remove them (which entails cleaning up the
  1283. // relevant DOM nodes)
  1284. removeVnodes(oldCh, oldStartIdx, oldEndIdx);
  1285. }
  1286. };
  1287. /**
  1288. * Compare two VNodes to determine if they are the same
  1289. *
  1290. * **NB**: This function is an equality _heuristic_ based on the available
  1291. * information set on the two VNodes and can be misleading under certain
  1292. * circumstances. In particular, if the two nodes do not have `key` attrs
  1293. * (available under `$key$` on VNodes) then the function falls back on merely
  1294. * checking that they have the same tag.
  1295. *
  1296. * So, in other words, if `key` attrs are not set on VNodes which may be
  1297. * changing order within a `children` array or something along those lines then
  1298. * we could obtain a false positive and then have to do needless re-rendering.
  1299. *
  1300. * @param leftVNode the first VNode to check
  1301. * @param rightVNode the second VNode to check
  1302. * @returns whether they're equal or not
  1303. */
  1304. const isSameVnode = (leftVNode, rightVNode) => {
  1305. // compare if two vnode to see if they're "technically" the same
  1306. // need to have the same element tag, and same key to be the same
  1307. if (leftVNode.$tag$ === rightVNode.$tag$) {
  1308. if (BUILD.slotRelocation && leftVNode.$tag$ === 'slot') {
  1309. return leftVNode.$name$ === rightVNode.$name$;
  1310. }
  1311. // this will be set if components in the build have `key` attrs set on them
  1312. if (BUILD.vdomKey) {
  1313. return leftVNode.$key$ === rightVNode.$key$;
  1314. }
  1315. return true;
  1316. }
  1317. return false;
  1318. };
  1319. const referenceNode = (node) => {
  1320. // this node was relocated to a new location in the dom
  1321. // because of some other component's slot
  1322. // but we still have an html comment in place of where
  1323. // it's original location was according to it's original vdom
  1324. return (node && node['s-ol']) || node;
  1325. };
  1326. const parentReferenceNode = (node) => (node['s-ol'] ? node['s-ol'] : node).parentNode;
  1327. /**
  1328. * Handle reconciling an outdated VNode with a new one which corresponds to
  1329. * it. This function handles flushing updates to the DOM and reconciling the
  1330. * children of the two nodes (if any).
  1331. *
  1332. * @param oldVNode an old VNode whose DOM element and children we want to update
  1333. * @param newVNode a new VNode representing an updated version of the old one
  1334. */
  1335. const patch = (oldVNode, newVNode) => {
  1336. const elm = (newVNode.$elm$ = oldVNode.$elm$);
  1337. const oldChildren = oldVNode.$children$;
  1338. const newChildren = newVNode.$children$;
  1339. const tag = newVNode.$tag$;
  1340. const text = newVNode.$text$;
  1341. let defaultHolder;
  1342. if (!BUILD.vdomText || text === null) {
  1343. if (BUILD.svg) {
  1344. // test if we're rendering an svg element, or still rendering nodes inside of one
  1345. // only add this to the when the compiler sees we're using an svg somewhere
  1346. isSvgMode = tag === 'svg' ? true : tag === 'foreignObject' ? false : isSvgMode;
  1347. }
  1348. if (BUILD.vdomAttribute || BUILD.reflect) {
  1349. if (BUILD.slot && tag === 'slot')
  1350. ;
  1351. else {
  1352. // either this is the first render of an element OR it's an update
  1353. // AND we already know it's possible it could have changed
  1354. // this updates the element's css classes, attrs, props, listeners, etc.
  1355. updateElement(oldVNode, newVNode, isSvgMode);
  1356. }
  1357. }
  1358. if (BUILD.updatable && oldChildren !== null && newChildren !== null) {
  1359. // looks like there's child vnodes for both the old and new vnodes
  1360. // so we need to call `updateChildren` to reconcile them
  1361. updateChildren(elm, oldChildren, newVNode, newChildren);
  1362. }
  1363. else if (newChildren !== null) {
  1364. // no old child vnodes, but there are new child vnodes to add
  1365. if (BUILD.updatable && BUILD.vdomText && oldVNode.$text$ !== null) {
  1366. // the old vnode was text, so be sure to clear it out
  1367. elm.textContent = '';
  1368. }
  1369. // add the new vnode children
  1370. addVnodes(elm, null, newVNode, newChildren, 0, newChildren.length - 1);
  1371. }
  1372. else if (BUILD.updatable && oldChildren !== null) {
  1373. // no new child vnodes, but there are old child vnodes to remove
  1374. removeVnodes(oldChildren, 0, oldChildren.length - 1);
  1375. }
  1376. if (BUILD.svg && isSvgMode && tag === 'svg') {
  1377. isSvgMode = false;
  1378. }
  1379. }
  1380. else if (BUILD.vdomText && BUILD.slotRelocation && (defaultHolder = elm['s-cr'])) {
  1381. // this element has slotted content
  1382. defaultHolder.parentNode.textContent = text;
  1383. }
  1384. else if (BUILD.vdomText && oldVNode.$text$ !== text) {
  1385. // update the text content for the text only vnode
  1386. // and also only if the text is different than before
  1387. elm.data = text;
  1388. }
  1389. };
  1390. const updateFallbackSlotVisibility = (elm) => {
  1391. // tslint:disable-next-line: prefer-const
  1392. const childNodes = elm.childNodes;
  1393. let childNode;
  1394. let i;
  1395. let ilen;
  1396. let j;
  1397. let slotNameAttr;
  1398. let nodeType;
  1399. for (i = 0, ilen = childNodes.length; i < ilen; i++) {
  1400. childNode = childNodes[i];
  1401. if (childNode.nodeType === 1 /* NODE_TYPE.ElementNode */) {
  1402. if (childNode['s-sr']) {
  1403. // this is a slot fallback node
  1404. // get the slot name for this slot reference node
  1405. slotNameAttr = childNode['s-sn'];
  1406. // by default always show a fallback slot node
  1407. // then hide it if there are other slots in the light dom
  1408. childNode.hidden = false;
  1409. for (j = 0; j < ilen; j++) {
  1410. nodeType = childNodes[j].nodeType;
  1411. if (childNodes[j]['s-hn'] !== childNode['s-hn'] || slotNameAttr !== '') {
  1412. // this sibling node is from a different component OR is a named fallback slot node
  1413. if (nodeType === 1 /* NODE_TYPE.ElementNode */ && slotNameAttr === childNodes[j].getAttribute('slot')) {
  1414. childNode.hidden = true;
  1415. break;
  1416. }
  1417. }
  1418. else {
  1419. // this is a default fallback slot node
  1420. // any element or text node (with content)
  1421. // should hide the default fallback slot node
  1422. if (nodeType === 1 /* NODE_TYPE.ElementNode */ ||
  1423. (nodeType === 3 /* NODE_TYPE.TextNode */ && childNodes[j].textContent.trim() !== '')) {
  1424. childNode.hidden = true;
  1425. break;
  1426. }
  1427. }
  1428. }
  1429. }
  1430. // keep drilling down
  1431. updateFallbackSlotVisibility(childNode);
  1432. }
  1433. }
  1434. };
  1435. const relocateNodes = [];
  1436. const relocateSlotContent = (elm) => {
  1437. // tslint:disable-next-line: prefer-const
  1438. let childNode;
  1439. let node;
  1440. let hostContentNodes;
  1441. let slotNameAttr;
  1442. let relocateNodeData;
  1443. let j;
  1444. let i = 0;
  1445. const childNodes = elm.childNodes;
  1446. const ilen = childNodes.length;
  1447. for (; i < ilen; i++) {
  1448. childNode = childNodes[i];
  1449. if (childNode['s-sr'] && (node = childNode['s-cr']) && node.parentNode) {
  1450. // first got the content reference comment node
  1451. // then we got it's parent, which is where all the host content is in now
  1452. hostContentNodes = node.parentNode.childNodes;
  1453. slotNameAttr = childNode['s-sn'];
  1454. for (j = hostContentNodes.length - 1; j >= 0; j--) {
  1455. node = hostContentNodes[j];
  1456. if (!node['s-cn'] && !node['s-nr'] && node['s-hn'] !== childNode['s-hn']) {
  1457. // let's do some relocating to its new home
  1458. // but never relocate a content reference node
  1459. // that is suppose to always represent the original content location
  1460. if (isNodeLocatedInSlot(node, slotNameAttr)) {
  1461. // it's possible we've already decided to relocate this node
  1462. relocateNodeData = relocateNodes.find((r) => r.$nodeToRelocate$ === node);
  1463. // made some changes to slots
  1464. // let's make sure we also double check
  1465. // fallbacks are correctly hidden or shown
  1466. checkSlotFallbackVisibility = true;
  1467. node['s-sn'] = node['s-sn'] || slotNameAttr;
  1468. if (relocateNodeData) {
  1469. // previously we never found a slot home for this node
  1470. // but turns out we did, so let's remember it now
  1471. relocateNodeData.$slotRefNode$ = childNode;
  1472. }
  1473. else {
  1474. // add to our list of nodes to relocate
  1475. relocateNodes.push({
  1476. $slotRefNode$: childNode,
  1477. $nodeToRelocate$: node,
  1478. });
  1479. }
  1480. if (node['s-sr']) {
  1481. relocateNodes.map((relocateNode) => {
  1482. if (isNodeLocatedInSlot(relocateNode.$nodeToRelocate$, node['s-sn'])) {
  1483. relocateNodeData = relocateNodes.find((r) => r.$nodeToRelocate$ === node);
  1484. if (relocateNodeData && !relocateNode.$slotRefNode$) {
  1485. relocateNode.$slotRefNode$ = relocateNodeData.$slotRefNode$;
  1486. }
  1487. }
  1488. });
  1489. }
  1490. }
  1491. else if (!relocateNodes.some((r) => r.$nodeToRelocate$ === node)) {
  1492. // so far this element does not have a slot home, not setting slotRefNode on purpose
  1493. // if we never find a home for this element then we'll need to hide it
  1494. relocateNodes.push({
  1495. $nodeToRelocate$: node,
  1496. });
  1497. }
  1498. }
  1499. }
  1500. }
  1501. if (childNode.nodeType === 1 /* NODE_TYPE.ElementNode */) {
  1502. relocateSlotContent(childNode);
  1503. }
  1504. }
  1505. };
  1506. const isNodeLocatedInSlot = (nodeToRelocate, slotNameAttr) => {
  1507. if (nodeToRelocate.nodeType === 1 /* NODE_TYPE.ElementNode */) {
  1508. if (nodeToRelocate.getAttribute('slot') === null && slotNameAttr === '') {
  1509. return true;
  1510. }
  1511. if (nodeToRelocate.getAttribute('slot') === slotNameAttr) {
  1512. return true;
  1513. }
  1514. return false;
  1515. }
  1516. if (nodeToRelocate['s-sn'] === slotNameAttr) {
  1517. return true;
  1518. }
  1519. return slotNameAttr === '';
  1520. };
  1521. const callNodeRefs = (vNode) => {
  1522. if (BUILD.vdomRef) {
  1523. vNode.$attrs$ && vNode.$attrs$.ref && vNode.$attrs$.ref(null);
  1524. vNode.$children$ && vNode.$children$.map(callNodeRefs);
  1525. }
  1526. };
  1527. const renderVdom = (hostRef, renderFnResults) => {
  1528. const hostElm = hostRef.$hostElement$;
  1529. const cmpMeta = hostRef.$cmpMeta$;
  1530. const oldVNode = hostRef.$vnode$ || newVNode(null, null);
  1531. const rootVnode = isHost(renderFnResults) ? renderFnResults : h(null, null, renderFnResults);
  1532. hostTagName = hostElm.tagName;
  1533. // <Host> runtime check
  1534. if (BUILD.isDev && Array.isArray(renderFnResults) && renderFnResults.some(isHost)) {
  1535. throw new Error(`The <Host> must be the single root component.
  1536. Looks like the render() function of "${hostTagName.toLowerCase()}" is returning an array that contains the <Host>.
  1537. The render() function should look like this instead:
  1538. render() {
  1539. // Do not return an array
  1540. return (
  1541. <Host>{content}</Host>
  1542. );
  1543. }
  1544. `);
  1545. }
  1546. if (BUILD.reflect && cmpMeta.$attrsToReflect$) {
  1547. rootVnode.$attrs$ = rootVnode.$attrs$ || {};
  1548. cmpMeta.$attrsToReflect$.map(([propName, attribute]) => (rootVnode.$attrs$[attribute] = hostElm[propName]));
  1549. }
  1550. rootVnode.$tag$ = null;
  1551. rootVnode.$flags$ |= 4 /* VNODE_FLAGS.isHost */;
  1552. hostRef.$vnode$ = rootVnode;
  1553. rootVnode.$elm$ = oldVNode.$elm$ = (BUILD.shadowDom ? hostElm.shadowRoot || hostElm : hostElm);
  1554. if (BUILD.scoped || BUILD.shadowDom) {
  1555. scopeId = hostElm['s-sc'];
  1556. }
  1557. if (BUILD.slotRelocation) {
  1558. contentRef = hostElm['s-cr'];
  1559. useNativeShadowDom = supportsShadow && (cmpMeta.$flags$ & 1 /* CMP_FLAGS.shadowDomEncapsulation */) !== 0;
  1560. // always reset
  1561. checkSlotFallbackVisibility = false;
  1562. }
  1563. // synchronous patch
  1564. patch(oldVNode, rootVnode);
  1565. if (BUILD.slotRelocation) {
  1566. // while we're moving nodes around existing nodes, temporarily disable
  1567. // the disconnectCallback from working
  1568. plt.$flags$ |= 1 /* PLATFORM_FLAGS.isTmpDisconnected */;
  1569. if (checkSlotRelocate) {
  1570. relocateSlotContent(rootVnode.$elm$);
  1571. let relocateData;
  1572. let nodeToRelocate;
  1573. let orgLocationNode;
  1574. let parentNodeRef;
  1575. let insertBeforeNode;
  1576. let refNode;
  1577. let i = 0;
  1578. for (; i < relocateNodes.length; i++) {
  1579. relocateData = relocateNodes[i];
  1580. nodeToRelocate = relocateData.$nodeToRelocate$;
  1581. if (!nodeToRelocate['s-ol']) {
  1582. // add a reference node marking this node's original location
  1583. // keep a reference to this node for later lookups
  1584. orgLocationNode =
  1585. BUILD.isDebug || BUILD.hydrateServerSide
  1586. ? originalLocationDebugNode(nodeToRelocate)
  1587. : doc.createTextNode('');
  1588. orgLocationNode['s-nr'] = nodeToRelocate;
  1589. nodeToRelocate.parentNode.insertBefore((nodeToRelocate['s-ol'] = orgLocationNode), nodeToRelocate);
  1590. }
  1591. }
  1592. for (i = 0; i < relocateNodes.length; i++) {
  1593. relocateData = relocateNodes[i];
  1594. nodeToRelocate = relocateData.$nodeToRelocate$;
  1595. if (relocateData.$slotRefNode$) {
  1596. // by default we're just going to insert it directly
  1597. // after the slot reference node
  1598. parentNodeRef = relocateData.$slotRefNode$.parentNode;
  1599. insertBeforeNode = relocateData.$slotRefNode$.nextSibling;
  1600. orgLocationNode = nodeToRelocate['s-ol'];
  1601. while ((orgLocationNode = orgLocationNode.previousSibling)) {
  1602. refNode = orgLocationNode['s-nr'];
  1603. if (refNode && refNode['s-sn'] === nodeToRelocate['s-sn'] && parentNodeRef === refNode.parentNode) {
  1604. refNode = refNode.nextSibling;
  1605. if (!refNode || !refNode['s-nr']) {
  1606. insertBeforeNode = refNode;
  1607. break;
  1608. }
  1609. }
  1610. }
  1611. if ((!insertBeforeNode && parentNodeRef !== nodeToRelocate.parentNode) ||
  1612. nodeToRelocate.nextSibling !== insertBeforeNode) {
  1613. // we've checked that it's worth while to relocate
  1614. // since that the node to relocate
  1615. // has a different next sibling or parent relocated
  1616. if (nodeToRelocate !== insertBeforeNode) {
  1617. if (!nodeToRelocate['s-hn'] && nodeToRelocate['s-ol']) {
  1618. // probably a component in the index.html that doesn't have it's hostname set
  1619. nodeToRelocate['s-hn'] = nodeToRelocate['s-ol'].parentNode.nodeName;
  1620. }
  1621. // add it back to the dom but in its new home
  1622. parentNodeRef.insertBefore(nodeToRelocate, insertBeforeNode);
  1623. }
  1624. }
  1625. }
  1626. else {
  1627. // this node doesn't have a slot home to go to, so let's hide it
  1628. if (nodeToRelocate.nodeType === 1 /* NODE_TYPE.ElementNode */) {
  1629. nodeToRelocate.hidden = true;
  1630. }
  1631. }
  1632. }
  1633. }
  1634. if (checkSlotFallbackVisibility) {
  1635. updateFallbackSlotVisibility(rootVnode.$elm$);
  1636. }
  1637. // done moving nodes around
  1638. // allow the disconnect callback to work again
  1639. plt.$flags$ &= ~1 /* PLATFORM_FLAGS.isTmpDisconnected */;
  1640. // always reset
  1641. relocateNodes.length = 0;
  1642. }
  1643. };
  1644. // slot comment debug nodes only created with the `--debug` flag
  1645. // otherwise these nodes are text nodes w/out content
  1646. const slotReferenceDebugNode = (slotVNode) => doc.createComment(`<slot${slotVNode.$name$ ? ' name="' + slotVNode.$name$ + '"' : ''}> (host=${hostTagName.toLowerCase()})`);
  1647. const originalLocationDebugNode = (nodeToRelocate) => doc.createComment(`org-location for ` +
  1648. (nodeToRelocate.localName
  1649. ? `<${nodeToRelocate.localName}> (host=${nodeToRelocate['s-hn']})`
  1650. : `[${nodeToRelocate.textContent}]`));
  1651. const attachToAncestor = (hostRef, ancestorComponent) => {
  1652. if (BUILD.asyncLoading && ancestorComponent && !hostRef.$onRenderResolve$ && ancestorComponent['s-p']) {
  1653. ancestorComponent['s-p'].push(new Promise((r) => (hostRef.$onRenderResolve$ = r)));
  1654. }
  1655. };
  1656. const scheduleUpdate = (hostRef, isInitialLoad) => {
  1657. if (BUILD.taskQueue && BUILD.updatable) {
  1658. hostRef.$flags$ |= 16 /* HOST_FLAGS.isQueuedForUpdate */;
  1659. }
  1660. if (BUILD.asyncLoading && hostRef.$flags$ & 4 /* HOST_FLAGS.isWaitingForChildren */) {
  1661. hostRef.$flags$ |= 512 /* HOST_FLAGS.needsRerender */;
  1662. return;
  1663. }
  1664. attachToAncestor(hostRef, hostRef.$ancestorComponent$);
  1665. // there is no ancestor component or the ancestor component
  1666. // has already fired off its lifecycle update then
  1667. // fire off the initial update
  1668. const dispatch = () => dispatchHooks(hostRef, isInitialLoad);
  1669. return BUILD.taskQueue ? writeTask(dispatch) : dispatch();
  1670. };
  1671. const dispatchHooks = (hostRef, isInitialLoad) => {
  1672. const elm = hostRef.$hostElement$;
  1673. const endSchedule = createTime('scheduleUpdate', hostRef.$cmpMeta$.$tagName$);
  1674. const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;
  1675. let promise;
  1676. if (isInitialLoad) {
  1677. if (BUILD.lazyLoad && BUILD.hostListener) {
  1678. hostRef.$flags$ |= 256 /* HOST_FLAGS.isListenReady */;
  1679. if (hostRef.$queuedListeners$) {
  1680. hostRef.$queuedListeners$.map(([methodName, event]) => safeCall(instance, methodName, event));
  1681. hostRef.$queuedListeners$ = null;
  1682. }
  1683. }
  1684. emitLifecycleEvent(elm, 'componentWillLoad');
  1685. if (BUILD.cmpWillLoad) {
  1686. promise = safeCall(instance, 'componentWillLoad');
  1687. }
  1688. }
  1689. else {
  1690. emitLifecycleEvent(elm, 'componentWillUpdate');
  1691. if (BUILD.cmpWillUpdate) {
  1692. promise = safeCall(instance, 'componentWillUpdate');
  1693. }
  1694. }
  1695. emitLifecycleEvent(elm, 'componentWillRender');
  1696. if (BUILD.cmpWillRender) {
  1697. promise = then(promise, () => safeCall(instance, 'componentWillRender'));
  1698. }
  1699. endSchedule();
  1700. return then(promise, () => updateComponent(hostRef, instance, isInitialLoad));
  1701. };
  1702. const updateComponent = async (hostRef, instance, isInitialLoad) => {
  1703. // updateComponent
  1704. const elm = hostRef.$hostElement$;
  1705. const endUpdate = createTime('update', hostRef.$cmpMeta$.$tagName$);
  1706. const rc = elm['s-rc'];
  1707. if (BUILD.style && isInitialLoad) {
  1708. // DOM WRITE!
  1709. attachStyles(hostRef);
  1710. }
  1711. const endRender = createTime('render', hostRef.$cmpMeta$.$tagName$);
  1712. if (BUILD.isDev) {
  1713. hostRef.$flags$ |= 1024 /* HOST_FLAGS.devOnRender */;
  1714. }
  1715. if (BUILD.hydrateServerSide) {
  1716. await callRender(hostRef, instance, elm);
  1717. }
  1718. else {
  1719. callRender(hostRef, instance, elm);
  1720. }
  1721. if (BUILD.cssVarShim && plt.$cssShim$) {
  1722. plt.$cssShim$.updateHost(elm);
  1723. }
  1724. if (BUILD.isDev) {
  1725. hostRef.$renderCount$++;
  1726. hostRef.$flags$ &= ~1024 /* HOST_FLAGS.devOnRender */;
  1727. }
  1728. if (BUILD.hydrateServerSide) {
  1729. try {
  1730. // manually connected child components during server-side hydrate
  1731. serverSideConnected(elm);
  1732. if (isInitialLoad) {
  1733. // using only during server-side hydrate
  1734. if (hostRef.$cmpMeta$.$flags$ & 1 /* CMP_FLAGS.shadowDomEncapsulation */) {
  1735. elm['s-en'] = '';
  1736. }
  1737. else if (hostRef.$cmpMeta$.$flags$ & 2 /* CMP_FLAGS.scopedCssEncapsulation */) {
  1738. elm['s-en'] = 'c';
  1739. }
  1740. }
  1741. }
  1742. catch (e) {
  1743. consoleError(e, elm);
  1744. }
  1745. }
  1746. if (BUILD.asyncLoading && rc) {
  1747. // ok, so turns out there are some child host elements
  1748. // waiting on this parent element to load
  1749. // let's fire off all update callbacks waiting
  1750. rc.map((cb) => cb());
  1751. elm['s-rc'] = undefined;
  1752. }
  1753. endRender();
  1754. endUpdate();
  1755. if (BUILD.asyncLoading) {
  1756. const childrenPromises = elm['s-p'];
  1757. const postUpdate = () => postUpdateComponent(hostRef);
  1758. if (childrenPromises.length === 0) {
  1759. postUpdate();
  1760. }
  1761. else {
  1762. Promise.all(childrenPromises).then(postUpdate);
  1763. hostRef.$flags$ |= 4 /* HOST_FLAGS.isWaitingForChildren */;
  1764. childrenPromises.length = 0;
  1765. }
  1766. }
  1767. else {
  1768. postUpdateComponent(hostRef);
  1769. }
  1770. };
  1771. const callRender = (hostRef, instance, elm) => {
  1772. // in order for bundlers to correctly treeshake the BUILD object
  1773. // we need to ensure BUILD is not deoptimized within a try/catch
  1774. // https://rollupjs.org/guide/en/#treeshake tryCatchDeoptimization
  1775. const allRenderFn = BUILD.allRenderFn ? true : false;
  1776. const lazyLoad = BUILD.lazyLoad ? true : false;
  1777. const taskQueue = BUILD.taskQueue ? true : false;
  1778. const updatable = BUILD.updatable ? true : false;
  1779. try {
  1780. renderingRef = instance;
  1781. instance = allRenderFn ? instance.render() : instance.render && instance.render();
  1782. if (updatable && taskQueue) {
  1783. hostRef.$flags$ &= ~16 /* HOST_FLAGS.isQueuedForUpdate */;
  1784. }
  1785. if (updatable || lazyLoad) {
  1786. hostRef.$flags$ |= 2 /* HOST_FLAGS.hasRendered */;
  1787. }
  1788. if (BUILD.hasRenderFn || BUILD.reflect) {
  1789. if (BUILD.vdomRender || BUILD.reflect) {
  1790. // looks like we've got child nodes to render into this host element
  1791. // or we need to update the css class/attrs on the host element
  1792. // DOM WRITE!
  1793. if (BUILD.hydrateServerSide) {
  1794. return Promise.resolve(instance).then((value) => renderVdom(hostRef, value));
  1795. }
  1796. else {
  1797. renderVdom(hostRef, instance);
  1798. }
  1799. }
  1800. else {
  1801. elm.textContent = instance;
  1802. }
  1803. }
  1804. }
  1805. catch (e) {
  1806. consoleError(e, hostRef.$hostElement$);
  1807. }
  1808. renderingRef = null;
  1809. return null;
  1810. };
  1811. const getRenderingRef = () => renderingRef;
  1812. const postUpdateComponent = (hostRef) => {
  1813. const tagName = hostRef.$cmpMeta$.$tagName$;
  1814. const elm = hostRef.$hostElement$;
  1815. const endPostUpdate = createTime('postUpdate', tagName);
  1816. const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;
  1817. const ancestorComponent = hostRef.$ancestorComponent$;
  1818. if (BUILD.cmpDidRender) {
  1819. if (BUILD.isDev) {
  1820. hostRef.$flags$ |= 1024 /* HOST_FLAGS.devOnRender */;
  1821. }
  1822. safeCall(instance, 'componentDidRender');
  1823. if (BUILD.isDev) {
  1824. hostRef.$flags$ &= ~1024 /* HOST_FLAGS.devOnRender */;
  1825. }
  1826. }
  1827. emitLifecycleEvent(elm, 'componentDidRender');
  1828. if (!(hostRef.$flags$ & 64 /* HOST_FLAGS.hasLoadedComponent */)) {
  1829. hostRef.$flags$ |= 64 /* HOST_FLAGS.hasLoadedComponent */;
  1830. if (BUILD.asyncLoading && BUILD.cssAnnotations) {
  1831. // DOM WRITE!
  1832. addHydratedFlag(elm);
  1833. }
  1834. if (BUILD.cmpDidLoad) {
  1835. if (BUILD.isDev) {
  1836. hostRef.$flags$ |= 2048 /* HOST_FLAGS.devOnDidLoad */;
  1837. }
  1838. safeCall(instance, 'componentDidLoad');
  1839. if (BUILD.isDev) {
  1840. hostRef.$flags$ &= ~2048 /* HOST_FLAGS.devOnDidLoad */;
  1841. }
  1842. }
  1843. emitLifecycleEvent(elm, 'componentDidLoad');
  1844. endPostUpdate();
  1845. if (BUILD.asyncLoading) {
  1846. hostRef.$onReadyResolve$(elm);
  1847. if (!ancestorComponent) {
  1848. appDidLoad(tagName);
  1849. }
  1850. }
  1851. }
  1852. else {
  1853. if (BUILD.cmpDidUpdate) {
  1854. // we've already loaded this component
  1855. // fire off the user's componentDidUpdate method (if one was provided)
  1856. // componentDidUpdate runs AFTER render() has been called
  1857. // and all child components have finished updating
  1858. if (BUILD.isDev) {
  1859. hostRef.$flags$ |= 1024 /* HOST_FLAGS.devOnRender */;
  1860. }
  1861. safeCall(instance, 'componentDidUpdate');
  1862. if (BUILD.isDev) {
  1863. hostRef.$flags$ &= ~1024 /* HOST_FLAGS.devOnRender */;
  1864. }
  1865. }
  1866. emitLifecycleEvent(elm, 'componentDidUpdate');
  1867. endPostUpdate();
  1868. }
  1869. if (BUILD.hotModuleReplacement) {
  1870. elm['s-hmr-load'] && elm['s-hmr-load']();
  1871. }
  1872. if (BUILD.method && BUILD.lazyLoad) {
  1873. hostRef.$onInstanceResolve$(elm);
  1874. }
  1875. // load events fire from bottom to top
  1876. // the deepest elements load first then bubbles up
  1877. if (BUILD.asyncLoading) {
  1878. if (hostRef.$onRenderResolve$) {
  1879. hostRef.$onRenderResolve$();
  1880. hostRef.$onRenderResolve$ = undefined;
  1881. }
  1882. if (hostRef.$flags$ & 512 /* HOST_FLAGS.needsRerender */) {
  1883. nextTick(() => scheduleUpdate(hostRef, false));
  1884. }
  1885. hostRef.$flags$ &= ~(4 /* HOST_FLAGS.isWaitingForChildren */ | 512 /* HOST_FLAGS.needsRerender */);
  1886. }
  1887. // ( •_•)
  1888. // ( •_•)>⌐■-■
  1889. // (⌐■_■)
  1890. };
  1891. const forceUpdate = (ref) => {
  1892. if (BUILD.updatable) {
  1893. const hostRef = getHostRef(ref);
  1894. const isConnected = hostRef.$hostElement$.isConnected;
  1895. if (isConnected &&
  1896. (hostRef.$flags$ & (2 /* HOST_FLAGS.hasRendered */ | 16 /* HOST_FLAGS.isQueuedForUpdate */)) === 2 /* HOST_FLAGS.hasRendered */) {
  1897. scheduleUpdate(hostRef, false);
  1898. }
  1899. // Returns "true" when the forced update was successfully scheduled
  1900. return isConnected;
  1901. }
  1902. return false;
  1903. };
  1904. const appDidLoad = (who) => {
  1905. // on appload
  1906. // we have finish the first big initial render
  1907. if (BUILD.cssAnnotations) {
  1908. addHydratedFlag(doc.documentElement);
  1909. }
  1910. if (BUILD.asyncQueue) {
  1911. plt.$flags$ |= 2 /* PLATFORM_FLAGS.appLoaded */;
  1912. }
  1913. nextTick(() => emitEvent(win, 'appload', { detail: { namespace: NAMESPACE } }));
  1914. if (BUILD.profile && performance.measure) {
  1915. performance.measure(`[Stencil] ${NAMESPACE} initial load (by ${who})`, 'st:app:start');
  1916. }
  1917. };
  1918. const safeCall = (instance, method, arg) => {
  1919. if (instance && instance[method]) {
  1920. try {
  1921. return instance[method](arg);
  1922. }
  1923. catch (e) {
  1924. consoleError(e);
  1925. }
  1926. }
  1927. return undefined;
  1928. };
  1929. const then = (promise, thenFn) => {
  1930. return promise && promise.then ? promise.then(thenFn) : thenFn();
  1931. };
  1932. const emitLifecycleEvent = (elm, lifecycleName) => {
  1933. if (BUILD.lifecycleDOMEvents) {
  1934. emitEvent(elm, 'stencil_' + lifecycleName, {
  1935. bubbles: true,
  1936. composed: true,
  1937. detail: {
  1938. namespace: NAMESPACE,
  1939. },
  1940. });
  1941. }
  1942. };
  1943. const addHydratedFlag = (elm) => BUILD.hydratedClass
  1944. ? elm.classList.add('hydrated')
  1945. : BUILD.hydratedAttribute
  1946. ? elm.setAttribute('hydrated', '')
  1947. : undefined;
  1948. const serverSideConnected = (elm) => {
  1949. const children = elm.children;
  1950. if (children != null) {
  1951. for (let i = 0, ii = children.length; i < ii; i++) {
  1952. const childElm = children[i];
  1953. if (typeof childElm.connectedCallback === 'function') {
  1954. childElm.connectedCallback();
  1955. }
  1956. serverSideConnected(childElm);
  1957. }
  1958. }
  1959. };
  1960. const getValue = (ref, propName) => getHostRef(ref).$instanceValues$.get(propName);
  1961. const setValue = (ref, propName, newVal, cmpMeta) => {
  1962. // check our new property value against our internal value
  1963. const hostRef = getHostRef(ref);
  1964. const elm = BUILD.lazyLoad ? hostRef.$hostElement$ : ref;
  1965. const oldVal = hostRef.$instanceValues$.get(propName);
  1966. const flags = hostRef.$flags$;
  1967. const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;
  1968. newVal = parsePropertyValue(newVal, cmpMeta.$members$[propName][0]);
  1969. // explicitly check for NaN on both sides, as `NaN === NaN` is always false
  1970. const areBothNaN = Number.isNaN(oldVal) && Number.isNaN(newVal);
  1971. const didValueChange = newVal !== oldVal && !areBothNaN;
  1972. if ((!BUILD.lazyLoad || !(flags & 8 /* HOST_FLAGS.isConstructingInstance */) || oldVal === undefined) && didValueChange) {
  1973. // gadzooks! the property's value has changed!!
  1974. // set our new value!
  1975. hostRef.$instanceValues$.set(propName, newVal);
  1976. if (BUILD.isDev) {
  1977. if (hostRef.$flags$ & 1024 /* HOST_FLAGS.devOnRender */) {
  1978. consoleDevWarn(`The state/prop "${propName}" changed during rendering. This can potentially lead to infinite-loops and other bugs.`, '\nElement', elm, '\nNew value', newVal, '\nOld value', oldVal);
  1979. }
  1980. else if (hostRef.$flags$ & 2048 /* HOST_FLAGS.devOnDidLoad */) {
  1981. consoleDevWarn(`The state/prop "${propName}" changed during "componentDidLoad()", this triggers extra re-renders, try to setup on "componentWillLoad()"`, '\nElement', elm, '\nNew value', newVal, '\nOld value', oldVal);
  1982. }
  1983. }
  1984. if (!BUILD.lazyLoad || instance) {
  1985. // get an array of method names of watch functions to call
  1986. if (BUILD.watchCallback && cmpMeta.$watchers$ && flags & 128 /* HOST_FLAGS.isWatchReady */) {
  1987. const watchMethods = cmpMeta.$watchers$[propName];
  1988. if (watchMethods) {
  1989. // this instance is watching for when this property changed
  1990. watchMethods.map((watchMethodName) => {
  1991. try {
  1992. // fire off each of the watch methods that are watching this property
  1993. instance[watchMethodName](newVal, oldVal, propName);
  1994. }
  1995. catch (e) {
  1996. consoleError(e, elm);
  1997. }
  1998. });
  1999. }
  2000. }
  2001. if (BUILD.updatable &&
  2002. (flags & (2 /* HOST_FLAGS.hasRendered */ | 16 /* HOST_FLAGS.isQueuedForUpdate */)) === 2 /* HOST_FLAGS.hasRendered */) {
  2003. if (BUILD.cmpShouldUpdate && instance.componentShouldUpdate) {
  2004. if (instance.componentShouldUpdate(newVal, oldVal, propName) === false) {
  2005. return;
  2006. }
  2007. }
  2008. // looks like this value actually changed, so we've got work to do!
  2009. // but only if we've already rendered, otherwise just chill out
  2010. // queue that we need to do an update, but don't worry about queuing
  2011. // up millions cuz this function ensures it only runs once
  2012. scheduleUpdate(hostRef, false);
  2013. }
  2014. }
  2015. }
  2016. };
  2017. /**
  2018. * Attach a series of runtime constructs to a compiled Stencil component
  2019. * constructor, including getters and setters for the `@Prop` and `@State`
  2020. * decorators, callbacks for when attributes change, and so on.
  2021. *
  2022. * @param Cstr the constructor for a component that we need to process
  2023. * @param cmpMeta metadata collected previously about the component
  2024. * @param flags a number used to store a series of bit flags
  2025. * @returns a reference to the same constructor passed in (but now mutated)
  2026. */
  2027. const proxyComponent = (Cstr, cmpMeta, flags) => {
  2028. if (BUILD.member && cmpMeta.$members$) {
  2029. if (BUILD.watchCallback && Cstr.watchers) {
  2030. cmpMeta.$watchers$ = Cstr.watchers;
  2031. }
  2032. // It's better to have a const than two Object.entries()
  2033. const members = Object.entries(cmpMeta.$members$);
  2034. const prototype = Cstr.prototype;
  2035. members.map(([memberName, [memberFlags]]) => {
  2036. if ((BUILD.prop || BUILD.state) &&
  2037. (memberFlags & 31 /* MEMBER_FLAGS.Prop */ ||
  2038. ((!BUILD.lazyLoad || flags & 2 /* PROXY_FLAGS.proxyState */) && memberFlags & 32 /* MEMBER_FLAGS.State */))) {
  2039. // proxyComponent - prop
  2040. Object.defineProperty(prototype, memberName, {
  2041. get() {
  2042. // proxyComponent, get value
  2043. return getValue(this, memberName);
  2044. },
  2045. set(newValue) {
  2046. // only during dev time
  2047. if (BUILD.isDev) {
  2048. const ref = getHostRef(this);
  2049. if (
  2050. // we are proxying the instance (not element)
  2051. (flags & 1 /* PROXY_FLAGS.isElementConstructor */) === 0 &&
  2052. // the element is not constructing
  2053. (ref.$flags$ & 8 /* HOST_FLAGS.isConstructingInstance */) === 0 &&
  2054. // the member is a prop
  2055. (memberFlags & 31 /* MEMBER_FLAGS.Prop */) !== 0 &&
  2056. // the member is not mutable
  2057. (memberFlags & 1024 /* MEMBER_FLAGS.Mutable */) === 0) {
  2058. consoleDevWarn(`@Prop() "${memberName}" on <${cmpMeta.$tagName$}> is immutable but was modified from within the component.\nMore information: https://stenciljs.com/docs/properties#prop-mutability`);
  2059. }
  2060. }
  2061. // proxyComponent, set value
  2062. setValue(this, memberName, newValue, cmpMeta);
  2063. },
  2064. configurable: true,
  2065. enumerable: true,
  2066. });
  2067. }
  2068. else if (BUILD.lazyLoad &&
  2069. BUILD.method &&
  2070. flags & 1 /* PROXY_FLAGS.isElementConstructor */ &&
  2071. memberFlags & 64 /* MEMBER_FLAGS.Method */) {
  2072. // proxyComponent - method
  2073. Object.defineProperty(prototype, memberName, {
  2074. value(...args) {
  2075. const ref = getHostRef(this);
  2076. return ref.$onInstancePromise$.then(() => ref.$lazyInstance$[memberName](...args));
  2077. },
  2078. });
  2079. }
  2080. });
  2081. if (BUILD.observeAttribute && (!BUILD.lazyLoad || flags & 1 /* PROXY_FLAGS.isElementConstructor */)) {
  2082. const attrNameToPropName = new Map();
  2083. prototype.attributeChangedCallback = function (attrName, _oldValue, newValue) {
  2084. plt.jmp(() => {
  2085. const propName = attrNameToPropName.get(attrName);
  2086. // In a web component lifecycle the attributeChangedCallback runs prior to connectedCallback
  2087. // in the case where an attribute was set inline.
  2088. // ```html
  2089. // <my-component some-attribute="some-value"></my-component>
  2090. // ```
  2091. //
  2092. // There is an edge case where a developer sets the attribute inline on a custom element and then
  2093. // programmatically changes it before it has been upgraded as shown below:
  2094. //
  2095. // ```html
  2096. // <!-- this component has _not_ been upgraded yet -->
  2097. // <my-component id="test" some-attribute="some-value"></my-component>
  2098. // <script>
  2099. // // grab non-upgraded component
  2100. // el = document.querySelector("#test");
  2101. // el.someAttribute = "another-value";
  2102. // // upgrade component
  2103. // customElements.define('my-component', MyComponent);
  2104. // </script>
  2105. // ```
  2106. // In this case if we do not unshadow here and use the value of the shadowing property, attributeChangedCallback
  2107. // will be called with `newValue = "some-value"` and will set the shadowed property (this.someAttribute = "another-value")
  2108. // to the value that was set inline i.e. "some-value" from above example. When
  2109. // the connectedCallback attempts to unshadow it will use "some-value" as the initial value rather than "another-value"
  2110. //
  2111. // The case where the attribute was NOT set inline but was not set programmatically shall be handled/unshadowed
  2112. // by connectedCallback as this attributeChangedCallback will not fire.
  2113. //
  2114. // https://developers.google.com/web/fundamentals/web-components/best-practices#lazy-properties
  2115. //
  2116. // TODO(STENCIL-16) we should think about whether or not we actually want to be reflecting the attributes to
  2117. // properties here given that this goes against best practices outlined here
  2118. // https://developers.google.com/web/fundamentals/web-components/best-practices#avoid-reentrancy
  2119. if (this.hasOwnProperty(propName)) {
  2120. newValue = this[propName];
  2121. delete this[propName];
  2122. }
  2123. else if (prototype.hasOwnProperty(propName) &&
  2124. typeof this[propName] === 'number' &&
  2125. this[propName] == newValue) {
  2126. // if the propName exists on the prototype of `Cstr`, this update may be a result of Stencil using native
  2127. // APIs to reflect props as attributes. Calls to `setAttribute(someElement, propName)` will result in
  2128. // `propName` to be converted to a `DOMString`, which may not be what we want for other primitive props.
  2129. return;
  2130. }
  2131. this[propName] = newValue === null && typeof this[propName] === 'boolean' ? false : newValue;
  2132. });
  2133. };
  2134. // create an array of attributes to observe
  2135. // and also create a map of html attribute name to js property name
  2136. Cstr.observedAttributes = members
  2137. .filter(([_, m]) => m[0] & 15 /* MEMBER_FLAGS.HasAttribute */) // filter to only keep props that should match attributes
  2138. .map(([propName, m]) => {
  2139. const attrName = m[1] || propName;
  2140. attrNameToPropName.set(attrName, propName);
  2141. if (BUILD.reflect && m[0] & 512 /* MEMBER_FLAGS.ReflectAttr */) {
  2142. cmpMeta.$attrsToReflect$.push([propName, attrName]);
  2143. }
  2144. return attrName;
  2145. });
  2146. }
  2147. }
  2148. return Cstr;
  2149. };
  2150. const initializeComponent = async (elm, hostRef, cmpMeta, hmrVersionId, Cstr) => {
  2151. // initializeComponent
  2152. if ((BUILD.lazyLoad || BUILD.hydrateServerSide || BUILD.style) &&
  2153. (hostRef.$flags$ & 32 /* HOST_FLAGS.hasInitializedComponent */) === 0) {
  2154. if (BUILD.lazyLoad || BUILD.hydrateClientSide) {
  2155. // we haven't initialized this element yet
  2156. hostRef.$flags$ |= 32 /* HOST_FLAGS.hasInitializedComponent */;
  2157. // lazy loaded components
  2158. // request the component's implementation to be
  2159. // wired up with the host element
  2160. Cstr = loadModule(cmpMeta, hostRef, hmrVersionId);
  2161. if (Cstr.then) {
  2162. // Await creates a micro-task avoid if possible
  2163. const endLoad = uniqueTime(`st:load:${cmpMeta.$tagName$}:${hostRef.$modeName$}`, `[Stencil] Load module for <${cmpMeta.$tagName$}>`);
  2164. Cstr = await Cstr;
  2165. endLoad();
  2166. }
  2167. if ((BUILD.isDev || BUILD.isDebug) && !Cstr) {
  2168. throw new Error(`Constructor for "${cmpMeta.$tagName$}#${hostRef.$modeName$}" was not found`);
  2169. }
  2170. if (BUILD.member && !Cstr.isProxied) {
  2171. // we've never proxied this Constructor before
  2172. // let's add the getters/setters to its prototype before
  2173. // the first time we create an instance of the implementation
  2174. if (BUILD.watchCallback) {
  2175. cmpMeta.$watchers$ = Cstr.watchers;
  2176. }
  2177. proxyComponent(Cstr, cmpMeta, 2 /* PROXY_FLAGS.proxyState */);
  2178. Cstr.isProxied = true;
  2179. }
  2180. const endNewInstance = createTime('createInstance', cmpMeta.$tagName$);
  2181. // ok, time to construct the instance
  2182. // but let's keep track of when we start and stop
  2183. // so that the getters/setters don't incorrectly step on data
  2184. if (BUILD.member) {
  2185. hostRef.$flags$ |= 8 /* HOST_FLAGS.isConstructingInstance */;
  2186. }
  2187. // construct the lazy-loaded component implementation
  2188. // passing the hostRef is very important during
  2189. // construction in order to directly wire together the
  2190. // host element and the lazy-loaded instance
  2191. try {
  2192. new Cstr(hostRef);
  2193. }
  2194. catch (e) {
  2195. consoleError(e);
  2196. }
  2197. if (BUILD.member) {
  2198. hostRef.$flags$ &= ~8 /* HOST_FLAGS.isConstructingInstance */;
  2199. }
  2200. if (BUILD.watchCallback) {
  2201. hostRef.$flags$ |= 128 /* HOST_FLAGS.isWatchReady */;
  2202. }
  2203. endNewInstance();
  2204. fireConnectedCallback(hostRef.$lazyInstance$);
  2205. }
  2206. else {
  2207. // sync constructor component
  2208. Cstr = elm.constructor;
  2209. hostRef.$flags$ |= 32 /* HOST_FLAGS.hasInitializedComponent */;
  2210. // wait for the CustomElementRegistry to mark the component as ready before setting `isWatchReady`. Otherwise,
  2211. // watchers may fire prematurely if `customElements.get()`/`customElements.whenDefined()` resolves _before_
  2212. // Stencil has completed instantiating the component.
  2213. customElements.whenDefined(cmpMeta.$tagName$).then(() => (hostRef.$flags$ |= 128 /* HOST_FLAGS.isWatchReady */));
  2214. }
  2215. if (BUILD.style && Cstr.style) {
  2216. // this component has styles but we haven't registered them yet
  2217. let style = Cstr.style;
  2218. if (BUILD.mode && typeof style !== 'string') {
  2219. style = style[(hostRef.$modeName$ = computeMode(elm))];
  2220. if (BUILD.hydrateServerSide && hostRef.$modeName$) {
  2221. elm.setAttribute('s-mode', hostRef.$modeName$);
  2222. }
  2223. }
  2224. const scopeId = getScopeId(cmpMeta, hostRef.$modeName$);
  2225. if (!styles.has(scopeId)) {
  2226. const endRegisterStyles = createTime('registerStyles', cmpMeta.$tagName$);
  2227. if (!BUILD.hydrateServerSide &&
  2228. BUILD.shadowDom &&
  2229. BUILD.shadowDomShim &&
  2230. cmpMeta.$flags$ & 8 /* CMP_FLAGS.needsShadowDomShim */) {
  2231. style = await import('./shadow-css.js').then((m) => m.scopeCss(style, scopeId, false));
  2232. }
  2233. registerStyle(scopeId, style, !!(cmpMeta.$flags$ & 1 /* CMP_FLAGS.shadowDomEncapsulation */));
  2234. endRegisterStyles();
  2235. }
  2236. }
  2237. }
  2238. // we've successfully created a lazy instance
  2239. const ancestorComponent = hostRef.$ancestorComponent$;
  2240. const schedule = () => scheduleUpdate(hostRef, true);
  2241. if (BUILD.asyncLoading && ancestorComponent && ancestorComponent['s-rc']) {
  2242. // this is the initial load and this component it has an ancestor component
  2243. // but the ancestor component has NOT fired its will update lifecycle yet
  2244. // so let's just cool our jets and wait for the ancestor to continue first
  2245. // this will get fired off when the ancestor component
  2246. // finally gets around to rendering its lazy self
  2247. // fire off the initial update
  2248. ancestorComponent['s-rc'].push(schedule);
  2249. }
  2250. else {
  2251. schedule();
  2252. }
  2253. };
  2254. const fireConnectedCallback = (instance) => {
  2255. if (BUILD.lazyLoad && BUILD.connectedCallback) {
  2256. safeCall(instance, 'connectedCallback');
  2257. }
  2258. };
  2259. const connectedCallback = (elm) => {
  2260. if ((plt.$flags$ & 1 /* PLATFORM_FLAGS.isTmpDisconnected */) === 0) {
  2261. const hostRef = getHostRef(elm);
  2262. const cmpMeta = hostRef.$cmpMeta$;
  2263. const endConnected = createTime('connectedCallback', cmpMeta.$tagName$);
  2264. if (BUILD.hostListenerTargetParent) {
  2265. // only run if we have listeners being attached to a parent
  2266. addHostEventListeners(elm, hostRef, cmpMeta.$listeners$, true);
  2267. }
  2268. if (!(hostRef.$flags$ & 1 /* HOST_FLAGS.hasConnected */)) {
  2269. // first time this component has connected
  2270. hostRef.$flags$ |= 1 /* HOST_FLAGS.hasConnected */;
  2271. let hostId;
  2272. if (BUILD.hydrateClientSide) {
  2273. hostId = elm.getAttribute(HYDRATE_ID);
  2274. if (hostId) {
  2275. if (BUILD.shadowDom && supportsShadow && cmpMeta.$flags$ & 1 /* CMP_FLAGS.shadowDomEncapsulation */) {
  2276. const scopeId = BUILD.mode
  2277. ? addStyle(elm.shadowRoot, cmpMeta, elm.getAttribute('s-mode'))
  2278. : addStyle(elm.shadowRoot, cmpMeta);
  2279. elm.classList.remove(scopeId + '-h', scopeId + '-s');
  2280. }
  2281. initializeClientHydrate(elm, cmpMeta.$tagName$, hostId, hostRef);
  2282. }
  2283. }
  2284. if (BUILD.slotRelocation && !hostId) {
  2285. // initUpdate
  2286. // if the slot polyfill is required we'll need to put some nodes
  2287. // in here to act as original content anchors as we move nodes around
  2288. // host element has been connected to the DOM
  2289. if (BUILD.hydrateServerSide ||
  2290. ((BUILD.slot || BUILD.shadowDom) &&
  2291. cmpMeta.$flags$ & (4 /* CMP_FLAGS.hasSlotRelocation */ | 8 /* CMP_FLAGS.needsShadowDomShim */))) {
  2292. setContentReference(elm);
  2293. }
  2294. }
  2295. if (BUILD.asyncLoading) {
  2296. // find the first ancestor component (if there is one) and register
  2297. // this component as one of the actively loading child components for its ancestor
  2298. let ancestorComponent = elm;
  2299. while ((ancestorComponent = ancestorComponent.parentNode || ancestorComponent.host)) {
  2300. // climb up the ancestors looking for the first
  2301. // component that hasn't finished its lifecycle update yet
  2302. if ((BUILD.hydrateClientSide &&
  2303. ancestorComponent.nodeType === 1 /* NODE_TYPE.ElementNode */ &&
  2304. ancestorComponent.hasAttribute('s-id') &&
  2305. ancestorComponent['s-p']) ||
  2306. ancestorComponent['s-p']) {
  2307. // we found this components first ancestor component
  2308. // keep a reference to this component's ancestor component
  2309. attachToAncestor(hostRef, (hostRef.$ancestorComponent$ = ancestorComponent));
  2310. break;
  2311. }
  2312. }
  2313. }
  2314. // Lazy properties
  2315. // https://developers.google.com/web/fundamentals/web-components/best-practices#lazy-properties
  2316. if (BUILD.prop && !BUILD.hydrateServerSide && cmpMeta.$members$) {
  2317. Object.entries(cmpMeta.$members$).map(([memberName, [memberFlags]]) => {
  2318. if (memberFlags & 31 /* MEMBER_FLAGS.Prop */ && elm.hasOwnProperty(memberName)) {
  2319. const value = elm[memberName];
  2320. delete elm[memberName];
  2321. elm[memberName] = value;
  2322. }
  2323. });
  2324. }
  2325. if (BUILD.initializeNextTick) {
  2326. // connectedCallback, taskQueue, initialLoad
  2327. // angular sets attribute AFTER connectCallback
  2328. // https://github.com/angular/angular/issues/18909
  2329. // https://github.com/angular/angular/issues/19940
  2330. nextTick(() => initializeComponent(elm, hostRef, cmpMeta));
  2331. }
  2332. else {
  2333. initializeComponent(elm, hostRef, cmpMeta);
  2334. }
  2335. }
  2336. else {
  2337. // not the first time this has connected
  2338. // reattach any event listeners to the host
  2339. // since they would have been removed when disconnected
  2340. addHostEventListeners(elm, hostRef, cmpMeta.$listeners$, false);
  2341. // fire off connectedCallback() on component instance
  2342. fireConnectedCallback(hostRef.$lazyInstance$);
  2343. }
  2344. endConnected();
  2345. }
  2346. };
  2347. const setContentReference = (elm) => {
  2348. // only required when we're NOT using native shadow dom (slot)
  2349. // or this browser doesn't support native shadow dom
  2350. // and this host element was NOT created with SSR
  2351. // let's pick out the inner content for slot projection
  2352. // create a node to represent where the original
  2353. // content was first placed, which is useful later on
  2354. const contentRefElm = (elm['s-cr'] = doc.createComment(BUILD.isDebug ? `content-ref (host=${elm.localName})` : ''));
  2355. contentRefElm['s-cn'] = true;
  2356. elm.insertBefore(contentRefElm, elm.firstChild);
  2357. };
  2358. const disconnectedCallback = (elm) => {
  2359. if ((plt.$flags$ & 1 /* PLATFORM_FLAGS.isTmpDisconnected */) === 0) {
  2360. const hostRef = getHostRef(elm);
  2361. const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;
  2362. if (BUILD.hostListener) {
  2363. if (hostRef.$rmListeners$) {
  2364. hostRef.$rmListeners$.map((rmListener) => rmListener());
  2365. hostRef.$rmListeners$ = undefined;
  2366. }
  2367. }
  2368. // clear CSS var-shim tracking
  2369. if (BUILD.cssVarShim && plt.$cssShim$) {
  2370. plt.$cssShim$.removeHost(elm);
  2371. }
  2372. if (BUILD.lazyLoad && BUILD.disconnectedCallback) {
  2373. safeCall(instance, 'disconnectedCallback');
  2374. }
  2375. if (BUILD.cmpDidUnload) {
  2376. safeCall(instance, 'componentDidUnload');
  2377. }
  2378. }
  2379. };
  2380. const defineCustomElement = (Cstr, compactMeta) => {
  2381. customElements.define(compactMeta[1], proxyCustomElement(Cstr, compactMeta));
  2382. };
  2383. const proxyCustomElement = (Cstr, compactMeta) => {
  2384. const cmpMeta = {
  2385. $flags$: compactMeta[0],
  2386. $tagName$: compactMeta[1],
  2387. };
  2388. if (BUILD.member) {
  2389. cmpMeta.$members$ = compactMeta[2];
  2390. }
  2391. if (BUILD.hostListener) {
  2392. cmpMeta.$listeners$ = compactMeta[3];
  2393. }
  2394. if (BUILD.watchCallback) {
  2395. cmpMeta.$watchers$ = Cstr.$watchers$;
  2396. }
  2397. if (BUILD.reflect) {
  2398. cmpMeta.$attrsToReflect$ = [];
  2399. }
  2400. if (BUILD.shadowDom && !supportsShadow && cmpMeta.$flags$ & 1 /* CMP_FLAGS.shadowDomEncapsulation */) {
  2401. cmpMeta.$flags$ |= 8 /* CMP_FLAGS.needsShadowDomShim */;
  2402. }
  2403. const originalConnectedCallback = Cstr.prototype.connectedCallback;
  2404. const originalDisconnectedCallback = Cstr.prototype.disconnectedCallback;
  2405. Object.assign(Cstr.prototype, {
  2406. __registerHost() {
  2407. registerHost(this, cmpMeta);
  2408. },
  2409. connectedCallback() {
  2410. connectedCallback(this);
  2411. if (BUILD.connectedCallback && originalConnectedCallback) {
  2412. originalConnectedCallback.call(this);
  2413. }
  2414. },
  2415. disconnectedCallback() {
  2416. disconnectedCallback(this);
  2417. if (BUILD.disconnectedCallback && originalDisconnectedCallback) {
  2418. originalDisconnectedCallback.call(this);
  2419. }
  2420. },
  2421. __attachShadow() {
  2422. if (supportsShadow) {
  2423. if (BUILD.shadowDelegatesFocus) {
  2424. this.attachShadow({
  2425. mode: 'open',
  2426. delegatesFocus: !!(cmpMeta.$flags$ & 16 /* CMP_FLAGS.shadowDelegatesFocus */),
  2427. });
  2428. }
  2429. else {
  2430. this.attachShadow({ mode: 'open' });
  2431. }
  2432. }
  2433. else {
  2434. this.shadowRoot = this;
  2435. }
  2436. },
  2437. });
  2438. Cstr.is = cmpMeta.$tagName$;
  2439. return proxyComponent(Cstr, cmpMeta, 1 /* PROXY_FLAGS.isElementConstructor */ | 2 /* PROXY_FLAGS.proxyState */);
  2440. };
  2441. const forceModeUpdate = (elm) => {
  2442. if (BUILD.style && BUILD.mode && !BUILD.lazyLoad) {
  2443. const mode = computeMode(elm);
  2444. const hostRef = getHostRef(elm);
  2445. if (hostRef.$modeName$ !== mode) {
  2446. const cmpMeta = hostRef.$cmpMeta$;
  2447. const oldScopeId = elm['s-sc'];
  2448. const scopeId = getScopeId(cmpMeta, mode);
  2449. const style = elm.constructor.style[mode];
  2450. const flags = cmpMeta.$flags$;
  2451. if (style) {
  2452. if (!styles.has(scopeId)) {
  2453. registerStyle(scopeId, style, !!(flags & 1 /* CMP_FLAGS.shadowDomEncapsulation */));
  2454. }
  2455. hostRef.$modeName$ = mode;
  2456. elm.classList.remove(oldScopeId + '-h', oldScopeId + '-s');
  2457. attachStyles(hostRef);
  2458. forceUpdate(elm);
  2459. }
  2460. }
  2461. }
  2462. };
  2463. const patchCloneNode = (HostElementPrototype) => {
  2464. const orgCloneNode = HostElementPrototype.cloneNode;
  2465. HostElementPrototype.cloneNode = function (deep) {
  2466. const srcNode = this;
  2467. const isShadowDom = BUILD.shadowDom ? srcNode.shadowRoot && supportsShadow : false;
  2468. const clonedNode = orgCloneNode.call(srcNode, isShadowDom ? deep : false);
  2469. if (BUILD.slot && !isShadowDom && deep) {
  2470. let i = 0;
  2471. let slotted, nonStencilNode;
  2472. const stencilPrivates = [
  2473. 's-id',
  2474. 's-cr',
  2475. 's-lr',
  2476. 's-rc',
  2477. 's-sc',
  2478. 's-p',
  2479. 's-cn',
  2480. 's-sr',
  2481. 's-sn',
  2482. 's-hn',
  2483. 's-ol',
  2484. 's-nr',
  2485. 's-si',
  2486. ];
  2487. for (; i < srcNode.childNodes.length; i++) {
  2488. slotted = srcNode.childNodes[i]['s-nr'];
  2489. nonStencilNode = stencilPrivates.every((privateField) => !srcNode.childNodes[i][privateField]);
  2490. if (slotted) {
  2491. if (BUILD.appendChildSlotFix && clonedNode.__appendChild) {
  2492. clonedNode.__appendChild(slotted.cloneNode(true));
  2493. }
  2494. else {
  2495. clonedNode.appendChild(slotted.cloneNode(true));
  2496. }
  2497. }
  2498. if (nonStencilNode) {
  2499. clonedNode.appendChild(srcNode.childNodes[i].cloneNode(true));
  2500. }
  2501. }
  2502. }
  2503. return clonedNode;
  2504. };
  2505. };
  2506. const patchSlotAppendChild = (HostElementPrototype) => {
  2507. HostElementPrototype.__appendChild = HostElementPrototype.appendChild;
  2508. HostElementPrototype.appendChild = function (newChild) {
  2509. const slotName = (newChild['s-sn'] = getSlotName(newChild));
  2510. const slotNode = getHostSlotNode(this.childNodes, slotName);
  2511. if (slotNode) {
  2512. const slotChildNodes = getHostSlotChildNodes(slotNode, slotName);
  2513. const appendAfter = slotChildNodes[slotChildNodes.length - 1];
  2514. return appendAfter.parentNode.insertBefore(newChild, appendAfter.nextSibling);
  2515. }
  2516. return this.__appendChild(newChild);
  2517. };
  2518. };
  2519. /**
  2520. * Patches the text content of an unnamed slotted node inside a scoped component
  2521. * @param hostElementPrototype the `Element` to be patched
  2522. * @param cmpMeta component runtime metadata used to determine if the component should be patched or not
  2523. */
  2524. const patchTextContent = (hostElementPrototype, cmpMeta) => {
  2525. if (BUILD.scoped && cmpMeta.$flags$ & 2 /* CMP_FLAGS.scopedCssEncapsulation */) {
  2526. const descriptor = Object.getOwnPropertyDescriptor(Node.prototype, 'textContent');
  2527. Object.defineProperty(hostElementPrototype, '__textContent', descriptor);
  2528. Object.defineProperty(hostElementPrototype, 'textContent', {
  2529. get() {
  2530. var _a;
  2531. // get the 'default slot', which would be the first slot in a shadow tree (if we were using one), whose name is
  2532. // the empty string
  2533. const slotNode = getHostSlotNode(this.childNodes, '');
  2534. // when a slot node is found, the textContent _may_ be found in the next sibling (text) node, depending on how
  2535. // nodes were reordered during the vdom render. first try to get the text content from the sibling.
  2536. if (((_a = slotNode === null || slotNode === void 0 ? void 0 : slotNode.nextSibling) === null || _a === void 0 ? void 0 : _a.nodeType) === 3 /* NODE_TYPES.TEXT_NODE */) {
  2537. return slotNode.nextSibling.textContent;
  2538. }
  2539. else if (slotNode) {
  2540. return slotNode.textContent;
  2541. }
  2542. else {
  2543. // fallback to the original implementation
  2544. return this.__textContent;
  2545. }
  2546. },
  2547. set(value) {
  2548. var _a;
  2549. // get the 'default slot', which would be the first slot in a shadow tree (if we were using one), whose name is
  2550. // the empty string
  2551. const slotNode = getHostSlotNode(this.childNodes, '');
  2552. // when a slot node is found, the textContent _may_ need to be placed in the next sibling (text) node,
  2553. // depending on how nodes were reordered during the vdom render. first try to set the text content on the
  2554. // sibling.
  2555. if (((_a = slotNode === null || slotNode === void 0 ? void 0 : slotNode.nextSibling) === null || _a === void 0 ? void 0 : _a.nodeType) === 3 /* NODE_TYPES.TEXT_NODE */) {
  2556. slotNode.nextSibling.textContent = value;
  2557. }
  2558. else if (slotNode) {
  2559. slotNode.textContent = value;
  2560. }
  2561. else {
  2562. // we couldn't find a slot, but that doesn't mean that there isn't one. if this check ran before the DOM
  2563. // loaded, we could have missed it. check for a content reference element on the scoped component and insert
  2564. // it there
  2565. this.__textContent = value;
  2566. const contentRefElm = this['s-cr'];
  2567. if (contentRefElm) {
  2568. this.insertBefore(contentRefElm, this.firstChild);
  2569. }
  2570. }
  2571. },
  2572. });
  2573. }
  2574. };
  2575. const patchChildSlotNodes = (elm, cmpMeta) => {
  2576. class FakeNodeList extends Array {
  2577. item(n) {
  2578. return this[n];
  2579. }
  2580. }
  2581. if (cmpMeta.$flags$ & 8 /* CMP_FLAGS.needsShadowDomShim */) {
  2582. const childNodesFn = elm.__lookupGetter__('childNodes');
  2583. Object.defineProperty(elm, 'children', {
  2584. get() {
  2585. return this.childNodes.map((n) => n.nodeType === 1);
  2586. },
  2587. });
  2588. Object.defineProperty(elm, 'childElementCount', {
  2589. get() {
  2590. return elm.children.length;
  2591. },
  2592. });
  2593. Object.defineProperty(elm, 'childNodes', {
  2594. get() {
  2595. const childNodes = childNodesFn.call(this);
  2596. if ((plt.$flags$ & 1 /* PLATFORM_FLAGS.isTmpDisconnected */) === 0 &&
  2597. getHostRef(this).$flags$ & 2 /* HOST_FLAGS.hasRendered */) {
  2598. const result = new FakeNodeList();
  2599. for (let i = 0; i < childNodes.length; i++) {
  2600. const slot = childNodes[i]['s-nr'];
  2601. if (slot) {
  2602. result.push(slot);
  2603. }
  2604. }
  2605. return result;
  2606. }
  2607. return FakeNodeList.from(childNodes);
  2608. },
  2609. });
  2610. }
  2611. };
  2612. const getSlotName = (node) => node['s-sn'] || (node.nodeType === 1 && node.getAttribute('slot')) || '';
  2613. /**
  2614. * Recursively searches a series of child nodes for a slot with the provided name.
  2615. * @param childNodes the nodes to search for a slot with a specific name.
  2616. * @param slotName the name of the slot to match on.
  2617. * @returns a reference to the slot node that matches the provided name, `null` otherwise
  2618. */
  2619. const getHostSlotNode = (childNodes, slotName) => {
  2620. let i = 0;
  2621. let childNode;
  2622. for (; i < childNodes.length; i++) {
  2623. childNode = childNodes[i];
  2624. if (childNode['s-sr'] && childNode['s-sn'] === slotName) {
  2625. return childNode;
  2626. }
  2627. childNode = getHostSlotNode(childNode.childNodes, slotName);
  2628. if (childNode) {
  2629. return childNode;
  2630. }
  2631. }
  2632. return null;
  2633. };
  2634. const getHostSlotChildNodes = (n, slotName) => {
  2635. const childNodes = [n];
  2636. while ((n = n.nextSibling) && n['s-sn'] === slotName) {
  2637. childNodes.push(n);
  2638. }
  2639. return childNodes;
  2640. };
  2641. const hmrStart = (elm, cmpMeta, hmrVersionId) => {
  2642. // ¯\_(ツ)_/¯
  2643. const hostRef = getHostRef(elm);
  2644. // reset state flags to only have been connected
  2645. hostRef.$flags$ = 1 /* HOST_FLAGS.hasConnected */;
  2646. // TODO
  2647. // detatch any event listeners that may have been added
  2648. // because we're not passing an exact event name it'll
  2649. // remove all of this element's event, which is good
  2650. // create a callback for when this component finishes hmr
  2651. elm['s-hmr-load'] = () => {
  2652. // finished hmr for this element
  2653. delete elm['s-hmr-load'];
  2654. };
  2655. // re-initialize the component
  2656. initializeComponent(elm, hostRef, cmpMeta, hmrVersionId);
  2657. };
  2658. const bootstrapLazy = (lazyBundles, options = {}) => {
  2659. if (BUILD.profile && performance.mark) {
  2660. performance.mark('st:app:start');
  2661. }
  2662. installDevTools();
  2663. const endBootstrap = createTime('bootstrapLazy');
  2664. const cmpTags = [];
  2665. const exclude = options.exclude || [];
  2666. const customElements = win.customElements;
  2667. const head = doc.head;
  2668. const metaCharset = /*@__PURE__*/ head.querySelector('meta[charset]');
  2669. const visibilityStyle = /*@__PURE__*/ doc.createElement('style');
  2670. const deferredConnectedCallbacks = [];
  2671. const styles = /*@__PURE__*/ doc.querySelectorAll(`[${HYDRATED_STYLE_ID}]`);
  2672. let appLoadFallback;
  2673. let isBootstrapping = true;
  2674. let i = 0;
  2675. Object.assign(plt, options);
  2676. plt.$resourcesUrl$ = new URL(options.resourcesUrl || './', doc.baseURI).href;
  2677. if (BUILD.asyncQueue) {
  2678. if (options.syncQueue) {
  2679. plt.$flags$ |= 4 /* PLATFORM_FLAGS.queueSync */;
  2680. }
  2681. }
  2682. if (BUILD.hydrateClientSide) {
  2683. // If the app is already hydrated there is not point to disable the
  2684. // async queue. This will improve the first input delay
  2685. plt.$flags$ |= 2 /* PLATFORM_FLAGS.appLoaded */;
  2686. }
  2687. if (BUILD.hydrateClientSide && BUILD.shadowDom) {
  2688. for (; i < styles.length; i++) {
  2689. registerStyle(styles[i].getAttribute(HYDRATED_STYLE_ID), convertScopedToShadow(styles[i].innerHTML), true);
  2690. }
  2691. }
  2692. lazyBundles.map((lazyBundle) => {
  2693. lazyBundle[1].map((compactMeta) => {
  2694. const cmpMeta = {
  2695. $flags$: compactMeta[0],
  2696. $tagName$: compactMeta[1],
  2697. $members$: compactMeta[2],
  2698. $listeners$: compactMeta[3],
  2699. };
  2700. if (BUILD.member) {
  2701. cmpMeta.$members$ = compactMeta[2];
  2702. }
  2703. if (BUILD.hostListener) {
  2704. cmpMeta.$listeners$ = compactMeta[3];
  2705. }
  2706. if (BUILD.reflect) {
  2707. cmpMeta.$attrsToReflect$ = [];
  2708. }
  2709. if (BUILD.watchCallback) {
  2710. cmpMeta.$watchers$ = {};
  2711. }
  2712. if (BUILD.shadowDom && !supportsShadow && cmpMeta.$flags$ & 1 /* CMP_FLAGS.shadowDomEncapsulation */) {
  2713. cmpMeta.$flags$ |= 8 /* CMP_FLAGS.needsShadowDomShim */;
  2714. }
  2715. const tagName = BUILD.transformTagName && options.transformTagName
  2716. ? options.transformTagName(cmpMeta.$tagName$)
  2717. : cmpMeta.$tagName$;
  2718. const HostElement = class extends HTMLElement {
  2719. // StencilLazyHost
  2720. constructor(self) {
  2721. // @ts-ignore
  2722. super(self);
  2723. self = this;
  2724. registerHost(self, cmpMeta);
  2725. if (BUILD.shadowDom && cmpMeta.$flags$ & 1 /* CMP_FLAGS.shadowDomEncapsulation */) {
  2726. // this component is using shadow dom
  2727. // and this browser supports shadow dom
  2728. // add the read-only property "shadowRoot" to the host element
  2729. // adding the shadow root build conditionals to minimize runtime
  2730. if (supportsShadow) {
  2731. if (BUILD.shadowDelegatesFocus) {
  2732. self.attachShadow({
  2733. mode: 'open',
  2734. delegatesFocus: !!(cmpMeta.$flags$ & 16 /* CMP_FLAGS.shadowDelegatesFocus */),
  2735. });
  2736. }
  2737. else {
  2738. self.attachShadow({ mode: 'open' });
  2739. }
  2740. }
  2741. else if (!BUILD.hydrateServerSide && !('shadowRoot' in self)) {
  2742. self.shadowRoot = self;
  2743. }
  2744. }
  2745. if (BUILD.slotChildNodesFix) {
  2746. patchChildSlotNodes(self, cmpMeta);
  2747. }
  2748. }
  2749. connectedCallback() {
  2750. if (appLoadFallback) {
  2751. clearTimeout(appLoadFallback);
  2752. appLoadFallback = null;
  2753. }
  2754. if (isBootstrapping) {
  2755. // connectedCallback will be processed once all components have been registered
  2756. deferredConnectedCallbacks.push(this);
  2757. }
  2758. else {
  2759. plt.jmp(() => connectedCallback(this));
  2760. }
  2761. }
  2762. disconnectedCallback() {
  2763. plt.jmp(() => disconnectedCallback(this));
  2764. }
  2765. componentOnReady() {
  2766. return getHostRef(this).$onReadyPromise$;
  2767. }
  2768. };
  2769. if (BUILD.cloneNodeFix) {
  2770. patchCloneNode(HostElement.prototype);
  2771. }
  2772. if (BUILD.appendChildSlotFix) {
  2773. patchSlotAppendChild(HostElement.prototype);
  2774. }
  2775. if (BUILD.hotModuleReplacement) {
  2776. HostElement.prototype['s-hmr'] = function (hmrVersionId) {
  2777. hmrStart(this, cmpMeta, hmrVersionId);
  2778. };
  2779. }
  2780. if (BUILD.scopedSlotTextContentFix) {
  2781. patchTextContent(HostElement.prototype, cmpMeta);
  2782. }
  2783. cmpMeta.$lazyBundleId$ = lazyBundle[0];
  2784. if (!exclude.includes(tagName) && !customElements.get(tagName)) {
  2785. cmpTags.push(tagName);
  2786. customElements.define(tagName, proxyComponent(HostElement, cmpMeta, 1 /* PROXY_FLAGS.isElementConstructor */));
  2787. }
  2788. });
  2789. });
  2790. if (BUILD.invisiblePrehydration && (BUILD.hydratedClass || BUILD.hydratedAttribute)) {
  2791. visibilityStyle.innerHTML = cmpTags + HYDRATED_CSS;
  2792. visibilityStyle.setAttribute('data-styles', '');
  2793. head.insertBefore(visibilityStyle, metaCharset ? metaCharset.nextSibling : head.firstChild);
  2794. }
  2795. // Process deferred connectedCallbacks now all components have been registered
  2796. isBootstrapping = false;
  2797. if (deferredConnectedCallbacks.length) {
  2798. deferredConnectedCallbacks.map((host) => host.connectedCallback());
  2799. }
  2800. else {
  2801. if (BUILD.profile) {
  2802. plt.jmp(() => (appLoadFallback = setTimeout(appDidLoad, 30, 'timeout')));
  2803. }
  2804. else {
  2805. plt.jmp(() => (appLoadFallback = setTimeout(appDidLoad, 30)));
  2806. }
  2807. }
  2808. // Fallback appLoad event
  2809. endBootstrap();
  2810. };
  2811. const getConnect = (_ref, tagName) => {
  2812. const componentOnReady = () => {
  2813. let elm = doc.querySelector(tagName);
  2814. if (!elm) {
  2815. elm = doc.createElement(tagName);
  2816. doc.body.appendChild(elm);
  2817. }
  2818. return typeof elm.componentOnReady === 'function' ? elm.componentOnReady() : Promise.resolve(elm);
  2819. };
  2820. const create = (...args) => {
  2821. return componentOnReady().then((el) => el.create(...args));
  2822. };
  2823. return {
  2824. create,
  2825. componentOnReady,
  2826. };
  2827. };
  2828. const getContext = (_elm, context) => {
  2829. if (context in Context) {
  2830. return Context[context];
  2831. }
  2832. else if (context === 'window') {
  2833. return win;
  2834. }
  2835. else if (context === 'document') {
  2836. return doc;
  2837. }
  2838. else if (context === 'isServer' || context === 'isPrerender') {
  2839. return BUILD.hydrateServerSide ? true : false;
  2840. }
  2841. else if (context === 'isClient') {
  2842. return BUILD.hydrateServerSide ? false : true;
  2843. }
  2844. else if (context === 'resourcesUrl' || context === 'publicPath') {
  2845. return getAssetPath('.');
  2846. }
  2847. else if (context === 'queue') {
  2848. return {
  2849. write: writeTask,
  2850. read: readTask,
  2851. tick: {
  2852. then(cb) {
  2853. return nextTick(cb);
  2854. },
  2855. },
  2856. };
  2857. }
  2858. return undefined;
  2859. };
  2860. const Fragment = (_, children) => children;
  2861. const addHostEventListeners = (elm, hostRef, listeners, attachParentListeners) => {
  2862. if (BUILD.hostListener && listeners) {
  2863. // this is called immediately within the element's constructor
  2864. // initialize our event listeners on the host element
  2865. // we do this now so that we can listen to events that may
  2866. // have fired even before the instance is ready
  2867. if (BUILD.hostListenerTargetParent) {
  2868. // this component may have event listeners that should be attached to the parent
  2869. if (attachParentListeners) {
  2870. // this is being ran from within the connectedCallback
  2871. // which is important so that we know the host element actually has a parent element
  2872. // filter out the listeners to only have the ones that ARE being attached to the parent
  2873. listeners = listeners.filter(([flags]) => flags & 32 /* LISTENER_FLAGS.TargetParent */);
  2874. }
  2875. else {
  2876. // this is being ran from within the component constructor
  2877. // everything BUT the parent element listeners should be attached at this time
  2878. // filter out the listeners that are NOT being attached to the parent
  2879. listeners = listeners.filter(([flags]) => !(flags & 32 /* LISTENER_FLAGS.TargetParent */));
  2880. }
  2881. }
  2882. listeners.map(([flags, name, method]) => {
  2883. const target = BUILD.hostListenerTarget ? getHostListenerTarget(elm, flags) : elm;
  2884. const handler = hostListenerProxy(hostRef, method);
  2885. const opts = hostListenerOpts(flags);
  2886. plt.ael(target, name, handler, opts);
  2887. (hostRef.$rmListeners$ = hostRef.$rmListeners$ || []).push(() => plt.rel(target, name, handler, opts));
  2888. });
  2889. }
  2890. };
  2891. const hostListenerProxy = (hostRef, methodName) => (ev) => {
  2892. try {
  2893. if (BUILD.lazyLoad) {
  2894. if (hostRef.$flags$ & 256 /* HOST_FLAGS.isListenReady */) {
  2895. // instance is ready, let's call it's member method for this event
  2896. hostRef.$lazyInstance$[methodName](ev);
  2897. }
  2898. else {
  2899. (hostRef.$queuedListeners$ = hostRef.$queuedListeners$ || []).push([methodName, ev]);
  2900. }
  2901. }
  2902. else {
  2903. hostRef.$hostElement$[methodName](ev);
  2904. }
  2905. }
  2906. catch (e) {
  2907. consoleError(e);
  2908. }
  2909. };
  2910. const getHostListenerTarget = (elm, flags) => {
  2911. if (BUILD.hostListenerTargetDocument && flags & 4 /* LISTENER_FLAGS.TargetDocument */)
  2912. return doc;
  2913. if (BUILD.hostListenerTargetWindow && flags & 8 /* LISTENER_FLAGS.TargetWindow */)
  2914. return win;
  2915. if (BUILD.hostListenerTargetBody && flags & 16 /* LISTENER_FLAGS.TargetBody */)
  2916. return doc.body;
  2917. if (BUILD.hostListenerTargetParent && flags & 32 /* LISTENER_FLAGS.TargetParent */)
  2918. return elm.parentElement;
  2919. return elm;
  2920. };
  2921. // prettier-ignore
  2922. const hostListenerOpts = (flags) => supportsListenerOptions
  2923. ? ({
  2924. passive: (flags & 1 /* LISTENER_FLAGS.Passive */) !== 0,
  2925. capture: (flags & 2 /* LISTENER_FLAGS.Capture */) !== 0,
  2926. })
  2927. : (flags & 2 /* LISTENER_FLAGS.Capture */) !== 0;
  2928. const setPlatformOptions = (opts) => Object.assign(plt, opts);
  2929. const insertVdomAnnotations = (doc, staticComponents) => {
  2930. if (doc != null) {
  2931. const docData = {
  2932. hostIds: 0,
  2933. rootLevelIds: 0,
  2934. staticComponents: new Set(staticComponents),
  2935. };
  2936. const orgLocationNodes = [];
  2937. parseVNodeAnnotations(doc, doc.body, docData, orgLocationNodes);
  2938. orgLocationNodes.forEach((orgLocationNode) => {
  2939. if (orgLocationNode != null) {
  2940. const nodeRef = orgLocationNode['s-nr'];
  2941. let hostId = nodeRef['s-host-id'];
  2942. let nodeId = nodeRef['s-node-id'];
  2943. let childId = `${hostId}.${nodeId}`;
  2944. if (hostId == null) {
  2945. hostId = 0;
  2946. docData.rootLevelIds++;
  2947. nodeId = docData.rootLevelIds;
  2948. childId = `${hostId}.${nodeId}`;
  2949. if (nodeRef.nodeType === 1 /* NODE_TYPE.ElementNode */) {
  2950. nodeRef.setAttribute(HYDRATE_CHILD_ID, childId);
  2951. }
  2952. else if (nodeRef.nodeType === 3 /* NODE_TYPE.TextNode */) {
  2953. if (hostId === 0) {
  2954. const textContent = nodeRef.nodeValue.trim();
  2955. if (textContent === '') {
  2956. // useless whitespace node at the document root
  2957. orgLocationNode.remove();
  2958. return;
  2959. }
  2960. }
  2961. const commentBeforeTextNode = doc.createComment(childId);
  2962. commentBeforeTextNode.nodeValue = `${TEXT_NODE_ID}.${childId}`;
  2963. nodeRef.parentNode.insertBefore(commentBeforeTextNode, nodeRef);
  2964. }
  2965. }
  2966. let orgLocationNodeId = `${ORG_LOCATION_ID}.${childId}`;
  2967. const orgLocationParentNode = orgLocationNode.parentElement;
  2968. if (orgLocationParentNode) {
  2969. if (orgLocationParentNode['s-en'] === '') {
  2970. // ending with a "." means that the parent element
  2971. // of this node's original location is a SHADOW dom element
  2972. // and this node is apart of the root level light dom
  2973. orgLocationNodeId += `.`;
  2974. }
  2975. else if (orgLocationParentNode['s-en'] === 'c') {
  2976. // ending with a ".c" means that the parent element
  2977. // of this node's original location is a SCOPED element
  2978. // and this node is apart of the root level light dom
  2979. orgLocationNodeId += `.c`;
  2980. }
  2981. }
  2982. orgLocationNode.nodeValue = orgLocationNodeId;
  2983. }
  2984. });
  2985. }
  2986. };
  2987. const parseVNodeAnnotations = (doc, node, docData, orgLocationNodes) => {
  2988. if (node == null) {
  2989. return;
  2990. }
  2991. if (node['s-nr'] != null) {
  2992. orgLocationNodes.push(node);
  2993. }
  2994. if (node.nodeType === 1 /* NODE_TYPE.ElementNode */) {
  2995. node.childNodes.forEach((childNode) => {
  2996. const hostRef = getHostRef(childNode);
  2997. if (hostRef != null && !docData.staticComponents.has(childNode.nodeName.toLowerCase())) {
  2998. const cmpData = {
  2999. nodeIds: 0,
  3000. };
  3001. insertVNodeAnnotations(doc, childNode, hostRef.$vnode$, docData, cmpData);
  3002. }
  3003. parseVNodeAnnotations(doc, childNode, docData, orgLocationNodes);
  3004. });
  3005. }
  3006. };
  3007. const insertVNodeAnnotations = (doc, hostElm, vnode, docData, cmpData) => {
  3008. if (vnode != null) {
  3009. const hostId = ++docData.hostIds;
  3010. hostElm.setAttribute(HYDRATE_ID, hostId);
  3011. if (hostElm['s-cr'] != null) {
  3012. hostElm['s-cr'].nodeValue = `${CONTENT_REF_ID}.${hostId}`;
  3013. }
  3014. if (vnode.$children$ != null) {
  3015. const depth = 0;
  3016. vnode.$children$.forEach((vnodeChild, index) => {
  3017. insertChildVNodeAnnotations(doc, vnodeChild, cmpData, hostId, depth, index);
  3018. });
  3019. }
  3020. if (hostElm && vnode && vnode.$elm$ && !hostElm.hasAttribute('c-id')) {
  3021. const parent = hostElm.parentElement;
  3022. if (parent && parent.childNodes) {
  3023. const parentChildNodes = Array.from(parent.childNodes);
  3024. const comment = parentChildNodes.find((node) => node.nodeType === 8 /* NODE_TYPE.CommentNode */ && node['s-sr']);
  3025. if (comment) {
  3026. const index = parentChildNodes.indexOf(hostElm) - 1;
  3027. vnode.$elm$.setAttribute(HYDRATE_CHILD_ID, `${comment['s-host-id']}.${comment['s-node-id']}.0.${index}`);
  3028. }
  3029. }
  3030. }
  3031. }
  3032. };
  3033. const insertChildVNodeAnnotations = (doc, vnodeChild, cmpData, hostId, depth, index) => {
  3034. const childElm = vnodeChild.$elm$;
  3035. if (childElm == null) {
  3036. return;
  3037. }
  3038. const nodeId = cmpData.nodeIds++;
  3039. const childId = `${hostId}.${nodeId}.${depth}.${index}`;
  3040. childElm['s-host-id'] = hostId;
  3041. childElm['s-node-id'] = nodeId;
  3042. if (childElm.nodeType === 1 /* NODE_TYPE.ElementNode */) {
  3043. childElm.setAttribute(HYDRATE_CHILD_ID, childId);
  3044. }
  3045. else if (childElm.nodeType === 3 /* NODE_TYPE.TextNode */) {
  3046. const parentNode = childElm.parentNode;
  3047. const nodeName = parentNode.nodeName;
  3048. if (nodeName !== 'STYLE' && nodeName !== 'SCRIPT') {
  3049. const textNodeId = `${TEXT_NODE_ID}.${childId}`;
  3050. const commentBeforeTextNode = doc.createComment(textNodeId);
  3051. parentNode.insertBefore(commentBeforeTextNode, childElm);
  3052. }
  3053. }
  3054. else if (childElm.nodeType === 8 /* NODE_TYPE.CommentNode */) {
  3055. if (childElm['s-sr']) {
  3056. const slotName = childElm['s-sn'] || '';
  3057. const slotNodeId = `${SLOT_NODE_ID}.${childId}.${slotName}`;
  3058. childElm.nodeValue = slotNodeId;
  3059. }
  3060. }
  3061. if (vnodeChild.$children$ != null) {
  3062. const childDepth = depth + 1;
  3063. vnodeChild.$children$.forEach((vnode, index) => {
  3064. insertChildVNodeAnnotations(doc, vnode, cmpData, hostId, childDepth, index);
  3065. });
  3066. }
  3067. };
  3068. const hostRefs = /*@__PURE__*/ new WeakMap();
  3069. const getHostRef = (ref) => hostRefs.get(ref);
  3070. const registerInstance = (lazyInstance, hostRef) => hostRefs.set((hostRef.$lazyInstance$ = lazyInstance), hostRef);
  3071. const registerHost = (elm, cmpMeta) => {
  3072. const hostRef = {
  3073. $flags$: 0,
  3074. $hostElement$: elm,
  3075. $cmpMeta$: cmpMeta,
  3076. $instanceValues$: new Map(),
  3077. };
  3078. if (BUILD.isDev) {
  3079. hostRef.$renderCount$ = 0;
  3080. }
  3081. if (BUILD.method && BUILD.lazyLoad) {
  3082. hostRef.$onInstancePromise$ = new Promise((r) => (hostRef.$onInstanceResolve$ = r));
  3083. }
  3084. if (BUILD.asyncLoading) {
  3085. hostRef.$onReadyPromise$ = new Promise((r) => (hostRef.$onReadyResolve$ = r));
  3086. elm['s-p'] = [];
  3087. elm['s-rc'] = [];
  3088. }
  3089. addHostEventListeners(elm, hostRef, cmpMeta.$listeners$, false);
  3090. return hostRefs.set(elm, hostRef);
  3091. };
  3092. const isMemberInElement = (elm, memberName) => memberName in elm;
  3093. const consoleError = (e, el) => (customError || console.error)(e, el);
  3094. const STENCIL_DEV_MODE = BUILD.isTesting
  3095. ? ['STENCIL:'] // E2E testing
  3096. : [
  3097. '%cstencil',
  3098. 'color: white;background:#4c47ff;font-weight: bold; font-size:10px; padding:2px 6px; border-radius: 5px',
  3099. ];
  3100. const consoleDevError = (...m) => console.error(...STENCIL_DEV_MODE, ...m);
  3101. const consoleDevWarn = (...m) => console.warn(...STENCIL_DEV_MODE, ...m);
  3102. const consoleDevInfo = (...m) => console.info(...STENCIL_DEV_MODE, ...m);
  3103. const setErrorHandler = (handler) => (customError = handler);
  3104. const cmpModules = /*@__PURE__*/ new Map();
  3105. const loadModule = (cmpMeta, hostRef, hmrVersionId) => {
  3106. // loadModuleImport
  3107. const exportName = cmpMeta.$tagName$.replace(/-/g, '_');
  3108. const bundleId = cmpMeta.$lazyBundleId$;
  3109. if (BUILD.isDev && typeof bundleId !== 'string') {
  3110. consoleDevError(`Trying to lazily load component <${cmpMeta.$tagName$}> with style mode "${hostRef.$modeName$}", but it does not exist.`);
  3111. return undefined;
  3112. }
  3113. const module = !BUILD.hotModuleReplacement ? cmpModules.get(bundleId) : false;
  3114. if (module) {
  3115. return module[exportName];
  3116. }
  3117. /*!__STENCIL_STATIC_IMPORT_SWITCH__*/
  3118. return import(
  3119. /* @vite-ignore */
  3120. /* webpackInclude: /\.entry\.js$/ */
  3121. /* webpackExclude: /\.system\.entry\.js$/ */
  3122. /* webpackMode: "lazy" */
  3123. `./${bundleId}.entry.js${BUILD.hotModuleReplacement && hmrVersionId ? '?s-hmr=' + hmrVersionId : ''}`).then((importedModule) => {
  3124. if (!BUILD.hotModuleReplacement) {
  3125. cmpModules.set(bundleId, importedModule);
  3126. }
  3127. return importedModule[exportName];
  3128. }, consoleError);
  3129. };
  3130. const styles = /*@__PURE__*/ new Map();
  3131. const modeResolutionChain = [];
  3132. const win = typeof window !== 'undefined' ? window : {};
  3133. const CSS = BUILD.cssVarShim ? win.CSS : null;
  3134. const doc = win.document || { head: {} };
  3135. const H = (win.HTMLElement || class {
  3136. });
  3137. const plt = {
  3138. $flags$: 0,
  3139. $resourcesUrl$: '',
  3140. jmp: (h) => h(),
  3141. raf: (h) => requestAnimationFrame(h),
  3142. ael: (el, eventName, listener, opts) => el.addEventListener(eventName, listener, opts),
  3143. rel: (el, eventName, listener, opts) => el.removeEventListener(eventName, listener, opts),
  3144. ce: (eventName, opts) => new CustomEvent(eventName, opts),
  3145. };
  3146. const setPlatformHelpers = (helpers) => {
  3147. Object.assign(plt, helpers);
  3148. };
  3149. const supportsShadow = BUILD.shadowDomShim && BUILD.shadowDom
  3150. ? /*@__PURE__*/ (() => (doc.head.attachShadow + '').indexOf('[native') > -1)()
  3151. : true;
  3152. const supportsListenerOptions = /*@__PURE__*/ (() => {
  3153. let supportsListenerOptions = false;
  3154. try {
  3155. doc.addEventListener('e', null, Object.defineProperty({}, 'passive', {
  3156. get() {
  3157. supportsListenerOptions = true;
  3158. },
  3159. }));
  3160. }
  3161. catch (e) { }
  3162. return supportsListenerOptions;
  3163. })();
  3164. const promiseResolve = (v) => Promise.resolve(v);
  3165. const supportsConstructableStylesheets = BUILD.constructableCSS
  3166. ? /*@__PURE__*/ (() => {
  3167. try {
  3168. new CSSStyleSheet();
  3169. return typeof new CSSStyleSheet().replaceSync === 'function';
  3170. }
  3171. catch (e) { }
  3172. return false;
  3173. })()
  3174. : false;
  3175. const queueDomReads = [];
  3176. const queueDomWrites = [];
  3177. const queueDomWritesLow = [];
  3178. const queueTask = (queue, write) => (cb) => {
  3179. queue.push(cb);
  3180. if (!queuePending) {
  3181. queuePending = true;
  3182. if (write && plt.$flags$ & 4 /* PLATFORM_FLAGS.queueSync */) {
  3183. nextTick(flush);
  3184. }
  3185. else {
  3186. plt.raf(flush);
  3187. }
  3188. }
  3189. };
  3190. const consume = (queue) => {
  3191. for (let i = 0; i < queue.length; i++) {
  3192. try {
  3193. queue[i](performance.now());
  3194. }
  3195. catch (e) {
  3196. consoleError(e);
  3197. }
  3198. }
  3199. queue.length = 0;
  3200. };
  3201. const consumeTimeout = (queue, timeout) => {
  3202. let i = 0;
  3203. let ts = 0;
  3204. while (i < queue.length && (ts = performance.now()) < timeout) {
  3205. try {
  3206. queue[i++](ts);
  3207. }
  3208. catch (e) {
  3209. consoleError(e);
  3210. }
  3211. }
  3212. if (i === queue.length) {
  3213. queue.length = 0;
  3214. }
  3215. else if (i !== 0) {
  3216. queue.splice(0, i);
  3217. }
  3218. };
  3219. const flush = () => {
  3220. if (BUILD.asyncQueue) {
  3221. queueCongestion++;
  3222. }
  3223. // always force a bunch of medium callbacks to run, but still have
  3224. // a throttle on how many can run in a certain time
  3225. // DOM READS!!!
  3226. consume(queueDomReads);
  3227. // DOM WRITES!!!
  3228. if (BUILD.asyncQueue) {
  3229. const timeout = (plt.$flags$ & 6 /* PLATFORM_FLAGS.queueMask */) === 2 /* PLATFORM_FLAGS.appLoaded */
  3230. ? performance.now() + 14 * Math.ceil(queueCongestion * (1.0 / 10.0))
  3231. : Infinity;
  3232. consumeTimeout(queueDomWrites, timeout);
  3233. consumeTimeout(queueDomWritesLow, timeout);
  3234. if (queueDomWrites.length > 0) {
  3235. queueDomWritesLow.push(...queueDomWrites);
  3236. queueDomWrites.length = 0;
  3237. }
  3238. if ((queuePending = queueDomReads.length + queueDomWrites.length + queueDomWritesLow.length > 0)) {
  3239. // still more to do yet, but we've run out of time
  3240. // let's let this thing cool off and try again in the next tick
  3241. plt.raf(flush);
  3242. }
  3243. else {
  3244. queueCongestion = 0;
  3245. }
  3246. }
  3247. else {
  3248. consume(queueDomWrites);
  3249. if ((queuePending = queueDomReads.length > 0)) {
  3250. // still more to do yet, but we've run out of time
  3251. // let's let this thing cool off and try again in the next tick
  3252. plt.raf(flush);
  3253. }
  3254. }
  3255. };
  3256. const nextTick = /*@__PURE__*/ (cb) => promiseResolve().then(cb);
  3257. const readTask = /*@__PURE__*/ queueTask(queueDomReads, false);
  3258. const writeTask = /*@__PURE__*/ queueTask(queueDomWrites, true);
  3259. export { BUILD, Env, NAMESPACE } from '@stencil/core/internal/app-data';
  3260. export { Build, CSS, Context, Fragment, H, H as HTMLElement, Host, STENCIL_DEV_MODE, addHostEventListeners, bootstrapLazy, cmpModules, connectedCallback, consoleDevError, consoleDevInfo, consoleDevWarn, consoleError, createEvent, defineCustomElement, disconnectedCallback, doc, forceModeUpdate, forceUpdate, getAssetPath, getConnect, getContext, getElement, getHostRef, getMode, getRenderingRef, getValue, h, insertVdomAnnotations, isMemberInElement, loadModule, modeResolutionChain, nextTick, parsePropertyValue, plt, postUpdateComponent, promiseResolve, proxyComponent, proxyCustomElement, readTask, registerHost, registerInstance, renderVdom, setAssetPath, setErrorHandler, setMode, setPlatformHelpers, setPlatformOptions, setValue, styles, supportsConstructableStylesheets, supportsListenerOptions, supportsShadow, win, writeTask };