Skip to content

AI-native design editor. Open-source Figma alternative.

fix(core): wrap and outline text in the face it is drawn in (#1642)

Danila Poyarkov9da768cf877e
diff --git a/bun.lock b/bun.lock
index e6747831d..93a2e9ece 100644
--- a/bun.lock
+++ b/bun.lock
@@ -14,7 +14,6 @@
"@atlaskit/pragmatic-drag-and-drop": "^1.8.1",
"@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.2.0",
"@aws-sdk/client-s3": "^3.1149.0",
- "@chenglou/pretext": "^0.0.7",
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-css": "^6.3.1",
@@ -279,7 +278,6 @@
"name": "@open-pencil/core",
"version": "0.16.0",
"dependencies": {
- "@chenglou/pretext": "^0.0.7",
"@iconify/utils": "^3.1.4",
"@open-pencil/design-jsx": "workspace:*",
"@open-pencil/dom-css": "workspace:*",
@@ -1206,8 +1204,6 @@
"@braidai/lang": ["@braidai/[email protected]", "", {}, "sha512-qBcknbBufNHlui137Hft8xauQMTZDKdophmLFv05r2eNmdIv/MlPuP4TdUknHG68UdWLgVZwgxVe735HzJNIwA=="],
- "@chenglou/pretext": ["@chenglou/[email protected]", "", {}, "sha512-FV5hj3fGqpBlzbANUbR+s+6XuNRrghVVyuNs33zdH2SzU7MvK+7GlW6xREjDCreixKbexEn7OEkDgAFeWuu5Hg=="],
-
"@clack/core": ["@clack/[email protected]", "", { "dependencies": { "picocolors": "^1.0.0", "sisteransi": "^1.0.5" } }, "sha512-Pxhij4UXg8KSr7rPek6Zowm+5M22rbd2g1nfojHJkxp5YkFqiZ2+YLEM/XGVIzvGOcM0nqjIFxrpDwWRZYWYjA=="],
"@clack/prompts": ["@clack/[email protected]", "", { "dependencies": { "@clack/core": "0.4.1", "picocolors": "^1.0.0", "sisteransi": "^1.0.5" } }, "sha512-JIpyaboYZeWYlyP0H+OoPPxd6nqueG/CmN6ixBiNFsIDHREevjIf0n0Ohh5gr5C8pEDknzgvz+pIJ8dMhzWIeg=="],
diff --git a/changes/1642/fixed.md b/changes/1642/fixed.md
new file mode 100644
index 000000000..ba270f462
--- /dev/null
+++ b/changes/1642/fixed.md
@@ -0,0 +1 @@
+- Text flattened or used in a boolean operation wraps where it is drawn and keeps its weight in variable fonts, instead of breaking lines by the default face or turning bold text regular.
diff --git a/package.json b/package.json
index b9232edf5..3b9663597 100644
--- a/package.json
+++ b/package.json
@@ -132,7 +132,6 @@
"@atlaskit/pragmatic-drag-and-drop": "^1.8.1",
"@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.2.0",
"@aws-sdk/client-s3": "^3.1149.0",
- "@chenglou/pretext": "^0.0.7",
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-css": "^6.3.1",
diff --git a/packages/core/package.json b/packages/core/package.json
index a67ab426a..78ca8f132 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -182,7 +182,6 @@
"typecheck": "tsc --noEmit -p tsconfig.test.json"
},
"dependencies": {
- "@chenglou/pretext": "^0.0.7",
"@iconify/utils": "^3.1.4",
"@open-pencil/design-jsx": "workspace:*",
"@open-pencil/dom-css": "workspace:*",
diff --git a/packages/core/src/text/font/glyphs.ts b/packages/core/src/text/font/glyphs.ts
index 52e97422d..e855073bd 100644
--- a/packages/core/src/text/font/glyphs.ts
+++ b/packages/core/src/text/font/glyphs.ts
@@ -226,19 +226,23 @@ export function fontHasGlyphSync(family: string, style: string, char: string): b
return fontGlyphCoverageSync(family, style, char) === 'has'
}
-/** Each glyph HarfBuzz shapes `text` into, with its outline, pen position, and advance. */
+/**
+ * Each glyph HarfBuzz shapes `text` into, with its outline, pen position, and advance. A variable
+ * font shapes and draws the instance at `variations`.
+ */
export function getGlyphOutlineMetricsSync(
family: string,
style: string,
text: string,
- fontSize: number
+ fontSize: number,
+ variations: readonly FontVariation[] = []
): GlyphOutlineMetrics[] | null {
const parsed = getParsedFont(family, style)
if (!parsed) return null
const scale = fontSize / parsed.face.upem
- const instance = fontInstance(parsed, [])
+ const instance = fontInstance(parsed, variations)
let pen = 0
- return shapeText(parsed, text).map((glyph) => {
+ return shapeText(parsed, text, { instance }).map((glyph) => {
// Shaping moves some glyphs off the pen, such as marks onto their base letter.
const offsetX = (glyph.xOffset ?? 0) * scale
// y runs down; subtracting keeps an unmoved glyph's baseline 0 rather than -0.
@@ -253,6 +257,27 @@ export function getGlyphOutlineMetricsSync(
})
}
+/**
+ * The advance of each glyph HarfBuzz shapes `text` into and the UTF-16 index it starts at, at
+ * `fontSize` and, in a variable font, the instance at `variations`.
+ */
+export function shapedAdvancesSync(
+ family: string,
+ style: string,
+ text: string,
+ fontSize: number,
+ variations: readonly FontVariation[] = []
+): { cluster: number; advance: number }[] | null {
+ const parsed = getParsedFont(family, style)
+ if (!parsed) return null
+ const scale = fontSize / parsed.face.upem
+ const instance = fontInstance(parsed, variations)
+ return shapeText(parsed, text, { instance }).map((glyph) => ({
+ cluster: glyph.cluster,
+ advance: (glyph.xAdvance ?? 0) * scale
+ }))
+}
+
/** Outlines of one loaded font, addressed by the glyph IDs a shaper produced. */
/** A glyph HarfBuzz shaped text into: its ID, the UTF-16 index it starts at, and its advance in em. */
export interface ShapedGlyph {
diff --git a/packages/core/src/text/outlines.ts b/packages/core/src/text/outlines.ts
index 5c3a7ebc0..5cc0b3b1b 100644
--- a/packages/core/src/text/outlines.ts
+++ b/packages/core/src/text/outlines.ts
@@ -1,13 +1,13 @@
-import { prepareWithSegments, layoutWithLines } from '@chenglou/pretext'
-
-import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
+import type { CharacterStyleOverride, FontVariation, SceneNode } from '@open-pencil/scene-graph'
import { faceStyleKey } from '@open-pencil/scene-graph/font-style'
import { rangeFontStyle } from '@open-pencil/scene-graph/shared-styles'
import { lineHeightPixels, textLengthPixels } from '@open-pencil/scene-graph/text'
+import { drawnFontVariations } from '#core/canvas/text/font-families'
import {
fontHasGlyphSync,
getGlyphOutlineMetricsSync,
+ shapedAdvancesSync,
type OutlineCommand
} from '#core/text/font/glyphs'
import { fontManager } from '#core/text/font/manager'
@@ -42,36 +42,66 @@ type TextStyle = Required<
CharacterStyleOverride,
'fontFamily' | 'fontSize' | 'fontWeight' | 'italic' | 'fontStyle' | 'letterSpacing'
>
->
+> & {
+ /** The axes a variable font draws the text at; a script fallback draws at the text font's. */
+ variations: FontVariation[]
+}
-function baseTextStyle(node: SceneNode): TextStyle {
+function withVariations(
+ style: Omit<TextStyle, 'variations'>,
+ variations: FontVariation[],
+ opticalSizeFromFontSize: boolean
+): TextStyle {
return {
- fontFamily: node.fontFamily,
- fontSize: node.fontSize,
- fontWeight: node.fontWeight,
- italic: node.italic,
- fontStyle: node.fontStyle,
- letterSpacing: node.letterSpacing
+ ...style,
+ variations: drawnFontVariations({
+ family: style.fontFamily,
+ weight: style.fontWeight,
+ italic: style.italic,
+ style: faceStyleKey(style),
+ fontSize: style.fontSize,
+ variations,
+ opticalSizeFromFontSize
+ })
}
}
+function baseTextStyle(node: SceneNode): TextStyle {
+ return withVariations(
+ {
+ fontFamily: node.fontFamily,
+ fontSize: node.fontSize,
+ fontWeight: node.fontWeight,
+ italic: node.italic,
+ fontStyle: node.fontStyle,
+ letterSpacing: node.letterSpacing
+ },
+ node.fontVariations,
+ node.opticalSizeFromFontSize
+ )
+}
+
function styleKey(style: TextStyle): string {
const spacing = textLengthPixels(style.letterSpacing, style.fontSize)
- return `${style.fontFamily}|${faceStyleKey(style)}|${style.fontSize}|${spacing}`
+ const axes = style.variations.map(({ axis, value }) => `${axis}=${value}`).join(',')
+ return `${style.fontFamily}|${faceStyleKey(style)}|${style.fontSize}|${spacing}|${axes}`
}
function textStyleAt(node: SceneNode, index: number): TextStyle {
- const base = baseTextStyle(node)
const run = node.styleRuns.find((item) => index >= item.start && index < item.start + item.length)
- if (!run) return base
- return {
- fontFamily: run.style.fontFamily ?? base.fontFamily,
- fontSize: run.style.fontSize ?? base.fontSize,
- fontWeight: run.style.fontWeight ?? base.fontWeight,
- italic: run.style.italic ?? base.italic,
- fontStyle: rangeFontStyle(node, run.style),
- letterSpacing: run.style.letterSpacing ?? base.letterSpacing
- }
+ if (!run) return baseTextStyle(node)
+ return withVariations(
+ {
+ fontFamily: run.style.fontFamily ?? node.fontFamily,
+ fontSize: run.style.fontSize ?? node.fontSize,
+ fontWeight: run.style.fontWeight ?? node.fontWeight,
+ italic: run.style.italic ?? node.italic,
+ fontStyle: rangeFontStyle(node, run.style),
+ letterSpacing: run.style.letterSpacing ?? node.letterSpacing
+ },
+ run.style.fontVariations ?? node.fontVariations,
+ run.style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize
+ )
}
function resolvedGlyphStyle(style: TextStyle, char: string): TextStyle | null {
@@ -142,31 +172,59 @@ function hardTextLines(text: string): TextLine[] {
return lines
}
-function glyphAdvance(node: SceneNode, absoluteIndex: number): number | null {
- const char = node.text[absoluteIndex]
- const style = resolvedGlyphStyle(textStyleAt(node, absoluteIndex), char)
- if (!style) return null
- const metrics = getGlyphOutlineMetricsSync(
- style.fontFamily,
- faceStyleKey(style),
- char,
- style.fontSize
- )
- const glyph = metrics?.[0]
- return glyph ? glyph.advance + textLengthPixels(style.letterSpacing, style.fontSize) : null
+interface StyleSegment {
+ start: number
+ end: number
+ style: TextStyle
+}
+
+/** `line` split where the style its characters are drawn in changes, or `null` when one has none. */
+function styleSegments(node: SceneNode, line: TextLine): StyleSegment[] | null {
+ const segments: StyleSegment[] = []
+ for (let index = 0; index < line.text.length; index++) {
+ const style = resolvedGlyphStyle(textStyleAt(node, line.start + index), line.text[index])
+ if (!style) return null
+ const last = segments.at(-1)
+ if (last && styleKey(last.style) === styleKey(style)) last.end = index + 1
+ else segments.push({ start: index, end: index + 1, style })
+ }
+ return segments
+}
+
+/**
+ * The width each character of `line` adds as its segments are shaped and drawn, kerning and
+ * ligatures included: a glyph's advance and spacing go to the character it starts at.
+ */
+function characterAdvances(node: SceneNode, line: TextLine): number[] | null {
+ const segments = styleSegments(node, line)
+ if (!segments) return null
+ const advances = Array.from<number>({ length: line.text.length }).fill(0)
+ for (const { start, end, style } of segments) {
+ const glyphs = shapedAdvancesSync(
+ style.fontFamily,
+ faceStyleKey(style),
+ line.text.slice(start, end),
+ style.fontSize,
+ style.variations
+ )
+ if (!glyphs) return null
+ const spacing = textLengthPixels(style.letterSpacing, style.fontSize)
+ for (const glyph of glyphs) advances[start + glyph.cluster] += glyph.advance + spacing
+ }
+ return advances
}
-function wrapStyledLine(node: SceneNode, line: TextLine): TextLine[] {
+function wrapLine(node: SceneNode, line: TextLine): TextLine[] {
if (!line.text || node.width <= 0) return [line]
+ const advances = characterAdvances(node, line)
+ if (!advances) return [line]
const result: TextLine[] = []
let lineStart = 0
let cursor = 0
let lastBreak = -1
for (let index = 0; index < line.text.length; index++) {
- const advance = glyphAdvance(node, line.start + index)
- if (advance == null) return [line]
- cursor += advance
+ cursor += advances[index]
if (/\s/.test(line.text[index])) {
lastBreak = index + 1
}
@@ -187,27 +245,7 @@ function wrapStyledLine(node: SceneNode, line: TextLine): TextLine[] {
function textLines(node: SceneNode): TextLine[] {
const hardLines = hardTextLines(node.text)
if (node.textAutoResize === 'WIDTH_AND_HEIGHT') return hardLines
- if (node.styleRuns.length > 0) return hardLines.flatMap((line) => wrapStyledLine(node, line))
-
- const result: TextLine[] = []
- for (const hardLine of hardLines) {
- if (!hardLine.text) {
- result.push(hardLine)
- continue
- }
- try {
- const prepared = prepareWithSegments(hardLine.text, `${node.fontSize}px ${node.fontFamily}`)
- const layout = layoutWithLines(prepared, node.width, lineHeight(node))
- let start = hardLine.start
- for (const line of layout.lines) {
- result.push({ text: line.text, start })
- start += line.text.length
- }
- } catch {
- result.push(hardLine)
- }
- }
- return result
+ return hardLines.flatMap((line) => wrapLine(node, line))
}
function lineOffsetX(node: SceneNode, width: number): number {
@@ -238,28 +276,18 @@ function lineGlyphs(
baseline: number,
xOffset: number
): { glyphs: TextOutlineGlyph[]; width: number } | null {
+ const segments = styleSegments(node, line)
+ if (!segments) return null
const glyphs: TextOutlineGlyph[] = []
let cursorX = xOffset
- let index = 0
-
- while (index < line.text.length) {
- const absoluteIndex = line.start + index
- const style = resolvedGlyphStyle(textStyleAt(node, absoluteIndex), line.text[index])
- if (!style) return null
- const key = styleKey(style)
- let end = index + 1
- while (end < line.text.length) {
- const nextStyle = resolvedGlyphStyle(textStyleAt(node, line.start + end), line.text[end])
- if (!nextStyle || styleKey(nextStyle) !== key) break
- end++
- }
- const segment = line.text.slice(index, end)
+ for (const { start, end, style } of segments) {
const metrics = getGlyphOutlineMetricsSync(
style.fontFamily,
faceStyleKey(style),
- segment,
- style.fontSize
+ line.text.slice(start, end),
+ style.fontSize,
+ style.variations
)
if (!metrics) return null
@@ -267,7 +295,6 @@ function lineGlyphs(
glyphs.push({ commands: glyph.commands, x: cursorX, y: baseline })
cursorX += glyph.advance + textLengthPixels(style.letterSpacing, style.fontSize)
}
- index = end
}
return { glyphs, width: cursorX - xOffset }
diff --git a/packages/core/tests/text/outlines.test.ts b/packages/core/tests/text/outlines.test.ts
new file mode 100644
index 000000000..17e537b4a
--- /dev/null
+++ b/packages/core/tests/text/outlines.test.ts
@@ -0,0 +1,77 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core'
+import { fontManager } from '@open-pencil/core/text'
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+import { textNodeToOutlineLayout } from '#core/text/outlines'
+
+const editor = createEditor()
+
+beforeAll(async () => {
+ const data = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()
+ await fontManager.markLoaded('Inter', 'Regular', data)
+ await fontManager.markLoaded('Inter', 'Bold', data)
+})
+
+function text(props: Partial<SceneNode>): SceneNode {
+ return editor.graph.createNode('TEXT', editor.state.currentPageId, {
+ text: 'Hello world',
+ fontFamily: 'Inter',
+ fontSize: 32,
+ width: 1000,
+ height: 100,
+ ...props
+ })
+}
+
+function lineCount(node: SceneNode): number {
+ const layout = textNodeToOutlineLayout(node)
+ if (!layout) throw new Error('No outline layout')
+ return new Set(layout.glyphs.map((glyph) => glyph.y)).size
+}
+
+function oneLineWidth(props: Partial<SceneNode>): number {
+ const layout = textNodeToOutlineLayout(text({ ...props, textAutoResize: 'WIDTH_AND_HEIGHT' }))
+ if (!layout) throw new Error('No outline layout')
+ return layout.width
+}
+
+describe('textNodeToOutlineLayout', () => {
+ test('wraps text without style runs at its width', () => {
+ const wrapped = text({ width: 100, textAutoResize: 'HEIGHT' })
+ const unwrapped = text({ textAutoResize: 'WIDTH_AND_HEIGHT' })
+
+ expect(lineCount(wrapped)).toBe(2)
+ expect(textNodeToOutlineLayout(wrapped)?.glyphs).toHaveLength(
+ textNodeToOutlineLayout(unwrapped)?.glyphs.length ?? -1
+ )
+ })
+
+ test('keeps a kerned line that fits on one line', () => {
+ const kerned = { text: 'AVAVAVAV' }
+ const width = oneLineWidth(kerned)
+ const unkerned = 'AVAVAVAV'.length * 0.5 * (oneLineWidth({ text: 'AA' }) + oneLineWidth({ text: 'VV' }))
+ expect(unkerned).toBeGreaterThan(width)
+
+ expect(lineCount(text({ ...kerned, width, textAutoResize: 'HEIGHT' }))).toBe(1)
+ })
+
+ test('wraps by the advances of the text face', () => {
+ const regular = oneLineWidth({ fontWeight: 400 })
+ const bold = oneLineWidth({ fontWeight: 700 })
+ expect(bold).toBeGreaterThan(regular)
+ const width = (regular + bold) / 2
+
+ expect(lineCount(text({ fontWeight: 400, width, textAutoResize: 'HEIGHT' }))).toBe(1)
+ expect(lineCount(text({ fontWeight: 700, width, textAutoResize: 'HEIGHT' }))).toBe(2)
+ })
+
+ test('wraps by letter spacing', () => {
+ const width = oneLineWidth({}) + 4
+ const letterSpacing = { value: 2, unit: 'PIXELS' as const }
+
+ expect(lineCount(text({ width, textAutoResize: 'HEIGHT' }))).toBe(1)
+ expect(lineCount(text({ width, letterSpacing, textAutoResize: 'HEIGHT' }))).toBe(2)
+ })
+})