Skip to content

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

feat: set optical size for a range of characters, as Figma does (#1568)

Danila Poyarkovb1a569f06e68
diff --git a/changes/1559/added.md b/changes/1559/added.md
index 3646042c6..0a7faca04 100644
--- a/changes/1559/added.md
+++ b/changes/1559/added.md
@@ -1 +1 @@
-- Set the axes of a variable font, such as its weight, width, or optical size, in the Typography section, or let the optical size follow the font size, as in Figma.
+- Set the axes of a variable font, such as its weight, width, or optical size, in the Typography section, for the whole text or the selected characters, or let the optical size follow the font size, as in Figma; a range of characters keeps its own optical size from Figma files.
diff --git a/packages/core/src/canvas/text/layout/build.ts b/packages/core/src/canvas/text/layout/build.ts
index bafd9446e..aaee0b8c8 100644
--- a/packages/core/src/canvas/text/layout/build.ts
+++ b/packages/core/src/canvas/text/layout/build.ts
@@ -181,6 +181,7 @@ function markerNode(node: ParagraphNode, item: TextListItem, style: ListStyle):
letterSpacing: override?.letterSpacing ?? node.letterSpacing,
lineHeight: override?.lineHeight !== undefined ? override.lineHeight : node.lineHeight,
fontVariations: override?.fontVariations ?? node.fontVariations,
+ opticalSizeFromFontSize: override?.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize,
fontFeatures:
item.listType === 'ORDERED' ? [...features, { tag: 'TNUM', enabled: true }] : features,
textLanguage: override?.textLanguage ?? node.textLanguage,
diff --git a/packages/core/src/canvas/text/paragraph/index.ts b/packages/core/src/canvas/text/paragraph/index.ts
index e64961585..6e40ca086 100644
--- a/packages/core/src/canvas/text/paragraph/index.ts
+++ b/packages/core/src/canvas/text/paragraph/index.ts
@@ -188,7 +188,7 @@ function pushStyleRun(
italic: runItalic,
fontSize: runFontSize,
variations: style.fontVariations ?? node.fontVariations,
- opticalSizeFromFontSize: node.opticalSizeFromFontSize
+ opticalSizeFromFontSize: style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize
})
),
fontFeatures: textFontFeatures(style.fontFeatures ?? node.fontFeatures),
diff --git a/packages/core/src/canvas/text/placed.ts b/packages/core/src/canvas/text/placed.ts
index ab80b8551..05b3f285b 100644
--- a/packages/core/src/canvas/text/placed.ts
+++ b/packages/core/src/canvas/text/placed.ts
@@ -63,7 +63,7 @@ function fontAt(node: SceneNode, index: number) {
italic,
fontSize: run?.style.fontSize ?? node.fontSize,
variations: run?.style.fontVariations ?? node.fontVariations,
- opticalSizeFromFontSize: node.opticalSizeFromFontSize
+ opticalSizeFromFontSize: run?.style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize
})
const drawn = loadedFace(family, weight, italic) ?? { weight, italic }
return { family, weight, italic, style, variations, drawn }
diff --git a/packages/core/src/figma-api/accessors/text/ranges.ts b/packages/core/src/figma-api/accessors/text/ranges.ts
index 0c96b0688..9859ddb48 100644
--- a/packages/core/src/figma-api/accessors/text/ranges.ts
+++ b/packages/core/src/figma-api/accessors/text/ranges.ts
@@ -160,7 +160,7 @@ function currentFont(node: SceneNode, index: number): CurrentFont {
style.fontFamily,
name,
style.fontVariations,
- node.opticalSizeFromFontSize
+ style.opticalSizeFromFontSize
)
}
}
diff --git a/packages/core/src/figma-api/text/style.ts b/packages/core/src/figma-api/text/style.ts
index 01b7abb30..616b932fb 100644
--- a/packages/core/src/figma-api/text/style.ts
+++ b/packages/core/src/figma-api/text/style.ts
@@ -99,13 +99,13 @@ function spacing(field: 'paragraphSpacing' | 'listSpacing' | 'paragraphIndent')
*/
const FIELD_READERS: Record<TextSegmentField, (context: FieldContext) => unknown> = {
fontSize: ({ style }) => style.fontSize,
- fontName: ({ node, style }) => {
+ fontName: ({ style }) => {
const name = weightToStyleName(style.fontWeight, style.italic)
const variationSettings = readVariationSettings(
style.fontFamily,
name,
style.fontVariations,
- node.opticalSizeFromFontSize
+ style.opticalSizeFromFontSize
)
return variationSettings
? { family: style.fontFamily, style: name, variationSettings }
diff --git a/packages/core/src/io/formats/svg/text/export.ts b/packages/core/src/io/formats/svg/text/export.ts
index 6ef4b1d9f..795f5d934 100644
--- a/packages/core/src/io/formats/svg/text/export.ts
+++ b/packages/core/src/io/formats/svg/text/export.ts
@@ -110,7 +110,7 @@ function fontRequest(
...textFontFace(node, style),
fontSize: style.fontSize ?? node.fontSize,
variations: style.fontVariations ?? node.fontVariations,
- opticalSizeFromFontSize: node.opticalSizeFromFontSize
+ opticalSizeFromFontSize: style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize
}
if (!fallback) return own
return {
diff --git a/packages/core/src/text/character-style.ts b/packages/core/src/text/character-style.ts
index c03ad40ea..99b1d43a5 100644
--- a/packages/core/src/text/character-style.ts
+++ b/packages/core/src/text/character-style.ts
@@ -31,6 +31,7 @@ export type CharacterStyle = Required<
| 'textDecorationSkipInk'
| 'fontFeatures'
| 'fontVariations'
+ | 'opticalSizeFromFontSize'
| 'textCase'
>
> & {
@@ -61,6 +62,7 @@ export const TEXT_STYLE_KEYS = [
'textUnderlineOffset',
'fontFeatures',
'fontVariations',
+ 'opticalSizeFromFontSize',
'textCase'
] as const satisfies readonly (keyof CharacterStyle)[]
@@ -93,6 +95,7 @@ export function nodeStyle(node: SceneNode): CharacterStyle {
textUnderlineOffset: node.textUnderlineOffset,
fontFeatures: node.fontFeatures,
fontVariations: node.fontVariations,
+ opticalSizeFromFontSize: node.opticalSizeFromFontSize,
textCase: node.textCase,
hyperlink: null,
textStyleId: node.textStyleId,
diff --git a/packages/core/tests/canvas/text/faces.test.ts b/packages/core/tests/canvas/text/faces.test.ts
index c4fb57d83..8d813fc19 100644
--- a/packages/core/tests/canvas/text/faces.test.ts
+++ b/packages/core/tests/canvas/text/faces.test.ts
@@ -139,6 +139,13 @@ describe('text faces', () => {
expect(
face({ opticalSizeFromFontSize: false, fontVariations: [{ axis: 'opsz', value: 32 }] })
).toEqual(automatic)
+ // A range detaches its own optical size, as Figma saves one, over text that follows it.
+ const range = (style: Partial<SceneNode['styleRuns'][number]['style']>) =>
+ face({ styleRuns: [{ start: 0, length: 5, style }] })
+ expect(range({ fontVariations: [{ axis: 'opsz', value: 14 }] })).toEqual(automatic)
+ expect(
+ range({ opticalSizeFromFontSize: false, fontVariations: [{ axis: 'opsz', value: 14 }] })
+ ).toEqual(face({ opticalSizeFromFontSize: false, fontVariations: [{ axis: 'opsz', value: 14 }] }))
})
test('draws each style of a family loaded from several files from its own file', async () => {
diff --git a/packages/fig/src/node-change/style/runs.ts b/packages/fig/src/node-change/style/runs.ts
index 5231f27a8..896e5476f 100644
--- a/packages/fig/src/node-change/style/runs.ts
+++ b/packages/fig/src/node-change/style/runs.ts
@@ -81,6 +81,9 @@ function convertStyleOverride(override: NodeChange, text: NodeChange): Character
if (override.fontSize !== undefined) style.fontSize = override.fontSize
const fontVariations = convertFontVariations(override)
if (fontVariations.length > 0) style.fontVariations = fontVariations
+ // Figma detaches a range's optical size from its font size in the range's own override.
+ if (override.detachOpticalSizeFromFontSize !== undefined)
+ style.opticalSizeFromFontSize = !override.detachOpticalSizeFromFontSize
const fontFeatures = convertFontFeatures(override)
if (fontFeatures.length > 0) style.fontFeatures = fontFeatures
if (override.letterSpacing) style.letterSpacing = convertLetterSpacing(override.letterSpacing)
diff --git a/packages/fig/src/node-change/text/data-export.ts b/packages/fig/src/node-change/text/data-export.ts
index 83b47ba11..bd38eb13b 100644
--- a/packages/fig/src/node-change/text/data-export.ts
+++ b/packages/fig/src/node-change/text/data-export.ts
@@ -53,6 +53,8 @@ function textStyleOverrideToKiwi(
if (style.fontVariations && style.fontVariations.length > 0) {
override.fontVariations = style.fontVariations.map(fontVariationToKiwi)
}
+ if (style.opticalSizeFromFontSize !== undefined)
+ override.detachOpticalSizeFromFontSize = !style.opticalSizeFromFontSize
if (style.fontFeatures && style.fontFeatures.length > 0) {
applyFontFeaturesToKiwi(override as NodeChange, style.fontFeatures)
}
diff --git a/packages/fig/tests/node-change/font-variations.test.ts b/packages/fig/tests/node-change/font-variations.test.ts
index b1ae66716..b8822b1f0 100644
--- a/packages/fig/tests/node-change/font-variations.test.ts
+++ b/packages/fig/tests/node-change/font-variations.test.ts
@@ -30,3 +30,41 @@ test('writes the detached optical size only when the text has one', () => {
expect(write(false).detachOpticalSizeFromFontSize).toBe(true)
expect(write(true).detachOpticalSizeFromFontSize).toBeUndefined()
})
+
+test('reads and writes an optical size detached for a range, as Figma saves one', () => {
+ // As Figma saved "Auto Fixed" with automatic optical size turned off for "Fixed" alone.
+ const props = nodeChangeToProps(
+ {
+ type: 'TEXT',
+ textData: {
+ characters: 'Auto Fixed',
+ characterStyleIDs: [0, 0, 0, 0, 0, 3, 3, 3, 3, 3],
+ styleOverrideTable: [
+ {
+ styleID: 3,
+ detachOpticalSizeFromFontSize: true,
+ fontVariations: [{ axisTag: OPSZ, axisName: 'OPTICAL SIZE', value: 40 }]
+ }
+ ]
+ }
+ } as NodeChange,
+ []
+ )
+ expect(props.opticalSizeFromFontSize).toBe(true)
+ expect(props.styleRuns).toEqual([
+ {
+ start: 5,
+ length: 5,
+ style: { opticalSizeFromFontSize: false, fontVariations: [{ axis: 'opsz', value: 40 }] }
+ }
+ ])
+
+ const graph = new SceneGraph()
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'Auto Fixed',
+ styleRuns: props.styleRuns
+ })
+ const [written] = sceneNodeToKiwi(node, { sessionID: 1, localID: 1 }, 0, { value: 2 }, graph, [])
+ expect(written.detachOpticalSizeFromFontSize).toBeUndefined()
+ expect(written.textData?.styleOverrideTable?.[0]?.detachOpticalSizeFromFontSize).toBe(true)
+})
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index eadc558c8..938e5ecd3 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -379,6 +379,8 @@ export interface CharacterStyleOverride {
lineHeight?: TextLength | null
fills?: Fill[]
fontVariations?: FontVariation[]
+ /** Whether the characters' optical size follows their font size, in place of the text's own. */
+ opticalSizeFromFontSize?: boolean
fontFeatures?: FontFeature[]
textLanguage?: string | null
textCase?: TextCase
diff --git a/packages/vue/src/controls/typography/axes.ts b/packages/vue/src/controls/typography/axes.ts
index 1c499e3d5..c62a1267d 100644
--- a/packages/vue/src/controls/typography/axes.ts
+++ b/packages/vue/src/controls/typography/axes.ts
@@ -66,14 +66,6 @@ export function createTypographyAxes(editor: Editor, nodes: ComputedRef<SceneNod
})
})
- /**
- * Whether the optical size can be set: not while text is edited, since whether it follows the
- * font size belongs to the layer, which selected characters cannot set for themselves.
- */
- const opticalSizeEditable = computed(() =>
- nodes.value.every((node) => editor.state.editingTextId !== node.id)
- )
-
/** Whether the optical size follows the font size on every layer, MIXED when they differ. */
const opticalSizeAuto = computed<MixedValue<boolean>>(() => {
const first = nodes.value.at(0)
@@ -115,7 +107,6 @@ export function createTypographyAxes(editor: Editor, nodes: ComputedRef<SceneNod
/** Draws the text at `value` on `axis` while it is dragged or typed. */
function previewAxis(axis: string, value: number) {
- if (axis === OPTICAL_SIZE && !opticalSizeEditable.value) return
previewEach((node) => axisChanges(node, axis, value))
}
@@ -129,7 +120,6 @@ export function createTypographyAxes(editor: Editor, nodes: ComputedRef<SceneNod
/** Sets `axis` to `value` on every selected text layer in one undo step. */
function setAxis(axis: string, value: number) {
- if (axis === OPTICAL_SIZE && !opticalSizeEditable.value) return
previewAxis(axis, value)
commitPreview(`Change ${axis} axis`)
}
@@ -139,7 +129,6 @@ export function createTypographyAxes(editor: Editor, nodes: ComputedRef<SceneNod
* Figma's "Set optical size automatically" does.
*/
function setOpticalSizeAuto(auto: boolean) {
- if (!opticalSizeEditable.value) return
previewEach((node) => {
const drawn = drawnAxes(node)?.find((axis) => axis.tag === OPTICAL_SIZE)
const rest = node.fontVariations.filter(({ axis }) => axis !== OPTICAL_SIZE)
@@ -153,7 +142,6 @@ export function createTypographyAxes(editor: Editor, nodes: ComputedRef<SceneNod
return {
axes,
opticalSizeAuto,
- opticalSizeEditable,
previewAxis,
cancelAxis,
setAxis,
diff --git a/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
index 952bb1511..0157cb2a7 100644
--- a/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
+++ b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
@@ -58,7 +58,6 @@ const actions = {
:list-type="ctx.listType"
:axes="ctx.axes"
:optical-size-auto="ctx.opticalSizeAuto"
- :optical-size-editable="ctx.opticalSizeEditable"
:actions="actions"
/>
</template>
diff --git a/packages/vue/tests/controls/typography.test.ts b/packages/vue/tests/controls/typography.test.ts
index 3e264e92b..08e8c2b97 100644
--- a/packages/vue/tests/controls/typography.test.ts
+++ b/packages/vue/tests/controls/typography.test.ts
@@ -301,13 +301,32 @@ test('an axis set while text is edited styles the selected characters, and undoe
])
editor.undoAction()
expect(node()?.styleRuns).toEqual([])
- // Whether optical size follows the font size is the layer's, which selected characters
- // cannot set for themselves.
- expect(axes.opticalSizeEditable.value).toBe(false)
+ // Whether optical size follows the font size is the selected characters' own, as in Figma.
axes.setOpticalSizeAuto(false)
- axes.setAxis('opsz', 20)
expect(node()?.opticalSizeFromFontSize).toBe(true)
+ expect(node()?.styleRuns).toEqual([
+ {
+ start: 6,
+ length: 5,
+ style: { opticalSizeFromFontSize: false, fontVariations: [{ axis: 'opsz', value: 14 }] }
+ }
+ ])
+ editor.undoAction()
expect(node()?.styleRuns).toEqual([])
+
+ // A typed optical size goes to the selected characters too, and stays when the edit ends.
+ axes.setAxis('opsz', 20)
+ const typed = {
+ start: 6,
+ length: 5,
+ style: { fontVariations: [{ axis: 'opsz', value: 20 }], opticalSizeFromFontSize: false }
+ }
+ expect(node()?.styleRuns).toEqual([typed])
+ expect(node()?.opticalSizeFromFontSize).toBe(true)
+ expect(node()?.fontVariations).toEqual([])
+ editor.commitTextEdit()
+ expect(editor.state.editingTextId).toBeNull()
+ expect(node()?.styleRuns).toEqual([typed])
} finally {
scope.stop()
editor.dispose()
diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vue
index 0c88b84e7..75e2b55ab 100644
--- a/src/components/properties/TypographySection.vue
+++ b/src/components/properties/TypographySection.vue
@@ -155,7 +155,6 @@ function picked<T>(value: MixedValue<T>): T | '' {
<FontAxisField
:axis="axis"
:optical-size-auto="ctx.opticalSizeAuto.value"
- :optical-size-editable="ctx.opticalSizeEditable.value"
@preview="ctx.actions.previewAxis(axis.tag, $event)"
@commit="ctx.actions.setAxis(axis.tag, $event)"
@cancel="ctx.actions.cancelAxis()"
diff --git a/src/components/properties/typography/FontAxisField.vue b/src/components/properties/typography/FontAxisField.vue
index e3b119e8b..2c77d40d6 100644
--- a/src/components/properties/typography/FontAxisField.vue
+++ b/src/components/properties/typography/FontAxisField.vue
@@ -15,11 +15,9 @@ import AppSelectItem from '@/components/ui/select/AppSelectItem.vue'
* One axis of a variable font. Optical size reads Auto while it follows the font size, as line
* height reads Auto, and its menu switches between that and a size set by hand.
*/
-const { axis, opticalSizeAuto, opticalSizeEditable } = defineProps<{
+const { axis, opticalSizeAuto } = defineProps<{
axis: TypographyAxis
opticalSizeAuto: MixedValue<boolean>
- /** False while text is edited: whether optical size follows the font size is the layer's. */
- opticalSizeEditable: boolean
}>()
const emit = defineEmits<{
preview: [value: number]
@@ -44,7 +42,6 @@ const tagIcon = computed(() =>
:min="axis.min"
:max="axis.max"
:icon="tagIcon"
- :disabled="opticalSize && !opticalSizeEditable"
:data-property="`font-axis-${axis.tag}`"
@update:model-value="emit('preview', $event)"
@commit="(value: number) => emit('commit', value)"
@@ -67,7 +64,6 @@ const tagIcon = computed(() =>
>
<SelectTrigger
:aria-label="panels.opticalSizeMode"
- :disabled="!opticalSizeEditable"
class="flex shrink-0 items-center self-stretch px-1 text-muted"
data-property="optical-size-mode"
@pointerdown.stop
diff --git a/tests/e2e/fonts/variable-weights-visual.spec.ts b/tests/e2e/fonts/variable-weights-visual.spec.ts
index 03a7f4b0d..a7f414c11 100644
--- a/tests/e2e/fonts/variable-weights-visual.spec.ts
+++ b/tests/e2e/fonts/variable-weights-visual.spec.ts
@@ -2,6 +2,8 @@ import { Buffer } from 'node:buffer'
import type { Page } from '@playwright/test'
+import type { SceneNode } from '@open-pencil/scene-graph'
+
import type { FontManager } from '#core/text/fonts'
import { expect, test } from '#tests/e2e/fixtures'
@@ -17,10 +19,12 @@ async function openEditor(page: Page): Promise<void> {
await new CanvasHelper(page).waitForInit()
}
-test('variable fonts render each style at its named instance', async ({ page }) => {
- await openEditor(page)
-
- const result = await page.evaluate(async () => {
+/**
+ * Lines of text in the variable Inter fixture, one under the other at 32 px, each with its own
+ * fields over the defaults, exported as a PNG with how ready each line's fonts were.
+ */
+async function exportLines(page: Page, lines: Array<Partial<SceneNode> & { text: string }>) {
+ return page.evaluate(async (lines) => {
const store = window.openPencil?.getStore?.()
if (!store?.renderer) throw new Error('OpenPencil renderer not initialized')
const fontModuleURL = performance
@@ -44,34 +48,21 @@ test('variable fonts render each style at its named instance', async ({ page })
await fontManager.markLoaded('Inter Variable', style, data)
}
- const samples = [
- { label: 'Regular 400', fontWeight: 400 },
- { label: 'Medium 500', fontWeight: 500 },
- { label: 'SemiBold 600', fontWeight: 600 },
- { label: 'Bold 700', fontWeight: 700 },
- {
- label: 'Bold, explicit wght 300',
- fontWeight: 700,
- fontVariations: [{ axis: 'wght', value: 300 }]
- }
- ]
- const ids = samples.map(
- (sample, index) =>
+ const ids = lines.map(
+ (line, index) =>
store.graph.createNode('TEXT', pageId, {
- name: sample.label,
+ name: line.text,
x: 40,
y: 40 + index * 56,
width: 520,
height: 44,
- text: `${sample.label} — Buttons`,
fontFamily: 'Inter Variable',
fontSize: 32,
- fontWeight: sample.fontWeight,
- fontVariations: sample.fontVariations ?? [],
textAutoResize: 'NONE',
fills: [
{ type: 'SOLID', color: { r: 0.04, g: 0.06, b: 0.12, a: 1 }, visible: true, opacity: 1 }
- ]
+ ],
+ ...line
}).id
)
@@ -87,8 +78,43 @@ test('variable fonts render each style at its named instance', async ({ page })
return node ? store.renderer?.nodeFontReadiness(node) : 'missing'
})
}
- })
+ }, lines)
+}
+
+test('variable fonts render each style at its named instance', async ({ page }) => {
+ await openEditor(page)
+
+ const samples = [
+ { label: 'Regular 400', fontWeight: 400 },
+ { label: 'Medium 500', fontWeight: 500 },
+ { label: 'SemiBold 600', fontWeight: 600 },
+ { label: 'Bold 700', fontWeight: 700 },
+ {
+ label: 'Bold, explicit wght 300',
+ fontWeight: 700,
+ fontVariations: [{ axis: 'wght', value: 300 }]
+ }
+ ]
+ const result = await exportLines(
+ page,
+ samples.map(({ label, ...fields }) => ({ text: `${label} — Buttons`, ...fields }))
+ )
expect(result.readiness).toEqual(['ready', 'ready', 'ready', 'ready', 'ready'])
expect(Buffer.from(result.image)).toMatchSnapshot('variable-font-weights.png')
})
+
+test('a range draws at its own optical size, as Figma saves one', async ({ page }) => {
+ await openEditor(page)
+
+ // At 32 px automatic optical size is 32; the fixture's axis runs from 14 to 32.
+ const fixed = { opticalSizeFromFontSize: false, fontVariations: [{ axis: 'opsz', value: 14 }] }
+ const result = await exportLines(page, [
+ { text: 'Automatic optical size' },
+ { text: 'Automatic, then fixed 14', styleRuns: [{ start: 11, length: 13, style: fixed }] },
+ { text: 'Fixed optical size 14', ...fixed }
+ ])
+
+ expect(result.readiness).toEqual(['ready', 'ready', 'ready'])
+ expect(Buffer.from(result.image)).toMatchSnapshot('variable-font-optical-size-ranges.png')
+})
diff --git a/tests/e2e/fonts/variable-weights-visual.spec.ts-snapshots/variable-font-optical-size-ranges-openpencil-darwin.png b/tests/e2e/fonts/variable-weights-visual.spec.ts-snapshots/variable-font-optical-size-ranges-openpencil-darwin.png
new file mode 100644
index 000000000..359ee9a46
Binary files /dev/null and b/tests/e2e/fonts/variable-weights-visual.spec.ts-snapshots/variable-font-optical-size-ranges-openpencil-darwin.png differ