packages/core/src/lib/define-primitive.ts
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import {
2 derivePrimitiveMetadata,
3 getPrimitiveDefinition,
4 setPrimitiveDefinition,
5 } from './element/metadata.js';
6 import {
7 CANVAS_2D_BACKEND,
8 } from './backend/canvas-2d-backend.js';
9 import type {
10 PibblBackendPrimitiveProgram,
11 PibblBackendToken,
12 } from './backend/types.js';
13 import type {
14 PibblPrimitiveComponent,
15 PreservedSignalPropKey,
16 PrimitiveCapabilities,
17 PrimitiveInput,
18 PrimitiveProgramProps,
19 PrimitiveRender,
20 RenderingContext2D,
21 SystemStyle,
22 } from './types.js';
23 import { GLOBAL_STATE } from './global-state.js';
24 import { withSignalWriteForbidden } from './signals/graph.js';
25 import type { SizingLength } from './style/sizing-length.js';
26
27 type DeclaresWhen<S> = S extends unknown ? 'when' extends keyof S ? true : false : never;
28 type PrimitiveStyleGuard<S, N, R> = true extends DeclaresWhen<S> | DeclaresWhen<N> | DeclaresWhen<R> ? {
29 readonly 'Pibbl: style.when is framework-owned; remove when from the primitive style type': never;
30 } : unknown;
31
32 // Any nonnumeric sizing syntax depends on allocation or an intrinsic owner.
33 // A primitive must normalize it before its render program receives the style.
34 type AllocationValue = Exclude<SizingLength, number | 'stretch'>;
35 type StretchSizingValue<S> = S extends unknown ? S[Extract<keyof S, 'width' | 'height' | 'minWidth' | 'maxWidth' | 'minHeight' | 'maxHeight' | 'flexBasis'>] : never;
36 type DeclaredStyleValue<S> = S extends unknown
37 ? S[Exclude<keyof S, 'custom'>]
38 : never;
39 type RequiresResolver<S> = [
40 Extract<DeclaredStyleValue<S>, AllocationValue> | Extract<StretchSizingValue<S>, 'stretch'>,
41 ] extends [never] ? false : true;
42 type PrimitiveCapabilitiesInput<
43 P,
44 S extends SystemStyle,
45 N extends SystemStyle,
46 R extends SystemStyle,
47 > = Readonly<PrimitiveCapabilities<P, S, N, R>> & PrimitiveStyleGuard<S, N, R> & (
48 [PreservedSignalPropKey<P>] extends [never] ? object : {
49 readonly preserveSignalProps: readonly [
50 PreservedSignalPropKey<P>,
51 ...PreservedSignalPropKey<P>[],
52 ];
53 }
54 );
55 type CapabilityArguments<
56 P,
57 S extends SystemStyle,
58 N extends SystemStyle,
59 R extends SystemStyle,
60 > = RequiresResolver<R> extends true ? [capabilities: never] :
61 RequiresResolver<S> extends true ? [
62 capabilities: PrimitiveCapabilitiesInput<P, S, N, R> & {
63 resolveStyle: NonNullable<
64 PrimitiveCapabilities<P, S, N, R>['resolveStyle']
65 >;
66 },
67 ] : [PreservedSignalPropKey<P>] extends [never] ? [
68 capabilities?: PrimitiveCapabilitiesInput<P, S, N, R>,
69 ] : [capabilities: PrimitiveCapabilitiesInput<P, S, N, R>];
70
71 /**
72 * Defines a platform component with private style and measurement behavior.
73 *
74 * @param render - Synchronous primitive renderer receiving props, resolved style, and Canvas
75 * context. See {@link PrimitiveRender} , {@link PrimitiveStyleGuard} , {@link PrimitiveInput} .
76 * @param capabilityArguments - Style normalization, resolution, and measurement capabilities
77 * required by the primitive. See {@link CapabilityArguments} .
78 * @returns A primitive component usable with JSX or createElement. See
79 * {@link PibblPrimitiveComponent} , {@link PrimitiveProgramProps} , {@link PrimitiveInput} .
80 *
81 * @see {@link PrimitiveRender}
82 * @see {@link PrimitiveInput}
83 * @see {@link PibblPrimitiveComponent}
84 * @see {@link PrimitiveProgramProps}
85 * @see {@link SystemStyle}
86 */
87 export function definePrimitive<
88 P = Record<string, never>,
89 S extends SystemStyle = SystemStyle,
90 N extends SystemStyle = S,
91 R extends SystemStyle = N,
92 >(
93 render: PrimitiveRender<P, R> & PrimitiveStyleGuard<S, N, R> & (
94 PrimitiveInput<P, S> extends never ? never : unknown
95 ),
96 ...capabilityArguments: CapabilityArguments<P, S, N, R>
97 ): PibblPrimitiveComponent<PrimitiveProgramProps<P>, PrimitiveInput<P, S>> {
98 return defineBackendPrimitive<P, S, N, R, RenderingContext2D>(
99 CANVAS_2D_BACKEND.token,
100 render,
101 ...capabilityArguments,
102 );
103 }
104
105 /**
106 * Defines a primitive owned by one official Pibbl rendering backend.
107 *
108 * @param backend - Identity of the backend that can execute this primitive. See
109 * {@link PibblBackendToken} .
110 * @param program - Synchronous program using the active backend environment. See
111 * {@link PibblBackendPrimitiveProgram} , {@link PrimitiveStyleGuard} , {@link PrimitiveInput} .
112 * @param capabilityArguments - Style and measurement capabilities for the primitive. See
113 * {@link CapabilityArguments} .
114 * @returns A primitive component bound to the specified backend. See {@link PibblPrimitiveComponent}
115 * , {@link PrimitiveProgramProps} , {@link PrimitiveInput} .
116 *
117 * @see {@link PibblBackendToken}
118 * @see {@link PibblBackendPrimitiveProgram}
119 * @see {@link PrimitiveInput}
120 * @see {@link PibblPrimitiveComponent}
121 * @see {@link PrimitiveProgramProps}
122 * @see {@link SystemStyle}
123 */
124 export function defineBackendPrimitive<
125 P = Record<string, never>,
126 S extends SystemStyle = SystemStyle,
127 N extends SystemStyle = S,
128 R extends SystemStyle = N,
129 E = unknown,
130 >(
131 backend: PibblBackendToken,
132 program: PibblBackendPrimitiveProgram<P, R, E> & PrimitiveStyleGuard<S, N, R> & (
133 PrimitiveInput<P, S> extends never ? never : unknown
134 ),
135 ...capabilityArguments: CapabilityArguments<P, S, N, R>
136 ): PibblPrimitiveComponent<PrimitiveProgramProps<P>, PrimitiveInput<P, S>> {
137 const componentName = primitiveComponentName(program.name);
138 const component = function PibblPrimitiveComponent(): never {
139 throw new Error(
140 `${componentName} is a Pibbl component and was invoked outside the Pibbl ` +
141 'renderer.\n' +
142 `Use <${componentName} ... /> in a Pibbl JSX file or ` +
143 `createElement(${componentName}, props).`,
144 );
145 } as unknown as PibblPrimitiveComponent<
146 PrimitiveProgramProps<P>,
147 PrimitiveInput<P, S>
148 >;
149 Object.defineProperty(component, 'name', {
150 configurable: true,
151 value: componentName,
152 });
153
154 const capabilities = (capabilityArguments[0] ?? {}) as Readonly<
155 PrimitiveCapabilities<P, S, N, R>
156 >;
157 setPrimitiveDefinition(component, {
158 backend,
159 program,
160 preserveSignalProps: capabilities.preserveSignalProps,
161 childInput: capabilities.childInput,
162 normalizeStyle: capabilities.normalizeStyle,
163 resolveStyle: capabilities.resolveStyle,
164 measure: capabilities.measure,
165 measureIntrinsic: capabilities.measureIntrinsic,
166 measureBaselines: capabilities.measureBaselines,
167 });
168 return component;
169 }
170
171 /**
172 * Derives a new official-package primitive identity with the source behavior.
173 *
174 * @param source - Primitive whose rendering and capabilities are reused.
175 * @returns A derived primitive with its own component identity.
176 *
177 * @see {@link PibblPrimitiveComponent}
178 */
179 export function derivePrimitive<T extends PibblPrimitiveComponent<any, any>>(
180 source: T,
181 ): T {
182 if (!getPrimitiveDefinition(source)) {
183 throw new TypeError('Can only derive a Pibbl primitive component.');
184 }
185 const componentName = source.name || 'Anonymous';
186 const derived = function PibblPrimitiveComponent(): never {
187 throw new Error(
188 `${componentName} is a Pibbl component and was invoked outside the Pibbl ` +
189 'renderer.\n' +
190 `Use <${componentName} ... /> in a Pibbl JSX file or ` +
191 `createElement(${componentName}, props).`,
192 );
193 } as unknown as T;
194 Object.defineProperty(derived, 'name', {
195 configurable: true,
196 value: componentName,
197 });
198 derivePrimitiveMetadata(source, derived);
199 return derived;
200 }
201
202 /**
203 * Runs one official-package primitive resolver without render side-effect authority.
204 *
205 * @param callback - Synchronous resolver to evaluate with hooks and signal writes forbidden.
206 * @returns The resolver's return value.
207 *
208 * @see {@link PrimitiveCapabilities}
209 */
210 export function pibblInternalRunPurePrimitiveResolver<T>(callback: () => T): T {
211 const previousComponentRefs = GLOBAL_STATE.componentRefs;
212 const previousComponentHookIndex = GLOBAL_STATE.componentHookIndex;
213 const previousComponentIsMounting = GLOBAL_STATE.componentIsMounting;
214 GLOBAL_STATE.componentRefs = undefined;
215 GLOBAL_STATE.componentHookIndex = 0;
216 GLOBAL_STATE.componentIsMounting = false;
217 try {
218 return withSignalWriteForbidden('Pibbl pure primitive resolver', callback);
219 } finally {
220 GLOBAL_STATE.componentRefs = previousComponentRefs;
221 GLOBAL_STATE.componentHookIndex = previousComponentHookIndex;
222 GLOBAL_STATE.componentIsMounting = previousComponentIsMounting;
223 }
224 }
225
226 function primitiveComponentName(renderName: string): string {
227 if (/^render[A-Z]/.test(renderName)) return renderName.slice('render'.length);
228 return renderName || 'Anonymous';
229 }
230
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.