@7x7cl/qwik
Version:
An Open-Source sub-framework designed with a focus on server-side-rendering, lazy-loading, and styling/animation.
1,402 lines (1,377 loc) • 343 kB
JavaScript
/**
* @license
* @builder.io/qwik 1.1.5-dev20230608174334
* Copyright Builder.io, Inc. All Rights Reserved.
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://github.com/BuilderIO/qwik/blob/main/LICENSE
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@builder.io/qwik/build')) :
typeof define === 'function' && define.amd ? define(['exports', '@builder.io/qwik/build'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.qwikCore = {}, global.qwikBuild));
})(this, (function (exports, build) { 'use strict';
// <docs markdown="../readme.md#implicit$FirstArg">
// !!DO NOT EDIT THIS COMMENT DIRECTLY!!!
// (edit ../readme.md#implicit$FirstArg instead)
/**
* Create a `____$(...)` convenience method from `___(...)`.
*
* It is very common for functions to take a lazy-loadable resource as a first argument. For this
* reason, the Qwik Optimizer automatically extracts the first argument from any function which
* ends in `$`.
*
* This means that `foo$(arg0)` and `foo($(arg0))` are equivalent with respect to Qwik Optimizer.
* The former is just a shorthand for the latter.
*
* For example, these function calls are equivalent:
*
* - `component$(() => {...})` is same as `component($(() => {...}))`
*
* ```tsx
* export function myApi(callback: QRL<() => void>): void {
* // ...
* }
*
* export const myApi$ = implicit$FirstArg(myApi);
* // type of myApi$: (callback: () => void): void
*
* // can be used as:
* myApi$(() => console.log('callback'));
*
* // will be transpiled to:
* // FILE: <current file>
* myApi(qrl('./chunk-abc.js', 'callback'));
*
* // FILE: chunk-abc.js
* export const callback = () => console.log('callback');
* ```
*
* @param fn - a function that should have its first argument automatically `$`.
* @public
*/
// </docs>
const implicit$FirstArg = (fn) => {
return function (first, ...rest) {
return fn.call(null, $(first), ...rest);
};
};
const qDev = globalThis.qDev !== false;
const qInspector = globalThis.qInspector === true;
const qSerialize = globalThis.qSerialize !== false;
const qDynamicPlatform = globalThis.qDynamicPlatform !== false;
const qTest = globalThis.qTest === true;
const qRuntimeQrl = globalThis.qRuntimeQrl === true;
const seal = (obj) => {
if (qDev) {
Object.seal(obj);
}
};
const isNode$1 = (value) => {
return value && typeof value.nodeType === 'number';
};
const isDocument = (value) => {
return value.nodeType === 9;
};
const isElement$1 = (value) => {
return value.nodeType === 1;
};
const isQwikElement = (value) => {
const nodeType = value.nodeType;
return nodeType === 1 || nodeType === 111;
};
const isNodeElement = (value) => {
const nodeType = value.nodeType;
return nodeType === 1 || nodeType === 111 || nodeType === 3;
};
const isVirtualElement = (value) => {
return value.nodeType === 111;
};
const isText = (value) => {
return value.nodeType === 3;
};
const isComment = (value) => {
return value.nodeType === 8;
};
const STYLE = qDev
? `background: #564CE0; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;`
: '';
const logError = (message, ...optionalParams) => {
const err = message instanceof Error ? message : createError(message);
const messageStr = err.stack || err.message;
console.error('%cQWIK ERROR', STYLE, messageStr, ...printParams(optionalParams));
return err;
};
const createError = (message) => {
const err = new Error(message);
return err;
};
const logErrorAndStop = (message, ...optionalParams) => {
const err = logError(message, ...optionalParams);
// eslint-disable-next-line no-debugger
debugger;
return err;
};
const _printed = /*#__PURE__*/ new Set();
const logOnceWarn = (message, ...optionalParams) => {
if (qDev) {
const key = 'warn' + String(message);
if (!_printed.has(key)) {
_printed.add(key);
logWarn(message, ...optionalParams);
}
}
};
const logWarn = (message, ...optionalParams) => {
if (qDev) {
console.warn('%cQWIK WARN', STYLE, message, ...printParams(optionalParams));
}
};
const logDebug = (message, ...optionalParams) => {
if (qDev) {
// eslint-disable-next-line no-console
console.debug('%cQWIK', STYLE, message, ...printParams(optionalParams));
}
};
const tryGetContext$1 = (element) => {
return element['_qc_'];
};
const printParams = (optionalParams) => {
if (qDev) {
return optionalParams.map((p) => {
if (isNode$1(p) && isElement$1(p)) {
return printElement(p);
}
return p;
});
}
return optionalParams;
};
const printElement = (el) => {
const ctx = tryGetContext$1(el);
const isServer = /*#__PURE__*/ (() => typeof process !== 'undefined' && !!process.versions && !!process.versions.node)();
return {
tagName: el.tagName,
renderQRL: ctx?.$componentQrl$?.getSymbol(),
element: isServer ? undefined : el,
ctx: isServer ? undefined : ctx,
};
};
const QError_stringifyClassOrStyle = 0;
const QError_verifySerializable = 3; // 'Only primitive and object literals can be serialized', value,
const QError_cannotRenderOverExistingContainer = 5; //'You can render over a existing q:container. Skipping render().'
const QError_setProperty = 6; //'Set property'
const QError_qrlIsNotFunction = 10;
const QError_dynamicImportFailed = 11;
const QError_unknownTypeArgument = 12;
const QError_notFoundContext = 13;
const QError_useMethodOutsideContext = 14;
const QError_immutableProps = 17;
const QError_useInvokeContext = 20;
const QError_containerAlreadyPaused = 21;
const QError_invalidJsxNodeType = 25;
const QError_trackUseStore = 26;
const QError_missingObjectId = 27;
const QError_invalidContext = 28;
const QError_canNotRenderHTML = 29;
const QError_qrlMissingContainer = 30;
const QError_qrlMissingChunk = 31;
const QError_invalidRefValue = 32;
const qError = (code, ...parts) => {
const text = codeToText(code);
return logErrorAndStop(text, ...parts);
};
const codeToText = (code) => {
if (qDev) {
const MAP = [
'Error while serializing class attribute',
'Can not serialize a HTML Node that is not an Element',
'Runtime but no instance found on element.',
'Only primitive and object literals can be serialized',
'Crash while rendering',
'You can render over a existing q:container. Skipping render().',
'Set property',
"Only function's and 'string's are supported.",
"Only objects can be wrapped in 'QObject'",
`Only objects literals can be wrapped in 'QObject'`,
'QRL is not a function',
'Dynamic import not found',
'Unknown type argument',
'Actual value for useContext() can not be found, make sure some ancestor component has set a value using useContextProvider()',
"Invoking 'use*()' method outside of invocation context.",
'Cant access renderCtx for existing context',
'Cant access document for existing context',
'props are immutable',
'<div> component can only be used at the root of a Qwik component$()',
'Props are immutable by default.',
`Calling a 'use*()' method outside 'component$(() => { HERE })' is not allowed. 'use*()' methods provide hooks to the 'component$' state and lifecycle, ie 'use' hooks can only be called synchronously within the 'component$' function or another 'use' method.
For more information see: https://qwik.builder.io/docs/components/tasks/#use-method-rules`,
'Container is already paused. Skipping',
'Components using useServerMount() can only be mounted in the server, if you need your component to be mounted in the client, use "useMount$()" instead',
'When rendering directly on top of Document, the root node must be a <html>',
'A <html> node must have 2 children. The first one <head> and the second one a <body>',
'Invalid JSXNode type. It must be either a function or a string. Found:',
'Tracking value changes can only be done to useStore() objects and component props',
'Missing Object ID for captured object',
'The provided Context reference is not a valid context created by createContextId()',
'<html> is the root container, it can not be rendered inside a component',
'QRLs can not be resolved because it does not have an attached container. This means that the QRL does not know where it belongs inside the DOM, so it cant dynamically import() from a relative path.',
'QRLs can not be dynamically resolved, because it does not have a chunk path',
'The JSX ref attribute must be a Signal', // 32
];
return `Code(${code}): ${MAP[code] ?? ''}`;
}
else {
return `Code(${code})`;
}
};
const createPlatform = () => {
return {
isServer: build.isServer,
importSymbol(containerEl, url, symbolName) {
if (build.isServer) {
const hash = getSymbolHash(symbolName);
const regSym = globalThis.__qwik_reg_symbols?.get(hash);
if (regSym) {
return regSym;
}
}
if (!url) {
throw qError(QError_qrlMissingChunk, symbolName);
}
if (!containerEl) {
throw qError(QError_qrlMissingContainer, url, symbolName);
}
const urlDoc = toUrl(containerEl.ownerDocument, containerEl, url).toString();
const urlCopy = new URL(urlDoc);
urlCopy.hash = '';
urlCopy.search = '';
const importURL = urlCopy.href;
return import(/* @vite-ignore */ importURL).then((mod) => {
return mod[symbolName];
});
},
raf: (fn) => {
return new Promise((resolve) => {
requestAnimationFrame(() => {
resolve(fn());
});
});
},
nextTick: (fn) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(fn());
});
});
},
chunkForSymbol(symbolName, chunk) {
return [symbolName, chunk ?? '_'];
},
};
};
/**
* Convert relative base URI and relative URL into a fully qualified URL.
*
* @param base -`QRL`s are relative, and therefore they need a base for resolution.
* - `Element` use `base.ownerDocument.baseURI`
* - `Document` use `base.baseURI`
* - `string` use `base` as is
* - `QConfig` use `base.baseURI`
* @param url - relative URL
* @returns fully qualified URL.
*/
const toUrl = (doc, containerEl, url) => {
const baseURI = doc.baseURI;
const base = new URL(containerEl.getAttribute('q:base') ?? baseURI, baseURI);
return new URL(url, base);
};
let _platform = /*#__PURE__ */ createPlatform();
// <docs markdown="./readme.md#setPlatform">
// !!DO NOT EDIT THIS COMMENT DIRECTLY!!!
// (edit ./readme.md#setPlatform instead)
/**
* Sets the `CorePlatform`.
*
* This is useful to override the platform in tests to change the behavior of,
* `requestAnimationFrame`, and import resolution.
*
* @param doc - The document of the application for which the platform is needed.
* @param platform - The platform to use.
* @public
*/
// </docs>
const setPlatform = (plt) => (_platform = plt);
// <docs markdown="./readme.md#getPlatform">
// !!DO NOT EDIT THIS COMMENT DIRECTLY!!!
// (edit ./readme.md#getPlatform instead)
/**
* Retrieve the `CorePlatform`.
*
* The `CorePlatform` is also responsible for retrieving the Manifest, that contains mappings
* from symbols to javascript import chunks. For this reason, `CorePlatform` can't be global, but
* is specific to the application currently running. On server it is possible that many different
* applications are running in a single server instance, and for this reason the `CorePlatform`
* is associated with the application document.
*
* @param docOrNode - The document (or node) of the application for which the platform is needed.
* @public
*/
// </docs>
const getPlatform = () => {
return _platform;
};
const isServerPlatform = () => {
if (qDynamicPlatform) {
return _platform.isServer;
}
return false;
};
const ASSERT_DISCLAIMER = 'Internal assert, this is likely caused by a bug in Qwik: ';
function assertDefined(value, text, ...parts) {
if (qDev) {
if (value != null) {
return;
}
throw logErrorAndStop(ASSERT_DISCLAIMER + text, ...parts);
}
}
function assertEqual(value1, value2, text, ...parts) {
if (qDev) {
if (value1 === value2) {
return;
}
throw logErrorAndStop(ASSERT_DISCLAIMER + text, ...parts);
}
}
function assertFail(text, ...parts) {
if (qDev) {
throw logErrorAndStop(ASSERT_DISCLAIMER + text, ...parts);
}
}
function assertTrue(value1, text, ...parts) {
if (qDev) {
if (value1 === true) {
return;
}
throw logErrorAndStop(ASSERT_DISCLAIMER + text, ...parts);
}
}
function assertNumber(value1, text, ...parts) {
if (qDev) {
if (typeof value1 === 'number') {
return;
}
throw logErrorAndStop(ASSERT_DISCLAIMER + text, ...parts);
}
}
function assertString(value1, text, ...parts) {
if (qDev) {
if (typeof value1 === 'string') {
return;
}
throw logErrorAndStop(ASSERT_DISCLAIMER + text, ...parts);
}
}
function assertQwikElement(el) {
if (qDev) {
if (!isQwikElement(el)) {
console.error('Not a Qwik Element, got', el);
throw logErrorAndStop(ASSERT_DISCLAIMER + 'Not a Qwik Element');
}
}
}
function assertElement(el) {
if (qDev) {
if (!isElement$1(el)) {
console.error('Not a Element, got', el);
throw logErrorAndStop(ASSERT_DISCLAIMER + 'Not an Element');
}
}
}
/**
* @private
*/
const isSerializableObject = (v) => {
const proto = Object.getPrototypeOf(v);
return proto === Object.prototype || proto === null;
};
const isObject = (v) => {
return v && typeof v === 'object';
};
const isArray = (v) => {
return Array.isArray(v);
};
const isString = (v) => {
return typeof v === 'string';
};
const isFunction = (v) => {
return typeof v === 'function';
};
const isPromise = (value) => {
return value instanceof Promise;
};
const safeCall = (call, thenFn, rejectFn) => {
try {
const promise = call();
if (isPromise(promise)) {
return promise.then(thenFn, rejectFn);
}
else {
return thenFn(promise);
}
}
catch (e) {
return rejectFn(e);
}
};
const then = (promise, thenFn) => {
return isPromise(promise) ? promise.then(thenFn) : thenFn(promise);
};
const promiseAll = (promises) => {
const hasPromise = promises.some(isPromise);
if (hasPromise) {
return Promise.all(promises);
}
return promises;
};
const promiseAllLazy = (promises) => {
if (promises.length > 0) {
return Promise.all(promises);
}
return promises;
};
const isNotNullable = (v) => {
return v != null;
};
const delay = (timeout) => {
return new Promise((resolve) => {
setTimeout(resolve, timeout);
});
};
// import { qDev } from './qdev';
const EMPTY_ARRAY = [];
const EMPTY_OBJ = {};
if (qDev) {
Object.freeze(EMPTY_ARRAY);
Object.freeze(EMPTY_OBJ);
}
const getDocument = (node) => {
if (!qDynamicPlatform) {
return document;
}
if (typeof document !== 'undefined') {
return document;
}
if (node.nodeType === 9) {
return node;
}
const doc = node.ownerDocument;
assertDefined(doc, 'doc must be defined');
return doc;
};
/**
* State factory of the component.
*/
const OnRenderProp = 'q:renderFn';
/**
* Component style content prefix
*/
const ComponentStylesPrefixContent = '⭐️';
/**
* `<some-element q:slot="...">`
*/
const QSlot = 'q:slot';
const QSlotRef = 'q:sref';
const QSlotS = 'q:s';
const QStyle = 'q:style';
const QScopedStyle = 'q:sstyle';
const QLocaleAttr = 'q:locale';
const QContainerAttr = 'q:container';
const QContainerSelector = '[q\\:container]';
const ResourceEvent = 'qResource';
const ComputedEvent = 'qComputed';
const RenderEvent = 'qRender';
const ELEMENT_ID = 'q:id';
const ELEMENT_ID_PREFIX = '#';
const fromCamelToKebabCase = (text) => {
return text.replace(/([A-Z])/g, '-$1').toLowerCase();
};
const fromKebabToCamelCase = (text) => {
return text.replace(/-./g, (x) => x[1].toUpperCase());
};
const directSetAttribute = (el, prop, value) => {
return el.setAttribute(prop, value);
};
const directGetAttribute = (el, prop) => {
return el.getAttribute(prop);
};
const directRemoveAttribute = (el, prop) => {
return el.removeAttribute(prop);
};
const CONTAINER_STATE = Symbol('ContainerState');
/**
* @internal
*/
const _getContainerState = (containerEl) => {
let set = containerEl[CONTAINER_STATE];
if (!set) {
containerEl[CONTAINER_STATE] = set = createContainerState(containerEl, directGetAttribute(containerEl, 'q:base') ?? '/');
}
return set;
};
const createContainerState = (containerEl, base) => {
const containerState = {
$containerEl$: containerEl,
$elementIndex$: 0,
$styleMoved$: false,
$proxyMap$: new WeakMap(),
$opsNext$: new Set(),
$watchNext$: new Set(),
$watchStaging$: new Set(),
$hostsNext$: new Set(),
$hostsStaging$: new Set(),
$styleIds$: new Set(),
$events$: new Set(),
$serverData$: {},
$base$: base,
$renderPromise$: undefined,
$hostsRendering$: undefined,
$pauseCtx$: undefined,
$subsManager$: null,
};
seal(containerState);
containerState.$subsManager$ = createSubscriptionManager(containerState);
return containerState;
};
const removeContainerState = (containerEl) => {
delete containerEl[CONTAINER_STATE];
};
const setRef = (value, elm) => {
if (isFunction(value)) {
return value(elm);
}
else if (isObject(value)) {
if ('value' in value) {
return (value.value = elm);
}
}
throw qError(QError_invalidRefValue, value);
};
const SHOW_ELEMENT = 1;
const SHOW_COMMENT$1 = 128;
const FILTER_REJECT$1 = 2;
const FILTER_SKIP = 3;
const isContainer$1 = (el) => {
return isElement$1(el) && el.hasAttribute(QContainerAttr);
};
const intToStr = (nu) => {
return nu.toString(36);
};
const strToInt = (nu) => {
return parseInt(nu, 36);
};
const getEventName = (attribute) => {
const colonPos = attribute.indexOf(':');
if (attribute) {
return fromKebabToCamelCase(attribute.slice(colonPos + 1));
}
else {
return attribute;
}
};
const ON_PROP_REGEX = /^(on|window:|document:)/;
const PREVENT_DEFAULT = 'preventdefault:';
const isOnProp = (prop) => {
return prop.endsWith('$') && ON_PROP_REGEX.test(prop);
};
const groupListeners = (listeners) => {
if (listeners.length === 0) {
return EMPTY_ARRAY;
}
if (listeners.length === 1) {
const listener = listeners[0];
return [[listener[0], [listener[1]]]];
}
const keys = [];
for (let i = 0; i < listeners.length; i++) {
const eventName = listeners[i][0];
if (!keys.includes(eventName)) {
keys.push(eventName);
}
}
return keys.map((eventName) => {
return [eventName, listeners.filter((l) => l[0] === eventName).map((a) => a[1])];
});
};
const setEvent = (existingListeners, prop, input, containerEl) => {
assertTrue(prop.endsWith('$'), 'render: event property does not end with $', prop);
prop = normalizeOnProp(prop.slice(0, -1));
if (input) {
if (isArray(input)) {
const processed = input
.flat(Infinity)
.filter((q) => q != null)
.map((q) => [prop, ensureQrl(q, containerEl)]);
existingListeners.push(...processed);
}
else {
existingListeners.push([prop, ensureQrl(input, containerEl)]);
}
}
return prop;
};
const PREFIXES = ['on', 'window:on', 'document:on'];
const SCOPED = ['on', 'on-window', 'on-document'];
const normalizeOnProp = (prop) => {
let scope = 'on';
for (let i = 0; i < PREFIXES.length; i++) {
const prefix = PREFIXES[i];
if (prop.startsWith(prefix)) {
scope = SCOPED[i];
prop = prop.slice(prefix.length);
break;
}
}
if (prop.startsWith('-')) {
prop = fromCamelToKebabCase(prop.slice(1));
}
else {
prop = prop.toLowerCase();
}
return scope + ':' + prop;
};
const ensureQrl = (value, containerEl) => {
if (qSerialize && !qRuntimeQrl) {
assertQrl(value);
value.$setContainer$(containerEl);
return value;
}
const qrl = isQrl(value) ? value : $(value);
qrl.$setContainer$(containerEl);
return qrl;
};
const getDomListeners = (elCtx, containerEl) => {
const attributes = elCtx.$element$.attributes;
const listeners = [];
for (let i = 0; i < attributes.length; i++) {
const { name, value } = attributes.item(i);
if (name.startsWith('on:') ||
name.startsWith('on-window:') ||
name.startsWith('on-document:')) {
const urls = value.split('\n');
for (const url of urls) {
const qrl = parseQRL(url, containerEl);
if (qrl.$capture$) {
inflateQrl(qrl, elCtx);
}
listeners.push([name, qrl]);
}
}
}
return listeners;
};
function isElement(value) {
return isNode(value) && value.nodeType === 1;
}
function isNode(value) {
return value && typeof value.nodeType === 'number';
}
const QObjectRecursive = 1 << 0;
const QObjectImmutable = 1 << 1;
const QOjectTargetSymbol = Symbol('proxy target');
const QObjectFlagsSymbol = Symbol('proxy flags');
const QObjectManagerSymbol = Symbol('proxy manager');
/**
* @internal
*/
const _IMMUTABLE = Symbol('IMMUTABLE');
const _IMMUTABLE_PREFIX = '$$';
/**
* @internal
*/
const _fnSignal = (fn, args, fnStr) => {
return new SignalDerived(fn, args, fnStr);
};
const serializeDerivedSignalFunc = (signal) => {
const fnBody = qSerialize ? signal.$funcStr$ : 'null';
assertDefined(fnBody, 'If qSerialize is true then fnStr must be provided.');
let args = '';
for (let i = 0; i < signal.$args$.length; i++) {
args += `p${i},`;
}
return `(${args})=>(${fnBody})`;
};
var _a$1;
/**
* @internal
*/
const _createSignal = (value, containerState, flags, subscriptions) => {
const manager = containerState.$subsManager$.$createManager$(subscriptions);
const signal = new SignalImpl(value, manager, flags);
return signal;
};
const QObjectSignalFlags = Symbol('proxy manager');
const SIGNAL_IMMUTABLE = 1 << 0;
const SIGNAL_UNASSIGNED = 1 << 1;
const SignalUnassignedException = Symbol('unassigned signal');
class SignalBase {
}
class SignalImpl extends SignalBase {
constructor(v, manager, flags) {
super();
this[_a$1] = 0;
this.untrackedValue = v;
this[QObjectManagerSymbol] = manager;
this[QObjectSignalFlags] = flags;
}
// prevent accidental use as value
valueOf() {
if (qDev) {
throw new TypeError('Cannot coerce a Signal, use `.value` instead');
}
}
toString() {
return `[Signal ${String(this.value)}]`;
}
toJSON() {
return { value: this.value };
}
get value() {
if (this[QObjectSignalFlags] & SIGNAL_UNASSIGNED) {
throw SignalUnassignedException;
}
const sub = tryGetInvokeContext()?.$subscriber$;
if (sub) {
this[QObjectManagerSymbol].$addSub$(sub);
}
return this.untrackedValue;
}
set value(v) {
if (qDev) {
if (this[QObjectSignalFlags] & SIGNAL_IMMUTABLE) {
throw new Error('Cannot mutate immutable signal');
}
if (qSerialize) {
verifySerializable(v);
}
const invokeCtx = tryGetInvokeContext();
if (invokeCtx) {
if (invokeCtx.$event$ === RenderEvent) {
logWarn('State mutation inside render function. Use useTask$() instead.', invokeCtx.$hostElement$);
}
else if (invokeCtx.$event$ === ComputedEvent) {
logWarn('State mutation inside useComputed$() is an antipattern. Use useTask$() instead', invokeCtx.$hostElement$);
}
else if (invokeCtx.$event$ === ResourceEvent) {
logWarn('State mutation inside useResource$() is an antipattern. Use useTask$() instead', invokeCtx.$hostElement$);
}
}
}
const manager = this[QObjectManagerSymbol];
const oldValue = this.untrackedValue;
if (manager && oldValue !== v) {
this.untrackedValue = v;
manager.$notifySubs$();
}
}
}
_a$1 = QObjectSignalFlags;
class SignalDerived extends SignalBase {
constructor($func$, $args$, $funcStr$) {
super();
this.$func$ = $func$;
this.$args$ = $args$;
this.$funcStr$ = $funcStr$;
}
get value() {
return this.$func$.apply(undefined, this.$args$);
}
}
class SignalWrapper extends SignalBase {
constructor(ref, prop) {
super();
this.ref = ref;
this.prop = prop;
}
get [QObjectManagerSymbol]() {
return getProxyManager(this.ref);
}
get value() {
return this.ref[this.prop];
}
set value(value) {
this.ref[this.prop] = value;
}
}
const isSignal = (obj) => {
return obj instanceof SignalBase;
};
/**
* @internal
*/
const _wrapProp = (obj, prop) => {
if (!isObject(obj)) {
return obj[prop];
}
if (obj instanceof SignalBase) {
assertEqual(prop, 'value', 'Left side is a signal, prop must be value');
return obj;
}
const target = getProxyTarget(obj);
if (target) {
const signal = target[_IMMUTABLE_PREFIX + prop];
if (signal) {
assertTrue(isSignal(signal), `${_IMMUTABLE_PREFIX} has to be a signal kind`);
return signal;
}
if (target[_IMMUTABLE]?.[prop] !== true) {
return new SignalWrapper(obj, prop);
}
}
const immutable = obj[_IMMUTABLE]?.[prop];
if (isSignal(immutable)) {
return immutable;
}
return _IMMUTABLE;
};
/**
* @internal
*/
const _wrapSignal = (obj, prop) => {
const r = _wrapProp(obj, prop);
if (r === _IMMUTABLE) {
return obj[prop];
}
return r;
};
/**
* Creates a proxy that notifies of any writes.
*/
const getOrCreateProxy = (target, containerState, flags = 0) => {
const proxy = containerState.$proxyMap$.get(target);
if (proxy) {
return proxy;
}
if (flags !== 0) {
setObjectFlags(target, flags);
}
return createProxy(target, containerState, undefined);
};
const createProxy = (target, containerState, subs) => {
assertEqual(unwrapProxy(target), target, 'Unexpected proxy at this location', target);
assertTrue(!containerState.$proxyMap$.has(target), 'Proxy was already created', target);
assertTrue(isObject(target), 'Target must be an object');
assertTrue(isSerializableObject(target) || isArray(target), 'Target must be a serializable object');
const manager = containerState.$subsManager$.$createManager$(subs);
const proxy = new Proxy(target, new ReadWriteProxyHandler(containerState, manager));
containerState.$proxyMap$.set(target, proxy);
return proxy;
};
const createPropsState = () => {
const props = {};
setObjectFlags(props, QObjectImmutable);
return props;
};
const setObjectFlags = (obj, flags) => {
Object.defineProperty(obj, QObjectFlagsSymbol, { value: flags, enumerable: false });
};
/**
* @internal
*/
const _restProps = (props, omit) => {
const rest = {};
for (const key in props) {
if (!omit.includes(key)) {
rest[key] = props[key];
}
}
return rest;
};
class ReadWriteProxyHandler {
constructor($containerState$, $manager$) {
this.$containerState$ = $containerState$;
this.$manager$ = $manager$;
}
deleteProperty(target, prop) {
if (target[QObjectFlagsSymbol] & QObjectImmutable) {
throw qError(QError_immutableProps);
}
if (typeof prop != 'string' || !delete target[prop]) {
return false;
}
this.$manager$.$notifySubs$(isArray(target) ? undefined : prop);
return true;
}
get(target, prop) {
if (typeof prop === 'symbol') {
if (prop === QOjectTargetSymbol) {
return target;
}
if (prop === QObjectManagerSymbol) {
return this.$manager$;
}
return target[prop];
}
const flags = target[QObjectFlagsSymbol] ?? 0;
assertNumber(flags, 'flags must be an number');
const invokeCtx = tryGetInvokeContext();
const recursive = (flags & QObjectRecursive) !== 0;
const immutable = (flags & QObjectImmutable) !== 0;
const hiddenSignal = target[_IMMUTABLE_PREFIX + prop];
let subscriber;
let value;
if (invokeCtx) {
subscriber = invokeCtx.$subscriber$;
}
if (immutable && (!(prop in target) || immutableValue(target[_IMMUTABLE]?.[prop]))) {
subscriber = null;
}
if (hiddenSignal) {
assertTrue(isSignal(hiddenSignal), '$$ prop must be a signal');
value = hiddenSignal.value;
subscriber = null;
}
else {
value = target[prop];
}
if (subscriber) {
const isA = isArray(target);
this.$manager$.$addSub$(subscriber, isA ? undefined : prop);
}
return recursive ? wrap(value, this.$containerState$) : value;
}
set(target, prop, newValue) {
if (typeof prop === 'symbol') {
target[prop] = newValue;
return true;
}
const flags = target[QObjectFlagsSymbol] ?? 0;
assertNumber(flags, 'flags must be an number');
const immutable = (flags & QObjectImmutable) !== 0;
if (immutable) {
throw qError(QError_immutableProps);
}
const recursive = (flags & QObjectRecursive) !== 0;
const unwrappedNewValue = recursive ? unwrapProxy(newValue) : newValue;
if (qDev) {
if (qSerialize) {
verifySerializable(unwrappedNewValue);
}
const invokeCtx = tryGetInvokeContext();
if (invokeCtx) {
if (invokeCtx.$event$ === RenderEvent) {
logError('State mutation inside render function. Move mutation to useTask$() or useVisibleTask$()', prop);
}
else if (invokeCtx.$event$ === ComputedEvent) {
logWarn('State mutation inside useComputed$() is an antipattern. Use useTask$() instead', invokeCtx.$hostElement$);
}
else if (invokeCtx.$event$ === ResourceEvent) {
logWarn('State mutation inside useResource$() is an antipattern. Use useTask$() instead', invokeCtx.$hostElement$);
}
}
}
const isA = isArray(target);
if (isA) {
target[prop] = unwrappedNewValue;
this.$manager$.$notifySubs$();
return true;
}
const oldValue = target[prop];
target[prop] = unwrappedNewValue;
if (oldValue !== unwrappedNewValue) {
this.$manager$.$notifySubs$(prop);
}
return true;
}
has(target, property) {
if (property === QOjectTargetSymbol) {
return true;
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
if (hasOwnProperty.call(target, property)) {
return true;
}
if (typeof property === 'string' && hasOwnProperty.call(target, _IMMUTABLE_PREFIX + property)) {
return true;
}
return false;
}
ownKeys(target) {
const flags = target[QObjectFlagsSymbol] ?? 0;
assertNumber(flags, 'flags must be an number');
const immutable = (flags & QObjectImmutable) !== 0;
if (!immutable) {
let subscriber = null;
const invokeCtx = tryGetInvokeContext();
if (invokeCtx) {
subscriber = invokeCtx.$subscriber$;
}
if (subscriber) {
this.$manager$.$addSub$(subscriber);
}
}
if (isArray(target)) {
return Reflect.ownKeys(target);
}
return Reflect.ownKeys(target).map((a) => {
return typeof a === 'string' && a.startsWith(_IMMUTABLE_PREFIX)
? a.slice(_IMMUTABLE_PREFIX.length)
: a;
});
}
getOwnPropertyDescriptor(target, prop) {
if (isArray(target) || typeof prop === 'symbol') {
return Object.getOwnPropertyDescriptor(target, prop);
}
return {
enumerable: true,
configurable: true,
};
}
}
const immutableValue = (value) => {
return value === _IMMUTABLE || isSignal(value);
};
const wrap = (value, containerState) => {
if (isObject(value)) {
if (Object.isFrozen(value)) {
return value;
}
const nakedValue = unwrapProxy(value);
if (nakedValue !== value) {
// already a proxy return;
return value;
}
if (fastSkipSerialize(nakedValue)) {
return value;
}
if (isSerializableObject(nakedValue) || isArray(nakedValue)) {
const proxy = containerState.$proxyMap$.get(nakedValue);
return proxy ? proxy : getOrCreateProxy(nakedValue, containerState, QObjectRecursive);
}
}
return value;
};
const Q_CTX = '_qc_';
const HOST_FLAG_DIRTY = 1 << 0;
const HOST_FLAG_NEED_ATTACH_LISTENER = 1 << 1;
const HOST_FLAG_MOUNTED = 1 << 2;
const HOST_FLAG_DYNAMIC = 1 << 3;
const tryGetContext = (element) => {
return element[Q_CTX];
};
const getContext = (el, containerState) => {
assertQwikElement(el);
const ctx = tryGetContext(el);
if (ctx) {
return ctx;
}
const elCtx = createContext(el);
const elementID = directGetAttribute(el, 'q:id');
if (elementID) {
const pauseCtx = containerState.$pauseCtx$;
elCtx.$id$ = elementID;
if (pauseCtx) {
const { getObject, meta, refs } = pauseCtx;
if (isElement(el)) {
const refMap = refs[elementID];
if (refMap) {
assertTrue(isElement(el), 'el must be an actual DOM element');
elCtx.$refMap$ = refMap.split(' ').map(getObject);
elCtx.li = getDomListeners(elCtx, containerState.$containerEl$);
}
}
else {
const styleIds = el.getAttribute(QScopedStyle);
elCtx.$scopeIds$ = styleIds ? styleIds.split('|') : null;
const ctxMeta = meta[elementID];
if (ctxMeta) {
const seq = ctxMeta.s;
const host = ctxMeta.h;
const contexts = ctxMeta.c;
const watches = ctxMeta.w;
if (seq) {
elCtx.$seq$ = seq.split(' ').map(getObject);
}
if (watches) {
elCtx.$watches$ = watches.split(' ').map(getObject);
}
if (contexts) {
elCtx.$contexts$ = new Map();
for (const part of contexts.split(' ')) {
const [key, value] = part.split('=');
elCtx.$contexts$.set(key, getObject(value));
}
}
// Restore sequence scoping
if (host) {
const [renderQrl, props] = host.split(' ');
elCtx.$flags$ = HOST_FLAG_MOUNTED;
if (renderQrl) {
elCtx.$componentQrl$ = getObject(renderQrl);
}
if (props) {
const propsObj = getObject(props);
elCtx.$props$ = propsObj;
setObjectFlags(propsObj, QObjectImmutable);
propsObj[_IMMUTABLE] = getImmutableFromProps(propsObj);
}
else {
elCtx.$props$ = createProxy(createPropsState(), containerState);
}
}
}
}
}
}
return elCtx;
};
const getImmutableFromProps = (props) => {
const immutable = {};
const target = getProxyTarget(props);
for (const key in target) {
if (key.startsWith(_IMMUTABLE_PREFIX)) {
immutable[key.slice(_IMMUTABLE_PREFIX.length)] = target[key];
}
}
return immutable;
};
const createContext = (element) => {
const ctx = {
$flags$: 0,
$id$: '',
$element$: element,
$refMap$: [],
li: [],
$watches$: null,
$seq$: null,
$slots$: null,
$scopeIds$: null,
$appendStyles$: null,
$props$: null,
$vdom$: null,
$componentQrl$: null,
$contexts$: null,
$dynamicSlots$: null,
$parent$: null,
$slotParent$: null,
};
seal(ctx);
element[Q_CTX] = ctx;
return ctx;
};
const cleanupContext = (elCtx, subsManager) => {
elCtx.$watches$?.forEach((watch) => {
subsManager.$clearSub$(watch);
destroyWatch(watch);
});
elCtx.$componentQrl$ = null;
elCtx.$seq$ = null;
elCtx.$watches$ = null;
};
let _locale = undefined;
/**
* Retrieve the current lang.
*
* If no current lang and there is no `defaultLang` the function throws an error.
*
* @returns the lang.
* @internal
*/
function getLocale(defaultLocale) {
if (_locale === undefined) {
const ctx = tryGetInvokeContext();
if (ctx && ctx.$locale$) {
return ctx.$locale$;
}
if (defaultLocale !== undefined) {
return defaultLocale;
}
throw new Error('Reading `locale` outside of context.');
}
return _locale;
}
/**
* Override the `getLocale` with `lang` within the `fn` execution.
*
* @internal
*/
function withLocale(locale, fn) {
const previousLang = _locale;
try {
_locale = locale;
return fn();
}
finally {
_locale = previousLang;
}
}
/**
* Globally set a lang.
*
* This can be used only in browser. Server execution requires that each
* request could potentially be a different lang, therefore setting
* a global lang would produce incorrect responses.
*
* @param lang
*/
function setLocale(locale) {
_locale = locale;
}
let _context;
/**
* @public
*/
const tryGetInvokeContext = () => {
if (!_context) {
const context = typeof document !== 'undefined' && document && document.__q_context__;
if (!context) {
return undefined;
}
if (isArray(context)) {
return (document.__q_context__ = newInvokeContextFromTuple(context));
}
return context;
}
return _context;
};
const getInvokeContext = () => {
const ctx = tryGetInvokeContext();
if (!ctx) {
throw qError(QError_useMethodOutsideContext);
}
return ctx;
};
const useInvokeContext = () => {
const ctx = tryGetInvokeContext();
if (!ctx || ctx.$event$ !== RenderEvent) {
throw qError(QError_useInvokeContext);
}
assertDefined(ctx.$hostElement$, `invoke: $hostElement$ must be defined`, ctx);
assertDefined(ctx.$waitOn$, `invoke: $waitOn$ must be defined`, ctx);
assertDefined(ctx.$renderCtx$, `invoke: $renderCtx$ must be defined`, ctx);
assertDefined(ctx.$subscriber$, `invoke: $subscriber$ must be defined`, ctx);
return ctx;
};
const useBindInvokeContext = (callback) => {
if (callback == null) {
return callback;
}
const ctx = getInvokeContext();
return ((...args) => {
return invoke(ctx, callback.bind(undefined, ...args));
});
};
function invoke(context, fn, ...args) {
const previousContext = _context;
let returnValue;
try {
_context = context;
returnValue = fn.apply(this, args);
}
finally {
_context = previousContext;
}
return returnValue;
}
const waitAndRun = (ctx, callback) => {
const waitOn = ctx.$waitOn$;
if (waitOn.length === 0) {
const result = callback();
if (isPromise(result)) {
waitOn.push(result);
}
}
else {
waitOn.push(Promise.all(waitOn).then(callback));
}
};
const newInvokeContextFromTuple = (context) => {
const element = context[0];
const container = element.closest(QContainerSelector);
const locale = container?.getAttribute(QLocaleAttr) || undefined;
locale && setLocale(locale);
return newInvokeContext(locale, undefined, element, context[1], context[2]);
};
const newInvokeContext = (locale, hostElement, element, event, url) => {
const ctx = {
$seq$: 0,
$hostElement$: hostElement,
$element$: element,
$event$: event,
$url$: url,
$locale$: locale,
$qrl$: undefined,
$renderCtx$: undefined,
$subscriber$: undefined,
$waitOn$: undefined,
};
seal(ctx);
return ctx;
};
const getWrappingContainer = (el) => {
return el.closest(QContainerSelector);
};
/**
* @public
*/
const untrack = (fn) => {
return invoke(undefined, fn);
};
const trackInvocation = /*#__PURE__*/ newInvokeContext(undefined, undefined, undefined, RenderEvent);
/**
* @public
*/
const trackSignal = (signal, sub) => {
trackInvocation.$subscriber$ = sub;
return invoke(trackInvocation, () => signal.value);
};
/**
* @internal
*/
const _getContextElement = () => {
const iCtx = tryGetInvokeContext();
if (iCtx) {
return (iCtx.$element$ ?? iCtx.$hostElement$ ?? iCtx.$qrl$?.$setContainer$(undefined));
}
};
/**
* @internal
*/
const _getContextEvent = () => {
const iCtx = tryGetInvokeContext();
if (iCtx) {
return iCtx.$event$;
}
};
/**
* @internal
*/
const _jsxBranch = (input) => {
const iCtx = tryGetInvokeContext();
if (iCtx && iCtx.$hostElement$ && iCtx.$renderCtx$) {
const hostElement = iCtx.$hostElement$;
const elCtx = getContext(hostElement, iCtx.$renderCtx$.$static$.$containerState$);
elCtx.$flags$ |= HOST_FLAG_DYNAMIC;
}
return input;
};
/**
* @internal
*/
const _waitUntilRendered = (elm) => {
const containerEl = getWrappingContainer(elm);
if (!containerEl) {
return Promise.resolve();
}
const containerState = _getContainerState(containerEl);
return containerState.$renderPromise$ ?? Promise.resolve();
};
// <docs markdown="../readme.md#useOn">
// !!DO NOT EDIT THIS COMMENT DIRECTLY!!!
// (edit ../readme.md#useOn instead)
/**
* Register a listener on the current component's host element.
*
* Used to programmatically add event listeners. Useful from custom `use*` methods, which do not
* have access to the JSX. Otherwise, it's