Skip to content

packages/core/src/lib/style/positioning.ts

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import type { StyleResolutionContext, SystemStyle } from '../types.js';
2 import {
3   getPlacementSignalHandoffStyle,
4   setPlacementSignalHandoff,
5 } from '../element/metadata.js';
6 import type { PibblElement } from '../element/types.js';
7 import { isSignal } from '../signals/graph.js';
8 import { resolveLocalOffset } from './resolve-built-in.js';
9 import type { Length } from './types.js';
10 
11 const PLACEMENT_HANDOFF = Symbol('pibbl.placement-handoff');
12 const PLACEMENT_DERIVED_ABSOLUTE_AXES = Symbol('pibbl.placement-derived-absolute-axes');
13 
14 type PropsWithStyle = Record<PropertyKey, unknown> & {
15   readonly style?: unknown;
16 };
17 
18 type PlacementHandoff = Readonly<{
19   source: Readonly<SystemStyle>;
20 }>;
21 
22 let activeSignalHandoff: {
23   readonly signal: object;
24   readonly consumedStyle: Readonly<SystemStyle>;
25 } | undefined;
26 
27 function hasPositioning(style: Readonly<Record<PropertyKey, unknown>>): boolean {
28   if (Object.hasOwn(style, 'position') || Object.hasOwn(style, 'left') || Object.hasOwn(style, 'right') || Object.hasOwn(style, 'top') || Object.hasOwn(style, 'bottom') || Object.hasOwn(style, 'insetStart') || Object.hasOwn(style, 'insetEnd')) return true;
29   const when = style.when;
30   return Array.isArray(when) && when.some((rule) => {
31     if (!rule || typeof rule !== 'object') return false;
32     const patch = (rule as { style?: unknown }).style;
33     return !!patch && typeof patch === 'object' &&
34       (Object.hasOwn(patch, 'position') || Object.hasOwn(patch, 'left') || Object.hasOwn(patch, 'right') || Object.hasOwn(patch, 'top') || Object.hasOwn(patch, 'bottom') || Object.hasOwn(patch, 'insetStart') || Object.hasOwn(patch, 'insetEnd'));
35   });
36 }
37 
38 /** @internal Marks only a fresh placement-owned style; authored style objects are never changed. */
39 export function markDerivedAbsoluteAxes(style: SystemStyle, width: boolean, height: boolean): void {
40   (style as Record<PropertyKey, unknown>)[PLACEMENT_DERIVED_ABSOLUTE_AXES] = (width ? 1 : 0) | (height ? 2 : 0);
41 }
42 
43 /** @internal Substitutes settled axes only across an exact forwarded placement handoff. */
44 export function resolveForwardedDerivedAbsoluteAxes(
45   style: Readonly<SystemStyle>,
46   source: Readonly<SystemStyle> | undefined,
47 ): Readonly<SystemStyle> {
48   if (source === undefined) return style;
49   const axes = (source as Record<PropertyKey, unknown>)[PLACEMENT_DERIVED_ABSOLUTE_AXES] as number | undefined;
50   if (!axes || !samePositioning(style, source)) return style;
51   const raw = style as Readonly<Record<string, unknown>>;
52   const settled = source as Readonly<Record<string, unknown>>;
53   const width = (axes & 1) !== 0 && (raw.width === undefined || raw.width === 'auto') && typeof settled.width === 'number' ? settled.width : raw.width;
54   const height = (axes & 2) !== 0 && (raw.height === undefined || raw.height === 'auto') && typeof settled.height === 'number' ? settled.height : raw.height;
55   if (Object.is(width, raw.width) && Object.is(height, raw.height)) return style;
56   return Object.freeze({ ...raw, width, height }) as Readonly<SystemStyle>;
57 }
58 
59 function samePositioning(style: Readonly<SystemStyle>, source: Readonly<SystemStyle>): boolean {
60   const left = style as Readonly<Record<string, unknown>>;
61   const right = source as Readonly<Record<string, unknown>>;
62   return Object.is(left.position, right.position) && Object.is(left.left, right.left) &&
63     Object.is(left.right, right.right) && Object.is(left.top, right.top) &&
64     Object.is(left.bottom, right.bottom) && Object.is(left.insetStart, right.insetStart) &&
65     Object.is(left.insetEnd, right.insetEnd);
66 }
67 
68 /** @internal Marks a placed function component's object style for forwarding. */
69 export function withPlacementHandoff<P>(
70   props: P,
71   consumedStyle: Readonly<SystemStyle> | undefined,
72 ): P {
73   if (!props || typeof props !== 'object') return props;
74   const candidate = props as PropsWithStyle;
75   const style = candidate.style;
76   if (
77     !style ||
78     typeof style !== 'object' ||
79     isSignal(style) ||
80     (style as Record<PropertyKey, unknown>)[PLACEMENT_HANDOFF] !== undefined ||
81     !hasPositioning(style as Readonly<Record<PropertyKey, unknown>>)
82   ) {
83     return props;
84   }
85   return {
86     ...candidate,
87     style: Object.freeze({
88       ...(style as Record<PropertyKey, unknown>),
89       [PLACEMENT_HANDOFF]: Object.freeze({
90         source: consumedStyle ?? style as Readonly<SystemStyle>,
91       }),
92     }),
93   } as P;
94 }
95 
96 /** @internal Activates signal identity capture while one plain component runs. */
97 export function enterPlacementHandoffCapture(
98   props: unknown,
99   consumedStyle: Readonly<SystemStyle> | undefined,
100 ): () => void {
101   const style = props && typeof props === 'object' ?
102     (props as PropsWithStyle).style : undefined;
103   const previous = activeSignalHandoff;
104   activeSignalHandoff = style && isSignal(style) && consumedStyle !== undefined ? {
105     signal: style,
106     consumedStyle,
107   } : undefined;
108   return () => {
109     activeSignalHandoff = previous;
110   };
111 }
112 
113 /** @internal Annotates an element created with the active forwarded style signal. */
114 export function capturePlacementHandoff(
115   element: PibblElement<any>,
116   style: unknown,
117 ): void {
118   if (style && style === activeSignalHandoff?.signal) {
119     setPlacementSignalHandoff(element, activeSignalHandoff.consumedStyle);
120   }
121 }
122 
123 /** @internal Reads the original style behind an enumerable forwarding marker. */
124 export function getPlacementHandoffSource(
125   style: unknown,
126 ): Readonly<SystemStyle> | undefined {
127   if (!style || typeof style !== 'object') return undefined;
128   const marker = (style as Record<PropertyKey, unknown>)[PLACEMENT_HANDOFF];
129   if (!marker || typeof marker !== 'object') return undefined;
130   return (marker as PlacementHandoff).source;
131 }
132 
133 /** @internal Removes a private handoff marker before style callbacks run. */
134 export function consumePlacementHandoff(
135   style: Readonly<SystemStyle>,
136 ): Readonly<SystemStyle> {
137   const record = style as Record<PropertyKey, unknown>;
138   if (record[PLACEMENT_HANDOFF] === undefined && record[PLACEMENT_DERIVED_ABSOLUTE_AXES] === undefined) return style;
139   const withoutHandoff = { ...record };
140   delete withoutHandoff[PLACEMENT_HANDOFF];
141   delete withoutHandoff[PLACEMENT_DERIVED_ABSOLUTE_AXES];
142   return Object.freeze(withoutHandoff) as Readonly<SystemStyle>;
143 }
144 
145 /** @internal Determines whether a primitive consumes one forwarded signal style. */
146 export function getPlacementSignalHandoff(
147   element: PibblElement<any>,
148 ): Readonly<SystemStyle> | undefined {
149   return getPlacementSignalHandoffStyle(element);
150 }
151 
152 /**
153  * Offsets in the parent layout coordinate system; percentages resolve against the containing box.
154  *
155  * @see {@link Length}
156  * @see {@link SystemStyle}
157  */
158 export interface PositioningStyle extends SystemStyle {
159   /**
160    * Experimental direct-Flex placement mode. In a finite Flex, static
161    * keeps the allocated slot and ignores insets; relative offsets final geometry
162    * once without moving siblings. Primitive static/relative leaves support every
163    * main/writing direction and wrapping mode. Wrapped parents admit fixed numeric
164    * direct Flex owners that remain internally nowrap; non-row chains use the same
165    * fixed owner restriction, with zero grow/shrink and
166    * omitted or automatic basis; physical offsets retain their sign through main reversal. Absolute stays out of sibling allocation, using
167    * the padding box for explicit insets and content alignment for omitted axes.
168    * Fixed numeric, percentage and admitted automatic absolute profiles support all main directions
169    * and RTL, with numeric or percentage bounds applied before placement. In every wrapping mode,
170    * omitted axes use whole-content main/cross alignment; wrap-reverse reverses
171    * omitted cross alignment and combines with column RTL exactly once.
172    * Paired natural providers keep their exact/unbounded query in every admitted direction.
173    * Direct wrapped Text with a generic pixel font and visible fit/overflow may
174    * measure automatic height at a resolved numeric or percentage width through the same owned query.
175    * Unwrapped Text may measure automatic width at a resolved numeric or percentage height, using
176    * its existing Canvas ink-bounds width before bounds and physical anchoring.
177    * Generic unwrapped Text also supports natural ink height and both automatic
178    * dimensions through one unbounded query before independent numeric clamps;
179    * mixed opposing-pair/natural feedback and both-auto aspect remain excluded.
180    * On the documented finite direct-child path, automatic absolute axes resolve
181    * from opposing numeric or percentage physical insets. With a positive finite aspectRatio,
182    * exactly one automatic axis can instead derive from its resolved declared finite numeric or percentage opposite axis.
183    * Opposing insets win. Finite numeric or percentage min/max bounds clamp used axes
184    * independently after derivation; a clamp does not recouple aspectRatio, and a
185    * numeric minimum above its maximum rejects. A direct custom primitive with
186    * paired pure measurement providers may instead measure natural automatic
187    * width at a declared numeric or percentage height, or natural height at a declared numeric
188    * or percentage width. The automatic axis is unbounded; the exact axis uses its declared
189    * resolved padding-box value before bounds clamp the used dimensions.
190    * In direct declarative Flex chains,
191    * static Flex passes the containing box outward while relative Flex owns a local box.
192    * Omission retains the legacy local Flex boundary and left/top behavior.
193    */
194   position?: 'static' | 'relative' | 'absolute';
195   /** Left edge coordinate or inset. Explicit absolute Flex insets accept finite numbers or percentages of the containing padding-box axis; relative percentages use the parent content-box axis. See {@link Length}. */
196   left?: Exclude<Length, 'auto'>;
197   /** Right edge inset. Absolute Flex accepts finite numbers or percentages of the containing padding-box width; relative percentages use the parent content-box width. See {@link Length}. */
198   right?: Exclude<Length, 'auto'>;
199   /** Top edge coordinate or inset. Explicit absolute Flex insets accept finite numbers or percentages of the containing padding-box axis; relative percentages use the parent content-box axis. See {@link Length}. */
200   top?: Exclude<Length, 'auto'>;
201   /** Bottom edge inset. Absolute Flex accepts finite numbers or percentages of the containing padding-box height; relative percentages use the parent content-box height. See {@link Length}. */
202   bottom?: Exclude<Length, 'auto'>;
203   /** Experimental direct absolute Flex inline-start inset, mapped through the receiving Flex direction. Overrides the corresponding physical edge, including zero. Percentages use the selected containing padding-box width. See {@link Length}. */
204   insetStart?: Exclude<Length, 'auto'>;
205   /** Experimental direct absolute Flex inline-end inset, mapped through the receiving Flex direction. Overrides the corresponding physical edge. See {@link Length}. */
206   insetEnd?: Exclude<Length, 'auto'>;
207 }
208 
209 export interface ResolvedPosition {
210   left: number;
211   top: number;
212 }
213 
214 export function resolveStandalonePosition(
215   style: Readonly<PositioningStyle>,
216   context: Readonly<StyleResolutionContext>,
217 ): ResolvedPosition {
218   return {
219     left: resolveLocalOffset(style.left, context.percentageBasis.width, 'left', context),
220     top: resolveLocalOffset(style.top, context.percentageBasis.height, 'top', context),
221   };
222 }
223 

Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.