A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(text): TextOverflow.Shrink sets type smaller, a whole pixel at a time, until it fits its box; the Cocos import maps its Shrink labels to it
yhhe0811818ac38
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex d958fd264..2716afe2d 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -6201,11 +6201,12 @@"key": "overflow","type": "enum","default": "Visible",- "doc": "What text too big for its box does. Needs a layout box: Clip and Ellipsis drop the lines past its height and trim a line past its width.",+ "doc": "What text too big for its box does. Needs a layout box: Clip and Ellipsis drop the lines past its height and trim a line past its width; Shrink sets the text smaller until it fits both.","values": ["Visible","Clip",- "Ellipsis"+ "Ellipsis",+ "Shrink"]},{diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.tsindex cf4786773..0a5abf085 100644--- a/pipeline/src/import/cocos/components.ts+++ b/pipeline/src/import/cocos/components.ts@@ -154,7 +154,7 @@ function label(c: CocosComponent, siblings: CocosComponent[], box: UiBox | null,align: clamp012(d._horizontalAlign),verticalAlign: clamp012(d._verticalAlign),wordWrap: d._enableWrapText !== false,- overflow: overflow === 1 ? 1 : 0, // Clip : Visible+ overflow: overflow === 1 ? 1 : overflow === 2 ? 3 : 0, // Clip, Shrink, otherwise VisiblelineHeight: fontSize > 0 ? Math.round((lineHeight / fontSize) * 1000) / 1000 : 1.2,bold: d._isBold === true,italic: d._isItalic === true,@@ -166,9 +166,9 @@ function label(c: CocosComponent, siblings: CocosComponent[], box: UiBox | null,data.boxHeight = box.height;data.boxPivot = { x: box.ax, y: box.ay };}- if (overflow === 2 || overflow === 3) {+ if (overflow === 3) {status = 'partial';- ctx.report.note(overflow === 2 ? 'label-shrink-overflow' : 'label-resize-height', where);+ ctx.report.note('label-resize-height', where);}const fontUuid = uuidOf(d._font);diff --git a/sdk/src/ui/core/text.ts b/sdk/src/ui/core/text.tsindex cd738ba31..7d74aad9f 100644--- a/sdk/src/ui/core/text.ts+++ b/sdk/src/ui/core/text.ts@@ -43,6 +43,8 @@ export const TextOverflow = {Visible: 0,Clip: 1,Ellipsis: 2,+ /** Smaller type until the text fits the box: the size drops a whole pixel at a time, and line height and letter spacing with it. */+ Shrink: 3,} as const;/** @public */export type TextOverflow = (typeof TextOverflow)[keyof typeof TextOverflow];@@ -187,7 +189,7 @@ export const Text = defineComponent<TextData>('Text', {verticalAlign: { enum: enumOptions(TextVerticalAlign), tooltip: 'Vertical alignment: within the layout box when the entity has a UINode, else it anchors the text to the entity origin (top/middle/bottom).' },overflow: {enum: enumOptions(TextOverflow),- tooltip: 'What text too big for its box does. Needs a layout box: Clip and Ellipsis drop the lines past its height and trim a line past its width.',+ tooltip: 'What text too big for its box does. Needs a layout box: Clip and Ellipsis drop the lines past its height and trim a line past its width; Shrink sets the text smaller until it fits both.',},renderMode: { enum: enumOptions(TextRenderMode) },boxWidth: { tooltip: 'Layout box width for a text with no UINode (0 = no box: the origin is the box). Alignment, wrapping and overflow work inside it. A UINode, if present, decides the box instead.' },diff --git a/sdk/src/ui/text/layout.ts b/sdk/src/ui/text/layout.tsindex 23008d392..72de95bf1 100644--- a/sdk/src/ui/text/layout.ts+++ b/sdk/src/ui/text/layout.ts@@ -59,6 +59,8 @@ export interface TextLayout {width: number;/** Line height (display px). */lineHeight: number;+ /** The font size the text was laid out at, when that is not the one asked for ({@link TextOverflow.Shrink}). */+ fontSizePx?: number;}/**@@ -338,6 +340,49 @@ export function wrapLine(return wrapMeasured(text, s => append(0, s), maxWidth, append);}+/**+ * The largest whole-pixel font size, at most the one asked for, at which the text fits its box: no taller than+ * `boxHeight` and no wider than `boxWidth` (each only when given). Line height and letter spacing scale with the+ * size, as they do for a label the author sized by hand. Never below 1px: a box too small for anything shows+ * the smallest text rather than none.+ *+ * Fitting is assumed to get easier as type gets smaller, which holds for wrapping text (fewer, shorter lines) and+ * lets a binary search stand in for trying every size.+ */+export function shrinkFontSize(+ text: string, atlas: GlyphAtlas, fontFamily: string, opts: MultilineTextOptions, style = 0,+): number {+ const base = opts.fontSizePx;+ const width = opts.boxWidth ?? 0;+ const height = opts.boxHeight ?? 0;+ if (!(base > 1) || (!(width > 0) && !(height > 0))) return base;+ const fits = (size: number): boolean => {+ const laid = layoutText(text, atlas, fontFamily, scaledTo(opts, size), style);+ return (!(height > 0) || laid.lineHeight <= height + 1e-6) && (!(width > 0) || laid.width <= width + 1e-6);+ };+ const whole = Math.floor(base);+ if (fits(whole)) return base;+ let lo = 1; // the smallest size we will answer with, whether or not it fits+ let hi = whole - 1; // known not to fit at `whole`+ while (lo < hi) {+ const mid = Math.ceil((lo + hi) / 2);+ if (fits(mid)) lo = mid; else hi = mid - 1;+ }+ return lo;+}++/** The same layout request at another font size: line height and letter spacing follow, and nothing is clipped. */+function scaledTo(opts: MultilineTextOptions, size: number): MultilineTextOptions {+ const k = size / opts.fontSizePx;+ return {+ ...opts,+ fontSizePx: size,+ ...(opts.lineHeight !== undefined ? { lineHeight: opts.lineHeight * k } : {}),+ ...(opts.letterSpacing !== undefined ? { letterSpacing: opts.letterSpacing * k } : {}),+ overflow: TextOverflow.Visible,+ };+}+/*** Lay out multi-line text: splits on `\n`, lays each line out* (rich or plain), stacks lines downward (y-up: line 0 on top) by `lineHeight`,@@ -351,6 +396,11 @@ export function layoutText(opts: MultilineTextOptions,style = 0,): TextLayout {+ if (opts.overflow === TextOverflow.Shrink) {+ const size = shrinkFontSize(text, atlas, fontFamily, opts, style);+ const fitted = layoutText(text, atlas, fontFamily, scaledTo(opts, size), style);+ return size === opts.fontSizePx ? fitted : { ...fitted, fontSizePx: size };+ }const lineHeight = opts.lineHeight ?? opts.fontSizePx * 1.2;const align = opts.align ?? TEXT_ALIGN_LEFT;const baseColor = opts.color ?? ([1, 1, 1, 1] as const);diff --git a/sdk/src/ui/text/text-renderer.ts b/sdk/src/ui/text/text-renderer.tsindex a336e6a08..54a74df46 100644--- a/sdk/src/ui/text/text-renderer.ts+++ b/sdk/src/ui/text/text-renderer.ts@@ -199,8 +199,14 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTexconst boxHeight = p.boxHeight ?? 0;const boxWidth = p.boxWidth ?? 0;+ // A Shrink label was laid out smaller than it was asked for, so everything measured in em from here — the baseline,+ // half-leading, the outline — is measured in the size it got. A boxed origin already carries 0.8em of the asked-for+ // size (rectTextBox), which is put right.+ const fontSizePx = layout.fontSizePx ?? p.fontSizePx;+ const lineHeightPx = p.lineHeight !== undefined ? p.lineHeight * fontSizePx / p.fontSizePx : undefined;const originY = textBlockOriginY(- p.originY ?? 0, boxHeight, layout.lineHeight, p.fontSizePx, p.verticalAlign, p.lineHeight,+ (p.originY ?? 0) + (p.originY !== undefined ? (p.fontSizePx - fontSizePx) * 0.8 : 0),+ boxHeight, layout.lineHeight, fontSizePx, p.verticalAlign, lineHeightPx,);// A string can reference glyphs across several atlas pages; each page is a@@ -254,7 +260,7 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTex// is only ever asked for hairlines there.if (p.outline && p.outline.width > 0 && p.outline.color[3] > 0) {const w = p.outline.width;- const bias = outlineBias(atlas, p.fontSizePx, w);+ const bias = outlineBias(atlas, fontSizePx, w);if (bias > 0) emitPass(p.outline.color, 0, 0, bias);else for (const [ox, oy] of OUTLINE_OFFSETS) emitPass(p.outline.color, ox * w, oy * w);}diff --git a/sdk/tests/ui-text-overflow.test.ts b/sdk/tests/ui-text-overflow.test.tsindex 419a279f5..461fcee8d 100644--- a/sdk/tests/ui-text-overflow.test.ts+++ b/sdk/tests/ui-text-overflow.test.ts@@ -11,7 +11,7 @@ import { describe, it, expect } from 'vitest';import {GlyphAtlas, type GlyphRasterizer, type AtlasPageStore, type RasterGlyph,} from '../src/ui/text/glyph-atlas';-import { layoutText, measureWidth } from '../src/ui/text/layout';+import { layoutText, measureWidth, shrinkFontSize } from '../src/ui/text/layout';import { TextOverflow } from '../src/ui/core/text';function makeAtlas(): GlyphAtlas {@@ -159,3 +159,52 @@ it.each([-8, 0, 2.25])('matches whole-codepoint trimming with spaces and signed}}});++describe('TextOverflow.Shrink', () => {+ const wideText = 'the quick brown fox';+ const at = (size: number) => measureWidth(wideText, atlas, 'Arial', size, 0);++ it('leaves text that already fits exactly as it was', () => {+ const l = lay(wideText, { boxWidth: at(F) + 40, boxHeight: LINE * 2, overflow: TextOverflow.Shrink });+ expect(l.fontSizePx).toBeUndefined();+ expect(l.width).toBeCloseTo(at(F));+ });++ it('takes the largest whole size that fits the width, and not one more', () => {+ const box = at(F) * 0.6;+ const size = shrinkFontSize(wideText, atlas, 'Arial', { fontSizePx: F, lineHeight: LINE, boxWidth: box });+ expect(size).toBeLessThan(F);+ expect(Number.isInteger(size)).toBe(true);+ expect(at(size)).toBeLessThanOrEqual(box + 1e-6);+ expect(at(size + 1)).toBeGreaterThan(box);+ });++ it('lays the text out at that size, and says which size it was', () => {+ const box = at(F) * 0.6;+ const l = lay(wideText, { boxWidth: box, boxHeight: LINE, overflow: TextOverflow.Shrink });+ expect(l.fontSizePx).toBeLessThan(F);+ expect(l.width).toBeLessThanOrEqual(box + 1e-6);+ // line height shrinks with the type: the block is one line of the smaller size+ expect(l.lineHeight).toBeCloseTo(LINE * (l.fontSizePx! / F));+ });++ it('fits the height of wrapped text by making the lines smaller and more of them fit', () => {+ const box = { boxWidth: at(F) * 0.5, maxWidth: at(F) * 0.5, boxHeight: LINE * 1.5 };+ const l = lay(wideText, { ...box, overflow: TextOverflow.Shrink });+ expect(l.lineHeight).toBeLessThanOrEqual(box.boxHeight + 1e-6);+ expect(l.width).toBeLessThanOrEqual(box.boxWidth + 1e-6);+ // and the plain, unshrunk text really did not fit — otherwise this proves nothing+ expect(lay(wideText, { ...box, overflow: TextOverflow.Visible }).lineHeight).toBeGreaterThan(box.boxHeight);+ });++ it('is a no-op without a box, since nothing can overflow one', () => {+ const l = lay(wideText, { overflow: TextOverflow.Shrink });+ expect(l.fontSizePx).toBeUndefined();+ });++ it('never goes below one pixel: a box too small for anything shows the smallest text, not none', () => {+ const l = lay(wideText, { boxWidth: 1, boxHeight: 1, overflow: TextOverflow.Shrink });+ expect(l.fontSizePx).toBe(1);+ expect(l.glyphs.length).toBeGreaterThan(0);+ });+});