aptechka 0.95.9 → 0.96.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/{LocalLinks-yUje81qW.js → LocalLinks-D1YdCbCu.js} +1 -1
- package/lib/{LocalLinks-Ct89SJQ9.cjs → LocalLinks-aJx_34WY.cjs} +1 -1
- package/lib/api-fetcher/index.cjs +1 -1
- package/lib/api-fetcher/index.js +16 -1
- package/lib/css-value-parser/index.cjs +1 -1
- package/lib/css-value-parser/index.js +3 -1
- package/lib/jsx/index.cjs +1 -1
- package/lib/jsx/index.js +2 -2
- package/lib/local-links/index.cjs +1 -1
- package/lib/local-links/index.js +1 -1
- package/lib/morph-CsmERL3V.cjs +1 -0
- package/lib/{morph-xDx5h9G8.js → morph-DwKYrG4g.js} +60 -34
- package/lib/notched/NotchedElement.d.ts +22 -0
- package/lib/notched/index.cjs +3 -3
- package/lib/notched/index.js +31 -14
- package/lib/{render-C3udrJln.cjs → render-DCFa7iWE.cjs} +1 -1
- package/lib/{render-D_MhEAJB.js → render-GXhdK9Uz.js} +1 -1
- package/lib/router/index.cjs +1 -1
- package/lib/router/index.js +2 -2
- package/lib/spa/index.cjs +1 -1
- package/lib/spa/index.js +2 -2
- package/lib/utils/index.cjs +1 -1
- package/lib/utils/index.js +1 -1
- package/package.json +1 -1
- package/lib/morph-Bz2BCWvO.cjs +0 -1
|
@@ -6,7 +6,7 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
|
|
|
6
6
|
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
7
7
|
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value), __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
8
8
|
import { h as historyManager } from "./historyManager-DyjFBozJ.js";
|
|
9
|
-
import { N as NODE_TYPE_ELEMENT } from "./morph-
|
|
9
|
+
import { N as NODE_TYPE_ELEMENT } from "./morph-DwKYrG4g.js";
|
|
10
10
|
import "construct-style-sheets-polyfill";
|
|
11
11
|
import "./index-Z2Lgb7xU.js";
|
|
12
12
|
import { n as normalizeURL, i as isLocalUrl } from "./url-BdWQTlu6.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty;var __typeError=msg=>{throw TypeError(msg)};var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method);const historyManager=require("./historyManager-Car6P2ak.cjs"),morph=require("./morph-
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty;var __typeError=msg=>{throw TypeError(msg)};var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method);const historyManager=require("./historyManager-Car6P2ak.cjs"),morph=require("./morph-CsmERL3V.cjs");require("construct-style-sheets-polyfill");require("./index-BrasTsja.cjs");const url=require("./url-Dzvsir_7.cjs");var _options,_LocalLinks_instances,isElement_fn,processClickEvent_fn,_clickListener;const _LocalLinks=class _LocalLinks{constructor(options){__privateAdd(this,_LocalLinks_instances);__privateAdd(this,_options);__privateAdd(this,_clickListener,__name(event=>{var _a,_b;const result=__privateMethod(this,_LocalLinks_instances,processClickEvent_fn).call(this,event);if(!result)return;const{url:url2,options={}}=result;url2&&((_b=(_a=__privateGet(this,_options)).onClick)==null||_b.call(_a,url2,options))},"#clickListener"));__privateSet(this,_options,options),window.addEventListener("click",__privateGet(this,_clickListener))}destroy(){window.removeEventListener("click",__privateGet(this,_clickListener))}update(){document.querySelectorAll("a").forEach(link=>{const href=link.getAttribute("href");href&&url.normalizeURL(href,{base:__privateGet(this,_options).base,trailingSlash:__privateGet(this,_options).trailingSlash}).pathname===location.pathname?link.classList.add("current"):link.classList.remove("current")})}};_options=new WeakMap,_LocalLinks_instances=new WeakSet,isElement_fn=__name(function(target){return(target==null?void 0:target.nodeType)===morph.NODE_TYPE_ELEMENT},"#isElement"),processClickEvent_fn=__name(function(e){var _a;const target=e.composedPath()[0];if(!__privateMethod(this,_LocalLinks_instances,isElement_fn).call(this,target))return;const anchorElement=target.closest("a");if(!anchorElement||typeof __privateGet(this,_options).includeAnchor=="function"&&!__privateGet(this,_options).includeAnchor(anchorElement,e)||anchorElement.closest("[data-router-ignore]")||(_a=anchorElement.getAttribute("href"))!=null&&_a.startsWith("http"))return;const{href}=anchorElement;if(!url.isLocalUrl(href))return;const options={keepScrollPosition:"keepScrollPosition"in anchorElement.dataset,cache:"cache"in anchorElement.dataset,revalidate:"revalidate"in anchorElement.dataset,scrollValue:anchorElement.dataset.scrollTo},scrollOptions={behavior:anchorElement.dataset.scrollBehavior,center:!!anchorElement.dataset.scrollCenter,duration:anchorElement.dataset.scrollDuration?parseFloat(anchorElement.dataset.scrollDuration):void 0,easing:anchorElement.dataset.scrollEasing,offset:anchorElement.dataset.scrollOffset,startValue:anchorElement.dataset.scrollStartValue?parseFloat(anchorElement.dataset.scrollStartValue):void 0};if(Object.values(scrollOptions).length&&(options.scrollOptions=scrollOptions),e.preventDefault(),anchorElement.hasAttribute("data-back")&&historyManager.historyManager.size>1){history.back();return}return{url:url.normalizeURL(new URL(href),{base:__privateGet(this,_options).base,trailingSlash:__privateGet(this,_options).trailingSlash}),options}},"#processClickEvent"),_clickListener=new WeakMap,__name(_LocalLinks,"LocalLinks");let LocalLinks=_LocalLinks;exports.LocalLinks=LocalLinks;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty,__defProps=Object.defineProperties;var __getOwnPropDescs=Object.getOwnPropertyDescriptors;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __async=(__this,__arguments,generator)=>new Promise((resolve,reject)=>{var fulfilled=value=>{try{step(generator.next(value))}catch(e){reject(e)}},rejected=value=>{try{step(generator.throw(value))}catch(e){reject(e)}},step=x=>x.done?resolve(x.value):Promise.resolve(x.value).then(fulfilled,rejected);step((generator=generator.apply(__this,__arguments)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const cache_index=require("../cache/index.cjs");require("construct-style-sheets-polyfill");require("../index-BrasTsja.cjs");const url=require("../url-Dzvsir_7.cjs"),apiFetcherCache=new cache_index.Cache,pendingRequests=new Map;function apiFetcherClearPendingRequests(){pendingRequests.clear()}__name(apiFetcherClearPendingRequests,"apiFetcherClearPendingRequests");function apiFetcherGetPendingRequestsCount(){return pendingRequests.size}__name(apiFetcherGetPendingRequestsCount,"apiFetcherGetPendingRequestsCount");function apiFetcher(input,options){return __async(this,null,function*(){var _a,_b;const startTime=Date.now(),baseResult={data:null,errors:[],status:"unknown",response:new Response};try{let url$1=input;if(options!=null&&options.params){const params=url.searchParamsObjectToString(options.params);if(params){const separator=url$1.includes("?")?"&":"?";url$1+=`${separator}${params}`}}const
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty,__defProps=Object.defineProperties;var __getOwnPropDescs=Object.getOwnPropertyDescriptors;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __async=(__this,__arguments,generator)=>new Promise((resolve,reject)=>{var fulfilled=value=>{try{step(generator.next(value))}catch(e){reject(e)}},rejected=value=>{try{step(generator.throw(value))}catch(e){reject(e)}},step=x=>x.done?resolve(x.value):Promise.resolve(x.value).then(fulfilled,rejected);step((generator=generator.apply(__this,__arguments)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const cache_index=require("../cache/index.cjs");require("construct-style-sheets-polyfill");require("../index-BrasTsja.cjs");const url=require("../url-Dzvsir_7.cjs"),apiFetcherCache=new cache_index.Cache,pendingRequests=new Map;function apiFetcherClearPendingRequests(){pendingRequests.clear()}__name(apiFetcherClearPendingRequests,"apiFetcherClearPendingRequests");function apiFetcherGetPendingRequestsCount(){return pendingRequests.size}__name(apiFetcherGetPendingRequestsCount,"apiFetcherGetPendingRequestsCount");function normalizeHeaders(headers){return headers?headers instanceof Headers?Object.fromEntries(Array.from(headers.entries()).sort(([a],[b])=>a.localeCompare(b))):Array.isArray(headers)?Object.fromEntries([...headers].sort(([a],[b])=>a.localeCompare(b))):Object.fromEntries(Object.entries(headers).sort(([a],[b])=>a.localeCompare(b))):{}}__name(normalizeHeaders,"normalizeHeaders");function buildCacheKey(baseKey,init){const method=((init==null?void 0:init.method)||"GET").toUpperCase(),headers=normalizeHeaders(init==null?void 0:init.headers);return`${baseKey}::${method}::${JSON.stringify(headers)}`}__name(buildCacheKey,"buildCacheKey");function apiFetcher(input,options){return __async(this,null,function*(){var _a,_b;const startTime=Date.now(),baseResult={data:null,errors:[],status:"unknown",response:new Response};try{let url$1=input;if(options!=null&&options.params){const params=url.searchParamsObjectToString(options.params);if(params){const separator=url$1.includes("?")?"&":"?";url$1+=`${separator}${params}`}}const baseCacheKey=(_a=options==null?void 0:options.cacheKey)!=null?_a:url$1,cacheKey=buildCacheKey(baseCacheKey,options==null?void 0:options.init),cacheTTL=(_b=options==null?void 0:options.cacheTTLMinutes)!=null?_b:0,cacheAllowed=cacheTTL>0;if((options!=null&&options.forceClearCache||globalThis.forceClearCache)&&(apiFetcherCache.delete(cacheKey),pendingRequests.delete(cacheKey)),cacheAllowed){const cached=apiFetcherCache.get(cacheKey);if(cached)return __spreadProps(__spreadValues({},baseResult),{errors:cached.error?[cached.error]:cached.errors?cached.errors:baseResult.errors,data:cached.data||cached,cached:!0,status:"success",time:Date.now()-startTime})}const pendingRequest=pendingRequests.get(cacheKey);if(pendingRequest)return pendingRequest;const requestPromise=__async(this,null,function*(){try{const response=yield fetch(url$1,options==null?void 0:options.init);if(!response.ok){const errorText=yield response.text();return __spreadProps(__spreadValues({},baseResult),{errors:[errorText],status:"error",time:Date.now()-startTime,response})}const contentType=response.headers.get("content-type");if(!(contentType!=null&&contentType.includes("application/json")))return __spreadProps(__spreadValues({},baseResult),{errors:["Endpoint did not return JSON"],status:"error",time:Date.now()-startTime,response});const jsonData=yield response.json();return cacheAllowed&&apiFetcherCache.set(cacheKey,jsonData,cacheTTL),__spreadProps(__spreadValues({},baseResult),{errors:jsonData.error?[jsonData.error]:jsonData.errors?jsonData.errors:baseResult.errors,data:jsonData.data||jsonData,status:"success",time:Date.now()-startTime,response})}finally{pendingRequests.delete(cacheKey)}});return pendingRequests.set(cacheKey,requestPromise),yield requestPromise}catch(error){const errorMessage=error instanceof Error?error.message:String(error);return __spreadProps(__spreadValues({},baseResult),{errors:[errorMessage],status:"error",time:Date.now()-startTime})}})}__name(apiFetcher,"apiFetcher");exports.apiFetcher=apiFetcher;exports.apiFetcherCache=apiFetcherCache;exports.apiFetcherClearPendingRequests=apiFetcherClearPendingRequests;exports.apiFetcherGetPendingRequestsCount=apiFetcherGetPendingRequestsCount;
|
package/lib/api-fetcher/index.js
CHANGED
|
@@ -39,6 +39,21 @@ function apiFetcherGetPendingRequestsCount() {
|
|
|
39
39
|
return pendingRequests.size;
|
|
40
40
|
}
|
|
41
41
|
__name(apiFetcherGetPendingRequestsCount, "apiFetcherGetPendingRequestsCount");
|
|
42
|
+
function normalizeHeaders(headers) {
|
|
43
|
+
return headers ? headers instanceof Headers ? Object.fromEntries(
|
|
44
|
+
Array.from(headers.entries()).sort(([a], [b]) => a.localeCompare(b))
|
|
45
|
+
) : Array.isArray(headers) ? Object.fromEntries(
|
|
46
|
+
[...headers].sort(([a], [b]) => a.localeCompare(b))
|
|
47
|
+
) : Object.fromEntries(
|
|
48
|
+
Object.entries(headers).sort(([a], [b]) => a.localeCompare(b))
|
|
49
|
+
) : {};
|
|
50
|
+
}
|
|
51
|
+
__name(normalizeHeaders, "normalizeHeaders");
|
|
52
|
+
function buildCacheKey(baseKey, init) {
|
|
53
|
+
const method = ((init == null ? void 0 : init.method) || "GET").toUpperCase(), headers = normalizeHeaders(init == null ? void 0 : init.headers);
|
|
54
|
+
return `${baseKey}::${method}::${JSON.stringify(headers)}`;
|
|
55
|
+
}
|
|
56
|
+
__name(buildCacheKey, "buildCacheKey");
|
|
42
57
|
function apiFetcher(input, options) {
|
|
43
58
|
return __async(this, null, function* () {
|
|
44
59
|
var _a, _b;
|
|
@@ -57,7 +72,7 @@ function apiFetcher(input, options) {
|
|
|
57
72
|
url += `${separator}${params}`;
|
|
58
73
|
}
|
|
59
74
|
}
|
|
60
|
-
const
|
|
75
|
+
const baseCacheKey = (_a = options == null ? void 0 : options.cacheKey) != null ? _a : url, cacheKey = buildCacheKey(baseCacheKey, options == null ? void 0 : options.init), cacheTTL = (_b = options == null ? void 0 : options.cacheTTLMinutes) != null ? _b : 0, cacheAllowed = cacheTTL > 0;
|
|
61
76
|
if ((options != null && options.forceClearCache || globalThis.forceClearCache) && (apiFetcherCache.delete(cacheKey), pendingRequests.delete(cacheKey)), cacheAllowed) {
|
|
62
77
|
const cached = apiFetcherCache.get(cacheKey);
|
|
63
78
|
if (cached)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const cssUnitParser_index=require("../css-unit-parser/index.cjs"),Viewport=require("../Viewport-BdFs1Zsn.cjs"),_CSSValueParser=class _CSSValueParser{parse(value,element){var _a;const num=parseFloat(value),isNumber=!isNaN(num),unit=isNumber?(_a=value.match(/[a-z]+$/i))==null?void 0:_a[0]:void 0;return isNumber&&!unit?num:unit?unit==="px"?num:unit==="oh"?((element==null?void 0:element.offsetHeight)||0)*(num/100):unit==="ow"?((element==null?void 0:element.offsetWidth)||0)*(num/100):unit==="ohmh"?(((element==null?void 0:element.offsetHeight)||0)-Viewport.viewport.height)*(num/100):unit==="owmw"?(((element==null?void 0:element.offsetWidth)||0)-Viewport.viewport.width)*(num/100):unit&&_CSSValueParser.CSS_UNITS.has(unit)?cssUnitParser_index.cssUnitParser.parse(value,element):value:value.includes("calc")?value.includes("raw!")?value.replace("raw!",""):cssUnitParser_index.cssUnitParser.parse(value,element):value==="true"?!0:value==="false"?!1:value}};__name(_CSSValueParser,"CSSValueParser"),_CSSValueParser.CSS_UNITS=new Set(["px","rem","vw","vh","vmin","vmax","em","cm","mm","Q","in","pc","pt","ex","ch","lh","rlh","vb","vi","svw","svh","lvw","lvh","dvw","dvh"]);let CSSValueParser=_CSSValueParser;const cssValueParser=new CSSValueParser;exports.cssValueParser=cssValueParser;
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const cssUnitParser_index=require("../css-unit-parser/index.cjs"),Viewport=require("../Viewport-BdFs1Zsn.cjs"),_CSSValueParser=class _CSSValueParser{parse(value,element){var _a;const num=parseFloat(value),isNumber=!isNaN(num),unit=isNumber?(_a=value.match(/[a-z]+$/i))==null?void 0:_a[0]:void 0;return isNumber&&!unit?num:unit?unit==="px"?num:unit==="oh"?((element==null?void 0:element.offsetHeight)||0)*(num/100):unit==="ow"?((element==null?void 0:element.offsetWidth)||0)*(num/100):unit==="ohmh"?(((element==null?void 0:element.offsetHeight)||0)-Viewport.viewport.height)*(num/100):unit==="owmw"?(((element==null?void 0:element.offsetWidth)||0)+Viewport.viewport.width)*(num/100):unit==="ohph"?(console.log((((element==null?void 0:element.offsetHeight)||0)+Viewport.viewport.height)*(num/100)),(((element==null?void 0:element.offsetHeight)||0)+Viewport.viewport.height)*(num/100)):unit==="owpw"?(((element==null?void 0:element.offsetWidth)||0)-Viewport.viewport.width)*(num/100):unit&&_CSSValueParser.CSS_UNITS.has(unit)?cssUnitParser_index.cssUnitParser.parse(value,element):value:value.includes("calc")?value.includes("raw!")?value.replace("raw!",""):cssUnitParser_index.cssUnitParser.parse(value,element):value==="true"?!0:value==="false"?!1:value}};__name(_CSSValueParser,"CSSValueParser"),_CSSValueParser.CSS_UNITS=new Set(["px","rem","vw","vh","vmin","vmax","em","cm","mm","Q","in","pc","pt","ex","ch","lh","rlh","vb","vi","svw","svh","lvw","lvh","dvw","dvh"]);let CSSValueParser=_CSSValueParser;const cssValueParser=new CSSValueParser;exports.cssValueParser=cssValueParser;
|
|
@@ -6,7 +6,9 @@ const _CSSValueParser = class _CSSValueParser {
|
|
|
6
6
|
parse(value, element) {
|
|
7
7
|
var _a;
|
|
8
8
|
const num = parseFloat(value), isNumber = !isNaN(num), unit = isNumber ? (_a = value.match(/[a-z]+$/i)) == null ? void 0 : _a[0] : void 0;
|
|
9
|
-
return isNumber && !unit ? num : unit ? unit === "px" ? num : unit === "oh" ? ((element == null ? void 0 : element.offsetHeight) || 0) * (num / 100) : unit === "ow" ? ((element == null ? void 0 : element.offsetWidth) || 0) * (num / 100) : unit === "ohmh" ? (((element == null ? void 0 : element.offsetHeight) || 0) - viewport.height) * (num / 100) : unit === "owmw" ? (((element == null ? void 0 : element.offsetWidth) || 0)
|
|
9
|
+
return isNumber && !unit ? num : unit ? unit === "px" ? num : unit === "oh" ? ((element == null ? void 0 : element.offsetHeight) || 0) * (num / 100) : unit === "ow" ? ((element == null ? void 0 : element.offsetWidth) || 0) * (num / 100) : unit === "ohmh" ? (((element == null ? void 0 : element.offsetHeight) || 0) - viewport.height) * (num / 100) : unit === "owmw" ? (((element == null ? void 0 : element.offsetWidth) || 0) + viewport.width) * (num / 100) : unit === "ohph" ? (console.log(
|
|
10
|
+
(((element == null ? void 0 : element.offsetHeight) || 0) + viewport.height) * (num / 100)
|
|
11
|
+
), (((element == null ? void 0 : element.offsetHeight) || 0) + viewport.height) * (num / 100)) : unit === "owpw" ? (((element == null ? void 0 : element.offsetWidth) || 0) - viewport.width) * (num / 100) : unit && _CSSValueParser.CSS_UNITS.has(unit) ? cssUnitParser.parse(value, element) : value : value.includes("calc") ? value.includes("raw!") ? value.replace("raw!", "") : cssUnitParser.parse(value, element) : value === "true" ? !0 : value === "false" ? !1 : value;
|
|
10
12
|
}
|
|
11
13
|
};
|
|
12
14
|
__name(_CSSValueParser, "CSSValueParser"), _CSSValueParser.CSS_UNITS = /* @__PURE__ */ new Set([
|
package/lib/jsx/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty,__defProps=Object.defineProperties;var __getOwnPropDescs=Object.getOwnPropertyDescriptors;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__name=(target,value)=>__defProp(target,"name",{value,configurable:!0});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const render=require("../render-
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty,__defProps=Object.defineProperties;var __getOwnPropDescs=Object.getOwnPropertyDescriptors;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__name=(target,value)=>__defProp(target,"name",{value,configurable:!0});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const render=require("../render-DCFa7iWE.cjs"),cssProperty_index=require("../css-property/index.cjs"),string=require("../string-Bx5N38JG.cjs");require("construct-style-sheets-polyfill");const intersector_index=require("../index-BrasTsja.cjs"),Store=require("../Store-BP8tuWzQ.cjs"),store_index=require("../store/index.cjs"),DerivedArray=require("../DerivedArray-0qZFAKZ4.cjs"),elementResizer_index=require("../element-resizer/index.cjs"),windowResizer_index=require("../window-resizer/index.cjs");function useRef(){return{value:null}}__name(useRef,"useRef");function useConnect(callback){render.activeComponent.current.addConnectCallback(callback)}__name(useConnect,"useConnect");function useDisconnect(callback){render.activeComponent.current.addDisconnectCallback(callback)}__name(useDisconnect,"useDisconnect");function useCSSProperty(property,defaultValue,options){if(render.activeComponent.current){const cssProperty=new cssProperty_index.CSSProperty(render.activeComponent.current,property,defaultValue,options);return useConnect(()=>(options!=null&&options.callback&&cssProperty.subscribe(options.callback),cssProperty.observe(),()=>{cssProperty.close()})),cssProperty}}__name(useCSSProperty,"useCSSProperty");function useInternals(callback){const internals=render.activeComponent.current.attachInternals();return callback==null||callback(internals),internals}__name(useInternals,"useInternals");function useShadow(init,callback){if(!render.activeComponent.current.shadowRoot){const shadowRoot=render.activeComponent.current.attachShadow(__spreadValues({mode:"open"},init));callback==null||callback(shadowRoot)}return render.activeComponent.current.shadowRoot}__name(useShadow,"useShadow");function createStylesheet(cssText){const styleSheet=new CSSStyleSheet;return styleSheet.replaceSync(cssText),styleSheet}__name(createStylesheet,"createStylesheet");function generateCSS(source){let cssText="";const processObject=__name((obj,selector)=>{selector&&(cssText+=`${selector} {`);for(const[key,value]of Object.entries(obj))typeof value=="object"&&value!==null?processObject(value,key):cssText+=`${string.camelToKebab(key)}: ${value};`;selector&&(cssText+="}")},"processObject");return processObject(source),cssText}__name(generateCSS,"generateCSS");function addStylesToShadowRoot(shadowRoot,cssText){const newStylesheet=createStylesheet(cssText),destroyCallbacks=[];for(const currentStylesheet of shadowRoot.adoptedStyleSheets)Array.from(newStylesheet.cssRules).filter(newRule=>!Array.from(currentStylesheet.cssRules).some(currentRule=>currentRule.cssText===newRule.cssText)).forEach(newRule=>{const index=currentStylesheet.insertRule(newRule.cssText);destroyCallbacks.push(()=>currentStylesheet.deleteRule(index))});return()=>destroyCallbacks.forEach(callback=>callback())}__name(addStylesToShadowRoot,"addStylesToShadowRoot");function addStylesToDocument(cssText){const styleElement=document.createElement("style");return styleElement.textContent=cssText,document.head.appendChild(styleElement),()=>styleElement.remove()}__name(addStylesToDocument,"addStylesToDocument");function useStylesheet(source){const cssText=generateCSS(source);if(render.activeComponent.current.shadowRoot){render.activeComponent.current.shadowRoot.adoptedStyleSheets=[...render.activeComponent.current.shadowRoot.adoptedStyleSheets,createStylesheet(cssText)];return}useConnect(element=>{const rootNode=element.getRootNode();if(rootNode===document){if(!Array.from(document.head.querySelectorAll("style")).find(style=>style.textContent===cssText))return addStylesToDocument(cssText)}else if(rootNode instanceof ShadowRoot)return addStylesToShadowRoot(rootNode,cssText)})}__name(useStylesheet,"useStylesheet");function subscribe(create){const store=create();return render.activeComponent.current&&render.activeComponent.current.addDisconnectCallback(()=>{store.close()}),store}__name(subscribe,"subscribe");function useStore(...parameters){return subscribe(()=>new Store.Store(...parameters))}__name(useStore,"useStore");function useDerivedStore(...parameters){return subscribe(()=>new store_index.Derived(...parameters))}__name(useDerivedStore,"useDerivedStore");function useDerivedArrayStore(...parameters){return subscribe(()=>new DerivedArray.DerivedArray(...parameters))}__name(useDerivedArrayStore,"useDerivedArrayStore");function useDerivedKeyedArrayStore(...parameters){return subscribe(()=>new DerivedArray.DerivedKeyedArray(...parameters))}__name(useDerivedKeyedArrayStore,"useDerivedKeyedArrayStore");function useResourceStore(...parameters){return subscribe(()=>new store_index.Resource(...parameters))}__name(useResourceStore,"useResourceStore");function useComposedStore(...parameters){return subscribe(()=>new store_index.Composed(...parameters))}__name(useComposedStore,"useComposedStore");function useWindowResize(...parameters){render.activeComponent.current?useConnect(()=>windowResizer_index.windowResizer.subscribe(...parameters)):windowResizer_index.windowResizer.subscribe(...parameters)}__name(useWindowResize,"useWindowResize");function useElementResize(callback){useConnect(element=>elementResizer_index.elementResizer.subscribe(element,callback))}__name(useElementResize,"useElementResize");function useTicker(callback,options){if(render.activeComponent.current)useConnect(()=>intersector_index.ticker.subscribe(callback,__spreadProps(__spreadValues({},options),{culling:options!=null&&options.componentCulling?render.activeComponent.current:options==null?void 0:options.culling})));else return intersector_index.ticker.subscribe(callback,options)}__name(useTicker,"useTicker");exports.Fragment=render.Fragment;exports.h=render.h;exports.hydrate=render.hydrate;exports.indexMap=render.indexMap;exports.render=render.render;exports.useCSSProperty=useCSSProperty;exports.useComposedStore=useComposedStore;exports.useConnect=useConnect;exports.useDerivedArrayStore=useDerivedArrayStore;exports.useDerivedKeyedArrayStore=useDerivedKeyedArrayStore;exports.useDerivedStore=useDerivedStore;exports.useDisconnect=useDisconnect;exports.useElementResize=useElementResize;exports.useInternals=useInternals;exports.useRef=useRef;exports.useResourceStore=useResourceStore;exports.useShadow=useShadow;exports.useStore=useStore;exports.useStylesheet=useStylesheet;exports.useTicker=useTicker;exports.useWindowResize=useWindowResize;
|
package/lib/jsx/index.js
CHANGED
|
@@ -10,8 +10,8 @@ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { en
|
|
|
10
10
|
__propIsEnum.call(b2, prop) && __defNormalProp(a, prop, b2[prop]);
|
|
11
11
|
return a;
|
|
12
12
|
}, __spreadProps = (a, b2) => __defProps(a, __getOwnPropDescs(b2)), __name = (target, value) => __defProp(target, "name", { value, configurable: !0 });
|
|
13
|
-
import { a as activeComponent } from "../render-
|
|
14
|
-
import { F, h, b, i, r } from "../render-
|
|
13
|
+
import { a as activeComponent } from "../render-GXhdK9Uz.js";
|
|
14
|
+
import { F, h, b, i, r } from "../render-GXhdK9Uz.js";
|
|
15
15
|
import { CSSProperty } from "../css-property/index.js";
|
|
16
16
|
import { c as camelToKebab } from "../string-Ct-dy_cs.js";
|
|
17
17
|
import "construct-style-sheets-polyfill";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const LocalLinks=require("../LocalLinks-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const LocalLinks=require("../LocalLinks-aJx_34WY.cjs");exports.LocalLinks=LocalLinks.LocalLinks;
|
package/lib/local-links/index.js
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __async=(__this,__arguments,generator)=>new Promise((resolve,reject)=>{var fulfilled=value=>{try{step(generator.next(value))}catch(e){reject(e)}},rejected=value=>{try{step(generator.throw(value))}catch(e){reject(e)}},step=x=>x.done?resolve(x.value):Promise.resolve(x.value).then(fulfilled,rejected);step((generator=generator.apply(__this,__arguments)).next())});const compare=__name(attr=>(from,to)=>from[`node${attr}`]===to[`node${attr}`],"compare"),same={name:compare("Name"),type:compare("Type"),value:compare("Value")};function hasPermanentParent(node){if(!node)return!1;let current=node;for(;current;){if(current.nodeType===1&¤t.hasAttribute("data-preserve"))return!0;current=current.parentNode}return!1}__name(hasPermanentParent,"hasPermanentParent");function scriptAttributesChanged(from,to){if(from.localName!=="script"||to.localName!=="script")return!1;const importantAttrs=["src","type","async","defer","module","nomodule","integrity","crossorigin"];for(const attr of importantAttrs){const fromValue=from.getAttribute(attr),toValue=to.getAttribute(attr);if(fromValue!==toValue)return!0}return from.textContent!==to.textContent}__name(scriptAttributesChanged,"scriptAttributesChanged");function attributes(from,to){if(from.localName==="script"&&to.localName==="script"){const patches2=[];for(const attr of from.attributes)patches2.push({type:5,name:attr.name});for(const attr of to.attributes)patches2.push({type:4,name:attr.name,value:attr.value});return patches2}if(from.attributes.length===0&&to.attributes.length===0)return[];const patches=[],remove=new Map,update=new Map;for(const attr of from.attributes)remove.set(attr.name,attr.value);for(const attr of to.attributes){const fromAttr=remove.get(attr.name);attr.value===fromAttr?remove.delete(attr.name):(typeof fromAttr!="undefined"&&remove.delete(attr.name),update.set(attr.name,attr.value))}for(const attr of remove.keys())patches.push({type:5,name:attr});for(const[attr,value]of update.entries())patches.push({type:4,name:attr,value});return patches}__name(attributes,"attributes");function serialize(el,data=!0){let key=`${el.localName}`;for(const{name,value}of el.attributes)data&&name.startsWith("data-")||(key+=`[${name}=${value}]`);return key+=el.innerHTML,key}__name(serialize,"serialize");function getKey(el){switch(el.tagName){case"BASE":case"TITLE":return el.localName;case"META":{if(el.hasAttribute("name"))return`meta[name="${el.getAttribute("name")}"]`;if(el.hasAttribute("property"))return`meta[name="${el.getAttribute("property")}"]`;break}case"LINK":{if(el.hasAttribute("rel")&&el.hasAttribute("href"))return`link[rel="${el.getAttribute("rel")}"][href="${el.getAttribute("href")}"]`;if(el.hasAttribute("href"))return`link[href="${el.getAttribute("href")}"]`;break}}return serialize(el)}__name(getKey,"getKey");function clone(node){return node.nodeType===1&&node.hasAttribute("data-preserve")||node.nodeType===1&&node.localName==="script",node.cloneNode(!0)}__name(clone,"clone");function uniqueChildren(from,to){if(from.children.length===0&&to.children.length===0)return[];const patches=[],remove=new Map,update=new Map,add=new Map;for(const child of from.children)remove.set(getKey(child),child);for(const child of to.children){const key=getKey(child),fromEl=remove.get(key);fromEl?serialize(child,!1)!==serialize(fromEl,!1)&&update.set(key,clone(child)):add.set(key,clone(child)),remove.delete(key)}for(const node of from.childNodes){if(node.nodeType===1){const key=getKey(node);if(hasPermanentParent(node)){patches.push({type:7});continue}if(remove.has(key)){patches.push({type:1});continue}else if(update.has(key)){const nodeTo=update.get(key);patches.push({type:3,attributes:attributes(node,nodeTo),children:children(node,nodeTo)});continue}}patches.push(void 0)}for(const node of add.values())patches.push({type:0,node:clone(node)});return patches}__name(uniqueChildren,"uniqueChildren");function children(from,to){const patches=[],len=Math.max(from.childNodes.length,to.childNodes.length);for(let i=0;i<len;i++){const a=from.childNodes.item(i),b=to.childNodes.item(i);hasPermanentParent(a)||hasPermanentParent(b)?patches[i]={type:7}:patches[i]=diff(a,b)}return patches}__name(children,"children");function diff(from,to){if(hasPermanentParent(from)||hasPermanentParent(to))return{type:7};if(!from)return{type:0,node:clone(to)};if(!to)return hasPermanentParent(from)?{type:7}:{type:1};if(same.type(from,to)){if(from.nodeType===3){const a=from.nodeValue,b=to.nodeValue;if((a==null?void 0:a.trim().length)===0&&(b==null?void 0:b.trim().length)===0)return{type:6}}if(from.nodeType===1){if(same.name(from,to)){if(from.localName==="script"&&to.localName==="script"&&scriptAttributesChanged(from,to))return{type:2,node:clone(to)};const childFn=from.tagName==="HEAD"?uniqueChildren:children;return{type:3,attributes:attributes(from,to),children:childFn(from,to)}}return{type:2,node:clone(to)}}else return from.nodeType===9?diff(from.documentElement,to.documentElement):same.value(from,to)?{type:6}:{type:2,value:to.nodeValue}}return{type:2,node:clone(to)}}__name(diff,"diff");function patchAttributes(el,patches){if(patches.length!==0){for(const{type,name,value}of patches)if(type===5){if(name==="class"){const currentClasses=el.getAttribute("class");if(currentClasses!=null&¤tClasses.includes("preserve-")){const preserved=Array.from(el.classList).filter(c=>c.startsWith("preserve-"));preserved.length>0?el.setAttribute("class",preserved.join(" ")):el.removeAttribute("class");continue}}el.removeAttribute(name)}else if(type===4)if(name==="class"&&value){const preserved=Array.from(el.classList).filter(c=>c.startsWith("preserve-")),newClasses=value.split(/\s+/).filter(Boolean),merged=Array.from(new Set([...newClasses,...preserved]));el.setAttribute("class",merged.join(" "))}else el.setAttribute(name,value)}}__name(patchAttributes,"patchAttributes");function patch(parent,PATCH,child){return __async(this,null,function*(){if(!PATCH)return;let el;switch(parent.nodeType===9?(parent=parent.documentElement,el=parent):child?el=child:el=parent,PATCH.type){case 7:return;case 0:{let{node}=PATCH;if(node instanceof HTMLScriptElement){const newScript=document.createElement("script");for(const{name,value}of node.attributes)newScript.setAttribute(name,value);newScript.textContent=node.textContent,node=newScript}parent.appendChild(node);return}case 1:{if(!el||el.nodeType===1&&el.hasAttribute("data-preserve"))return;parent.removeChild(el);return}case 2:{if(!el||el.nodeType===1&&el.hasAttribute("data-preserve"))return;let{node,value}=PATCH;if(typeof value=="string"){el.nodeValue=value;return}if(node)if(node instanceof HTMLScriptElement){const newScript=document.createElement("script");for(const{name,value:value2}of node.attributes)newScript.setAttribute(name,value2);newScript.textContent=node.textContent,el.parentNode&&el.parentNode.replaceChild(newScript,el)}else el instanceof Element&&node instanceof Element?el.replaceWith(node):el.parentNode&&el.parentNode.replaceChild(node,el);return}case 3:{if(!el||el.nodeType!==1)return;const{attributes:attributes2,children:children2}=PATCH;patchAttributes(el,attributes2);const elements=Array.from(el.childNodes);yield Promise.all(children2.map((child2,index)=>patch(el,child2,elements[index])));return}case 6:return}})}__name(patch,"patch");function morph(from,to){return __async(this,null,function*(){const patches=diff(from,to);yield patch(document,patches)})}__name(morph,"morph");exports.ACTION_CREATE=0;exports.ACTION_PRESERVE=7;exports.ACTION_REMOVE=1;exports.ACTION_REMOVE_ATTR=5;exports.ACTION_REPLACE=2;exports.ACTION_SET_ATTR=4;exports.ACTION_SKIP=6;exports.ACTION_UPDATE=3;exports.NODE_TYPE_COMMENT=8;exports.NODE_TYPE_DOCUMENT=9;exports.NODE_TYPE_ELEMENT=1;exports.NODE_TYPE_TEXT=3;exports.diff=diff;exports.morph=morph;exports.patch=patch;
|
|
@@ -32,7 +32,43 @@ function hasPermanentParent(node) {
|
|
|
32
32
|
return !1;
|
|
33
33
|
}
|
|
34
34
|
__name(hasPermanentParent, "hasPermanentParent");
|
|
35
|
+
function scriptAttributesChanged(from, to) {
|
|
36
|
+
if (from.localName !== "script" || to.localName !== "script")
|
|
37
|
+
return !1;
|
|
38
|
+
const importantAttrs = [
|
|
39
|
+
"src",
|
|
40
|
+
"type",
|
|
41
|
+
"async",
|
|
42
|
+
"defer",
|
|
43
|
+
"module",
|
|
44
|
+
"nomodule",
|
|
45
|
+
"integrity",
|
|
46
|
+
"crossorigin"
|
|
47
|
+
];
|
|
48
|
+
for (const attr of importantAttrs) {
|
|
49
|
+
const fromValue = from.getAttribute(attr), toValue = to.getAttribute(attr);
|
|
50
|
+
if (fromValue !== toValue)
|
|
51
|
+
return !0;
|
|
52
|
+
}
|
|
53
|
+
return from.textContent !== to.textContent;
|
|
54
|
+
}
|
|
55
|
+
__name(scriptAttributesChanged, "scriptAttributesChanged");
|
|
35
56
|
function attributes(from, to) {
|
|
57
|
+
if (from.localName === "script" && to.localName === "script") {
|
|
58
|
+
const patches2 = [];
|
|
59
|
+
for (const attr of from.attributes)
|
|
60
|
+
patches2.push({
|
|
61
|
+
type: 5,
|
|
62
|
+
name: attr.name
|
|
63
|
+
});
|
|
64
|
+
for (const attr of to.attributes)
|
|
65
|
+
patches2.push({
|
|
66
|
+
type: 4,
|
|
67
|
+
name: attr.name,
|
|
68
|
+
value: attr.value
|
|
69
|
+
});
|
|
70
|
+
return patches2;
|
|
71
|
+
}
|
|
36
72
|
if (from.attributes.length === 0 && to.attributes.length === 0)
|
|
37
73
|
return [];
|
|
38
74
|
const patches = [], remove = /* @__PURE__ */ new Map(), update = /* @__PURE__ */ new Map();
|
|
@@ -80,15 +116,7 @@ function getKey(el) {
|
|
|
80
116
|
}
|
|
81
117
|
__name(getKey, "getKey");
|
|
82
118
|
function clone(node) {
|
|
83
|
-
|
|
84
|
-
return node.cloneNode(!0);
|
|
85
|
-
if (node.nodeType === 1 && node.localName === "script") {
|
|
86
|
-
const script = document.createElement("script");
|
|
87
|
-
for (let { name, value } of node.attributes)
|
|
88
|
-
script.setAttribute(name, value);
|
|
89
|
-
return script.innerHTML = node.innerHTML, script;
|
|
90
|
-
}
|
|
91
|
-
return node.cloneNode(!0);
|
|
119
|
+
return node.nodeType === 1 && node.hasAttribute("data-preserve") || node.nodeType === 1 && node.localName === "script", node.cloneNode(!0);
|
|
92
120
|
}
|
|
93
121
|
__name(clone, "clone");
|
|
94
122
|
function uniqueChildren(from, to) {
|
|
@@ -152,6 +180,11 @@ function diff(from, to) {
|
|
|
152
180
|
}
|
|
153
181
|
if (from.nodeType === 1) {
|
|
154
182
|
if (same.name(from, to)) {
|
|
183
|
+
if (from.localName === "script" && to.localName === "script" && scriptAttributesChanged(from, to))
|
|
184
|
+
return {
|
|
185
|
+
type: 2,
|
|
186
|
+
node: clone(to)
|
|
187
|
+
};
|
|
155
188
|
const childFn = from.tagName === "HEAD" ? uniqueChildren : children;
|
|
156
189
|
return {
|
|
157
190
|
type: 3,
|
|
@@ -159,22 +192,13 @@ function diff(from, to) {
|
|
|
159
192
|
children: childFn(from, to)
|
|
160
193
|
};
|
|
161
194
|
}
|
|
162
|
-
return {
|
|
163
|
-
type: 2,
|
|
164
|
-
node: clone(to)
|
|
165
|
-
};
|
|
195
|
+
return { type: 2, node: clone(to) };
|
|
166
196
|
} else return from.nodeType === 9 ? diff(
|
|
167
197
|
from.documentElement,
|
|
168
198
|
to.documentElement
|
|
169
|
-
) : same.value(from, to) ? { type: 6 } : {
|
|
170
|
-
type: 2,
|
|
171
|
-
value: to.nodeValue
|
|
172
|
-
};
|
|
199
|
+
) : same.value(from, to) ? { type: 6 } : { type: 2, value: to.nodeValue };
|
|
173
200
|
}
|
|
174
|
-
return {
|
|
175
|
-
type: 2,
|
|
176
|
-
node: clone(to)
|
|
177
|
-
};
|
|
201
|
+
return { type: 2, node: clone(to) };
|
|
178
202
|
}
|
|
179
203
|
__name(diff, "diff");
|
|
180
204
|
function patchAttributes(el, patches) {
|
|
@@ -203,17 +227,6 @@ function patchAttributes(el, patches) {
|
|
|
203
227
|
}
|
|
204
228
|
}
|
|
205
229
|
__name(patchAttributes, "patchAttributes");
|
|
206
|
-
function updateScripts(node) {
|
|
207
|
-
if (node instanceof HTMLElement) {
|
|
208
|
-
if (node.hasAttribute("data-preserve"))
|
|
209
|
-
return node;
|
|
210
|
-
node.tagName === "SCRIPT" ? node = clone(node) : node.querySelectorAll("script").forEach((script) => {
|
|
211
|
-
script.replaceWith(clone(script));
|
|
212
|
-
});
|
|
213
|
-
}
|
|
214
|
-
return node;
|
|
215
|
-
}
|
|
216
|
-
__name(updateScripts, "updateScripts");
|
|
217
230
|
function patch(parent, PATCH, child) {
|
|
218
231
|
return __async(this, null, function* () {
|
|
219
232
|
if (!PATCH) return;
|
|
@@ -223,7 +236,13 @@ function patch(parent, PATCH, child) {
|
|
|
223
236
|
return;
|
|
224
237
|
case 0: {
|
|
225
238
|
let { node } = PATCH;
|
|
226
|
-
node
|
|
239
|
+
if (node instanceof HTMLScriptElement) {
|
|
240
|
+
const newScript = document.createElement("script");
|
|
241
|
+
for (const { name, value } of node.attributes)
|
|
242
|
+
newScript.setAttribute(name, value);
|
|
243
|
+
newScript.textContent = node.textContent, node = newScript;
|
|
244
|
+
}
|
|
245
|
+
parent.appendChild(node);
|
|
227
246
|
return;
|
|
228
247
|
}
|
|
229
248
|
case 1: {
|
|
@@ -240,7 +259,14 @@ function patch(parent, PATCH, child) {
|
|
|
240
259
|
el.nodeValue = value;
|
|
241
260
|
return;
|
|
242
261
|
}
|
|
243
|
-
|
|
262
|
+
if (node)
|
|
263
|
+
if (node instanceof HTMLScriptElement) {
|
|
264
|
+
const newScript = document.createElement("script");
|
|
265
|
+
for (const { name, value: value2 } of node.attributes)
|
|
266
|
+
newScript.setAttribute(name, value2);
|
|
267
|
+
newScript.textContent = node.textContent, el.parentNode && el.parentNode.replaceChild(newScript, el);
|
|
268
|
+
} else
|
|
269
|
+
el instanceof Element && node instanceof Element ? el.replaceWith(node) : el.parentNode && el.parentNode.replaceChild(node, el);
|
|
244
270
|
return;
|
|
245
271
|
}
|
|
246
272
|
case 3: {
|
|
@@ -1,6 +1,28 @@
|
|
|
1
|
+
import { GetSvgPathParams } from './getSvgPath';
|
|
2
|
+
export interface NotchedElementUpdateParameters {
|
|
3
|
+
cornerRadius: number;
|
|
4
|
+
topLeftCornerRadius: number;
|
|
5
|
+
topRightCornerRadius: number;
|
|
6
|
+
bottomRightCornerRadius: number;
|
|
7
|
+
bottomLeftCornerRadius: number;
|
|
8
|
+
cornerAngleAlpha: number;
|
|
9
|
+
topLeftCornerAngleAlpha: number;
|
|
10
|
+
topRightCornerAngleAlpha: number;
|
|
11
|
+
bottomRightCornerAngleAlpha: number;
|
|
12
|
+
bottomLeftCornerAngleAlpha: number;
|
|
13
|
+
cornerSmoothing: number;
|
|
14
|
+
preserveSmoothing: number;
|
|
15
|
+
topNotches: number;
|
|
16
|
+
rightNotches: number;
|
|
17
|
+
bottomNotches: number;
|
|
18
|
+
leftNotches: number;
|
|
19
|
+
width: number;
|
|
20
|
+
height: number;
|
|
21
|
+
}
|
|
1
22
|
export declare class NotchedElement extends HTMLElement {
|
|
2
23
|
#private;
|
|
3
24
|
constructor();
|
|
25
|
+
update(params: Omit<GetSvgPathParams, 'width' | 'height'>): void;
|
|
4
26
|
protected connectedCallback(): void;
|
|
5
27
|
protected disconnectedCallback(): void;
|
|
6
28
|
}
|
package/lib/notched/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty;var __typeError=msg=>{throw TypeError(msg)};var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const cssUnitParser_index=require("../css-unit-parser/index.cjs"),cssValueParser_index=require("../css-value-parser/index.cjs"),elementResizer_index=require("../element-resizer/index.cjs"),string=require("../string-Bx5N38JG.cjs");require("construct-style-sheets-polyfill");require("../index-BrasTsja.cjs");function distributeAndNormalize({topLeftCornerRadius,topRightCornerRadius,bottomRightCornerRadius,bottomLeftCornerRadius,width,height}){const roundingAndSmoothingBudgetMap={topLeft:-1,topRight:-1,bottomLeft:-1,bottomRight:-1},cornerRadiusMap={topLeft:topLeftCornerRadius,topRight:topRightCornerRadius,bottomLeft:bottomLeftCornerRadius,bottomRight:bottomRightCornerRadius};return Object.entries(cornerRadiusMap).sort(([,radius1],[,radius2])=>radius2-radius1).forEach(([cornerName,radius])=>{const corner=cornerName,adjacents=adjacentsByCorner[corner],budget=Math.min(...adjacents.map(adjacent=>{const adjacentCornerRadius=cornerRadiusMap[adjacent.corner];if(radius===0&&adjacentCornerRadius===0)return 0;const adjacentCornerBudget=roundingAndSmoothingBudgetMap[adjacent.corner],sideLength=adjacent.side==="top"||adjacent.side==="bottom"?width:height;return adjacentCornerBudget>=0?sideLength-roundingAndSmoothingBudgetMap[adjacent.corner]:radius/(radius+adjacentCornerRadius)*sideLength}));roundingAndSmoothingBudgetMap[corner]=budget,cornerRadiusMap[corner]=Math.min(radius,budget)}),{topLeft:{radius:cornerRadiusMap.topLeft,roundingAndSmoothingBudget:roundingAndSmoothingBudgetMap.topLeft},topRight:{radius:cornerRadiusMap.topRight,roundingAndSmoothingBudget:roundingAndSmoothingBudgetMap.topRight},bottomLeft:{radius:cornerRadiusMap.bottomLeft,roundingAndSmoothingBudget:roundingAndSmoothingBudgetMap.bottomLeft},bottomRight:{radius:cornerRadiusMap.bottomRight,roundingAndSmoothingBudget:roundingAndSmoothingBudgetMap.bottomRight}}}__name(distributeAndNormalize,"distributeAndNormalize");const adjacentsByCorner={topLeft:[{corner:"topRight",side:"top"},{corner:"bottomLeft",side:"left"}],topRight:[{corner:"topLeft",side:"top"},{corner:"bottomRight",side:"right"}],bottomLeft:[{corner:"bottomRight",side:"bottom"},{corner:"topLeft",side:"left"}],bottomRight:[{corner:"bottomLeft",side:"bottom"},{corner:"topRight",side:"right"}]};function getPathParamsForCorner({cornerRadius,cornerSmoothing,preserveSmoothing,roundingAndSmoothingBudget,cornerAngleAlpha=90}){let p=(1+cornerSmoothing)*cornerRadius;if(!preserveSmoothing){const maxCornerSmoothing=roundingAndSmoothingBudget/cornerRadius-1;cornerSmoothing=Math.min(cornerSmoothing,maxCornerSmoothing),p=Math.min(p,roundingAndSmoothingBudget)}const arcMeasure=90*(1-cornerSmoothing),arcSectionLength=Math.sin(toRadians(arcMeasure/2))*cornerRadius*Math.sqrt(2),angleAlpha=(cornerAngleAlpha-arcMeasure)/2,p3ToP4Distance=cornerRadius*Math.tan(toRadians(angleAlpha/2)),angleBeta=45*cornerSmoothing,c=p3ToP4Distance*Math.cos(toRadians(angleBeta)),d=c*Math.tan(toRadians(angleBeta));let b=(p-arcSectionLength-c-d)/3,a=2*b;if(preserveSmoothing&&p>roundingAndSmoothingBudget){const p1ToP3MaxDistance=roundingAndSmoothingBudget-d-arcSectionLength-c,minA=p1ToP3MaxDistance/6,maxB=p1ToP3MaxDistance-minA;b=Math.min(b,maxB),a=p1ToP3MaxDistance-b,p=Math.min(p,roundingAndSmoothingBudget)}return{a,b,c,d,p,arcSectionLength,cornerRadius}}__name(getPathParamsForCorner,"getPathParamsForCorner");function getSVGPathFromPathParams({width,height,topLeftPathParams,topRightPathParams,bottomLeftPathParams,bottomRightPathParams,topNotches=[],rightNotches=[],bottomNotches=[],leftNotches=[]}){let d=`M ${topLeftPathParams.p} 0`;return topNotches.forEach(n=>{d+=drawTopNotch(n)}),d+=`L ${width-topRightPathParams.p} 0`,d+=drawTopRightPath(topRightPathParams),rightNotches.forEach(n=>{d+=drawRightNotch(n,width)}),d+=`L ${width} ${height-bottomRightPathParams.p}`,d+=drawBottomRightPath(bottomRightPathParams),bottomNotches.forEach(n=>{d+=drawBottomNotch(n,height)}),d+=`L ${bottomLeftPathParams.p} ${height}`,d+=drawBottomLeftPath(bottomLeftPathParams),leftNotches.forEach(n=>{d+=drawLeftNotch(n)}),d+=`L 0 ${topLeftPathParams.p}`,d+=drawTopLeftPath(topLeftPathParams),d+="Z",d.replace(/[\t\s\n]+/g," ").trim()}__name(getSVGPathFromPathParams,"getSVGPathFromPathParams");function drawTopNotch({start,length,slope,depth}){const end=start+length;return`
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty,__defProps=Object.defineProperties;var __getOwnPropDescs=Object.getOwnPropertyDescriptors;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __typeError=msg=>{throw TypeError(msg)};var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const cssUnitParser_index=require("../css-unit-parser/index.cjs"),cssValueParser_index=require("../css-value-parser/index.cjs"),elementResizer_index=require("../element-resizer/index.cjs"),string=require("../string-Bx5N38JG.cjs");require("construct-style-sheets-polyfill");require("../index-BrasTsja.cjs");function distributeAndNormalize({topLeftCornerRadius,topRightCornerRadius,bottomRightCornerRadius,bottomLeftCornerRadius,width,height}){const roundingAndSmoothingBudgetMap={topLeft:-1,topRight:-1,bottomLeft:-1,bottomRight:-1},cornerRadiusMap={topLeft:topLeftCornerRadius,topRight:topRightCornerRadius,bottomLeft:bottomLeftCornerRadius,bottomRight:bottomRightCornerRadius};return Object.entries(cornerRadiusMap).sort(([,radius1],[,radius2])=>radius2-radius1).forEach(([cornerName,radius])=>{const corner=cornerName,adjacents=adjacentsByCorner[corner],budget=Math.min(...adjacents.map(adjacent=>{const adjacentCornerRadius=cornerRadiusMap[adjacent.corner];if(radius===0&&adjacentCornerRadius===0)return 0;const adjacentCornerBudget=roundingAndSmoothingBudgetMap[adjacent.corner],sideLength=adjacent.side==="top"||adjacent.side==="bottom"?width:height;return adjacentCornerBudget>=0?sideLength-roundingAndSmoothingBudgetMap[adjacent.corner]:radius/(radius+adjacentCornerRadius)*sideLength}));roundingAndSmoothingBudgetMap[corner]=budget,cornerRadiusMap[corner]=Math.min(radius,budget)}),{topLeft:{radius:cornerRadiusMap.topLeft,roundingAndSmoothingBudget:roundingAndSmoothingBudgetMap.topLeft},topRight:{radius:cornerRadiusMap.topRight,roundingAndSmoothingBudget:roundingAndSmoothingBudgetMap.topRight},bottomLeft:{radius:cornerRadiusMap.bottomLeft,roundingAndSmoothingBudget:roundingAndSmoothingBudgetMap.bottomLeft},bottomRight:{radius:cornerRadiusMap.bottomRight,roundingAndSmoothingBudget:roundingAndSmoothingBudgetMap.bottomRight}}}__name(distributeAndNormalize,"distributeAndNormalize");const adjacentsByCorner={topLeft:[{corner:"topRight",side:"top"},{corner:"bottomLeft",side:"left"}],topRight:[{corner:"topLeft",side:"top"},{corner:"bottomRight",side:"right"}],bottomLeft:[{corner:"bottomRight",side:"bottom"},{corner:"topLeft",side:"left"}],bottomRight:[{corner:"bottomLeft",side:"bottom"},{corner:"topRight",side:"right"}]};function getPathParamsForCorner({cornerRadius,cornerSmoothing,preserveSmoothing,roundingAndSmoothingBudget,cornerAngleAlpha=90}){let p=(1+cornerSmoothing)*cornerRadius;if(!preserveSmoothing){const maxCornerSmoothing=roundingAndSmoothingBudget/cornerRadius-1;cornerSmoothing=Math.min(cornerSmoothing,maxCornerSmoothing),p=Math.min(p,roundingAndSmoothingBudget)}const arcMeasure=90*(1-cornerSmoothing),arcSectionLength=Math.sin(toRadians(arcMeasure/2))*cornerRadius*Math.sqrt(2),angleAlpha=(cornerAngleAlpha-arcMeasure)/2,p3ToP4Distance=cornerRadius*Math.tan(toRadians(angleAlpha/2)),angleBeta=45*cornerSmoothing,c=p3ToP4Distance*Math.cos(toRadians(angleBeta)),d=c*Math.tan(toRadians(angleBeta));let b=(p-arcSectionLength-c-d)/3,a=2*b;if(preserveSmoothing&&p>roundingAndSmoothingBudget){const p1ToP3MaxDistance=roundingAndSmoothingBudget-d-arcSectionLength-c,minA=p1ToP3MaxDistance/6,maxB=p1ToP3MaxDistance-minA;b=Math.min(b,maxB),a=p1ToP3MaxDistance-b,p=Math.min(p,roundingAndSmoothingBudget)}return{a,b,c,d,p,arcSectionLength,cornerRadius}}__name(getPathParamsForCorner,"getPathParamsForCorner");function getSVGPathFromPathParams({width,height,topLeftPathParams,topRightPathParams,bottomLeftPathParams,bottomRightPathParams,topNotches=[],rightNotches=[],bottomNotches=[],leftNotches=[]}){let d=`M ${topLeftPathParams.p} 0`;return topNotches.forEach(n=>{d+=drawTopNotch(n)}),d+=`L ${width-topRightPathParams.p} 0`,d+=drawTopRightPath(topRightPathParams),rightNotches.forEach(n=>{d+=drawRightNotch(n,width)}),d+=`L ${width} ${height-bottomRightPathParams.p}`,d+=drawBottomRightPath(bottomRightPathParams),bottomNotches.forEach(n=>{d+=drawBottomNotch(n,height)}),d+=`L ${bottomLeftPathParams.p} ${height}`,d+=drawBottomLeftPath(bottomLeftPathParams),leftNotches.forEach(n=>{d+=drawLeftNotch(n)}),d+=`L 0 ${topLeftPathParams.p}`,d+=drawTopLeftPath(topLeftPathParams),d+="Z",d.replace(/[\t\s\n]+/g," ").trim()}__name(getSVGPathFromPathParams,"getSVGPathFromPathParams");function drawTopNotch({start,length,slope,depth}){const end=start+length;return`
|
|
2
2
|
L${start} 0
|
|
3
3
|
C ${start+slope*.5},0 ${start+slope*.5},${depth} ${start+slope},${depth}
|
|
4
4
|
L${end-slope},${depth}
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
a ${cornerRadius} ${cornerRadius} 0 0 1 ${arcSectionLength} -${arcSectionLength}
|
|
45
45
|
c ${c} ${-d}
|
|
46
46
|
${b+c} ${-d}
|
|
47
|
-
${a+b+c} ${-d}`:rounded`l 0 ${-p}`}__name(drawTopLeftPath,"drawTopLeftPath");function toRadians(degrees){return degrees*Math.PI/180}__name(toRadians,"toRadians");function rounded(strings,...values){return strings.reduce((acc,str,i)=>{const value=values[i];return typeof value=="number"?acc+str+value.toFixed(4):acc+str+(value!=null?value:"")},"")}__name(rounded,"rounded");function getSvgPath({cornerRadius=0,topLeftCornerRadius,topRightCornerRadius,bottomRightCornerRadius,bottomLeftCornerRadius,cornerAngleAlpha=90,topLeftCornerAngleAlpha,topRightCornerAngleAlpha,bottomRightCornerAngleAlpha,bottomLeftCornerAngleAlpha,cornerSmoothing,preserveSmoothing=!1,topNotches,rightNotches,bottomNotches,leftNotches,width,height}){if(topLeftCornerRadius=topLeftCornerRadius!=null?topLeftCornerRadius:cornerRadius,topRightCornerRadius=topRightCornerRadius!=null?topRightCornerRadius:cornerRadius,bottomLeftCornerRadius=bottomLeftCornerRadius!=null?bottomLeftCornerRadius:cornerRadius,bottomRightCornerRadius=bottomRightCornerRadius!=null?bottomRightCornerRadius:cornerRadius,topLeftCornerAngleAlpha=topLeftCornerAngleAlpha!=null?topLeftCornerAngleAlpha:cornerAngleAlpha,topRightCornerAngleAlpha=topRightCornerAngleAlpha!=null?topRightCornerAngleAlpha:cornerAngleAlpha,bottomLeftCornerAngleAlpha=bottomLeftCornerAngleAlpha!=null?bottomLeftCornerAngleAlpha:cornerAngleAlpha,bottomRightCornerAngleAlpha=bottomRightCornerAngleAlpha!=null?bottomRightCornerAngleAlpha:cornerAngleAlpha,topLeftCornerRadius===topRightCornerRadius&&topRightCornerRadius===bottomRightCornerRadius&&bottomRightCornerRadius===bottomLeftCornerRadius&&bottomLeftCornerRadius===topLeftCornerRadius&&topLeftCornerAngleAlpha===topRightCornerAngleAlpha&&topRightCornerAngleAlpha===bottomRightCornerAngleAlpha&&bottomRightCornerAngleAlpha===bottomLeftCornerAngleAlpha&&bottomLeftCornerAngleAlpha===topLeftCornerAngleAlpha){const roundingAndSmoothingBudget=Math.min(width,height)/2,cornerRadius2=Math.min(topLeftCornerRadius,roundingAndSmoothingBudget),pathParams=getPathParamsForCorner({cornerRadius:cornerRadius2,cornerSmoothing,cornerAngleAlpha,preserveSmoothing,roundingAndSmoothingBudget});return getSVGPathFromPathParams({width,height,topLeftPathParams:pathParams,topRightPathParams:pathParams,bottomLeftPathParams:pathParams,bottomRightPathParams:pathParams,topNotches,rightNotches,bottomNotches,leftNotches})}const{topLeft,topRight,bottomLeft,bottomRight}=distributeAndNormalize({topLeftCornerRadius,topRightCornerRadius,bottomRightCornerRadius,bottomLeftCornerRadius,width,height});return getSVGPathFromPathParams({width,height,topLeftPathParams:getPathParamsForCorner({cornerSmoothing,preserveSmoothing,cornerRadius:topLeft.radius,roundingAndSmoothingBudget:topLeft.roundingAndSmoothingBudget,cornerAngleAlpha:topLeftCornerAngleAlpha}),topRightPathParams:getPathParamsForCorner({cornerSmoothing,preserveSmoothing,cornerRadius:topRight.radius,roundingAndSmoothingBudget:topRight.roundingAndSmoothingBudget,cornerAngleAlpha:topRightCornerAngleAlpha}),bottomRightPathParams:getPathParamsForCorner({cornerSmoothing,preserveSmoothing,cornerRadius:bottomRight.radius,roundingAndSmoothingBudget:bottomRight.roundingAndSmoothingBudget,cornerAngleAlpha:bottomRightCornerAngleAlpha}),bottomLeftPathParams:getPathParamsForCorner({cornerSmoothing,preserveSmoothing,cornerRadius:bottomLeft.radius,roundingAndSmoothingBudget:bottomLeft.roundingAndSmoothingBudget,cornerAngleAlpha:bottomLeftCornerAngleAlpha}),topNotches,rightNotches,bottomNotches,leftNotches})}__name(getSvgPath,"getSvgPath");var _imageElement,_clipId,_resizeListener,_NotchedElement_instances,parseCSSNotchValue_fn;const _NotchedElement=class _NotchedElement extends HTMLElement{constructor(){super();__privateAdd(this,_NotchedElement_instances);__privateAdd(this,_imageElement,null);__privateAdd(this,_clipId,null);__privateAdd(this,_resizeListener,__name(()=>{const
|
|
47
|
+
${a+b+c} ${-d}`:rounded`l 0 ${-p}`}__name(drawTopLeftPath,"drawTopLeftPath");function toRadians(degrees){return degrees*Math.PI/180}__name(toRadians,"toRadians");function rounded(strings,...values){return strings.reduce((acc,str,i)=>{const value=values[i];return typeof value=="number"?acc+str+value.toFixed(4):acc+str+(value!=null?value:"")},"")}__name(rounded,"rounded");function getSvgPath({cornerRadius=0,topLeftCornerRadius,topRightCornerRadius,bottomRightCornerRadius,bottomLeftCornerRadius,cornerAngleAlpha=90,topLeftCornerAngleAlpha,topRightCornerAngleAlpha,bottomRightCornerAngleAlpha,bottomLeftCornerAngleAlpha,cornerSmoothing,preserveSmoothing=!1,topNotches,rightNotches,bottomNotches,leftNotches,width,height}){if(topLeftCornerRadius=topLeftCornerRadius!=null?topLeftCornerRadius:cornerRadius,topRightCornerRadius=topRightCornerRadius!=null?topRightCornerRadius:cornerRadius,bottomLeftCornerRadius=bottomLeftCornerRadius!=null?bottomLeftCornerRadius:cornerRadius,bottomRightCornerRadius=bottomRightCornerRadius!=null?bottomRightCornerRadius:cornerRadius,topLeftCornerAngleAlpha=topLeftCornerAngleAlpha!=null?topLeftCornerAngleAlpha:cornerAngleAlpha,topRightCornerAngleAlpha=topRightCornerAngleAlpha!=null?topRightCornerAngleAlpha:cornerAngleAlpha,bottomLeftCornerAngleAlpha=bottomLeftCornerAngleAlpha!=null?bottomLeftCornerAngleAlpha:cornerAngleAlpha,bottomRightCornerAngleAlpha=bottomRightCornerAngleAlpha!=null?bottomRightCornerAngleAlpha:cornerAngleAlpha,topLeftCornerRadius===topRightCornerRadius&&topRightCornerRadius===bottomRightCornerRadius&&bottomRightCornerRadius===bottomLeftCornerRadius&&bottomLeftCornerRadius===topLeftCornerRadius&&topLeftCornerAngleAlpha===topRightCornerAngleAlpha&&topRightCornerAngleAlpha===bottomRightCornerAngleAlpha&&bottomRightCornerAngleAlpha===bottomLeftCornerAngleAlpha&&bottomLeftCornerAngleAlpha===topLeftCornerAngleAlpha){const roundingAndSmoothingBudget=Math.min(width,height)/2,cornerRadius2=Math.min(topLeftCornerRadius,roundingAndSmoothingBudget),pathParams=getPathParamsForCorner({cornerRadius:cornerRadius2,cornerSmoothing,cornerAngleAlpha,preserveSmoothing,roundingAndSmoothingBudget});return getSVGPathFromPathParams({width,height,topLeftPathParams:pathParams,topRightPathParams:pathParams,bottomLeftPathParams:pathParams,bottomRightPathParams:pathParams,topNotches,rightNotches,bottomNotches,leftNotches})}const{topLeft,topRight,bottomLeft,bottomRight}=distributeAndNormalize({topLeftCornerRadius,topRightCornerRadius,bottomRightCornerRadius,bottomLeftCornerRadius,width,height});return getSVGPathFromPathParams({width,height,topLeftPathParams:getPathParamsForCorner({cornerSmoothing,preserveSmoothing,cornerRadius:topLeft.radius,roundingAndSmoothingBudget:topLeft.roundingAndSmoothingBudget,cornerAngleAlpha:topLeftCornerAngleAlpha}),topRightPathParams:getPathParamsForCorner({cornerSmoothing,preserveSmoothing,cornerRadius:topRight.radius,roundingAndSmoothingBudget:topRight.roundingAndSmoothingBudget,cornerAngleAlpha:topRightCornerAngleAlpha}),bottomRightPathParams:getPathParamsForCorner({cornerSmoothing,preserveSmoothing,cornerRadius:bottomRight.radius,roundingAndSmoothingBudget:bottomRight.roundingAndSmoothingBudget,cornerAngleAlpha:bottomRightCornerAngleAlpha}),bottomLeftPathParams:getPathParamsForCorner({cornerSmoothing,preserveSmoothing,cornerRadius:bottomLeft.radius,roundingAndSmoothingBudget:bottomLeft.roundingAndSmoothingBudget,cornerAngleAlpha:bottomLeftCornerAngleAlpha}),topNotches,rightNotches,bottomNotches,leftNotches})}__name(getSvgPath,"getSvgPath");var _imageElement,_clipId,_resizeListener,_NotchedElement_instances,parseCSSNotchValue_fn;const _NotchedElement=class _NotchedElement extends HTMLElement{constructor(){super();__privateAdd(this,_NotchedElement_instances);__privateAdd(this,_imageElement,null);__privateAdd(this,_clipId,null);__privateAdd(this,_resizeListener,__name(()=>{if(this.hasAttribute("manual-update"))return;const computed=getComputedStyle(this),cornerRadius=cssUnitParser_index.cssUnitParser.parse(computed.getPropertyValue("--notched-corner-radius")),topLeftCornerRadius=cssUnitParser_index.cssUnitParser.parse(computed.getPropertyValue("--notched-top-left-corner-radius")),topRightCornerRadius=cssUnitParser_index.cssUnitParser.parse(computed.getPropertyValue("--notched-top-right-corner-radius")),bottomRightCornerRadius=cssUnitParser_index.cssUnitParser.parse(computed.getPropertyValue("--notched-bottom-right-corner-radius")),bottomLeftCornerRadius=cssUnitParser_index.cssUnitParser.parse(computed.getPropertyValue("--notched-bottom-left-corner-radius")),cornerAngleAlpha=parseFloat(computed.getPropertyValue("--notched-corner-angle-alpha"))||void 0,topLeftCornerAngleAlpha=parseFloat(computed.getPropertyValue("--notched-top-left-corner-angle-alpha"))||void 0,topRightCornerAngleAlpha=parseFloat(computed.getPropertyValue("--notched-top-right-corner-angle-alpha"))||void 0,bottomRightCornerAngleAlpha=parseFloat(computed.getPropertyValue("--notched-bottom-right-corner-angle-alpha"))||void 0,bottomLeftCornerAngleAlpha=parseFloat(computed.getPropertyValue("--notched-bottom-left-corner-angle-alpha"))||void 0,cornerSmoothing=parseFloat(computed.getPropertyValue("--notched-corner-smoothing"))||0,preserveSmoothing=computed.getPropertyValue("--notched-preserve-smoothing")!=="false",topNotches=__privateMethod(this,_NotchedElement_instances,parseCSSNotchValue_fn).call(this,computed.getPropertyValue("--notched-top-notches")),rightNotches=__privateMethod(this,_NotchedElement_instances,parseCSSNotchValue_fn).call(this,computed.getPropertyValue("--notched-right-notches")),bottomNotches=__privateMethod(this,_NotchedElement_instances,parseCSSNotchValue_fn).call(this,computed.getPropertyValue("--notched-bottom-notches")),leftNotches=__privateMethod(this,_NotchedElement_instances,parseCSSNotchValue_fn).call(this,computed.getPropertyValue("--notched-left-notches"));this.update({cornerRadius,topLeftCornerRadius,topRightCornerRadius,bottomRightCornerRadius,bottomLeftCornerRadius,cornerAngleAlpha,topLeftCornerAngleAlpha,topRightCornerAngleAlpha,bottomRightCornerAngleAlpha,bottomLeftCornerAngleAlpha,cornerSmoothing,preserveSmoothing,topNotches,rightNotches,bottomNotches,leftNotches})},"#resizeListener"));const clip=this.hasAttribute("clip");__privateSet(this,_clipId,clip?"clip-"+string.generateId(10):null),__privateGet(this,_clipId)||(__privateSet(this,_imageElement,document.createElement("img")),__privateGet(this,_imageElement).style.cssText=`
|
|
48
48
|
position: absolute;
|
|
49
49
|
top: 0;
|
|
50
50
|
left: 0;
|
|
@@ -52,4 +52,4 @@
|
|
|
52
52
|
display: block;
|
|
53
53
|
width: 100%;
|
|
54
54
|
height: 100%;
|
|
55
|
-
`,this.prepend(__privateGet(this,_imageElement)))}connectedCallback(){elementResizer_index.elementResizer.subscribe(this,__privateGet(this,_resizeListener))}disconnectedCallback(){elementResizer_index.elementResizer.unsubscribe(__privateGet(this,_resizeListener))}};_imageElement=new WeakMap,_clipId=new WeakMap,_resizeListener=new WeakMap,_NotchedElement_instances=new WeakSet,parseCSSNotchValue_fn=__name(function(value){const notchesString=value.split(",").map(v=>v.trim()).filter(v=>!!v),notches=[];return notchesString.forEach(notchString=>{const valuesStrings=notchString.split(" ").map(v=>v.trim()).filter(v=>!!v);notches.push({start:cssValueParser_index.cssValueParser.parse(valuesStrings[0],this)||0,length:cssValueParser_index.cssValueParser.parse(valuesStrings[1],this)||0,slope:cssValueParser_index.cssValueParser.parse(valuesStrings[2],this)||0,depth:cssValueParser_index.cssValueParser.parse(valuesStrings[3],this)||0})}),notches},"#parseCSSNotchValue"),__name(_NotchedElement,"NotchedElement");let NotchedElement=_NotchedElement;customElements.get("e-notched")||customElements.define("e-notched",NotchedElement);exports.NotchedElement=NotchedElement;
|
|
55
|
+
`,this.prepend(__privateGet(this,_imageElement)))}update(params){const width=this.offsetWidth,height=this.offsetHeight,path=getSvgPath(__spreadProps(__spreadValues({},params),{width,height}));if(__privateGet(this,_clipId)){const svg=`data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${this.offsetWidth}' height='${this.offsetHeight}' viewBox='0 0 ${this.offsetWidth} ${this.offsetHeight}'%3E%3Cdefs%3E%3CclipPath id='${__privateGet(this,_clipId)}'%3E%3Cpath fill='%23000' d='${path}'/%3E%3C/clipPath%3E%3C/defs%3E%3Cg clip-path='url(%23${__privateGet(this,_clipId)})' %3E%3Crect width='${this.offsetWidth}' height='${this.offsetHeight}' fill='%23000'/%3E%3C/g%3E%3C/svg%3E`;this.style.maskImage=`url("${svg}")`,this.style.maskPosition="center center",this.style.maskRepeat="no-repeat",this.style.maskSize="contain"}else if(__privateGet(this,_imageElement)){const svg=`data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${width}' height='${height}' viewBox='0 0 ${width} ${height}'%3E%3Cpath fill='%23000' d='${path}'/%3E%3C/svg%3E`;__privateGet(this,_imageElement).src=svg}}connectedCallback(){elementResizer_index.elementResizer.subscribe(this,__privateGet(this,_resizeListener))}disconnectedCallback(){elementResizer_index.elementResizer.unsubscribe(__privateGet(this,_resizeListener))}};_imageElement=new WeakMap,_clipId=new WeakMap,_resizeListener=new WeakMap,_NotchedElement_instances=new WeakSet,parseCSSNotchValue_fn=__name(function(value){const notchesString=value.split(",").map(v=>v.trim()).filter(v=>!!v),notches=[];return notchesString.forEach(notchString=>{const valuesStrings=notchString.split(" ").map(v=>v.trim()).filter(v=>!!v);notches.push({start:cssValueParser_index.cssValueParser.parse(valuesStrings[0],this)||0,length:cssValueParser_index.cssValueParser.parse(valuesStrings[1],this)||0,slope:cssValueParser_index.cssValueParser.parse(valuesStrings[2],this)||0,depth:cssValueParser_index.cssValueParser.parse(valuesStrings[3],this)||0})}),notches},"#parseCSSNotchValue"),__name(_NotchedElement,"NotchedElement");let NotchedElement=_NotchedElement;customElements.get("e-notched")||customElements.define("e-notched",NotchedElement);exports.NotchedElement=NotchedElement;
|
package/lib/notched/index.js
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
1
|
+
var __defProp = Object.defineProperty, __defProps = Object.defineProperties;
|
|
2
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
3
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty, __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
2
5
|
var __typeError = (msg) => {
|
|
3
6
|
throw TypeError(msg);
|
|
4
7
|
};
|
|
5
|
-
var
|
|
8
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues = (a, b) => {
|
|
9
|
+
for (var prop in b || (b = {}))
|
|
10
|
+
__hasOwnProp.call(b, prop) && __defNormalProp(a, prop, b[prop]);
|
|
11
|
+
if (__getOwnPropSymbols)
|
|
12
|
+
for (var prop of __getOwnPropSymbols(b))
|
|
13
|
+
__propIsEnum.call(b, prop) && __defNormalProp(a, prop, b[prop]);
|
|
14
|
+
return a;
|
|
15
|
+
}, __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)), __name = (target, value) => __defProp(target, "name", { value, configurable: !0 });
|
|
6
16
|
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
7
17
|
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value), __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
8
18
|
import { cssUnitParser } from "../css-unit-parser/index.js";
|
|
@@ -381,7 +391,9 @@ const _NotchedElement = class _NotchedElement extends HTMLElement {
|
|
|
381
391
|
__privateAdd(this, _imageElement, null);
|
|
382
392
|
__privateAdd(this, _clipId, null);
|
|
383
393
|
__privateAdd(this, _resizeListener, /* @__PURE__ */ __name(() => {
|
|
384
|
-
|
|
394
|
+
if (this.hasAttribute("manual-update"))
|
|
395
|
+
return;
|
|
396
|
+
const computed = getComputedStyle(this), cornerRadius = cssUnitParser.parse(
|
|
385
397
|
computed.getPropertyValue("--notched-corner-radius")
|
|
386
398
|
), topLeftCornerRadius = cssUnitParser.parse(
|
|
387
399
|
computed.getPropertyValue("--notched-top-left-corner-radius")
|
|
@@ -399,7 +411,8 @@ const _NotchedElement = class _NotchedElement extends HTMLElement {
|
|
|
399
411
|
computed.getPropertyValue("--notched-bottom-right-corner-angle-alpha")
|
|
400
412
|
) || void 0, bottomLeftCornerAngleAlpha = parseFloat(
|
|
401
413
|
computed.getPropertyValue("--notched-bottom-left-corner-angle-alpha")
|
|
402
|
-
) || void 0, cornerSmoothing = parseFloat(computed.getPropertyValue("--notched-corner-smoothing")) || 0, preserveSmoothing = computed.getPropertyValue("--notched-preserve-smoothing") !== "false", topNotches = __privateMethod(this, _NotchedElement_instances, parseCSSNotchValue_fn).call(this, computed.getPropertyValue("--notched-top-notches")), rightNotches = __privateMethod(this, _NotchedElement_instances, parseCSSNotchValue_fn).call(this, computed.getPropertyValue("--notched-right-notches")), bottomNotches = __privateMethod(this, _NotchedElement_instances, parseCSSNotchValue_fn).call(this, computed.getPropertyValue("--notched-bottom-notches")), leftNotches = __privateMethod(this, _NotchedElement_instances, parseCSSNotchValue_fn).call(this, computed.getPropertyValue("--notched-left-notches"))
|
|
414
|
+
) || void 0, cornerSmoothing = parseFloat(computed.getPropertyValue("--notched-corner-smoothing")) || 0, preserveSmoothing = computed.getPropertyValue("--notched-preserve-smoothing") !== "false", topNotches = __privateMethod(this, _NotchedElement_instances, parseCSSNotchValue_fn).call(this, computed.getPropertyValue("--notched-top-notches")), rightNotches = __privateMethod(this, _NotchedElement_instances, parseCSSNotchValue_fn).call(this, computed.getPropertyValue("--notched-right-notches")), bottomNotches = __privateMethod(this, _NotchedElement_instances, parseCSSNotchValue_fn).call(this, computed.getPropertyValue("--notched-bottom-notches")), leftNotches = __privateMethod(this, _NotchedElement_instances, parseCSSNotchValue_fn).call(this, computed.getPropertyValue("--notched-left-notches"));
|
|
415
|
+
this.update({
|
|
403
416
|
cornerRadius,
|
|
404
417
|
topLeftCornerRadius,
|
|
405
418
|
topRightCornerRadius,
|
|
@@ -415,17 +428,8 @@ const _NotchedElement = class _NotchedElement extends HTMLElement {
|
|
|
415
428
|
topNotches,
|
|
416
429
|
rightNotches,
|
|
417
430
|
bottomNotches,
|
|
418
|
-
leftNotches
|
|
419
|
-
width,
|
|
420
|
-
height
|
|
431
|
+
leftNotches
|
|
421
432
|
});
|
|
422
|
-
if (__privateGet(this, _clipId)) {
|
|
423
|
-
const svg = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${this.offsetWidth}' height='${this.offsetHeight}' viewBox='0 0 ${this.offsetWidth} ${this.offsetHeight}'%3E%3Cdefs%3E%3CclipPath id='${__privateGet(this, _clipId)}'%3E%3Cpath fill='%23000' d='${path}'/%3E%3C/clipPath%3E%3C/defs%3E%3Cg clip-path='url(%23${__privateGet(this, _clipId)})' %3E%3Crect width='${this.offsetWidth}' height='${this.offsetHeight}' fill='%23000'/%3E%3C/g%3E%3C/svg%3E`;
|
|
424
|
-
this.style.maskImage = `url("${svg}")`, this.style.maskPosition = "center center", this.style.maskRepeat = "no-repeat", this.style.maskSize = "contain";
|
|
425
|
-
} else if (__privateGet(this, _imageElement)) {
|
|
426
|
-
const svg = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${width}' height='${height}' viewBox='0 0 ${width} ${height}'%3E%3Cpath fill='%23000' d='${path}'/%3E%3C/svg%3E`;
|
|
427
|
-
__privateGet(this, _imageElement).src = svg;
|
|
428
|
-
}
|
|
429
433
|
}, "#resizeListener"));
|
|
430
434
|
const clip = this.hasAttribute("clip");
|
|
431
435
|
__privateSet(this, _clipId, clip ? "clip-" + generateId(10) : null), __privateGet(this, _clipId) || (__privateSet(this, _imageElement, document.createElement("img")), __privateGet(this, _imageElement).style.cssText = `
|
|
@@ -438,6 +442,19 @@ const _NotchedElement = class _NotchedElement extends HTMLElement {
|
|
|
438
442
|
height: 100%;
|
|
439
443
|
`, this.prepend(__privateGet(this, _imageElement)));
|
|
440
444
|
}
|
|
445
|
+
update(params) {
|
|
446
|
+
const width = this.offsetWidth, height = this.offsetHeight, path = getSvgPath(__spreadProps(__spreadValues({}, params), {
|
|
447
|
+
width,
|
|
448
|
+
height
|
|
449
|
+
}));
|
|
450
|
+
if (__privateGet(this, _clipId)) {
|
|
451
|
+
const svg = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${this.offsetWidth}' height='${this.offsetHeight}' viewBox='0 0 ${this.offsetWidth} ${this.offsetHeight}'%3E%3Cdefs%3E%3CclipPath id='${__privateGet(this, _clipId)}'%3E%3Cpath fill='%23000' d='${path}'/%3E%3C/clipPath%3E%3C/defs%3E%3Cg clip-path='url(%23${__privateGet(this, _clipId)})' %3E%3Crect width='${this.offsetWidth}' height='${this.offsetHeight}' fill='%23000'/%3E%3C/g%3E%3C/svg%3E`;
|
|
452
|
+
this.style.maskImage = `url("${svg}")`, this.style.maskPosition = "center center", this.style.maskRepeat = "no-repeat", this.style.maskSize = "contain";
|
|
453
|
+
} else if (__privateGet(this, _imageElement)) {
|
|
454
|
+
const svg = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${width}' height='${height}' viewBox='0 0 ${width} ${height}'%3E%3Cpath fill='%23000' d='${path}'/%3E%3C/svg%3E`;
|
|
455
|
+
__privateGet(this, _imageElement).src = svg;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
441
458
|
connectedCallback() {
|
|
442
459
|
elementResizer.subscribe(this, __privateGet(this, _resizeListener));
|
|
443
460
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty,__defProps=Object.defineProperties;var __getOwnPropDescs=Object.getOwnPropertyDescriptors;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __typeError=msg=>{throw TypeError(msg)};var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method);const Store=require("./Store-BP8tuWzQ.cjs"),attributes=require("./attributes-BADnRZpK.cjs"),string=require("./string-Bx5N38JG.cjs"),morph=require("./morph-Bz2BCWvO.cjs"),object=require("./object-DTY_W6xG.cjs");require("construct-style-sheets-polyfill");const intersector_index=require("./index-BrasTsja.cjs"),connector_index=require("./connector/index.cjs"),DerivedArray=require("./DerivedArray-0qZFAKZ4.cjs");require("./css-value-parser/index.cjs");require("./window-resizer/index.cjs");require("./element-resizer/index.cjs");const activeComponent={current:null};let previousComponent=null;const componentElementLoadingTypes=["idle","load","visible","constructor","connect"];var _loadCallback,_connectCallbacks,_disconnectCallbacks,_loadingType,_idleId,_windowLoadListener,_idleListener,_intersectionListener,_ComponentElement_instances,connect_fn;const _ComponentElement=class _ComponentElement extends HTMLElement{constructor(){super();__privateAdd(this,_ComponentElement_instances);__privateAdd(this,_loadCallback);__privateAdd(this,_connectCallbacks,[]);__privateAdd(this,_disconnectCallbacks,[]);__privateAdd(this,_loadingType,"idle");__privateAdd(this,_idleId);__privateAdd(this,_windowLoadListener,__name(()=>{window.removeEventListener("load",__privateGet(this,_windowLoadListener)),__privateGet(this,_loadingType)==="load"&&__privateMethod(this,_ComponentElement_instances,connect_fn).call(this)},"#windowLoadListener"));__privateAdd(this,_idleListener,__name(()=>{__privateSet(this,_idleId,void 0),__privateGet(this,_loadingType)==="idle"&&__privateMethod(this,_ComponentElement_instances,connect_fn).call(this)},"#idleListener"));__privateAdd(this,_intersectionListener,__name(entry=>{entry.isIntersecting&&(intersector_index.intersector.unsubscribe(__privateGet(this,_intersectionListener)),__privateGet(this,_loadingType)==="visible"&&__privateMethod(this,_ComponentElement_instances,connect_fn).call(this))},"#intersectionListener"));previousComponent=activeComponent.current,activeComponent.current=this}addLoadCallback(callback){this.hasAttribute("loading")&&componentElementLoadingTypes.includes(this.getAttribute("loading"))?__privateSet(this,_loadingType,this.getAttribute("loading")):__privateSet(this,_loadingType,"constructor"),__privateSet(this,_loadCallback,callback),__privateGet(this,_loadingType)==="constructor"&&__privateGet(this,_loadCallback).call(this)}addConnectCallback(callback){__privateGet(this,_connectCallbacks).push(callback)}addDisconnectCallback(callback){__privateGet(this,_disconnectCallbacks).push(callback)}connectedCallback(){const windowLoadSetup=__name(()=>{document.readyState==="complete"?__privateGet(this,_windowLoadListener).call(this):window.addEventListener("load",__privateGet(this,_windowLoadListener))},"windowLoadSetup");__privateGet(this,_loadingType)==="connect"||__privateGet(this,_loadingType)==="constructor"?__privateMethod(this,_ComponentElement_instances,connect_fn).call(this):__privateGet(this,_loadingType)==="load"?windowLoadSetup():__privateGet(this,_loadingType)==="idle"?window.requestIdleCallback?__privateSet(this,_idleId,window.requestIdleCallback(__privateGet(this,_idleListener))):windowLoadSetup():__privateGet(this,_loadingType)==="visible"&&intersector_index.intersector.subscribe(this,__privateGet(this,_intersectionListener)),activeComponent.current===this&&(activeComponent.current=previousComponent)}disconnectedCallback(){__privateGet(this,_disconnectCallbacks).forEach(callback=>{callback(this)}),__privateSet(this,_connectCallbacks,[]),__privateSet(this,_disconnectCallbacks,[]),activeComponent.current===this&&(activeComponent.current=previousComponent),window.removeEventListener("load",__privateGet(this,_windowLoadListener)),window.cancelIdleCallback&&__privateGet(this,_idleId)&&window.cancelIdleCallback(__privateGet(this,_idleId)),intersector_index.intersector.unsubscribe(__privateGet(this,_intersectionListener))}};_loadCallback=new WeakMap,_connectCallbacks=new WeakMap,_disconnectCallbacks=new WeakMap,_loadingType=new WeakMap,_idleId=new WeakMap,_windowLoadListener=new WeakMap,_idleListener=new WeakMap,_intersectionListener=new WeakMap,_ComponentElement_instances=new WeakSet,connect_fn=__name(function(){var _a;activeComponent.current=this,this.querySelectorAll("[data-fallback]").forEach(el=>{el.remove()}),__privateGet(this,_loadingType)!=="constructor"&&((_a=__privateGet(this,_loadCallback))==null||_a.call(this)),__privateGet(this,_connectCallbacks).forEach(callback=>{const unsub=callback(this);unsub&&__privateGet(this,_disconnectCallbacks).push(unsub)}),activeComponent.current===this&&(activeComponent.current=previousComponent)},"#connect"),__name(_ComponentElement,"ComponentElement");let ComponentElement=_ComponentElement;function subscribeToStore(element,store,callback){const unsubscribe=store.subscribe(e=>{callback(e)});connector_index.connector.subscribe(element,{disconnectCallback:__name(()=>{unsubscribe()},"disconnectCallback"),maxWaitSec:20,unsubscribeAfterDisconnect:!0})}__name(subscribeToStore,"subscribeToStore");function setClassAttribute(element,classes){classes&&(classes instanceof Store.Store?subscribeToStore(element,classes,e=>{e.previous&&element.classList.remove(e.previous.toString()),e.current&&element.classList.add(e.current.toString())}):typeof classes=="object"&&!Array.isArray(classes)?Object.entries(classes).forEach(([key,value])=>{value instanceof Store.Store?subscribeToStore(element,value,e=>{element.classList.toggle(key,!!e.current)}):value&&element.classList.add(key)}):Array.isArray(classes)?classes.forEach(item=>{typeof item=="string"?element.classList.add(item):setClassAttribute(element,item)}):classes.toString().split(" ").map(v=>element.classList.add(v.trim())))}__name(setClassAttribute,"setClassAttribute");function setStyleAttribute(element,value){value&&(typeof value=="object"?Object.entries(value).forEach(([key,value2])=>{value2 instanceof Store.Store?subscribeToStore(element,value2,e=>{var _a;element.style[key]=(_a=e.current)==null?void 0:_a.toString()}):(typeof value2=="number"||typeof value2=="string"||typeof value2=="boolean")&&(element.style[key]=value2.toString())}):typeof value=="string"&&(element.style=value))}__name(setStyleAttribute,"setStyleAttribute");function setAttribute(element,key,value){key==="ref"&&value?Array.isArray(value)?value.forEach(v=>{typeof v=="object"&&"value"in v&&(v.value=element)}):typeof value=="object"&&"value"in value&&(value.value=element):key==="className"||key==="class"?setClassAttribute(element,value):key==="style"?setStyleAttribute(element,value):key==="setHtml"&&value!=null?element.innerHTML=value:typeof value=="number"?key==="tabIndex"?element.setAttribute("tabindex",value.toString()):setAttribute(element,key,value.toString()):typeof value=="string"?key==="htmlFor"?element.setAttribute("for",value):element.setAttribute(key,value):typeof value=="boolean"?value?element.setAttribute(key,""):element.removeAttribute(key):value instanceof Store.Store&&subscribeToStore(element,value,e=>{key in element?element[key]=e.current:setAttribute(element,key,e.current)})}__name(setAttribute,"setAttribute");function setAttributes(ele,attributes2){for(const[key,value]of Object.entries(attributes2!=null?attributes2:{}))typeof value=="function"&&key.startsWith("on")?ele.addEventListener(string.uncapitalize(key.replace("on","")),value):setAttribute(ele,key,value)}__name(setAttributes,"setAttributes");function createElement(tag,isSVG){return tag==="svg"?document.createElementNS("http://www.w3.org/2000/svg","svg"):isSVG?document.createElementNS("http://www.w3.org/2000/svg",tag):document.createElement(tag)}__name(createElement,"createElement");function filterChildren(children){const filtered=[];return(Array.isArray(children)?children:[children]).forEach(child=>{child!=null&&(typeof child=="number"?filtered.push(child.toString()):Array.isArray(child)?child.forEach(c=>{filtered.push(...filterChildren(c))}):filtered.push(child))}),filtered}__name(filterChildren,"filterChildren");function hydrateTextNode(element,newChild,index){const existingChild=element.childNodes[index];existingChild&&existingChild.nodeType===Node.TEXT_NODE?existingChild.textContent!==String(newChild)&&(console.warn(`Hydration text mismatch: expected "${newChild}", got "${existingChild.textContent}"`),existingChild.textContent=String(newChild)):newChild!=null&&newChild!==""&&element.insertBefore(document.createTextNode(String(newChild)),element.childNodes[index]||null)}__name(hydrateTextNode,"hydrateTextNode");function storeChildren(element,store){const currentChildNodes=[...element.childNodes].filter(node=>node.__storeId===store.id),newChildren=store.current,newChildrenArray=Array.isArray(newChildren)?newChildren:[newChildren],newNodes=[];if(newChildrenArray.forEach(newChild=>{let newNode=null;typeof newChild=="boolean"||typeof newChild=="number"||typeof newChild=="string"?newNode=document.createTextNode(newChild.toString()):newChild instanceof Node&&(newNode=newChild),newNode&&(newNode.__storeId=store.id,newNodes.push(newNode))}),store instanceof DerivedArray.DerivedKeyedArray){const nodesToStay=[];newNodes.forEach((newNode,i)=>{const oldNode=currentChildNodes.find(oldNode2=>oldNode2.__key===newNode.__key);oldNode?oldNode.isEqualNode(newNode)?nodesToStay.push(oldNode):(oldNode.replaceWith(newNode),nodesToStay.push(newNode)):(nodesToStay.push(newNode),element.appendChild(newNode))}),currentChildNodes.forEach(currentNode=>{nodesToStay.includes(currentNode)||currentNode.remove()})}else newNodes.forEach((node,i)=>{var _a;const founded=currentChildNodes[i];if(founded)founded.isEqualNode(node)||(founded.replaceWith(node),currentChildNodes[i]=node);else{const lastChildNode=currentChildNodes[currentChildNodes.length-1];lastChildNode?(_a=lastChildNode.parentNode)==null||_a.insertBefore(node,lastChildNode.nextSibling):element.appendChild(node)}}),currentChildNodes.slice(newNodes.length).forEach(node=>{node.remove()})}__name(storeChildren,"storeChildren");const _Props=class _Props{constructor(tag,attributes2,children){this.tag=tag,this.attributes=attributes2,this.children=children}};__name(_Props,"Props");let Props=_Props;const _ComponentProps=class _ComponentProps extends Props{};__name(_ComponentProps,"ComponentProps");let ComponentProps=_ComponentProps;const _ElementProps=class _ElementProps extends Props{};__name(_ElementProps,"ElementProps");let ElementProps=_ElementProps;const _HeadProps=class _HeadProps extends Props{};__name(_HeadProps,"HeadProps");let HeadProps=_HeadProps;function appendChildren(element,attributes2,children,isSVG=!1){const filteredChildren=filterChildren(children);setAttributes(element,attributes2),filteredChildren.forEach((child,index)=>{handleChild(element,child,index,isSVG)})}__name(appendChildren,"appendChildren");function handleChild(element,child,index,isSVG){child instanceof Store.Store?handleStoreChild(element,child):child instanceof ComponentProps?handleComponentProps(element,child):child instanceof ElementProps?handleElementProps(element,child,index,isSVG):child instanceof HeadProps?handleHeadProps(child):handleTextNode(element,child,index)}__name(handleChild,"handleChild");function handleStoreChild(element,child){subscribeToStore(element,child,()=>{storeChildren(element,child)})}__name(handleStoreChild,"handleStoreChild");function handleComponentProps(element,child){child.tag==="shadow"&&element.shadowRoot?appendChildren(element.shadowRoot,child.attributes,child.children):appendChildren(element,child.attributes,child.children)}__name(handleComponentProps,"handleComponentProps");function handleElementProps(element,child,index,isSVG){let childElement=null;if(isHydrating.value){const existingChild=element.children[index];(existingChild==null?void 0:existingChild.nodeName.toLowerCase())===child.tag?(childElement=existingChild,appendChildren(childElement,child.attributes,child.children,isSVG)):(childElement=createElement(child.tag,isSVG),appendChildren(childElement,child.attributes,child.children,isSVG),element.append(childElement))}else childElement=createElement(child.tag,isSVG),appendChildren(childElement,child.attributes,child.children,isSVG),element.append(childElement)}__name(handleElementProps,"handleElementProps");function handleHeadProps(child){const headElement=document.createElement(child.tag);appendChildren(headElement,child.attributes,child.children);const patches=morph.diff(document.head,headElement);morph.patch(document.head,patches)}__name(handleHeadProps,"handleHeadProps");function handleTextNode(element,child,index){isHydrating.value?hydrateTextNode(element,child,index):element.append(child)}__name(handleTextNode,"handleTextNode");function processChildren(attributes2,children){let result=children.filter(Boolean).length?children:attributes2==null?void 0:attributes2.children;return result?result.flat(2):[]}__name(processChildren,"processChildren");function handleStringTag(tag,attributes2,children){switch(tag){case"component":case"shadow":return new ComponentProps(tag,attributes2,children);case"head":return new HeadProps(tag,attributes2,children);default:return new ElementProps(tag,attributes2,children)}}__name(handleStringTag,"handleStringTag");function handleFunctionTag(jsxTag,attributes2,children){return object.isESClass(jsxTag)?createClassElement(jsxTag,attributes2,children):jsxTag===Fragment?Fragment(children):jsxTag.template?jsxTag(__spreadValues({},attributes2)):createCustomElement(jsxTag,attributes2,children)}__name(handleFunctionTag,"handleFunctionTag");function createClassElement(jsxTag,attributes2,children){const element=new jsxTag;return appendChildren(element,attributes2,children),element}__name(createClassElement,"createClassElement");function createCustomElement(jsxTag,attributes2,children){const name=jsxTag.define||`e-${string.camelToKebab(jsxTag.name)}`,Constructor=getOrDefineCustomElement(name,jsxTag,attributes2);if(attributes2!=null&&attributes2.__onlyDefine)return;const id=generateElementId(jsxTag.name,attributes2),element=getOrCreateElement(name,id,Constructor);return fillComponentElement(element,jsxTag,attributes2,children),element}__name(createCustomElement,"createCustomElement");function getOrDefineCustomElement(name,jsxTag,attributes$1){var _a;let Constructor=customElements.get(name);return Constructor||(Constructor=(_a=class extends ComponentElement{constructor(){super(),attributes$1!=null&&attributes$1.__onlyDefine&&this.addLoadCallback(()=>fillComponentElement(this,jsxTag,attributes.getElementAttributesAdvanced(this),[]))}},__name(_a,"Constructor"),_a.formAssociated=jsxTag.formAssociated,_a),customElements.define(name,Constructor)),Constructor}__name(getOrDefineCustomElement,"getOrDefineCustomElement");function generateElementId(tagName,attributes2){if(attributes2!=null&&attributes2.__hydrationId)return attributes2.__hydrationId;const index=(indexMap.get(tagName)||0)+1;return indexMap.set(tagName,index),`${tagName}-${index}`}__name(generateElementId,"generateElementId");function getOrCreateElement(name,id,Constructor){if(isHydrating.value){const selector=`${name}[data-id="${id}"]`,existingElement=document.querySelector(selector);if(existingElement&&existingElement instanceof Constructor)return existingElement}const element=new Constructor;return element.setAttribute("data-id",id),element}__name(getOrCreateElement,"getOrCreateElement");function fillComponentElement(element,jsxTag,attributes2,children){const props=__spreadProps(__spreadValues({},attributes2),{children}),setHtml=props.setHtml;delete props.setHtml;const result=jsxTag(props);result instanceof ElementProps?appendChildren(element,{setHtml},result):result instanceof ComponentProps&&appendChildren(element,__spreadProps(__spreadValues({},result.attributes),{setHtml}),result.children)}__name(fillComponentElement,"fillComponentElement");const isHydrating={value:!1},indexMap=new Map;function h(jsxTag,attributes2,...children){const processedChildren=processChildren(attributes2,children),processedAttributes=__spreadValues({},attributes2);return delete processedAttributes.children,typeof jsxTag=="string"?handleStringTag(jsxTag,processedAttributes,processedChildren):handleFunctionTag(jsxTag,processedAttributes,processedChildren)}__name(h,"h");function Fragment(children){const fragment=document.createDocumentFragment();return appendChildren(fragment,void 0,children),fragment}__name(Fragment,"Fragment");function render(container,Component,params,children){const element=h(Component,__spreadValues({},params),children);return container.append(element),element}__name(render,"render");function hydrate(Component,params,children){isHydrating.value=!0;const element=h(Component,__spreadValues({},params),children);return isHydrating.value=!1,element}__name(hydrate,"hydrate");exports.Fragment=Fragment;exports.activeComponent=activeComponent;exports.h=h;exports.hydrate=hydrate;exports.indexMap=indexMap;exports.render=render;
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty,__defProps=Object.defineProperties;var __getOwnPropDescs=Object.getOwnPropertyDescriptors;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __typeError=msg=>{throw TypeError(msg)};var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method);const Store=require("./Store-BP8tuWzQ.cjs"),attributes=require("./attributes-BADnRZpK.cjs"),string=require("./string-Bx5N38JG.cjs"),morph=require("./morph-CsmERL3V.cjs"),object=require("./object-DTY_W6xG.cjs");require("construct-style-sheets-polyfill");const intersector_index=require("./index-BrasTsja.cjs"),connector_index=require("./connector/index.cjs"),DerivedArray=require("./DerivedArray-0qZFAKZ4.cjs");require("./css-value-parser/index.cjs");require("./window-resizer/index.cjs");require("./element-resizer/index.cjs");const activeComponent={current:null};let previousComponent=null;const componentElementLoadingTypes=["idle","load","visible","constructor","connect"];var _loadCallback,_connectCallbacks,_disconnectCallbacks,_loadingType,_idleId,_windowLoadListener,_idleListener,_intersectionListener,_ComponentElement_instances,connect_fn;const _ComponentElement=class _ComponentElement extends HTMLElement{constructor(){super();__privateAdd(this,_ComponentElement_instances);__privateAdd(this,_loadCallback);__privateAdd(this,_connectCallbacks,[]);__privateAdd(this,_disconnectCallbacks,[]);__privateAdd(this,_loadingType,"idle");__privateAdd(this,_idleId);__privateAdd(this,_windowLoadListener,__name(()=>{window.removeEventListener("load",__privateGet(this,_windowLoadListener)),__privateGet(this,_loadingType)==="load"&&__privateMethod(this,_ComponentElement_instances,connect_fn).call(this)},"#windowLoadListener"));__privateAdd(this,_idleListener,__name(()=>{__privateSet(this,_idleId,void 0),__privateGet(this,_loadingType)==="idle"&&__privateMethod(this,_ComponentElement_instances,connect_fn).call(this)},"#idleListener"));__privateAdd(this,_intersectionListener,__name(entry=>{entry.isIntersecting&&(intersector_index.intersector.unsubscribe(__privateGet(this,_intersectionListener)),__privateGet(this,_loadingType)==="visible"&&__privateMethod(this,_ComponentElement_instances,connect_fn).call(this))},"#intersectionListener"));previousComponent=activeComponent.current,activeComponent.current=this}addLoadCallback(callback){this.hasAttribute("loading")&&componentElementLoadingTypes.includes(this.getAttribute("loading"))?__privateSet(this,_loadingType,this.getAttribute("loading")):__privateSet(this,_loadingType,"constructor"),__privateSet(this,_loadCallback,callback),__privateGet(this,_loadingType)==="constructor"&&__privateGet(this,_loadCallback).call(this)}addConnectCallback(callback){__privateGet(this,_connectCallbacks).push(callback)}addDisconnectCallback(callback){__privateGet(this,_disconnectCallbacks).push(callback)}connectedCallback(){const windowLoadSetup=__name(()=>{document.readyState==="complete"?__privateGet(this,_windowLoadListener).call(this):window.addEventListener("load",__privateGet(this,_windowLoadListener))},"windowLoadSetup");__privateGet(this,_loadingType)==="connect"||__privateGet(this,_loadingType)==="constructor"?__privateMethod(this,_ComponentElement_instances,connect_fn).call(this):__privateGet(this,_loadingType)==="load"?windowLoadSetup():__privateGet(this,_loadingType)==="idle"?window.requestIdleCallback?__privateSet(this,_idleId,window.requestIdleCallback(__privateGet(this,_idleListener))):windowLoadSetup():__privateGet(this,_loadingType)==="visible"&&intersector_index.intersector.subscribe(this,__privateGet(this,_intersectionListener)),activeComponent.current===this&&(activeComponent.current=previousComponent)}disconnectedCallback(){__privateGet(this,_disconnectCallbacks).forEach(callback=>{callback(this)}),__privateSet(this,_connectCallbacks,[]),__privateSet(this,_disconnectCallbacks,[]),activeComponent.current===this&&(activeComponent.current=previousComponent),window.removeEventListener("load",__privateGet(this,_windowLoadListener)),window.cancelIdleCallback&&__privateGet(this,_idleId)&&window.cancelIdleCallback(__privateGet(this,_idleId)),intersector_index.intersector.unsubscribe(__privateGet(this,_intersectionListener))}};_loadCallback=new WeakMap,_connectCallbacks=new WeakMap,_disconnectCallbacks=new WeakMap,_loadingType=new WeakMap,_idleId=new WeakMap,_windowLoadListener=new WeakMap,_idleListener=new WeakMap,_intersectionListener=new WeakMap,_ComponentElement_instances=new WeakSet,connect_fn=__name(function(){var _a;activeComponent.current=this,this.querySelectorAll("[data-fallback]").forEach(el=>{el.remove()}),__privateGet(this,_loadingType)!=="constructor"&&((_a=__privateGet(this,_loadCallback))==null||_a.call(this)),__privateGet(this,_connectCallbacks).forEach(callback=>{const unsub=callback(this);unsub&&__privateGet(this,_disconnectCallbacks).push(unsub)}),activeComponent.current===this&&(activeComponent.current=previousComponent)},"#connect"),__name(_ComponentElement,"ComponentElement");let ComponentElement=_ComponentElement;function subscribeToStore(element,store,callback){const unsubscribe=store.subscribe(e=>{callback(e)});connector_index.connector.subscribe(element,{disconnectCallback:__name(()=>{unsubscribe()},"disconnectCallback"),maxWaitSec:20,unsubscribeAfterDisconnect:!0})}__name(subscribeToStore,"subscribeToStore");function setClassAttribute(element,classes){classes&&(classes instanceof Store.Store?subscribeToStore(element,classes,e=>{e.previous&&element.classList.remove(e.previous.toString()),e.current&&element.classList.add(e.current.toString())}):typeof classes=="object"&&!Array.isArray(classes)?Object.entries(classes).forEach(([key,value])=>{value instanceof Store.Store?subscribeToStore(element,value,e=>{element.classList.toggle(key,!!e.current)}):value&&element.classList.add(key)}):Array.isArray(classes)?classes.forEach(item=>{typeof item=="string"?element.classList.add(item):setClassAttribute(element,item)}):classes.toString().split(" ").map(v=>element.classList.add(v.trim())))}__name(setClassAttribute,"setClassAttribute");function setStyleAttribute(element,value){value&&(typeof value=="object"?Object.entries(value).forEach(([key,value2])=>{value2 instanceof Store.Store?subscribeToStore(element,value2,e=>{var _a;element.style[key]=(_a=e.current)==null?void 0:_a.toString()}):(typeof value2=="number"||typeof value2=="string"||typeof value2=="boolean")&&(element.style[key]=value2.toString())}):typeof value=="string"&&(element.style=value))}__name(setStyleAttribute,"setStyleAttribute");function setAttribute(element,key,value){key==="ref"&&value?Array.isArray(value)?value.forEach(v=>{typeof v=="object"&&"value"in v&&(v.value=element)}):typeof value=="object"&&"value"in value&&(value.value=element):key==="className"||key==="class"?setClassAttribute(element,value):key==="style"?setStyleAttribute(element,value):key==="setHtml"&&value!=null?element.innerHTML=value:typeof value=="number"?key==="tabIndex"?element.setAttribute("tabindex",value.toString()):setAttribute(element,key,value.toString()):typeof value=="string"?key==="htmlFor"?element.setAttribute("for",value):element.setAttribute(key,value):typeof value=="boolean"?value?element.setAttribute(key,""):element.removeAttribute(key):value instanceof Store.Store&&subscribeToStore(element,value,e=>{key in element?element[key]=e.current:setAttribute(element,key,e.current)})}__name(setAttribute,"setAttribute");function setAttributes(ele,attributes2){for(const[key,value]of Object.entries(attributes2!=null?attributes2:{}))typeof value=="function"&&key.startsWith("on")?ele.addEventListener(string.uncapitalize(key.replace("on","")),value):setAttribute(ele,key,value)}__name(setAttributes,"setAttributes");function createElement(tag,isSVG){return tag==="svg"?document.createElementNS("http://www.w3.org/2000/svg","svg"):isSVG?document.createElementNS("http://www.w3.org/2000/svg",tag):document.createElement(tag)}__name(createElement,"createElement");function filterChildren(children){const filtered=[];return(Array.isArray(children)?children:[children]).forEach(child=>{child!=null&&(typeof child=="number"?filtered.push(child.toString()):Array.isArray(child)?child.forEach(c=>{filtered.push(...filterChildren(c))}):filtered.push(child))}),filtered}__name(filterChildren,"filterChildren");function hydrateTextNode(element,newChild,index){const existingChild=element.childNodes[index];existingChild&&existingChild.nodeType===Node.TEXT_NODE?existingChild.textContent!==String(newChild)&&(console.warn(`Hydration text mismatch: expected "${newChild}", got "${existingChild.textContent}"`),existingChild.textContent=String(newChild)):newChild!=null&&newChild!==""&&element.insertBefore(document.createTextNode(String(newChild)),element.childNodes[index]||null)}__name(hydrateTextNode,"hydrateTextNode");function storeChildren(element,store){const currentChildNodes=[...element.childNodes].filter(node=>node.__storeId===store.id),newChildren=store.current,newChildrenArray=Array.isArray(newChildren)?newChildren:[newChildren],newNodes=[];if(newChildrenArray.forEach(newChild=>{let newNode=null;typeof newChild=="boolean"||typeof newChild=="number"||typeof newChild=="string"?newNode=document.createTextNode(newChild.toString()):newChild instanceof Node&&(newNode=newChild),newNode&&(newNode.__storeId=store.id,newNodes.push(newNode))}),store instanceof DerivedArray.DerivedKeyedArray){const nodesToStay=[];newNodes.forEach((newNode,i)=>{const oldNode=currentChildNodes.find(oldNode2=>oldNode2.__key===newNode.__key);oldNode?oldNode.isEqualNode(newNode)?nodesToStay.push(oldNode):(oldNode.replaceWith(newNode),nodesToStay.push(newNode)):(nodesToStay.push(newNode),element.appendChild(newNode))}),currentChildNodes.forEach(currentNode=>{nodesToStay.includes(currentNode)||currentNode.remove()})}else newNodes.forEach((node,i)=>{var _a;const founded=currentChildNodes[i];if(founded)founded.isEqualNode(node)||(founded.replaceWith(node),currentChildNodes[i]=node);else{const lastChildNode=currentChildNodes[currentChildNodes.length-1];lastChildNode?(_a=lastChildNode.parentNode)==null||_a.insertBefore(node,lastChildNode.nextSibling):element.appendChild(node)}}),currentChildNodes.slice(newNodes.length).forEach(node=>{node.remove()})}__name(storeChildren,"storeChildren");const _Props=class _Props{constructor(tag,attributes2,children){this.tag=tag,this.attributes=attributes2,this.children=children}};__name(_Props,"Props");let Props=_Props;const _ComponentProps=class _ComponentProps extends Props{};__name(_ComponentProps,"ComponentProps");let ComponentProps=_ComponentProps;const _ElementProps=class _ElementProps extends Props{};__name(_ElementProps,"ElementProps");let ElementProps=_ElementProps;const _HeadProps=class _HeadProps extends Props{};__name(_HeadProps,"HeadProps");let HeadProps=_HeadProps;function appendChildren(element,attributes2,children,isSVG=!1){const filteredChildren=filterChildren(children);setAttributes(element,attributes2),filteredChildren.forEach((child,index)=>{handleChild(element,child,index,isSVG)})}__name(appendChildren,"appendChildren");function handleChild(element,child,index,isSVG){child instanceof Store.Store?handleStoreChild(element,child):child instanceof ComponentProps?handleComponentProps(element,child):child instanceof ElementProps?handleElementProps(element,child,index,isSVG):child instanceof HeadProps?handleHeadProps(child):handleTextNode(element,child,index)}__name(handleChild,"handleChild");function handleStoreChild(element,child){subscribeToStore(element,child,()=>{storeChildren(element,child)})}__name(handleStoreChild,"handleStoreChild");function handleComponentProps(element,child){child.tag==="shadow"&&element.shadowRoot?appendChildren(element.shadowRoot,child.attributes,child.children):appendChildren(element,child.attributes,child.children)}__name(handleComponentProps,"handleComponentProps");function handleElementProps(element,child,index,isSVG){let childElement=null;if(isHydrating.value){const existingChild=element.children[index];(existingChild==null?void 0:existingChild.nodeName.toLowerCase())===child.tag?(childElement=existingChild,appendChildren(childElement,child.attributes,child.children,isSVG)):(childElement=createElement(child.tag,isSVG),appendChildren(childElement,child.attributes,child.children,isSVG),element.append(childElement))}else childElement=createElement(child.tag,isSVG),appendChildren(childElement,child.attributes,child.children,isSVG),element.append(childElement)}__name(handleElementProps,"handleElementProps");function handleHeadProps(child){const headElement=document.createElement(child.tag);appendChildren(headElement,child.attributes,child.children);const patches=morph.diff(document.head,headElement);morph.patch(document.head,patches)}__name(handleHeadProps,"handleHeadProps");function handleTextNode(element,child,index){isHydrating.value?hydrateTextNode(element,child,index):element.append(child)}__name(handleTextNode,"handleTextNode");function processChildren(attributes2,children){let result=children.filter(Boolean).length?children:attributes2==null?void 0:attributes2.children;return result?result.flat(2):[]}__name(processChildren,"processChildren");function handleStringTag(tag,attributes2,children){switch(tag){case"component":case"shadow":return new ComponentProps(tag,attributes2,children);case"head":return new HeadProps(tag,attributes2,children);default:return new ElementProps(tag,attributes2,children)}}__name(handleStringTag,"handleStringTag");function handleFunctionTag(jsxTag,attributes2,children){return object.isESClass(jsxTag)?createClassElement(jsxTag,attributes2,children):jsxTag===Fragment?Fragment(children):jsxTag.template?jsxTag(__spreadValues({},attributes2)):createCustomElement(jsxTag,attributes2,children)}__name(handleFunctionTag,"handleFunctionTag");function createClassElement(jsxTag,attributes2,children){const element=new jsxTag;return appendChildren(element,attributes2,children),element}__name(createClassElement,"createClassElement");function createCustomElement(jsxTag,attributes2,children){const name=jsxTag.define||`e-${string.camelToKebab(jsxTag.name)}`,Constructor=getOrDefineCustomElement(name,jsxTag,attributes2);if(attributes2!=null&&attributes2.__onlyDefine)return;const id=generateElementId(jsxTag.name,attributes2),element=getOrCreateElement(name,id,Constructor);return fillComponentElement(element,jsxTag,attributes2,children),element}__name(createCustomElement,"createCustomElement");function getOrDefineCustomElement(name,jsxTag,attributes$1){var _a;let Constructor=customElements.get(name);return Constructor||(Constructor=(_a=class extends ComponentElement{constructor(){super(),attributes$1!=null&&attributes$1.__onlyDefine&&this.addLoadCallback(()=>fillComponentElement(this,jsxTag,attributes.getElementAttributesAdvanced(this),[]))}},__name(_a,"Constructor"),_a.formAssociated=jsxTag.formAssociated,_a),customElements.define(name,Constructor)),Constructor}__name(getOrDefineCustomElement,"getOrDefineCustomElement");function generateElementId(tagName,attributes2){if(attributes2!=null&&attributes2.__hydrationId)return attributes2.__hydrationId;const index=(indexMap.get(tagName)||0)+1;return indexMap.set(tagName,index),`${tagName}-${index}`}__name(generateElementId,"generateElementId");function getOrCreateElement(name,id,Constructor){if(isHydrating.value){const selector=`${name}[data-id="${id}"]`,existingElement=document.querySelector(selector);if(existingElement&&existingElement instanceof Constructor)return existingElement}const element=new Constructor;return element.setAttribute("data-id",id),element}__name(getOrCreateElement,"getOrCreateElement");function fillComponentElement(element,jsxTag,attributes2,children){const props=__spreadProps(__spreadValues({},attributes2),{children}),setHtml=props.setHtml;delete props.setHtml;const result=jsxTag(props);result instanceof ElementProps?appendChildren(element,{setHtml},result):result instanceof ComponentProps&&appendChildren(element,__spreadProps(__spreadValues({},result.attributes),{setHtml}),result.children)}__name(fillComponentElement,"fillComponentElement");const isHydrating={value:!1},indexMap=new Map;function h(jsxTag,attributes2,...children){const processedChildren=processChildren(attributes2,children),processedAttributes=__spreadValues({},attributes2);return delete processedAttributes.children,typeof jsxTag=="string"?handleStringTag(jsxTag,processedAttributes,processedChildren):handleFunctionTag(jsxTag,processedAttributes,processedChildren)}__name(h,"h");function Fragment(children){const fragment=document.createDocumentFragment();return appendChildren(fragment,void 0,children),fragment}__name(Fragment,"Fragment");function render(container,Component,params,children){const element=h(Component,__spreadValues({},params),children);return container.append(element),element}__name(render,"render");function hydrate(Component,params,children){isHydrating.value=!0;const element=h(Component,__spreadValues({},params),children);return isHydrating.value=!1,element}__name(hydrate,"hydrate");exports.Fragment=Fragment;exports.activeComponent=activeComponent;exports.h=h;exports.hydrate=hydrate;exports.indexMap=indexMap;exports.render=render;
|
|
@@ -18,7 +18,7 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
|
|
|
18
18
|
import { S as Store } from "./Store-LDYxlJNu.js";
|
|
19
19
|
import { g as getElementAttributesAdvanced } from "./attributes-FObgMNCf.js";
|
|
20
20
|
import { u as uncapitalize, c as camelToKebab } from "./string-Ct-dy_cs.js";
|
|
21
|
-
import { d as diff, p as patch } from "./morph-
|
|
21
|
+
import { d as diff, p as patch } from "./morph-DwKYrG4g.js";
|
|
22
22
|
import { i as isESClass } from "./object-CiIdEmJx.js";
|
|
23
23
|
import "construct-style-sheets-polyfill";
|
|
24
24
|
import { i as intersector } from "./index-Z2Lgb7xU.js";
|
package/lib/router/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty,__defProps=Object.defineProperties;var __getOwnPropDescs=Object.getOwnPropertyDescriptors;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __typeError=msg=>{throw TypeError(msg)};var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method);var __privateWrapper=(obj,member,setter,getter)=>({set _(value){__privateSet(obj,member,value,setter)},get _(){return __privateGet(obj,member,getter)}});var __async=(__this,__arguments,generator)=>new Promise((resolve,reject)=>{var fulfilled=value=>{try{step(generator.next(value))}catch(e){reject(e)}},rejected=value=>{try{step(generator.throw(value))}catch(e){reject(e)}},step=x=>x.done?resolve(x.value):Promise.resolve(x.value).then(fulfilled,rejected);step((generator=generator.apply(__this,__arguments)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const history_index=require("../history/index.cjs"),LocalLinks=require("../LocalLinks-Ct89SJQ9.cjs"),PageAnnouncerElement=require("../PageAnnouncerElement-DreveHSN.cjs"),PageScroll=require("../PageScroll-xuHDTIoC.cjs");require("construct-style-sheets-polyfill");require("../index-BrasTsja.cjs");const url=require("../url-Dzvsir_7.cjs"),urlpatternPolyfill=require("urlpattern-polyfill"),render=require("../render-C3udrJln.cjs"),object=require("../object-DTY_W6xG.cjs");var _pattern,_module,_urlPattern,_elementConstructor,_elementInstance,_isActive,_nestTarget,_mutationObserver,_permanentHeadNodes,_temporalHeadNodes,_Route_instances,initializeRouteModule_fn,appendPermanentHeadNodes_fn,renderRouteComponent_fn,findNestTarget_fn,cleanup_fn,removeTemporalHeadNodes_fn,handleHeadMutations_fn,waitForHeadNodesLoad_fn,isLoadableNode_fn,_instanceReplaceListener;const _Route=class _Route{constructor(pattern,module2){__privateAdd(this,_Route_instances);__privateAdd(this,_pattern);__privateAdd(this,_module);__privateAdd(this,_urlPattern);__privateAdd(this,_elementConstructor,null);__privateAdd(this,_elementInstance,null);__privateAdd(this,_isActive,!1);__privateAdd(this,_nestTarget,null);__privateAdd(this,_mutationObserver);__privateAdd(this,_permanentHeadNodes,[]);__privateAdd(this,_temporalHeadNodes,[]);__privateAdd(this,_instanceReplaceListener,__name(e=>{__privateGet(this,_elementInstance).removeEventListener("__hmrInstanceReplace",__privateGet(this,_instanceReplaceListener)),__privateSet(this,_elementInstance,e.detail.element),__privateGet(this,_elementInstance).addEventListener("__hmrInstanceReplace",__privateGet(this,_instanceReplaceListener))},"#instanceReplaceListener"));__privateSet(this,_pattern,pattern),__privateSet(this,_module,module2),__privateSet(this,_urlPattern,new URLPattern({pathname:__privateGet(this,_pattern)})),__privateSet(this,_mutationObserver,new MutationObserver(__privateMethod(this,_Route_instances,handleHeadMutations_fn).bind(this)))}get pattern(){return __privateGet(this,_pattern)}get isActive(){return __privateGet(this,_isActive)}get element(){return __privateGet(this,_elementInstance)}get nest(){return __privateGet(this,_nestTarget)}testPathname(pathname){return __privateGet(this,_urlPattern).test({pathname})}render(container,url2){return __async(this,null,function*(){__privateGet(this,_mutationObserver).observe(document.head,{childList:!0,subtree:!0}),__privateGet(this,_elementConstructor)?__privateMethod(this,_Route_instances,appendPermanentHeadNodes_fn).call(this):yield __privateMethod(this,_Route_instances,initializeRouteModule_fn).call(this),yield __privateMethod(this,_Route_instances,waitForHeadNodesLoad_fn).call(this),__privateGet(this,_elementConstructor)&&(yield __privateMethod(this,_Route_instances,renderRouteComponent_fn).call(this,container,url2)),__privateGet(this,_mutationObserver).disconnect()})}close(){__privateMethod(this,_Route_instances,cleanup_fn).call(this)}};_pattern=new WeakMap,_module=new WeakMap,_urlPattern=new WeakMap,_elementConstructor=new WeakMap,_elementInstance=new WeakMap,_isActive=new WeakMap,_nestTarget=new WeakMap,_mutationObserver=new WeakMap,_permanentHeadNodes=new WeakMap,_temporalHeadNodes=new WeakMap,_Route_instances=new WeakSet,initializeRouteModule_fn=__name(function(){return __async(this,null,function*(){const content=yield __privateGet(this,_module).call(this);__privateSet(this,_temporalHeadNodes,[...__privateGet(this,_permanentHeadNodes)]),typeof content.default=="function"&&__privateSet(this,_elementConstructor,content.default)})},"#initializeRouteModule"),appendPermanentHeadNodes_fn=__name(function(){__privateGet(this,_permanentHeadNodes).forEach(node=>{document.head.appendChild(node.cloneNode(!0))})},"#appendPermanentHeadNodes"),renderRouteComponent_fn=__name(function(container,url2){return __async(this,null,function*(){var _a;const routeParams={urlPatternResult:__privateGet(this,_urlPattern).exec({pathname:url2.pathname})};object.isESClass(__privateGet(this,_elementConstructor))?(__privateSet(this,_elementInstance,new(__privateGet(this,_elementConstructor))(routeParams)),container.appendChild(__privateGet(this,_elementInstance))):__privateSet(this,_elementInstance,render.render(container,__privateGet(this,_elementConstructor),routeParams)),(_a=__privateGet(this,_elementInstance))==null||_a.addEventListener("__hmrInstanceReplace",__privateGet(this,_instanceReplaceListener)),__privateMethod(this,_Route_instances,findNestTarget_fn).call(this),__privateSet(this,_isActive,!0)})},"#renderRouteComponent"),findNestTarget_fn=__name(function(){var _a;__privateGet(this,_elementInstance)&&__privateSet(this,_nestTarget,__privateGet(this,_elementInstance).querySelector("[data-nest]")||((_a=__privateGet(this,_elementInstance).shadowRoot)==null?void 0:_a.querySelector("[data-nest]"))||__privateGet(this,_elementInstance).shadowRoot||__privateGet(this,_elementInstance))},"#findNestTarget"),cleanup_fn=__name(function(){__privateGet(this,_mutationObserver).disconnect(),__privateGet(this,_elementInstance)&&(__privateGet(this,_elementInstance).removeEventListener("__hmrInstanceReplace",__privateGet(this,_instanceReplaceListener)),__privateGet(this,_elementInstance).remove()),__privateSet(this,_isActive,!1),__privateMethod(this,_Route_instances,removeTemporalHeadNodes_fn).call(this)},"#cleanup"),removeTemporalHeadNodes_fn=__name(function(){__privateGet(this,_temporalHeadNodes).forEach(node=>{node.parentNode===document.head&&document.head.removeChild(node)}),__privateSet(this,_temporalHeadNodes,[])},"#removeTemporalHeadNodes"),handleHeadMutations_fn=__name(function(mutations){mutations.forEach(mutation=>{mutation.addedNodes.forEach(node=>{__privateGet(this,_elementConstructor)?__privateGet(this,_temporalHeadNodes).push(node):__privateGet(this,_permanentHeadNodes).push(node)})})},"#handleHeadMutations"),waitForHeadNodesLoad_fn=__name(function(){return __async(this,null,function*(){const loadableNodes=__privateGet(this,_permanentHeadNodes).filter(__privateMethod(this,_Route_instances,isLoadableNode_fn));yield Promise.all(loadableNodes.map(node=>new Promise(resolve=>{__privateMethod(this,_Route_instances,isLoadableNode_fn).call(this,node)?node.onload=()=>resolve():resolve()})))})},"#waitForHeadNodesLoad"),isLoadableNode_fn=__name(function(node){return node instanceof HTMLElement&&(node.tagName==="STYLE"||node.tagName==="SCRIPT"||node.tagName==="LINK")},"#isLoadableNode"),_instanceReplaceListener=new WeakMap,__name(_Route,"Route");let Route=_Route;globalThis.URLPattern=urlpatternPolyfill.URLPattern;var _options,_scroll,_links,_history,_announcerElement,_updateId,_routes,_lastRoute,_Router_instances,runPreprocessor_fn,categorizeRoutes_fn,closeOldRoutes_fn,renderNewRoutes_fn,sortRoutesByPathDepth_fn;const _Router=class _Router{constructor(options){__privateAdd(this,_Router_instances);__privateAdd(this,_options,null);__privateAdd(this,_scroll,null);__privateAdd(this,_links,null);__privateAdd(this,_history,null);__privateAdd(this,_announcerElement,null);__privateAdd(this,_updateId,0);__privateAdd(this,_routes,[]);__privateAdd(this,_lastRoute,null);__privateSet(this,_options,__spreadProps(__spreadValues({},options),{rootElement:(options==null?void 0:options.rootElement)||document.body,base:url.normalizeBase(options==null?void 0:options.base)})),__privateSet(this,_announcerElement,new PageAnnouncerElement.PageAnnouncerElement),__privateSet(this,_scroll,new PageScroll.PageScroll(__privateGet(this,_options).scrollSelector)),__privateGet(this,_scroll).update(),__privateSet(this,_links,new LocalLinks.LocalLinks({base:__privateGet(this,_options).base,trailingSlash:__privateGet(this,_options).trailingSlash,includeAnchor:options==null?void 0:options.includeAnchor,onClick:__name((url2,options2)=>{try{this.navigate(url2,options2)}catch(e){window.location.assign(url2)}},"onClick")})),__privateGet(this,_links).update(),__privateSet(this,_history,new history_index.History({onPop:__name(url2=>{this.navigate(url2)},"onPop")}))}history(){return __privateGet(this,_history)}get scroll(){return scroll}get routes(){return __privateGet(this,_routes)}run(){__privateMethod(this,_Router_instances,sortRoutesByPathDepth_fn).call(this),this.navigate(new URL(location.href),{revalidate:!0})}defineRoute(pattern,module2){const route=new Route(pattern,module2);__privateGet(this,_routes).push(route)}navigate(url$1,options){return __async(this,null,function*(){var _a,_b,_c,_d,_e,_f;const isBack=__privateGet(this,_history).isBack,updateId=++__privateWrapper(this,_updateId)._;let fullUrl=url.normalizeURL(url$1,{base:__privateGet(this,_options).base,trailingSlash:__privateGet(this,_options).trailingSlash});if(__privateGet(this,_options).urlModifier&&(fullUrl=__privateGet(this,_options).urlModifier(fullUrl)),!(yield __privateMethod(this,_Router_instances,runPreprocessor_fn).call(this,fullUrl))||__privateGet(this,_updateId)!==updateId||(yield(_b=(_a=__privateGet(this,_options)).beforeNavigation)==null?void 0:_b.call(_a),__privateGet(this,_updateId)!==updateId))return;const{activeRoutes,newRoutes,oldRoutes,keepRoutes}=__privateMethod(this,_Router_instances,categorizeRoutes_fn).call(this,fullUrl);__privateSet(this,_lastRoute,(_c=keepRoutes[keepRoutes.length-1])!=null?_c:null),isBack||(__privateGet(this,_history).push(fullUrl),((_d=options==null?void 0:options.keepScrollPosition)==null||_d)&&__privateGet(this,_scroll).element.scrollTo({top:0,behavior:"instant"})),__privateGet(this,_announcerElement).create(document,fullUrl.pathname),__privateGet(this,_options).viewTransition&&document.startViewTransition?yield document.startViewTransition(()=>__privateMethod(this,_Router_instances,renderNewRoutes_fn).call(this,oldRoutes,newRoutes,fullUrl)).finished:yield __privateMethod(this,_Router_instances,renderNewRoutes_fn).call(this,oldRoutes,newRoutes,fullUrl),__privateGet(this,_scroll).update(),__privateGet(this,_links).update(),__privateGet(this,_announcerElement).done(),yield(_f=(_e=__privateGet(this,_options)).afterNavigation)==null?void 0:_f.call(_e)})}};_options=new WeakMap,_scroll=new WeakMap,_links=new WeakMap,_history=new WeakMap,_announcerElement=new WeakMap,_updateId=new WeakMap,_routes=new WeakMap,_lastRoute=new WeakMap,_Router_instances=new WeakSet,runPreprocessor_fn=__name(function(url2){return __async(this,null,function*(){if(!__privateGet(this,_options).preprocessor)return!0;try{return yield new Promise((resolve,reject)=>{var _a,_b;(_b=(_a=__privateGet(this,_options)).preprocessor)==null||_b.call(_a,{url:url2,resolve,reject})}),!0}catch(error){return console.error(error!=null?error:"Route change canceled"),!1}})},"#runPreprocessor"),categorizeRoutes_fn=__name(function(url2){let leaf=url2.pathname.replace(__privateGet(this,_options).base,"");leaf.startsWith("/")||(leaf=`/${leaf}`);const activeRoutes=__privateGet(this,_routes).filter(route=>route.isActive);return{activeRoutes,newRoutes:__privateGet(this,_routes).filter(route=>!activeRoutes.includes(route)&&route.testPathname(leaf)),oldRoutes:activeRoutes.filter(route=>!route.testPathname(leaf)),keepRoutes:activeRoutes.filter(route=>route.testPathname(leaf))}},"#categorizeRoutes"),closeOldRoutes_fn=__name(function(routes){routes.forEach(route=>route.close())},"#closeOldRoutes"),renderNewRoutes_fn=__name(function(oldRoutes,routes,url2){return __async(this,null,function*(){var _a,_b;__privateMethod(this,_Router_instances,closeOldRoutes_fn).call(this,oldRoutes);for(const route of routes){const target=(_b=(_a=__privateGet(this,_lastRoute))==null?void 0:_a.nest)!=null?_b:__privateGet(this,_options).rootElement;yield route.render(target,url2),__privateSet(this,_lastRoute,route)}})},"#renderNewRoutes"),sortRoutesByPathDepth_fn=__name(function(){__privateGet(this,_routes).sort((a,b)=>{const depthA=a.pattern.split("/").length,depthB=b.pattern.split("/").length;return depthA-depthB})},"#sortRoutesByPathDepth"),__name(_Router,"Router");let Router=_Router;exports.Router=Router;
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty,__defProps=Object.defineProperties;var __getOwnPropDescs=Object.getOwnPropertyDescriptors;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __typeError=msg=>{throw TypeError(msg)};var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method);var __privateWrapper=(obj,member,setter,getter)=>({set _(value){__privateSet(obj,member,value,setter)},get _(){return __privateGet(obj,member,getter)}});var __async=(__this,__arguments,generator)=>new Promise((resolve,reject)=>{var fulfilled=value=>{try{step(generator.next(value))}catch(e){reject(e)}},rejected=value=>{try{step(generator.throw(value))}catch(e){reject(e)}},step=x=>x.done?resolve(x.value):Promise.resolve(x.value).then(fulfilled,rejected);step((generator=generator.apply(__this,__arguments)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const history_index=require("../history/index.cjs"),LocalLinks=require("../LocalLinks-aJx_34WY.cjs"),PageAnnouncerElement=require("../PageAnnouncerElement-DreveHSN.cjs"),PageScroll=require("../PageScroll-xuHDTIoC.cjs");require("construct-style-sheets-polyfill");require("../index-BrasTsja.cjs");const url=require("../url-Dzvsir_7.cjs"),urlpatternPolyfill=require("urlpattern-polyfill"),render=require("../render-DCFa7iWE.cjs"),object=require("../object-DTY_W6xG.cjs");var _pattern,_module,_urlPattern,_elementConstructor,_elementInstance,_isActive,_nestTarget,_mutationObserver,_permanentHeadNodes,_temporalHeadNodes,_Route_instances,initializeRouteModule_fn,appendPermanentHeadNodes_fn,renderRouteComponent_fn,findNestTarget_fn,cleanup_fn,removeTemporalHeadNodes_fn,handleHeadMutations_fn,waitForHeadNodesLoad_fn,isLoadableNode_fn,_instanceReplaceListener;const _Route=class _Route{constructor(pattern,module2){__privateAdd(this,_Route_instances);__privateAdd(this,_pattern);__privateAdd(this,_module);__privateAdd(this,_urlPattern);__privateAdd(this,_elementConstructor,null);__privateAdd(this,_elementInstance,null);__privateAdd(this,_isActive,!1);__privateAdd(this,_nestTarget,null);__privateAdd(this,_mutationObserver);__privateAdd(this,_permanentHeadNodes,[]);__privateAdd(this,_temporalHeadNodes,[]);__privateAdd(this,_instanceReplaceListener,__name(e=>{__privateGet(this,_elementInstance).removeEventListener("__hmrInstanceReplace",__privateGet(this,_instanceReplaceListener)),__privateSet(this,_elementInstance,e.detail.element),__privateGet(this,_elementInstance).addEventListener("__hmrInstanceReplace",__privateGet(this,_instanceReplaceListener))},"#instanceReplaceListener"));__privateSet(this,_pattern,pattern),__privateSet(this,_module,module2),__privateSet(this,_urlPattern,new URLPattern({pathname:__privateGet(this,_pattern)})),__privateSet(this,_mutationObserver,new MutationObserver(__privateMethod(this,_Route_instances,handleHeadMutations_fn).bind(this)))}get pattern(){return __privateGet(this,_pattern)}get isActive(){return __privateGet(this,_isActive)}get element(){return __privateGet(this,_elementInstance)}get nest(){return __privateGet(this,_nestTarget)}testPathname(pathname){return __privateGet(this,_urlPattern).test({pathname})}render(container,url2){return __async(this,null,function*(){__privateGet(this,_mutationObserver).observe(document.head,{childList:!0,subtree:!0}),__privateGet(this,_elementConstructor)?__privateMethod(this,_Route_instances,appendPermanentHeadNodes_fn).call(this):yield __privateMethod(this,_Route_instances,initializeRouteModule_fn).call(this),yield __privateMethod(this,_Route_instances,waitForHeadNodesLoad_fn).call(this),__privateGet(this,_elementConstructor)&&(yield __privateMethod(this,_Route_instances,renderRouteComponent_fn).call(this,container,url2)),__privateGet(this,_mutationObserver).disconnect()})}close(){__privateMethod(this,_Route_instances,cleanup_fn).call(this)}};_pattern=new WeakMap,_module=new WeakMap,_urlPattern=new WeakMap,_elementConstructor=new WeakMap,_elementInstance=new WeakMap,_isActive=new WeakMap,_nestTarget=new WeakMap,_mutationObserver=new WeakMap,_permanentHeadNodes=new WeakMap,_temporalHeadNodes=new WeakMap,_Route_instances=new WeakSet,initializeRouteModule_fn=__name(function(){return __async(this,null,function*(){const content=yield __privateGet(this,_module).call(this);__privateSet(this,_temporalHeadNodes,[...__privateGet(this,_permanentHeadNodes)]),typeof content.default=="function"&&__privateSet(this,_elementConstructor,content.default)})},"#initializeRouteModule"),appendPermanentHeadNodes_fn=__name(function(){__privateGet(this,_permanentHeadNodes).forEach(node=>{document.head.appendChild(node.cloneNode(!0))})},"#appendPermanentHeadNodes"),renderRouteComponent_fn=__name(function(container,url2){return __async(this,null,function*(){var _a;const routeParams={urlPatternResult:__privateGet(this,_urlPattern).exec({pathname:url2.pathname})};object.isESClass(__privateGet(this,_elementConstructor))?(__privateSet(this,_elementInstance,new(__privateGet(this,_elementConstructor))(routeParams)),container.appendChild(__privateGet(this,_elementInstance))):__privateSet(this,_elementInstance,render.render(container,__privateGet(this,_elementConstructor),routeParams)),(_a=__privateGet(this,_elementInstance))==null||_a.addEventListener("__hmrInstanceReplace",__privateGet(this,_instanceReplaceListener)),__privateMethod(this,_Route_instances,findNestTarget_fn).call(this),__privateSet(this,_isActive,!0)})},"#renderRouteComponent"),findNestTarget_fn=__name(function(){var _a;__privateGet(this,_elementInstance)&&__privateSet(this,_nestTarget,__privateGet(this,_elementInstance).querySelector("[data-nest]")||((_a=__privateGet(this,_elementInstance).shadowRoot)==null?void 0:_a.querySelector("[data-nest]"))||__privateGet(this,_elementInstance).shadowRoot||__privateGet(this,_elementInstance))},"#findNestTarget"),cleanup_fn=__name(function(){__privateGet(this,_mutationObserver).disconnect(),__privateGet(this,_elementInstance)&&(__privateGet(this,_elementInstance).removeEventListener("__hmrInstanceReplace",__privateGet(this,_instanceReplaceListener)),__privateGet(this,_elementInstance).remove()),__privateSet(this,_isActive,!1),__privateMethod(this,_Route_instances,removeTemporalHeadNodes_fn).call(this)},"#cleanup"),removeTemporalHeadNodes_fn=__name(function(){__privateGet(this,_temporalHeadNodes).forEach(node=>{node.parentNode===document.head&&document.head.removeChild(node)}),__privateSet(this,_temporalHeadNodes,[])},"#removeTemporalHeadNodes"),handleHeadMutations_fn=__name(function(mutations){mutations.forEach(mutation=>{mutation.addedNodes.forEach(node=>{__privateGet(this,_elementConstructor)?__privateGet(this,_temporalHeadNodes).push(node):__privateGet(this,_permanentHeadNodes).push(node)})})},"#handleHeadMutations"),waitForHeadNodesLoad_fn=__name(function(){return __async(this,null,function*(){const loadableNodes=__privateGet(this,_permanentHeadNodes).filter(__privateMethod(this,_Route_instances,isLoadableNode_fn));yield Promise.all(loadableNodes.map(node=>new Promise(resolve=>{__privateMethod(this,_Route_instances,isLoadableNode_fn).call(this,node)?node.onload=()=>resolve():resolve()})))})},"#waitForHeadNodesLoad"),isLoadableNode_fn=__name(function(node){return node instanceof HTMLElement&&(node.tagName==="STYLE"||node.tagName==="SCRIPT"||node.tagName==="LINK")},"#isLoadableNode"),_instanceReplaceListener=new WeakMap,__name(_Route,"Route");let Route=_Route;globalThis.URLPattern=urlpatternPolyfill.URLPattern;var _options,_scroll,_links,_history,_announcerElement,_updateId,_routes,_lastRoute,_Router_instances,runPreprocessor_fn,categorizeRoutes_fn,closeOldRoutes_fn,renderNewRoutes_fn,sortRoutesByPathDepth_fn;const _Router=class _Router{constructor(options){__privateAdd(this,_Router_instances);__privateAdd(this,_options,null);__privateAdd(this,_scroll,null);__privateAdd(this,_links,null);__privateAdd(this,_history,null);__privateAdd(this,_announcerElement,null);__privateAdd(this,_updateId,0);__privateAdd(this,_routes,[]);__privateAdd(this,_lastRoute,null);__privateSet(this,_options,__spreadProps(__spreadValues({},options),{rootElement:(options==null?void 0:options.rootElement)||document.body,base:url.normalizeBase(options==null?void 0:options.base)})),__privateSet(this,_announcerElement,new PageAnnouncerElement.PageAnnouncerElement),__privateSet(this,_scroll,new PageScroll.PageScroll(__privateGet(this,_options).scrollSelector)),__privateGet(this,_scroll).update(),__privateSet(this,_links,new LocalLinks.LocalLinks({base:__privateGet(this,_options).base,trailingSlash:__privateGet(this,_options).trailingSlash,includeAnchor:options==null?void 0:options.includeAnchor,onClick:__name((url2,options2)=>{try{this.navigate(url2,options2)}catch(e){window.location.assign(url2)}},"onClick")})),__privateGet(this,_links).update(),__privateSet(this,_history,new history_index.History({onPop:__name(url2=>{this.navigate(url2)},"onPop")}))}history(){return __privateGet(this,_history)}get scroll(){return scroll}get routes(){return __privateGet(this,_routes)}run(){__privateMethod(this,_Router_instances,sortRoutesByPathDepth_fn).call(this),this.navigate(new URL(location.href),{revalidate:!0})}defineRoute(pattern,module2){const route=new Route(pattern,module2);__privateGet(this,_routes).push(route)}navigate(url$1,options){return __async(this,null,function*(){var _a,_b,_c,_d,_e,_f;const isBack=__privateGet(this,_history).isBack,updateId=++__privateWrapper(this,_updateId)._;let fullUrl=url.normalizeURL(url$1,{base:__privateGet(this,_options).base,trailingSlash:__privateGet(this,_options).trailingSlash});if(__privateGet(this,_options).urlModifier&&(fullUrl=__privateGet(this,_options).urlModifier(fullUrl)),!(yield __privateMethod(this,_Router_instances,runPreprocessor_fn).call(this,fullUrl))||__privateGet(this,_updateId)!==updateId||(yield(_b=(_a=__privateGet(this,_options)).beforeNavigation)==null?void 0:_b.call(_a),__privateGet(this,_updateId)!==updateId))return;const{activeRoutes,newRoutes,oldRoutes,keepRoutes}=__privateMethod(this,_Router_instances,categorizeRoutes_fn).call(this,fullUrl);__privateSet(this,_lastRoute,(_c=keepRoutes[keepRoutes.length-1])!=null?_c:null),isBack||(__privateGet(this,_history).push(fullUrl),((_d=options==null?void 0:options.keepScrollPosition)==null||_d)&&__privateGet(this,_scroll).element.scrollTo({top:0,behavior:"instant"})),__privateGet(this,_announcerElement).create(document,fullUrl.pathname),__privateGet(this,_options).viewTransition&&document.startViewTransition?yield document.startViewTransition(()=>__privateMethod(this,_Router_instances,renderNewRoutes_fn).call(this,oldRoutes,newRoutes,fullUrl)).finished:yield __privateMethod(this,_Router_instances,renderNewRoutes_fn).call(this,oldRoutes,newRoutes,fullUrl),__privateGet(this,_scroll).update(),__privateGet(this,_links).update(),__privateGet(this,_announcerElement).done(),yield(_f=(_e=__privateGet(this,_options)).afterNavigation)==null?void 0:_f.call(_e)})}};_options=new WeakMap,_scroll=new WeakMap,_links=new WeakMap,_history=new WeakMap,_announcerElement=new WeakMap,_updateId=new WeakMap,_routes=new WeakMap,_lastRoute=new WeakMap,_Router_instances=new WeakSet,runPreprocessor_fn=__name(function(url2){return __async(this,null,function*(){if(!__privateGet(this,_options).preprocessor)return!0;try{return yield new Promise((resolve,reject)=>{var _a,_b;(_b=(_a=__privateGet(this,_options)).preprocessor)==null||_b.call(_a,{url:url2,resolve,reject})}),!0}catch(error){return console.error(error!=null?error:"Route change canceled"),!1}})},"#runPreprocessor"),categorizeRoutes_fn=__name(function(url2){let leaf=url2.pathname.replace(__privateGet(this,_options).base,"");leaf.startsWith("/")||(leaf=`/${leaf}`);const activeRoutes=__privateGet(this,_routes).filter(route=>route.isActive);return{activeRoutes,newRoutes:__privateGet(this,_routes).filter(route=>!activeRoutes.includes(route)&&route.testPathname(leaf)),oldRoutes:activeRoutes.filter(route=>!route.testPathname(leaf)),keepRoutes:activeRoutes.filter(route=>route.testPathname(leaf))}},"#categorizeRoutes"),closeOldRoutes_fn=__name(function(routes){routes.forEach(route=>route.close())},"#closeOldRoutes"),renderNewRoutes_fn=__name(function(oldRoutes,routes,url2){return __async(this,null,function*(){var _a,_b;__privateMethod(this,_Router_instances,closeOldRoutes_fn).call(this,oldRoutes);for(const route of routes){const target=(_b=(_a=__privateGet(this,_lastRoute))==null?void 0:_a.nest)!=null?_b:__privateGet(this,_options).rootElement;yield route.render(target,url2),__privateSet(this,_lastRoute,route)}})},"#renderNewRoutes"),sortRoutesByPathDepth_fn=__name(function(){__privateGet(this,_routes).sort((a,b)=>{const depthA=a.pattern.split("/").length,depthB=b.pattern.split("/").length;return depthA-depthB})},"#sortRoutesByPathDepth"),__name(_Router,"Router");let Router=_Router;exports.Router=Router;
|
package/lib/router/index.js
CHANGED
|
@@ -40,14 +40,14 @@ var __async = (__this, __arguments, generator) => new Promise((resolve, reject)
|
|
|
40
40
|
step((generator = generator.apply(__this, __arguments)).next());
|
|
41
41
|
});
|
|
42
42
|
import { History } from "../history/index.js";
|
|
43
|
-
import { L as LocalLinks } from "../LocalLinks-
|
|
43
|
+
import { L as LocalLinks } from "../LocalLinks-D1YdCbCu.js";
|
|
44
44
|
import { P as PageAnnouncerElement } from "../PageAnnouncerElement-CI048qxO.js";
|
|
45
45
|
import { P as PageScroll } from "../PageScroll-CrYJVAHA.js";
|
|
46
46
|
import "construct-style-sheets-polyfill";
|
|
47
47
|
import "../index-Z2Lgb7xU.js";
|
|
48
48
|
import { a as normalizeBase, n as normalizeURL } from "../url-BdWQTlu6.js";
|
|
49
49
|
import { URLPattern as URLPattern$1 } from "urlpattern-polyfill";
|
|
50
|
-
import { r as render } from "../render-
|
|
50
|
+
import { r as render } from "../render-GXhdK9Uz.js";
|
|
51
51
|
import { i as isESClass } from "../object-CiIdEmJx.js";
|
|
52
52
|
var _pattern, _module, _urlPattern, _elementConstructor, _elementInstance, _isActive, _nestTarget, _mutationObserver, _permanentHeadNodes, _temporalHeadNodes, _Route_instances, initializeRouteModule_fn, appendPermanentHeadNodes_fn, renderRouteComponent_fn, findNestTarget_fn, cleanup_fn, removeTemporalHeadNodes_fn, handleHeadMutations_fn, waitForHeadNodesLoad_fn, isLoadableNode_fn, _instanceReplaceListener;
|
|
53
53
|
const _Route = class _Route {
|
package/lib/spa/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty,__defProps=Object.defineProperties;var __getOwnPropDescs=Object.getOwnPropertyDescriptors;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __typeError=msg=>{throw TypeError(msg)};var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value);var __privateWrapper=(obj,member,setter,getter)=>({set _(value){__privateSet(obj,member,value,setter)},get _(){return __privateGet(obj,member,getter)}});var __async=(__this,__arguments,generator)=>new Promise((resolve,reject)=>{var fulfilled=value=>{try{step(generator.next(value))}catch(e){reject(e)}},rejected=value=>{try{step(generator.throw(value))}catch(e){reject(e)}},step=x=>x.done?resolve(x.value):Promise.resolve(x.value).then(fulfilled,rejected);step((generator=generator.apply(__this,__arguments)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const cache_index=require("../cache/index.cjs"),LocalLinks=require("../LocalLinks-
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty,__defProps=Object.defineProperties;var __getOwnPropDescs=Object.getOwnPropertyDescriptors;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __typeError=msg=>{throw TypeError(msg)};var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value);var __privateWrapper=(obj,member,setter,getter)=>({set _(value){__privateSet(obj,member,value,setter)},get _(){return __privateGet(obj,member,getter)}});var __async=(__this,__arguments,generator)=>new Promise((resolve,reject)=>{var fulfilled=value=>{try{step(generator.next(value))}catch(e){reject(e)}},rejected=value=>{try{step(generator.throw(value))}catch(e){reject(e)}},step=x=>x.done?resolve(x.value):Promise.resolve(x.value).then(fulfilled,rejected);step((generator=generator.apply(__this,__arguments)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const cache_index=require("../cache/index.cjs"),LocalLinks=require("../LocalLinks-aJx_34WY.cjs"),PageAnnouncerElement=require("../PageAnnouncerElement-DreveHSN.cjs"),PageScroll=require("../PageScroll-xuHDTIoC.cjs"),ScrollNavigator=require("../ScrollNavigator-CNKI1Iae.cjs"),historyManager=require("../historyManager-Car6P2ak.cjs"),events=require("../events-UlGk63iC.cjs"),morph=require("../morph-CsmERL3V.cjs");require("construct-style-sheets-polyfill");require("../index-BrasTsja.cjs");const url=require("../url-Dzvsir_7.cjs");var _cache,_domParser,_options,_scroll,_links,_announcerElement,_updateId,_isBack;const _SPA=class _SPA{constructor(options){__privateAdd(this,_cache,new cache_index.Cache);__privateAdd(this,_domParser,new DOMParser);__privateAdd(this,_options,null);__privateAdd(this,_scroll,null);__privateAdd(this,_links,null);__privateAdd(this,_announcerElement,null);__privateAdd(this,_updateId,0);__privateAdd(this,_isBack,!1);_SPA.instance||(_SPA.instance=this,__privateSet(this,_options,__spreadProps(__spreadValues({},options),{base:url.normalizeBase(options==null?void 0:options.base)})),__privateSet(this,_announcerElement,new PageAnnouncerElement.PageAnnouncerElement),__privateSet(this,_scroll,new PageScroll.PageScroll(__privateGet(this,_options).scrollSelector)),__privateGet(this,_scroll).update(),__privateSet(this,_links,new LocalLinks.LocalLinks({base:__privateGet(this,_options).base,trailingSlash:__privateGet(this,_options).trailingSlash,includeAnchor:options==null?void 0:options.includeAnchor,onClick:__name((url2,options2)=>{try{this.navigate(url2,options2)}catch(e){window.location.assign(url2)}},"onClick")})),__privateGet(this,_links).update(),historyManager.historyManager.addPopStateHandler(event=>{var _a,_b,_c,_d,_e,_f;(_b=(_a=event.state)==null?void 0:_a.data)!=null&&_b.popover||(_d=(_c=event.previousState)==null?void 0:_c.data)!=null&&_d.popover||(__privateSet(this,_isBack,!0),this.navigate(location.href.replace(location.origin,""),{scrollValue:((_f=(_e=event.state)==null?void 0:_e.data)==null?void 0:_f.scrollTop)||0}))}))}get scroll(){return __privateGet(this,_scroll)}navigate(url$1,options){return __async(this,null,function*(){var _a,_b,_c,_d,_e,_f,_g;let isBack=__privateGet(this,_isBack);__privateSet(this,_isBack,!1);const updateId=++__privateWrapper(this,_updateId)._;let fullUrl=url.normalizeURL(url$1,{base:__privateGet(this,_options).base,trailingSlash:__privateGet(this,_options).trailingSlash});__privateGet(this,_options).urlModifier&&(fullUrl=__privateGet(this,_options).urlModifier(fullUrl)),events.dispatchEvent(document,"spaBeforeFetch",{custom:!0});let contents=__privateGet(this,_cache).get(fullUrl.toString());if((!contents||options!=null&&options.revalidate)&&(contents=yield fetch(`${fullUrl}`,{headers:{"X-SPA":"true"}}).then(res=>res.text()).catch(()=>{window.location.assign(fullUrl)})),events.dispatchEvent(document,"spaAfterFetch",{custom:!0}),!contents||(options!=null&&options.cache&&__privateGet(this,_cache).set(fullUrl.toString(),contents),__privateGet(this,_updateId)!==updateId))return;isBack?historyManager.historyManager.updatePreviousStateData({scrollTop:__privateGet(this,_scroll).y}):(historyManager.historyManager.updateCurrentStateData({scrollTop:__privateGet(this,_scroll).y}),historyManager.historyManager.pushState(fullUrl));const html=__privateGet(this,_domParser).parseFromString(contents,"text/html");if(url.normalizeRelativeURLs(html,fullUrl),yield(_b=(_a=__privateGet(this,_options)).beforeDiff)==null?void 0:_b.call(_a,html),__privateGet(this,_updateId)!==updateId)return;events.dispatchEvent(document,"spaBeforeUpdate",{custom:!0});let title=(_c=html.querySelector("title"))==null?void 0:_c.textContent;if(title)document.title=title;else{const h1=document.querySelector("h1");title=(_e=(_d=h1==null?void 0:h1.innerText)!=null?_d:h1==null?void 0:h1.textContent)!=null?_e:fullUrl.pathname}__privateGet(this,_announcerElement).create(html,title);const updateDone=__name(()=>{__privateGet(this,_scroll).update(),__privateGet(this,_links).update(),__privateGet(this,_announcerElement).done(),options!=null&&options.keepScrollPosition||ScrollNavigator.ScrollNavigator.scrollToElement((options==null?void 0:options.scrollValue)||0,__spreadValues({scrollElement:__privateGet(this,_scroll).element,behavior:"instant"},options==null?void 0:options.scrollOptions))},"updateDone");if(__privateGet(this,_options).viewTransition&&document.startViewTransition){const v=document.startViewTransition(()=>morph.morph(document,html));yield v.updateCallbackDone,updateDone(),yield v.finished}else yield morph.morph(document,html),updateDone();yield(_g=(_f=__privateGet(this,_options)).afterDiff)==null?void 0:_g.call(_f),events.dispatchEvent(document,"spaAfterUpdate",{custom:!0})})}};_cache=new WeakMap,_domParser=new WeakMap,_options=new WeakMap,_scroll=new WeakMap,_links=new WeakMap,_announcerElement=new WeakMap,_updateId=new WeakMap,_isBack=new WeakMap,__name(_SPA,"SPA"),_SPA.instance=null;let SPA=_SPA;exports.SPA=SPA;
|
package/lib/spa/index.js
CHANGED
|
@@ -40,13 +40,13 @@ var __async = (__this, __arguments, generator) => new Promise((resolve, reject)
|
|
|
40
40
|
step((generator = generator.apply(__this, __arguments)).next());
|
|
41
41
|
});
|
|
42
42
|
import { Cache } from "../cache/index.js";
|
|
43
|
-
import { L as LocalLinks } from "../LocalLinks-
|
|
43
|
+
import { L as LocalLinks } from "../LocalLinks-D1YdCbCu.js";
|
|
44
44
|
import { P as PageAnnouncerElement } from "../PageAnnouncerElement-CI048qxO.js";
|
|
45
45
|
import { P as PageScroll } from "../PageScroll-CrYJVAHA.js";
|
|
46
46
|
import { S as ScrollNavigator } from "../ScrollNavigator-CiZjoiyk.js";
|
|
47
47
|
import { h as historyManager } from "../historyManager-DyjFBozJ.js";
|
|
48
48
|
import { d as dispatchEvent } from "../events-Ds-TuvYW.js";
|
|
49
|
-
import { m as morph } from "../morph-
|
|
49
|
+
import { m as morph } from "../morph-DwKYrG4g.js";
|
|
50
50
|
import "construct-style-sheets-polyfill";
|
|
51
51
|
import "../index-Z2Lgb7xU.js";
|
|
52
52
|
import { a as normalizeBase, n as normalizeURL, b as normalizeRelativeURLs } from "../url-BdWQTlu6.js";
|
package/lib/utils/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const attributes=require("../attributes-BADnRZpK.cjs"),browser=require("../browser-CIp8NsnF.cjs"),canvas=require("../canvas-BP1ceie3.cjs"),coordinates=require("../coordinates-DQ9XV9M1.cjs"),customElements=require("../custom-elements-BfZCJde6.cjs"),dom=require("../dom-B40i6NXw.cjs"),easings=require("../easings-Bgvyia2r.cjs"),element=require("../element-CqD0jqBJ.cjs"),events=require("../events-UlGk63iC.cjs"),file=require("../file-RHfA3OS-.cjs"),_function=require("../function-H4b_gTg6.cjs"),gestures=require("../gestures-DtYbQr49.cjs"),stylesheet=require("../stylesheet-B-bI1cZ3.cjs"),layout=require("../layout-rR4-aYTY.cjs"),loading=require("../loading-7Ju1mFST.cjs"),math=require("../math-C-knY2TL.cjs"),metadata=require("../metadata-BrHUfpV9.cjs"),morph=require("../morph-Bz2BCWvO.cjs"),number=require("../number-Bu4sGvW7.cjs"),object=require("../object-DTY_W6xG.cjs"),polyfills=require("../polyfills-DZCuDBkA.cjs"),promises=require("../promises-nDm8_iG6.cjs"),string=require("../string-Bx5N38JG.cjs"),style=require("../style-IDJ6db6n.cjs"),intersector_index=require("../index-BrasTsja.cjs"),url=require("../url-Dzvsir_7.cjs");function insert(arr,index,...newItems){return[...arr.slice(0,index),...newItems,...arr.slice(index)]}__name(insert,"insert");function shiftArray(arr,positions){const len=arr.length;positions=positions%len;const result=new Array(len);for(let i=0;i<len;i++){const newPos=(i+positions)%len;result[newPos]=arr[i]}return result}__name(shiftArray,"shiftArray");function formatBytes(bytes,decimals=2){if(!+bytes)return"0 Bytes";const k=1024,dm=decimals<0?0:decimals,sizes=["Bytes","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"],i=Math.floor(Math.log(bytes)/Math.log(k));return`${parseFloat((bytes/Math.pow(k,i)).toFixed(dm))} ${sizes[i]}`}__name(formatBytes,"formatBytes");function copyTextToClipboard(text){if(navigator.clipboard)navigator.clipboard.writeText(text).then(()=>{console.log("Text copied to clipboard successfully!")}).catch(err=>{console.error("Failed to copy text to clipboard:",err)});else{const textArea=document.createElement("textarea");textArea.value=text,textArea.style.position="fixed",textArea.style.top="0",textArea.style.left="0",document.body.appendChild(textArea),textArea.select();try{document.execCommand("copy")?console.log("Text copied to clipboard successfully!"):console.error("Failed to copy text to clipboard.")}catch(err){console.error("Failed to copy text to clipboard:",err)}document.body.removeChild(textArea)}}__name(copyTextToClipboard,"copyTextToClipboard");function dotRectCollision(dot,rect){return dot.x<rect.x+rect.width&&dot.x>rect.x&&dot.y<rect.y+rect.height&&dot.y>rect.y}__name(dotRectCollision,"dotRectCollision");function dotCircleCollision(dot,circle){return Math.sqrt((dot.x-circle.x)**2+(dot.y-circle.y)**2)<circle.radius}__name(dotCircleCollision,"dotCircleCollision");function dotPolygonCollision(dot,polygon){let inside=!1;const{x,y}=dot;for(let i=0,j=polygon.length-1;i<polygon.length;j=i++){const xi=polygon[i].x,yi=polygon[i].y,xj=polygon[j].x,yj=polygon[j].y;yi>y!=yj>y&&x<(xj-xi)*(y-yi)/(yj-yi)+xi&&(inside=!inside)}return inside}__name(dotPolygonCollision,"dotPolygonCollision");function rgbToHex(r,g,b){const toHex=__name(c=>{const hex=c.toString(16);return hex.length===1?"0"+hex:hex},"toHex");return`#${toHex(r)}${toHex(g)}${toHex(b)}`}__name(rgbToHex,"rgbToHex");function getStyleRuleActualValue(rule,name){const obj=rule.style.getPropertyValue(name);if(obj){const stringValue=obj.toString();return stringValue.startsWith("var")?getStyleRuleActualValue(rule,stringValue.slice(4,-1)):stringValue}}__name(getStyleRuleActualValue,"getStyleRuleActualValue");function getRootVariables(...names){const variables={};return Array.from(document.styleSheets).forEach(stylesheet2=>{Array.from(stylesheet2.cssRules).forEach(rule=>{rule instanceof CSSStyleRule&&rule.selectorText===":root"&&names.forEach(name=>{const value=getStyleRuleActualValue(rule,name);value&&(variables[name]=value)})})}),names.forEach(name=>{variables[name]||console.warn(`variable named ${name} not found`)}),variables}__name(getRootVariables,"getRootVariables");function encode(string2){const decodedStr=window.atob(string2);return decodeURIComponent(window.escape(decodedStr))}__name(encode,"encode");function decode(string2){const encodedStr=window.unescape(encodeURIComponent(string2));return window.btoa(encodedStr)}__name(decode,"decode");const phoneRegex=/^(\+?\d{1,3}[-.\s]?)?(\(?\d{3}\)?[-.\s]?)?\d{1,4}[-.\s]?\d{2,4}[-.\s]?\d{2,4}$/,emailRegex=/^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,}$/;function tryCreateHrefFromContact(contact){let href,type;return emailRegex.test(contact)?(href=`mailto:${contact.trim()}`,type="email"):phoneRegex.test(contact)&&(href=`tel:${contact.replace(/[^0-9\\.\\+]+/g,"")}`,type="phone"),{href,type,contact}}__name(tryCreateHrefFromContact,"tryCreateHrefFromContact");function transliterate(text,options={}){const{separator="-",lowercase=!0,replaceNumbers=!0,maxLength=60}=options,charMap={а:"a",б:"b",в:"v",г:"g",д:"d",е:"e",ё:"e",ж:"zh",з:"z",и:"i",й:"j",к:"k",л:"l",м:"m",н:"n",о:"o",п:"p",р:"r",с:"s",т:"t",у:"u",ф:"f",х:"h",ц:"c",ч:"ch",ш:"sh",щ:"sh",ъ:"",ы:"y",ь:"",э:"e",ю:"yu",я:"ya"};let result=text.replace(/[а-яё]/gi,char=>{const lowerChar=char.toLowerCase(),replacement=charMap[lowerChar]||"";return char===lowerChar?replacement:replacement.toUpperCase()});if(replaceNumbers){const numberMap={0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"};result=result.replace(/[0-9]/g,num=>numberMap[num]||num)}return lowercase&&(result=result.toLowerCase()),result=result.replace(/[^\w\-]+/g,separator).replace(new RegExp(`\\${separator}+`,"g"),separator).replace(new RegExp(`(^\\${separator}|\\${separator}$)`,"g"),""),maxLength>0&&result.length>maxLength&&(result=result.substring(0,maxLength).replace(new RegExp(`\\${separator}[^\\${separator}]*$`),"")),result}__name(transliterate,"transliterate");function distributeProgress(progress,...items){if(items.length===0)return[];if(items.some(item=>item.weight<0))throw new Error("Все веса должны быть неотрицательными числами");const totalWeight=items.map(item=>item.weight).reduce((sum,weight)=>sum+weight,0);if(totalWeight===0)return items.forEach(item=>{var _a;return(_a=item.callback)==null?void 0:_a.call(item,0)}),Array(items.length).fill(0);const distributed=[];let accumulatedProgress=0;for(let i=0;i<items.length;i++){const{weight,callback}=items[i],itemShare=weight/totalWeight,itemStart=accumulatedProgress,itemEnd=accumulatedProgress+itemShare;let itemProgress=0;progress>=itemEnd?itemProgress=1:progress>itemStart&&(itemProgress=(progress-itemStart)/itemShare);const finalProgress=Math.min(1,Math.max(0,itemProgress));distributed.push(finalProgress),callback==null||callback(finalProgress),accumulatedProgress=itemEnd}return distributed}__name(distributeProgress,"distributeProgress");function splitProgress(progress,items,initialItemsWithFullProgress=0){const totalItems=items-initialItemsWithFullProgress,splitted=[];for(let item=0;item<items;item++){const offset=item/totalItems-initialItemsWithFullProgress/totalItems,itemProgress=Math.min(1,Math.max(0,(progress-offset)*totalItems));splitted.push(itemProgress)}return splitted}__name(splitProgress,"splitProgress");function setElementsProgress(progress,elements,initialItemsWithFullProgress=0){const totalItems=elements.length-initialItemsWithFullProgress;elements.forEach((el,index)=>{const offset=index/totalItems-initialItemsWithFullProgress/totalItems,itemProgress=Math.min(1,Math.max(0,(progress-offset)*totalItems));el.style.setProperty("--item-progress",itemProgress.toString())})}__name(setElementsProgress,"setElementsProgress");function setActiveContentClasses(index,elements){elements.forEach((el,i)=>{i>index?(el.classList.remove("current","previous"),el.classList.add("next")):i<index?(el.classList.remove("current","next"),el.classList.add("previous")):(el.classList.remove("previous","next"),el.classList.add("current"))})}__name(setActiveContentClasses,"setActiveContentClasses");function cloneTemplateContent(templateElement,callback){if(templateElement){const element2=templateElement.content.cloneNode(!0).firstElementChild;return element2&&(callback==null||callback(element2)),element2}return null}__name(cloneTemplateContent,"cloneTemplateContent");function setIntervalOnIntersection(element2,delay,callback,options){let intervalId,isIntersecting=!1,current=0,previous=0,tickerUnsubsribe;const toggleInterval=__name(()=>{clearInterval(intervalId),tickerUnsubsribe==null||tickerUnsubsribe(),options!=null&&options.restartCounter&&(current=0),isIntersecting&&(callback({current,previous,progress:0}),previous=current,tickerUnsubsribe=restartTicker(),intervalId=setInterval(()=>{tickerUnsubsribe==null||tickerUnsubsribe(),current++,callback({current,previous,progress:0}),previous=current,tickerUnsubsribe=restartTicker()},delay))},"toggleInterval"),restartTicker=__name(()=>intersector_index.ticker.subscribe(e=>{const progress=e.timeElapsedSinceSubscription/delay;callback({current,previous,progress})}),"restartTicker"),intersectorUnsubscribe=intersector_index.intersector.subscribe(element2,e=>{isIntersecting=e.isIntersecting,toggleInterval()});return{destroy:__name(()=>{tickerUnsubsribe==null||tickerUnsubsribe(),intersectorUnsubscribe(),clearInterval(intervalId)},"destroy"),restart:__name((currentValue,previousValue)=>{current=currentValue||0,previousValue&&(previous=previousValue),toggleInterval()},"restart"),stop:__name(()=>{clearInterval(intervalId),tickerUnsubsribe==null||tickerUnsubsribe()},"stop")}}__name(setIntervalOnIntersection,"setIntervalOnIntersection");exports.getElementAttributesAdvanced=attributes.getElementAttributesAdvanced;exports.parseAttribute=attributes.parseAttribute;exports.parseAttributeValue=attributes.parseAttributeValue;exports.parseAttributeValueAdvanced=attributes.parseAttributeValueAdvanced;exports.isBrowser=browser.isBrowser;exports.contain=canvas.contain;exports.cover=canvas.cover;exports.fixPosition=canvas.fixPosition;exports.measureText=canvas.measureText;exports.getPointerPosition=coordinates.getPointerPosition;exports.normalize=coordinates.normalize;exports.screenToCartesian=coordinates.screenToCartesian;exports.whenDefined=customElements.whenDefined;exports.createScriptElement=dom.createScriptElement;exports.deepQuerySelectorAll=dom.deepQuerySelectorAll;exports.excludeElements=dom.excludeElements;exports.findParentElement=dom.findParentElement;exports.findScrollParentElement=dom.findScrollParentElement;exports.getAllParentElements=dom.getAllParentElements;exports.getElement=dom.getElement;exports.intersectElements=dom.intersectElements;exports.traverseNodes=dom.traverseNodes;exports.traverseShadowRoots=dom.traverseShadowRoots;exports.easeInCubic=easings.easeInCubic;exports.easeInExpo=easings.easeInExpo;exports.easeInOutCubic=easings.easeInOutCubic;exports.easeInOutExpo=easings.easeInOutExpo;exports.easeInOutQuad=easings.easeInOutQuad;exports.easeInOutQuart=easings.easeInOutQuart;exports.easeInOutQuint=easings.easeInOutQuint;exports.easeInQuad=easings.easeInQuad;exports.easeInQuart=easings.easeInQuart;exports.easeInQuint=easings.easeInQuint;exports.easeOutCubic=easings.easeOutCubic;exports.easeOutExpo=easings.easeOutExpo;exports.easeOutQuad=easings.easeOutQuad;exports.easeOutQuart=easings.easeOutQuart;exports.easeOutQuint=easings.easeOutQuint;exports.easeOvershoot=easings.easeOvershoot;exports.easings=easings.easings;exports.linear=easings.linear;exports.isElementVisible=element.isElementVisible;exports.dispatchEvent=events.dispatchEvent;exports.createJSONAndSave=file.createJSONAndSave;exports.downloadURI=file.downloadURI;exports.debounce=_function.debounce;exports.throttle=_function.throttle;exports.setupDrag=gestures.setupDrag;exports.createStylesheet=stylesheet.createStylesheet;exports.styleToString=stylesheet.styleToString;exports.getCumulativeOffsetLeft=layout.getCumulativeOffsetLeft;exports.getCumulativeOffsetTop=layout.getCumulativeOffsetTop;exports.getCumulativePosition=layout.getCumulativePosition;exports.getStickyOffset=layout.getStickyOffset;exports.requestLoadingCallback=loading.requestLoadingCallback;exports.calculateDistance=math.calculateDistance;exports.calculateDistanceWithRadius=math.calculateDistanceWithRadius;exports.clamp=math.clamp;exports.damp=math.damp;exports.lerp=math.lerp;exports.mapRange=math.mapRange;exports.round=math.round;exports.smootherstep=math.smootherstep;exports.smoothstep=math.smoothstep;exports.step=math.step;exports.formatMediaDuration=metadata.formatMediaDuration;exports.ACTION_CREATE=morph.ACTION_CREATE;exports.ACTION_PRESERVE=morph.ACTION_PRESERVE;exports.ACTION_REMOVE=morph.ACTION_REMOVE;exports.ACTION_REMOVE_ATTR=morph.ACTION_REMOVE_ATTR;exports.ACTION_REPLACE=morph.ACTION_REPLACE;exports.ACTION_SET_ATTR=morph.ACTION_SET_ATTR;exports.ACTION_SKIP=morph.ACTION_SKIP;exports.ACTION_UPDATE=morph.ACTION_UPDATE;exports.NODE_TYPE_COMMENT=morph.NODE_TYPE_COMMENT;exports.NODE_TYPE_DOCUMENT=morph.NODE_TYPE_DOCUMENT;exports.NODE_TYPE_ELEMENT=morph.NODE_TYPE_ELEMENT;exports.NODE_TYPE_TEXT=morph.NODE_TYPE_TEXT;exports.diff=morph.diff;exports.morph=morph.morph;exports.patch=morph.patch;exports.beautifyNumber=number.beautifyNumber;exports.loopNumber=number.loopNumber;exports.preciseNumber=number.preciseNumber;exports.roundNumberTo=number.roundNumberTo;exports.toStep=number.toStep;exports.cloneDeep=object.cloneDeep;exports.compareObjects=object.compareObjects;exports.isESClass=object.isESClass;exports.isNullish=object.isNullish;exports.isObject=object.isObject;exports.mergeDeep=object.mergeDeep;exports.mixin=object.mixin;exports.omit=object.omit;exports.pick=object.pick;exports.nullishCoalescing=polyfills.nullishCoalescing;exports.requestIdleCallback=polyfills.requestIdleCallback;exports.wait=promises.wait;exports.camelToKebab=string.camelToKebab;exports.capitalize=string.capitalize;exports.declension=string.declension;exports.decodeHtmlEntities=string.decodeHtmlEntities;exports.generateId=string.generateId;exports.getRandomChar=string.getRandomChar;exports.isUppercase=string.isUppercase;exports.kebabToCamel=string.kebabToCamel;exports.snakeToDotted=string.snakeToDotted;exports.toPascalCase=string.toPascalCase;exports.uncapitalize=string.uncapitalize;exports.getElementTransitionDurationMS=style.getElementTransitionDurationMS;exports.getElementTransitionDurationS=style.getElementTransitionDurationS;exports.addParamsToURL=url.addParamsToURL;exports.changeHistory=url.changeHistory;exports.isLocalUrl=url.isLocalUrl;exports.normalizeBase=url.normalizeBase;exports.normalizeRelativeURLs=url.normalizeRelativeURLs;exports.normalizeURL=url.normalizeURL;exports.parseSearchParameters=url.parseSearchParameters;exports.searchParamsObjectToString=url.searchParamsObjectToString;exports.searchParamsToObject=url.searchParamsToObject;exports.splitPath=url.splitPath;exports.updateSearchParameter=url.updateSearchParameter;exports.cloneTemplateContent=cloneTemplateContent;exports.copyTextToClipboard=copyTextToClipboard;exports.decode=decode;exports.distributeProgress=distributeProgress;exports.dotCircleCollision=dotCircleCollision;exports.dotPolygonCollision=dotPolygonCollision;exports.dotRectCollision=dotRectCollision;exports.encode=encode;exports.formatBytes=formatBytes;exports.getRootVariables=getRootVariables;exports.getStyleRuleActualValue=getStyleRuleActualValue;exports.insert=insert;exports.rgbToHex=rgbToHex;exports.setActiveContentClasses=setActiveContentClasses;exports.setElementsProgress=setElementsProgress;exports.setIntervalOnIntersection=setIntervalOnIntersection;exports.shiftArray=shiftArray;exports.splitProgress=splitProgress;exports.transliterate=transliterate;exports.tryCreateHrefFromContact=tryCreateHrefFromContact;
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const attributes=require("../attributes-BADnRZpK.cjs"),browser=require("../browser-CIp8NsnF.cjs"),canvas=require("../canvas-BP1ceie3.cjs"),coordinates=require("../coordinates-DQ9XV9M1.cjs"),customElements=require("../custom-elements-BfZCJde6.cjs"),dom=require("../dom-B40i6NXw.cjs"),easings=require("../easings-Bgvyia2r.cjs"),element=require("../element-CqD0jqBJ.cjs"),events=require("../events-UlGk63iC.cjs"),file=require("../file-RHfA3OS-.cjs"),_function=require("../function-H4b_gTg6.cjs"),gestures=require("../gestures-DtYbQr49.cjs"),stylesheet=require("../stylesheet-B-bI1cZ3.cjs"),layout=require("../layout-rR4-aYTY.cjs"),loading=require("../loading-7Ju1mFST.cjs"),math=require("../math-C-knY2TL.cjs"),metadata=require("../metadata-BrHUfpV9.cjs"),morph=require("../morph-CsmERL3V.cjs"),number=require("../number-Bu4sGvW7.cjs"),object=require("../object-DTY_W6xG.cjs"),polyfills=require("../polyfills-DZCuDBkA.cjs"),promises=require("../promises-nDm8_iG6.cjs"),string=require("../string-Bx5N38JG.cjs"),style=require("../style-IDJ6db6n.cjs"),intersector_index=require("../index-BrasTsja.cjs"),url=require("../url-Dzvsir_7.cjs");function insert(arr,index,...newItems){return[...arr.slice(0,index),...newItems,...arr.slice(index)]}__name(insert,"insert");function shiftArray(arr,positions){const len=arr.length;positions=positions%len;const result=new Array(len);for(let i=0;i<len;i++){const newPos=(i+positions)%len;result[newPos]=arr[i]}return result}__name(shiftArray,"shiftArray");function formatBytes(bytes,decimals=2){if(!+bytes)return"0 Bytes";const k=1024,dm=decimals<0?0:decimals,sizes=["Bytes","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"],i=Math.floor(Math.log(bytes)/Math.log(k));return`${parseFloat((bytes/Math.pow(k,i)).toFixed(dm))} ${sizes[i]}`}__name(formatBytes,"formatBytes");function copyTextToClipboard(text){if(navigator.clipboard)navigator.clipboard.writeText(text).then(()=>{console.log("Text copied to clipboard successfully!")}).catch(err=>{console.error("Failed to copy text to clipboard:",err)});else{const textArea=document.createElement("textarea");textArea.value=text,textArea.style.position="fixed",textArea.style.top="0",textArea.style.left="0",document.body.appendChild(textArea),textArea.select();try{document.execCommand("copy")?console.log("Text copied to clipboard successfully!"):console.error("Failed to copy text to clipboard.")}catch(err){console.error("Failed to copy text to clipboard:",err)}document.body.removeChild(textArea)}}__name(copyTextToClipboard,"copyTextToClipboard");function dotRectCollision(dot,rect){return dot.x<rect.x+rect.width&&dot.x>rect.x&&dot.y<rect.y+rect.height&&dot.y>rect.y}__name(dotRectCollision,"dotRectCollision");function dotCircleCollision(dot,circle){return Math.sqrt((dot.x-circle.x)**2+(dot.y-circle.y)**2)<circle.radius}__name(dotCircleCollision,"dotCircleCollision");function dotPolygonCollision(dot,polygon){let inside=!1;const{x,y}=dot;for(let i=0,j=polygon.length-1;i<polygon.length;j=i++){const xi=polygon[i].x,yi=polygon[i].y,xj=polygon[j].x,yj=polygon[j].y;yi>y!=yj>y&&x<(xj-xi)*(y-yi)/(yj-yi)+xi&&(inside=!inside)}return inside}__name(dotPolygonCollision,"dotPolygonCollision");function rgbToHex(r,g,b){const toHex=__name(c=>{const hex=c.toString(16);return hex.length===1?"0"+hex:hex},"toHex");return`#${toHex(r)}${toHex(g)}${toHex(b)}`}__name(rgbToHex,"rgbToHex");function getStyleRuleActualValue(rule,name){const obj=rule.style.getPropertyValue(name);if(obj){const stringValue=obj.toString();return stringValue.startsWith("var")?getStyleRuleActualValue(rule,stringValue.slice(4,-1)):stringValue}}__name(getStyleRuleActualValue,"getStyleRuleActualValue");function getRootVariables(...names){const variables={};return Array.from(document.styleSheets).forEach(stylesheet2=>{Array.from(stylesheet2.cssRules).forEach(rule=>{rule instanceof CSSStyleRule&&rule.selectorText===":root"&&names.forEach(name=>{const value=getStyleRuleActualValue(rule,name);value&&(variables[name]=value)})})}),names.forEach(name=>{variables[name]||console.warn(`variable named ${name} not found`)}),variables}__name(getRootVariables,"getRootVariables");function encode(string2){const decodedStr=window.atob(string2);return decodeURIComponent(window.escape(decodedStr))}__name(encode,"encode");function decode(string2){const encodedStr=window.unescape(encodeURIComponent(string2));return window.btoa(encodedStr)}__name(decode,"decode");const phoneRegex=/^(\+?\d{1,3}[-.\s]?)?(\(?\d{3}\)?[-.\s]?)?\d{1,4}[-.\s]?\d{2,4}[-.\s]?\d{2,4}$/,emailRegex=/^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,}$/;function tryCreateHrefFromContact(contact){let href,type;return emailRegex.test(contact)?(href=`mailto:${contact.trim()}`,type="email"):phoneRegex.test(contact)&&(href=`tel:${contact.replace(/[^0-9\\.\\+]+/g,"")}`,type="phone"),{href,type,contact}}__name(tryCreateHrefFromContact,"tryCreateHrefFromContact");function transliterate(text,options={}){const{separator="-",lowercase=!0,replaceNumbers=!0,maxLength=60}=options,charMap={а:"a",б:"b",в:"v",г:"g",д:"d",е:"e",ё:"e",ж:"zh",з:"z",и:"i",й:"j",к:"k",л:"l",м:"m",н:"n",о:"o",п:"p",р:"r",с:"s",т:"t",у:"u",ф:"f",х:"h",ц:"c",ч:"ch",ш:"sh",щ:"sh",ъ:"",ы:"y",ь:"",э:"e",ю:"yu",я:"ya"};let result=text.replace(/[а-яё]/gi,char=>{const lowerChar=char.toLowerCase(),replacement=charMap[lowerChar]||"";return char===lowerChar?replacement:replacement.toUpperCase()});if(replaceNumbers){const numberMap={0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"};result=result.replace(/[0-9]/g,num=>numberMap[num]||num)}return lowercase&&(result=result.toLowerCase()),result=result.replace(/[^\w\-]+/g,separator).replace(new RegExp(`\\${separator}+`,"g"),separator).replace(new RegExp(`(^\\${separator}|\\${separator}$)`,"g"),""),maxLength>0&&result.length>maxLength&&(result=result.substring(0,maxLength).replace(new RegExp(`\\${separator}[^\\${separator}]*$`),"")),result}__name(transliterate,"transliterate");function distributeProgress(progress,...items){if(items.length===0)return[];if(items.some(item=>item.weight<0))throw new Error("Все веса должны быть неотрицательными числами");const totalWeight=items.map(item=>item.weight).reduce((sum,weight)=>sum+weight,0);if(totalWeight===0)return items.forEach(item=>{var _a;return(_a=item.callback)==null?void 0:_a.call(item,0)}),Array(items.length).fill(0);const distributed=[];let accumulatedProgress=0;for(let i=0;i<items.length;i++){const{weight,callback}=items[i],itemShare=weight/totalWeight,itemStart=accumulatedProgress,itemEnd=accumulatedProgress+itemShare;let itemProgress=0;progress>=itemEnd?itemProgress=1:progress>itemStart&&(itemProgress=(progress-itemStart)/itemShare);const finalProgress=Math.min(1,Math.max(0,itemProgress));distributed.push(finalProgress),callback==null||callback(finalProgress),accumulatedProgress=itemEnd}return distributed}__name(distributeProgress,"distributeProgress");function splitProgress(progress,items,initialItemsWithFullProgress=0){const totalItems=items-initialItemsWithFullProgress,splitted=[];for(let item=0;item<items;item++){const offset=item/totalItems-initialItemsWithFullProgress/totalItems,itemProgress=Math.min(1,Math.max(0,(progress-offset)*totalItems));splitted.push(itemProgress)}return splitted}__name(splitProgress,"splitProgress");function setElementsProgress(progress,elements,initialItemsWithFullProgress=0){const totalItems=elements.length-initialItemsWithFullProgress;elements.forEach((el,index)=>{const offset=index/totalItems-initialItemsWithFullProgress/totalItems,itemProgress=Math.min(1,Math.max(0,(progress-offset)*totalItems));el.style.setProperty("--item-progress",itemProgress.toString())})}__name(setElementsProgress,"setElementsProgress");function setActiveContentClasses(index,elements){elements.forEach((el,i)=>{i>index?(el.classList.remove("current","previous"),el.classList.add("next")):i<index?(el.classList.remove("current","next"),el.classList.add("previous")):(el.classList.remove("previous","next"),el.classList.add("current"))})}__name(setActiveContentClasses,"setActiveContentClasses");function cloneTemplateContent(templateElement,callback){if(templateElement){const element2=templateElement.content.cloneNode(!0).firstElementChild;return element2&&(callback==null||callback(element2)),element2}return null}__name(cloneTemplateContent,"cloneTemplateContent");function setIntervalOnIntersection(element2,delay,callback,options){let intervalId,isIntersecting=!1,current=0,previous=0,tickerUnsubsribe;const toggleInterval=__name(()=>{clearInterval(intervalId),tickerUnsubsribe==null||tickerUnsubsribe(),options!=null&&options.restartCounter&&(current=0),isIntersecting&&(callback({current,previous,progress:0}),previous=current,tickerUnsubsribe=restartTicker(),intervalId=setInterval(()=>{tickerUnsubsribe==null||tickerUnsubsribe(),current++,callback({current,previous,progress:0}),previous=current,tickerUnsubsribe=restartTicker()},delay))},"toggleInterval"),restartTicker=__name(()=>intersector_index.ticker.subscribe(e=>{const progress=e.timeElapsedSinceSubscription/delay;callback({current,previous,progress})}),"restartTicker"),intersectorUnsubscribe=intersector_index.intersector.subscribe(element2,e=>{isIntersecting=e.isIntersecting,toggleInterval()});return{destroy:__name(()=>{tickerUnsubsribe==null||tickerUnsubsribe(),intersectorUnsubscribe(),clearInterval(intervalId)},"destroy"),restart:__name((currentValue,previousValue)=>{current=currentValue||0,previousValue&&(previous=previousValue),toggleInterval()},"restart"),stop:__name(()=>{clearInterval(intervalId),tickerUnsubsribe==null||tickerUnsubsribe()},"stop")}}__name(setIntervalOnIntersection,"setIntervalOnIntersection");exports.getElementAttributesAdvanced=attributes.getElementAttributesAdvanced;exports.parseAttribute=attributes.parseAttribute;exports.parseAttributeValue=attributes.parseAttributeValue;exports.parseAttributeValueAdvanced=attributes.parseAttributeValueAdvanced;exports.isBrowser=browser.isBrowser;exports.contain=canvas.contain;exports.cover=canvas.cover;exports.fixPosition=canvas.fixPosition;exports.measureText=canvas.measureText;exports.getPointerPosition=coordinates.getPointerPosition;exports.normalize=coordinates.normalize;exports.screenToCartesian=coordinates.screenToCartesian;exports.whenDefined=customElements.whenDefined;exports.createScriptElement=dom.createScriptElement;exports.deepQuerySelectorAll=dom.deepQuerySelectorAll;exports.excludeElements=dom.excludeElements;exports.findParentElement=dom.findParentElement;exports.findScrollParentElement=dom.findScrollParentElement;exports.getAllParentElements=dom.getAllParentElements;exports.getElement=dom.getElement;exports.intersectElements=dom.intersectElements;exports.traverseNodes=dom.traverseNodes;exports.traverseShadowRoots=dom.traverseShadowRoots;exports.easeInCubic=easings.easeInCubic;exports.easeInExpo=easings.easeInExpo;exports.easeInOutCubic=easings.easeInOutCubic;exports.easeInOutExpo=easings.easeInOutExpo;exports.easeInOutQuad=easings.easeInOutQuad;exports.easeInOutQuart=easings.easeInOutQuart;exports.easeInOutQuint=easings.easeInOutQuint;exports.easeInQuad=easings.easeInQuad;exports.easeInQuart=easings.easeInQuart;exports.easeInQuint=easings.easeInQuint;exports.easeOutCubic=easings.easeOutCubic;exports.easeOutExpo=easings.easeOutExpo;exports.easeOutQuad=easings.easeOutQuad;exports.easeOutQuart=easings.easeOutQuart;exports.easeOutQuint=easings.easeOutQuint;exports.easeOvershoot=easings.easeOvershoot;exports.easings=easings.easings;exports.linear=easings.linear;exports.isElementVisible=element.isElementVisible;exports.dispatchEvent=events.dispatchEvent;exports.createJSONAndSave=file.createJSONAndSave;exports.downloadURI=file.downloadURI;exports.debounce=_function.debounce;exports.throttle=_function.throttle;exports.setupDrag=gestures.setupDrag;exports.createStylesheet=stylesheet.createStylesheet;exports.styleToString=stylesheet.styleToString;exports.getCumulativeOffsetLeft=layout.getCumulativeOffsetLeft;exports.getCumulativeOffsetTop=layout.getCumulativeOffsetTop;exports.getCumulativePosition=layout.getCumulativePosition;exports.getStickyOffset=layout.getStickyOffset;exports.requestLoadingCallback=loading.requestLoadingCallback;exports.calculateDistance=math.calculateDistance;exports.calculateDistanceWithRadius=math.calculateDistanceWithRadius;exports.clamp=math.clamp;exports.damp=math.damp;exports.lerp=math.lerp;exports.mapRange=math.mapRange;exports.round=math.round;exports.smootherstep=math.smootherstep;exports.smoothstep=math.smoothstep;exports.step=math.step;exports.formatMediaDuration=metadata.formatMediaDuration;exports.ACTION_CREATE=morph.ACTION_CREATE;exports.ACTION_PRESERVE=morph.ACTION_PRESERVE;exports.ACTION_REMOVE=morph.ACTION_REMOVE;exports.ACTION_REMOVE_ATTR=morph.ACTION_REMOVE_ATTR;exports.ACTION_REPLACE=morph.ACTION_REPLACE;exports.ACTION_SET_ATTR=morph.ACTION_SET_ATTR;exports.ACTION_SKIP=morph.ACTION_SKIP;exports.ACTION_UPDATE=morph.ACTION_UPDATE;exports.NODE_TYPE_COMMENT=morph.NODE_TYPE_COMMENT;exports.NODE_TYPE_DOCUMENT=morph.NODE_TYPE_DOCUMENT;exports.NODE_TYPE_ELEMENT=morph.NODE_TYPE_ELEMENT;exports.NODE_TYPE_TEXT=morph.NODE_TYPE_TEXT;exports.diff=morph.diff;exports.morph=morph.morph;exports.patch=morph.patch;exports.beautifyNumber=number.beautifyNumber;exports.loopNumber=number.loopNumber;exports.preciseNumber=number.preciseNumber;exports.roundNumberTo=number.roundNumberTo;exports.toStep=number.toStep;exports.cloneDeep=object.cloneDeep;exports.compareObjects=object.compareObjects;exports.isESClass=object.isESClass;exports.isNullish=object.isNullish;exports.isObject=object.isObject;exports.mergeDeep=object.mergeDeep;exports.mixin=object.mixin;exports.omit=object.omit;exports.pick=object.pick;exports.nullishCoalescing=polyfills.nullishCoalescing;exports.requestIdleCallback=polyfills.requestIdleCallback;exports.wait=promises.wait;exports.camelToKebab=string.camelToKebab;exports.capitalize=string.capitalize;exports.declension=string.declension;exports.decodeHtmlEntities=string.decodeHtmlEntities;exports.generateId=string.generateId;exports.getRandomChar=string.getRandomChar;exports.isUppercase=string.isUppercase;exports.kebabToCamel=string.kebabToCamel;exports.snakeToDotted=string.snakeToDotted;exports.toPascalCase=string.toPascalCase;exports.uncapitalize=string.uncapitalize;exports.getElementTransitionDurationMS=style.getElementTransitionDurationMS;exports.getElementTransitionDurationS=style.getElementTransitionDurationS;exports.addParamsToURL=url.addParamsToURL;exports.changeHistory=url.changeHistory;exports.isLocalUrl=url.isLocalUrl;exports.normalizeBase=url.normalizeBase;exports.normalizeRelativeURLs=url.normalizeRelativeURLs;exports.normalizeURL=url.normalizeURL;exports.parseSearchParameters=url.parseSearchParameters;exports.searchParamsObjectToString=url.searchParamsObjectToString;exports.searchParamsToObject=url.searchParamsToObject;exports.splitPath=url.splitPath;exports.updateSearchParameter=url.updateSearchParameter;exports.cloneTemplateContent=cloneTemplateContent;exports.copyTextToClipboard=copyTextToClipboard;exports.decode=decode;exports.distributeProgress=distributeProgress;exports.dotCircleCollision=dotCircleCollision;exports.dotPolygonCollision=dotPolygonCollision;exports.dotRectCollision=dotRectCollision;exports.encode=encode;exports.formatBytes=formatBytes;exports.getRootVariables=getRootVariables;exports.getStyleRuleActualValue=getStyleRuleActualValue;exports.insert=insert;exports.rgbToHex=rgbToHex;exports.setActiveContentClasses=setActiveContentClasses;exports.setElementsProgress=setElementsProgress;exports.setIntervalOnIntersection=setIntervalOnIntersection;exports.shiftArray=shiftArray;exports.splitProgress=splitProgress;exports.transliterate=transliterate;exports.tryCreateHrefFromContact=tryCreateHrefFromContact;
|
package/lib/utils/index.js
CHANGED
|
@@ -17,7 +17,7 @@ import { a as a5, b as b4, c as c6, g as g5 } from "../layout-DxOCR4qe.js";
|
|
|
17
17
|
import { r as r2 } from "../loading-BYWPyUhc.js";
|
|
18
18
|
import { e as e3, f as f4, c as c7, d as d6, l as l2, m as m3, r as r3, b as b5, a as a6, s as s4 } from "../math-r8V23YFe.js";
|
|
19
19
|
import { f as f5 } from "../metadata-BNdkmeeD.js";
|
|
20
|
-
import { A, k as k2, e as e4, i as i5, f as f6, h as h3, j as j2, g as g6, b as b6, c as c8, N, a as a7, d as d7, m as m4, p as p3 } from "../morph-
|
|
20
|
+
import { A, k as k2, e as e4, i as i5, f as f6, h as h3, j as j2, g as g6, b as b6, c as c8, N, a as a7, d as d7, m as m4, p as p3 } from "../morph-DwKYrG4g.js";
|
|
21
21
|
import { b as b7, l as l3, p as p4, r as r4, t as t3 } from "../number-DiVt2xnh.js";
|
|
22
22
|
import { c as c9, d as d8, i as i6, b as b8, a as a8, m as m5, e as e5, o as o2, p as p5 } from "../object-CiIdEmJx.js";
|
|
23
23
|
import { n as n3, r as r5 } from "../polyfills-CG1XJNia.js";
|
package/package.json
CHANGED
package/lib/morph-Bz2BCWvO.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __async=(__this,__arguments,generator)=>new Promise((resolve,reject)=>{var fulfilled=value=>{try{step(generator.next(value))}catch(e){reject(e)}},rejected=value=>{try{step(generator.throw(value))}catch(e){reject(e)}},step=x=>x.done?resolve(x.value):Promise.resolve(x.value).then(fulfilled,rejected);step((generator=generator.apply(__this,__arguments)).next())});const compare=__name(attr=>(from,to)=>from[`node${attr}`]===to[`node${attr}`],"compare"),same={name:compare("Name"),type:compare("Type"),value:compare("Value")};function hasPermanentParent(node){if(!node)return!1;let current=node;for(;current;){if(current.nodeType===1&¤t.hasAttribute("data-preserve"))return!0;current=current.parentNode}return!1}__name(hasPermanentParent,"hasPermanentParent");function attributes(from,to){if(from.attributes.length===0&&to.attributes.length===0)return[];const patches=[],remove=new Map,update=new Map;for(const attr of from.attributes)remove.set(attr.name,attr.value);for(const attr of to.attributes){const fromAttr=remove.get(attr.name);attr.value===fromAttr?remove.delete(attr.name):(typeof fromAttr!="undefined"&&remove.delete(attr.name),update.set(attr.name,attr.value))}for(const attr of remove.keys())patches.push({type:5,name:attr});for(const[attr,value]of update.entries())patches.push({type:4,name:attr,value});return patches}__name(attributes,"attributes");function serialize(el,data=!0){let key=`${el.localName}`;for(const{name,value}of el.attributes)data&&name.startsWith("data-")||(key+=`[${name}=${value}]`);return key+=el.innerHTML,key}__name(serialize,"serialize");function getKey(el){switch(el.tagName){case"BASE":case"TITLE":return el.localName;case"META":{if(el.hasAttribute("name"))return`meta[name="${el.getAttribute("name")}"]`;if(el.hasAttribute("property"))return`meta[name="${el.getAttribute("property")}"]`;break}case"LINK":{if(el.hasAttribute("rel")&&el.hasAttribute("href"))return`link[rel="${el.getAttribute("rel")}"][href="${el.getAttribute("href")}"]`;if(el.hasAttribute("href"))return`link[href="${el.getAttribute("href")}"]`;break}}return serialize(el)}__name(getKey,"getKey");function clone(node){if(node.nodeType===1&&node.hasAttribute("data-preserve"))return node.cloneNode(!0);if(node.nodeType===1&&node.localName==="script"){const script=document.createElement("script");for(let{name,value}of node.attributes)script.setAttribute(name,value);return script.innerHTML=node.innerHTML,script}return node.cloneNode(!0)}__name(clone,"clone");function uniqueChildren(from,to){if(from.children.length===0&&to.children.length===0)return[];const patches=[],remove=new Map,update=new Map,add=new Map;for(const child of from.children)remove.set(getKey(child),child);for(const child of to.children){const key=getKey(child),fromEl=remove.get(key);fromEl?serialize(child,!1)!==serialize(fromEl,!1)&&update.set(key,clone(child)):add.set(key,clone(child)),remove.delete(key)}for(const node of from.childNodes){if(node.nodeType===1){const key=getKey(node);if(hasPermanentParent(node)){patches.push({type:7});continue}if(remove.has(key)){patches.push({type:1});continue}else if(update.has(key)){const nodeTo=update.get(key);patches.push({type:3,attributes:attributes(node,nodeTo),children:children(node,nodeTo)});continue}}patches.push(void 0)}for(const node of add.values())patches.push({type:0,node:clone(node)});return patches}__name(uniqueChildren,"uniqueChildren");function children(from,to){const patches=[],len=Math.max(from.childNodes.length,to.childNodes.length);for(let i=0;i<len;i++){const a=from.childNodes.item(i),b=to.childNodes.item(i);hasPermanentParent(a)||hasPermanentParent(b)?patches[i]={type:7}:patches[i]=diff(a,b)}return patches}__name(children,"children");function diff(from,to){if(hasPermanentParent(from)||hasPermanentParent(to))return{type:7};if(!from)return{type:0,node:clone(to)};if(!to)return hasPermanentParent(from)?{type:7}:{type:1};if(same.type(from,to)){if(from.nodeType===3){const a=from.nodeValue,b=to.nodeValue;if((a==null?void 0:a.trim().length)===0&&(b==null?void 0:b.trim().length)===0)return{type:6}}if(from.nodeType===1){if(same.name(from,to)){const childFn=from.tagName==="HEAD"?uniqueChildren:children;return{type:3,attributes:attributes(from,to),children:childFn(from,to)}}return{type:2,node:clone(to)}}else return from.nodeType===9?diff(from.documentElement,to.documentElement):same.value(from,to)?{type:6}:{type:2,value:to.nodeValue}}return{type:2,node:clone(to)}}__name(diff,"diff");function patchAttributes(el,patches){if(patches.length!==0){for(const{type,name,value}of patches)if(type===5){if(name==="class"){const currentClasses=el.getAttribute("class");if(currentClasses!=null&¤tClasses.includes("preserve-")){const preserved=Array.from(el.classList).filter(c=>c.startsWith("preserve-"));preserved.length>0?el.setAttribute("class",preserved.join(" ")):el.removeAttribute("class");continue}}el.removeAttribute(name)}else if(type===4)if(name==="class"&&value){const preserved=Array.from(el.classList).filter(c=>c.startsWith("preserve-")),newClasses=value.split(/\s+/).filter(Boolean),merged=Array.from(new Set([...newClasses,...preserved]));el.setAttribute("class",merged.join(" "))}else el.setAttribute(name,value)}}__name(patchAttributes,"patchAttributes");function updateScripts(node){if(node instanceof HTMLElement){if(node.hasAttribute("data-preserve"))return node;node.tagName==="SCRIPT"?node=clone(node):node.querySelectorAll("script").forEach(script=>{script.replaceWith(clone(script))})}return node}__name(updateScripts,"updateScripts");function patch(parent,PATCH,child){return __async(this,null,function*(){if(!PATCH)return;let el;switch(parent.nodeType===9?(parent=parent.documentElement,el=parent):child?el=child:el=parent,PATCH.type){case 7:return;case 0:{let{node}=PATCH;node=updateScripts(node),parent.appendChild(node);return}case 1:{if(!el||el.nodeType===1&&el.hasAttribute("data-preserve"))return;parent.removeChild(el);return}case 2:{if(!el||el.nodeType===1&&el.hasAttribute("data-preserve"))return;let{node,value}=PATCH;if(typeof value=="string"){el.nodeValue=value;return}node&&(node=updateScripts(node),el instanceof Element&&node instanceof Element?el.replaceWith(node):el.parentNode&&el.parentNode.replaceChild(node,el));return}case 3:{if(!el||el.nodeType!==1)return;const{attributes:attributes2,children:children2}=PATCH;patchAttributes(el,attributes2);const elements=Array.from(el.childNodes);yield Promise.all(children2.map((child2,index)=>patch(el,child2,elements[index])));return}case 6:return}})}__name(patch,"patch");function morph(from,to){return __async(this,null,function*(){const patches=diff(from,to);yield patch(document,patches)})}__name(morph,"morph");exports.ACTION_CREATE=0;exports.ACTION_PRESERVE=7;exports.ACTION_REMOVE=1;exports.ACTION_REMOVE_ATTR=5;exports.ACTION_REPLACE=2;exports.ACTION_SET_ATTR=4;exports.ACTION_SKIP=6;exports.ACTION_UPDATE=3;exports.NODE_TYPE_COMMENT=8;exports.NODE_TYPE_DOCUMENT=9;exports.NODE_TYPE_ELEMENT=1;exports.NODE_TYPE_TEXT=3;exports.diff=diff;exports.morph=morph;exports.patch=patch;
|