packages/core/src/lib/components/text.ts
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import { resolveTexturePaint } from '../textures/texture-protocol.js';
2 import { definePrimitive } from '../define-primitive.js';
3 import { materializeTextChildren } from '../element/children.js';
4 import { GLOBAL_STATE } from '../global-state.js';
5 import type {
6 PibblEventFocusOptions,
7 PibblEventHandlers,
8 PibblEventParticipationOptions,
9 } from '../events/types.js';
10 import {
11 resolveOptionalLength,
12 stripLayoutParticipation,
13 } from '../style/resolve-built-in.js';
14 import { registerOpaqueStyleProperties } from '../style/resolve-dispatch.js';
15 import type { ResolvedTextStyle, TextStyle } from '../style/types.js';
16 import {
17 CanvasMeasurementService,
18 MeasureResult,
19 IntrinsicSizesResult,
20 RenderingContext2D,
21 } from '../types.js';
22 import type { Constraints } from '../layout/types.js';
23 import type { PibblRenderTransaction, PibblTextInput } from '../types.js';
24 import type { PibblPhysics2DPropExtension } from '../types.js';
25 import { resolveScalarSizingLength } from '../style/sizing-length.js';
26 import { normalizeBoxInsets } from '../layout/box-insets.js';
27 import { wireCommonEvents } from '../util/wire-common-events.js';
28 import { pushClippingPath } from '../util/push-clipping-path.js';
29 import { resolveTextClipBounds, resolveTextLayout } from './text-layout.js';
30 import { withReceiverInputProvision } from '../signals/input-provision.js';
31 import { withSignalDependencyRole, withSignalWriteForbidden } from '../signals/graph.js';
32 import { withHooksForbidden } from '../hooks/hook-slot.js';
33
34 /**
35 * Authored inputs for Text, including the declared data and presentation options.
36 *
37 * @see {@link PibblEventHandlers}
38 * @see {@link PibblEventParticipationOptions}
39 * @see {@link PibblPhysics2DPropExtension}
40 * @see {@link PibblTextInput}
41 * @see {@link Text}
42 */
43 export interface TextProps
44 extends
45 PibblEventHandlers,
46 PibblEventFocusOptions,
47 PibblEventParticipationOptions,
48 PibblPhysics2DPropExtension {
49 /** Descendant content or the callback that supplies it. See {@link PibblTextInput}. */
50 children?: PibblTextInput;
51 }
52
53 const materializedTextTransactions = new WeakMap<
54 PibblRenderTransaction,
55 WeakMap<object, string>
56 >();
57
58 function renderText(
59 props: TextProps,
60 style: Readonly<ResolvedTextStyle>,
61 ctx: RenderingContext2D,
62 ) {
63 const text = materializeTextContent(props);
64 const {
65 font = '13px sans-serif',
66 textBaseline = 'top',
67 textAlign = 'left',
68 fill,
69 stroke,
70 strokeWidth = 0,
71 opacity,
72 cursor,
73 } = style;
74
75 if (opacity !== undefined) {
76 ctx.globalAlpha = ctx.globalAlpha * opacity;
77 }
78
79 ctx.font = font;
80 ctx.textBaseline = textBaseline;
81 ctx.textAlign = textAlign;
82
83 const layout = resolveTextLayout(
84 value => ctx.measureText(value),
85 text,
86 style,
87 );
88 const clipBounds =
89 layout.clipBounds ?? resolveTextClipBounds(style, ctx.canvas.height);
90
91 let releaseClip: (() => void) | undefined;
92 if (clipBounds) {
93 const clipPath = new Path2D();
94 clipPath.rect(
95 clipBounds.x,
96 clipBounds.y,
97 clipBounds.width,
98 clipBounds.height,
99 );
100 releaseClip = pushClippingPath(ctx, clipPath);
101 }
102
103 try {
104 const textBounds = props.pointerEvents === 'none' ? undefined : new Path2D();
105
106 for (const line of layout.lines) {
107 if (stroke && strokeWidth) {
108 ctx.strokeStyle = resolveTexturePaint(stroke, ctx, layout.bounds ?? line.bounds);
109 ctx.lineWidth = strokeWidth;
110 ctx.strokeText(line.text, line.x, line.y, line.squishWidth);
111 }
112
113 if (fill) {
114 ctx.fillStyle = resolveTexturePaint(fill, ctx, layout.bounds ?? line.bounds);
115 ctx.fillText(line.text, line.x, line.y, line.squishWidth);
116 }
117
118 if (textBounds) {
119 textBounds.moveTo(line.bounds.x, line.bounds.y);
120 textBounds.lineTo(line.bounds.x + line.bounds.width, line.bounds.y);
121 textBounds.lineTo(
122 line.bounds.x + line.bounds.width,
123 line.bounds.y + line.bounds.height,
124 );
125 textBounds.lineTo(line.bounds.x, line.bounds.y + line.bounds.height);
126 textBounds.closePath();
127 }
128 }
129
130 wireCommonEvents(
131 props,
132 textBounds,
133 true,
134 strokeWidth,
135 cursor,
136 layout.bounds,
137 );
138 } finally {
139 releaseClip?.();
140 }
141 }
142
143 /**
144 * Draws Canvas text from textual children using the resolved font, wrapping, fitting, and paint
145 * style.
146 *
147 * @param props - Authored component inputs, supplied through JSX or createElement. See the linked
148 * props and style types.
149 * @throws When called directly; Pibbl mounts this component through JSX or createElement.
150 *
151 * @see {@link TextProps}
152 * @see {@link TextStyle}
153 */
154 export const Text = definePrimitive<
155 TextProps,
156 TextStyle,
157 TextStyle,
158 ResolvedTextStyle
159 >(renderText, {
160 childInput: 'text',
161 resolveStyle: (style, context) => {
162 let x = 0, y = 0;
163 if (style.padding !== undefined || style.paddingStart !== undefined || style.paddingEnd !== undefined ||
164 style.borderWidth !== undefined || style.borderStartWidth !== undefined || style.borderEndWidth !== undefined) {
165 const insets = normalizeBoxInsets(style, context);
166 x = insets.left; y = insets.top;
167 }
168 return {
169 ...stripLayoutParticipation(style),
170 x,
171 y,
172 width: resolveOptionalLength(
173 style.width,
174 context.percentageBasis.width,
175 'width',
176 context,
177 ),
178 height: resolveOptionalLength(
179 style.height,
180 context.percentageBasis.height,
181 'height',
182 context,
183 ),
184 } as ResolvedTextStyle;
185 },
186 measure: ({ props, style, constraints, service }) =>
187 measureTextStyle(
188 materializeTextContent(props),
189 style,
190 constraints,
191 service,
192 ),
193 measureIntrinsic: ({ props, style, service }) => measureTextIntrinsic(props, style, service),
194 measureBaselines: ({ props, style, allocation, service }) =>
195 measureTextBaselines(
196 materializeTextContent(props),
197 style,
198 allocation,
199 service,
200 ),
201 });
202 registerOpaqueStyleProperties(Text, [
203 'font',
204 'fill',
205 'stroke',
206 'cursor',
207 'fit',
208 'textBaseline',
209 'textAlign',
210 ]);
211
212
213 function measureTextBaselines(
214 text: string,
215 style: Readonly<TextStyle>,
216 allocation: Readonly<{ width: number; height: number }>,
217 service: CanvasMeasurementService,
218 ) {
219 if (text.length === 0) return { status: 'unsupported' as const, reason: 'Text baseline measurement requires nonempty text' };
220 const measureAtBaseline = service.measureTextAtBaseline;
221 if (!measureAtBaseline) {
222 return {
223 status: 'unsupported' as const,
224 reason: 'Text baseline measurement requires CanvasMeasurementService.measureTextAtBaseline',
225 };
226 }
227 const font = style.font ?? '13px sans-serif';
228 const textBaseline = style.textBaseline ?? 'top';
229 const layout = resolveTextLayout(
230 value => measureAtBaseline.call(service, value, { font, textBaseline }),
231 text,
232 { ...style, x: 0, y: 0, width: allocation.width, height: allocation.height },
233 );
234 const firstLine = layout.lines[0];
235 const lastLine = layout.lines[layout.lines.length - 1];
236 if (!firstLine || !lastLine || firstLine.text.length === 0 || lastLine.text.length === 0) {
237 return { status: 'unsupported' as const, reason: 'Text does not resolve a line for baseline measurement: requires a nonempty rendered baseline line' };
238 }
239 const firstMetrics = measureAtBaseline.call(service, firstLine.text, { font, textBaseline });
240 const first = firstLine.y - firstMetrics.alphabeticBaseline;
241 let last = first;
242 if (lastLine !== firstLine) {
243 const lastMetrics = measureAtBaseline.call(service, lastLine.text, { font, textBaseline });
244 last = lastLine.y - lastMetrics.alphabeticBaseline;
245 }
246 if (!Number.isFinite(first) || !Number.isFinite(last)) {
247 return {
248 status: 'unsupported' as const,
249 reason: 'Canvas text metrics do not provide a finite alphabeticBaseline for Text baseline measurement',
250 };
251 }
252 return { status: 'measured' as const, first, last };
253 }
254
255 /** Width contributions and their respective natural heights share Text's existing wrap policy. */
256 function measureTextIntrinsic(props: Readonly<TextProps>, style: Readonly<TextStyle>, service: CanvasMeasurementService): IntrinsicSizesResult {
257 const text = prepareLayoutTextContent(props, {});
258 const font = style.font ?? '13px sans-serif';
259 const maximum = style.wrap ? measureLayoutTextNaturalRun(text, { font, service }) : service.measureText(text, font).width;
260 const minimum = style.wrap ? measureLayoutTextMinimumWidth(props, { font, service }) : maximum;
261 const intrinsicStyle = { ...style, width: undefined, height: undefined, fit: 'visible' as const };
262 const minResult = measureTextStyle(text, intrinsicStyle, { minWidth: 0, maxWidth: minimum, minHeight: 0, maxHeight: Infinity }, service);
263 const maxResult = measureTextStyle(text, intrinsicStyle, { minWidth: 0, maxWidth: maximum, minHeight: 0, maxHeight: Infinity }, service);
264 if (minResult.status !== 'measured') return minResult;
265 if (maxResult.status !== 'measured') return maxResult;
266 return { status: 'measured', minContent: { width: minimum, height: minResult.size.height }, maxContent: { width: maximum, height: maxResult.size.height } };
267 }
268
269 function measureTextStyle(
270 text: string,
271 style: Readonly<TextStyle>,
272 constraints: Readonly<Constraints>,
273 service: CanvasMeasurementService,
274 ): MeasureResult {
275 const context = {
276 component: 'Text',
277 algorithm: 'measurement',
278 constraints,
279 };
280 const specifiedWidth = style.width === undefined ? undefined :
281 resolveScalarSizingLength(style.width, constraints.maxWidth, 'width', context);
282 const specifiedHeight = style.height === undefined ? undefined :
283 resolveScalarSizingLength(style.height, constraints.maxHeight, 'height', context);
284 const layoutWidth = specifiedWidth ?? (
285 style.wrap && Number.isFinite(constraints.maxWidth) ?
286 constraints.maxWidth :
287 undefined
288 );
289 const font = style.font ?? '13px sans-serif';
290 const layout = resolveTextLayout(
291 value => service.measureText(value, font),
292 text,
293 {
294 ...style,
295 x: 0,
296 y: 0,
297 width: layoutWidth,
298 height: specifiedHeight,
299 },
300 );
301 return {
302 status: 'measured',
303 size: {
304 width: specifiedWidth ?? (style.wrap && layoutWidth !== undefined ?
305 layoutWidth :
306 layout.bounds?.width ?? 0),
307 height: specifiedHeight ?? (style.wrap ?
308 layout.lines.length * (style.lineHeight ?? 13) :
309 layout.bounds?.height ?? 0),
310 },
311 };
312 }
313
314 /** @internal Measure a materialized value without bypassing receiver reads. */
315 export function measureLayoutTextNaturalRun(
316 text: string, options: { font: string; service: CanvasMeasurementService },
317 ): number {
318 // wrapText discards leading empty words but preserves later spaces. Use the
319 // same boundary rather than adding a CSS whitespace-normalization policy.
320 let start = 0;
321 while (text.charCodeAt(start) === 32) start++;
322 if (start === text.length) return 0;
323 const width = options.service.measureText(text.slice(start), options.font).width;
324 if (!Number.isFinite(width) || width < 0) {
325 throw new Error('Text intrinsic measurement requires a finite nonnegative natural width.');
326 }
327 return width;
328 }
329
330 /** @internal Longest run under Text's existing ASCII-space wrapping contract. */
331 export function measureLayoutTextMinimumWidth(
332 props: Readonly<TextProps>,
333 options: { font: string; service: CanvasMeasurementService; receiverToken?: object },
334 ): number {
335 const text = prepareLayoutTextContent(props, { receiverToken: options.receiverToken });
336 let longest = 0;
337 let start = 0;
338 for (let index = 0; index <= text.length; index++) {
339 if (index !== text.length && text.charCodeAt(index) !== 32) continue;
340 if (index > start) {
341 const width = options.service.measureText(text.slice(start, index), options.font).width;
342 if (!Number.isFinite(width) || width < 0) {
343 throw new Error('Text intrinsic measurement requires finite nonnegative word widths.');
344 }
345 if (width > longest) longest = width;
346 }
347 start = index + 1;
348 }
349 return longest;
350 }
351
352 /** @internal Prepare measured Text through its existing transaction/receiver ownership. */
353 export function prepareLayoutTextContent(
354 props: Readonly<TextProps>, options: { receiverToken?: object },
355 ): string {
356 return withSignalWriteForbidden('Signal writes are forbidden during Pibbl measurement', () =>
357 withHooksForbidden('Pibbl hooks cannot be called while preparing measured Text content.', () =>
358 materializeTextContent(props, options.receiverToken),
359 ),
360 );
361 }
362
363 function materializeTextContent(
364 props: Readonly<TextProps>, receiver = GLOBAL_STATE.primitiveReceiverToken,
365 ): string {
366 const transaction = GLOBAL_STATE.renderTransaction;
367 if (!transaction || !receiver) {
368 return materializeTextChildren(props.children, 'Text');
369 }
370
371 let receivers = materializedTextTransactions.get(transaction);
372 if (!receivers) {
373 receivers = new WeakMap();
374 materializedTextTransactions.set(transaction, receivers);
375 }
376 const cached = receivers.get(receiver);
377 if (cached !== undefined) return cached;
378 const materialized = withReceiverInputProvision(
379 transaction,
380 receiver,
381 () => withSignalDependencyRole(
382 'measurement',
383 () => materializeTextChildren(props.children, 'Text'),
384 ),
385 );
386 receivers.set(receiver, materialized);
387 return materialized;
388 }
389
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.