Skip to content

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

fix!: load and draw font faces by their names, and list them in the style menu (#1620)

Danila Poyarkovf6277040f6eb
diff --git a/bunfig.toml b/bunfig.toml
index 5ddc325e3..494370744 100644
--- a/bunfig.toml
+++ b/bunfig.toml
@@ -2,6 +2,7 @@
# Preload discovery-file isolation for every `bun test` run so engine tests
# never clobber the real ~/Library/Application Support/OpenPencil/mcp.json
# (which would break a running OpenPencil desktop app). See
-# tests/helpers/mcp/discovery-isolation.ts for the rationale.
+# tests/helpers/mcp/discovery-isolation.ts for the rationale. Web font
+# providers start off, so no test reaches the network (tests/helpers/fonts/offline.ts).
[test]
-preload = ["./tests/helpers/mcp/discovery-isolation.ts"]
+preload = ["./tests/helpers/mcp/discovery-isolation.ts", "./tests/helpers/fonts/offline.ts"]
diff --git a/changes/1620/breaking.md b/changes/1620/breaking.md
new file mode 100644
index 000000000..b9ff79d08
--- /dev/null
+++ b/changes/1620/breaking.md
@@ -0,0 +1 @@
+- The desktop `list_system_fonts` command and `setHostFontCatalog` list each face with its style, weight, and slant instead of style names; the typography SDK's `weights` is `faces` (with `faceName` and `setFace`); `resolveParagraphFontFamilies` takes a face; `figma.loadFontAsync` rejects a style the family has no face of, as Figma does.
diff --git a/changes/1620/fixed.md b/changes/1620/fixed.md
new file mode 100644
index 000000000..f225e153c
--- /dev/null
+++ b/changes/1620/fixed.md
@@ -0,0 +1,2 @@
+- Text in a face that its weight alone cannot pick, such as Avenir Book, Roboto Condensed Bold, or Fira Code Retina, loads and draws in that face rather than the family's face of the same weight, keeps the weight Figma saved for it, and the style menu lists each face of a family by its name. On desktop, installed fonts are listed and loaded by the names their font files give each face.
+- The missing fonts banner updates as fonts finish loading after a paste or a script, instead of only after Retry fonts.
diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock
index 03140ea1c..c5a7409bd 100644
--- a/desktop/Cargo.lock
+++ b/desktop/Cargo.lock
@@ -99,6 +99,12 @@ dependencies = [
"x11rb",
]
+[[package]]
+name = "arrayvec"
+version = "0.7.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
+
[[package]]
name = "async-broadcast"
version = "0.7.2"
@@ -1213,6 +1219,15 @@ version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7"
+[[package]]
+name = "euclid"
+version = "0.22.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "event-listener"
version = "5.4.2"
@@ -2571,6 +2586,18 @@ dependencies = [
"libc",
]
+[[package]]
+name = "kurbo"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"
+dependencies = [
+ "arrayvec",
+ "euclid",
+ "polycool",
+ "smallvec",
+]
+
[[package]]
name = "libappindicator"
version = "0.9.0"
@@ -3262,6 +3289,7 @@ dependencies = [
"keyring",
"objc2-core-foundation",
"objc2-core-text",
+ "read-fonts",
"reqwest 0.12.28",
"security-framework",
"semver",
@@ -3284,6 +3312,7 @@ dependencies = [
"tokio",
"url",
"which",
+ "write-fonts",
"zip 2.4.2",
"zstd",
]
@@ -3566,6 +3595,15 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "polycool"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"
+dependencies = [
+ "arrayvec",
+]
+
[[package]]
name = "portable-atomic"
version = "1.15.0"
@@ -6752,6 +6790,19 @@ dependencies = [
"wayland-protocols-wlr",
]
+[[package]]
+name = "write-fonts"
+version = "0.50.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cae90d1d9f6d1d36ef116b0b1e651a6d7c12ba925439d4d06ff9adc94662a3d8"
+dependencies = [
+ "font-types",
+ "indexmap 2.14.0",
+ "kurbo",
+ "log",
+ "read-fonts",
+]
+
[[package]]
name = "writeable"
version = "0.6.4"
diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml
index a1fb1e1cf..30b391c82 100644
--- a/desktop/Cargo.toml
+++ b/desktop/Cargo.toml
@@ -40,6 +40,8 @@ zip = { version = "2", default-features = false }
which = "7.0.3"
semver = "1"
fontique = "0.11"
+# The same read-fonts fontique uses, to read each face's style names and named instances.
+read-fonts = "0.41"
fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs", branch = "dev" }
tauri-plugin-updater = "2"
tauri-plugin-process = "2"
@@ -51,6 +53,9 @@ url = "2"
httparse = "1"
tauri-plugin-wdio-webdriver = { version = "1.3.0", optional = true }
+[dev-dependencies]
+write-fonts = "=0.50.0"
+
[target.'cfg(target_os = "macos")'.dependencies]
security-framework = "3"
swift-rs = "=1.0.9"
diff --git a/desktop/src/fonts/catalog.rs b/desktop/src/fonts/catalog.rs
index ce78c7866..c5bc38a5b 100644
--- a/desktop/src/fonts/catalog.rs
+++ b/desktop/src/fonts/catalog.rs
@@ -4,7 +4,8 @@
use fontique::{Blob, Collection, CollectionOptions, FontInfo, FontStyle, SourceCache};
use std::sync::{Mutex, OnceLock};
-use super::style::named_weight;
+use super::names::{face_names, spelling, FaceNames};
+use super::style::{named_weight, names_weight, requested_face, style_name};
struct Catalog {
collection: Collection,
@@ -74,8 +75,78 @@ pub fn choose_face(faces: &[FaceTraits], weight: f32, italic: bool) -> Option<us
})
}
-/// Visible family names with the traits of each face.
-pub fn families() -> Vec<(String, Vec<FaceTraits>)> {
+/// A face as the frontend lists it: the name its font gives it, its weight, and its slant.
+#[derive(Clone, Debug, PartialEq, serde::Serialize)]
+pub struct ListedFace {
+ pub style: String,
+ pub weight: f32,
+ pub italic: bool,
+}
+
+/// The faces a font file draws, by the names it gives them: each named instance of a variable
+/// font, at its weight, else the face's own style name. A face whose font names it nothing takes
+/// the standard name of its weight.
+pub fn listed_faces(traits: &FaceTraits, names: &FaceNames) -> Vec<ListedFace> {
+ let mut faces: Vec<ListedFace> = names
+ .instances
+ .iter()
+ .map(|instance| ListedFace {
+ style: instance.name.clone(),
+ weight: instance.weight.unwrap_or(traits.weight),
+ italic: traits.italic,
+ })
+ .collect();
+ // The face the file draws by default, unless one of its instances already names it.
+ let own = names
+ .style
+ .clone()
+ .unwrap_or_else(|| style_name(traits.weight, traits.italic));
+ if !faces
+ .iter()
+ .any(|face| spelling(&face.style) == spelling(&own))
+ {
+ faces.push(ListedFace {
+ style: own,
+ weight: traits.weight,
+ italic: traits.italic,
+ });
+ }
+ faces
+}
+
+/// Picks the face `style` names: the face of that name, or a variable face with an instance of
+/// it, compared without case or spaces. A name that only names a weight falls back to that
+/// weight's face, as before faces had names; any other name is that face or none.
+pub fn choose_named_face(faces: &[(FaceTraits, FaceNames)], style: &str) -> Option<usize> {
+ let wanted = spelling(style);
+ // One pass in the order `families` lists them: the first font that names the face, by one
+ // of its instances or its own name (a variable font's own face is listed beside them).
+ let named = faces.iter().position(|(_, names)| {
+ names
+ .instances
+ .iter()
+ .any(|instance| spelling(&instance.name) == wanted)
+ || names.style.as_deref().map(spelling) == Some(wanted.clone())
+ });
+ named.or_else(|| {
+ if !names_weight(style) {
+ return None;
+ }
+ let (weight, italic) = requested_face(style);
+ let traits: Vec<FaceTraits> = faces.iter().map(|(traits, _)| *traits).collect();
+ choose_face(&traits, weight, italic)
+ })
+}
+
+/// The names a face's font gives it, read from the font file without caching its data.
+fn names_of(font: &FontInfo) -> FaceNames {
+ font.load(None)
+ .map(|data| face_names(data.as_ref(), font.index()))
+ .unwrap_or_default()
+}
+
+/// Visible family names with each face they list, by the names their fonts give them.
+pub fn families() -> Vec<(String, Vec<ListedFace>)> {
with_catalog(|catalog| {
let names: Vec<String> = catalog
.collection
@@ -87,18 +158,34 @@ pub fn families() -> Vec<(String, Vec<FaceTraits>)> {
.into_iter()
.filter_map(|name| {
let family = catalog.collection.family_by_name(&name)?;
- let faces = family.fonts().iter().map(FaceTraits::of).collect();
+ let mut faces: Vec<ListedFace> = Vec::new();
+ for font in family.fonts() {
+ for face in listed_faces(&FaceTraits::of(font), &names_of(font)) {
+ // An upright and an italic file may each name an instance "Bold".
+ if !faces.iter().any(|listed| {
+ spelling(&listed.style) == spelling(&face.style)
+ && listed.italic == face.italic
+ }) {
+ faces.push(face);
+ }
+ }
+ }
Some((name, faces))
})
.collect()
})
}
-pub fn load_face(family: &str, weight: f32, italic: bool) -> Option<Face> {
+/// The face of `family` that `style` names, as `choose_named_face` picks it.
+pub fn load_face(family: &str, style: &str) -> Option<Face> {
with_catalog(|catalog| {
let family = catalog.collection.family_by_name(family)?;
- let traits: Vec<FaceTraits> = family.fonts().iter().map(FaceTraits::of).collect();
- let font = &family.fonts()[choose_face(&traits, weight, italic)?];
+ let faces: Vec<(FaceTraits, FaceNames)> = family
+ .fonts()
+ .iter()
+ .map(|font| (FaceTraits::of(font), names_of(font)))
+ .collect();
+ let font = &family.fonts()[choose_named_face(&faces, style)?];
Some(Face {
data: font.load(Some(&mut catalog.cache))?,
index: font.index(),
@@ -108,6 +195,7 @@ pub fn load_face(family: &str, weight: f32, italic: bool) -> Option<Face> {
#[cfg(test)]
mod tests {
+ use super::super::names::NamedInstance;
use super::*;
fn face(weight: f32, italic: bool) -> FaceTraits {
@@ -161,4 +249,128 @@ mod tests {
};
assert_eq!(choose_face(&[narrow], 700.0, false), None);
}
+
+ fn named(style: &str) -> FaceNames {
+ FaceNames {
+ style: Some(style.to_string()),
+ instances: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn chooses_a_static_face_by_its_own_name() {
+ let faces = [
+ (face(400.0, false), named("Roman")),
+ (face(350.0, false), named("Book")),
+ (face(700.0, false), named("Condensed Bold")),
+ (face(700.0, false), named("Bold")),
+ ];
+ assert_eq!(choose_named_face(&faces, "Book"), Some(1));
+ assert_eq!(choose_named_face(&faces, "condensed bold"), Some(2));
+ // A weight name falls back to that weight's face; another name is that face or none.
+ assert_eq!(choose_named_face(&faces, "Regular"), Some(0));
+ assert_eq!(choose_named_face(&faces, "Heavy"), None);
+ }
+
+ #[test]
+ fn chooses_a_variable_face_by_one_of_its_instances() {
+ let variable = FaceNames {
+ style: Some("Regular".to_string()),
+ instances: vec![
+ NamedInstance {
+ name: "Bold".to_string(),
+ weight: Some(700.0),
+ },
+ NamedInstance {
+ name: "Condensed Bold".to_string(),
+ weight: Some(700.0),
+ },
+ ],
+ };
+ let faces = [(face(400.0, false), variable)];
+ assert_eq!(choose_named_face(&faces, "Condensed Bold"), Some(0));
+ assert_eq!(choose_named_face(&faces, "Condensed Black"), None);
+ }
+
+ #[test]
+ fn loads_a_variable_face_by_its_own_name_beside_its_instances() {
+ let variable = FaceNames {
+ style: Some("Text".to_string()),
+ instances: vec![NamedInstance {
+ name: "Display".to_string(),
+ weight: Some(400.0),
+ }],
+ };
+ let faces = [(face(400.0, false), variable)];
+ assert_eq!(choose_named_face(&faces, "Text"), Some(0));
+ assert_eq!(choose_named_face(&faces, "Display"), Some(0));
+ }
+
+ #[test]
+ fn loads_the_font_the_listing_takes_a_name_from() {
+ // An earlier variable font lists "Display" as an instance; a later font is named so.
+ let variable = FaceNames {
+ style: Some("Text".to_string()),
+ instances: vec![NamedInstance {
+ name: "Display".to_string(),
+ weight: Some(700.0),
+ }],
+ };
+ let faces = [
+ (face(400.0, false), variable),
+ (face(700.0, false), named("Display")),
+ ];
+ assert_eq!(choose_named_face(&faces, "Display"), Some(0));
+ }
+
+ #[test]
+ fn keeps_a_variable_face_s_default_when_no_instance_names_it() {
+ let variable = FaceNames {
+ style: Some("Text".to_string()),
+ instances: vec![NamedInstance {
+ name: "Display".to_string(),
+ weight: Some(400.0),
+ }],
+ };
+ let styles: Vec<String> = listed_faces(&face(400.0, false), &variable)
+ .into_iter()
+ .map(|listed| listed.style)
+ .collect();
+ assert_eq!(styles, ["Display", "Text"]);
+ }
+
+ #[test]
+ fn lists_a_variable_face_by_its_instances_and_a_static_one_by_its_name() {
+ let variable = FaceNames {
+ style: Some("Retina".to_string()),
+ instances: vec![NamedInstance {
+ name: "Retina".to_string(),
+ weight: Some(450.0),
+ }],
+ };
+ assert_eq!(
+ listed_faces(&face(400.0, false), &variable),
+ [ListedFace {
+ style: "Retina".to_string(),
+ weight: 450.0,
+ italic: false
+ }]
+ );
+ assert_eq!(
+ listed_faces(&face(350.0, false), &named("Book")),
+ [ListedFace {
+ style: "Book".to_string(),
+ weight: 350.0,
+ italic: false
+ }]
+ );
+ assert_eq!(
+ listed_faces(&face(700.0, true), &FaceNames::default()),
+ [ListedFace {
+ style: "Bold Italic".to_string(),
+ weight: 700.0,
+ italic: true
+ }]
+ );
+ }
}
diff --git a/desktop/src/fonts/mod.rs b/desktop/src/fonts/mod.rs
index fd324b9df..4815e2cf9 100644
--- a/desktop/src/fonts/mod.rs
+++ b/desktop/src/fonts/mod.rs
@@ -3,16 +3,18 @@
mod catalog;
#[cfg(target_os = "macos")]
mod macos;
+mod names;
mod sfnt;
mod style;
use serde::Serialize;
use std::sync::OnceLock;
+/// A family and its faces, each by the name its font gives it, with its weight and slant.
#[derive(Serialize, Clone)]
pub struct FontFamily {
family: String,
- styles: Vec<String>,
+ faces: Vec<catalog::ListedFace>,
}
static FONT_CACHE: OnceLock<Vec<FontFamily>> = OnceLock::new();
@@ -21,17 +23,7 @@ fn enumerate_system_fonts() -> Vec<FontFamily> {
let mut families: Vec<FontFamily> = catalog::families()
.into_iter()
.filter(|(_, faces)| !faces.is_empty())
- .map(|(family, faces)| {
- let mut styles: Vec<String> = Vec::new();
- for face in &faces {
- for name in style::face_styles(face.weight, face.italic, face.weight_axis) {
- if !styles.contains(&name) {
- styles.push(name);
- }
- }
- }
- FontFamily { family, styles }
- })
+ .map(|(family, faces)| FontFamily { family, faces })
.collect();
families.sort_by(|a, b| a.family.cmp(&b.family));
families
@@ -72,8 +64,7 @@ impl FontLoadError {
}
fn load_system_font_blocking(family: String, style: String) -> Result<Vec<u8>, FontLoadError> {
- let (weight, italic) = style::requested_face(&style);
- let Some(face) = catalog::load_face(&family, weight, italic) else {
+ let Some(face) = catalog::load_face(&family, &style) else {
#[cfg(target_os = "macos")]
if macos::family_has_only_unsupported_outlines(&family) {
return Err(FontLoadError::new(
diff --git a/desktop/src/fonts/names.rs b/desktop/src/fonts/names.rs
new file mode 100644
index 000000000..7a98fc383
--- /dev/null
+++ b/desktop/src/fonts/names.rs
@@ -0,0 +1,246 @@
+//! A face's own style names, read from its font file: the name Figma and the frontend find the
+//! face by ("Book", "Condensed Bold"), and for a variable font each named instance it draws.
+
+use read_fonts::tables::name::Name;
+use read_fonts::types::{NameId, Tag};
+use read_fonts::{FontRef, TableProvider};
+
+/// The Windows platform, whose English records fonts fill most reliably.
+const WINDOWS_PLATFORM: u16 = 3;
+/// US English, on the Windows platform.
+const ENGLISH: u16 = 0x0409;
+/// The Macintosh platform, and English on it.
+const MAC_PLATFORM: u16 = 1;
+const MAC_ENGLISH: u16 = 0;
+const WEIGHT_AXIS: Tag = Tag::new(b"wght");
+
+/// A named instance of a variable font, with the weight it is drawn at.
+#[derive(Clone, Debug, PartialEq)]
+pub struct NamedInstance {
+ pub name: String,
+ pub weight: Option<f32>,
+}
+
+/// A face's style name and, for a variable font, its named instances.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct FaceNames {
+ pub style: Option<String>,
+ pub instances: Vec<NamedInstance>,
+}
+
+/// The string a name record holds for `id`: the Windows English record first, then the others
+/// in their order, skipping any that is blank or cannot be read.
+fn name_string(name: &Name, id: NameId) -> Option<String> {
+ let data = name.string_data();
+ let mut records: Vec<_> = name
+ .name_record()
+ .iter()
+ .filter(|record| record.name_id() == id)
+ .collect();
+ // Windows English, then Mac English, then the rest, each in table order.
+ records.sort_by_key(
+ |record| match (record.platform_id(), record.language_id()) {
+ (WINDOWS_PLATFORM, ENGLISH) => 0,
+ (MAC_PLATFORM, MAC_ENGLISH) => 1,
+ _ => 2,
+ },
+ );
+ records.iter().find_map(|record| {
+ let text = record.string(data).ok()?.to_string();
+ let text = text.trim();
+ (!text.is_empty()).then(|| text.to_string())
+ })
+}
+
+/// The names of the face at `index` in `data`: its typographic subfamily (name ID 17), else its
+/// legacy subfamily (ID 2), which families of more than four faces leave at "Regular" or "Bold".
+pub fn face_names(data: &[u8], index: u32) -> FaceNames {
+ let Ok(font) = FontRef::from_index(data, index) else {
+ return FaceNames::default();
+ };
+ let Ok(name) = font.name() else {
+ return FaceNames::default();
+ };
+ let style = name_string(&name, NameId::TYPOGRAPHIC_SUBFAMILY_NAME)
+ .or_else(|| name_string(&name, NameId::SUBFAMILY_NAME));
+ let instances = font
+ .fvar()
+ .ok()
+ .and_then(|fvar| {
+ let weight_axis = fvar
+ .axes()
+ .ok()?
+ .iter()
+ .position(|axis| axis.axis_tag() == WEIGHT_AXIS);
+ let instances = fvar.instances().ok()?;
+ Some(
+ instances
+ .iter()
+ .filter_map(|instance| instance.ok())
+ .filter_map(|instance| {
+ Some(NamedInstance {
+ name: name_string(&name, instance.subfamily_name_id)?,
+ weight: weight_axis
+ .and_then(|axis| instance.coordinates.get(axis))
+ .map(|value| value.get().to_f32()),
+ })
+ })
+ .collect(),
+ )
+ })
+ .unwrap_or_default();
+ FaceNames { style, instances }
+}
+
+/// A name compared without case or spaces, so "Semi Bold" and "SemiBold" name one face.
+pub fn spelling(name: &str) -> String {
+ name.chars()
+ .filter(|c| !c.is_whitespace())
+ .flat_map(char::to_lowercase)
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use write_fonts::tables::fvar::{
+ AxisInstanceArrays, Fvar, InstanceRecord, VariationAxisRecord,
+ };
+ use write_fonts::tables::name::{Name, NameRecord};
+ use write_fonts::types::{Fixed, NameId as WriteNameId, Tag as WriteTag};
+ use write_fonts::{FontBuilder, OffsetMarker};
+
+ #[test]
+ fn compares_names_without_case_or_spaces() {
+ assert_eq!(spelling("Semi Bold"), spelling("SemiBold"));
+ assert_ne!(spelling("Book"), spelling("Roman"));
+ }
+
+ /// A name record: platform, encoding, language, name ID, and the string.
+ type Record<'a> = (u16, u16, u16, u16, &'a str);
+
+ const WINDOWS_ENGLISH: (u16, u16, u16) = (3, 1, 0x0409);
+ const MAC_ROMAN: (u16, u16, u16) = (1, 0, 0);
+
+ fn record(platform: (u16, u16, u16), id: u16, text: &str) -> Record<'_> {
+ (platform.0, platform.1, platform.2, id, text)
+ }
+
+ /// A font of only a name table and, when `instances` has any, an fvar table with a weight
+ /// axis and those instances, each by the name ID it is named under and its weight.
+ fn font(records: &[Record], instances: &[(u16, i32)]) -> Vec<u8> {
+ // A name table holds its records sorted, by platform, encoding, language, and ID.
+ let mut records = records.to_vec();
+ records.sort_by_key(|&(platform, encoding, language, id, _)| {
+ (platform, encoding, language, id)
+ });
+ let name = Name::new(
+ records
+ .iter()
+ .map(|&(platform, encoding, language, id, text)| {
+ NameRecord::new(
+ platform,
+ encoding,
+ language,
+ WriteNameId::new(id),
+ OffsetMarker::new(text.to_string()),
+ )
+ })
+ .collect(),
+ );
+ let mut builder = FontBuilder::new();
+ builder.add_table(&name).expect("name table");
+ if !instances.is_empty() {
+ let axis = VariationAxisRecord::new(
+ WriteTag::new(b"wght"),
+ Fixed::from_i32(100),
+ Fixed::from_i32(400),
+ Fixed::from_i32(900),
+ 0,
+ WriteNameId::new(255),
+ );
+ let instances = instances
+ .iter()
+ .map(|&(id, weight)| InstanceRecord {
+ subfamily_name_id: WriteNameId::new(id),
+ flags: 0,
+ coordinates: vec![Fixed::from_i32(weight)],
+ post_script_name_id: None,
+ })
+ .collect();
+ let fvar = Fvar::new(AxisInstanceArrays::new(vec![axis], instances));
+ builder.add_table(&fvar).expect("fvar table");
+ }
+ builder.build()
+ }
+
+ #[test]
+ fn reads_the_typographic_name_over_the_legacy_one() {
+ // A family of more than four faces leaves the legacy subfamily at "Regular".
+ let data = font(
+ &[
+ record(WINDOWS_ENGLISH, 2, "Regular"),
+ record(WINDOWS_ENGLISH, 17, "SemiBold"),
+ ],
+ &[],
+ );
+ assert_eq!(face_names(&data, 0).style.as_deref(), Some("SemiBold"));
+ let legacy = font(&[record(WINDOWS_ENGLISH, 2, "Bold")], &[]);
+ assert_eq!(face_names(&legacy, 0).style.as_deref(), Some("Bold"));
+ }
+
+ #[test]
+ fn reads_another_record_when_the_windows_english_one_is_blank() {
+ let data = font(
+ &[
+ record(WINDOWS_ENGLISH, 17, " "),
+ record(MAC_ROMAN, 17, "Book"),
+ ],
+ &[],
+ );
+ assert_eq!(face_names(&data, 0).style.as_deref(), Some("Book"));
+ }
+
+ #[test]
+ fn reads_the_mac_english_record_before_another_language() {
+ let data = font(
+ &[
+ record(WINDOWS_ENGLISH, 17, ""),
+ record((3, 1, 0x0407), 17, "Fett"),
+ record(MAC_ROMAN, 17, "Bold"),
+ ],
+ &[],
+ );
+ assert_eq!(face_names(&data, 0).style.as_deref(), Some("Bold"));
+ }
+
+ #[test]
+ fn reads_a_variable_font_s_instances_at_their_weights() {
+ let data = font(
+ &[
+ record(WINDOWS_ENGLISH, 17, "Regular"),
+ record(WINDOWS_ENGLISH, 256, "Bold"),
+ record(WINDOWS_ENGLISH, 257, "Retina"),
+ ],
+ &[(256, 700), (257, 450)],
+ );
+ assert_eq!(
+ face_names(&data, 0).instances,
+ [
+ NamedInstance {
+ name: "Bold".to_string(),
+ weight: Some(700.0)
+ },
+ NamedInstance {
+ name: "Retina".to_string(),
+ weight: Some(450.0)
+ },
+ ]
+ );
+ }
+
+ #[test]
+ fn reads_nothing_from_bytes_that_are_not_a_font() {
+ assert_eq!(face_names(b"not a font", 0), FaceNames::default());
+ }
+}
diff --git a/desktop/src/fonts/style.rs b/desktop/src/fonts/style.rs
index f4f096db4..53133130a 100644
--- a/desktop/src/fonts/style.rs
+++ b/desktop/src/fonts/style.rs
@@ -1,4 +1,6 @@
-//! Named font styles the frontend uses and the weights they stand for.
+//! The standard weight names, and how a requested style name maps to a weight and slant.
+
+use super::names::spelling;
/// Style names by the weight each stands for, lightest first.
const WEIGHT_STYLES: [(f32, &str); 9] = [
@@ -36,28 +38,26 @@ pub fn style_name(weight: f32, italic: bool) -> String {
}
}
-/// The named weight and slant a style name such as `SemiBold Italic` asks for.
+/// The named weight and slant a style name such as `SemiBold Italic` asks for, compared without
+/// case or spaces; a name that is not a weight asks for 400.
pub fn requested_face(style: &str) -> (f32, bool) {
- let italic = style.contains("Italic");
- let name = style.replace(" Italic", "").replace("Italic", "");
+ let spelled = spelling(style);
+ let italic = spelled.contains("italic");
+ let name = spelled.replace("italic", "");
let weight = WEIGHT_STYLES
.iter()
- .find(|(_, candidate)| *candidate == name)
+ .find(|(_, candidate)| spelling(candidate) == name)
.map_or(400.0, |(weight, _)| *weight);
(weight, italic)
}
-/// The styles a face can render: its own for a static face, and every named weight inside the
-/// `wght` axis for a variable one.
-pub fn face_styles(weight: f32, italic: bool, weight_axis: Option<(f32, f32)>) -> Vec<String> {
- match weight_axis {
- Some((min, max)) => WEIGHT_STYLES
- .iter()
- .filter(|(named, _)| (min..=max).contains(named))
- .map(|(named, _)| style_name(*named, italic))
- .collect(),
- None => vec![style_name(weight, italic)],
- }
+/// Whether `style` only names a weight and slant ("Bold Italic", "Semi Bold", "Italic"), so any
+/// face of that weight is it; "Book" or "Condensed Bold" names one face of its own.
+pub fn names_weight(style: &str) -> bool {
+ let (weight, italic) = requested_face(style);
+ let spelled = spelling(style);
+ spelled == spelling(&style_name(weight, italic))
+ || (italic && weight == 400.0 && spelled == "italic")
}
#[cfg(test)]
@@ -68,6 +68,7 @@ mod tests {
fn maps_style_names_to_weight_and_slant() {
assert_eq!(requested_face("Regular"), (400.0, false));
assert_eq!(requested_face("SemiBold Italic"), (600.0, true));
+ assert_eq!(requested_face("Semi Bold Italic"), (600.0, true));
assert_eq!(requested_face("Italic"), (400.0, true));
assert_eq!(requested_face("Unknown"), (400.0, false));
}
@@ -81,16 +82,25 @@ mod tests {
}
#[test]
- fn lists_every_named_weight_a_variable_face_covers() {
- assert_eq!(face_styles(510.0, false, None), ["Medium"]);
- assert_eq!(
- face_styles(400.0, true, Some((350.0, 700.0))),
- [
- "Regular Italic",
- "Medium Italic",
- "SemiBold Italic",
- "Bold Italic"
- ]
- );
+ fn tells_weight_names_from_names_of_their_own() {
+ for name in [
+ "Regular",
+ "Italic",
+ "Regular Italic",
+ "Semi Bold",
+ "ExtraBold Italic",
+ ] {
+ assert!(names_weight(name), "{name}");
+ }
+ for name in [
+ "Book",
+ "Roman",
+ "Condensed Bold",
+ "Retina",
+ "Oblique",
+ "Heavy",
+ ] {
+ assert!(!names_weight(name), "{name}");
+ }
}
}
diff --git a/packages/core/src/canvas/labels/paragraph-cache.ts b/packages/core/src/canvas/labels/paragraph-cache.ts
index d8021d170..66b0c54a8 100644
--- a/packages/core/src/canvas/labels/paragraph-cache.ts
+++ b/packages/core/src/canvas/labels/paragraph-cache.ts
@@ -26,7 +26,11 @@ export interface LabelFontOptions {
/** Semibold labels are section titles, drawn in their own face; the rest in Inter. */
function labelFontFamilies(weight: number): string[] {
- const families = resolveParagraphFontFamilies(DEFAULT_FONT_FAMILY, faceLoadKey(weight))
+ const families = resolveParagraphFontFamilies(DEFAULT_FONT_FAMILY, {
+ weight,
+ italic: false,
+ style: faceLoadKey(weight)
+ })
return weight >= 600 ? [SECTION_TITLE_FONT_FAMILY, ...families] : families
}
diff --git a/packages/core/src/canvas/text/decorations.ts b/packages/core/src/canvas/text/decorations.ts
index 37fc25e64..264275c2e 100644
--- a/packages/core/src/canvas/text/decorations.ts
+++ b/packages/core/src/canvas/text/decorations.ts
@@ -8,7 +8,7 @@ import type {
TextDecorationStyle
} from '@open-pencil/scene-graph'
import { resolveRGBAForPreview } from '@open-pencil/scene-graph/color'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
+import { faceStyleKey } from '@open-pencil/scene-graph/font-style'
import { outlineInk, savedGlyphInk, type InkSpan } from '#core/canvas/text/ink'
import { COMBINING_KEYCAP, drawKeycapFrame } from '#core/canvas/text/keycap'
@@ -166,8 +166,7 @@ function decorationRects(
lines: LineSpan[]
): TextDecorationRect[] {
const metrics =
- fontDecorationMetricsSync(style.fontFamily, faceLoadKey(style.fontWeight, style.italic)) ??
- UNLOADED_FONT_METRICS
+ fontDecorationMetricsSync(style.fontFamily, faceStyleKey(style)) ?? UNLOADED_FONT_METRICS
const size = style.fontSize
const underline = style.textDecoration === 'UNDERLINE'
// Figma measures from the baseline rounded to a whole pixel. An underline's offset and
diff --git a/packages/core/src/canvas/text/font-families.ts b/packages/core/src/canvas/text/font-families.ts
index 989141f9a..ef721f5cc 100644
--- a/packages/core/src/canvas/text/font-families.ts
+++ b/packages/core/src/canvas/text/font-families.ts
@@ -1,7 +1,7 @@
import { uniq } from 'es-toolkit/array'
import type { FontVariation } from '@open-pencil/scene-graph'
-import { parseFontStyle, faceLoadKey } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { ResourceCache } from '#core/cache/resource'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
@@ -18,6 +18,8 @@ export interface DrawnFontAxes {
family: string
weight: number
italic: boolean
+ /** The face's key, as {@link faceStyleKey} gives it; its weight's key when left out. */
+ style?: string
fontSize: number
/** The axes the text sets. */
variations: readonly FontVariation[]
@@ -30,8 +32,12 @@ export interface DrawnFontAxes {
* a stored `opsz` is ignored. Fonts without an axis ignore its value.
*/
export function drawnFontVariations(font: DrawnFontAxes): FontVariation[] {
+ // A face named apart from its weight ("Condensed Bold") is the instance of that name.
+ const weightKey = faceLoadKey(font.weight, font.italic)
const named =
- fontManager.namedInstanceVariations(font.family, faceLoadKey(font.weight, font.italic)) ?? []
+ fontManager.namedInstanceVariations(font.family, font.style ?? weightKey) ??
+ fontManager.namedInstanceVariations(font.family, weightKey) ??
+ []
const set = font.opticalSizeFromFontSize
? [
...font.variations.filter((variation) => variation.axis !== 'opsz'),
@@ -61,16 +67,28 @@ export function drawnFontAxes(font: DrawnFontAxes): DrawnFontAxis[] | null {
}))
}
+/** A loaded face text is drawn in: its weight and slant, and the key it is loaded under. */
+export interface LoadedFace extends FaceWeight {
+ style: string
+}
+
/**
- * The loaded face of a family that text asking for a style is drawn in: that style, or the
- * nearest loaded weight in the same slant, then the other, as font matching picks it; `null`
- * when the family has none loaded.
+ * The loaded face of a family that text asking for a face is drawn in: that face, by its key,
+ * or the nearest loaded weight in the same slant, then the other, as font matching picks it;
+ * `null` when the family has none loaded.
*/
-export function loadedFace(family: string, weight: number, italic: boolean): FaceWeight | null {
+export function loadedFace(
+ family: string,
+ weight: number,
+ italic: boolean,
+ style = faceLoadKey(weight, italic)
+): LoadedFace | null {
+ if (fontManager.isStyleLoaded(family, style)) return { weight, italic, style }
for (const slant of [italic, !italic]) {
for (const candidate of fontWeightMatchOrder(weight)) {
- if (fontManager.isStyleLoaded(family, faceLoadKey(candidate, slant)))
- return { weight: candidate, italic: slant }
+ const key = faceLoadKey(candidate, slant)
+ if (fontManager.isStyleLoaded(family, key))
+ return { weight: candidate, italic: slant, style: key }
}
}
return null
@@ -106,21 +124,17 @@ function renderFamilies(family: string, style: string): string[] {
/**
* The paragraph's families as CanvasKit is asked for them: the family in the face it draws the
- * style in, and its fallbacks, each by the names `renderFamilies` gives it.
+ * face in, and its fallbacks, each by the names `renderFamilies` gives it.
*/
export function resolveParagraphFontFamilies(
primary: string,
- style: string,
+ face: { weight: number; italic: boolean; style: string },
arabicFallbacks: readonly string[] = fontManager.getArabicFallbackFamilies(),
cjkFallbacks: readonly string[] = fontManager.getCJKFallbackFamilies()
): string[] {
- // The face the family draws the style in, which may be the nearest one loaded.
- const asked = parseFontStyle(style)
- const drawn = loadedFace(primary, asked.weight, asked.italic)
- const renderPrimary = renderFamilies(
- primary,
- drawn ? faceLoadKey(drawn.weight, drawn.italic) : style
- )
+ // The face the family draws it in, which may be the nearest one loaded.
+ const drawn = loadedFace(primary, face.weight, face.italic, face.style)
+ const renderPrimary = renderFamilies(primary, drawn?.style ?? face.style)
const renderArabicFallbacks = arabicFallbacks.flatMap((family) =>
renderFamilies(family, 'Regular')
)
diff --git a/packages/core/src/canvas/text/index.ts b/packages/core/src/canvas/text/index.ts
index 0979c3085..b4e8402bd 100644
--- a/packages/core/src/canvas/text/index.ts
+++ b/packages/core/src/canvas/text/index.ts
@@ -1,9 +1,9 @@
import type { SceneNode } from '@open-pencil/scene-graph'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import { shownCharacters, shownText } from '#core/text/case'
import { fontManager } from '#core/text/font/manager'
+import { textFontFace } from '#core/text/requirements/collect'
import {
fontCoverageDemand,
fontFaceDemand,
@@ -42,12 +42,9 @@ function requiredNodeFaces(node: SceneNode): Array<{ family: string; style: stri
const baseFamily = node.fontFamily || DEFAULT_FONT_FAMILY
const faces = new Map<string, { family: string; style: string }>()
const add = (family: string, style: string) => faces.set(`${family}\0${style}`, { family, style })
- add(baseFamily, faceLoadKey(node.fontWeight, node.italic))
+ add(baseFamily, textFontFace(node).style)
for (const run of node.styleRuns) {
- const family = run.style.fontFamily ?? baseFamily
- const weight = run.style.fontWeight ?? node.fontWeight
- const italic = run.style.italic ?? node.italic
- add(family, faceLoadKey(weight, italic))
+ add(run.style.fontFamily ?? baseFamily, textFontFace(node, run.style).style)
}
return Array.from(faces.values())
}
diff --git a/packages/core/src/canvas/text/layout/build.ts b/packages/core/src/canvas/text/layout/build.ts
index 09fa2bab8..33d939424 100644
--- a/packages/core/src/canvas/text/layout/build.ts
+++ b/packages/core/src/canvas/text/layout/build.ts
@@ -1,7 +1,7 @@
import type { Paragraph } from 'canvaskit-wasm'
import type { CharacterStyleOverride, StyleRun } from '@open-pencil/scene-graph'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
+import { rangeFontStyle } from '@open-pencil/scene-graph/shared-styles'
import {
hasParagraphSpacing,
hasTextList,
@@ -31,6 +31,7 @@ import { utf8Length } from '#core/canvas/text/utf8'
import { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'
import { shownText } from '#core/text/case'
import { glyphAdvanceSync } from '#core/text/font/glyphs'
+import { textFontFace } from '#core/text/requirements/collect'
/** A list item's indent per level, in ems of the list's first character. */
const LIST_INDENT_EMS = 1.5
@@ -153,6 +154,8 @@ interface ListStyle {
em: number
family: string
style: string
+ /** The name of the first character's face, which its markers are drawn in. */
+ faceName: string | null
/** The list's first character's style, which its markers take. */
override: CharacterStyleOverride | undefined
}
@@ -162,7 +165,8 @@ function listStyle(node: ParagraphNode, firstCharacter: number): ListStyle {
return {
em: override?.fontSize ?? (node.fontSize || DEFAULT_FONT_SIZE),
family: override?.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY),
- style: faceLoadKey(override?.fontWeight ?? node.fontWeight, override?.italic ?? node.italic),
+ style: textFontFace(node, override).style,
+ faceName: rangeFontStyle(node, override ?? {}),
override
}
}
@@ -178,6 +182,7 @@ function markerNode(node: ParagraphNode, item: TextListItem, style: ListStyle):
fontFamily: style.family,
fontWeight: override?.fontWeight ?? node.fontWeight,
italic: override?.italic ?? node.italic,
+ fontStyle: style.faceName,
letterSpacing: override?.letterSpacing ?? node.letterSpacing,
lineHeight: override?.lineHeight !== undefined ? override.lineHeight : node.lineHeight,
fontVariations: override?.fontVariations ?? node.fontVariations,
diff --git a/packages/core/src/canvas/text/paragraph/index.ts b/packages/core/src/canvas/text/paragraph/index.ts
index dc0471584..3885402d9 100644
--- a/packages/core/src/canvas/text/paragraph/index.ts
+++ b/packages/core/src/canvas/text/paragraph/index.ts
@@ -11,7 +11,8 @@ import type {
import type { SceneNode } from '@open-pencil/scene-graph'
import { resolveRGBAForPreview } from '@open-pencil/scene-graph/color'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
+import { faceStyleKey, type NamedFace } 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 { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/direction'
@@ -124,8 +125,14 @@ function blockHeightBehavior(
* native text stack draws the same, so a missing face is drawn as the face that exists and
* reported missing, as Figma does. A family with no face loaded asks for the style as given.
*/
-function drawnFontStyle(ck: CanvasKit, family: string, weight: number, italic: boolean): FontStyle {
- const face = loadedFace(family, weight, italic) ?? { weight, italic }
+function drawnFontStyle(
+ ck: CanvasKit,
+ family: string,
+ weight: number,
+ italic: boolean,
+ style: string
+): FontStyle {
+ const face = loadedFace(family, weight, italic, style) ?? { weight, italic }
return {
weight: { value: face.weight },
slant: face.italic ? ck.FontSlant.Italic : ck.FontSlant.Upright
@@ -158,7 +165,7 @@ function pushStyleRun(
run: SceneNode['styleRuns'][number],
baseColor: Float32Array,
baseFontSize: number,
- fontFamilies: (primary: string, weight: number, italic?: boolean) => string[],
+ fontFamilies: (primary: string, face: NamedFace) => string[],
halfLeading: boolean,
paintStyle?: ParagraphPaintStyle
): void {
@@ -173,18 +180,25 @@ function pushStyleRun(
const runFamily = style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)
const runWeight = style.fontWeight ?? node.fontWeight
const runItalic = style.italic ?? node.italic
+ const runFace = {
+ fontWeight: runWeight,
+ italic: runItalic,
+ fontStyle: rangeFontStyle(node, style)
+ }
+ const runKey = faceStyleKey(runFace)
const textStyle = new ck.TextStyle({
color: styleRunColor(ck, style, baseColor),
- fontFamilies: fontFamilies(runFamily, runWeight, runItalic),
+ fontFamilies: fontFamilies(runFamily, runFace),
fontSize: runFontSize,
locale: styleRunLanguage(style, node),
- fontStyle: drawnFontStyle(ck, runFamily, runWeight, runItalic),
+ fontStyle: drawnFontStyle(ck, runFamily, runWeight, runItalic, runKey),
fontVariations: textFontVariations(
drawnFontVariations({
family: runFamily,
weight: runWeight,
italic: runItalic,
+ style: runKey,
fontSize: runFontSize,
variations: style.fontVariations ?? node.fontVariations,
opticalSizeFromFontSize: style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize
@@ -214,7 +228,7 @@ function addStyledRuns(
node: ParagraphNode,
baseColor: Float32Array,
baseFontSize: number,
- fontFamilies: (primary: string, weight: number, italic?: boolean) => string[],
+ fontFamilies: (primary: string, face: NamedFace) => string[],
halfLeading: boolean,
paintStyle?: ParagraphPaintStyle
): void {
@@ -277,34 +291,33 @@ export function buildSkParagraph(
const truncateOpts = block.truncation ?? buildTruncateOpts(node)
- const fontFamilies = (primary: string, weight: number, italic = false) =>
+ const fontFamilies = (primary: string, face: NamedFace) =>
resolveParagraphFontFamilies(
primary,
- faceLoadKey(weight, italic),
+ { weight: face.fontWeight, italic: face.italic, style: faceStyleKey(face) },
arabicFallbacks,
cjkFallbacks
)
+ const nodeKey = faceStyleKey(node)
const baseTextStyle = {
color: baseColor,
- fontFamilies: fontFamilies(
- node.fontFamily || DEFAULT_FONT_FAMILY,
- node.fontWeight,
- node.italic
- ),
+ fontFamilies: fontFamilies(node.fontFamily || DEFAULT_FONT_FAMILY, node),
fontSize: baseFontSize,
locale: node.textLanguage ?? undefined,
fontStyle: drawnFontStyle(
ck,
node.fontFamily || DEFAULT_FONT_FAMILY,
node.fontWeight,
- node.italic
+ node.italic,
+ nodeKey
),
fontVariations: textFontVariations(
drawnFontVariations({
family: node.fontFamily || DEFAULT_FONT_FAMILY,
weight: node.fontWeight,
italic: node.italic,
+ style: nodeKey,
fontSize: baseFontSize,
variations: node.fontVariations,
opticalSizeFromFontSize: node.opticalSizeFromFontSize
diff --git a/packages/core/src/canvas/text/paragraph/inputs.ts b/packages/core/src/canvas/text/paragraph/inputs.ts
index f46ee418b..50a94be77 100644
--- a/packages/core/src/canvas/text/paragraph/inputs.ts
+++ b/packages/core/src/canvas/text/paragraph/inputs.ts
@@ -10,6 +10,7 @@ export const PARAGRAPH_INPUT_KEYS = [
'fontSize',
'fontWeight',
'italic',
+ 'fontStyle',
'styleRuns',
'fontVariations',
'opticalSizeFromFontSize',
diff --git a/packages/core/src/canvas/text/placed.ts b/packages/core/src/canvas/text/placed.ts
index 73959f561..d8842ae41 100644
--- a/packages/core/src/canvas/text/placed.ts
+++ b/packages/core/src/canvas/text/placed.ts
@@ -2,7 +2,6 @@ import type { Paragraph } from 'canvaskit-wasm'
import { uniq } from 'es-toolkit/array'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import {
drawnFontVariations,
@@ -20,6 +19,7 @@ import {
type GlyphOutlineSource
} from '#core/text/font/glyphs'
import { fontManager } from '#core/text/font/manager'
+import { textFontFace } from '#core/text/requirements/collect'
type GlyphRun = ReturnType<Paragraph['getShapedLines']>[number]['runs'][number]
@@ -40,10 +40,14 @@ export interface LaidOutGlyph {
source: GlyphOutlineSource | null
}
-/** The loaded face of a family the paragraph draws a style in, as its style name. */
-function loadedStyle(family: string, weight: number, italic: boolean): string | null {
- const face = loadedFace(family, weight, italic)
- return face ? faceLoadKey(face.weight, face.italic) : null
+/** The loaded face of a family the paragraph draws a face in, as its key. */
+function loadedStyle(
+ family: string,
+ weight: number,
+ italic: boolean,
+ style: string
+): string | null {
+ return loadedFace(family, weight, italic, style)?.style ?? null
}
/**
@@ -56,16 +60,17 @@ function fontAt(node: SceneNode, index: number) {
const family = run?.style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)
const weight = run?.style.fontWeight ?? node.fontWeight
const italic = run?.style.italic ?? node.italic
- const style = faceLoadKey(weight, italic)
+ const style = textFontFace(node, run?.style).style
const variations = drawnFontVariations({
family,
weight,
italic,
+ style,
fontSize: run?.style.fontSize ?? node.fontSize,
variations: run?.style.fontVariations ?? node.fontVariations,
opticalSizeFromFontSize: run?.style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize
})
- const drawn = loadedFace(family, weight, italic) ?? { weight, italic }
+ const drawn = loadedFace(family, weight, italic, style) ?? { weight, italic, style }
return { family, weight, italic, style, variations, drawn }
}
@@ -79,7 +84,7 @@ function sourceStyle(family: string, font: ReturnType<typeof fontAt>): string |
(fontManager.getArabicFallbackFamilies().includes(family) ||
fontManager.getCJKFallbackFamilies().includes(family))
if (scriptFallback) return fontManager.isStyleLoaded(family, 'Regular') ? 'Regular' : null
- return loadedStyle(family, font.drawn.weight, font.drawn.italic)
+ return loadedStyle(family, font.drawn.weight, font.drawn.italic, font.drawn.style)
}
/** The outline source of each font the paragraph may have drawn a character in, in its order. */
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index 11c538671..26822e51b 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -101,6 +101,9 @@ export function createEditor(options?: EditorOptions) {
if (event === 'settled') pendingTextLayout.relayoutReady(_renderer)
events.emit('font:resolution-changed', event, snapshot)
})
+ const stopFontLoadEvents = fontManager.onFaceLoaded((family, style) =>
+ events.emit('font:loaded', family, style)
+ )
void prefetchFigmaSchema()
@@ -404,6 +407,7 @@ export function createEditor(options?: EditorOptions) {
nodes.cancelNodePreviews()
interactiveEdits.clear()
stopFontResolutionEvents()
+ stopFontLoadEvents()
unsubscribeFromGraph()
}
diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.ts
index ee6020f76..7fdb30827 100644
--- a/packages/core/src/editor/text.ts
+++ b/packages/core/src/editor/text.ts
@@ -1,6 +1,6 @@
import type { SceneNode } from '@open-pencil/scene-graph'
import { copyDerivedGlyphs, copyGeometryPaths } from '@open-pencil/scene-graph/copy'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
+import { faceStyleKey } from '@open-pencil/scene-graph/font-style'
import {
cloneInstanceOverrideState,
setInstanceOverride,
@@ -36,7 +36,7 @@ import { createVariableBindingActions } from './variable-bindings'
*/
function isPathTextEditable(node: SceneNode): boolean {
if (!node.textPathData) return true
- return hasGlyphOutlines(node.fontFamily, faceLoadKey(node.fontWeight, node.italic))
+ return hasGlyphOutlines(node.fontFamily, faceStyleKey(node))
}
type PathTextEditSnapshot = Pick<
diff --git a/packages/core/src/editor/text/path-edit.ts b/packages/core/src/editor/text/path-edit.ts
index 4a583595b..a961420ee 100644
--- a/packages/core/src/editor/text/path-edit.ts
+++ b/packages/core/src/editor/text/path-edit.ts
@@ -2,8 +2,9 @@ import { mean } from 'es-toolkit'
import { encodePathCommandsBlob } from '@open-pencil/fig/node-change'
import type { DerivedTextGlyph, SceneNode, TextPathData } from '@open-pencil/scene-graph'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
+import { faceStyleKey } from '@open-pencil/scene-graph/font-style'
import type { Rect } from '@open-pencil/scene-graph/primitives'
+import { rangeFontStyle } from '@open-pencil/scene-graph/shared-styles'
import { textLengthPixels } from '@open-pencil/scene-graph/text'
import { getGlyphOutlineMetricsSync } from '#core/text/font/glyphs'
@@ -22,6 +23,7 @@ const PATH_TEXT_LAYOUT_FIELDS = [
'fontFamily',
'fontWeight',
'italic',
+ 'fontStyle',
'fontSize',
'letterSpacing',
'textAlignHorizontal'
@@ -44,7 +46,7 @@ function layOutPathText(
const letterSpacing = textLengthPixels(type.letterSpacing, fontSize)
const metrics = getGlyphOutlineMetricsSync(
type.fontFamily,
- faceLoadKey(type.fontWeight, type.italic),
+ faceStyleKey(type),
type.text,
fontSize
)
@@ -110,6 +112,8 @@ export function pathTextEditChanges(
fontFamily: changes.fontFamily ?? node.fontFamily,
fontWeight: changes.fontWeight ?? node.fontWeight,
italic: changes.italic ?? node.italic,
+ // A pending face change without a name names no face of the old one.
+ fontStyle: rangeFontStyle(node, changes),
fontSize: changes.fontSize ?? node.fontSize,
letterSpacing: changes.letterSpacing ?? node.letterSpacing,
textAlignHorizontal: changes.textAlignHorizontal ?? node.textAlignHorizontal
@@ -231,7 +235,7 @@ function alignedRun(
if (align !== 'CENTER' && align !== 'RIGHT') return all
const old = getGlyphOutlineMetricsSync(
node.fontFamily,
- faceLoadKey(node.fontWeight, node.italic),
+ faceStyleKey(node),
node.text,
node.fontSize
)
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index 55a2f3bd0..56fe8842b 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -226,6 +226,8 @@ export interface EditorEvents extends SceneGraphEvents {
'guides:changed': (ownerId: string, guides: readonly CanvasGuide[]) => void
'clipboard:images-missing': (resolution: ClipboardImageResolution) => void
'font:resolution-changed': (event: FontResolutionEvent, snapshot: FontResolutionSnapshot) => void
+ /** A font face finished loading, however it was asked for. */
+ 'font:loaded': (family: string, style: string) => void
'viewport:changed': (
viewport: { panX: number; panY: number; zoom: number },
previous: { panX: number; panY: number; zoom: number }
diff --git a/packages/core/src/figma-api/fonts/load.ts b/packages/core/src/figma-api/fonts/load.ts
index 81769db0c..924c8d2ab 100644
--- a/packages/core/src/figma-api/fonts/load.ts
+++ b/packages/core/src/figma-api/fonts/load.ts
@@ -1,53 +1,73 @@
import { uniq, uniqBy } from 'es-toolkit/array'
-import { faceLoadKey, parseFontStyle } from '@open-pencil/scene-graph/font-style'
+import { faceStyleKey, namesWeight, styleSpelling } from '@open-pencil/scene-graph/font-style'
import type { FigmaFontNameInput } from '#core/figma-api/fonts/names'
-import type { FaceWeight } from '#core/text/font/faces'
+import type { FamilyFace } from '#core/text/font/faces'
import { fontManager } from '#core/text/font/manager'
-
-/**
- * The style name text asks the font manager for, whichever way a script spells it ("Italic",
- * "Semi Bold"), so a font a script loaded is the one its text edits find loaded.
- */
-function textFaceStyle(style: string): string {
- const { weight, italic } = parseFontStyle(style)
- return faceLoadKey(weight, italic)
-}
+import { faceForStyle } from '#core/text/font/names'
+import { hasNamedInstance } from '#core/text/font/variation'
/** Figma's rejection for a font it cannot load. */
function fontLoadError(family: string, style: string): Error {
return new Error(`The font "${family} ${style}" could not be loaded`)
}
+/** The key a face loads under, as text set in it asks for it. */
+function faceKey(face: FamilyFace): string {
+ return faceStyleKey({ fontWeight: face.weight, italic: face.italic, fontStyle: face.style })
+}
+
+/**
+ * Whether the family has the face `style` names, as Figma requires of a font it loads: one of
+ * the faces its fonts list, or a named instance of the variable font loaded for it. A family
+ * whose faces are unknown has whatever face loaded.
+ */
+function familyHasFace(
+ family: string,
+ style: string,
+ key: string,
+ faces: readonly FamilyFace[] | null
+): boolean {
+ if (!faces) return true
+ if (faces.some((face) => styleSpelling(face.style) === styleSpelling(style))) return true
+ const data = fontManager.loadedData(family, key)
+ return data !== null && hasNamedInstance(data, style)
+}
+
/**
* Loads a font as Figma's `loadFontAsync` does, so text measures and draws with it from then on,
- * and rejects when it cannot load. A family named alone loads every style it has: one style of
- * each slant first, so the rest reuse its file where one variable file draws the whole slant, and
- * then the named styles a variable file draws, which text set by its axes alone takes.
+ * and rejects a face that cannot load or that the family does not have. A family named alone
+ * loads every face it has: one of each slant first, so the rest reuse its file where one
+ * variable file draws the whole slant, and then the named instances a variable file draws,
+ * which text set by its axes alone takes.
*/
export async function loadFigmaFont({ family, style }: FigmaFontNameInput): Promise<void> {
+ const faces = await fontManager.familyFaces(family).catch(() => null)
if (style !== undefined) {
- const face = textFaceStyle(style)
- await fontManager.loadFont(family, face).catch(() => null)
- if (!fontManager.isStyleLoaded(family, face)) throw fontLoadError(family, style)
+ const key = faceKey(faceForStyle(family, style))
+ await fontManager.loadFont(family, key).catch(() => null)
+ if (!fontManager.isStyleLoaded(family, key) || !familyHasFace(family, style, key, faces)) {
+ throw fontLoadError(family, style)
+ }
return
}
- const faces: FaceWeight[] = (await fontManager.familyFaces(family).catch(() => null)) ?? [
- { weight: 400, italic: false }
- ]
- const load = (face: string) => fontManager.loadFont(family, face).catch(() => null)
- const first = uniqBy(faces, (face) => face.italic)
- await Promise.all(first.map((face) => load(faceLoadKey(face.weight, face.italic))))
+ const listed = faces ?? [{ weight: 400, italic: false, style: 'Regular' }]
+ const load = (key: string) => fontManager.loadFont(family, key).catch(() => null)
+ const first = uniqBy(listed, (face) => face.italic)
+ await Promise.all(first.map((face) => load(faceKey(face))))
await Promise.all(
- faces
- .filter((face) => !first.includes(face))
- .map((face) => load(faceLoadKey(face.weight, face.italic)))
+ listed.filter((face) => !first.includes(face)).map((face) => load(faceKey(face)))
)
if (!fontManager.isLoaded(family)) throw fontLoadError(family, 'Regular')
const named = [false, true].flatMap((italic) =>
(fontManager.familyVariation(family, italic)?.instances ?? []).map((instance) =>
- faceLoadKey(parseFontStyle(instance.name).weight, italic)
+ faceStyleKey({
+ fontWeight: instance.variations.find(({ axis }) => axis === 'wght')?.value ?? 400,
+ italic,
+ // An instance that only names a weight is that weight in this file's slant.
+ fontStyle: namesWeight(instance.name) ? null : instance.name
+ })
)
)
await Promise.all(uniq(named).map(load))
diff --git a/packages/core/src/kiwi/fig/node-change/font/digests.ts b/packages/core/src/kiwi/fig/node-change/font/digests.ts
index c7da56540..d04088257 100644
--- a/packages/core/src/kiwi/fig/node-change/font/digests.ts
+++ b/packages/core/src/kiwi/fig/node-change/font/digests.ts
@@ -1,7 +1,7 @@
import type { SceneGraph } from '@open-pencil/scene-graph'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { fontManager } from '#core/text/font/manager'
+import { textFontFace } from '#core/text/requirements/collect'
const fontDigestCache = new Map<string, Uint8Array>()
@@ -29,13 +29,10 @@ function documentFontKeys(graph: SceneGraph): Set<string> {
const fontKeys = new Set<string>()
for (const node of graph.getAllNodes()) {
if (node.type !== 'TEXT') continue
- const baseStyle = faceLoadKey(node.fontWeight, node.italic)
- fontKeys.add(`${node.fontFamily}|${baseStyle}`)
+ fontKeys.add(`${node.fontFamily}|${textFontFace(node).style}`)
for (const run of node.styleRuns) {
const family = run.style.fontFamily ?? node.fontFamily
- const weight = run.style.fontWeight ?? node.fontWeight
- const italic = run.style.italic ?? node.italic
- fontKeys.add(`${family}|${faceLoadKey(weight, italic)}`)
+ fontKeys.add(`${family}|${textFontFace(node, run.style).style}`)
}
}
return fontKeys
diff --git a/packages/core/src/layout/text-measurement.ts b/packages/core/src/layout/text-measurement.ts
index 6d34fcfb5..8c3ebf172 100644
--- a/packages/core/src/layout/text-measurement.ts
+++ b/packages/core/src/layout/text-measurement.ts
@@ -1,5 +1,5 @@
import type { SceneNode } from '@open-pencil/scene-graph'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
+import { faceStyleKey } from '@open-pencil/scene-graph/font-style'
import { lineHeightPixels } from '@open-pencil/scene-graph/text'
import { measureTextWithFont } from '#core/text/font/glyphs'
@@ -19,7 +19,7 @@ export function estimateTextSize(
): { width: number; height: number } {
const fontSize = node.fontSize || 14
const family = node.fontFamily || 'Inter'
- const style = faceLoadKey(node.fontWeight || 400, node.italic)
+ const style = faceStyleKey({ ...node, fontWeight: node.fontWeight || 400 })
const text = node.text || ''
const ownLineH = lineHeightPixels(node.lineHeight, fontSize) ?? 0
diff --git a/packages/core/src/text/coverage.ts b/packages/core/src/text/coverage.ts
index 33fb5d8cc..d0581a6e1 100644
--- a/packages/core/src/text/coverage.ts
+++ b/packages/core/src/text/coverage.ts
@@ -1,5 +1,4 @@
import type { SceneNode } from '@open-pencil/scene-graph'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import {
@@ -13,6 +12,7 @@ import {
type FontFallbackScript
} from '#core/text/fallbacks'
import { fontGlyphCoverageSync } from '#core/text/font/glyphs'
+import { textFontFace } from '#core/text/requirements/collect'
const CJK_CHAR_RE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u
@@ -41,19 +41,15 @@ function styleForCharacter(
): { family: string; style: string; language: string | null } {
const baseFamily = node.fontFamily || DEFAULT_FONT_FAMILY
let family = baseFamily
- let weight = node.fontWeight
- let italic = node.italic
let language = node.textLanguage
const run = node.styleRuns.find((item) => index >= item.start && index < item.start + item.length)
if (run) {
family = run.style.fontFamily ?? family
- weight = run.style.fontWeight ?? weight
- italic = run.style.italic ?? italic
if (run.style.textLanguage !== undefined) language = run.style.textLanguage
}
- return { family, style: faceLoadKey(weight, italic), language }
+ return { family, style: textFontFace(node, run?.style).style, language }
}
/**
diff --git a/packages/core/src/text/editor.ts b/packages/core/src/text/editor.ts
index b7bf05d82..f82dcf6f4 100644
--- a/packages/core/src/text/editor.ts
+++ b/packages/core/src/text/editor.ts
@@ -1,7 +1,7 @@
import type { CanvasKit } from 'canvaskit-wasm'
import type { DerivedTextGlyph, SceneNode } from '@open-pencil/scene-graph'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
+import { faceStyleKey } from '@open-pencil/scene-graph/font-style'
import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/direction'
@@ -67,10 +67,7 @@ export class TextEditor {
private pathText(): { glyphs: DerivedTextGlyph[]; metrics: PathTextLineMetrics } | null {
const node = this.paragraphNode
if (!node?.textPathData || !node.derivedTextGlyphs?.length) return null
- const metrics = fontVerticalMetricsSync(
- node.fontFamily,
- faceLoadKey(node.fontWeight, node.italic)
- )
+ const metrics = fontVerticalMetricsSync(node.fontFamily, faceStyleKey(node))
return metrics ? { glyphs: node.derivedTextGlyphs, metrics } : null
}
diff --git a/packages/core/src/text/font/catalog.ts b/packages/core/src/text/font/catalog.ts
index 8e759a8df..677c8f98b 100644
--- a/packages/core/src/text/font/catalog.ts
+++ b/packages/core/src/text/font/catalog.ts
@@ -6,6 +6,12 @@ import {
} from '#core/text/font/faces'
import type { FontInfo } from '#core/text/font/sources'
+/** A family a desktop host has installed, with its faces by the names their fonts give them. */
+export interface HostFontFamily {
+ family: string
+ faces: readonly FamilyFace[]
+}
+
/** Where a family's faces come from besides the host's catalog. */
export interface FamilyFaceSources {
/** The browser's installed fonts, once listed. */
@@ -18,16 +24,16 @@ export interface FamilyFaceSources {
/** The faces each family has, as its installed, web, or bundled fonts list them. */
export class FamilyFaceCatalog {
- private hostStyles = new Map<string, readonly string[]>()
+ private hostFaces = new Map<string, readonly FamilyFace[]>()
private lookups = new Map<string, Promise<FamilyFace[] | null>>()
private found = new Map<string, FamilyFace[] | null>()
private listeners = new Set<() => void>()
constructor(private readonly sources: FamilyFaceSources) {}
- /** The system fonts a desktop host lists, by family, with the style names of their faces. */
- setHostCatalog(fonts: readonly { family: string; styles: readonly string[] }[]): void {
- this.hostStyles = new Map(fonts.map((font) => [font.family, [...font.styles]]))
+ /** The system fonts a desktop host lists, by family, with their faces. */
+ setHostCatalog(fonts: readonly HostFontFamily[]): void {
+ this.hostFaces = new Map(fonts.map((font) => [font.family, [...font.faces]]))
this.forget()
}
@@ -95,9 +101,8 @@ export class FamilyFaceCatalog {
/** The faces of an installed family, from the host's catalog or the browser's local fonts. */
private installedFaces(family: string): FamilyFace[] | null {
- // The desktop host lists weights by generated names, so its faces take the standard names.
- const host = this.hostStyles.get(family)
- if (host && host.length > 0) return standardFaces(host)
+ const host = this.hostFaces.get(family)
+ if (host && host.length > 0) return [...host]
const local = this.sources.localFonts()?.filter((font) => font.family === family) ?? []
return local.length > 0 ? facesFromStyles(local.map((font) => font.style)) : null
}
diff --git a/packages/core/src/text/font/manager.ts b/packages/core/src/text/font/manager.ts
index 631bdfe2b..9cdaa70f9 100644
--- a/packages/core/src/text/font/manager.ts
+++ b/packages/core/src/text/font/manager.ts
@@ -5,6 +5,7 @@ import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'
import type { FontVariation, SceneGraph } from '@open-pencil/scene-graph'
import {
faceLoadKey,
+ namesWeight,
normalizeFontFamily,
parseFontStyle,
styleToWeight
@@ -13,7 +14,7 @@ import {
import { DEFAULT_FONT_FAMILY, IS_BROWSER } from '#core/constants'
import { fontFallbackEntry, type FontFallbackScript } from '#core/text/fallbacks'
import { BundledFonts, type BundledFontLocator } from '#core/text/font/bundled'
-import { FamilyFaceCatalog } from '#core/text/font/catalog'
+import { FamilyFaceCatalog, type HostFontFamily } from '#core/text/font/catalog'
import { fontFaceRenderFamily, type FamilyFace } from '#core/text/font/faces'
import { loadHarfBuzz } from '#core/text/font/harfbuzz'
import { LocalFonts } from '#core/text/font/local'
@@ -30,6 +31,7 @@ import {
} from '#core/text/font/sources'
import {
fontAxes,
+ hasNamedInstance,
namedInstances,
namedInstanceVariations,
type FontAxis,
@@ -77,6 +79,7 @@ export class FontManager {
private hostFontLoader: HostFontLoader | null = null
private readonly hostFontRequests = new SharedReads()
private webFonts = new WebFontResolver()
+ private readonly faceListeners = new Set<(family: string, style: string) => void>()
private readonly bundled = new BundledFonts()
private readonly localFonts = new LocalFonts()
private readonly faces = new FamilyFaceCatalog({
@@ -170,7 +173,7 @@ export class FontManager {
}
/** The system fonts a desktop host lists, by family, with the style names of their faces. */
- setHostFontCatalog(fonts: readonly { family: string; styles: readonly string[] }[]): void {
+ setHostFontCatalog(fonts: readonly HostFontFamily[]): void {
this.faces.setHostCatalog(fonts)
}
@@ -343,6 +346,8 @@ export class FontManager {
const resolved = await this.webFonts.fetchFont(families, style, requestedCharacters, signal)
if (!resolved || resolved.buffers.length === 0) return null
const primary = resolved.buffers[0]
+ // Providers serve faces by weight; a named face comes only from a variable file that has it.
+ if (!namesWeight(style) && !hasNamedInstance(primary, style)) return null
await this.writeDownloadedFont(family, style, primary, requestedCharacters)
const registered = this.registerAndCache(family, style, primary, resolved.provider)
const loadedCoverage = this.remoteCoverage.get(`${family}|${style}`) ?? new Set<string>()
@@ -422,11 +427,14 @@ export class FontManager {
*/
private sharedVariableFace(family: string, style: string): ArrayBuffer | null {
const { weight, italic } = parseFontStyle(style)
+ // A face named apart from its weight ("Condensed Bold") is drawn by a file that has it.
+ const named = !namesWeight(style)
for (const [key, data] of this.loadedFamilies) {
if (!key.startsWith(`${family}|`)) continue
if (parseFontStyle(key.slice(family.length + 1)).italic !== italic) continue
+ if (named && !hasNamedInstance(data, style)) continue
const wght = fontAxes(data)?.find((axis) => axis.tag === 'wght')
- if (!wght || weight < wght.min || weight > wght.max) continue
+ if (!wght || (!named && (weight < wght.min || weight > wght.max))) continue
const coverage = this.remoteCoverage.get(key)
if (coverage) this.remoteCoverage.set(`${family}|${style}`, new Set(coverage))
return this.registerAndCache(family, style, data, this.loadedFamilySources.get(key))
@@ -789,9 +797,19 @@ export class FontManager {
if (source) this.loadedFamilySources.set(key, source)
this.registerFontInCanvasKit(family, buffer)
this.registerFontInBrowser(family, style, buffer)
+ for (const listener of this.faceListeners) listener(family, style)
return buffer
}
+ /**
+ * Calls the listener with each face once its file is registered, by whatever path it loaded:
+ * a paste, a script, a retry, or the renderer.
+ */
+ onFaceLoaded(listener: (family: string, style: string) => void): () => void {
+ this.faceListeners.add(listener)
+ return () => this.faceListeners.delete(listener)
+ }
+
private registerFontInCanvasKit(family: string, data: ArrayBuffer): boolean {
let registered = false
for (const provider of this.fontProviders) {
diff --git a/packages/core/src/text/font/names.ts b/packages/core/src/text/font/names.ts
index cf0163fc0..6a5c3c8f6 100644
--- a/packages/core/src/text/font/names.ts
+++ b/packages/core/src/text/font/names.ts
@@ -1,7 +1,11 @@
import { uniqBy } from 'es-toolkit/array'
import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
-import { parseFontStyle, standardStyleName } from '@open-pencil/scene-graph/font-style'
+import {
+ parseFontStyle,
+ standardStyleName,
+ styleSpelling
+} from '@open-pencil/scene-graph/font-style'
import { rangeFontStyle } from '@open-pencil/scene-graph/shared-styles'
import type { FamilyFace } from '#core/text/font/faces'
@@ -27,22 +31,38 @@ export function textStyleName(style: TextFace): string {
return style.fontStyle ?? faceStyleName(style.fontFamily, style.fontWeight, style.italic)
}
-/** A name compared without case or spaces, so "Semi Bold" and "SemiBold" name one face. */
-function spellingKey(style: string): string {
- return style.toLowerCase().replace(/\s+/gu, '')
+/**
+ * The named instance of that name in the family's loaded variable font, in either slant, as a
+ * face at its instance's weight ("Condensed Bold" at 700, "Retina" at 450).
+ */
+function instanceFace(family: string, style: string): FamilyFace | null {
+ for (const italic of [false, true]) {
+ const instance = fontManager
+ .familyVariation(family, italic)
+ ?.instances.find((candidate) => styleSpelling(candidate.name) === styleSpelling(style))
+ const weight = instance?.variations.find(({ axis }) => axis === 'wght')?.value
+ if (instance && weight !== undefined) return { weight, italic, style: instance.name }
+ }
+ return null
}
/**
* The face `style` names in the family, by the family's own name for it, where the family names
- * it alike but for case and spaces, as Inter 3's "Semi Bold" names Inter 4's "SemiBold". A name
- * the family's faces do not hold, or while they are unknown, stays as asked, with the weight and
+ * it alike but for case and spaces, as Inter 3's "Semi Bold" names Inter 4's "SemiBold"; else
+ * the named instance of that name in its loaded variable font. Of two faces of one name, as an
+ * upright and an italic file can both name an instance "Bold", the one in `italic`'s slant is
+ * it. A name neither holds, or while the family is unknown, stays as asked, with the weight and
* slant its words stand for.
*/
-export function faceForStyle(family: string, style: string): FamilyFace {
- const faces = fontManager.familyFacesSync(family) ?? []
+export function faceForStyle(family: string, style: string, italic?: boolean): FamilyFace {
+ const named = (fontManager.familyFacesSync(family) ?? []).filter(
+ (candidate) => styleSpelling(candidate.style) === styleSpelling(style)
+ )
const face =
- faces.find((candidate) => candidate.style === style) ??
- faces.find((candidate) => spellingKey(candidate.style) === spellingKey(style))
+ named.find((candidate) => candidate.italic === italic) ??
+ named.find((candidate) => candidate.style === style) ??
+ named.at(0) ??
+ instanceFace(family, style)
return face ?? { ...parseFontStyle(style), style }
}
diff --git a/packages/core/src/text/font/style.ts b/packages/core/src/text/font/style.ts
index 0009d05de..893fc8668 100644
--- a/packages/core/src/text/font/style.ts
+++ b/packages/core/src/text/font/style.ts
@@ -1,5 +1,6 @@
import {
FONT_WEIGHT_NAMES,
+ namesWeight,
normalizeFontFamily,
type FontFamilyStyle,
parseFontStyle
@@ -44,6 +45,8 @@ export function chooseLocalFontMatch<T extends FontFamilyStyle>(
? fonts.find((font) => font.family === candidateFamily && font.style === style)
: undefined
if (exact) return exact
+ // A face named apart from its weight is that face or none, never another of its weight.
+ if (style && !namesWeight(style)) continue
const candidates = fonts.filter((font) => font.family === candidateFamily)
const sameStyle = candidates.find((font) => {
diff --git a/packages/core/src/text/font/variation.ts b/packages/core/src/text/font/variation.ts
index 53f2d2eb0..e2ec0202a 100644
--- a/packages/core/src/text/font/variation.ts
+++ b/packages/core/src/text/font/variation.ts
@@ -1,5 +1,5 @@
import type { FontVariation } from '@open-pencil/scene-graph'
-import { styleToWeight } from '@open-pencil/scene-graph/font-style'
+import { styleSpelling, styleToWeight } from '@open-pencil/scene-graph/font-style'
interface TableRange {
offset: number
@@ -52,10 +52,6 @@ function fixed(view: DataView, offset: number): number {
return view.getInt32(offset) / 65536
}
-function normalizeStyleName(style: string): string {
- return style.toLowerCase().replace(/\s+/g, '')
-}
-
function fontName(view: DataView, name: TableRange, nameId: number): string | null {
const end = name.offset + name.length
if (name.length < NAME_HEADER_SIZE) return null
@@ -152,6 +148,13 @@ export interface NamedInstance {
variations: FontVariation[]
}
+/** Whether a variable font has a named instance of this name, spelled alike but for case and spaces. */
+export function hasNamedInstance(data: ArrayBuffer, style: string): boolean {
+ return namedInstances(data).some(
+ (instance) => styleSpelling(instance.name) === styleSpelling(style)
+ )
+}
+
/** A variable font's named instances, in its order. */
export function namedInstances(data: ArrayBuffer): NamedInstance[] {
const table = variationTable(data)
@@ -177,11 +180,11 @@ export function namedInstanceVariations(data: ArrayBuffer, style: string): FontV
const table = variationTable(data)
if (!table) return null
const { view, axes, instances, name } = table
- const requested = normalizeStyleName(style)
+ const requested = styleSpelling(style)
const instance = name
? instances.find((offset) => {
const instanceName = fontName(view, name, view.getUint16(offset))
- return instanceName !== null && normalizeStyleName(instanceName) === requested
+ return instanceName !== null && styleSpelling(instanceName) === requested
})
: undefined
if (instance !== undefined) {
diff --git a/packages/core/src/text/index.ts b/packages/core/src/text/index.ts
index c1884ac06..1e571a18a 100644
--- a/packages/core/src/text/index.ts
+++ b/packages/core/src/text/index.ts
@@ -17,6 +17,7 @@ export * from './web-font/resolver'
export * from './path'
export * from './prepare'
export * from './font/faces'
+export type { HostFontFamily } from './font/catalog'
export * from './font/names'
export {
probeGlyphOutlineCommands,
diff --git a/packages/core/src/text/outlines.ts b/packages/core/src/text/outlines.ts
index 901b77de1..5c3a7ebc0 100644
--- a/packages/core/src/text/outlines.ts
+++ b/packages/core/src/text/outlines.ts
@@ -1,7 +1,8 @@
import { prepareWithSegments, layoutWithLines } from '@chenglou/pretext'
import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
+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 {
@@ -39,7 +40,7 @@ const COMPLEX_SCRIPT_PATTERN = /[\u0590-\u08ff\u0900-\u0dff\ufb1d-\ufdff\ufe70-\
type TextStyle = Required<
Pick<
CharacterStyleOverride,
- 'fontFamily' | 'fontSize' | 'fontWeight' | 'italic' | 'letterSpacing'
+ 'fontFamily' | 'fontSize' | 'fontWeight' | 'italic' | 'fontStyle' | 'letterSpacing'
>
>
@@ -49,17 +50,14 @@ function baseTextStyle(node: SceneNode): TextStyle {
fontSize: node.fontSize,
fontWeight: node.fontWeight,
italic: node.italic,
+ fontStyle: node.fontStyle,
letterSpacing: node.letterSpacing
}
}
-function styleName(style: Pick<TextStyle, 'fontWeight' | 'italic'>): string {
- return faceLoadKey(style.fontWeight, style.italic)
-}
-
function styleKey(style: TextStyle): string {
const spacing = textLengthPixels(style.letterSpacing, style.fontSize)
- return `${style.fontFamily}|${styleName(style)}|${style.fontSize}|${spacing}`
+ return `${style.fontFamily}|${faceStyleKey(style)}|${style.fontSize}|${spacing}`
}
function textStyleAt(node: SceneNode, index: number): TextStyle {
@@ -71,17 +69,18 @@ function textStyleAt(node: SceneNode, index: number): TextStyle {
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
}
}
function resolvedGlyphStyle(style: TextStyle, char: string): TextStyle | null {
- if (fontHasGlyphSync(style.fontFamily, styleName(style), char)) return style
+ if (fontHasGlyphSync(style.fontFamily, faceStyleKey(style), char)) return style
const family = fallbackFamilies().find((candidate) => {
const next = fallbackStyle(style, candidate)
return (
- fontManager.loadedData(next.fontFamily, styleName(next)) &&
- fontHasGlyphSync(next.fontFamily, styleName(next), char)
+ fontManager.loadedData(next.fontFamily, faceStyleKey(next)) &&
+ fontHasGlyphSync(next.fontFamily, faceStyleKey(next), char)
)
})
return family ? fallbackStyle(style, family) : null
@@ -91,8 +90,9 @@ function fallbackFamilies(): string[] {
return [...fontManager.getCJKFallbackFamilies(), ...fontManager.getArabicFallbackFamilies()]
}
+/** `style` in a script fallback family, which has none of the text family's named faces. */
function fallbackStyle(style: TextStyle, family: string): TextStyle {
- return { ...style, fontFamily: family }
+ return { ...style, fontFamily: family, fontStyle: null }
}
function textStyles(node: SceneNode): TextStyle[] {
@@ -110,7 +110,7 @@ export function getTextOutlineSupport(node: SceneNode): TextOutlineSupport {
if (!node.text) return { supported: false, reason: 'empty-text' }
if (COMPLEX_SCRIPT_PATTERN.test(node.text)) return { supported: false, reason: 'complex-script' }
for (const style of textStyles(node)) {
- if (!fontManager.loadedData(style.fontFamily, styleName(style))) {
+ if (!fontManager.loadedData(style.fontFamily, faceStyleKey(style))) {
return { supported: false, reason: 'missing-font' }
}
}
@@ -148,7 +148,7 @@ function glyphAdvance(node: SceneNode, absoluteIndex: number): number | null {
if (!style) return null
const metrics = getGlyphOutlineMetricsSync(
style.fontFamily,
- styleName(style),
+ faceStyleKey(style),
char,
style.fontSize
)
@@ -257,7 +257,7 @@ function lineGlyphs(
const segment = line.text.slice(index, end)
const metrics = getGlyphOutlineMetricsSync(
style.fontFamily,
- styleName(style),
+ faceStyleKey(style),
segment,
style.fontSize
)
diff --git a/packages/core/src/text/requirements/collect.ts b/packages/core/src/text/requirements/collect.ts
index b422da9ef..b6136e0bc 100644
--- a/packages/core/src/text/requirements/collect.ts
+++ b/packages/core/src/text/requirements/collect.ts
@@ -1,20 +1,27 @@
import { uniqBy } from 'es-toolkit/array'
import type { CharacterStyleOverride, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
+import { faceStyleKey } from '@open-pencil/scene-graph/font-style'
+import { rangeFontStyle } from '@open-pencil/scene-graph/shared-styles'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import { shownCharacters } from '#core/text/case'
import { fontFallbackScriptForCharacter, type FontFallbackScript } from '#core/text/fallbacks'
import type { FontFaceRef } from '#core/text/font/faces'
-/** The face a text draws in, or the face a style run over it draws in. */
-export function textFontFace(node: SceneNode, style: CharacterStyleOverride = {}): FontFaceRef {
+/**
+ * The face a text draws in, or the face a style run over it draws in, keyed as it loads: by its
+ * weight, or by its own name where the weight cannot pick it.
+ */
+export function textFontFace(
+ node: Pick<SceneNode, 'fontFamily' | 'fontWeight' | 'italic' | 'fontStyle'>,
+ style: CharacterStyleOverride = {}
+): FontFaceRef {
const weight = style.fontWeight ?? (node.fontWeight || 400)
const italic = style.italic ?? node.italic
return {
family: style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY),
- style: faceLoadKey(weight, italic),
+ style: faceStyleKey({ fontWeight: weight, italic, fontStyle: rangeFontStyle(node, style) }),
weight,
italic
}
diff --git a/packages/core/tests/canvas/text/faces.test.ts b/packages/core/tests/canvas/text/faces.test.ts
index aa4e752b8..f22e958ef 100644
--- a/packages/core/tests/canvas/text/faces.test.ts
+++ b/packages/core/tests/canvas/text/faces.test.ts
@@ -119,6 +119,25 @@ describe('text faces', () => {
expect(drawn(ck, fontProvider, { fontWeight: 700, italic: false })).not.toEqual(regular)
})
+ test('draws a face named apart from its weight as the named instance of that name', async () => {
+ const ck = await getCanvasKit()
+ const fontProvider = ck.TypefaceFontProvider.Make()
+ fontManager.attachProvider(ck, fontProvider)
+ // Inter with an extra instance, "Display Heavy" at wght 850, as Roboto has "Condensed Bold".
+ const fontFamily = 'Faces Test Named'
+ await fontManager.markLoaded(fontFamily, 'Regular', await fixtureFont('InterVariable-Named.ttf'))
+ expect(await fontManager.loadFont(fontFamily, 'Display Heavy')).not.toBeNull()
+ // A name the font has no instance of is not drawn by some other instance.
+ expect(await fontManager.loadFont(fontFamily, 'Condensed Bold')).toBeNull()
+ const face = (fields: Partial<SceneNode>) =>
+ drawn(ck, fontProvider, { fontFamily, fontWeight: 400, italic: false, ...fields })
+ const named = face({ fontWeight: 850, fontStyle: 'Display Heavy' })
+ expect(named).toEqual(face({ fontVariations: [{ axis: 'wght', value: 850 }] }))
+ expect(named).not.toEqual(face({}))
+ // Its weight alone picks the instance its weight is nearest, Black at 900, not this face.
+ expect(named).not.toEqual(face({ fontWeight: 850 }))
+ })
+
test('draws optical size at the font size unless the text detaches it, as Figma does', async () => {
const ck = await getCanvasKit()
const fontProvider = ck.TypefaceFontProvider.Make()
diff --git a/packages/core/tests/editor/text/fonts.test.ts b/packages/core/tests/editor/text/fonts.test.ts
new file mode 100644
index 000000000..2d5792263
--- /dev/null
+++ b/packages/core/tests/editor/text/fonts.test.ts
@@ -0,0 +1,20 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core'
+import { fontManager } from '@open-pencil/core/text'
+
+test('tells listeners each face that loads, however it was asked for', async () => {
+ const editor = createEditor()
+ const loaded: string[] = []
+ editor.onEditorEvent('font:loaded', (family, style) => loaded.push(`${family} ${style}`))
+ try {
+ // As a paste or a script loads a face, past the renderer's font resolver.
+ await fontManager.markLoaded('Font Events Sans', 'Bold', new ArrayBuffer(8))
+ expect(loaded).toEqual(['Font Events Sans Bold'])
+ } finally {
+ editor.dispose()
+ }
+ // A disposed editor no longer hears of loads.
+ await fontManager.markLoaded('Font Events Sans', 'Light', new ArrayBuffer(8))
+ expect(loaded).toEqual(['Font Events Sans Bold'])
+})
diff --git a/packages/core/tests/figma-api/accessors/basic/resize/limits.test.ts b/packages/core/tests/figma-api/accessors/basic/resize/limits.test.ts
index a82d1ebd9..008038560 100644
--- a/packages/core/tests/figma-api/accessors/basic/resize/limits.test.ts
+++ b/packages/core/tests/figma-api/accessors/basic/resize/limits.test.ts
@@ -1,9 +1,14 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { registerTestFont } from '#core-tests/helpers/figma-api'
import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
import { hasInstanceOverride } from '@open-pencil/scene-graph/instances'
+// Text edits need the text's font loaded, as in Figma; this file must not rely on another's.
+beforeAll(() => registerTestFont())
+
// Recorded in Figma desktop 126 (2026-10-27).
const size = (node: FigmaNodeProxy) => [node.width, node.height]
diff --git a/packages/core/tests/figma-api/fonts/load.test.ts b/packages/core/tests/figma-api/fonts/load.test.ts
index c94b5ab7d..d3d414b34 100644
--- a/packages/core/tests/figma-api/fonts/load.test.ts
+++ b/packages/core/tests/figma-api/fonts/load.test.ts
@@ -1,6 +1,8 @@
import { beforeAll, expect, test } from 'bun:test'
+import { join } from 'node:path'
-import { registerTestFont } from '#core-tests/helpers/figma-api'
+import { asTextNode, registerTestFont } from '#core-tests/helpers/figma-api'
+import { FIXTURES } from '#core-tests/helpers/paths'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { fontManager } from '@open-pencil/core/text'
@@ -31,3 +33,59 @@ test('figma.loadFontAsync rejects a font that cannot load, as Figma does', async
'The font "Missing Regular" could not be loaded'
)
})
+
+test('figma.loadFontAsync rejects a style the family has no face of, as Figma does', async () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ // Bundled Inter lists its faces; a name none of them has is not some other face of it.
+ await expect(figma.loadFontAsync({ family: 'Inter', style: 'Condensed Bold' })).rejects.toThrow(
+ 'The font "Inter Condensed Bold" could not be loaded'
+ )
+ await expect(figma.loadFontAsync({ family: 'Inter', style: 'Bogus' })).rejects.toThrow(
+ 'The font "Inter Bogus" could not be loaded'
+ )
+})
+
+test('figma.loadFontAsync loads a named instance by its name, at its weight', async () => {
+ const family = 'Load Named'
+ const data = await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Named.ttf')).arrayBuffer()
+ await fontManager.markLoaded(family, 'Regular', data)
+ const figma = new FigmaAPI(new SceneGraph())
+ await figma.loadFontAsync({ family, style: 'Display Heavy' })
+ expect(fontManager.isStyleLoaded(family, 'Display Heavy')).toBe(true)
+ const text = asTextNode(figma.createText())
+ text.fontName = { family, style: 'Display Heavy' }
+ expect(text.fontName).toMatchObject({ family, style: 'Display Heavy' })
+ expect(text.fontWeight).toBe(850)
+})
+
+test('figma.loadFontAsync loads an installed face by the name its font gives it', async () => {
+ const family = 'Load Installed'
+ const book = await Bun.file(join(FIXTURES, 'fonts', 'InterRegular-Faces.ttf')).arrayBuffer()
+ fontManager.setHostFontCatalog([
+ {
+ family,
+ faces: [
+ { style: 'Book', weight: 350, italic: false },
+ { style: 'Roman', weight: 400, italic: false }
+ ]
+ }
+ ])
+ fontManager.setHostFontLoader(async (requested, style) =>
+ requested === family && style === 'Book' ? book.slice(0) : null
+ )
+ try {
+ const figma = new FigmaAPI(new SceneGraph())
+ await figma.loadFontAsync({ family, style: 'Book' })
+ expect(fontManager.isStyleLoaded(family, 'Book')).toBe(true)
+ const text = asTextNode(figma.createText())
+ text.fontName = { family, style: 'Book' }
+ expect(text.fontWeight).toBe(350)
+ // Roman, its other face of about that weight, is a face of its own the host did not give.
+ await expect(figma.loadFontAsync({ family, style: 'Roman' })).rejects.toThrow(
+ `The font "${family} Roman" could not be loaded`
+ )
+ } finally {
+ fontManager.setHostFontLoader(null)
+ fontManager.setHostFontCatalog([])
+ }
+})
diff --git a/packages/core/tests/figma-api/fonts/variations.test.ts b/packages/core/tests/figma-api/fonts/variations.test.ts
index f03605a28..c49ce3883 100644
--- a/packages/core/tests/figma-api/fonts/variations.test.ts
+++ b/packages/core/tests/figma-api/fonts/variations.test.ts
@@ -4,7 +4,7 @@ import { join } from 'node:path'
import { FIXTURES } from '#core-tests/helpers/paths'
import { FigmaAPI } from '@open-pencil/core/figma-api'
-import { fontManager } from '@open-pencil/core/text'
+import { facesFromStyles, fontManager } from '@open-pencil/core/text'
import { SceneGraph } from '@open-pencil/scene-graph'
// Behaviour measured in live Figma (2026-10-25) with its variable Inter and Roboto Flex. These
@@ -152,7 +152,10 @@ describe('variable fonts in the plugin API', () => {
const providers = fontManager.enabledOnlineFontProviders()
fontManager.setOnlineFontProviders({})
fontManager.setHostFontCatalog([
- { family: 'Variations Load', styles: ['Regular', 'Bold', 'Regular Italic', 'Bold Italic'] }
+ {
+ family: 'Variations Load',
+ faces: facesFromStyles(['Regular', 'Bold', 'Regular Italic', 'Bold Italic'])
+ }
])
const data = await Bun.file(join(FIXTURES, 'fonts', 'InterRegular-Faces.ttf')).arrayBuffer()
fontManager.setHostFontLoader(async (family, style) => {
diff --git a/packages/core/tests/figma-api/render-bounds.test.ts b/packages/core/tests/figma-api/render-bounds.test.ts
index 984962ea6..675f32859 100644
--- a/packages/core/tests/figma-api/render-bounds.test.ts
+++ b/packages/core/tests/figma-api/render-bounds.test.ts
@@ -1,10 +1,13 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
-import { solidFill } from '#core-tests/helpers/figma-api'
+import { registerTestFont, solidFill } from '#core-tests/helpers/figma-api'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
+// Text edits need the text's font loaded, as in Figma; this file must not rely on another's.
+beforeAll(() => registerTestFont())
+
describe('absoluteRenderBounds', () => {
test('absoluteRenderBounds includes strokes and effects and returns null for invisible pixels', () => {
const api = new FigmaAPI(new SceneGraph())
diff --git a/packages/core/tests/text/font/manager.test.ts b/packages/core/tests/text/font/manager.test.ts
index c7d82368e..e62be1011 100644
--- a/packages/core/tests/text/font/manager.test.ts
+++ b/packages/core/tests/text/font/manager.test.ts
@@ -5,7 +5,7 @@ import { FIXTURES } from '#core-tests/helpers/paths'
import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'
-import { FontManager } from '@open-pencil/core/text'
+import { FontManager, facesFromStyles } from '@open-pencil/core/text'
/** A font manager that asks no web provider, so a family's faces come from its catalog. */
function offlineManager() {
@@ -28,7 +28,7 @@ function countingProvider() {
test('a face lookup that outlives a new catalog does not overwrite what the catalog says', async () => {
const manager = offlineManager()
const before = manager.familyFaces('Oswald')
- manager.setHostFontCatalog([{ family: 'Oswald', styles: ['Regular', 'Bold'] }])
+ manager.setHostFontCatalog([{ family: 'Oswald', faces: facesFromStyles(['Regular', 'Bold']) }])
expect(await before).toBeNull()
expect(manager.loadedFamilyFaces('Oswald')).toBeUndefined()
expect(await manager.familyFaces('Oswald')).toEqual([
@@ -37,14 +37,16 @@ test('a face lookup that outlives a new catalog does not overwrite what the cata
])
})
-test('names faces as each source can: local fonts by their own names, the rest as Google does', async () => {
+test('names faces as each source does: installed fonts by their own names, the rest as Google does', async () => {
const manager = offlineManager()
- // The desktop catalog lists generated names, so its italic takes the standard "Italic".
- manager.setHostFontCatalog([{ family: 'Host Sans', styles: ['Regular Italic', 'SemiBold'] }])
- expect(await manager.familyFaces('Host Sans')).toEqual([
- { weight: 400, italic: true, style: 'Italic' },
- { weight: 600, italic: false, style: 'SemiBold' }
- ])
+ // The desktop catalog reads each face's name and weight from its font file.
+ const avenir = [
+ { style: 'Book', weight: 350, italic: false },
+ { style: 'Roman', weight: 400, italic: false },
+ { style: 'Oblique', weight: 400, italic: true }
+ ]
+ manager.setHostFontCatalog([{ family: 'Avenir', faces: avenir }])
+ expect(await manager.familyFaces('Avenir')).toEqual(avenir)
// Bundled Inter names its instances as Google Fonts does.
expect(await manager.familyFaces('Inter')).toContainEqual({
weight: 400,
@@ -57,7 +59,7 @@ test('a new catalog tells listeners to ask for their families again', () => {
const manager = offlineManager()
let resets = 0
const stop = manager.onFamilyFacesReset(() => resets++)
- manager.setHostFontCatalog([{ family: 'Oswald', styles: ['Regular'] }])
+ manager.setHostFontCatalog([{ family: 'Oswald', faces: facesFromStyles(['Regular']) }])
stop()
manager.setHostFontCatalog([])
expect(resets).toBe(1)
diff --git a/packages/core/tests/text/font/names.test.ts b/packages/core/tests/text/font/names.test.ts
index 8a8c0ff2c..b39637e14 100644
--- a/packages/core/tests/text/font/names.test.ts
+++ b/packages/core/tests/text/font/names.test.ts
@@ -70,3 +70,22 @@ test('a range in a new weight takes no name, and a new weight for all of it clea
editor.dispose()
}
})
+
+test('of two faces of one name, finds the one in the slant asked for', () => {
+ // An upright and an italic variable file can each name an instance "Bold".
+ fontManager.setHostFontCatalog([
+ {
+ family: 'Two Slants',
+ faces: [
+ { style: 'Bold', weight: 700, italic: false },
+ { style: 'Bold', weight: 700, italic: true }
+ ]
+ }
+ ])
+ try {
+ expect(faceForStyle('Two Slants', 'Bold', true)).toMatchObject({ italic: true })
+ expect(faceForStyle('Two Slants', 'Bold', false)).toMatchObject({ italic: false })
+ } finally {
+ fontManager.setHostFontCatalog([])
+ }
+})
diff --git a/packages/core/tests/text/font/style.test.ts b/packages/core/tests/text/font/style.test.ts
index a287f2ed9..0b630693d 100644
--- a/packages/core/tests/text/font/style.test.ts
+++ b/packages/core/tests/text/font/style.test.ts
@@ -19,6 +19,19 @@ describe('chooseLocalFontMatch', () => {
expect(chooseLocalFontMatch(fonts, 'Inter', 'Bold')).toBeUndefined()
})
+ test('finds a face named apart from its weight by that name, never another face of its weight', () => {
+ const helvetica = [
+ { family: 'Helvetica Neue', style: 'Regular' },
+ { family: 'Helvetica Neue', style: 'Bold' },
+ { family: 'Helvetica Neue', style: 'Condensed Bold' }
+ ]
+ expect(chooseLocalFontMatch(helvetica, 'Helvetica Neue', 'Condensed Bold')?.style).toBe(
+ 'Condensed Bold'
+ )
+ expect(chooseLocalFontMatch(helvetica, 'Helvetica Neue', 'Condensed Black')).toBeUndefined()
+ expect(chooseLocalFontMatch(helvetica, 'Helvetica Neue', 'Book')).toBeUndefined()
+ })
+
test('without a style, takes the face CSS font matching picks for regular', () => {
const faces = [
{ family: 'Inter', style: 'Black' },
diff --git a/packages/core/tests/tools/modify/update.test.ts b/packages/core/tests/tools/modify/update.test.ts
index a8c71a970..8803946b0 100644
--- a/packages/core/tests/tools/modify/update.test.ts
+++ b/packages/core/tests/tools/modify/update.test.ts
@@ -1,10 +1,15 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { registerTestFont } from '#core-tests/helpers/figma-api'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
import { updateNode } from '#core/tools/modify/update'
+// Text edits need the text's font loaded, as in Figma; this file must not rely on another's.
+beforeAll(() => registerTestFont())
+
describe('update_node', () => {
test('does not report a size it could not set on a layer inside an instance', async () => {
const figma = new FigmaAPI(new SceneGraph())
diff --git a/packages/docs/programmable/sdk/api/composables/use-typography.md b/packages/docs/programmable/sdk/api/composables/use-typography.md
index acd421474..873f02085 100644
--- a/packages/docs/programmable/sdk/api/composables/use-typography.md
+++ b/packages/docs/programmable/sdk/api/composables/use-typography.md
@@ -12,7 +12,7 @@ of them in one undo step, so a selection of text and other layers edits only the
It exposes:
- font family
-- font weight, and `weights`: the weights the selected layers' families have, read from installed fonts and web font providers, every weight while a family's faces are unknown
+- font style: `faces`, the faces of the selected layers' family by the names their fonts give them (Avenir's Book and Roman apart), read from installed fonts and web font providers, every standard weight while a family's faces are unknown; `faceName`, the face the layers share or `MIXED`; and `setFace(style)`, which sets a face by its name
- font size
- formatting state
- missing-font status
@@ -22,7 +22,7 @@ It exposes:
- OpenType feature toggles
- variable font axes (`axes`, `opticalSizeAuto`)
- list style (`listType`, `null` when the paragraphs differ) and hanging lists
-- helpers for changing family, weight, alignment, and decorations
+- helpers for changing family, face, weight, alignment, and decorations
- `merged(key)` and `fontFeature(tag)`, which return the shared value or `MIXED`
## Usage
@@ -42,6 +42,7 @@ const {
fontSize,
activeFormatting,
setFamily,
+ setFace,
setWeight,
setAlign,
setVerticalAlign,
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index f32d928a6..0da1db9a9 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -7,7 +7,6 @@ import {
DEFAULT_STROKE_WEIGHT
} from '@open-pencil/scene-graph/constants'
import { getNodeLocalMatrix } from '@open-pencil/scene-graph/coordinate'
-import { styleToWeight } from '@open-pencil/scene-graph/font-style'
import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'
import { OPEN_PENCIL_PLUGIN_DATA } from '@open-pencil/scene-graph/plugin-data'
import { POINT_COUNT_RANGE } from '@open-pencil/scene-graph/polygon'
@@ -91,6 +90,7 @@ import type {
} from '@open-pencil/scene-graph'
import type { Vector, GUID } from '@open-pencil/scene-graph/primitives'
+import { savedFace } from './font/style'
import { numericVariableAssignmentScales, sourceVariableBindingScales } from './variable/bindings'
export { VARIABLE_BINDING_FIELDS, VARIABLE_BINDING_FIELDS_INVERSE } from './variable/bindings'
@@ -454,12 +454,13 @@ function convertShapeWithTextProps(
}
function convertTextProps(nc: NodeChange, blobs: Uint8Array[]): TextProps {
+ const face = nc.fontName ? savedFace(nc, nc.fontName) : { fontWeight: 400, italic: false }
return {
text: nc.textData?.characters ?? '',
fontSize: nc.fontSize ?? 14,
fontFamily: nc.fontName?.family ?? DEFAULT_FONT_FAMILY,
- fontWeight: styleToWeight(nc.fontName?.style ?? ''),
- italic: nc.fontName?.style.toLowerCase().includes('italic') ?? false,
+ fontWeight: face.fontWeight,
+ italic: face.italic,
// Figma finds the face by this exact name, which the weight and slant cannot always name.
fontStyle: nc.fontName?.style || null,
textAlignHorizontal: (nc.textAlignHorizontal ?? 'LEFT') as
diff --git a/packages/fig/src/node-change/derived-text/build.ts b/packages/fig/src/node-change/derived-text/build.ts
index ed15c4b44..1532b78d9 100644
--- a/packages/fig/src/node-change/derived-text/build.ts
+++ b/packages/fig/src/node-change/derived-text/build.ts
@@ -2,7 +2,8 @@ import { groupBy } from 'es-toolkit/array'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import type { CharacterStyleOverride, DerivedTextGlyph, SceneNode } from '@open-pencil/scene-graph'
-import { normalizeFontFamily, faceLoadKey } from '@open-pencil/scene-graph/font-style'
+import { faceStyleKey, normalizeFontFamily } from '@open-pencil/scene-graph/font-style'
+import { rangeFontStyle } from '@open-pencil/scene-graph/shared-styles'
import {
hasTextList,
lineHeightPixels,
@@ -88,7 +89,9 @@ function fontMetaData(
fonts.push({
key: { family: normalized, style: name, postscript: '' },
fontLineHeight: 1.2,
- fontDigest: digestMap.get(`${normalized}|${faceLoadKey(weight, italic)}`),
+ fontDigest: digestMap.get(
+ `${normalized}|${faceStyleKey({ fontWeight: weight, italic, fontStyle: rangeFontStyle(node, style) })}`
+ ),
fontStyle: italic ? 'ITALIC' : 'NORMAL',
fontWeight: weight
})
diff --git a/packages/fig/src/node-change/font/style.ts b/packages/fig/src/node-change/font/style.ts
index fe5a34feb..fd277ca74 100644
--- a/packages/fig/src/node-change/font/style.ts
+++ b/packages/fig/src/node-change/font/style.ts
@@ -1,5 +1,10 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
-import { normalizeFontFamily, standardStyleName } from '@open-pencil/scene-graph/font-style'
+import {
+ normalizeFontFamily,
+ parseFontStyle,
+ standardStyleName
+} from '@open-pencil/scene-graph/font-style'
import { rangeFontStyle } from '@open-pencil/scene-graph/shared-styles'
/** The name a family's font gives its face at a weight and slant. */
@@ -40,3 +45,22 @@ export function figmaStyleName(
own ?? nameFace(family, style.fontWeight ?? node.fontWeight, style.italic ?? node.italic)
return FIGMA_STYLE_NAMES[normalizeFontFamily(family)]?.[name] ?? name
}
+
+/**
+ * The weight and slant of the face `fontName` names in `text`, as Figma saved them beside its
+ * glyphs (Avenir Book 350, Fira Code Retina 450, Roboto Condensed Bold 700); the name's own
+ * words where the file saved no glyphs.
+ */
+export function savedFace(
+ text: NodeChange,
+ fontName: { family: string; style: string }
+): { fontWeight: number; italic: boolean } {
+ const meta = text.derivedTextData?.fontMetaData?.find(
+ ({ key }) => key.family === fontName.family && key.style === fontName.style
+ )
+ if (meta?.fontWeight !== undefined) {
+ return { fontWeight: meta.fontWeight, italic: meta.fontStyle === 'ITALIC' }
+ }
+ const { weight, italic } = parseFontStyle(fontName.style)
+ return { fontWeight: weight, italic }
+}
diff --git a/packages/fig/src/node-change/style/runs.ts b/packages/fig/src/node-change/style/runs.ts
index a129e0bf2..a21dac771 100644
--- a/packages/fig/src/node-change/style/runs.ts
+++ b/packages/fig/src/node-change/style/runs.ts
@@ -9,9 +9,9 @@ import type {
StyleRun,
TextCase
} from '@open-pencil/scene-graph'
-import { styleToWeight } from '@open-pencil/scene-graph/font-style'
import { convertFontFeatures } from '../font/features'
+import { savedFace } from '../font/style'
import { convertFontVariations } from '../font/variations'
import { convertFills } from '../paint'
import { convertLetterSpacing, convertLineHeight, mapTextDecoration } from '../text/values'
@@ -75,8 +75,9 @@ function convertStyleOverride(override: NodeChange, text: NodeChange): Character
const style: CharacterStyleOverride = {}
if (override.fontName) {
style.fontFamily = override.fontName.family
- style.fontWeight = styleToWeight(override.fontName.style)
- style.italic = override.fontName.style.toLowerCase().includes('italic')
+ const face = savedFace(text, override.fontName)
+ style.fontWeight = face.fontWeight
+ style.italic = face.italic
style.fontStyle = override.fontName.style || null
}
if (override.fontSize !== undefined) style.fontSize = override.fontSize
diff --git a/packages/fig/tests/node-change/font/style.test.ts b/packages/fig/tests/node-change/font/style.test.ts
index 40bb1f8d4..cef4efe79 100644
--- a/packages/fig/tests/node-change/font/style.test.ts
+++ b/packages/fig/tests/node-change/font/style.test.ts
@@ -91,3 +91,66 @@ test('names a range that sets another face without a name by that face, not the
expect(written.fontName?.style).toBe('Book')
expect(written.textData?.styleOverrideTable?.[0]?.fontName?.style).toBe('Bold')
})
+
+test('reads a face’s weight and slant from the font data Figma saves beside its glyphs', () => {
+ // As Figma desktop saved them (2026-10-30): the weight its font gives each face.
+ const text = (family: string, style: string, fontWeight: number, italic = false) =>
+ nodeChangeToProps(
+ {
+ type: 'TEXT',
+ fontName: { family, style, postscript: '' },
+ derivedTextData: {
+ fontMetaData: [
+ {
+ key: { family, style, postscript: '' },
+ fontWeight,
+ fontStyle: italic ? 'ITALIC' : 'NORMAL'
+ }
+ ]
+ }
+ } as NodeChange,
+ []
+ )
+ expect(text('Avenir', 'Book', 350)).toMatchObject({ fontWeight: 350, fontStyle: 'Book' })
+ expect(text('Avenir', 'Heavy', 800)).toMatchObject({ fontWeight: 800, italic: false })
+ expect(text('Avenir', 'Oblique', 400, true)).toMatchObject({ fontWeight: 400, italic: true })
+ expect(text('Roboto', 'Condensed Bold', 700)).toMatchObject({ fontWeight: 700 })
+ expect(text('Fira Code', 'Retina', 450)).toMatchObject({ fontWeight: 450 })
+})
+
+test('reads a range’s weight and slant from the saved font data, not its name', () => {
+ const props = nodeChangeToProps(
+ {
+ type: 'TEXT',
+ fontName: { family: 'Avenir', style: 'Roman', postscript: '' },
+ textData: {
+ characters: 'Roman Book',
+ characterStyleIDs: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
+ styleOverrideTable: [
+ { styleID: 1, fontName: { family: 'Avenir', style: 'Book', postscript: '' } }
+ ]
+ },
+ derivedTextData: {
+ fontMetaData: [
+ {
+ key: { family: 'Avenir', style: 'Roman', postscript: '' },
+ fontWeight: 400,
+ fontStyle: 'NORMAL',
+ fontLineHeight: 1.2
+ },
+ // A slant its name does not say, so only the saved data can give it.
+ {
+ key: { family: 'Avenir', style: 'Book', postscript: '' },
+ fontWeight: 350,
+ fontStyle: 'ITALIC',
+ fontLineHeight: 1.2
+ }
+ ]
+ }
+ } as NodeChange,
+ []
+ )
+ expect(props.styleRuns).toMatchObject([
+ { start: 6, length: 4, style: { fontWeight: 350, italic: true, fontStyle: 'Book' } }
+ ])
+})
diff --git a/packages/scene-graph/src/font-style.ts b/packages/scene-graph/src/font-style.ts
index 87202fa4d..659148c56 100644
--- a/packages/scene-graph/src/font-style.ts
+++ b/packages/scene-graph/src/font-style.ts
@@ -81,3 +81,41 @@ export function standardStyleName(weight: number, italic = false): string {
if (!italic) return label
return label === 'Regular' ? 'Italic' : `${label} Italic`
}
+
+/** A style name compared without case or spaces, so "Semi Bold" and "SemiBold" name one face. */
+export function styleSpelling(style: string): string {
+ return style.toLowerCase().replace(/\s+/gu, '')
+}
+
+/**
+ * Whether `style` only names a weight and slant ("Bold Italic", "Semi Bold"), so any face of that
+ * weight is it; a name such as "Book" or "Condensed Bold" is one face of its own.
+ */
+export function namesWeight(style: string): boolean {
+ const { weight, italic } = parseFontStyle(style)
+ const spelling = styleSpelling(style)
+ return [faceLoadKey(weight, italic), standardStyleName(weight, italic)]
+ .map(styleSpelling)
+ .includes(spelling)
+}
+
+/** A face as text sets it: a weight and slant, and the name it was given, if any. */
+export interface NamedFace {
+ fontWeight: number
+ italic: boolean
+ fontStyle: string | null
+}
+
+/**
+ * The style a face loads and draws as. A name that only spells its weight and slant ("Semi Bold",
+ * "Italic") loads as the weight's key, so whichever font of the family draws that weight draws
+ * it; any other name ("Book", "Condensed Bold", "Retina") is a face the weight cannot pick, and
+ * it loads and draws by that name.
+ */
+export function faceStyleKey({ fontWeight, italic, fontStyle }: NamedFace): string {
+ const key = faceLoadKey(fontWeight, italic)
+ if (!fontStyle) return key
+ const spelling = styleSpelling(fontStyle)
+ const weightNames = [key, standardStyleName(fontWeight, italic)].map(styleSpelling)
+ return weightNames.includes(spelling) ? key : fontStyle
+}
diff --git a/packages/scene-graph/tests/font-style.test.ts b/packages/scene-graph/tests/font-style.test.ts
index c619b4049..6c3bf5198 100644
--- a/packages/scene-graph/tests/font-style.test.ts
+++ b/packages/scene-graph/tests/font-style.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, test } from 'bun:test'
import {
faceLoadKey,
+ faceStyleKey,
+ namesWeight,
normalizeFontFamily,
standardStyleName,
styleToWeight
@@ -105,3 +107,32 @@ describe('normalizeFontFamily', () => {
expect(normalizeFontFamily('12pt Serif')).toBe('12pt Serif')
})
})
+
+describe('faceStyleKey', () => {
+ const face = (fontWeight: number, fontStyle: string | null, italic = false) =>
+ faceStyleKey({ fontWeight, italic, fontStyle })
+
+ test('loads a face its weight already names by the weight, however its name is spelled', () => {
+ expect(face(600, null)).toBe('SemiBold')
+ expect(face(600, 'Semi Bold')).toBe('SemiBold')
+ expect(face(400, 'Italic', true)).toBe('Regular Italic')
+ expect(face(700, 'bold')).toBe('Bold')
+ })
+
+ test('loads a face its weight cannot pick by its own name', () => {
+ expect(face(350, 'Book')).toBe('Book')
+ expect(face(400, 'Roman')).toBe('Roman')
+ expect(face(800, 'Heavy')).toBe('Heavy')
+ expect(face(700, 'Condensed Bold')).toBe('Condensed Bold')
+ expect(face(450, 'Retina')).toBe('Retina')
+ })
+})
+
+describe('namesWeight', () => {
+ test('tells names of a weight and slant from names of a face of their own', () => {
+ for (const name of ['Regular', 'Italic', 'Regular Italic', 'Semi Bold', 'ExtraBold Italic'])
+ expect(namesWeight(name)).toBe(true)
+ for (const name of ['Book', 'Roman', 'Heavy', 'Oblique', 'Condensed Bold', 'Retina'])
+ expect(namesWeight(name)).toBe(false)
+ })
+})
diff --git a/packages/vue/src/controls/typography/actions.ts b/packages/vue/src/controls/typography/actions.ts
index ee1f9aad3..cac84f521 100644
--- a/packages/vue/src/controls/typography/actions.ts
+++ b/packages/vue/src/controls/typography/actions.ts
@@ -2,14 +2,14 @@ import { computed } from 'vue'
import type { ComputedRef } from 'vue'
import type { Editor } from '@open-pencil/core'
-import { fontManager, nearestFamilyFace } from '@open-pencil/core/text'
+import { faceForStyle, fontManager, nearestFamilyFace } from '@open-pencil/core/text'
import type {
SceneNode,
TextLength,
TextListType,
TextParagraphSpacingField
} from '@open-pencil/scene-graph'
-import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey, faceStyleKey } from '@open-pencil/scene-graph/font-style'
import { shapeWithTextLabel } from '@open-pencil/scene-graph/generated'
import {
@@ -71,8 +71,10 @@ export function createTypographyState(editor: Editor) {
const fontFamily = computed(() => node.value?.fontFamily ?? '')
const fontWeight = computed(() => node.value?.fontWeight ?? 400)
const fontSize = computed(() => node.value?.fontSize ?? 16)
- const { weights, supports, styleName } = useFamilyFaces(nodes)
+ const { faces, supports, styleName } = useFamilyFaces(nodes)
const currentWeightLabel = computed(() => (node.value ? styleName(node.value) : 'Regular'))
+ /** The face every selected text layer is set in, by its name, or MIXED when they differ. */
+ const faceName = computed(() => sharedValue(nodes.value.map((text) => styleName(text))))
const activeFormatting = computed(() => sharedFormatting(nodes.value))
/**
* The list style every selected text shares, or that of the paragraphs being edited; `null`
@@ -114,9 +116,10 @@ export function createTypographyState(editor: Editor) {
fontWeight,
fontSize,
currentWeightLabel,
+ faceName,
activeFormatting,
listType,
- weights,
+ faces,
supports,
missingFonts,
hasMissingFonts
@@ -235,6 +238,25 @@ export function createTypographyActions({
)
}
+ /**
+ * Sets the face `style` names in each layer's family, as the style menu sets one: its weight,
+ * slant, and name, loaded first so the text is laid out once with it.
+ */
+ async function setFace(style: string, targets = nodes.value) {
+ await updateAfterLoading(
+ 'Change font style',
+ ['fontWeight', 'italic', 'fontStyle'],
+ async (target) => {
+ // The menu lists the faces of the layer's slant, so a name in both slants is that one.
+ const face = faceForStyle(target.fontFamily, style, target.italic)
+ const fields = { fontWeight: face.weight, italic: face.italic, fontStyle: face.style }
+ await options.fontLoader?.load(target.fontFamily, faceStyleKey(fields))
+ return { ...fields, fontVariations: styleFontVariations(target) }
+ },
+ targets
+ )
+ }
+
function setAlign(align: TextAlign) {
update('Change text alignment', { textAlignHorizontal: align })
}
@@ -424,6 +446,7 @@ export function createTypographyActions({
return {
setFamily,
setWeight,
+ setFace,
setAlign,
setDirection,
setVerticalAlign,
diff --git a/packages/vue/src/controls/typography/faces.ts b/packages/vue/src/controls/typography/faces.ts
index 8fb8c98ef..c9a112814 100644
--- a/packages/vue/src/controls/typography/faces.ts
+++ b/packages/vue/src/controls/typography/faces.ts
@@ -1,8 +1,9 @@
-import { uniq } from 'es-toolkit'
+import { uniq, uniqBy } from 'es-toolkit'
import { computed, onScopeDispose, ref, watch, type ComputedRef } from 'vue'
-import { faceStyleName, fontManager, textStyleName } from '@open-pencil/core/text'
+import { fontManager, standardFace, textStyleName } from '@open-pencil/core/text'
import type { SceneNode } from '@open-pencil/scene-graph'
+import { styleSpelling } from '@open-pencil/scene-graph/font-style'
import { TYPOGRAPHY_WEIGHTS } from '#vue/controls/typography/weights'
@@ -37,34 +38,54 @@ export function useFamilyFaces(nodes: ComputedRef<SceneNode[]>) {
}
/**
- * The weights every selected layer's family has at that layer's slant, and the weights the
- * layers already use, so the field still names one their family lacks. Each is named as the
- * first layer's font names that face, as Figma's style menu lists a family's own names.
+ * Whether a layer's family has a face of this name in the layer's slant, which choosing it
+ * keeps, or nothing says it has not.
*/
- const weights = computed(() => {
+ function offersStyle(node: SceneNode, style: string): boolean {
+ const faces = fontManager.loadedFamilyFaces(node.fontFamily)
+ return (
+ !faces ||
+ faces.some(
+ (face) => face.italic === node.italic && styleSpelling(face.style) === styleSpelling(style)
+ )
+ )
+ }
+
+ /**
+ * The faces of the first layer's family in its slant, lightest first, by the names its fonts
+ * give them, as Figma's style menu lists a family's faces ("Book" and "Roman" apart), and only
+ * those every selected layer's family has. A family whose faces are unknown offers every
+ * standard weight. The faces the layers are set in stay listed, by the layers' own names, so
+ * the field still names one their family lacks or a file spells its own way.
+ */
+ // Each option's value is the face's name, which is also what choosing it sets.
+ const faces = computed(() => {
void arrived.value
const first = nodes.value.at(0)
- return TYPOGRAPHY_WEIGHTS.filter(
- ({ value }) =>
- nodes.value.some((node) => node.fontWeight === value) ||
- nodes.value.every((node) => supports(node, value, node.italic))
- ).map(({ value, label }) => ({
- value,
- label: first ? weightName(first, value) : label
- }))
+ if (!first) return []
+ const known =
+ fontManager.loadedFamilyFaces(first.fontFamily) ??
+ TYPOGRAPHY_WEIGHTS.map(({ value }) => standardFace(value, first.italic))
+ const listed = known
+ .filter((face) => face.italic === first.italic)
+ .toSorted((a, b) => a.weight - b.weight)
+ .map((face) => face.style)
+ .filter((style) => nodes.value.every((node) => offersStyle(node, style)))
+ const own = nodes.value.map((node) => textStyleName(node))
+ const names = uniqBy(
+ [...listed, ...own].map(
+ (style) => own.find((name) => styleSpelling(name) === styleSpelling(style)) ?? style
+ ),
+ styleSpelling
+ )
+ return names.map((style) => ({ value: style, label: style }))
})
- /** A weight's name in a layer's family; its own weight keeps the name the layer has for it. */
- function weightName(node: SceneNode, weight: number): string {
- if (weight === node.fontWeight) return textStyleName(node)
- return faceStyleName(node.fontFamily, weight, node.italic)
- }
-
/** The name of the face a layer is set in, as its font names it once its faces arrive. */
function styleName(node: SceneNode): string {
void arrived.value
return textStyleName(node)
}
- return { weights, supports, styleName }
+ return { faces, supports, styleName }
}
diff --git a/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
index ecd8363c6..27ba28b11 100644
--- a/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
+++ b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
@@ -21,6 +21,7 @@ function onFormattingChange(val: AcceptableValue | AcceptableValue[]) {
const actions = {
setFamily: ctx.setFamily,
setWeight: ctx.setWeight,
+ setFace: ctx.setFace,
setDirection: ctx.setDirection,
setVerticalAlign: ctx.setVerticalAlign,
setTextCase: ctx.setTextCase,
@@ -52,7 +53,8 @@ const actions = {
:merged="ctx.merged"
:paragraph-spacing="ctx.paragraphSpacing"
:font-feature="ctx.fontFeature"
- :weights="ctx.weights"
+ :faces="ctx.faces"
+ :face-name="ctx.faceName"
:missing-fonts="ctx.missingFonts"
:has-missing-fonts="ctx.hasMissingFonts"
:active-formatting="ctx.activeFormatting"
diff --git a/packages/vue/tests/controls/typography.test.ts b/packages/vue/tests/controls/typography.test.ts
index 5d64c11bc..ee680151d 100644
--- a/packages/vue/tests/controls/typography.test.ts
+++ b/packages/vue/tests/controls/typography.test.ts
@@ -5,7 +5,7 @@ import { computed, effectScope, nextTick, shallowRef } from 'vue'
import { createEditor } from '@open-pencil/core'
import { SkiaRenderer } from '@open-pencil/core/canvas'
import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
-import { DEFAULT_WEB_FONT_PROVIDER_SETTINGS, fontManager } from '@open-pencil/core/text'
+import { facesFromStyles, fontManager, WEB_FONT_PROVIDER_IDS } from '@open-pencil/core/text'
import type { SceneNode } from '@open-pencil/scene-graph'
import { createTypographyActions } from '#vue/controls/typography/actions'
@@ -26,10 +26,12 @@ const LORA = [
]
const OSWALD = ['ExtraLight', 'Light', 'Regular', 'Medium', 'SemiBold', 'Bold']
const CATALOG = [
- { family: 'Lora', styles: LORA },
- { family: 'Oswald', styles: OSWALD }
+ { family: 'Lora', faces: facesFromStyles(LORA) },
+ { family: 'Oswald', faces: facesFromStyles(OSWALD) }
]
+const providers = fontManager.enabledOnlineFontProviders()
+
beforeAll(() => {
fontManager.setOnlineFontProviders({})
fontManager.setHostFontCatalog(CATALOG)
@@ -37,7 +39,9 @@ beforeAll(() => {
afterAll(() => {
fontManager.setHostFontCatalog([])
- fontManager.setOnlineFontProviders(DEFAULT_WEB_FONT_PROVIDER_SETTINGS)
+ fontManager.setOnlineFontProviders(
+ Object.fromEntries(WEB_FONT_PROVIDER_IDS.map((id) => [id, providers.includes(id)]))
+ )
})
/** Two text layers, the typography actions over a selection, and a font load that waits. */
@@ -118,18 +122,18 @@ test('a family chosen while loading skips layers deleted in the meantime', async
/** Text layers in Inter at these styles, with typography actions and face lists over them. */
function styled(
- ...faces: { fontWeight: number; italic?: boolean; fontFamily?: string; fontStyle?: string }[]
+ ...styles: { fontWeight: number; italic?: boolean; fontFamily?: string; fontStyle?: string }[]
) {
const editor = createEditor()
const page = editor.state.currentPageId
- const texts = faces.map((face) =>
- editor.graph.createNode('TEXT', page, { text: 'a', fontFamily: 'Inter', ...face })
+ const texts = styles.map((style) =>
+ editor.graph.createNode('TEXT', page, { text: 'a', fontFamily: 'Inter', ...style })
)
const nodes = computed(() => texts)
const scope = effectScope()
const lists = scope.run(() => useFamilyFaces(nodes))
if (!lists) throw new Error('Expected family faces')
- const { weights, supports } = lists
+ const { faces, supports } = lists
const actions = createTypographyActions({
editor,
nodes,
@@ -137,7 +141,7 @@ function styled(
supports,
options: {}
})
- return { texts, weights, actions, stop: () => scope.stop() }
+ return { texts, faces, actions, stop: () => scope.stop() }
}
test('a family switch keeps a face the family has, or takes the nearest weight, as in Figma', async () => {
@@ -156,20 +160,51 @@ test('a family switch keeps a face the family has, or takes the nearest weight,
])
})
-test('the weight list offers only the weights the family has', async () => {
- const { weights } = styled({ fontWeight: 400, fontFamily: 'Oswald' })
+test('the style list offers only the faces the family has', async () => {
+ const { faces } = styled({ fontWeight: 400, fontFamily: 'Oswald' })
await fontManager.familyFaces('Oswald')
await nextTick()
- expect(weights.value.map((weight) => weight.value)).toEqual([200, 300, 400, 500, 600, 700])
+ expect(faces.value.map((face) => face.value)).toEqual(OSWALD)
})
-test('the weight list names faces as the family does, and the text’s own weight as the text does', async () => {
- const { weights } = styled({ fontWeight: 600, fontStyle: 'Semi Bold' })
+test('the style list names faces as the family does, and the text’s own face as the text does', async () => {
+ const { faces } = styled({ fontWeight: 600, fontStyle: 'Semi Bold' })
await fontManager.familyFaces('Inter')
await nextTick()
- const label = (value: number) => weights.value.find((weight) => weight.value === value)?.label
// A file from Figma spells Inter 3's name; our Inter 4 names its other faces its own way.
- expect([label(600), label(800), label(200)]).toEqual(['Semi Bold', 'ExtraBold', 'ExtraLight'])
+ expect(faces.value.map((face) => face.label)).toEqual([
+ 'Thin',
+ 'ExtraLight',
+ 'Light',
+ 'Regular',
+ 'Medium',
+ 'Semi Bold',
+ 'Bold',
+ 'ExtraBold',
+ 'Black'
+ ])
+})
+
+test('lists faces of one weight apart, and sets the one chosen by its name', async () => {
+ const avenir = [
+ { style: 'Light', weight: 300, italic: false },
+ { style: 'Roman', weight: 400, italic: false },
+ { style: 'Book', weight: 350, italic: false },
+ { style: 'Heavy', weight: 800, italic: false }
+ ]
+ fontManager.setHostFontCatalog([...CATALOG, { family: 'Avenir', faces: avenir }])
+ try {
+ const { texts, faces, actions } = styled({ fontWeight: 400, fontFamily: 'Avenir' })
+ await fontManager.familyFaces('Avenir')
+ await nextTick()
+ expect(faces.value.map((face) => face.value)).toEqual(['Light', 'Book', 'Roman', 'Heavy'])
+ await actions.setFace('Book')
+ expect(texts.map((text) => [text.fontWeight, text.italic, text.fontStyle])).toEqual([
+ [350, false, 'Book']
+ ])
+ } finally {
+ fontManager.setHostFontCatalog(CATALOG)
+ }
})
test('italic does nothing on a family without italics, and bold goes to Bold', async () => {
@@ -183,15 +218,45 @@ test('italic does nothing on a family without italics, and bold goes to Bold', a
expect(texts[0].fontWeight).toBe(700)
})
-test('the weight list follows a font catalog that arrives after the first lookup', async () => {
- const { weights, stop } = styled({ fontWeight: 400, fontFamily: 'Late Sans' })
+test('offers a face only where every selected layer has it in its own slant', async () => {
+ const family = 'Slant Sans'
+ fontManager.setHostFontCatalog([
+ ...CATALOG,
+ {
+ family,
+ faces: [
+ { style: 'Regular', weight: 400, italic: false },
+ { style: 'Black', weight: 900, italic: false },
+ { style: 'Italic', weight: 400, italic: true }
+ ]
+ }
+ ])
+ try {
+ const { faces } = styled(
+ { fontWeight: 400, fontFamily: family },
+ { fontWeight: 400, italic: true, fontFamily: family }
+ )
+ await fontManager.familyFaces(family)
+ await nextTick()
+ // Black exists only upright, so choosing it would turn the italic layer upright.
+ expect(faces.value.map((face) => face.value)).not.toContain('Black')
+ } finally {
+ fontManager.setHostFontCatalog(CATALOG)
+ }
+})
+
+test('the style list follows a font catalog that arrives after the first lookup', async () => {
+ const { faces, stop } = styled({ fontWeight: 400, fontFamily: 'Late Sans' })
await fontManager.familyFaces('Late Sans')
await nextTick()
- expect(weights.value).toHaveLength(9)
- fontManager.setHostFontCatalog([...CATALOG, { family: 'Late Sans', styles: ['Regular', 'Bold'] }])
+ expect(faces.value).toHaveLength(9)
+ fontManager.setHostFontCatalog([
+ ...CATALOG,
+ { family: 'Late Sans', faces: facesFromStyles(['Regular', 'Bold']) }
+ ])
await fontManager.familyFaces('Late Sans')
await nextTick()
- expect(weights.value.map((weight) => weight.value)).toEqual([400, 700])
+ expect(faces.value.map((face) => face.value)).toEqual(['Regular', 'Bold'])
stop()
fontManager.setHostFontCatalog(CATALOG)
})
diff --git a/src/app/automation/bridge/figma-factory.ts b/src/app/automation/bridge/figma-factory.ts
index 8e5cae147..9cdc27728 100644
--- a/src/app/automation/bridge/figma-factory.ts
+++ b/src/app/automation/bridge/figma-factory.ts
@@ -47,8 +47,8 @@ export function makeFigmaFromStore(
if (store.renderer) api.rasterCodec = createCanvasKitRasterCodec(store.renderer.ck)
api.listAvailableFontsAsync = async () => {
const [systemFonts, familyOptions] = await Promise.all([listFonts(), listFamilies()])
- const fonts = systemFonts.flatMap(({ family, styles }) =>
- styles.map((style) => ({ fontName: { family, style } }))
+ const fonts = systemFonts.flatMap(({ family, faces }) =>
+ faces.map(({ style }) => ({ fontName: { family, style } }))
)
const seenFamilies = new Set(systemFonts.map(({ family }) => family))
for (const { family } of familyOptions) {
diff --git a/src/app/editor/fonts/index.ts b/src/app/editor/fonts/index.ts
index b2bba5f55..edf5c50a8 100644
--- a/src/app/editor/fonts/index.ts
+++ b/src/app/editor/fonts/index.ts
@@ -8,6 +8,7 @@ import {
fontManager,
missingGraphFontScripts,
type FontFamilyOption,
+ type HostFontFamily,
type LocalFontAccessState,
type WebFontProviderId,
UnsupportedFontFormatError
@@ -66,19 +67,14 @@ function configureTauriFontCache() {
configureTauriFontCache()
if (!isTauri()) fontManager.setWebFontFetch(browserWebFontFetch)
-interface TauriFontFamily {
- family: string
- styles: string[]
-}
-
-let tauriFontsCache: TauriFontFamily[] | null = null
-let tauriFontsPromise: Promise<TauriFontFamily[]> | null = null
+let tauriFontsCache: HostFontFamily[] | null = null
+let tauriFontsPromise: Promise<HostFontFamily[]> | null = null
-async function getTauriFonts(): Promise<TauriFontFamily[]> {
+async function getTauriFonts(): Promise<HostFontFamily[]> {
if (tauriFontsCache) return tauriFontsCache
if (!tauriFontsPromise) {
tauriFontsPromise = import('@tauri-apps/api/core')
- .then(({ invoke }) => invoke<TauriFontFamily[]>('list_system_fonts'))
+ .then(({ invoke }) => invoke<HostFontFamily[]>('list_system_fonts'))
.then((fonts) => {
tauriFontsCache = fonts
// The weight list and family switches read each family's faces from these.
@@ -125,7 +121,7 @@ export async function predownloadFallbackFonts() {
return fontManager.ensureFallbackPack()
}
-function registerFontFaces(fonts: TauriFontFamily[]): void {
+function registerFontFaces(fonts: HostFontFamily[]): void {
if (typeof document === 'undefined') return
for (const { family } of fonts) {
const face = new FontFace(family, `local("${family}")`)
@@ -148,7 +144,7 @@ export async function listFamilies(): Promise<FontFamilyOption[]> {
return fontManager.listFamilyOptions()
}
-export async function listFonts(): Promise<TauriFontFamily[]> {
+export async function listFonts(): Promise<HostFontFamily[]> {
configureTauriFontCache()
if (isTauri()) {
return getTauriFonts()
diff --git a/src/app/editor/fonts/status.ts b/src/app/editor/fonts/status.ts
index 27e961a37..e7007d82d 100644
--- a/src/app/editor/fonts/status.ts
+++ b/src/app/editor/fonts/status.ts
@@ -17,6 +17,8 @@ export function useDocumentFontStatus() {
}
useEditorEvent('font:resolution-changed', refresh)
+ // Fonts a paste or script loads reach no resolver, so their arrival refreshes the status too.
+ useEditorEvent('font:loaded', refresh)
useEditorEvent('graph:replaced', refresh)
useEditorEvent('page:changed', refresh)
useEditorEvent('node:created', refresh)
diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vue
index 1193d944e..17f58cdcb 100644
--- a/src/components/properties/TypographySection.vue
+++ b/src/components/properties/TypographySection.vue
@@ -124,10 +124,10 @@ function picked<T>(value: MixedValue<T>): T | '' {
<PanelFieldGroup :label="panels.fontWeight">
<AppSelect
:label="panels.fontWeight"
- :model-value="picked(ctx.merged('fontWeight'))"
- :options="ctx.weights.value"
+ :model-value="picked(ctx.faceName.value)"
+ :options="ctx.faces.value"
:placeholder="panels.mixed"
- @update:model-value="ctx.actions.setWeight(+$event)"
+ @update:model-value="ctx.actions.setFace(String($event))"
/>
</PanelFieldGroup>
<PanelFieldGroup :label="panels.fontSize">
diff --git a/tests/e2e/fonts/variable-weights-visual.spec.ts b/tests/e2e/fonts/variable-weights-visual.spec.ts
index ce020a879..af0807ae8 100644
--- a/tests/e2e/fonts/variable-weights-visual.spec.ts
+++ b/tests/e2e/fonts/variable-weights-visual.spec.ts
@@ -19,66 +19,91 @@ async function openEditor(page: Page): Promise<void> {
await new CanvasHelper(page).waitForInit()
}
+/** A variable font fixture, installed under a family for the styles it draws. */
+interface VariableFixture {
+ file: string
+ family: string
+ styles: string[]
+}
+
+const INTER_VARIABLE: VariableFixture = {
+ file: 'InterVariable-Latin.ttf',
+ family: 'Inter Variable',
+ styles: ['Regular', 'Medium', 'SemiBold', 'Bold']
+}
+
/**
- * Lines of text in the variable Inter fixture, one under the other at 32 px, each with its own
+ * Lines of text in a variable font 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
- .getEntriesByType('resource')
- .map((entry) => entry.name)
- .find((url) => url.includes('/packages/core/src/text/font/manager.ts'))
- if (!fontModuleURL) throw new Error('Active font manager module not found')
- const { fontManager } = (await import(/* @vite-ignore */ fontModuleURL)) as {
- fontManager: FontManager
- }
- const pageId = store.state.currentPageId
- for (const id of store.graph.getNode(pageId)?.childIds.slice() ?? []) {
- store.graph.deleteNode(id)
- }
+async function exportLines(
+ page: Page,
+ lines: Array<Partial<SceneNode> & { text: string }>,
+ font: VariableFixture = INTER_VARIABLE
+) {
+ return page.evaluate(
+ async ({ lines, font }) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store?.renderer) throw new Error('OpenPencil renderer not initialized')
+ const fontModuleURL = performance
+ .getEntriesByType('resource')
+ .map((entry) => entry.name)
+ .find((url) => url.includes('/packages/core/src/text/font/manager.ts'))
+ if (!fontModuleURL) throw new Error('Active font manager module not found')
+ const { fontManager } = (await import(/* @vite-ignore */ fontModuleURL)) as {
+ fontManager: FontManager
+ }
+ const pageId = store.state.currentPageId
+ for (const id of store.graph.getNode(pageId)?.childIds.slice() ?? []) {
+ store.graph.deleteNode(id)
+ }
- // One variable file serves every style, as installed variable fonts such as SF Pro do.
- const data = await fetch('/tests/fixtures/fonts/InterVariable-Latin.ttf').then((response) =>
- response.arrayBuffer()
- )
- for (const style of ['Regular', 'Medium', 'SemiBold', 'Bold']) {
- await fontManager.markLoaded('Inter Variable', style, data)
- }
+ // One variable file serves every style, as installed variable fonts such as SF Pro do.
+ const data = await fetch(`/tests/fixtures/fonts/${font.file}`).then((response) =>
+ response.arrayBuffer()
+ )
+ for (const style of font.styles) {
+ await fontManager.markLoaded(font.family, style, data)
+ }
- const ids = lines.map(
- (line, index) =>
- store.graph.createNode('TEXT', pageId, {
- name: line.text,
- x: 40,
- y: 40 + index * 56,
- width: 520,
- height: 44,
- fontFamily: 'Inter Variable',
- fontSize: 32,
- textAutoResize: 'NONE',
- fills: [
- { type: 'SOLID', color: { r: 0.04, g: 0.06, b: 0.12, a: 1 }, visible: true, opacity: 1 }
- ],
- ...line
- }).id
- )
-
- await store.loadFontsForNodes(ids)
- store.renderer.invalidateAllPictures()
- store.requestRender()
- const image = await store.renderExportImage(ids, 2, 'PNG')
- if (!image) throw new Error('Export failed')
- return {
- image: Array.from(image),
- readiness: ids.map((id) => {
- const node = store.graph.getNode(id)
- return node ? store.renderer?.nodeFontReadiness(node) : 'missing'
- })
- }
- }, lines)
+ const ids = lines.map(
+ (line, index) =>
+ store.graph.createNode('TEXT', pageId, {
+ name: line.text,
+ x: 40,
+ y: 40 + index * 56,
+ width: 520,
+ height: 44,
+ fontFamily: font.family,
+ fontSize: 32,
+ textAutoResize: 'NONE',
+ fills: [
+ {
+ type: 'SOLID',
+ color: { r: 0.04, g: 0.06, b: 0.12, a: 1 },
+ visible: true,
+ opacity: 1
+ }
+ ],
+ ...line
+ }).id
+ )
+
+ await store.loadFontsForNodes(ids)
+ store.renderer.invalidateAllPictures()
+ store.requestRender()
+ const image = await store.renderExportImage(ids, 2, 'PNG')
+ if (!image) throw new Error('Export failed')
+ return {
+ image: Array.from(image),
+ readiness: ids.map((id) => {
+ const node = store.graph.getNode(id)
+ return node ? store.renderer?.nodeFontReadiness(node) : 'missing'
+ })
+ }
+ },
+ { lines, font }
+ )
}
test('variable fonts render each style at its named instance', async ({ page }) => {
@@ -118,3 +143,44 @@ test('a range draws at its own optical size, as Figma saves one', async ({ page
expect(result.readiness).toEqual(['ready', 'ready', 'ready'])
expect(Buffer.from(result.image)).toMatchSnapshot('variable-font-optical-size-ranges.png')
})
+
+test('a face named apart from its weight draws at the named instance of that name', async ({
+ page
+}) => {
+ await openEditor(page)
+
+ // Inter with an extra instance, "Display Heavy" at wght 850, as Roboto has "Condensed Bold".
+ const result = await exportLines(
+ page,
+ [
+ { text: 'Display Heavy, by name', fontWeight: 850, fontStyle: 'Display Heavy' },
+ { text: 'Regular, wght 850', fontVariations: [{ axis: 'wght', value: 850 }] },
+ { text: 'Weight 850, no name', fontWeight: 850 }
+ ],
+ { file: 'InterVariable-Named.ttf', family: 'Inter Named', styles: ['Regular'] }
+ )
+
+ expect(result.readiness).toEqual(['ready', 'ready', 'ready'])
+ expect(Buffer.from(result.image)).toMatchSnapshot('variable-font-named-instance.png')
+})
+
+test('a list marker draws in its item’s face, named apart from its weight too', async ({
+ page
+}) => {
+ await openEditor(page)
+
+ // The number follows the face of its item's first character, as Figma draws it.
+ const list = { textParagraphs: [{ listType: 'ORDERED' as const, indentation: 1 }] }
+ const heavy = { fontWeight: 850, fontStyle: 'Display Heavy' }
+ const result = await exportLines(
+ page,
+ [
+ { text: 'Display Heavy item', ...list, styleRuns: [{ start: 0, length: 18, style: heavy }] },
+ { text: 'Regular item', ...list }
+ ],
+ { file: 'InterVariable-Named.ttf', family: 'Inter Named', styles: ['Regular'] }
+ )
+
+ expect(result.readiness).toEqual(['ready', 'ready'])
+ expect(Buffer.from(result.image)).toMatchSnapshot('variable-font-named-list-marker.png')
+})
diff --git a/tests/e2e/fonts/variable-weights-visual.spec.ts-snapshots/variable-font-named-instance-openpencil-darwin.png b/tests/e2e/fonts/variable-weights-visual.spec.ts-snapshots/variable-font-named-instance-openpencil-darwin.png
new file mode 100644
index 000000000..382d6d1b8
Binary files /dev/null and b/tests/e2e/fonts/variable-weights-visual.spec.ts-snapshots/variable-font-named-instance-openpencil-darwin.png differ
diff --git a/tests/e2e/fonts/variable-weights-visual.spec.ts-snapshots/variable-font-named-list-marker-openpencil-darwin.png b/tests/e2e/fonts/variable-weights-visual.spec.ts-snapshots/variable-font-named-list-marker-openpencil-darwin.png
new file mode 100644
index 000000000..e6954a80c
Binary files /dev/null and b/tests/e2e/fonts/variable-weights-visual.spec.ts-snapshots/variable-font-named-list-marker-openpencil-darwin.png differ
diff --git a/tests/engine/render/canvas/labels/fonts.test.ts b/tests/engine/render/canvas/labels/fonts.test.ts
index 0a972597c..4a877760f 100644
--- a/tests/engine/render/canvas/labels/fonts.test.ts
+++ b/tests/engine/render/canvas/labels/fonts.test.ts
@@ -56,7 +56,7 @@ test.each([
const families = () =>
resolveParagraphFontFamilies(
'Inter',
- 'Regular',
+ { weight: 400, italic: false, style: 'Regular' },
loaded && fixture.arabic ? [fixture.family] : [],
loaded && !fixture.arabic ? [fixture.family] : []
)
diff --git a/tests/engine/render/canvas/text/preparation-cache.test.ts b/tests/engine/render/canvas/text/preparation-cache.test.ts
index d1da6c692..4217c4ebe 100644
--- a/tests/engine/render/canvas/text/preparation-cache.test.ts
+++ b/tests/engine/render/canvas/text/preparation-cache.test.ts
@@ -247,6 +247,7 @@ describe('text preparation cache', () => {
fontSize: 20,
fontWeight: 700,
italic: true,
+ fontStyle: 'Condensed Bold',
fontFeatures: [{ tag: 'liga', enabled: false }],
fontVariations: [{ axis: 'wght', value: 700 }],
opticalSizeFromFontSize: false,
diff --git a/tests/engine/tauri/fonts.test.ts b/tests/engine/tauri/fonts.test.ts
index 98ae52d71..c5944a059 100644
--- a/tests/engine/tauri/fonts.test.ts
+++ b/tests/engine/tauri/fonts.test.ts
@@ -9,20 +9,24 @@ afterEach(async () => {
vi.restoreAllMocks()
})
+/** As the desktop catalog lists a family: each face by its font's name, weight, and slant. */
+const SYSTEM_UI_FACES = [
+ { style: 'Regular', weight: 400, italic: false },
+ { style: 'Bold', weight: 700, italic: false }
+]
+
describe('Tauri font helpers', () => {
test('lists system font families through mocked Tauri IPC', async () => {
await mockTauriIPC((cmd) => {
expect(cmd).toBe('list_system_fonts')
- return [{ family: 'System UI', styles: ['Regular', 'Bold'] }]
+ return [{ family: 'System UI', faces: SYSTEM_UI_FACES }]
})
vi.spyOn(fontManager, 'listFamilyOptions').mockResolvedValue([])
const { listFamilies, listFonts } = await import('@/app/editor/fonts')
await expect(listFamilies()).resolves.toEqual([{ family: 'System UI', source: 'local' }])
- await expect(listFonts()).resolves.toEqual([
- { family: 'System UI', styles: ['Regular', 'Bold'] }
- ])
+ await expect(listFonts()).resolves.toEqual([{ family: 'System UI', faces: SYSTEM_UI_FACES }])
})
test('loads system font bytes and registers the face', async () => {
diff --git a/tests/engine/text/fonts/status.test.ts b/tests/engine/text/fonts/status.test.ts
index 8f4c3b114..8f2e8aa96 100644
--- a/tests/engine/text/fonts/status.test.ts
+++ b/tests/engine/text/fonts/status.test.ts
@@ -185,14 +185,15 @@ describe('documentFontStatus', () => {
})
const issues = documentFontStatus(graph, pageId(graph), new FontManager()).issues
+ // Faces their weight cannot pick load by their own names.
expect(issues.map(({ name, style }) => [name, style])).toEqual([
['Bold', 'Bold'],
- ['Book', 'Regular'],
- ['Roman', 'Regular']
+ ['Book', 'Book'],
+ ['Roman', 'Roman']
])
})
- test('a named face is available once the style it loads as is loaded', async () => {
+ test('a named face is available once it is loaded by its name', async () => {
const graph = new SceneGraph()
graph.createNode('TEXT', pageId(graph), {
name: 'Book',
@@ -201,11 +202,11 @@ describe('documentFontStatus', () => {
fontStyle: 'Book'
})
const manager = new FontManager()
- await manager.markLoaded('Avenir', 'Regular', new ArrayBuffer(8), 'local')
+ await manager.markLoaded('Avenir', 'Book', new ArrayBuffer(8), 'local')
expect(documentFontStatus(graph, pageId(graph), manager)).toMatchObject({
faithful: true,
- faces: [{ family: 'Avenir', name: 'Book', style: 'Regular', status: 'available' }]
+ faces: [{ family: 'Avenir', name: 'Book', style: 'Book', status: 'available' }]
})
})
})
diff --git a/tests/fixtures/fonts/InterVariable-Named.ttf b/tests/fixtures/fonts/InterVariable-Named.ttf
new file mode 100644
index 000000000..f99109136
--- /dev/null
+++ b/tests/fixtures/fonts/InterVariable-Named.ttf
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7137cdc5f0d8067d745c0f874c796f3c601b8e4c86220c219fdcb4c4e1260195
+size 31228
diff --git a/tests/helpers/fonts/offline.ts b/tests/helpers/fonts/offline.ts
new file mode 100644
index 000000000..97c763376
--- /dev/null
+++ b/tests/helpers/fonts/offline.ts
@@ -0,0 +1,8 @@
+import { fontManager } from '@open-pencil/core/text'
+
+/**
+ * Test preload: no web font provider is on, so no test waits on Google or Fontsource, whose
+ * answers outside a browser would come from the real network. A test that needs a provider turns
+ * it on with `setOnlineFontProviders`, stubs `setWebFontFetch`, and restores what it found.
+ */
+fontManager.setOnlineFontProviders({})