raea/text loadFont: a composition asks for a Google Fonts family by name and the page gets it (part of #13)

snapcn's components (#13) load their families by name from Google Fonts; raea had no way for a composition
to ask for one. Google families came only with RAEA_PAGE_GOOGLE_FONTS=1, which fetches every family a
page names, so it is off by default (Chrome loads only what a page links, and every composition's root names Inter).

loadFont("Space Grotesk") (sdk/video/src/fonts.ts, exported from raea/text) returns { fontFamily } and calls the
new native fonts.google, which marks that family wanted in raea-sys-fonts google.rs: the page fetches its Latin
faces, every weight and style, once through raea's URL cache, so a render stays a function of its code and plays
offline once cached. Families nobody asked for still fall back as before. Outside raea (a browser) it links Google's
stylesheet, so the same code shows the same family there.

bench/load-font/check.sh: "Hello raea" in Rubik Mono One with loadFont differs from the fallback by 12885 px, and an
offline render from the cache matches the first exactly. Needs the network on the first render.
This commit is contained in:
shinyobjectz committed 2026-11-08 10:38:36 -08:00
1 parent ffd2738dcc
commit ac39b671ee
9 files changed
+106 -5

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
#!/bin/bash
# raea/text loadFont: a composition that asks for a Google Fonts family by name gets it, as a stylesheet link gets it
# in Chrome (#13: snapcn's components load theirs by name). "Hello raea" in Rubik Mono One, a
# family no Mac has: with loadFont its frame must differ from the same text without it (which falls back as it did),
# and a second render offline (RAEA_OFFLINE=1, from raea's URL cache) must match the first exactly. The first render
# needs the network (fonts.googleapis.com). Exits 1 on a failure.
# bench/load-font/check.sh (RAEA_BIN: the raea to run, default target/release/raea)
cd "$(dirname "$0")/../.." || exit 2
BIN=${RAEA_BIN:-$PWD/target/release/raea}
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-load-font.XXXXXX")
export RAEA_CACHE=$OUT/cache
trap 'rm -rf "$OUT"' EXIT
comp() { # NAME LINES
cat > "$OUT/$1.tsx" <<TSX
import { AbsoluteFill, Composition, registerRoot } from "raea";
$2
const Shot = () => (
<AbsoluteFill style={{ backgroundColor: "#fff", color: "#000", fontFamily, fontSize: 64, padding: 20 }}>Hello raea</AbsoluteFill>
);
registerRoot(() => <Composition id="f" component={Shot} width={640} height={160} fps={30} durationInFrames={1} />);
TSX
}
frame() { # NAME OUT
"$BIN" render "$OUT/$1.tsx" -o "$OUT/$2.mp4" > "$OUT/$2.log" 2>&1 || { echo "FAIL $2: the render failed"; sed 's/^/ /' "$OUT/$2.log" | tail -6; exit 1; }
ffmpeg -loglevel error -i "$OUT/$2.mp4" -frames:v 1 -y "$OUT/$2.png" || { echo "FAIL $2: no frame"; exit 1; }
}
comp on 'import { loadFont } from "raea/text";
const { fontFamily } = loadFont("Rubik Mono One");'
comp off 'const fontFamily = "Rubik Mono One";'
frame on on
frame off off
RAEA_OFFLINE=1 frame on again
status=0
diff=$(magick compare -metric AE "$OUT/on.png" "$OUT/off.png" null: 2>&1 | cut -d' ' -f1)
(( ${diff%.*} > 1000 )) && echo "ok loadFont changes the text's face ($diff px differ)" || { echo "FAIL loadFont: only $diff px differ from the fallback"; status=1; }
same=$(magick compare -metric AE "$OUT/on.png" "$OUT/again.png" null: 2>&1 | cut -d' ' -f1)
[ "${same%.*}" = 0 ] && echo "ok offline, from the cache: the same frame" || { echo "FAIL offline: $same px differ"; status=1; }
[ $status = 0 ] && echo "PASS loadFont"
exit $status
+6
View File
@@ -170,6 +170,11 @@ pub fn call(name: &str, v: &Value) -> R<Value> {
// placement by relations (raea-core-place)
"place.solve" => raea_core_place::solve_json(v),
"fonts.families" => Ok(families().into()),
"fonts.google" => {
let family = s(v, "family")?;
raea_sys_fonts::google::want(&family);
Ok(json!({ "family": family }))
}
"fonts.atlases" => font_atlases(v),
n if n.starts_with("solid.") || n.starts_with("section.") => solid::call(&mut st, n, v),
n => media::call(&mut st, n, v),
@@ -209,6 +214,7 @@ pub fn register() {
("solid.free", "{ id: number }", "null", "drop a solid"),
("place.solve", "{ objects: { id: string; size: [number, number, number]; at?: [number, number, number]; yaw?: number; fixed?: boolean }[]; rules: Record<string, string | number>[]; room?: { min: [number, number]; max: [number, number] } }", "{ objects: { id: string; at: [number, number, number]; yaw: number; size: [number, number, number] }[]; found: { part: string; check: string; level: string; says: string }[]; errors: number }", "boxes placed by relations (on, against, beside, near, apart, facing, align, clear), what can't hold found"),
("fonts.families", "{}", "string[]", "the system's font families by name, sorted, as fontique (bevy_text's FontCx) lists them"),
("fonts.google", "{ family: string }", "{ family: string }", "a Google Fonts family the page loads (its Latin faces, every weight and style, fetched once through raea's URL cache), as a stylesheet link loads it in Chrome (raea/text loadFont)"),
("fonts.atlases", "{ font: string; size: number; text: string }", "{ width: number; height: number; src: string }[]", "bevy_text's glyph atlases for a text in a font file at a size px, each page a PNG data: URL, as Bevy's FontAtlasSet holds them"),
("media.live", "{}", "{ vdecs: number; vencs: number; adecs: number; frames: number; solids: number; worlds: number }", "how many native coders, frames, solids and worlds are alive (for leak checks)"),
("media.size", "{ path: string }", "number", "a file's size in bytes"),
+2
View File
@@ -76,6 +76,8 @@ export interface NativeCalls {
"fonts.atlases": { args: { font: string; size: number; text: string }; answer: { width: number; height: number; src: string }[] };
/** the system's font families by name, sorted, as fontique (bevy_text's FontCx) lists them */
"fonts.families": { args: {}; answer: string[] };
/** a Google Fonts family the page loads (its Latin faces, every weight and style, fetched once through raea's URL cache), as a stylesheet link loads it in Chrome (raea/text loadFont) */
"fonts.google": { args: { family: string }; answer: { family: string } };
/** drop an engine frame */
"frame.free": { args: { frame: number }; answer: null };
/** an engine frame's size */
+1
View File
@@ -3,3 +3,4 @@
// raea/text (bevy_text): text in the world, and time anchored to the words said.
export { Text3D, RichText, Span, type Text3DProps, type RichTextProps, type SpanProps, type GlyphInfo, type GlyphStyle } from "./3d";
export * from "@raea/video/words";
export { loadFont } from "@raea/video/fonts";
+1 -1
View File
@@ -91,7 +91,7 @@ with a capital, hooks with `use`. A component's props are in its file.
## `raea/text` (sdk/raea/src/text.ts)
`RichText`, `Span`, `Text3D`
`RichText`, `Span`, `Text3D`, `loadFont`
## `raea/time` (sdk/raea/src/time.ts)
+2 -1
View File
@@ -19,7 +19,8 @@
"./codecs": "./src/codecs.ts",
"./arena": "./src/arena.tsx",
"./input-region": "./src/input-region.tsx",
"./css": "./src/css.ts"
"./css": "./src/css.ts",
"./fonts": "./src/fonts.ts"
},
"peerDependencies": { "react": "19.2.0" }
}
+26
View File
@@ -0,0 +1,26 @@
// loadFont (raea/text): a Google Fonts family for the page, as a stylesheet <link> loads it in Chrome. Inside raea the
// page fetches the family's Latin faces (each weight and style Google has) once, through raea's URL cache
// (raea-sys-fonts google.rs), so a render stays a function of its code and plays offline once cached. Families
// nobody asked for aren't fetched: Chrome loads only what a page links (RAEA_PAGE_GOOGLE_FONTS=1 fetches every family
// a page names). In a browser it links Google's stylesheet, so the same code shows the same family there.
import { hasNative, native } from "@raea/app/native";
// every weight, upright and italic: Google answers with the ones the family has (as google.rs asks)
const WEIGHTS = "100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i";
const asked = new Set<string>();
/** The page gets Google Fonts' `family` ("Inter", "Space Grotesk"); `fontFamily` is the name to style text with. */
export function loadFont(family: string): { fontFamily: string } {
const name = family.trim();
if (!name || asked.has(name)) return { fontFamily: name };
asked.add(name);
if (hasNative()) {
native("fonts.google", { family: name });
} else if (typeof document !== "undefined" && document.head) {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = `https://fonts.googleapis.com/css?family=${encodeURIComponent(name).replace(/%20/g, "+")}:${WEIGHTS}&display=block`;
document.head.appendChild(link);
}
return { fontFamily: name };
}
+26 -2
View File
@@ -23,17 +23,41 @@ static FAMILIES: Mutex<Option<HashMap<String, Faces>>> = Mutex::new(None);
/// Every weight, upright and italic: Google's CSS API answers with the ones the family has
const WEIGHTS: &str = "100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i";
/// RAEA_PAGE_GOOGLE_FONTS=1 turns it on (off by default: Chrome loads only what a page links)
pub fn enabled() -> bool {
/// Families a composition asked for by name (raea/text loadFont, the `fonts.google` call), as a stylesheet link
/// asks Chrome for them: fetched whatever RAEA_PAGE_GOOGLE_FONTS says, and only these when it's off
static WANTED: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// RAEA_PAGE_GOOGLE_FONTS=1: every family a page names (off by default: Chrome loads only what a page links)
fn every() -> bool {
static ON: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| std::env::var("RAEA_PAGE_GOOGLE_FONTS").as_deref() == Ok("1"));
*ON
}
/// `family` wanted from Google Fonts (case aside), as a page that links its stylesheet wants it
pub fn want(family: &str) {
let mut w = WANTED.lock().unwrap();
if !w.iter().any(|f| f.eq_ignore_ascii_case(family)) {
w.push(family.to_string());
}
}
fn wanted(family: &str) -> bool {
every() || WANTED.lock().unwrap().iter().any(|f| f.eq_ignore_ascii_case(family))
}
/// Whether a page looks for missing families at all: RAEA_PAGE_GOOGLE_FONTS=1, or a family asked for by name
pub fn enabled() -> bool {
every() || !WANTED.lock().unwrap().is_empty()
}
/// Gives `doc` the faces of each family its elements name that it has none of and Google Fonts has; true when one
/// was given (its text is laid out again).
pub fn load_missing(doc: &mut BaseDocument) -> bool {
let mut loaded = false;
for family in doc.missing_font_families() {
if !wanted(&family) {
continue;
}
let faces = FAMILIES.lock().unwrap().get_or_insert_default().get(&family).cloned();
let faces = faces.unwrap_or_else(|| {
let found = Arc::new(fetch(&family));
+2 -1
View File
@@ -158,7 +158,8 @@ pub fn resolve(mut docs: NonSendMut<Docs>, pages: Query<(Entity, &Page)>, time:
let t0 = std::time::Instant::now();
doc.resolve(at);
// families it names that no face here has, from Google Fonts by name (raea-sys-fonts google.rs), looked for when its
// nodes change: the second resolve below lays its text out in them. Only with RAEA_PAGE_GOOGLE_FONTS=1: Chrome
// nodes change: the second resolve below lays its text out in them. Only those raea/text loadFont asked for (or
// every one with RAEA_PAGE_GOOGLE_FONTS=1): Chrome
// loads only what a page links, so a family that isn't installed falls back there (ui-parity's p12 cases name
// Inter, and so does every composition's root through sdk/react)
if raea_sys_fonts::google::enabled() && scanned.insert(e, doc.tree().len()) != Some(doc.tree().len()) && raea_sys_fonts::google::load_missing(doc) {