@qwik.dev/core
Version:
An open source framework for building instant loading web apps at any scale, without the extra effort.
1,348 lines (1,243 loc) • 164 kB
TypeScript
import { ComputedSignal as ComputedSignal_2 } from '..';
import * as CSS_2 from 'csstype';
import { isBrowser } from './build';
import { isDev } from './build';
import { isServer } from './build';
import { JSXNode as JSXNode_2 } from './types/jsx-node';
import { QRL as QRL_2 } from './qrl.public';
/**
* Qwik Optimizer marker function.
*
* Use `$(...)` to tell Qwik Optimizer to extract the expression in `$(...)` into a lazy-loadable
* resource referenced by `QRL`.
*
* @param expression - Expression which should be lazy loaded
* @public
* @see `implicit$FirstArg` for additional `____$(...)` rules.
*
* In this example, `$(...)` is used to capture the callback function of `onmousemove` into a
* lazy-loadable reference. This allows the code to refer to the function without actually
* loading the function. In this example, the callback function does not get loaded until
* `mousemove` event fires.
*
* ```tsx
* useOnDocument(
* 'mousemove',
* $((event) => console.log('mousemove', event))
* );
* ```
*
* In this code, the Qwik Optimizer detects `$(...)` and transforms the code into:
*
* ```tsx
* // FILE: <current file>
* useOnDocument('mousemove', qrl('./chunk-abc.js', 'onMousemove'));
*
* // FILE: chunk-abc.js
* export const onMousemove = () => console.log('mousemove');
* ```
*
* ## Special Rules
*
* The Qwik Optimizer places special rules on functions that can be lazy-loaded.
*
* 1. The expression of the `$(expression)` function must be importable by the system.
* (expression shows up in `import` or has `export`)
* 2. If inlined function, then all lexically captured values must be:
* - importable (vars show up in `import`s or `export`s)
* - const (The capturing process differs from JS capturing in that writing to captured
* variables does not update them, and therefore writes are forbidden. The best practice is that
* all captured variables are constants.)
* - Must be runtime serializable.
*
* ```tsx
*
* import { createContextId, useContext, useContextProvider } from './use/use-context';
* import { Resource } from './use/use-resource';
* import { useResource$ } from './use/use-resource-dollar';
* import { useSignal } from './use/use-signal';
*
* export const greet = () => console.log('greet');
* function topLevelFn() {}
*
* function myCode() {
* const store = useStore({});
* function localFn() {}
* // Valid Examples
* $(greet); // greet is importable
* $(() => greet()); // greet is importable;
* $(() => console.log(store)); // store is serializable.
*
* // Compile time errors
* $(topLevelFn); // ERROR: `topLevelFn` not importable
* $(() => topLevelFn()); // ERROR: `topLevelFn` not importable
*
* // Runtime errors
* $(localFn); // ERROR: `localFn` fails serialization
* $(() => localFn()); // ERROR: `localFn` fails serialization
* }
*
* ```
*/
export declare const $: <T>(expression: T) => QRL<T>;
declare interface AddRootFn {
(obj: unknown, returnRef?: never): number;
(obj: unknown, returnRef: true): SeenRef;
}
declare type AllEventKeys = keyof AllEventsMap;
declare type AllEventMapRaw = HTMLElementEventMap & DocumentEventMap & WindowEventHandlersEventMap & {
qidle: QwikIdleEvent;
qinit: QwikInitEvent;
qsymbol: QwikSymbolEvent;
qvisible: QwikVisibleEvent;
qviewtransition: QwikViewTransitionEvent;
};
declare type AllEventsMap = Omit<AllEventMapRaw, keyof EventCorrectionMap> & EventCorrectionMap;
declare type _AllowPlainQrl<Q> = QRLEventHandlerMulti<any, any> extends Q ? Q extends QRLEventHandlerMulti<infer EV, infer EL> ? Q | (EL extends Element ? EventHandler<EV, EL> : never) : Q : Q extends QRL<infer U> ? Q | U : NonNullable<Q> extends never ? Q : QRL<Q> | Q;
declare type AllPascalEventMaps = PascalMap<AllEventsMap>;
declare type AllSignalFlags = SignalFlags | WrappedSignalFlags | SerializationSignalFlags;
/**
* TS defines these with the React syntax which is not compatible with Qwik. E.g. `ariaAtomic`
* instead of `aria-atomic`.
*
* @public
*/
declare interface AriaAttributes {
/**
* Identifies the currently active element when DOM focus is on a composite widget, textbox,
* group, or application.
*/
'aria-activedescendant'?: string | undefined;
/**
* Indicates whether assistive technologies will present all, or only parts of, the changed region
* based on the change notifications defined by the aria-relevant attribute.
*/
'aria-atomic'?: Booleanish | undefined;
/**
* Indicates whether inputting text could trigger display of one or more predictions of the user's
* intended value for an input and specifies how predictions would be presented if they are made.
*/
'aria-autocomplete'?: 'none' | 'inline' | 'list' | 'both' | undefined;
/**
* Indicates an element is being modified and that assistive technologies MAY want to wait until
* the modifications are complete before exposing them to the user.
*/
'aria-busy'?: Booleanish | undefined;
/**
* Indicates the current "checked" state of checkboxes, radio buttons, and other widgets.
*
* @see aria-pressed @see aria-selected.
*/
'aria-checked'?: boolean | 'false' | 'mixed' | 'true' | undefined;
/**
* Defines the total number of columns in a table, grid, or treegrid.
*
* @see aria-colindex.
*/
'aria-colcount'?: number | undefined;
/**
* Defines an element's column index or position with respect to the total number of columns
* within a table, grid, or treegrid.
*
* @see aria-colcount @see aria-colspan.
*/
'aria-colindex'?: number | undefined;
/**
* Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid.
*
* @see aria-colindex @see aria-rowspan.
*/
'aria-colspan'?: number | undefined;
/**
* Identifies the element (or elements) whose contents or presence are controlled by the current
* element.
*
* @see aria-owns.
*/
'aria-controls'?: string | undefined;
/**
* Indicates the element that represents the current item within a container or set of related
* elements.
*/
'aria-current'?: boolean | 'false' | 'true' | 'page' | 'step' | 'location' | 'date' | 'time' | undefined;
/**
* Identifies the element (or elements) that describes the object.
*
* @see aria-labelledby
*/
'aria-describedby'?: string | undefined;
/**
* Identifies the element that provides a detailed, extended description for the object.
*
* @see aria-describedby.
*/
'aria-details'?: string | undefined;
/**
* Indicates that the element is perceivable but disabled, so it is not editable or otherwise
* operable.
*
* @see aria-hidden @see aria-readonly.
*/
'aria-disabled'?: Booleanish | undefined;
/**
* Indicates what functions can be performed when a dragged object is released on the drop target.
*
* @deprecated In ARIA 1.1
*/
'aria-dropeffect'?: 'none' | 'copy' | 'execute' | 'link' | 'move' | 'popup' | undefined;
/**
* Identifies the element that provides an error message for the object.
*
* @see aria-invalid @see aria-describedby.
*/
'aria-errormessage'?: string | undefined;
/**
* Indicates whether the element, or another grouping element it controls, is currently expanded
* or collapsed.
*/
'aria-expanded'?: Booleanish | undefined;
/**
* Identifies the next element (or elements) in an alternate reading order of content which, at
* the user's discretion, allows assistive technology to override the general default of reading
* in document source order.
*/
'aria-flowto'?: string | undefined;
/**
* Indicates an element's "grabbed" state in a drag-and-drop operation.
*
* @deprecated In ARIA 1.1
*/
'aria-grabbed'?: Booleanish | undefined;
/**
* Indicates the availability and type of interactive popup element, such as menu or dialog, that
* can be triggered by an element.
*/
'aria-haspopup'?: boolean | 'false' | 'true' | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog' | undefined;
/**
* Indicates whether the element is exposed to an accessibility API.
*
* @see aria-disabled.
*/
'aria-hidden'?: Booleanish | undefined;
/**
* Indicates the entered value does not conform to the format expected by the application.
*
* @see aria-errormessage.
*/
'aria-invalid'?: boolean | 'false' | 'true' | 'grammar' | 'spelling' | undefined;
/**
* Indicates keyboard shortcuts that an author has implemented to activate or give focus to an
* element.
*/
'aria-keyshortcuts'?: string | undefined;
/**
* Defines a string value that labels the current element.
*
* @see aria-labelledby.
*/
'aria-label'?: string | undefined;
/**
* Identifies the element (or elements) that labels the current element.
*
* @see aria-describedby.
*/
'aria-labelledby'?: string | undefined;
/** Defines the hierarchical level of an element within a structure. */
'aria-level'?: number | undefined;
/**
* Indicates that an element will be updated, and describes the types of updates the user agents,
* assistive technologies, and user can expect from the live region.
*/
'aria-live'?: 'off' | 'assertive' | 'polite' | undefined;
/** Indicates whether an element is modal when displayed. */
'aria-modal'?: Booleanish | undefined;
/** Indicates whether a text box accepts multiple lines of input or only a single line. */
'aria-multiline'?: Booleanish | undefined;
/** Indicates that the user may select more than one item from the current selectable descendants. */
'aria-multiselectable'?: Booleanish | undefined;
/** Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */
'aria-orientation'?: 'horizontal' | 'vertical' | undefined;
/**
* Identifies an element (or elements) in order to define a visual, functional, or contextual
* parent/child relationship between DOM elements where the DOM hierarchy cannot be used to
* represent the relationship.
*
* @see aria-controls.
*/
'aria-owns'?: string | undefined;
/**
* Defines a short hint (a word or short phrase) intended to aid the user with data entry when the
* control has no value. A hint could be a sample value or a brief description of the expected
* format.
*/
'aria-placeholder'?: string | undefined;
/**
* Defines an element's number or position in the current set of listitems or treeitems. Not
* required if all elements in the set are present in the DOM.
*
* @see aria-setsize.
*/
'aria-posinset'?: number | undefined;
/**
* Indicates the current "pressed" state of toggle buttons.
*
* @see aria-checked @see aria-selected.
*/
'aria-pressed'?: boolean | 'false' | 'mixed' | 'true' | undefined;
/**
* Indicates that the element is not editable, but is otherwise operable.
*
* @see aria-disabled.
*/
'aria-readonly'?: Booleanish | undefined;
/**
* Indicates what notifications the user agent will trigger when the accessibility tree within a
* live region is modified.
*
* @see aria-atomic.
*/
'aria-relevant'?: 'additions' | 'additions removals' | 'additions text' | 'all' | 'removals' | 'removals additions' | 'removals text' | 'text' | 'text additions' | 'text removals' | undefined;
/** Indicates that user input is required on the element before a form may be submitted. */
'aria-required'?: Booleanish | undefined;
/** Defines a human-readable, author-localized description for the role of an element. */
'aria-roledescription'?: string | undefined;
/**
* Defines the total number of rows in a table, grid, or treegrid.
*
* @see aria-rowindex.
*/
'aria-rowcount'?: number | undefined;
/**
* Defines an element's row index or position with respect to the total number of rows within a
* table, grid, or treegrid.
*
* @see aria-rowcount @see aria-rowspan.
*/
'aria-rowindex'?: number | undefined;
/**
* Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid.
*
* @see aria-rowindex @see aria-colspan.
*/
'aria-rowspan'?: number | undefined;
/**
* Indicates the current "selected" state of various widgets.
*
* @see aria-checked @see aria-pressed.
*/
'aria-selected'?: Booleanish | undefined;
/**
* Defines the number of items in the current set of listitems or treeitems. Not required if all
* elements in the set are present in the DOM.
*
* @see aria-posinset.
*/
'aria-setsize'?: number | undefined;
/** Indicates if items in a table or grid are sorted in ascending or descending order. */
'aria-sort'?: 'none' | 'ascending' | 'descending' | 'other' | undefined;
/** Defines the maximum allowed value for a range widget. */
'aria-valuemax'?: number | undefined;
/** Defines the minimum allowed value for a range widget. */
'aria-valuemin'?: number | undefined;
/**
* Defines the current value for a range widget.
*
* @see aria-valuetext.
*/
'aria-valuenow'?: number | undefined;
/** Defines the human readable text alternative of aria-valuenow for a range widget. */
'aria-valuetext'?: string | undefined;
}
/** @public */
declare type AriaRole = 'alert' | 'alertdialog' | 'application' | 'article' | 'banner' | 'button' | 'cell' | 'checkbox' | 'columnheader' | 'combobox' | 'complementary' | 'contentinfo' | 'definition' | 'dialog' | 'directory' | 'document' | 'feed' | 'figure' | 'form' | 'grid' | 'gridcell' | 'group' | 'heading' | 'img' | 'link' | 'list' | 'listbox' | 'listitem' | 'log' | 'main' | 'marquee' | 'math' | 'menu' | 'menubar' | 'menuitem' | 'menuitemcheckbox' | 'menuitemradio' | 'navigation' | 'none' | 'note' | 'option' | 'presentation' | 'progressbar' | 'radio' | 'radiogroup' | 'region' | 'row' | 'rowgroup' | 'rowheader' | 'scrollbar' | 'search' | 'searchbox' | 'separator' | 'slider' | 'spinbutton' | 'status' | 'switch' | 'tab' | 'table' | 'tablist' | 'tabpanel' | 'term' | 'textbox' | 'timer' | 'toolbar' | 'tooltip' | 'tree' | 'treegrid' | 'treeitem' | (string & {});
declare type AsyncComputedCtx = {
track: Tracker;
cleanup: (callback: () => void) => void;
};
/** @public */
export declare type AsyncComputedFn<T> = (ctx: AsyncComputedCtx) => Promise<T>;
/** @public */
export declare interface AsyncComputedReadonlySignal<T = unknown> extends ComputedSignal<T> {
/** Whether the signal is currently loading. */
loading: boolean;
/** The error that occurred while computing the signal. */
error: Error | null;
resolve(): Promise<T>;
}
/** @public */
export declare type AsyncComputedReturnType<T> = T extends Promise<infer T> ? AsyncComputedReadonlySignal<T> : AsyncComputedReadonlySignal<T>;
/**
* # ================================
*
* AsyncComputedSignalImpl
*
* # ================================
*/
declare class AsyncComputedSignalImpl<T> extends ComputedSignalImpl<T, AsyncComputeQRL<T>> implements BackRef {
$untrackedLoading$: boolean;
$untrackedError$: Error | null;
$loadingEffects$: null | Set<EffectSubscription>;
$errorEffects$: null | Set<EffectSubscription>;
$destroy$: NoSerialize<() => void> | null;
private $promiseValue$;
[_EFFECT_BACK_REF]: Map<EffectProperty | string, EffectSubscription> | null;
constructor(container: Container | null, fn: AsyncComputeQRL<T>, flags?: SignalFlags | SerializationSignalFlags);
/**
* Loading is true if the signal is still waiting for the promise to resolve, false if the promise
* has resolved or rejected.
*/
get loading(): boolean;
set untrackedLoading(value: boolean);
get untrackedLoading(): boolean;
/** The error that occurred when the signal was resolved. */
get error(): Error | null;
set untrackedError(value: Error | null);
get untrackedError(): Error | null;
invalidate(): void;
resolve(): Promise<T>;
$computeIfNeeded$(): boolean | undefined;
}
declare type AsyncComputeQRL<T> = QRLInternal<AsyncComputedFn<T>>;
/**
* Replace given element's props with custom types and return all props specific to the element. Use
* this for known props that are incorrect or missing.
*
* Uses Prettify so we see the special props for each element in editor hover
*/
declare type Augmented<E, A = {}> = Prettify<Filtered<E, A> & A>;
/** Class for back reference to the EffectSubscription */
declare abstract class BackRef {
[_EFFECT_BACK_REF]: Map<EffectProperty | string, EffectSubscription> | null;
}
declare type BivariantQrlFn<ARGS extends any[], RETURN> = {
/**
* Resolve the QRL of closure and invoke it.
*
* @param args - Closure arguments.
* @returns A promise of the return value of the closure.
*/
bivarianceHack(...args: ARGS): Promise<RETURN>;
}['bivarianceHack'];
/** @public */
declare type Booleanish = boolean | `${boolean}`;
/**
* Handles events for bind:checked
*
* @internal
*/
export declare const _chk: (_: any, element: HTMLInputElement) => void;
declare interface Chore<T extends ChoreType = ChoreType> {
$type$: T;
$idx$: number | string;
$host$: HostElement;
$target$: ChoreTarget | null;
$payload$: unknown;
$state$: ChoreState;
$blockedChores$: ChoreArray | null;
$startTime$: number | undefined;
$endTime$: number | undefined;
$resolve$: ((value: any) => void) | undefined;
$reject$: ((reason?: any) => void) | undefined;
$returnValue$: ValueOrPromise<ChoreReturnValue<T>>;
}
declare class ChoreArray extends Array<Chore> {
add(value: Chore): number;
delete(value: Chore): number;
}
declare type ChoreReturnValue<T extends ChoreType = ChoreType> = T extends ChoreType.RECOMPUTE_AND_SCHEDULE_EFFECTS | ChoreType.WAIT_FOR_QUEUE | ChoreType.NODE_PROP ? void : T extends ChoreType.NODE_DIFF | ChoreType.COMPONENT ? JSXOutput : unknown;
declare enum ChoreState {
NONE = 0,
RUNNING = 1,
FAILED = 2,
DONE = 3
}
declare type ChoreTarget = HostElement | QRLInternal<(...args: unknown[]) => unknown> | Signal | StoreTarget;
declare const enum ChoreType {
MACRO = 240,
MICRO = 15,
/** Ensure that the QRL promise is resolved before processing next chores in the queue */
QRL_RESOLVE = 1,
RUN_QRL = 2,
TASK = 3,
NODE_DIFF = 4,
NODE_PROP = 5,
COMPONENT = 6,
RECOMPUTE_AND_SCHEDULE_EFFECTS = 7,
VISIBLE = 16,
CLEANUP_VISIBLE = 32,
WAIT_FOR_QUEUE = 255
}
/**
* A class list can be a string, a boolean, an array, or an object.
*
* If it's an array, each item is a class list and they are all added.
*
* If it's an object, then the keys are class name strings, and the values are booleans that
* determine if the class name string should be added or not.
*
* @public
*/
export declare type ClassList = string | undefined | null | false | Record<string, boolean | string | number | null | undefined> | ClassList[];
/** @internal */
export declare interface ClientContainer extends Container {
document: _QDocument;
element: _ContainerElement;
qContainer: string;
$locale$: string;
qManifestHash: string;
rootVNode: _ElementVNode;
$journal$: VNodeJournal;
$forwardRefs$: Array<number> | null;
$flushEpoch$: number;
parseQRL<T = unknown>(qrl: string): QRL<T>;
$setRawState$(id: number, vParent: _ElementVNode | _VirtualVNode): void;
}
/**
* Declare a Qwik component that can be used to create UI.
*
* Use `component$` to declare a Qwik component. A Qwik component is a special kind of component
* that allows the Qwik framework to lazy load and execute the component independently of other Qwik
* components as well as lazy load the component's life-cycle hooks and event handlers.
*
* Side note: You can also declare regular (standard JSX) components that will have standard
* synchronous behavior.
*
* Qwik component is a facade that describes how the component should be used without forcing the
* implementation of the component to be eagerly loaded. A minimum Qwik definition consists of:
*
* ### Example
*
* An example showing how to create a counter component:
*
* ```tsx
* export interface CounterProps {
* initialValue?: number;
* step?: number;
* }
* export const Counter = component$((props: CounterProps) => {
* const state = useStore({ count: props.initialValue || 0 });
* return (
* <div>
* <span>{state.count}</span>
* <button onClick$={() => (state.count += props.step || 1)}>+</button>
* </div>
* );
* });
* ```
*
* - `component$` is how a component gets declared.
* - `{ value?: number; step?: number }` declares the public (props) interface of the component.
* - `{ count: number }` declares the private (state) interface of the component.
*
* The above can then be used like so:
*
* ```tsx
* export const OtherComponent = component$(() => {
* return <Counter initialValue={100} />;
* });
* ```
*
* See also: `component`, `useCleanup`, `onResume`, `onPause`, `useOn`, `useOnDocument`,
* `useOnWindow`, `useStyles`
*
* @public
*/
export declare const component$: <PROPS = unknown>(onMount: OnRenderFn<PROPS>) => Component<PROPS>;
/**
* Type representing the Qwik component.
*
* `Component` is the type returned by invoking `component$`.
*
* ```tsx
* interface MyComponentProps {
* someProp: string;
* }
* const MyComponent: Component<MyComponentProps> = component$((props: MyComponentProps) => {
* return <span>{props.someProp}</span>;
* });
* ```
*
* @public
*/
export declare type Component<PROPS = unknown> = FunctionComponent<PublicProps<PROPS>>;
/** @public */
export declare interface ComponentBaseProps {
key?: string | number | null | undefined;
'q:slot'?: string;
}
declare type ComponentChildren<PROPS> = PROPS extends {
children: any;
} ? never : {
children?: JSXChildren;
};
/** @public */
declare interface ComponentEntryStrategy {
type: 'component';
manual?: Record<string, string>;
}
/** @internal */
export declare const componentQrl: <PROPS extends Record<any, any>>(componentQrl: QRL<OnRenderFn<PROPS>>) => Component<PROPS>;
/** @public */
export declare type ComputedFn<T> = () => T;
/** @public */
export declare interface ComputedOptions {
serializationStrategy?: SerializationStrategy;
container?: Container;
}
/** @public */
export declare type ComputedReturnType<T> = T extends Promise<any> ? never : ComputedSignal<T>;
/**
* A computed signal is a signal which is calculated from other signals. When the signals change,
* the computed signal is recalculated, and if the result changed, all tasks which are tracking the
* signal will be re-run and all components that read the signal will be re-rendered.
*
* @public
*/
export declare interface ComputedSignal<T> extends ReadonlySignal<T> {
/**
* Use this to force running subscribers, for example when the calculated value mutates but
* remains the same object.
*/
force(): void;
/**
* Use this to force recalculation and running subscribers, for example when the calculated value
* mutates but remains the same object.
*/
invalidate(): void;
}
/**
* A signal which is computed from other signals.
*
* The value is available synchronously, but the computation is done lazily.
*/
declare class ComputedSignalImpl<T, S extends QRLInternal = ComputeQRL<T>> extends SignalImpl<T> implements BackRef {
/**
* The compute function is stored here.
*
* The computed functions must be executed synchronously (because of this we need to eagerly
* resolve the QRL during the mark dirty phase so that any call to it will be synchronous). )
*/
$computeQrl$: S;
$flags$: SignalFlags | SerializationSignalFlags;
[_EFFECT_BACK_REF]: Map<EffectProperty | string, EffectSubscription> | null;
constructor(container: Container | null, fn: S, flags?: SignalFlags | SerializationSignalFlags);
invalidate(): void;
/**
* Use this to force running subscribers, for example when the calculated value has mutated but
* remained the same object
*/
force(): void;
get untrackedValue(): T;
$computeIfNeeded$(): void;
set value(_: any);
get value(): any;
}
declare type ComputeQRL<T> = QRLInternal<ComputedFn<T>>;
/** @internal */
export declare const _CONST_PROPS: unique symbol;
/**
* Effect is something which needs to happen (side-effect) due to signal value change.
*
* There are three types of effects:
*
* - `Task`: `useTask`, `useVisibleTask`, `useResource`
* - `VNode` and `ISsrNode`: Either a component or `<Signal>`
* - `Signal2`: A derived signal which contains a computation function.
*/
declare type Consumer = Task | _VNode | ISsrNode | SignalImpl;
declare interface Container {
readonly $version$: string;
readonly $scheduler$: Scheduler;
readonly $storeProxyMap$: ObjToProxyMap;
readonly $locale$: string;
readonly $getObjectById$: (id: number | string) => any;
readonly $serverData$: Record<string, any>;
$currentUniqueId$: number;
$buildBase$: string | null;
handleError(err: any, $host$: HostElement | null): void;
getParentHost(host: HostElement): HostElement | null;
setContext<T>(host: HostElement, context: ContextId<T>, value: T): void;
resolveContext<T>(host: HostElement, contextId: ContextId<T>): T | undefined;
setHostProp<T>(host: HostElement, name: string, value: T): void;
getHostProp<T>(host: HostElement, name: string): T | null;
$appendStyle$(content: string, styleId: string, host: HostElement, scoped: boolean): void;
/**
* When component is about to be executed, it may add/remove children. This can cause problems
* with the projection because deleting content will prevent the projection references from
* looking up vnodes. Therefore before we execute the component we need to ensure that all of its
* references to vnode are resolved.
*
* @param renderHost - Host element to ensure projection is resolved.
*/
ensureProjectionResolved(host: HostElement): void;
serializationCtxFactory(NodeConstructor: {
new (...rest: any[]): {
__brand__: 'SsrNode';
};
} | null, DomRefConstructor: {
new (...rest: any[]): {
__brand__: 'DomRef';
};
} | null, symbolToChunkResolver: SymbolToChunkResolver, writer?: StreamWriter): SerializationContext;
}
/** @internal */
export declare interface _ContainerElement extends HTMLElement {
qContainer?: ClientContainer;
/**
* Map of element ID to Element. If VNodeData has a reference to an element, then it is added to
* this map for later retrieval.
*
* Once retrieved the element is replaced with its VNode.
*
* NOTE: This map leaks memory! Once the application is resumed we don't know which element IDs
* are still in the deserialized state. we will probably need a GC cycle. Some process running in
* the idle time which processes few elements at a time to see if they are still referenced and
* removes them from the map if they are not.
*/
qVNodeRefs?: Map<number, Element | _ElementVNode>;
/** String from `<script type="qwik/vnode">` tag. */
qVnodeData?: string;
}
/**
* ContextId is a typesafe ID for your context.
*
* Context is a way to pass stores to the child components without prop-drilling.
*
* Use `createContextId()` to create a `ContextId`. A `ContextId` is just a serializable identifier
* for the context. It is not the context value itself. See `useContextProvider()` and
* `useContext()` for the values. Qwik needs a serializable ID for the context so that the it can
* track context providers and consumers in a way that survives resumability.
*
* ### Example
*
* ```tsx
* // Declare the Context type.
* interface TodosStore {
* items: string[];
* }
* // Create a Context ID (no data is saved here.)
* // You will use this ID to both create and retrieve the Context.
* export const TodosContext = createContextId<TodosStore>('Todos');
*
* // Example of providing context to child components.
* export const App = component$(() => {
* useContextProvider(
* TodosContext,
* useStore<TodosStore>({
* items: ['Learn Qwik', 'Build Qwik app', 'Profit'],
* })
* );
*
* return <Items />;
* });
*
* // Example of retrieving the context provided by a parent component.
* export const Items = component$(() => {
* const todos = useContext(TodosContext);
* return (
* <ul>
* {todos.items.map((item) => (
* <li>{item}</li>
* ))}
* </ul>
* );
* });
*
* ```
*
* @public
*/
export declare interface ContextId<STATE> {
/** Design-time property to store type information for the context. */
readonly __brand_context_type__: STATE;
/** A unique ID for the context. */
readonly id: string;
}
/**
* Low-level API for platform abstraction.
*
* Different platforms (browser, node, service workers) may have different ways of handling things
* such as `requestAnimationFrame` and imports. To make Qwik platform-independent Qwik uses the
* `CorePlatform` API to access the platform API.
*
* `CorePlatform` also is responsible for importing symbols. The import map is different on the
* client (browser) then on the server. For this reason, the server has a manifest that is used to
* map symbols to javascript chunks. The manifest is encapsulated in `CorePlatform`, for this
* reason, the `CorePlatform` can't be global as there may be multiple applications running at
* server concurrently.
*
* This is a low-level API and there should not be a need for you to access this.
*
* @public
*/
export declare interface CorePlatform {
/**
* True of running on the server platform.
*
* @returns True if we are running on the server (not the browser.)
*/
isServer: boolean;
/**
* Retrieve a symbol value from QRL.
*
* Qwik needs to lazy load data and closures. For this Qwik uses QRLs that are serializable
* references of resources that are needed. The QRLs contain all the information necessary to
* retrieve the reference using `importSymbol`.
*
* Why not use `import()`? Because `import()` is relative to the current file, and the current
* file is always the Qwik framework. So QRLs have additional information that allows them to
* serialize imports relative to application base rather than the Qwik framework file.
*
* @param element - The element against which the `url` is resolved. Used to locate the container
* root and `q:base` attribute.
* @param url - Relative URL retrieved from the attribute that needs to be resolved against the
* container `q:base` attribute.
* @param symbol - The name of the symbol to import.
* @returns A promise that resolves to the imported symbol.
*/
importSymbol: (containerEl: Element | undefined, url: string | URL | undefined | null, symbol: string) => ValueOrPromise<any>;
/**
* Perform operation on next request-animation-frame.
*
* @param fn - The function to call when the next animation frame is ready.
*/
raf: (fn: () => any) => Promise<any>;
/**
* Retrieve chunk name for the symbol.
*
* When the application is running on the server the symbols may be imported from different files
* (as server build is typically a single javascript chunk.) For this reason, it is necessary to
* convert the chunks from server format to client (browser) format. This is done by looking up
* symbols (which are globally unique) in the manifest. (Manifest is the mapping of symbols to the
* client chunk names.)
*
* @param symbolName - Resolve `symbolName` against the manifest and return the chunk that
* contains the symbol.
*/
chunkForSymbol: (symbolName: string, chunk: string | null, parent?: string) => readonly [symbol: string, chunk: string] | undefined;
}
/** This corrects the TS definition for ToggleEvent @public */
export declare interface CorrectedToggleEvent extends Event {
readonly newState: 'open' | 'closed';
readonly prevState: 'open' | 'closed';
}
/**
* Create an async computed signal which is calculated from the given QRL. A computed signal is a
* signal which is calculated from other signals or async operation. When the signals change, the
* computed signal is recalculated.
*
* The QRL must be a function which returns the value of the signal. The function must not have side
* effects, and it can be async.
*
* @public
*/
export declare const createAsyncComputed$: <T>(qrl: () => Promise<T>, options?: ComputedOptions) => AsyncComputedReturnType<T>;
/** @internal */
export declare const createAsyncComputedQrl: <T>(qrl: QRL<(ctx: AsyncComputedCtx) => Promise<T>>, options?: ComputedOptions) => AsyncComputedSignalImpl<T>;
/**
* Create a computed signal which is calculated from the given QRL. A computed signal is a signal
* which is calculated from other signals. When the signals change, the computed signal is
* recalculated.
*
* The QRL must be a function which returns the value of the signal. The function must not have side
* effects, and it must be synchronous.
*
* If you need the function to be async, use `useAsyncComputed$` instead.
*
* @public
*/
export declare const createComputed$: <T>(qrl: () => T, options?: ComputedOptions) => ComputedReturnType<T>;
/** @internal */
export declare const createComputedQrl: <T>(qrl: QRL<() => T>, options?: ComputedOptions) => ComputedSignalImpl<T>;
/**
* Create a context ID to be used in your application. The name should be written with no spaces.
*
* Context is a way to pass stores to the child components without prop-drilling.
*
* Use `createContextId()` to create a `ContextId`. A `ContextId` is just a serializable identifier
* for the context. It is not the context value itself. See `useContextProvider()` and
* `useContext()` for the values. Qwik needs a serializable ID for the context so that the it can
* track context providers and consumers in a way that survives resumability.
*
* ### Example
*
* ```tsx
* // Declare the Context type.
* interface TodosStore {
* items: string[];
* }
* // Create a Context ID (no data is saved here.)
* // You will use this ID to both create and retrieve the Context.
* export const TodosContext = createContextId<TodosStore>('Todos');
*
* // Example of providing context to child components.
* export const App = component$(() => {
* useContextProvider(
* TodosContext,
* useStore<TodosStore>({
* items: ['Learn Qwik', 'Build Qwik app', 'Profit'],
* })
* );
*
* return <Items />;
* });
*
* // Example of retrieving the context provided by a parent component.
* export const Items = component$(() => {
* const todos = useContext(TodosContext);
* return (
* <ul>
* {todos.items.map((item) => (
* <li>{item}</li>
* ))}
* </ul>
* );
* });
*
* ```
*
* @param name - The name of the context.
* @public
*/
export declare const createContextId: <STATE = unknown>(name: string) => ContextId<STATE>;
declare const createScheduler: (container: Container, journalFlush: () => void, choreQueue: ChoreArray, blockedChores: Set<Chore>, runningChores: Set<Chore>) => {
(type: ChoreType.QRL_RESOLVE, ignore: null, target: ComputeQRL<any> | AsyncComputeQRL<any>): Chore<ChoreType.QRL_RESOLVE>;
(type: ChoreType.WAIT_FOR_QUEUE): Chore<ChoreType.WAIT_FOR_QUEUE>;
(type: ChoreType.RECOMPUTE_AND_SCHEDULE_EFFECTS, host: HostElement | null, target: Signal<unknown> | StoreTarget, effects: Set<EffectSubscription> | null): Chore<ChoreType.RECOMPUTE_AND_SCHEDULE_EFFECTS>;
(type: ChoreType.TASK | ChoreType.VISIBLE, task: Task): Chore<ChoreType.TASK | ChoreType.VISIBLE>;
(type: ChoreType.RUN_QRL, host: HostElement, target: QRLInternal<(...args: unknown[]) => unknown>, args: unknown[]): Chore<ChoreType.RUN_QRL>;
(type: ChoreType.COMPONENT, host: HostElement, qrl: QRLInternal<OnRenderFn<unknown>>, props: Props | null): Chore<ChoreType.COMPONENT>;
(type: ChoreType.NODE_DIFF, host: HostElement, target: HostElement, value: JSXOutput | Signal): Chore<ChoreType.NODE_DIFF>;
(type: ChoreType.NODE_PROP, host: HostElement, prop: string, value: any): Chore<ChoreType.NODE_PROP>;
(type: ChoreType.CLEANUP_VISIBLE, task: Task): Chore<ChoreType.CLEANUP_VISIBLE>;
};
/**
* Create a signal that holds a custom serializable value. See {@link useSerializer$} for more
* details.
*
* @public
*/
export declare const createSerializer$: <T, S>(arg: SerializerArg<T, S>) => T extends Promise<any> ? never : SerializerSignal<T>;
/** @internal */
export declare const createSerializerQrl: <T, S>(arg: QRL<{
serialize: (data: S | undefined) => T;
deserialize: (data: T) => S;
initial?: S;
}>) => SerializerSignalImpl<T, S>;
/**
* Creates a Signal with the given value. If no value is given, the signal is created with
* `undefined`.
*
* @public
*/
export declare const createSignal: {
<T>(): Signal<T | undefined>;
<T>(value: T): Signal<T>;
};
/** @public */
export declare interface CSSProperties extends CSS_2.Properties<string | number>, CSS_2.PropertiesHyphen<string | number> {
/**
* The index signature was removed to enable closed typing for style using CSSType. You're able to
* use type assertion or module augmentation to add properties or an index signature of your own.
*
* For examples and more information, visit:
* https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors
*/
[v: `--${string}`]: string | number | undefined;
}
/** @public */
declare interface DescriptorBase<T = unknown, B = unknown> extends BackRef {
$flags$: number;
$index$: number;
$el$: HostElement;
$qrl$: QRLInternal<T>;
$state$: B | undefined;
$destroy$: NoSerialize<() => void> | null;
}
/**
* Deserialize data from string to an array of objects.
*
* @param rawStateData - Data to deserialize
* @param element - Container element
* @internal
*/
export declare function _deserialize(rawStateData: string | null, element?: unknown): unknown[];
declare interface DeserializeContainer {
$getObjectById$: (id: number | string) => unknown;
element: HTMLElement | null;
getSyncFn: (id: number) => (...args: unknown[]) => unknown;
$state$?: unknown[];
$storeProxyMap$: ObjToProxyMap;
$forwardRefs$: Array<number> | null;
readonly $scheduler$: Scheduler | null;
}
/** @public */
export declare interface DevJSX {
fileName: string;
lineNumber: number;
columnNumber: number;
stack?: string;
}
/** The Qwik-specific attributes that DOM elements accept @public */
export declare interface DOMAttributes<EL extends Element> extends DOMAttributesBase<EL>, QwikEvents<EL> {
class?: ClassList | Signal<ClassList> | undefined;
}
declare interface DOMAttributesBase<EL extends Element> extends QwikIntrinsicAttributes, PreventDefault, StopPropagation, RefAttr<EL> {
dangerouslySetInnerHTML?: string | undefined;
}
/** @internal */
declare class DomContainer extends _SharedContainer implements ClientContainer {
element: _ContainerElement;
qContainer: string;
qManifestHash: string;
rootVNode: _ElementVNode;
document: _QDocument;
$journal$: VNodeJournal;
$rawStateData$: unknown[];
$storeProxyMap$: ObjToProxyMap;
$qFuncs$: Array<(...args: unknown[]) => unknown>;
$instanceHash$: string;
$forwardRefs$: Array<number> | null;
vNodeLocate: (id: string | Element) => _VNode;
private $stateData$;
private $styleIds$;
constructor(element: _ContainerElement);
$setRawState$(id: number, vParent: _ElementVNode | _VirtualVNode): void;
parseQRL<T = unknown>(qrl: string): QRL<T>;
handleError(err: any, host: _VNode | null): void;
setContext<T>(host: _VNode, context: ContextId<T>, value: T): void;
resolveContext<T>(host: _VNode, contextId: ContextId<T>): T | undefined;
getParentHost(host: _VNode): _VNode | null;
setHostProp<T>(host: HostElement, name: string, value: T): void;
getHostProp<T>(host: HostElement, name: string): T | null;
ensureProjectionResolved(vNode: _VirtualVNode): void;
$getObjectById$: (id: number | string) => unknown;
getSyncFn(id: number): (...args: unknown[]) => unknown;
$appendStyle$(content: string, styleId: string, host: _VirtualVNode, scoped: boolean): void;
/** Set the server data for the Qwik Router. */
private $setServerData$;
}
export { DomContainer }
export { DomContainer as _DomContainer }
declare type DomRef = {
$ssrNode$: SsrNode;
};
/** @internal */
export declare const _dumpState: (state: unknown[], color?: boolean, prefix?: string, limit?: number | null) => string;
/** @internal */
export declare const _EFFECT_BACK_REF: unique symbol;
declare const enum EffectProperty {
COMPONENT = ":",
VNODE = "."
}
/**
* An effect consumer plus type of effect, back references to producers and additional data
*
* An effect can be trigger by one or more of signal inputs. The first step of re-running an effect
* is to clear its subscriptions so that the effect can re add new set of subscriptions. In order to
* clear the subscriptions we need to store them here.
*
* Imagine you have effect such as:
*
* ```
* function effect1() {
* console.log(signalA.value ? signalB.value : 'default');
* }
* ```
*
* In the above case the `signalB` needs to be unsubscribed when `signalA` is falsy. We do this by
* always clearing all of the subscriptions
*
* The `EffectSubscription` stores
*
* ```
* subscription1 = [effectConsumer1, EffectProperty.COMPONENT, Set[(signalA, signalB)]];
* ```
*
* The `signal1` and `signal2` back references are needed to "clear" existing subscriptions.
*
* Both `signalA` as well as `signalB` will have a reference to `subscription` to the so that the
* effect can be scheduled if either `signalA` or `signalB` triggers. The `subscription1` is shared
* between the signals.
*
* The second position `EffectProperty|string` store the property name of the effect.
*
* - Property name of the VNode
* - `EffectProperty.COMPONENT` if component
* - `EffectProperty.VNODE` if VNode
*/
declare type EffectSubscription = [
Consumer,
// EffectSubscriptionProp.CONSUMER
EffectProperty | string,
// EffectSubscriptionProp.PROPERTY or string for attributes
Set<SignalImpl | StoreTarget> | null,
// EffectSubscriptionProp.BACK_REF
_SubscriptionData | null
];
/** @internal */
export declare class _ElementVNode extends _VNode {
firstChild: _VNode | null | undefined;
lastChild: _VNode | null | undefined;
element: QElement;
elementName: string | undefined;
constructor(flags: _VNodeFlags, parent: _ElementVNode | _VirtualVNode | null, previousSibling: _VNode | null | undefined, nextSibling: _VNode | null | undefined, firstChild: _VNode | null | undefined, lastChild: _VNode | null | undefined, element: QElement, elementName: string | undefined);
}
/** @internal */
export declare const _EMPTY_ARRAY: any[];
/** @public */
declare type EntryStrategy = InlineEntryStrategy | HoistEntryStrategy | SingleEntryStrategy | HookEntryStrategy | SegmentEntryStrategy | ComponentEntryStrategy | SmartEntryStrategy;
/** @public */
export declare interface ErrorBoundaryStore {
error: any | undefined;
}
/** @public */
export declare const event$: <T>(qrl: T) => QRL_2<T>;
declare type EventCorrectionMap = {
auxclick: PointerEvent;
beforetoggle: CorrectedToggleEvent;
click: PointerEvent;
dblclick: PointerEvent;
input: InputEvent;
toggle: CorrectedToggleEvent;
};
declare type EventFromName<T extends string> = LcEvent<T>;
/**
* A DOM event handler
*
* @public
*/
export declare type EventHandler<EV = Event, EL = Element> = {
bivarianceHack(event: EV, element: EL): any;
}['bivarianceHack'];
declare type EventQRL<T extends string = AllEventKeys> = QRL<EventHandler<EventFromName<T>, Element>> | undefined;
/** @internal */
export declare const eventQrl: <T>(qrl: QRL<T>) => QRL<T>;
declare type FilterBase<T> = {
[K in keyof T as K extends string ? K extends Uppercase<K> ? never : any extends T[K] ? never : false extends IsAcceptableDOMValue<T[K]> ? never : IsReadOnlyKey<T, K> extends true ? never : K extends UnwantedKeys ? never : K : never]?: T[K];
};
/** Only keep props that are specific to the element and make partial */
declare type Filtered<T, A = {}> = {
[K in keyof Omit<FilterBase<T>, keyof HTMLAttributes<any> | keyof A>]?: T[K];
};
/** @internal */
export declare const _fnSignal: <T extends (...args: any) => any>(fn: T, args: Parameters<T>, fnStr?: string) => WrappedSignalImpl<any>;
/**
* Force a store to recompute and schedule effects.
*
* @public
*/
export declare const forceStoreEffects: (value: StoreTarget, prop: keyof StoreTarget) => void;
/** @public */
export declare const Fragment: FunctionComponent<{
children?: any;
key?: string | number | null;
}>;
/**
* Any function taking a props object that returns JSXOutput.
*
* The `key`, `flags` and `dev` parameters are for internal use.
*
* @public
*/
export declare type FunctionComponent<P = unknown> = {
renderFn(props: P, key: string | null, flags: number, dev?: DevJSX): JSXOutput;
}['renderFn'];
/** Used by the optimizer for spread props operations @internal */
export declare const _getConstProps: (props: PropsProxy | Record<string, unknown> | null | undefined) => Props | null;
/** @internal */
export declare const _getContextContainer: () => ClientContainer | undefined;
/** @internal */
export declare const _getContextElement: () => unknown;
/** @internal */
export declare const _getContextEvent: () => unknown;
/** @public */
declare function getDomContainer(element: Element | _VNode): ClientContainer;
export { getDomContainer as _getDomContainer }
export { getDomContainer }
/**
* Retrieve the current locale.
*
* If no current locale and there is no `defaultLocale` the function throws an error.
*
* @returns The locale.
* @public
*/
export declare function getLocale(defaultLocale?: string): string;
/**
* 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
*/
export declare const getPlatform: () => CorePlatform;
/** @internal */
export declare function _getQContainerElement(element: Element | _VNode): Element | null;
/** Used by the optimizer for spread props operations @internal */
export declare const _getVarProps: (props: PropsProxy | Record<string, unknown> | null | undefined) => Props | null;
/** @public */
declare interface GlobalInjections {
tag: string;
attributes?: {
[key: string]: string;
};
location: 'head' | 'body';
}
/**
* The legacy transform, used by some JSX transpilers. The optimizer normally replaces this with
* optimized calls, with the same caveat as `jsx()`.
*
* @public
*/
declare function h<TYPE extends string | FunctionComponent<PROPS>, PROPS extends {} = {}>(type: TYPE, props?: PROPS | null, ...children: any[]): JSXNode<TYPE>;
export { h as createElement }
export { h }
/**
* @returns True if the store has effects for the given prop
* @internal
*/
export declare const _hasStoreEffects: (value: StoreTarget, prop: keyof StoreTarget) => boolean;
/** @public */
declare interface HoistEntryStrategy {
type: 'hoist';
}
/** @deprecated Use SegmentStrategy instead */
declare interface HookEntryStrategy {
type: 'hook';
manual?: Record<string, string>;
}
declare type HostElement = _VNode | ISsrNode;
/** @public */
declare type HTMLAttributeAnchorTarget = '_self' | '_blank' | '_parent' | '_top' | (string & {});
/** @public */
declare type HTMLAttributeReferrerPolicy = ReferrerPolicy;
/** @public */
declare interface HTMLAttributes<E extends Element> extends HTMLElementAttrs, DOMAttributes<E> {
}
declare interface HTMLAttributesBase extends AriaAttributes {
/** @deprecated Use `class` instead */
className?: ClassList | undefined;
contentEditable?: 'true' | 'false' | 'inherit' | undefined;
style?: CSSProperties | string | undefined;
role?: AriaRole | undefined;
about?: string | undefined;
datatype?: string | undefined;
inlist?: any;
property?: string | undefined;
resource?: string | undefined;
typeof?: string | undefined;
vocab?: string | undefined;
autoCapitalize?: 'none' | 'off' | 'sentences' | 'on' | 'words' | 'characters' | undefined;
autoCorrect?: string | undefined;
autoFocus?: boolean | undefined;
autoSave?: string | undefined;
hidden?: boolean | 'hidden' | 'until-found' | undefined;
itemProp?: string | undefined;
itemScope?: boolean | undefined;
itemType?: string | und