Skip to content

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

fix: draw typed emoji, keycaps, and missing characters in the editor and in Figma (#1291)

Danila Poyarkov1bed7d46b8b1
diff --git a/bun.lock b/bun.lock
index 588144cc7..639d23086 100644
--- a/bun.lock
+++ b/bun.lock
@@ -723,7 +723,11 @@
},
"tools/generate/emoji-metrics": {
"name": "@open-pencil/emoji-metrics-tools",
+ "dependencies": {
+ "opentype.js": "^2.0.0",
+ },
"devDependencies": {
+ "@open-pencil/core": "workspace:*",
"@open-pencil/package-artifacts-tools": "workspace:*",
},
},
diff --git a/changes/1291/fixed.md b/changes/1291/fixed.md
new file mode 100644
index 000000000..5889e5fb6
--- /dev/null
+++ b/changes/1291/fixed.md
@@ -0,0 +1,3 @@
+- Text typed in OpenPencil with an emoji draws its emoji and its letters in Figma after a copy or save, instead of showing blank.
+- Typed keycaps such as 1️⃣ draw as their character in a keycap frame, as in Figma, instead of hiding their text.
+- Text with a character no font has draws with a missing-glyph box for that character instead of disappearing, and draws in Figma after a copy or save.
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index b7d5fe58d..043a79ab7 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -84,6 +84,7 @@ Canvas is CanvasKit (Skia WASM) on a WebGL surface, not DOM.
- Paragraph construction is typed against `packages/core/src/canvas/text/paragraph/inputs.ts`; the same inputs drive preparation-cache invalidation. Add a mutation case when extending that contract. Drawing borrows native paragraphs; the renderer owns their bounded cache and destruction.
- Text lays out through `buildParagraph` into a `TextLayout` (`packages/core/src/canvas/text/layout/`): one native paragraph for plain text, or one per paragraph with its list indent, marker, and spacing, since Skia has no hanging indent. Drawing, measurement, the text editor, saved glyphs (`shapeText`), and text outlines all read that layout rather than laying text out again (`packages/core/tests/canvas/text/lists.test.ts`).
- Emoji are 1 em squares with their image drawn over, once per text and apart from the fills, as Figma does: `drawSavedEmoji` over a saved glyph's placeholder square (`emojiCodePoints`), `drawLaidOutEmoji` over the blank square the layout gives a character it falls back to `OpenPencil Emoji Metrics` for, the last fallback family, generated by `bun run generate:emoji-metrics`. The image comes from the browser's emoji font through a 2D canvas, or from Noto Color Emoji that `prepareGraphFonts` loads where nothing draws platform emoji (`tests/e2e/canvas/saved-glyph-visual.spec.ts`).
+- A keycap mark (U+20E3) is laid out as a zero-width space (`laidOutText`), since CanvasKit shapes it with the key's font, which lacks it; its frame, Noto Sans Symbols' outline that Figma draws, is drawn in the text's paint and saved apart (`packages/core/src/canvas/text/keycap.ts`, written by `bun run generate:emoji-metrics`; `packages/core/tests/canvas/text/shape.test.ts`).
### Text decorations
diff --git a/packages/core/assets/NotoSansSymbols-OFL.txt b/packages/core/assets/NotoSansSymbols-OFL.txt
new file mode 100644
index 000000000..7c95767f5
--- /dev/null
+++ b/packages/core/assets/NotoSansSymbols-OFL.txt
@@ -0,0 +1,93 @@
+Copyright 2022 The Noto Project Authors (https://github.com/notofonts/symbols)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/packages/core/assets/OpenPencilEmojiMetrics-Regular.ttf b/packages/core/assets/OpenPencilEmojiMetrics-Regular.ttf
index 7175fa35c..6b098ffda 100644
Binary files a/packages/core/assets/OpenPencilEmojiMetrics-Regular.ttf and b/packages/core/assets/OpenPencilEmojiMetrics-Regular.ttf differ
diff --git a/packages/core/src/canvas/text/decorations.ts b/packages/core/src/canvas/text/decorations.ts
index f5b8dddd3..d53a4b019 100644
--- a/packages/core/src/canvas/text/decorations.ts
+++ b/packages/core/src/canvas/text/decorations.ts
@@ -10,9 +10,12 @@ import type {
import { resolveRGBAForPreview } from '@open-pencil/scene-graph/color'
import { outlineInk, savedGlyphInk, type InkSpan } from '#core/canvas/text/ink'
+import { COMBINING_KEYCAP, drawKeycapFrame } from '#core/canvas/text/keycap'
+import type { TextLayout } from '#core/canvas/text/layout'
+import { styleRunColor } from '#core/canvas/text/paragraph'
import { laidOutGlyphs, type LaidOutGlyph } from '#core/canvas/text/placed'
import type { PreparedText } from '#core/canvas/text/preparation/cache'
-import { shownText } from '#core/text/case'
+import { shownCharacters, shownText } from '#core/text/case'
import { characterStyles, TEXT_STYLE_KEYS, type CharacterStyle } from '#core/text/character-style'
import { weightToStyle } from '#core/text/fonts'
import { fontDecorationMetricsSync, type FontDecorationMetrics } from '#core/text/opentype'
@@ -347,6 +350,42 @@ export function savedTextDecorationRects(
* Draws laid-out text and its decorations, `y` below the node's top. The decorations are kept
* with the prepared text, which its cache replaces when an input of the text changes.
*/
+/** The frames of the text's keycaps, which its layout leaves to be drawn, in their text's colour. */
+function drawKeycapFrames(
+ ck: CanvasKit,
+ canvas: Canvas,
+ node: SceneNode,
+ layout: TextLayout,
+ y: number,
+ paint: Paint
+): void {
+ const text = shownText(node)
+ if (!text.includes(COMBINING_KEYCAP)) return
+ // Style runs index the source text, which a case such as `ß` to `SS` makes shorter.
+ const sourceIndexAt = new Map<number, number>()
+ let shownIndex = 0
+ for (const { character, sourceIndex } of shownCharacters(node)) {
+ sourceIndexAt.set(shownIndex, sourceIndex)
+ shownIndex += character.length
+ }
+ const runPaint = paint.copy()
+ try {
+ for (const glyph of laidOutGlyphs(node, layout, text, y) ?? []) {
+ const character = glyph.firstCharacter
+ if (character === undefined || text[character] !== COMBINING_KEYCAP) continue
+ // The frame takes the colour the paragraph gives its mark: its style run's, if it has one.
+ const source = sourceIndexAt.get(character) ?? character
+ const run = node.styleRuns.find(
+ (item) => source >= item.start && source < item.start + item.length
+ )
+ runPaint.setColor(run ? styleRunColor(ck, run.style, paint.getColor()) : paint.getColor())
+ drawKeycapFrame(ck, canvas, glyph.x, glyph.y, glyph.fontSize, runPaint)
+ }
+ } finally {
+ runPaint.delete()
+ }
+}
+
export function drawTextLayout(
ck: CanvasKit,
canvas: Canvas,
@@ -357,6 +396,7 @@ export function drawTextLayout(
): void {
const layout = prepared.paragraph
layout.draw(canvas, 0, y)
+ drawKeycapFrames(ck, canvas, node, layout, y, textPaint)
if (!hasDecoration(node)) return
if (prepared.decorations?.y !== y) {
const glyphs = laidOutGlyphs(node, layout, shownText(node), y)
diff --git a/packages/core/src/canvas/text/index.ts b/packages/core/src/canvas/text/index.ts
index 284419436..175abd5ff 100644
--- a/packages/core/src/canvas/text/index.ts
+++ b/packages/core/src/canvas/text/index.ts
@@ -161,7 +161,9 @@ function observedGlyphReadiness(r: TextRenderer, node: SceneNode): NodeFontReadi
}
}
if (pending) return 'pending'
- return exhausted ? 'exhausted' : 'ready'
+ // Once no fallback is left for a character, the text draws with the fonts it has, the font's
+ // missing-glyph box standing in for that character, rather than not at all.
+ return exhausted ? 'substituted' : 'ready'
}
function canObserveGlyphCoverage(r: FontReadinessRenderer): r is TextRenderer {
diff --git a/packages/core/src/canvas/text/keycap.ts b/packages/core/src/canvas/text/keycap.ts
new file mode 100644
index 000000000..6d4560d2a
--- /dev/null
+++ b/packages/core/src/canvas/text/keycap.ts
@@ -0,0 +1,54 @@
+import type { Canvas, CanvasKit, Paint } from 'canvaskit-wasm'
+
+import { KEYCAP_FRAME } from '#core/text/keycap'
+import type { OutlineCommand } from '#core/text/opentype'
+
+import { appendOutlineCommand } from './outline-path'
+
+/** The combining enclosing keycap, which draws a frame around the character before it. */
+export const COMBINING_KEYCAP = '⃣'
+
+/** What the keycap mark becomes for layout: nothing to draw, and as long in UTF-16 and UTF-8. */
+const ZERO_WIDTH_SPACE = '​'
+
+/**
+ * Text as CanvasKit lays it out. CanvasKit shapes a keycap mark with the font of the character it
+ * frames, and a text font has no glyph for it, so the mark is laid out as a zero-width space and
+ * its frame drawn apart, as Figma draws it from Noto Sans Symbols. Offsets do not move.
+ */
+export function laidOutText(text: string): string {
+ return text.includes(COMBINING_KEYCAP)
+ ? text.replaceAll(COMBINING_KEYCAP, ZERO_WIDTH_SPACE)
+ : text
+}
+
+/** The keycap frame in pixels at `size`, y down from the baseline, centred on the pen. */
+export function keycapFrame(size: number): OutlineCommand[] {
+ return KEYCAP_FRAME.map((command) => {
+ const scaled: OutlineCommand = { type: command.type }
+ for (const key of ['x', 'y', 'x1', 'y1', 'x2', 'y2'] as const) {
+ const value = command[key]
+ if (value !== undefined) scaled[key] = value * size
+ }
+ return scaled
+ })
+}
+
+/** Draws a keycap frame with `paint`, its pen at `x` on the baseline `y`. */
+export function drawKeycapFrame(
+ ck: CanvasKit,
+ canvas: Canvas,
+ x: number,
+ y: number,
+ size: number,
+ paint: Paint
+): void {
+ const builder = new ck.PathBuilder()
+ for (const command of keycapFrame(size)) appendOutlineCommand(builder, command, x, y)
+ const path = builder.detachAndDelete()
+ try {
+ canvas.drawPath(path, paint)
+ } finally {
+ path.delete()
+ }
+}
diff --git a/packages/core/src/canvas/text/outline-path.ts b/packages/core/src/canvas/text/outline-path.ts
new file mode 100644
index 000000000..788f0fec7
--- /dev/null
+++ b/packages/core/src/canvas/text/outline-path.ts
@@ -0,0 +1,41 @@
+import type { PathBuilder } from 'canvaskit-wasm'
+
+import type { OutlineCommand } from '#core/text/opentype'
+
+/** Appends an outline command, offset by `xOffset` and `yOffset`, to a path being built. */
+export function appendOutlineCommand(
+ path: PathBuilder,
+ command: OutlineCommand,
+ xOffset: number,
+ yOffset: number
+): void {
+ switch (command.type) {
+ case 'M':
+ path.moveTo((command.x ?? 0) + xOffset, (command.y ?? 0) + yOffset)
+ break
+ case 'L':
+ path.lineTo((command.x ?? 0) + xOffset, (command.y ?? 0) + yOffset)
+ break
+ case 'C':
+ path.cubicTo(
+ (command.x1 ?? 0) + xOffset,
+ (command.y1 ?? 0) + yOffset,
+ (command.x2 ?? 0) + xOffset,
+ (command.y2 ?? 0) + yOffset,
+ (command.x ?? 0) + xOffset,
+ (command.y ?? 0) + yOffset
+ )
+ break
+ case 'Q':
+ path.quadTo(
+ (command.x1 ?? 0) + xOffset,
+ (command.y1 ?? 0) + yOffset,
+ (command.x ?? 0) + xOffset,
+ (command.y ?? 0) + yOffset
+ )
+ break
+ case 'Z':
+ path.close()
+ break
+ }
+}
diff --git a/packages/core/src/canvas/text/outlines.ts b/packages/core/src/canvas/text/outlines.ts
index 72829a6f0..7c9bffd14 100644
--- a/packages/core/src/canvas/text/outlines.ts
+++ b/packages/core/src/canvas/text/outlines.ts
@@ -1,54 +1,17 @@
-import type { Path, PathBuilder } from 'canvaskit-wasm'
+import type { Path } from 'canvaskit-wasm'
import type { SceneNode } from '@open-pencil/scene-graph'
import type { SkiaRenderer } from '#core/canvas/renderer'
-import type { OutlineCommand } from '#core/text/opentype'
import {
getTextOutlineSupport,
textNodeToOutlineLayout,
type TextOutlineGlyph
} from '#core/text/outlines'
+import { appendOutlineCommand } from './outline-path'
import { shapeText } from './shape'
-function appendOutlineCommand(
- path: PathBuilder,
- command: OutlineCommand,
- xOffset: number,
- yOffset: number
-): void {
- switch (command.type) {
- case 'M':
- path.moveTo((command.x ?? 0) + xOffset, (command.y ?? 0) + yOffset)
- break
- case 'L':
- path.lineTo((command.x ?? 0) + xOffset, (command.y ?? 0) + yOffset)
- break
- case 'C':
- path.cubicTo(
- (command.x1 ?? 0) + xOffset,
- (command.y1 ?? 0) + yOffset,
- (command.x2 ?? 0) + xOffset,
- (command.y2 ?? 0) + yOffset,
- (command.x ?? 0) + xOffset,
- (command.y ?? 0) + yOffset
- )
- break
- case 'Q':
- path.quadTo(
- (command.x1 ?? 0) + xOffset,
- (command.y1 ?? 0) + yOffset,
- (command.x ?? 0) + xOffset,
- (command.y ?? 0) + yOffset
- )
- break
- case 'Z':
- path.close()
- break
- }
-}
-
/**
* The glyphs the canvas draws, list markers included, when every one has an outline; text set
* partly in a fallback or variable font has none and keeps the outline layout's own glyphs.
diff --git a/packages/core/src/canvas/text/paragraph/index.ts b/packages/core/src/canvas/text/paragraph/index.ts
index 0e172596d..90ca1cc1a 100644
--- a/packages/core/src/canvas/text/paragraph/index.ts
+++ b/packages/core/src/canvas/text/paragraph/index.ts
@@ -14,6 +14,7 @@ import { resolveRGBAForPreview } from '@open-pencil/scene-graph/color'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
import { resolveParagraphFontFamilies } from '#core/canvas/text/font-families'
+import { laidOutText } from '#core/canvas/text/keycap'
import {
pushParagraphStyle,
type ParagraphPaintStyle,
@@ -116,7 +117,8 @@ function blockHeightBehavior(
return ck.TextHeightBehavior.All
}
-function styleRunColor(
+/** The colour a style run's text is drawn in: its first visible solid fill, or `baseColor`. */
+export function styleRunColor(
ck: CanvasKit,
style: SceneNode['styleRuns'][number]['style'],
baseColor: Float32Array
@@ -181,7 +183,7 @@ function addParagraphText(
start: number,
end: number
): void {
- builder.addText(shownTextSlice(node, start, end))
+ builder.addText(laidOutText(shownTextSlice(node, start, end)))
}
function addStyledRuns(
diff --git a/packages/core/src/canvas/text/placed.ts b/packages/core/src/canvas/text/placed.ts
index 7e978f6fc..ac8721bb6 100644
--- a/packages/core/src/canvas/text/placed.ts
+++ b/packages/core/src/canvas/text/placed.ts
@@ -1,8 +1,10 @@
import type { Paragraph } from 'canvaskit-wasm'
+import { uniq } from 'es-toolkit/array'
import type { SceneNode } from '@open-pencil/scene-graph'
import { resolveParagraphFontFamilies } from '#core/canvas/text/font-families'
+import { laidOutText } from '#core/canvas/text/keycap'
import type { TextLayout, TextLayoutMarker } from '#core/canvas/text/layout'
import { textFontVariations } from '#core/canvas/text/paragraph'
import { utf16IndicesByUtf8 } from '#core/canvas/text/utf8'
@@ -100,6 +102,45 @@ function drawsOwnGlyph(
return false
}
+/** Characters a shaper draws as nothing, such as variation selectors and joiners, whatever the font. */
+const DRAWN_AS_NOTHING = /[\s\p{Default_Ignorable_Code_Point}]/u
+
+/**
+ * The characters a run draws with glyphs of its font, leaving out whitespace and characters the
+ * shaper draws as nothing. A character no font has is shaped as the run font's missing glyph
+ * (ID 0), which says nothing about which font that is, so it does not count against the font
+ * the run's other characters confirm.
+ */
+function drawnCharacters(
+ text: string,
+ run: GlyphRun,
+ offsets: number[],
+ start: number,
+ end: number
+): string {
+ // A glyph covers the characters up to the next greater offset in the run, whatever its
+ // direction; the sorted offsets give that once for every glyph.
+ const boundaries = uniq([...offsets, end]).sort((a, b) => a - b)
+ const nextBoundary = new Map(
+ boundaries.map((offset, index) => [offset, boundaries[index + 1] ?? end])
+ )
+ const missing = new Set<number>()
+ for (const [index, glyph] of run.glyphs.entries()) {
+ if (glyph !== 0) continue
+ const from = offsets[index]
+ const to = nextBoundary.get(from) ?? end
+ for (let character = from; character < to; character++) missing.add(character)
+ }
+ let characters = ''
+ for (let index = start; index < end;) {
+ const codePoint = text.codePointAt(index) ?? 0
+ const character = String.fromCodePoint(codePoint)
+ if (!missing.has(index) && !DRAWN_AS_NOTHING.test(character)) characters += character
+ index += character.length
+ }
+ return characters
+}
+
/**
* The font a run was shaped with. CanvasKit leaves `GlyphRun.typeface` null, so the run's font
* is found as the paragraph falls back: the first of the fonts it lists, the style's own then
@@ -109,6 +150,7 @@ function drawsOwnGlyph(
function runOutlineSource(
node: SceneNode,
text: string,
+ shaped: string,
run: GlyphRun,
characterAt: (offset: number) => number
): GlyphOutlineSource | null {
@@ -116,7 +158,7 @@ function runOutlineSource(
const offsets = Array.from(run.offsets, characterAt)
const start = Math.min(...offsets)
const end = Math.max(...offsets)
- const characters = text.slice(start, end).replace(/\s/g, '')
+ const characters = drawnCharacters(shaped, run, offsets, start, end)
for (const source of candidateSources(fontAt(node, start))) {
if (!source.covers(characters)) continue
if (characters === '' || drawsOwnGlyph(source, run, text, characterAt)) return source
@@ -186,6 +228,8 @@ export function laidOutGlyphs(
const metrics = layout.getLineMetrics()
if (lines.length === 0 || lines.length !== metrics.length) return null
const characterAt = utf16IndicesByUtf8(text)
+ // The runs drew the text as laid out, a keycap mark as a zero-width space.
+ const shaped = laidOutText(text)
const markers = new Map(layout.getMarkers().map((marker) => [marker.lineNumber, marker]))
const glyphs: LaidOutGlyph[] = []
for (const [lineIndex, line] of lines.entries()) {
@@ -198,7 +242,7 @@ export function laidOutGlyphs(
lastLine && runIndex === line.runs.length - 1 && layout.didExceedMaxLines()
? ellipsisSource(node, run, characterAt)
: null
- const source = ellipsis ?? runOutlineSource(node, text, run, characterAt)
+ const source = ellipsis ?? runOutlineSource(node, text, shaped, run, characterAt)
for (let index = 0; index < run.glyphs.length; index++) {
const x = run.positions[index * 2]
glyphs.push({
diff --git a/packages/core/src/canvas/text/shape.ts b/packages/core/src/canvas/text/shape.ts
index 7ba5da141..c2bdbb69e 100644
--- a/packages/core/src/canvas/text/shape.ts
+++ b/packages/core/src/canvas/text/shape.ts
@@ -13,10 +13,14 @@ import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { buildParagraph, textVerticalOffset } from '#core/canvas/text'
import { textDecorationRects, type DecoratedGlyph } from '#core/canvas/text/decorations'
import { outlineInk, savedGlyphInk } from '#core/canvas/text/ink'
-import { laidOutGlyphs } from '#core/canvas/text/placed'
+import { COMBINING_KEYCAP, keycapFrame } from '#core/canvas/text/keycap'
+import { characterFamily, laidOutGlyphs, type LaidOutGlyph } from '#core/canvas/text/placed'
import { getCanvasKit } from '#core/canvaskit'
import { shownText } from '#core/text/case'
+import { EMOJI_METRICS_FAMILY } from '#core/text/emoji'
import { fontManager } from '#core/text/fonts'
+import { nextGraphemeBoundary } from '#core/text/graphemes'
+import type { OutlineCommand } from '#core/text/opentype'
/**
* Whether saved glyphs could stand for this text: case changes that alter its length move
@@ -36,11 +40,69 @@ function completeCharacterOffsets(offsets: Array<number | undefined>): number[]
})
}
+/**
+ * The square Figma saves for an emoji, in pixels at `size` with y down: 1 em wide, from 0.07 em
+ * below the baseline, closed with a line back to its start as Figma writes it.
+ */
+function emojiPlaceholder(size: number): OutlineCommand[] {
+ const bottom = 0.07 * size
+ const top = -0.93 * size
+ return [
+ { type: 'M', x: 0, y: bottom },
+ { type: 'L', x: size, y: bottom },
+ { type: 'L', x: size, y: top },
+ { type: 'L', x: 0, y: top },
+ { type: 'L', x: 0, y: bottom },
+ { type: 'Z' }
+ ]
+}
+
+interface SavedEmoji {
+ codePoints: number[]
+ /** Where the emoji's characters end in the text. */
+ end: number
+}
+
+/**
+ * The emoji a glyph starts, as Figma saves it, when the layout gave it to the emoji metrics font:
+ * its code points, an emoji that shows as text by default with the selector that asks for its
+ * emoji form, as Figma saves ☺ as ☺️.
+ */
+function savedEmoji(node: SceneNode, text: string, glyph: LaidOutGlyph): SavedEmoji | undefined {
+ const start = glyph.firstCharacter
+ if (start === undefined || characterFamily(node, text, start) !== EMOJI_METRICS_FAMILY)
+ return undefined
+ const end = nextGraphemeBoundary(text, start)
+ const emoji = text.slice(start, end)
+ const codePoints = Array.from(emoji, (character) => character.codePointAt(0) ?? 0)
+ if (codePoints.length === 1 && !/\p{Emoji_Presentation}/u.test(emoji)) codePoints.push(0xfe0f)
+ return { codePoints, end }
+}
+
+/**
+ * A glyph's saved outline: an emoji's placeholder, nothing inside one, a keycap's frame, or its
+ * font's outline.
+ */
+function savedOutline(
+ glyph: LaidOutGlyph,
+ text: string,
+ emoji: SavedEmoji | undefined,
+ insideEmoji: boolean
+): OutlineCommand[] | null {
+ if (insideEmoji) return []
+ if (emoji) return emojiPlaceholder(glyph.fontSize)
+ const character = glyph.firstCharacter
+ if (character !== undefined && text[character] === COMBINING_KEYCAP)
+ return keycapFrame(glyph.fontSize)
+ return glyph.source?.outline(glyph.id, glyph.fontSize) ?? null
+}
+
/**
* Lay a text node out as the renderer draws it and pair each shaped glyph with the outline of
- * the glyph ID CanvasKit chose, so ligatures and contextual forms keep their shapes. When a run's
- * font is missing, variable, or a fallback, no glyph gets an outline: the layout still stands,
- * and readers draw the text themselves.
+ * the glyph ID CanvasKit chose, so ligatures and contextual forms keep their shapes. An emoji the
+ * layout gives the emoji metrics font is saved as Figma saves one: a placeholder square with its
+ * code points. When a run's font cannot be told, no glyph gets an outline: the layout still
+ * stands and OpenPencil lays the text out again on reading, but Figma draws it blank.
* Returns `null` for text saved glyphs cannot represent at all.
*/
export function shapeText(
@@ -60,17 +122,24 @@ export function shapeText(
if (!placed) return null
const metrics = paragraph.getLineMetrics()
const characterOffsets: Array<number | undefined> = Array.from({ length: text.length })
+ // A sequence the font does not join is several glyphs: the first stands for the emoji, and
+ // the rest keep their place and draw nothing. Glyphs come in visual order, so in
+ // right-to-left text a character before the emoji can follow it: the whole range counts.
+ let emojiRange = { start: 0, end: 0 }
const glyphs: ShapedTextGlyph[] = placed.map((glyph) => {
- if (glyph.firstCharacter !== undefined) {
- characterOffsets[glyph.firstCharacter] ??= glyph.x - glyph.lineLeft
- }
+ const start = glyph.firstCharacter
+ if (start !== undefined) characterOffsets[start] ??= glyph.x - glyph.lineLeft
+ const insideEmoji = start !== undefined && start > emojiRange.start && start < emojiRange.end
+ const emoji = insideEmoji ? undefined : savedEmoji(node, text, glyph)
+ if (emoji && start !== undefined) emojiRange = { start, end: emoji.end }
return {
- commands: glyph.source?.outline(glyph.id, glyph.fontSize) ?? null,
+ commands: savedOutline(glyph, text, emoji, insideEmoji),
x: glyph.x,
y: glyph.y,
fontSize: glyph.fontSize,
- firstCharacter: glyph.firstCharacter,
- advance: glyph.advance
+ firstCharacter: start,
+ advance: glyph.advance,
+ emojiCodePoints: emoji?.codePoints
}
})
// Outlines from some runs only would draw the text with characters missing.
diff --git a/packages/core/src/text/index.ts b/packages/core/src/text/index.ts
index 98a83d518..4e289aae7 100644
--- a/packages/core/src/text/index.ts
+++ b/packages/core/src/text/index.ts
@@ -12,3 +12,4 @@ export * from './web-fonts'
export * from './path'
export * from './prepare'
export * from './font/faces'
+export type { OutlineCommand } from './opentype'
diff --git a/packages/core/src/text/keycap.ts b/packages/core/src/text/keycap.ts
new file mode 100644
index 000000000..574ceccd0
--- /dev/null
+++ b/packages/core/src/text/keycap.ts
@@ -0,0 +1,304 @@
+// Generated by `bun run generate:emoji-metrics`; do not edit.
+// Copyright 2022 The Noto Project Authors (https://github.com/notofonts/symbols)
+// Licensed under the SIL Open Font License, Version 1.1 (packages/core/assets/NotoSansSymbols-OFL.txt).
+
+import type { OutlineCommand } from './opentype'
+
+/**
+ * The frame Figma draws a keycap with: Noto Sans Symbols' combining enclosing keycap (U+20E3),
+ * in em with y down from the baseline. It has no advance and is centred where the key's
+ * character ends.
+ */
+export const KEYCAP_FRAME: readonly OutlineCommand[] = [
+ {
+ type: 'M',
+ x: 0.336,
+ y: 0.01
+ },
+ {
+ type: 'L',
+ x: -0.335,
+ y: 0.01
+ },
+ {
+ type: 'Q',
+ x: -0.398,
+ y: -0.0135,
+ x1: -0.374,
+ y1: 0.01
+ },
+ {
+ type: 'Q',
+ x: -0.422,
+ y: -0.076,
+ x1: -0.422,
+ y1: -0.037
+ },
+ {
+ type: 'L',
+ x: -0.422,
+ y: -0.076
+ },
+ {
+ type: 'L',
+ x: -0.422,
+ y: -0.746
+ },
+ {
+ type: 'Q',
+ x: -0.398,
+ y: -0.8085,
+ x1: -0.422,
+ y1: -0.785
+ },
+ {
+ type: 'Q',
+ x: -0.335,
+ y: -0.832,
+ x1: -0.374,
+ y1: -0.832
+ },
+ {
+ type: 'L',
+ x: -0.335,
+ y: -0.832
+ },
+ {
+ type: 'L',
+ x: 0.336,
+ y: -0.832
+ },
+ {
+ type: 'Q',
+ x: 0.3985,
+ y: -0.8085,
+ x1: 0.375,
+ y1: -0.832
+ },
+ {
+ type: 'Q',
+ x: 0.422,
+ y: -0.746,
+ x1: 0.422,
+ y1: -0.785
+ },
+ {
+ type: 'L',
+ x: 0.422,
+ y: -0.746
+ },
+ {
+ type: 'L',
+ x: 0.422,
+ y: -0.076
+ },
+ {
+ type: 'Q',
+ x: 0.3985,
+ y: -0.0135,
+ x1: 0.422,
+ y1: -0.037
+ },
+ {
+ type: 'Q',
+ x: 0.336,
+ y: 0.01,
+ x1: 0.375,
+ y1: 0.01
+ },
+ {
+ type: 'L',
+ x: 0.336,
+ y: 0.01
+ },
+ {
+ type: 'Z'
+ },
+ {
+ type: 'M',
+ x: -0.197,
+ y: -0.122
+ },
+ {
+ type: 'L',
+ x: -0.197,
+ y: -0.122
+ },
+ {
+ type: 'L',
+ x: 0.198,
+ y: -0.122
+ },
+ {
+ type: 'Q',
+ x: 0.251,
+ y: -0.137,
+ x1: 0.236,
+ y1: -0.122
+ },
+ {
+ type: 'Q',
+ x: 0.266,
+ y: -0.19,
+ x1: 0.266,
+ y1: -0.152
+ },
+ {
+ type: 'L',
+ x: 0.266,
+ y: -0.19
+ },
+ {
+ type: 'L',
+ x: 0.266,
+ y: -0.631
+ },
+ {
+ type: 'Q',
+ x: 0.251,
+ y: -0.6845,
+ x1: 0.266,
+ y1: -0.669
+ },
+ {
+ type: 'Q',
+ x: 0.198,
+ y: -0.7,
+ x1: 0.236,
+ y1: -0.7
+ },
+ {
+ type: 'L',
+ x: 0.198,
+ y: -0.7
+ },
+ {
+ type: 'L',
+ x: -0.197,
+ y: -0.7
+ },
+ {
+ type: 'Q',
+ x: -0.2495,
+ y: -0.684,
+ x1: -0.234,
+ y1: -0.7
+ },
+ {
+ type: 'Q',
+ x: -0.265,
+ y: -0.631,
+ x1: -0.265,
+ y1: -0.668
+ },
+ {
+ type: 'L',
+ x: -0.265,
+ y: -0.631
+ },
+ {
+ type: 'L',
+ x: -0.265,
+ y: -0.19
+ },
+ {
+ type: 'Q',
+ x: -0.2495,
+ y: -0.1375,
+ x1: -0.265,
+ y1: -0.153
+ },
+ {
+ type: 'Q',
+ x: -0.197,
+ y: -0.122,
+ x1: -0.234,
+ y1: -0.122
+ },
+ {
+ type: 'Z'
+ },
+ {
+ type: 'M',
+ x: 0.314,
+ y: -0.093
+ },
+ {
+ type: 'L',
+ x: 0.398,
+ y: -0.052
+ },
+ {
+ type: 'L',
+ x: 0.398,
+ y: -0.733
+ },
+ {
+ type: 'Q',
+ x: 0.3785,
+ y: -0.7865,
+ x1: 0.398,
+ y1: -0.765
+ },
+ {
+ type: 'Q',
+ x: 0.327,
+ y: -0.808,
+ x1: 0.359,
+ y1: -0.808
+ },
+ {
+ type: 'L',
+ x: 0.327,
+ y: -0.808
+ },
+ {
+ type: 'L',
+ x: -0.355,
+ y: -0.808
+ },
+ {
+ type: 'L',
+ x: -0.282,
+ y: -0.748
+ },
+ {
+ type: 'L',
+ x: 0.247,
+ y: -0.748
+ },
+ {
+ type: 'Q',
+ x: 0.2845,
+ y: -0.7405,
+ x1: 0.27,
+ y1: -0.748
+ },
+ {
+ type: 'Q',
+ x: 0.3065,
+ y: -0.7175,
+ x1: 0.299,
+ y1: -0.733
+ },
+ {
+ type: 'Q',
+ x: 0.314,
+ y: -0.678,
+ x1: 0.314,
+ y1: -0.702
+ },
+ {
+ type: 'L',
+ x: 0.314,
+ y: -0.678
+ },
+ {
+ type: 'L',
+ x: 0.314,
+ y: -0.093
+ },
+ {
+ type: 'Z'
+ }
+]
diff --git a/packages/core/tests/canvas/text/readiness.test.ts b/packages/core/tests/canvas/text/readiness.test.ts
new file mode 100644
index 000000000..2cdfa169f
--- /dev/null
+++ b/packages/core/tests/canvas/text/readiness.test.ts
@@ -0,0 +1,37 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
+
+import { nodeFontReadiness } from '#core/canvas/text'
+import { getCanvasKit } from '#core/canvaskit'
+import { fontManager } from '#core/text/fonts'
+
+/**
+ * A character no font has, once no fallback is left for it, shows as the font's missing glyph
+ * and leaves the rest of the text drawn; it used to hide the whole text.
+ */
+describe('text readiness with characters no font has', () => {
+ beforeAll(async () => {
+ const inter = expectDefined(
+ await fontManager.fetchBundledFont('/Inter-Regular.ttf'),
+ 'bundled Inter font'
+ )
+ fontManager.markLoaded('Inter', 'Regular', inter)
+ })
+
+ test('draws the text with the fonts it has', async () => {
+ const ck = await getCanvasKit()
+ const fontProvider = ck.TypefaceFontProvider.Make()
+ fontManager.attachProvider(ck, fontProvider)
+ const node = createDefaultNode(() => 'tamil-text', 'TEXT', {
+ text: 'Tamil \u0b86 ok',
+ fontFamily: 'Inter',
+ fontSize: 24,
+ width: 300,
+ height: 40
+ })
+ expect(nodeFontReadiness({ ck, fontProvider, fontsLoaded: true }, node)).toBe('substituted')
+ })
+})
diff --git a/packages/core/tests/canvas/text/shape.test.ts b/packages/core/tests/canvas/text/shape.test.ts
index 1297402e1..eaf386719 100644
--- a/packages/core/tests/canvas/text/shape.test.ts
+++ b/packages/core/tests/canvas/text/shape.test.ts
@@ -64,6 +64,159 @@ describe('text shaping for saved glyphs', () => {
expect([advance(1), advance(3), advance(3 + family.length)]).toEqual([40, 40, 40])
})
+ /**
+ * Figma draws a saved emoji from its code points over a placeholder square 1 em wide, from
+ * 0.07 em below the baseline, and saves ☺ with the selector for its emoji form; measured in
+ * Figma desktop. The other glyphs keep their outlines.
+ */
+ test('saves an emoji as Figma does: a placeholder square with its code points', async () => {
+ const metrics = expectDefined(
+ await fontManager.fetchBundledFont('/OpenPencilEmojiMetrics-Regular.ttf'),
+ 'bundled emoji metrics font'
+ )
+ fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)
+ const shaped = expectDefined(
+ await shape({ text: 'a😀☺©', fontSize: 40, width: 400, textAutoResize: 'NONE' }),
+ 'shaped text'
+ )
+ const glyph = (character: number) =>
+ expectDefined(
+ shaped.glyphs.find((candidate) => candidate.firstCharacter === character),
+ `glyph ${character}`
+ )
+ expect(glyph(1).emojiCodePoints).toEqual([0x1f600])
+ expect(glyph(3).emojiCodePoints).toEqual([0x263a, 0xfe0f])
+ const square = (glyph(1).commands ?? []).map(({ type, x, y }) => [type, x, y?.toFixed(2)])
+ expect(square).toEqual([
+ ['M', 0, '2.80'],
+ ['L', 40, '2.80'],
+ ['L', 40, '-37.20'],
+ ['L', 0, '-37.20'],
+ ['L', 0, '2.80'],
+ ['Z', undefined, undefined]
+ ])
+ for (const character of [0, 4]) {
+ expect(glyph(character).emojiCodePoints).toBeUndefined()
+ expect(glyph(character).commands?.length).toBeGreaterThan(1)
+ }
+ })
+
+ /**
+ * Figma draws pasted or saved text only from the glyph outlines written for it. A character no
+ * font has is shaped as the font's missing glyph; it must not cost the other characters their
+ * outlines, or Figma shows the text blank. Checked by pasting into Figma desktop.
+ */
+ test('outlines every glyph of text with a character no font has', async () => {
+ const shaped = expectDefined(
+ await shape({ text: 'Tamil \u0b86 ok', fontSize: 40, width: 400, textAutoResize: 'NONE' }),
+ 'shaped text'
+ )
+ expect(shaped.glyphs.every((glyph) => glyph.commands !== null)).toBe(true)
+ })
+
+ /**
+ * Figma draws a keycap as the text font's character with Noto Sans Symbols' keycap frame
+ * after it: no advance, centred where the character ends, from 0.01 em below the baseline to
+ * 0.83 em above. Measured from a keycap Figma saved.
+ */
+ test('saves a keycap as Figma does: the character, then the frame around it', async () => {
+ const shaped = expectDefined(
+ await shape({ text: 'Key 1\ufe0f\u20e3', fontSize: 100, width: 600, textAutoResize: 'NONE' }),
+ 'shaped text'
+ )
+ expect(shaped.glyphs.every((glyph) => glyph.commands !== null)).toBe(true)
+ const frame = expectDefined(
+ shaped.glyphs.find((glyph) => glyph.firstCharacter === 6),
+ 'keycap frame glyph'
+ )
+ const digit = expectDefined(
+ shaped.glyphs.find((glyph) => glyph.firstCharacter === 4),
+ 'keycap digit glyph'
+ )
+ const bounds = (axis: 'x' | 'y') => {
+ const values = (frame.commands ?? []).flatMap((command) =>
+ command[axis] === undefined ? [] : [command[axis]]
+ )
+ return [Math.min(...values), Math.max(...values)].map((value) => Number(value.toFixed(2)))
+ }
+ expect(frame.advance).toBe(0)
+ expect(frame.x).toBeCloseTo(digit.x + digit.advance, 3)
+ expect(bounds('x')).toEqual([-42.2, 42.2])
+ expect(bounds('y')).toEqual([-83.2, 1])
+ })
+
+ /** An emoji sequence the font does not join is several glyphs; Figma gets the emoji once. */
+ test('saves an unjoined emoji sequence once, at its first glyph', async () => {
+ const metrics = expectDefined(
+ await fontManager.fetchBundledFont('/OpenPencilEmojiMetrics-Regular.ttf'),
+ 'bundled emoji metrics font'
+ )
+ fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)
+ const sequence = '\u{1f469}\u200d\u{1f9af}\u200d\u{1f4bb}'
+ const shaped = expectDefined(
+ await shape({ text: `x${sequence}x`, fontSize: 40, width: 400, textAutoResize: 'NONE' }),
+ 'shaped text'
+ )
+ const emoji = shaped.glyphs.filter((glyph) => glyph.emojiCodePoints)
+ expect(emoji.map((glyph) => glyph.firstCharacter)).toEqual([1])
+ expect(emoji[0]?.emojiCodePoints).toEqual(Array.from(sequence, (c) => c.codePointAt(0) ?? 0))
+ expect(shaped.glyphs.length).toBeGreaterThan(3)
+ expect(shaped.glyphs.every((glyph) => glyph.commands !== null)).toBe(true)
+ })
+
+ /**
+ * Glyphs come in visual order, so in right-to-left text a letter before an emoji can follow
+ * it; that letter keeps its outline.
+ */
+ test('keeps the outlines of letters an emoji precedes in right-to-left text', async () => {
+ const metrics = expectDefined(
+ await fontManager.fetchBundledFont('/OpenPencilEmojiMetrics-Regular.ttf'),
+ 'bundled emoji metrics font'
+ )
+ fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)
+ const shaped = expectDefined(
+ await shape({
+ text: '\u05d0\u{1f600}\u05d1',
+ textDirection: 'RTL',
+ fontSize: 40,
+ width: 400,
+ textAutoResize: 'NONE'
+ }),
+ 'shaped text'
+ )
+ // Inter has no Hebrew: each letter is the missing glyph's box, an outline all the same.
+ for (const character of [0, 3]) {
+ const glyph = shaped.glyphs.find((candidate) => candidate.firstCharacter === character)
+ expect(glyph?.commands?.length).toBeGreaterThan(1)
+ }
+ })
+
+ /**
+ * Characters the shaper draws as nothing, tag characters among them, take two UTF-16 units
+ * past the Basic Multilingual Plane; they must not cost the letters around them their outlines.
+ */
+ test('outlines letters beside a tag sequence and a supplementary tag character', async () => {
+ const metrics = expectDefined(
+ await fontManager.fetchBundledFont('/OpenPencilEmojiMetrics-Regular.ttf'),
+ 'bundled emoji metrics font'
+ )
+ fontManager.markLoaded(EMOJI_METRICS_FAMILY, 'Regular', metrics)
+ const scotland = '\u{1f3f4}\u{e0067}\u{e0062}\u{e0073}\u{e0063}\u{e0074}\u{e007f}'
+ const shaped = expectDefined(
+ await shape({
+ text: `Flag ${scotland} a\u{e0001}b`,
+ fontSize: 40,
+ width: 600,
+ textAutoResize: 'NONE'
+ }),
+ 'shaped text'
+ )
+ expect(shaped.glyphs.every((glyph) => glyph.commands !== null)).toBe(true)
+ expect(shaped.glyphs.find((glyph) => glyph.emojiCodePoints)?.emojiCodePoints).toEqual(
+ Array.from(scotland, (c) => c.codePointAt(0) ?? 0)
+ )
+ })
+
test('breaks lines at the layer width (#914)', async () => {
const shaped = expectDefined(await shape({ text: SENTENCE }), 'shaped text')
const [first, second] = shaped.baselines
diff --git a/packages/fig/src/node-change/derived-text/build.ts b/packages/fig/src/node-change/derived-text/build.ts
index c6210cfdc..4bbb24d95 100644
--- a/packages/fig/src/node-change/derived-text/build.ts
+++ b/packages/fig/src/node-change/derived-text/build.ts
@@ -36,6 +36,8 @@ export interface ShapedTextGlyph {
firstCharacter?: number
/** Horizontal advance in pixels. */
advance: number
+ /** The emoji the glyph stands for, when it is one: its outline is then the placeholder square. */
+ emojiCodePoints?: number[]
}
/** Text laid out at the node's width, as the renderer draws it. */
@@ -114,7 +116,8 @@ function shapedGlyphRecords(
fontSize: glyph.fontSize,
firstCharacter: glyph.firstCharacter,
advance: glyph.fontSize > 0 ? glyph.advance / glyph.fontSize : 0,
- rotation: 0
+ rotation: 0,
+ ...emojiGlyphFields(glyph)
}))
}
diff --git a/tests/e2e/canvas/saved-glyph-visual.spec.ts b/tests/e2e/canvas/saved-glyph-visual.spec.ts
index b4c8235d0..7d31ec8fb 100644
--- a/tests/e2e/canvas/saved-glyph-visual.spec.ts
+++ b/tests/e2e/canvas/saved-glyph-visual.spec.ts
@@ -262,3 +262,74 @@ test('typed emoji take a 1 em square and draw their image', async () => {
maxDiffPixels: 500
})
})
+
+/**
+ * Figma draws a keycap as the text font's character with Noto Sans Symbols' keycap frame after
+ * it, in the colour of its text, a style run's included; the whole text used to disappear, as
+ * Inter has no keycap mark.
+ */
+test('typed keycaps draw their character in a keycap frame', async () => {
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('Missing editor')
+ store.graph.createNode('TEXT', store.state.currentPageId, {
+ x: 40,
+ y: 100,
+ width: 600,
+ height: 80,
+ text: 'Keys 1⃣ #⃣ ok',
+ fontFamily: 'Inter',
+ fontSize: 48,
+ fills: [
+ { type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.2, a: 1 }, opacity: 1, visible: true }
+ ],
+ styleRuns: [
+ {
+ start: 8,
+ length: 2,
+ style: {
+ fills: [
+ { type: 'SOLID', color: { r: 0.9, g: 0.1, b: 0.1, a: 1 }, opacity: 1, visible: true }
+ ]
+ }
+ }
+ ]
+ })
+ // Upper-cased, ß shows as SS: the keycap's run is found by its source index all the same.
+ store.graph.createNode('TEXT', store.state.currentPageId, {
+ x: 40,
+ y: 200,
+ width: 600,
+ height: 80,
+ text: '\u00df 1\u20e3',
+ textCase: 'UPPER',
+ fontFamily: 'Inter',
+ fontSize: 48,
+ fills: [
+ { type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.2, a: 1 }, opacity: 1, visible: true }
+ ],
+ styleRuns: [
+ {
+ start: 2,
+ length: 2,
+ style: {
+ fills: [
+ { type: 'SOLID', color: { r: 0.9, g: 0.1, b: 0.1, a: 1 }, opacity: 1, visible: true }
+ ]
+ }
+ }
+ ]
+ })
+ store.requestRender()
+ })
+ await editor.page.evaluate(
+ () =>
+ new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
+ })
+ )
+ // Letters a few hundred pixels wide stand out from edge noise; the default 1% would not.
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('typed-keycap.png', {
+ maxDiffPixels: 500
+ })
+})
diff --git a/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/typed-keycap-openpencil-darwin.png b/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/typed-keycap-openpencil-darwin.png
new file mode 100644
index 000000000..99cdb8c51
Binary files /dev/null and b/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/typed-keycap-openpencil-darwin.png differ
diff --git a/tools/generate/emoji-metrics/package.json b/tools/generate/emoji-metrics/package.json
index c5a09a6fd..9325a3d3a 100644
--- a/tools/generate/emoji-metrics/package.json
+++ b/tools/generate/emoji-metrics/package.json
@@ -8,7 +8,11 @@
"scripts": {
"test": "bun test tests"
},
+ "dependencies": {
+ "opentype.js": "^2.0.0"
+ },
"devDependencies": {
+ "@open-pencil/core": "workspace:*",
"@open-pencil/package-artifacts-tools": "workspace:*"
}
}
diff --git a/tools/generate/emoji-metrics/src/generate.ts b/tools/generate/emoji-metrics/src/generate.ts
index 393ae17f4..c3bd7cc33 100644
--- a/tools/generate/emoji-metrics/src/generate.ts
+++ b/tools/generate/emoji-metrics/src/generate.ts
@@ -1,31 +1,48 @@
/**
- * Writes the emoji metrics font into `packages/core/assets` from Noto Color Emoji at a
- * pinned google/fonts commit, with Noto's licence beside it. usage: bun generate.ts
+ * Writes the emoji metrics font into `packages/core/assets` from Noto Color Emoji, and the
+ * keycap frame into Core's source from Noto Sans Symbols, each at a pinned google/fonts commit
+ * with its licence beside it. usage: bun generate.ts
*/
import { join } from 'node:path'
import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts-tools'
+import { keycapModule, keycapOutline } from './keycap'
import { EMOJI_METRICS_ASSET, emojiMetricsFont } from './metrics'
import { readFontTables, writeFontTables } from './sfnt'
-const SOURCE_COMMIT = '142c8963e7606b510c93a644c82a4c4cdeae6ef9'
-const SOURCE = `https://raw.githubusercontent.com/google/fonts/${SOURCE_COMMIT}/ofl/notocoloremoji`
-const COPYRIGHT =
+const EMOJI_SOURCE =
+ 'https://raw.githubusercontent.com/google/fonts/142c8963e7606b510c93a644c82a4c4cdeae6ef9/ofl/notocoloremoji'
+const SYMBOLS_SOURCE =
+ 'https://raw.githubusercontent.com/google/fonts/8b0a1d0f5983c89bc2b93f1b5fb55f9e252744b5/ofl/notosanssymbols'
+const EMOJI_COPYRIGHT =
'Copyright 2021 Google Inc. All Rights Reserved. Derived from Noto Color Emoji: metrics only.'
+const SYMBOLS_COPYRIGHT =
+ 'Copyright 2022 The Noto Project Authors (https://github.com/notofonts/symbols)'
-async function download(file: string): Promise<Uint8Array> {
- const response = await fetch(`${SOURCE}/${file}`)
- if (!response.ok) throw new Error(`${file}: HTTP ${response.status}`)
+async function download(url: string): Promise<Uint8Array> {
+ const response = await fetch(url)
+ if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`)
return new Uint8Array(await response.arrayBuffer())
}
-const [font, licence] = await Promise.all([
- download('NotoColorEmoji-Regular.ttf'),
- download('OFL.txt')
+const [emoji, emojiLicence, symbols, symbolsLicence] = await Promise.all([
+ download(`${EMOJI_SOURCE}/NotoColorEmoji-Regular.ttf`),
+ download(`${EMOJI_SOURCE}/OFL.txt`),
+ download(`${SYMBOLS_SOURCE}/NotoSansSymbols%5Bwght%5D.ttf`),
+ download(`${SYMBOLS_SOURCE}/OFL.txt`)
])
-const output = writeFontTables(emojiMetricsFont(readFontTables(font), COPYRIGHT))
-const assets = join(await resolveWorkspaceRoot(import.meta.dir), 'packages/core/assets')
+const root = await resolveWorkspaceRoot(import.meta.dir)
+const assets = join(root, 'packages/core/assets')
+const output = writeFontTables(emojiMetricsFont(readFontTables(emoji), EMOJI_COPYRIGHT))
await Bun.write(join(assets, EMOJI_METRICS_ASSET), output)
-await Bun.write(join(assets, 'OpenPencilEmojiMetrics-OFL.txt'), licence)
-console.log(`${EMOJI_METRICS_ASSET}: ${output.length} bytes`)
+await Bun.write(join(assets, 'OpenPencilEmojiMetrics-OFL.txt'), emojiLicence)
+await Bun.write(join(assets, 'NotoSansSymbols-OFL.txt'), symbolsLicence)
+const keycap = join(root, 'packages/core/src/text/keycap.ts')
+await Bun.write(keycap, keycapModule(keycapOutline(symbols), SYMBOLS_COPYRIGHT))
+// The module is source, so it takes the repository's formatting.
+const formatted = Bun.spawnSync([join(root, 'node_modules/.bin/oxfmt'), '--write', keycap], {
+ cwd: root
+})
+if (!formatted.success) throw new Error(`oxfmt: ${formatted.stderr.toString()}`)
+console.log(`${EMOJI_METRICS_ASSET}: ${output.length} bytes; keycap frame written`)
diff --git a/tools/generate/emoji-metrics/src/keycap.ts b/tools/generate/emoji-metrics/src/keycap.ts
new file mode 100644
index 000000000..d93735394
--- /dev/null
+++ b/tools/generate/emoji-metrics/src/keycap.ts
@@ -0,0 +1,48 @@
+import * as opentype from 'opentype.js'
+
+import type { OutlineCommand } from '@open-pencil/core/text'
+
+/** The combining enclosing keycap, which draws a keycap's frame around the character before it. */
+export const COMBINING_KEYCAP = 0x20e3
+
+const round = (value: number | undefined) =>
+ value === undefined ? undefined : Math.round(value * 10000) / 10000
+
+/**
+ * The keycap frame of a font, in em with y down from the baseline as Core's outline commands
+ * are, relative to the pen: the glyph has no advance and is centred on where the key's character
+ * ends.
+ */
+export function keycapOutline(font: Uint8Array): OutlineCommand[] {
+ const parsed = opentype.parse(
+ font.buffer.slice(font.byteOffset, font.byteOffset + font.byteLength)
+ )
+ const glyph = parsed.charToGlyph(String.fromCodePoint(COMBINING_KEYCAP))
+ if (!glyph.index) throw new Error('The source font has no keycap')
+ const em = parsed.unitsPerEm
+ return glyph.path.commands.map((command) => {
+ const scaled: OutlineCommand = { type: command.type }
+ for (const key of ['x', 'y', 'x1', 'y1', 'x2', 'y2'] as const) {
+ const value = (command as Record<string, number | undefined>)[key]
+ if (value !== undefined) scaled[key] = round(key.startsWith('y') ? -value / em : value / em)
+ }
+ return scaled
+ })
+}
+
+/** Core's source holding the frame, with where it came from and its licence. */
+export function keycapModule(commands: OutlineCommand[], copyright: string): string {
+ return `// Generated by \`bun run generate:emoji-metrics\`; do not edit.
+// ${copyright}
+// Licensed under the SIL Open Font License, Version 1.1 (packages/core/assets/NotoSansSymbols-OFL.txt).
+
+import type { OutlineCommand } from './opentype'
+
+/**
+ * The frame Figma draws a keycap with: Noto Sans Symbols' combining enclosing keycap (U+20E3),
+ * in em with y down from the baseline. It has no advance and is centred where the key's
+ * character ends.
+ */
+export const KEYCAP_FRAME: readonly OutlineCommand[] = ${JSON.stringify(commands, null, 2)}
+`
+}
diff --git a/tools/generate/emoji-metrics/src/metrics.ts b/tools/generate/emoji-metrics/src/metrics.ts
index 5c43ab834..46adc4e14 100644
--- a/tools/generate/emoji-metrics/src/metrics.ts
+++ b/tools/generate/emoji-metrics/src/metrics.ts
@@ -1,4 +1,5 @@
import { readCharacterMap, writeCharacterMap } from './cmap'
+import { COMBINING_KEYCAP } from './keycap'
import type { FontTables } from './sfnt'
/** The family the metrics font registers under, which the editor's text layout falls back to. */
@@ -11,12 +12,11 @@ export const EMOJI_METRICS_ASSET = 'OpenPencilEmojiMetrics-Regular.ttf'
const KEPT_TABLES = ['GSUB', 'OS/2', 'post'] as const
/**
- * Noto maps ASCII digits, `#`, `*`, and the space for its keycap sequences. Figma draws a keycap
- * as the text font's character with the combining keycap after it, so those stay with the text
- * font and the keycap mark takes no room.
+ * Noto maps ASCII digits, `#`, `*`, the space, and the combining keycap for its keycap sequences.
+ * Figma draws a keycap as the text font's character with a keycap frame after it, which Core
+ * draws itself, so none of them are the metrics font's.
*/
const TEXT_CHARACTER_LIMIT = 0x80
-const COMBINING_KEYCAP = 0x20e3
/**
* The missing glyph's outline: a glyph header with no contours, all zero. Browsers' font
@@ -97,16 +97,15 @@ export function emojiMetricsFont(source: FontTables, copyright: string): FontTab
const characters = new Map(
[...readCharacterMap(required(source, 'cmap'))].filter(
- ([codePoint]) => codePoint >= TEXT_CHARACTER_LIMIT
+ ([codePoint]) => codePoint >= TEXT_CHARACTER_LIMIT && codePoint !== COMBINING_KEYCAP
)
)
- const zeroWidth = new Set([characters.get(COMBINING_KEYCAP)])
const hmtx = new Uint8Array(glyphCount * 4)
const hmtxView = new DataView(hmtx.buffer)
for (let glyph = 0; glyph < glyphCount; glyph++) {
const advance = sourceView.getUint16(Math.min(glyph, sourceMetricCount - 1) * 4)
- hmtxView.setUint16(glyph * 4, advance > 0 && !zeroWidth.has(glyph) ? unitsPerEm : 0)
+ hmtxView.setUint16(glyph * 4, advance > 0 ? unitsPerEm : 0)
}
// Short offsets, in words: the missing glyph holds the only outline, and every other is empty.
headView.setInt16(50, 0)
diff --git a/tools/generate/emoji-metrics/tests/metrics.test.ts b/tools/generate/emoji-metrics/tests/metrics.test.ts
index 3259dd46c..d2420aa18 100644
--- a/tools/generate/emoji-metrics/tests/metrics.test.ts
+++ b/tools/generate/emoji-metrics/tests/metrics.test.ts
@@ -34,8 +34,8 @@ test('the committed metrics font gives each emoji 1 em and its joiners none', as
expect(advance(0x1f600)).toBe(unitsPerEm)
expect(advance(0x1f1fa)).toBe(unitsPerEm)
expect(advance(0x200d)).toBe(0)
- expect(advance(0x20e3)).toBe(0)
- // Keycaps keep the text font's character, as Figma draws them.
+ // Keycaps keep the text font's character and Core draws their frame, as Figma draws them.
+ expect(advance(0x20e3)).toBeUndefined()
expect([...characters.keys()].some((codePoint) => codePoint < 0x80)).toBe(false)
expect(tables.has('CBDT') || tables.has('COLR') || tables.has('SVG ')).toBe(false)
})