Skip to content

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

fix: read quoted font-family names in HTML and draw.io import (#1409)

Jungwoo2531b1e2c199
diff --git a/changes/1409/fixed.md b/changes/1409/fixed.md
new file mode 100644
index 000000000..b5b3fea2c
--- /dev/null
+++ b/changes/1409/fixed.md
@@ -0,0 +1 @@
+- HTML and draw.io import read a quoted `font-family`, such as `'Noto Sans KR'` or `"Foo, Bar"`, as the font family instead of keeping the quotes in its name or cutting it at a comma.
diff --git a/packages/core/src/io/formats/drawio/label.ts b/packages/core/src/io/formats/drawio/label.ts
index 6bab04a5c..a77ebd2eb 100644
--- a/packages/core/src/io/formats/drawio/label.ts
+++ b/packages/core/src/io/formats/drawio/label.ts
@@ -2,6 +2,7 @@ import { parseFragment, type DefaultTreeAdapterTypes } from 'parse5'
import type { CharacterStyleOverride, StyleRun } from '@open-pencil/scene-graph'
import { tryParseColor } from '@open-pencil/scene-graph/color'
+import { parseCSSFontFamily } from '@open-pencil/scene-graph/css'
import type { Color } from '@open-pencil/scene-graph/primitives'
/** How a stretch of a label looks: the cell's style, as tags inside the label change it. */
@@ -50,7 +51,7 @@ function tagFormat(element: Element, format: LabelFormat): LabelFormat {
if (tag === 'u') next.underline = true
if (tag === 'font') {
next.color = tryParseColor(attribute(element, 'color') ?? '') ?? next.color
- next.family = attribute(element, 'face')?.split(',')[0]?.trim() || next.family
+ next.family = parseCSSFontFamily(attribute(element, 'face') ?? undefined) ?? next.family
}
return next
}
@@ -69,7 +70,7 @@ function cssFormat(css: Map<string, string>, format: LabelFormat): LabelFormat {
if (style) next.italic = style === 'italic'
const decoration = css.get('text-decoration') ?? css.get('text-decoration-line')
if (decoration) next.underline = decoration.includes('underline')
- const family = css.get('font-family')?.split(',')[0]?.replace(/["']/g, '').trim()
+ const family = parseCSSFontFamily(css.get('font-family'))
if (family) next.family = family
return next
}
diff --git a/packages/core/src/io/formats/drawio/paint.ts b/packages/core/src/io/formats/drawio/paint.ts
index 978a09eef..758d8c48e 100644
--- a/packages/core/src/io/formats/drawio/paint.ts
+++ b/packages/core/src/io/formats/drawio/paint.ts
@@ -2,6 +2,7 @@ import { styleNumber, type DrawIOStyle } from '@open-pencil/drawio'
import type { Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'
import { tryParseColor } from '@open-pencil/scene-graph/color'
import { BLACK, WHITE } from '@open-pencil/scene-graph/constants'
+import { parseCSSFontFamily } from '@open-pencil/scene-graph/css'
import type { Color } from '@open-pencil/scene-graph/primitives'
import type { LabelFormat } from './label'
@@ -86,7 +87,7 @@ export function labelFormat(style: DrawIOStyle): LabelFormat {
underline: (fontStyle & 4) !== 0,
size: styleNumber(style, 'fontSize', DEFAULT_FONT_SIZE),
color: styleColor(style, 'fontColor', BLACK) ?? BLACK,
- family: style.values.fontFamily?.split(',')[0]?.trim() || DEFAULT_FONT_FAMILY
+ family: parseCSSFontFamily(style.values.fontFamily) ?? DEFAULT_FONT_FAMILY
}
}
diff --git a/packages/dom-css/src/export/bundle.ts b/packages/dom-css/src/export/bundle.ts
index e93c4479f..db6a2bffb 100644
--- a/packages/dom-css/src/export/bundle.ts
+++ b/packages/dom-css/src/export/bundle.ts
@@ -218,25 +218,11 @@ async function compileTailwindClasses(classNames: string[], tokens: string): Pro
return compiler.build(classNames)
}
-function stripFontFamilyQuotes(value: string): string {
- if (value.length < 2) return value
- const first = value[0]
- const last = value[value.length - 1]
- if ((first === '"' && last === '"') || (first === "'" && last === "'")) return value.slice(1, -1)
- return value
-}
-
-function firstFontFamily(value: string): string {
- const commaIndex = value.indexOf(',')
- const raw = commaIndex !== -1 ? value.slice(0, commaIndex) : value
- return stripFontFamilyQuotes(raw.trim())
-}
-
function collectFontRequests(node: DesignNode, fonts: Map<string, WebFontFaceRequest>): void {
if (node.type === 'text') return
const source = node.sourceSceneNode
if (source?.type === 'TEXT') {
- const family = normalizeFontFamily(firstFontFamily(source.fontFamily))
+ const family = normalizeFontFamily(source.fontFamily)
const style = source.italic ? 'italic' : 'normal'
const key = `${family}|${source.fontWeight}|${style}`
fonts.set(key, { family, weight: source.fontWeight, style })
diff --git a/packages/dom-css/src/import/text.ts b/packages/dom-css/src/import/text.ts
index 53f29e2d7..bc50c2734 100644
--- a/packages/dom-css/src/import/text.ts
+++ b/packages/dom-css/src/import/text.ts
@@ -10,6 +10,7 @@ import type {
} from '@open-pencil/scene-graph'
import {
parseCSSColor,
+ parseCSSFontFamily,
parseCSSLetterSpacing,
parseCSSLineHeight,
parseCSSNumber
@@ -110,7 +111,7 @@ export function characterStyleFromCSS(
base: CSSCharacterStyle
): CSSCharacterStyle {
const fills = colorToFillFromCSS(pickStyle(style, 'color'))
- const family = pickStyle(style, 'font-family')?.split(',')[0]?.replaceAll('"', '').trim()
+ const family = parseCSSFontFamily(pickStyle(style, 'font-family'))
const decorationColor = pickStyle(style, 'text-decoration-color')
const decorationFills = parseCSSColor(decorationColor) ? colorToFillFromCSS(decorationColor) : []
const line = pickStyle(style, 'text-decoration-line')
diff --git a/packages/dom-css/tests/import/text.test.ts b/packages/dom-css/tests/import/text.test.ts
index e05804e8e..ee473502a 100644
--- a/packages/dom-css/tests/import/text.test.ts
+++ b/packages/dom-css/tests/import/text.test.ts
@@ -182,6 +182,14 @@ describe('rich text import', () => {
expect(text?.styleRuns).toEqual([{ start: 5, length: 5, style: { textCase: 'ORIGINAL' } }])
})
+ test('reads the first font family without its single or double quotes', async () => {
+ const [single, double] = await texts(
+ `<div style="display: flex"><span style="font-family: 'Noto Sans KR', sans-serif">a</span><span style='font-family: "Fira Code", monospace'>b</span></div>`
+ )
+ expect(single?.fontFamily).toBe('Noto Sans KR')
+ expect(double?.fontFamily).toBe('Fira Code')
+ })
+
test('reads back the links and cases it writes', async () => {
const styleRuns = [
{
diff --git a/packages/scene-graph/src/css/index.ts b/packages/scene-graph/src/css/index.ts
index 83004a1fb..131734732 100644
--- a/packages/scene-graph/src/css/index.ts
+++ b/packages/scene-graph/src/css/index.ts
@@ -6,5 +6,5 @@ export {
parseCSSJustifyContent
} from './layout'
export { parseCSSShadows } from './shadows'
-export { parseCSSLetterSpacing, parseCSSLineHeight } from './text'
+export { parseCSSFontFamily, parseCSSLetterSpacing, parseCSSLineHeight } from './text'
export { parseCSSColor, parseCSSNumber, splitCSSValue } from './values'
diff --git a/packages/scene-graph/src/css/text.ts b/packages/scene-graph/src/css/text.ts
index 7cd5eca23..d851be762 100644
--- a/packages/scene-graph/src/css/text.ts
+++ b/packages/scene-graph/src/css/text.ts
@@ -4,6 +4,47 @@ import { percentLength, pixelLength } from '../text/lengths'
import type { TextLength } from '../types'
import { parseCSSNumber } from './values'
+/** A CSS escape: hex digits and one optional whitespace, an escaped line break, or any one character. */
+const CSS_ESCAPE = /\\(?:([0-9a-fA-F]{1,6})(?:\r\n|[ \t\n\r\f])?|(?:\r\n|[\n\r\f])|([\s\S]))?/gu
+
+/** The largest Unicode code point. */
+const MAX_CODE_POINT = 0x10ffff
+
+/** Text with its CSS escapes decoded; an escaped line break continues the line. */
+function decodeCSSEscapes(text: string): string {
+ return text.replace(CSS_ESCAPE, (_escape, hex: string | undefined, char: string | undefined) => {
+ if (hex === undefined) return char ?? ''
+ const codePoint = Number.parseInt(hex, 16)
+ const surrogate = codePoint >= 0xd800 && codePoint <= 0xdfff
+ return codePoint === 0 || surrogate || codePoint > MAX_CODE_POINT
+ ? '\uFFFD'
+ : String.fromCodePoint(codePoint)
+ })
+}
+
+/** The index of the first unescaped `stop` character from `from`, or the text's length. */
+function unescapedIndexOf(text: string, stop: string, from: number): number {
+ let index = from
+ while (index < text.length && text[index] !== stop) index += text[index] === '\\' ? 2 : 1
+ return index
+}
+
+/**
+ * The first family of a CSS `font-family` list, without its quotes and escapes. A family is a quoted
+ * string or unquoted words, which join with single spaces; a quote opens a string only at the start
+ * of the family, so a name list such as draw.io's keeps `O'Reilly`. Null for an empty list.
+ */
+export function parseCSSFontFamily(value: string | undefined): string | null {
+ const text = value?.trimStart()
+ if (!text) return null
+ const quote = text[0]
+ if (quote === '"' || quote === "'") {
+ return decodeCSSEscapes(text.slice(1, unescapedIndexOf(text, quote, 1))) || null
+ }
+ const words = decodeCSSEscapes(text.slice(0, unescapedIndexOf(text, ',', 0)))
+ return words.trim().replace(/\s+/gu, ' ') || null
+}
+
/** A CSS dimension's number and lowercase unit, or null. */
function dimension(value: string): { number: number; unit: string } | null {
const parsed = valueParser.unit(value)
diff --git a/packages/scene-graph/tests/css/text.test.ts b/packages/scene-graph/tests/css/text.test.ts
index 84d786694..9dcb35044 100644
--- a/packages/scene-graph/tests/css/text.test.ts
+++ b/packages/scene-graph/tests/css/text.test.ts
@@ -1,8 +1,30 @@
import { describe, expect, test } from 'bun:test'
-import { parseCSSLetterSpacing, parseCSSLineHeight } from '@open-pencil/scene-graph/css'
+import {
+ parseCSSFontFamily,
+ parseCSSLetterSpacing,
+ parseCSSLineHeight
+} from '@open-pencil/scene-graph/css'
import { percentLength, pixelLength } from '@open-pencil/scene-graph/text'
+describe('parseCSSFontFamily', () => {
+ test.each([
+ ["'Noto Sans KR', sans-serif", 'Noto Sans KR'],
+ ['"Fira Code", monospace', 'Fira Code'],
+ ['"Foo, Bar", serif', 'Foo, Bar'],
+ ['"O\'Reilly"', "O'Reilly"],
+ ['Noto Sans KR, Arial', 'Noto Sans KR'],
+ ["O'Reilly, Arial", "O'Reilly"],
+ ["'O\\'Reilly', serif", "O'Reilly"],
+ ['"A\\26 B"', 'A&B'],
+ ['Foo\\,Bar, serif', 'Foo,Bar'],
+ ['Inter', 'Inter'],
+ ['', null]
+ ])('%s', (value, expected) => {
+ expect(parseCSSFontFamily(value)).toBe(expected)
+ })
+})
+
describe('parseCSSLineHeight', () => {
test.each([
['1.5', percentLength(150)],