feat(studio): 34 typefaces with real weights and italics, a categorised font picker

The book catalogue grows from 7 families to 34, all self-hosted through
@fontsource under the SIL OFL 1.1 or the Apache License 2.0: condensed and
poster faces, heavy retro display, elegant display serifs, Montserrat, twelve
scripts and DM Mono. Weights run from 100 to 900, each family offering only
the weights it ships, and the serifs gain real italics.

The catalogue lives in @trek/shared (book-fonts.data.ts) with each family's
roles (display, heading, body, script, mono), weights, italics and letter
width, so the Studio, the findings, the design engine and the assistant read
one list. Page operations and the design engine set a weight a family lacks
at its nearest one, describe_book_page names the role and the weight, and
font_mix no longer counts scripts and mono faces, warning above three.

The Studio gets StudioFontPicker: the current family set in itself, a
searchable list grouped by kind with every family in its own face and the
book's own families first, and a weight slider over the weights the family
has. Faces load only when used; the assistant's page snapshot embeds only the
faces a page draws, the service worker installs only the latin files of the
original seven families, and the faces of an opened book are cached for
offline use. BOOK_SCHEMA_REV goes to 2.
This commit is contained in:
Maurice
2026-10-23 19:02:12 +02:00
parent 507d4f73bc
commit fabefed39f
138 changed files with 3921 additions and 394 deletions
+51
View File
@@ -53,3 +53,54 @@ own switch in the admin panel. https://cloud.google.com/maps-platform/terms
`server/assets/airports.json` is built from **OurAirports**
(https://ourairports.com/data/), released into the public domain.
## Typefaces: Studio books and the app
Every typeface a book can be set in, and the app's own (Poppins, MuseoModerno,
Geist), is self-hosted from the **@fontsource** npm packages, which redistribute
the families published on Google Fonts split into subsets by script. The catalogue of book faces is
`shared/src/book/book-fonts.data.ts`. Each package carries its licence and the
copyright notice of the family's authors in its `LICENSE` file.
Both licences allow a font to be bundled with software and embedded in a
document made with it, so a printed or exported book may carry the faces it is
set in. No family is renamed, redrawn or sold on its own. SIL OFL 1.1: https://openfontlicense.org. Apache 2.0:
https://www.apache.org/licenses/LICENSE-2.0
| Family | Package | Licence |
|---|---|---|
| Abril Fatface | `@fontsource/abril-fatface` | SIL Open Font License 1.1 |
| Alfa Slab One | `@fontsource/alfa-slab-one` | SIL Open Font License 1.1 |
| Allura | `@fontsource/allura` | SIL Open Font License 1.1 |
| Anton | `@fontsource/anton` | SIL Open Font License 1.1 |
| Archivo Black | `@fontsource/archivo-black` | SIL Open Font License 1.1 |
| Bebas Neue | `@fontsource/bebas-neue` | SIL Open Font License 1.1 |
| Big Shoulders Display | `@fontsource/big-shoulders-display` | SIL Open Font License 1.1 |
| Bodoni Moda | `@fontsource/bodoni-moda` | SIL Open Font License 1.1 |
| Bricolage Grotesque | `@fontsource/bricolage-grotesque` | SIL Open Font License 1.1 |
| Caveat | `@fontsource/caveat` | SIL Open Font License 1.1 |
| Cormorant Garamond | `@fontsource/cormorant-garamond` | SIL Open Font License 1.1 |
| Dancing Script | `@fontsource/dancing-script` | SIL Open Font License 1.1 |
| DM Mono | `@fontsource/dm-mono` | SIL Open Font License 1.1 |
| DM Serif Display | `@fontsource/dm-serif-display` | SIL Open Font License 1.1 |
| EB Garamond | `@fontsource/eb-garamond` | SIL Open Font License 1.1 |
| Fraunces | `@fontsource/fraunces` | SIL Open Font License 1.1 |
| Great Vibes | `@fontsource/great-vibes` | SIL Open Font License 1.1 |
| Homemade Apple | `@fontsource/homemade-apple` | Apache License 2.0 |
| Inter | `@fontsource/inter` | SIL Open Font License 1.1 |
| Kaushan Script | `@fontsource/kaushan-script` | SIL Open Font License 1.1 |
| League Gothic | `@fontsource/league-gothic` | SIL Open Font License 1.1 |
| Lora | `@fontsource/lora` | SIL Open Font License 1.1 |
| Montserrat | `@fontsource/montserrat` | SIL Open Font License 1.1 |
| MuseoModerno | `@fontsource/museomoderno` | SIL Open Font License 1.1 |
| Oswald | `@fontsource/oswald` | SIL Open Font License 1.1 |
| Pacifico | `@fontsource/pacifico` | SIL Open Font License 1.1 |
| Parisienne | `@fontsource/parisienne` | SIL Open Font License 1.1 |
| Permanent Marker | `@fontsource/permanent-marker` | Apache License 2.0 |
| Playfair Display | `@fontsource/playfair-display` | SIL Open Font License 1.1 |
| Poppins | `@fontsource/poppins` | SIL Open Font License 1.1 |
| Sacramento | `@fontsource/sacramento` | SIL Open Font License 1.1 |
| Satisfy | `@fontsource/satisfy` | Apache License 2.0 |
| Shrikhand | `@fontsource/shrikhand` | SIL Open Font License 1.1 |
| Yellowtail | `@fontsource/yellowtail` | Apache License 2.0 |
| Geist Sans | `@fontsource/geist-sans` | SIL Open Font License 1.1 |
+67
View File
@@ -0,0 +1,67 @@
import { BOOK_FONT_FACES, BOOK_FONTS_PRECACHED } from '@trek/shared';
/**
* Which font files the service worker installs with the app.
*
* The precache takes every woff and woff2 the build emits, and with the book's
* catalogue at thirty four families that is every weight, both styles and
* every script subset of each: megabytes fetched at install by every user,
* most of it for faces no book of theirs is set in. So the book's faces are
* held to this:
*
* - The faces the app itself draws (Poppins and MuseoModerno for the chrome,
* imported in src/main.tsx) stay exactly as they were.
* - The faces the book shipped with before the catalogue grew
* (`BOOK_FONTS_PRECACHED`) keep their latin woff2, so a book set in them
* still opens offline before Studio was ever opened online.
* - Every other file of a book family, woff, other subsets, new families,
* real italics, is left to the `book-fonts` runtime cache in vite.config.js,
* which the Studio fills with the faces of each book it opens
* (src/components/Studio/bookFontWarm.ts).
*
* Shared by vite.config.js and its test, which reads the filter against file
* names as the build writes them.
*/
/** The faces src/main.tsx imports for the app chrome, which the book shares; bookFontPrecache.test.ts checks this copy. */
export const APP_FACES = {
poppins: [300, 400, 500, 600, 700],
museomoderno: [400, 700, 800],
};
/** The book packages, longest name first, so `dm-serif-display` is never read as `dm-…`. */
const BOOK_PACKAGES = [...new Set(Object.values(BOOK_FONT_FACES).map((f) => f.pkg))].sort(
(a, b) => b.length - a.length
);
const PRECACHED = new Map(
Object.entries(BOOK_FONTS_PRECACHED).map(([id, weights]) => [BOOK_FONT_FACES[id].pkg, new Set(weights)])
);
/**
* A font file as the build names it, `<package>-<subset>-<weight>-<style>-<hash>.<ext>`,
* read against the book's packages; null for any other file.
*/
export function bookFontFile(url) {
const name = url.split('/').pop() ?? '';
const match = /^(.+)-(\d{3})-(normal|italic)-[\w-]+\.(woff2?)$/.exec(name);
if (!match) return null;
const [, head, weight, style, ext] = match;
const pkg = BOOK_PACKAGES.find((p) => head.startsWith(`${p}-`));
if (!pkg) return null;
return { pkg, subset: head.slice(pkg.length + 1), weight: Number(weight), italic: style === 'italic', ext };
}
/** Whether a file of the build goes into the install-time precache. */
export function keepInPrecache(url) {
const file = bookFontFile(url);
if (!file) return true;
if (!file.italic && APP_FACES[file.pkg]?.includes(file.weight)) return true;
const kept = PRECACHED.get(file.pkg);
return !file.italic && file.subset === 'latin' && file.ext === 'woff2' && !!kept?.has(file.weight);
}
/** The precache manifest without the book faces left to the runtime cache: a Workbox `manifestTransforms` entry. */
export function withoutRuntimeFonts(entries) {
return { manifest: entries.filter((entry) => keepInPrecache(entry.url)), warnings: [] };
}
+27
View File
@@ -47,14 +47,41 @@
},
"dependencies": {
"@assistant-ui/react": "0.15.25",
"@fontsource/abril-fatface": "^5.3.0",
"@fontsource/alfa-slab-one": "^5.3.0",
"@fontsource/allura": "^5.3.0",
"@fontsource/anton": "^5.3.0",
"@fontsource/archivo-black": "^5.3.0",
"@fontsource/bebas-neue": "^5.3.0",
"@fontsource/big-shoulders-display": "^5.3.0",
"@fontsource/bodoni-moda": "^5.3.0",
"@fontsource/bricolage-grotesque": "^5.3.0",
"@fontsource/caveat": "^5.3.0",
"@fontsource/cormorant-garamond": "^5.3.0",
"@fontsource/dancing-script": "^5.3.0",
"@fontsource/dm-mono": "^5.3.0",
"@fontsource/dm-serif-display": "^5.3.0",
"@fontsource/eb-garamond": "^5.3.0",
"@fontsource/fraunces": "^5.3.0",
"@fontsource/geist-sans": "^5.3.0",
"@fontsource/great-vibes": "^5.3.0",
"@fontsource/homemade-apple": "^5.3.0",
"@fontsource/inter": "^5.3.0",
"@fontsource/kaushan-script": "^5.3.0",
"@fontsource/league-gothic": "^5.3.0",
"@fontsource/lora": "^5.3.0",
"@fontsource/montserrat": "^5.3.0",
"@fontsource/museomoderno": "^5.3.0",
"@fontsource/oswald": "^5.3.0",
"@fontsource/pacifico": "^5.3.0",
"@fontsource/parisienne": "^5.3.0",
"@fontsource/permanent-marker": "^5.3.0",
"@fontsource/playfair-display": "^5.3.0",
"@fontsource/poppins": "^5.3.0",
"@fontsource/sacramento": "^5.3.0",
"@fontsource/satisfy": "^5.3.0",
"@fontsource/shrikhand": "^5.3.0",
"@fontsource/yellowtail": "^5.3.0",
"@mapbox/mapbox-gl-rtl-text": "^0.4.0",
"@maplibre/maplibre-gl-leaflet": "0.1.4",
"@simplewebauthn/browser": "^13.3.0",
+1 -1
View File
@@ -26,5 +26,5 @@
"src/pages/atlas/useAtlas.ts": 1211,
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3270,
"src/styles/studio.css": 2087
"src/styles/studio.css": 2057
}
+2 -2
View File
@@ -1,5 +1,5 @@
import type { BookPageSetup, BookSpread } from '@trek/shared'
import { fontStack } from './bookFonts'
import { fontStack, nearestWeight } from './bookFonts'
import { folioInk } from './folioColour'
import { isNumbered } from './bookSheets'
@@ -94,7 +94,7 @@ export function PageNumbers({
textAlign: at.align,
fontFamily: fontStack(cfg.font),
fontSize: `${size}pt`,
fontWeight: 500,
fontWeight: nearestWeight(cfg.font, 500),
letterSpacing: '0.08em',
lineHeight: 1,
color: ink.color,
+2 -2
View File
@@ -3,7 +3,7 @@ import type {
BookElement, BookIconElement, BookPageSetup, BookPhotoElement, BookShapeElement, BookSpread,
} from '@trek/shared'
import { photoSrc } from './bookRender'
import { fontStack } from './bookFonts'
import { fontStack, nearestWeight } from './bookFonts'
import { iconComponent } from './iconLibrary'
import { HOLED_SHAPES, SHAPE_PATHS, scalePath, unitPath } from './shapes'
import { TravelElementView } from './TravelElements'
@@ -417,7 +417,7 @@ export function ElementView({
// the conversion exactly.
fontSize: `${el.size}pt`,
fontFamily: fontStack(el.font),
fontWeight: el.weight,
fontWeight: nearestWeight(el.font, el.weight),
fontStyle: el.italic ? 'italic' : undefined,
lineHeight: el.leading,
letterSpacing: `${el.tracking}em`,
@@ -5,7 +5,7 @@ import { SpreadFold, SpreadView } from './SpreadView'
import { PeerCursors } from './PeerCursors'
import type { PeerCursor } from './useBookPresence'
import { bookElementId as elementId } from '@trek/shared'
import { fontStack } from './bookFonts'
import { fontStack, nearestWeight } from './bookFonts'
import { useSpreadInteraction, type HandleId } from './useSpreadInteraction'
import { useStudioStore } from '../../store/studioStore'
import { useTranslation } from '../../i18n'
@@ -325,7 +325,7 @@ export function StudioCanvas({
// The document is in pt; the overlay is on screen at the same zoom.
fontSize: `${el.size * (96 / 72) * zoom}px`,
fontFamily: fontStack(el.font),
fontWeight: el.weight,
fontWeight: nearestWeight(el.font, el.weight),
fontStyle: el.italic ? 'italic' : undefined,
lineHeight: el.leading,
letterSpacing: `${el.tracking}em`,
@@ -0,0 +1,112 @@
import { blankBook, bookTextElementSchema, type BookDocument, type BookElement, type BookSpread } from '@trek/shared';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, within } from '../../../tests/helpers/render';
import { useStudioStore } from '../../store/studioStore';
import { BOOK_FONT_ORDER } from './bookFonts';
import { matchFonts, pickFont } from './fontPicker';
import { StudioFontPicker } from './StudioFontPicker';
/**
* The typeface picker (FE-STUDIO-FONTPICK): the current family set in itself,
* a list grouped by kind with every family in its own face, the book's own
* families first, a search, and a weight that lands on one the family has.
*/
const t = (k: string, params?: Record<string, string | number>) =>
params ? `${k} ${Object.values(params).join(' ')}` : k;
const groupName = (c: string) => `journey.studio.fonts.cat.${c}`;
const frame = { x: 10, y: 10, w: 80, h: 20 };
function bookIn(...fonts: string[]): BookDocument {
const doc = blankBook({ title: 'Porto', newId: (p) => `${p}-x` });
const elements = fonts.map(
(font, i) => bookTextElementSchema.parse({ id: `t${i}`, kind: 'text', frame, text: 'Porto', font }) as BookElement
);
const [cover, ...rest] = doc.spreads as [BookSpread, ...BookSpread[]];
return {
...doc,
page: { ...doc.page, pageNumbers: { ...doc.page.pageNumbers, show: false } },
spreads: [{ ...cover, elements }, ...rest],
};
}
const open = () => fireEvent.click(screen.getByRole('button', { name: /journey\.studio\.fonts\.change/ }));
afterEach(() => {
useStudioStore.setState({ doc: null });
});
describe('choosing a family', () => {
it('FE-STUDIO-FONTPICK-001: moves the weight onto one the new family has', () => {
expect(pickFont('anton', 700)).toEqual({ font: 'anton', weight: 400 });
expect(pickFont('sans', 700)).toEqual({ font: 'sans', weight: 700 });
expect(pickFont('oswald', 900)).toEqual({ font: 'oswald', weight: 700 });
});
it('FE-STUDIO-FONTPICK-002: finds families by name, id and group, in picker order', () => {
expect(matchFonts('', groupName)).toEqual(BOOK_FONT_ORDER);
expect(matchFonts(' GARA ', groupName)).toEqual(['garamond', 'cormorant']);
expect(matchFonts('mono', groupName)).toEqual(['mono']);
expect(matchFonts('cat.script', groupName)).toContain('pacifico');
expect(matchFonts('nothing like it', groupName)).toEqual([]);
});
});
describe('the picker', () => {
it('FE-STUDIO-FONTPICK-003: shows the current family set in itself and opens a grouped list with the book families first', () => {
act(() => useStudioStore.setState({ doc: bookIn('caveat', 'serif') }));
render(<StudioFontPicker font="serif" weight={400} onPick={vi.fn()} t={t} />);
const current = screen.getByRole('button', { name: 'journey.studio.fonts.change: Lora' });
expect(current.getAttribute('aria-expanded')).toBe('false');
expect(within(current).getByText('Lora').getAttribute('style')).toContain('Lora');
open();
expect(current.getAttribute('aria-expanded')).toBe('true');
expect(document.activeElement).toBe(screen.getByRole('textbox', { name: 'journey.studio.fonts.search' }));
const groups = screen.getAllByRole('group');
expect(groups[0]?.getAttribute('aria-label')).toBe('journey.studio.fonts.used');
const used = within(groups[0] as HTMLElement).getAllByRole('option');
expect(used.map((o) => o.querySelector('.st-fontpick-face')?.textContent)).toEqual(['Lora', 'Caveat']);
expect(used[1]?.textContent).toContain('journey.studio.fonts.range 400 700');
// Every family, once per group it is in, each set in its own face.
const rows = screen.getAllByRole('option');
expect(rows).toHaveLength(BOOK_FONT_ORDER.length + 2);
const anton = rows.find((r) => r.textContent?.startsWith('Anton'));
expect(anton?.querySelector('span')?.getAttribute('style')).toContain('Anton');
expect(anton?.textContent).toContain('400');
expect(rows.filter((r) => r.getAttribute('aria-selected') === 'true')).toHaveLength(2);
});
it('FE-STUDIO-FONTPICK-004: picks a family at a weight it has and closes, back on the button', () => {
const onPick = vi.fn();
render(<StudioFontPicker font="sans" weight={700} onPick={onPick} t={t} />);
open();
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'anton' } });
expect(screen.queryByRole('group', { name: 'journey.studio.fonts.used' })).toBeNull();
fireEvent.click(screen.getByText('Anton'));
expect(onPick).toHaveBeenCalledWith({ font: 'anton', weight: 400 });
expect(screen.queryByRole('listbox')).toBeNull();
expect(document.activeElement?.getAttribute('aria-expanded')).toBe('false');
});
it('FE-STUDIO-FONTPICK-005: says when nothing matches, clears the search, and closes on Escape', () => {
render(<StudioFontPicker font="sans" weight={400} onPick={vi.fn()} t={t} />);
open();
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'zzz' } });
expect(screen.getByText('journey.studio.fonts.none')).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: 'common.clear' }));
expect((screen.getByRole('textbox') as HTMLInputElement).value).toBe('');
expect(screen.queryByText('journey.studio.fonts.none')).toBeNull();
fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Escape' });
expect(screen.queryByRole('listbox')).toBeNull();
// A second click on the open button closes it too.
open();
open();
expect(screen.queryByRole('listbox')).toBeNull();
});
it('FE-STUDIO-FONTPICK-006: reads a family this build does not know as the default one', () => {
render(<StudioFontPicker font="gone" weight={400} onPick={vi.fn()} t={t} />);
expect(screen.getByRole('button', { name: 'journey.studio.fonts.change: Poppins' })).toBeTruthy();
});
});
@@ -0,0 +1,198 @@
import { BOOK_FONT_CATEGORIES, bookFontsUsed, type BookFontCategory } from '@trek/shared';
import { Check, ChevronDown, Search, X } from 'lucide-react';
import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent } from 'react';
import { useStudioStore } from '../../store/studioStore';
import '../../styles/studio-fonts.css';
import { BOOK_FONTS, nearestWeight, type BookFontId } from './bookFonts';
import { matchFonts, pickFont, weightSpan, type FontPick, type FontT } from './fontPicker';
/**
* The typeface picker, shared by the text inspector and the travel inspector.
*
* Thirty four families do not fit as a wall of buttons the way seven did, and
* a plain list of names says nothing about how a face looks, which is the only
* thing anyone is choosing between. So the current family sits on one line,
* set in itself, and opens a list grouped the way people look for type
* (a sans, a serif, something for a poster, a script to lay over a photo)
* where every family is again set in its own face. The families the book is
* already set in come first, because the second text of a book is usually set
* like the first.
*
* The list opens inside the inspector rather than floating over the page: the
* inspector scrolls, and a popover pinned to a control that scrolls away is a
* popover pointing at nothing.
*/
function FontRow({
id,
on,
weight,
onPick,
t,
}: {
id: BookFontId;
on: boolean;
weight: number;
onPick: () => void;
t: FontT;
}) {
const face = BOOK_FONTS[id];
return (
<button
type="button"
role="option"
aria-selected={on}
className={`st-fontpick-row ${on ? 'is-on' : ''}`}
onClick={onPick}
title={face.name}
>
<span className="st-fontpick-face" style={{ fontFamily: face.stack, fontWeight: nearestWeight(id, weight) }}>
{face.name}
</span>
<span className="st-fontpick-span">{weightSpan(id, t)}</span>
<span className="st-fontpick-tick">{on && <Check size={13} />}</span>
</button>
);
}
function FontGroup({
label,
ids,
font,
weight,
onPick,
t,
}: {
label: string;
ids: BookFontId[];
font: string;
weight: number;
onPick: (id: BookFontId) => void;
t: FontT;
}) {
if (!ids.length) return null;
return (
<div className="st-fontpick-group" role="group" aria-label={label}>
<div className="st-fontpick-label">{label}</div>
{ids.map((id) => (
<FontRow key={id} id={id} on={font === id} weight={weight} onPick={() => onPick(id)} t={t} />
))}
</div>
);
}
/** The families the open book is set in, read from the document the Studio holds. */
function useFontsInBook(): BookFontId[] {
const doc = useStudioStore((s) => s.doc);
return useMemo(() => (doc ? bookFontsUsed(doc) : []), [doc]);
}
export function StudioFontPicker({
font,
weight,
onPick,
t,
}: {
font: string;
weight: number;
onPick: (patch: FontPick) => void;
t: FontT;
}) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState('');
const trigger = useRef<HTMLButtonElement>(null);
const search = useRef<HTMLInputElement>(null);
const listId = useId();
const inBook = useFontsInBook();
const current = BOOK_FONTS[font as BookFontId] ?? BOOK_FONTS.sans;
const groupName = (c: BookFontCategory) => t(`journey.studio.fonts.cat.${c}`);
const found = matchFonts(query, groupName);
// Opened on purpose, so typing goes straight to the search.
useEffect(() => {
if (open) search.current?.focus();
}, [open]);
const close = () => {
setOpen(false);
setQuery('');
trigger.current?.focus();
};
const choose = (id: BookFontId) => {
onPick(pickFont(id, weight));
close();
};
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.stopPropagation();
close();
};
return (
<div className={`st-fontpick ${open ? 'is-open' : ''}`} onKeyDown={onKey}>
<button
ref={trigger}
type="button"
className="st-fontpick-current"
aria-expanded={open}
aria-controls={listId}
aria-label={`${t('journey.studio.fonts.change')}: ${current.name}`}
onClick={() => (open ? close() : setOpen(true))}
>
<span
className="st-fontpick-face"
style={{ fontFamily: current.stack, fontWeight: nearestWeight(current.id, weight) }}
>
{current.name}
</span>
<span className="st-fontpick-span">{groupName(current.category)}</span>
<ChevronDown size={14} className="st-fontpick-caret" />
</button>
{open && (
<div className="st-fontpick-panel">
<div className="st-search st-fontpick-search">
<Search size={14} />
<input
ref={search}
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t('journey.studio.fonts.search')}
aria-label={t('journey.studio.fonts.search')}
aria-controls={listId}
spellCheck={false}
/>
{query && (
<button type="button" onClick={() => setQuery('')} aria-label={t('common.clear')}>
<X size={13} />
</button>
)}
</div>
<div id={listId} className="st-fontpick-list" role="listbox" aria-label={t('journey.studio.fonts.list')}>
{!query && (
<FontGroup
label={t('journey.studio.fonts.used')}
ids={inBook}
font={font}
weight={weight}
onPick={choose}
t={t}
/>
)}
{BOOK_FONT_CATEGORIES.map((category) => (
<FontGroup
key={category}
label={groupName(category)}
ids={found.filter((id) => BOOK_FONTS[id].category === category)}
font={font}
weight={weight}
onPick={choose}
t={t}
/>
))}
{!found.length && <p className="st-hint st-fontpick-none">{t('journey.studio.fonts.none')}</p>}
</div>
</div>
)}
</div>
);
}
@@ -13,7 +13,9 @@ import { Swatches } from './StudioSwatches'
import { formatBookCoords } from '@trek/shared'
import { iconComponent, iconLabel, searchIcons } from './iconLibrary'
import { Choice, Line, NumField, Section, Switch } from './StudioControls'
import { FontButtons, WeightLine } from './StudioTypeControls'
import { StudioFontPicker } from './StudioFontPicker'
import { WeightLine } from './StudioTypeControls'
import { italicTitle } from './fontPicker'
import type { JourneySource } from './StudioSidebar'
import { Tooltip } from '../shared/Tooltip'
@@ -323,7 +325,7 @@ export function StudioInspector({
nothing about a typeface — and grouped, because "which serif"
is a different question from "serif or sans".
*/}
<FontButtons font={el.font} weight={el.weight} onPick={patch => set(patch)} />
<StudioFontPicker font={el.font} weight={el.weight} onPick={patch => set(patch)} t={t} />
<div style={{ marginTop: 10 }}>
<WeightLine font={el.font} weight={el.weight} onPick={weight => set({ weight })} t={t} />
<Line label={t('journey.studio.align')}>
@@ -344,7 +346,7 @@ export function StudioInspector({
<button type="button"
className={`st-chip is-icon ${el.italic ? 'is-on' : ''}`}
onClick={() => set({ italic: !el.italic })}
title={t('journey.studio.italic')}
title={italicTitle(el.font, el.weight, t)}
aria-label={t('journey.studio.italic')}
aria-pressed={el.italic}
>
@@ -26,6 +26,7 @@ import { useStudioAssistant, type StudioAssistant } from './useStudioAssistant'
import '../../styles/dashboard.css'
import '../../styles/studio.css'
import './bookFontFaces'
import { useWarmBookFaces } from './bookFontWarm'
import HelpButton from '../Help/HelpButton'
/**
@@ -45,6 +46,8 @@ export default function StudioShell() {
const [bookView, setBookView] = useState(true)
const [exporting, setExporting] = useState(false)
const assistant = useStudioAssistant({ journeyId: s.journeyId, flush: s.flushBook })
// The book's faces into the offline cache as it opens (bookFontWarm.ts).
useWarmBookFaces()
if (s.isMobile) {
return createPortal(
@@ -5,7 +5,8 @@ import type {
} from '@trek/shared'
import { BOOK_METRICS, MAX_PATH_POINTS, MAX_PATH_SEGMENTS, isStale, refreshPatch } from '@trek/shared'
import { Swatches } from './StudioSwatches'
import { FontButtons, WeightLine } from './StudioTypeControls'
import { StudioFontPicker } from './StudioFontPicker'
import { WeightLine } from './StudioTypeControls'
import { sourceIdOf, useMapSources } from './mapSources'
import { printDpi, tileView } from './mapTiles'
import { useCartoApiKey } from '../../hooks/useTileUrl'
@@ -82,7 +83,7 @@ export function TravelInspector({ el, stats, path, set, t }: TravelInspectorProp
* wrong typeface and no way to fix it.
*/}
<Section label={t('journey.studio.typography')} defaultOpen={false}>
<FontButtons font={el.font} weight={el.weight} onPick={patch => set(patch as Partial<BookElement>)} />
<StudioFontPicker font={el.font} weight={el.weight} onPick={patch => set(patch as Partial<BookElement>)} t={t} />
<div style={{ marginTop: 10 }}>
<WeightLine
font={el.font}
@@ -1,50 +1,47 @@
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { BOOK_FONT_ORDER } from './bookFonts';
import { FontButtons, WeightLine } from './StudioTypeControls';
import { italicTitle } from './fontPicker';
import { WeightLine } from './StudioTypeControls';
const t = (k: string) => k;
describe('FontButtons', () => {
it('offers every bundled family in the picker order and marks the current one', () => {
render(<FontButtons font="serif" weight={400} onPick={vi.fn()} />);
const buttons = screen.getAllByRole('button');
expect(buttons).toHaveLength(BOOK_FONT_ORDER.length);
expect(screen.getByRole('button', { name: 'Lora' }).className).toContain('is-on');
expect(screen.getByRole('button', { name: 'Poppins' }).className).not.toContain('is-on');
});
it('keeps the weight when the new family ships it', () => {
const onPick = vi.fn();
render(<FontButtons font="sans" weight={700} onPick={onPick} />);
fireEvent.click(screen.getByRole('button', { name: 'Inter' }));
expect(onPick).toHaveBeenCalledWith({ font: 'inter', weight: 700 });
});
it('moves the weight to one the new family really has', () => {
const onPick = vi.fn();
render(<FontButtons font="sans" weight={700} onPick={onPick} />);
fireEvent.click(screen.getByRole('button', { name: 'Bebas Neue' }));
expect(onPick).toHaveBeenCalledWith({ font: 'bebas', weight: 400 });
});
});
describe('WeightLine', () => {
it('greys the weights the family does not ship and says why', () => {
render(<WeightLine font="bebas" weight={400} onPick={vi.fn()} t={t} />);
it('steps through only the weights the family has and says the drawn one by name and number', () => {
render(<WeightLine font="oswald" weight={700} onPick={vi.fn()} t={t} />);
expect(screen.getByText('journey.studio.weight')).toBeTruthy();
const bold = screen.getByRole('radio', { name: '700' }) as HTMLButtonElement;
expect(bold.disabled).toBe(true);
expect(bold.title).toBe('journey.studio.weightMissing');
const regular = screen.getByRole('radio', { name: '400' }) as HTMLButtonElement;
expect(regular.disabled).toBe(false);
expect(regular.getAttribute('aria-checked')).toBe('true');
const slider = screen.getByRole('slider') as HTMLInputElement;
// Oswald ships 200 to 700: six stops, the last one drawn.
expect([slider.min, slider.max, slider.value]).toEqual(['0', '5', '5']);
expect(slider.getAttribute('aria-valuetext')).toBe('journey.studio.weight.700 700');
expect(screen.getByText('journey.studio.weight.700 700')).toBeTruthy();
});
it('hands the picked weight back', () => {
it('hands back the weight at the stop picked', () => {
const onPick = vi.fn();
render(<WeightLine font="sans" weight={400} onPick={onPick} t={t} />);
fireEvent.click(screen.getByRole('radio', { name: '600' }));
expect(onPick).toHaveBeenCalledWith(600);
fireEvent.change(screen.getByRole('slider'), { target: { value: '0' } });
expect(onPick).toHaveBeenCalledWith(100);
fireEvent.change(screen.getByRole('slider'), { target: { value: '8' } });
expect(onPick).toHaveBeenLastCalledWith(900);
});
it('shows the one weight of a family that has one, with nothing to drag, and the weight it really draws', () => {
render(<WeightLine font="bebas" weight={700} onPick={vi.fn()} t={t} />);
expect(screen.queryByRole('slider')).toBeNull();
expect(screen.getByText('journey.studio.weightOnly')).toBeTruthy();
expect(screen.getByText('journey.studio.weight.400 400')).toBeTruthy();
});
it('reads a family this build does not know as the default one', () => {
render(<WeightLine font="gone" weight={500} onPick={vi.fn()} t={t} />);
expect((screen.getByRole('slider') as HTMLInputElement).value).toBe('4');
});
});
describe('italicTitle', () => {
it('says when the browser slants a family that has no italic of its own', () => {
expect(italicTitle('garamond', 400, t)).toBe('journey.studio.italic');
expect(italicTitle('sans', 400, t)).toBe('journey.studio.italicSlanted');
expect(italicTitle('playfair', 300, t)).toBe('journey.studio.italic');
});
});
@@ -1,58 +1,27 @@
import type { BookTextElement } from '@trek/shared';
import type { BookFontId } from './bookFonts';
import { BOOK_FONTS, BOOK_FONT_ORDER, hasWeight, nearestWeight } from './bookFonts';
import { Choice, Line } from './StudioControls';
import type { BookWeight } from '@trek/shared';
import { BOOK_FONTS, nearestWeight, type BookFontId } from './bookFonts';
import { Line } from './StudioControls';
/**
* The typeface buttons and the weight line, shared by the text inspector and
* the travel inspector so both set type the same way.
* The weight line, shared by the text inspector and the travel inspector so
* both set type the same way. The typeface itself is picked in
* StudioFontPicker.tsx, the italic's title comes from fontPicker.ts.
*/
/** The weight set the book schema allows, taken from it so there is one list. */
type BookWeight = BookTextElement['weight'];
type T = (key: string) => string;
const WEIGHTS = [400, 500, 600, 700] as const;
/** The weights a family ships, lightest first; Poppins' for a family this build does not know. */
const weightsOf = (font: string) => (BOOK_FONTS[font as BookFontId] ?? BOOK_FONTS.sans).weights;
/** One button per bundled family, each set in its own face. */
export function FontButtons({
font,
weight,
onPick,
}: {
font: string;
weight: BookWeight;
onPick: (patch: { font: BookFontId; weight: BookWeight }) => void;
}) {
return (
<div className="st-fonts">
{BOOK_FONT_ORDER.map((id) => {
const face = BOOK_FONTS[id];
return (
<button
type="button"
key={id}
className={`st-font ${font === id ? 'is-on' : ''}`}
style={{ fontFamily: face.stack }}
onClick={() =>
onPick({
font: id,
// A family that does not ship this weight would render a
// synthesised bold, a smeared regular in print, so the
// weight moves to the nearest one it really has.
weight: nearestWeight(id, weight) as BookWeight,
})
}
title={face.name}
>
{face.name}
</button>
);
})}
</div>
);
}
/** The four weights, with the ones the family does not ship greyed out. */
/**
* A slider over the weights the family really has, and only those.
*
* Nine chips from 100 to 900 with most of them greyed out read as a broken
* control for a family with two weights, and as a wall for one with nine.
* The slider steps through what exists, says the weight by its name and its
* number, and a family with a single weight shows that weight and nothing to
* drag.
*/
export function WeightLine({
font,
weight,
@@ -60,22 +29,36 @@ export function WeightLine({
t,
}: {
font: string;
weight: BookWeight;
weight: number;
onPick: (weight: BookWeight) => void;
t: (k: string) => string;
t: T;
}) {
const weights = weightsOf(font);
const drawn = nearestWeight(font, weight);
const at = Math.max(0, weights.indexOf(drawn as BookWeight));
const word = `${t(`journey.studio.weight.${drawn}`)} ${drawn}`;
return (
<Line label={t('journey.studio.weight')}>
<Choice
value={weight}
options={WEIGHTS.map((w) => ({
value: w,
label: String(w),
disabled: !hasWeight(font, w),
title: hasWeight(font, w) ? undefined : t('journey.studio.weightMissing'),
}))}
onPick={onPick}
/>
<div className="st-field st-weight">
{weights.length > 1 ? (
<input
type="range"
min={0}
max={weights.length - 1}
step={1}
value={at}
aria-label={t('journey.studio.weight')}
aria-valuetext={word}
onChange={(e) => {
const next = weights[Number(e.target.value)];
if (next !== undefined) onPick(next);
}}
/>
) : (
<span className="st-weight-only">{t('journey.studio.weightOnly')}</span>
)}
<span className="st-weight-value">{word}</span>
</div>
</Line>
);
}
@@ -7,7 +7,7 @@ import {
Camera, CalendarDays, Footprints, Globe, MapPin, Navigation, Route,
type LucideIcon,
} from 'lucide-react'
import { fontStack } from './bookFonts'
import { fontStack, lighterWeight, nearestWeight } from './bookFonts'
import { haversineKm } from '../../utils/geo'
import { brightness } from './folioColour'
import { COUNTRY_SHAPES, countryParts, countryWorldPath, projectMercator, unprojectMercator } from './countryShapes'
@@ -140,8 +140,8 @@ export function TravelElementView({ el, frameStyle, big = false }: {
* `textScale` moves their size. Hard-coded 700s meant the only way to lighten a
* stats block was to not use one.
*/
const heavy = (el: { weight: number }) => el.weight
const light = (el: { weight: number }) => Math.max(400, el.weight - 100)
const heavy = (el: { font: string; weight: number }) => nearestWeight(el.font, el.weight)
const light = (el: { font: string; weight: number }) => lighterWeight(el.font, el.weight)
const MAP_PALETTES = {
minimal: { land: '#e9e5dc', border: '#d6d0c4', onDark: false },
+180 -14
View File
@@ -1,43 +1,209 @@
/**
* The @font-face rules behind the book's typefaces.
*
* bookFonts.ts names the seven families; this is where the faces they need
* arrive. Poppins comes with the app chrome in main.tsx and is not repeated
* here, and neither are MuseoModerno's 400 and 700: importing a face twice only
* duplicates every rule. Its 500 and 600 are the book's alone, which is why
* they are down here rather than up there.
* The catalogue in @trek/shared (book-fonts.data.ts) names the families, the
* weights each ships and the weights it has a real italic for; this is where
* those faces arrive, one import per face. Poppins 300 to 700 and
* MuseoModerno 400, 700 and 800 come with the app chrome in main.tsx and are
* not repeated here: importing a face twice only duplicates every rule.
*
* Pulled in by StudioShell rather than by main.tsx: nothing outside the editor
* is set in Lora or Bebas Neue, so the faces travel with the Studio chunk and
* cost the app's first paint nothing. Once that chunk is loaded they are
* ordinary stylesheets on the document, which is what lets printSheets copy
* them into the print frame with everything else.
* is set in Lora or Anton, so the rules travel with the Studio chunk and cost
* the app's first paint nothing. Once that chunk is loaded they are ordinary
* stylesheets on the document, which is what lets printSheets copy them into
* the print frame with everything else.
*
* Upright only, as everywhere else in the app: the editor's italic toggle has
* always been the browser's synthetic slant, and a second file per weight is a
* lot of download to change that.
* A rule is not a download. The browser fetches a face's file only when text
* on the page is set in it, and only the subsets (latin, latin-ext, cyrillic
* and so on) whose characters that text uses, so a book set in two families
* loads two families however long this list grows. The print frame loads the
* same way, and the assistant's page snapshot embeds only the faces a page
* draws (snapshotFonts.ts).
*
* Real italics for the serifs, where the browser's slant reads as a mistake;
* the sans faces keep the synthetic oblique they always had, which saves a
* second file per weight nobody would tell apart.
*/
import '@fontsource/poppins/100.css'
import '@fontsource/poppins/200.css'
import '@fontsource/poppins/800.css'
import '@fontsource/poppins/900.css'
import '@fontsource/inter/100.css'
import '@fontsource/inter/200.css'
import '@fontsource/inter/300.css'
import '@fontsource/inter/400.css'
import '@fontsource/inter/500.css'
import '@fontsource/inter/600.css'
import '@fontsource/inter/700.css'
import '@fontsource/inter/800.css'
import '@fontsource/inter/900.css'
import '@fontsource/montserrat/100.css'
import '@fontsource/montserrat/200.css'
import '@fontsource/montserrat/300.css'
import '@fontsource/montserrat/400.css'
import '@fontsource/montserrat/500.css'
import '@fontsource/montserrat/600.css'
import '@fontsource/montserrat/700.css'
import '@fontsource/montserrat/800.css'
import '@fontsource/montserrat/900.css'
import '@fontsource/lora/400.css'
import '@fontsource/lora/500.css'
import '@fontsource/lora/600.css'
import '@fontsource/lora/700.css'
import '@fontsource/lora/400-italic.css'
import '@fontsource/lora/500-italic.css'
import '@fontsource/lora/600-italic.css'
import '@fontsource/lora/700-italic.css'
import '@fontsource/eb-garamond/400.css'
import '@fontsource/eb-garamond/500.css'
import '@fontsource/eb-garamond/600.css'
import '@fontsource/eb-garamond/700.css'
import '@fontsource/eb-garamond/800.css'
import '@fontsource/eb-garamond/400-italic.css'
import '@fontsource/eb-garamond/500-italic.css'
import '@fontsource/eb-garamond/600-italic.css'
import '@fontsource/eb-garamond/700-italic.css'
import '@fontsource/eb-garamond/800-italic.css'
import '@fontsource/playfair-display/400.css'
import '@fontsource/playfair-display/500.css'
import '@fontsource/playfair-display/600.css'
import '@fontsource/playfair-display/700.css'
import '@fontsource/playfair-display/800.css'
import '@fontsource/playfair-display/900.css'
import '@fontsource/playfair-display/400-italic.css'
import '@fontsource/playfair-display/500-italic.css'
import '@fontsource/playfair-display/600-italic.css'
import '@fontsource/playfair-display/700-italic.css'
import '@fontsource/playfair-display/800-italic.css'
import '@fontsource/playfair-display/900-italic.css'
import '@fontsource/museomoderno/500.css'
import '@fontsource/museomoderno/600.css'
import '@fontsource/fraunces/100.css'
import '@fontsource/fraunces/200.css'
import '@fontsource/fraunces/300.css'
import '@fontsource/fraunces/400.css'
import '@fontsource/fraunces/500.css'
import '@fontsource/fraunces/600.css'
import '@fontsource/fraunces/700.css'
import '@fontsource/fraunces/800.css'
import '@fontsource/fraunces/900.css'
import '@fontsource/fraunces/100-italic.css'
import '@fontsource/fraunces/200-italic.css'
import '@fontsource/fraunces/300-italic.css'
import '@fontsource/fraunces/400-italic.css'
import '@fontsource/fraunces/500-italic.css'
import '@fontsource/fraunces/600-italic.css'
import '@fontsource/fraunces/700-italic.css'
import '@fontsource/fraunces/800-italic.css'
import '@fontsource/fraunces/900-italic.css'
import '@fontsource/cormorant-garamond/300.css'
import '@fontsource/cormorant-garamond/400.css'
import '@fontsource/cormorant-garamond/500.css'
import '@fontsource/cormorant-garamond/600.css'
import '@fontsource/cormorant-garamond/700.css'
import '@fontsource/cormorant-garamond/300-italic.css'
import '@fontsource/cormorant-garamond/400-italic.css'
import '@fontsource/cormorant-garamond/500-italic.css'
import '@fontsource/cormorant-garamond/600-italic.css'
import '@fontsource/cormorant-garamond/700-italic.css'
import '@fontsource/dm-serif-display/400.css'
import '@fontsource/dm-serif-display/400-italic.css'
import '@fontsource/bodoni-moda/400.css'
import '@fontsource/bodoni-moda/500.css'
import '@fontsource/bodoni-moda/600.css'
import '@fontsource/bodoni-moda/700.css'
import '@fontsource/bodoni-moda/800.css'
import '@fontsource/bodoni-moda/900.css'
import '@fontsource/bodoni-moda/400-italic.css'
import '@fontsource/bodoni-moda/500-italic.css'
import '@fontsource/bodoni-moda/600-italic.css'
import '@fontsource/bodoni-moda/700-italic.css'
import '@fontsource/bodoni-moda/800-italic.css'
import '@fontsource/bodoni-moda/900-italic.css'
import '@fontsource/bebas-neue/400.css'
import '@fontsource/anton/400.css'
import '@fontsource/oswald/200.css'
import '@fontsource/oswald/300.css'
import '@fontsource/oswald/400.css'
import '@fontsource/oswald/500.css'
import '@fontsource/oswald/600.css'
import '@fontsource/oswald/700.css'
import '@fontsource/league-gothic/400.css'
import '@fontsource/big-shoulders-display/100.css'
import '@fontsource/big-shoulders-display/200.css'
import '@fontsource/big-shoulders-display/300.css'
import '@fontsource/big-shoulders-display/400.css'
import '@fontsource/big-shoulders-display/500.css'
import '@fontsource/big-shoulders-display/600.css'
import '@fontsource/big-shoulders-display/700.css'
import '@fontsource/big-shoulders-display/800.css'
import '@fontsource/big-shoulders-display/900.css'
import '@fontsource/archivo-black/400.css'
import '@fontsource/museomoderno/100.css'
import '@fontsource/museomoderno/200.css'
import '@fontsource/museomoderno/300.css'
import '@fontsource/museomoderno/500.css'
import '@fontsource/museomoderno/600.css'
import '@fontsource/museomoderno/900.css'
import '@fontsource/shrikhand/400.css'
import '@fontsource/alfa-slab-one/400.css'
import '@fontsource/bricolage-grotesque/200.css'
import '@fontsource/bricolage-grotesque/300.css'
import '@fontsource/bricolage-grotesque/400.css'
import '@fontsource/bricolage-grotesque/500.css'
import '@fontsource/bricolage-grotesque/600.css'
import '@fontsource/bricolage-grotesque/700.css'
import '@fontsource/bricolage-grotesque/800.css'
import '@fontsource/abril-fatface/400.css'
import '@fontsource/caveat/400.css'
import '@fontsource/caveat/500.css'
import '@fontsource/caveat/600.css'
import '@fontsource/caveat/700.css'
import '@fontsource/dancing-script/400.css'
import '@fontsource/dancing-script/500.css'
import '@fontsource/dancing-script/600.css'
import '@fontsource/dancing-script/700.css'
import '@fontsource/pacifico/400.css'
import '@fontsource/great-vibes/400.css'
import '@fontsource/sacramento/400.css'
import '@fontsource/kaushan-script/400.css'
import '@fontsource/allura/400.css'
import '@fontsource/parisienne/400.css'
import '@fontsource/satisfy/400.css'
import '@fontsource/yellowtail/400.css'
import '@fontsource/homemade-apple/400.css'
import '@fontsource/permanent-marker/400.css'
import '@fontsource/dm-mono/300.css'
import '@fontsource/dm-mono/400.css'
import '@fontsource/dm-mono/500.css'
@@ -0,0 +1,79 @@
import { act, renderHook } from '@testing-library/react';
import { blankBook, bookTextElementSchema, type BookDocument, type BookElement, type BookSpread } from '@trek/shared';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { useStudioStore } from '../../store/studioStore';
import { bookSample, faceSpec, useWarmBookFaces, warmBookFaces } from './bookFontWarm';
/**
* The open book's faces go into the offline cache as it opens
* (FE-STUDIO-FONTWARM): each face it uses is asked for once, with the book's
* own characters, and a face that does not load costs nothing.
*/
const frame = { x: 10, y: 10, w: 80, h: 20 };
const text = (id: string, words: string, over: Record<string, unknown> = {}) =>
bookTextElementSchema.parse({ id, kind: 'text', frame, text: words, ...over }) as BookElement;
function book(elements: BookElement[]): BookDocument {
const doc = blankBook({ title: 'Kraków', newId: (p) => `${p}-x` });
const [cover, ...rest] = doc.spreads as [BookSpread, ...BookSpread[]];
return { ...doc, spreads: [{ ...cover, elements }, ...rest] };
}
afterEach(() => {
useStudioStore.setState({ doc: null });
});
describe('the faces of a book', () => {
it('FE-STUDIO-FONTWARM-001: samples each character of the book once, the title and the figures with it', () => {
const sample = bookSample(book([text('t1', 'Łódź Łódź'), text('t2', ' ')]));
expect(sample).toContain('Ł');
expect(sample).toContain('ó');
expect(sample).toContain('K');
expect(sample.startsWith('0123456789')).toBe(true);
expect(new Set(sample).size).toBe(sample.length);
expect(sample).not.toContain(' ');
});
it('FE-STUDIO-FONTWARM-002: names a face the way document.fonts reads it', () => {
expect(faceSpec({ font: 'serif', weight: 700, italic: true })).toBe('italic 700 16px "Lora"');
expect(faceSpec({ font: 'caveat', weight: 400, italic: false })).toBe('400 16px "Caveat"');
});
it('FE-STUDIO-FONTWARM-003: asks for every face once, counts the ones that loaded and never rejects', async () => {
const doc = book([
text('t1', 'Porto', { font: 'caveat', weight: 700 }),
text('t2', 'Douro', { font: 'serif', italic: true }),
]);
const load = vi.fn(async (spec: string, _text?: string) => (spec.includes('Caveat') ? [{} as FontFace] : []));
expect(await warmBookFaces(doc, { load })).toBe(1);
const specs = load.mock.calls.map(([spec]) => spec);
expect(specs).toEqual(expect.arrayContaining(['700 16px "Caveat"', 'italic 400 16px "Lora"']));
expect(load.mock.calls[0]?.[1]).toContain('P');
const broken = vi.fn(async () => {
throw new Error('offline');
});
expect(await warmBookFaces(doc, { load: broken })).toBe(0);
expect(await warmBookFaces(doc, undefined)).toBe(0);
});
it('FE-STUDIO-FONTWARM-004: warms when the set of faces changes, not on every edit of the words', async () => {
const load = vi.fn(async () => [] as FontFace[]);
Object.defineProperty(document, 'fonts', { configurable: true, value: { load } });
const doc = book([text('t1', 'Porto', { font: 'anton' })]);
act(() => useStudioStore.setState({ doc }));
renderHook(() => useWarmBookFaces());
await act(async () => {});
const first = load.mock.calls.length;
expect(first).toBeGreaterThan(0);
const retyped = book([text('t1', 'Porto, again', { font: 'anton' })]);
await act(async () => useStudioStore.setState({ doc: retyped }));
expect(load.mock.calls.length).toBe(first);
const another = book([text('t1', 'Porto', { font: 'anton' }), text('t2', 'Lisboa', { font: 'vibes' })]);
await act(async () => useStudioStore.setState({ doc: another }));
expect(load.mock.calls.length).toBeGreaterThan(first);
});
});
@@ -0,0 +1,64 @@
import { BOOK_FONT_FACES, bookFacesUsed, type BookDocument, type BookFaceUse } from '@trek/shared';
import { useEffect, useMemo } from 'react';
import { useStudioStore } from '../../store/studioStore';
/**
* The faces of the open book, loaded as soon as it opens, so it reads in its
* own type offline as well.
*
* The service worker installs the latin files of the seven families the book
* shipped with (vite.config.js); every other face is cached by its runtime
* rule the first time it is fetched. A face the browser only fetches once
* text is drawn in it would be cached only for the pages someone happened to
* look at, so a book opened online and read offline later would show its
* third chapter in the fallback. Asking for every face the book uses, with the
* characters it sets, fetches each one now, through the worker, into that
* cache: a face nobody uses is never downloaded.
*/
/** The book's own characters, for asking the right subsets of each face: its words, its title, the figures. */
export function bookSample(doc: BookDocument): string {
const seen = new Set<string>('0123456789');
const take = (s: string) => {
for (const ch of s) if (ch.trim()) seen.add(ch);
};
take(doc.title);
for (const spread of doc.spreads) {
for (const el of spread.elements) if (el.kind === 'text') take(el.text);
}
// A face's subsets are chosen by its unicode ranges, so one character of each is enough; the cap keeps it short.
return [...seen].slice(0, 512).join('');
}
/** One face as the CSS font shorthand `document.fonts.load` takes. */
export function faceSpec(use: BookFaceUse): string {
const family = BOOK_FONT_FACES[use.font].name;
return `${use.italic ? 'italic ' : ''}${use.weight} 16px "${family}"`;
}
type FontLoader = Pick<FontFaceSet, 'load'>;
/** Fetch every face the book needs; resolves with how many loaded, never rejects. */
export async function warmBookFaces(
doc: BookDocument,
fonts: FontLoader | undefined = globalThis.document?.fonts
): Promise<number> {
if (!fonts) return 0;
const sample = bookSample(doc);
const loads = await Promise.allSettled(bookFacesUsed(doc).map((use) => fonts.load(faceSpec(use), sample)));
return loads.filter((r) => r.status === 'fulfilled' && r.value.length > 0).length;
}
/**
* Warms the faces of the book the Studio holds whenever the set of faces it
* uses changes; typing into a text does not, so an edit costs nothing here.
*/
export function useWarmBookFaces(): void {
const doc = useStudioStore((s) => s.doc);
const key = useMemo(() => (doc ? bookFacesUsed(doc).map(faceSpec).sort().join('|') : ''), [doc]);
useEffect(() => {
const current = useStudioStore.getState().doc;
// A face that will not load is drawn in its fallback, which the picker already shows; nothing to tell anyone.
if (key && current) void warmBookFaces(current);
}, [key]);
}
+38 -105
View File
@@ -1,118 +1,51 @@
import {
BOOK_FONT_CATEGORIES, BOOK_FONT_FACES, BOOK_FONTS_IDS, bookFontHasItalic, bookFontHasWeight, bookLighterWeight,
nearestBookWeight,
type BookFontCategory, type BookFontFace, type BookFontFamily,
} from '@trek/shared'
/**
* The book's typefaces.
* The book's typefaces, as the Studio draws them.
*
* ── Why this file exists ──────────────────────────────────────────────────
*
* The font stack used to name Georgia for its serif. Georgia is a system font:
* it is on most desktops and on no Linux container, so the print renderer would
* quietly substitute something else and a book proofread in one typeface would
* print in another. The existing Journey PDF export has the same bug today — it
* asks for Inter while only Poppins, Geist and MuseoModerno are bundled.
* print in another.
*
* So every family here is self-hosted through @fontsource, all of them OFL, and
* So every family is self-hosted through @fontsource, OFL or Apache 2.0, and
* every stack ends in a generic rather than in another named font nobody
* shipped. What the editor draws is what the renderer has.
*
* The faces themselves are loaded next door in bookFontFaces.ts. A family named
* here and not imported there falls back to exactly the system font this file
* was written against, which is how five of the seven shipped (#2183).
*
* ── Why these seven ───────────────────────────────────────────────────────
*
* A photo book needs more than one voice and fewer than a menu. Two workhorse
* sans faces, three serifs across the range from bookish to high-contrast, and
* two display faces for a cover. Anything past that is a font picker rather
* than a design decision.
* The catalogue itself (names, stacks, weights, italics, roles) lives in
* @trek/shared (book-fonts.data.ts), because the findings, the design engine
* and the assistant read the same families. This file only gives the Studio
* its view of it; the faces are loaded next door in bookFontFaces.ts.
*/
export interface BookFont {
export type BookFontId = BookFontFamily
export interface BookFont extends BookFontFace {
id: BookFontId
/** What it is called, shown as itself in the picker. */
name: string
/** The CSS stack. Ends generic — never in a font that is not bundled. */
stack: string
/** Where it belongs, for grouping the picker. */
kind: 'sans' | 'serif' | 'display'
/**
* Weights actually loaded. Asking for 700 on a family that ships one weight
* gets a synthesised bold, which prints as a smeared version of the regular.
*/
weights: number[]
}
export type BookFontId =
| 'sans' | 'serif' | 'display'
| 'inter' | 'garamond' | 'playfair' | 'bebas'
/**
* `sans`, `serif` and `display` keep their names because documents already
* contain them — the three original slots, now pointing at bundled families
* rather than at whatever the machine happened to have.
*/
export const BOOK_FONTS: Record<BookFontId, BookFont> = {
sans: {
id: 'sans',
name: 'Poppins',
stack: '"Poppins", system-ui, sans-serif',
kind: 'sans',
weights: [400, 500, 600, 700],
},
inter: {
id: 'inter',
name: 'Inter',
stack: '"Inter", system-ui, sans-serif',
kind: 'sans',
weights: [400, 500, 600, 700],
},
serif: {
id: 'serif',
name: 'Lora',
stack: '"Lora", Georgia, serif',
kind: 'serif',
weights: [400, 500, 600, 700],
},
garamond: {
id: 'garamond',
name: 'EB Garamond',
stack: '"EB Garamond", Georgia, serif',
kind: 'serif',
weights: [400, 500, 600, 700],
},
playfair: {
id: 'playfair',
name: 'Playfair Display',
stack: '"Playfair Display", Georgia, serif',
kind: 'serif',
weights: [400, 500, 600, 700],
},
display: {
id: 'display',
name: 'MuseoModerno',
stack: '"MuseoModerno", "Poppins", system-ui, sans-serif',
kind: 'display',
weights: [400, 500, 600, 700],
},
bebas: {
id: 'bebas',
name: 'Bebas Neue',
stack: '"Bebas Neue", Impact, sans-serif',
kind: 'display',
// One weight only. Asking for bold gets a synthesised one, which is why
// the inspector greys the weights this family does not have.
weights: [400],
},
}
export const BOOK_FONTS = Object.fromEntries(
BOOK_FONTS_IDS.map(id => [id, { id, ...BOOK_FONT_FACES[id] }]),
) as unknown as Record<BookFontId, BookFont>
// Geist Sans is deliberately absent: it is TREK's own subtext face, part of the
// app's voice rather than the book's, and a book set in the interface font
// reads as a screenshot of the app.
/** The picker's order: workhorses first, display last. */
export const BOOK_FONT_ORDER: BookFontId[] = [
'sans', 'inter',
'serif', 'garamond', 'playfair',
'display', 'bebas',
]
/** The picker's order: by category (sans first, mono last), the catalogue's order within one. */
export const BOOK_FONT_ORDER: BookFontId[] = BOOK_FONT_CATEGORIES.flatMap(category =>
BOOK_FONTS_IDS.filter(id => BOOK_FONT_FACES[id].category === category))
/** The families of one picker group, in picker order. */
export function fontsIn(category: BookFontCategory): BookFontId[] {
return BOOK_FONT_ORDER.filter(id => BOOK_FONTS[id].category === category)
}
/**
* The CSS stack for a font id.
@@ -126,20 +59,20 @@ export function fontStack(id: string): string {
}
/** Whether a family actually ships the weight being asked for. */
export function hasWeight(id: string, weight: number): boolean {
const font = BOOK_FONTS[id as BookFontId]
return font ? font.weights.includes(weight) : true
}
export const hasWeight = bookFontHasWeight
/** Whether a family has a real italic at that weight, rather than the browser's slant. */
export const hasItalic = bookFontHasItalic
/**
* The nearest weight a family really has.
*
* A synthesised bold is a smeared regular in print, so a family with one weight
* gets that weight rather than a request the renderer has to fake.
* gets that weight rather than a request the renderer has to fake. The
* renderer draws every element through this as well, so a book whose weight
* was set before its family changed still prints in a face that exists.
*/
export function nearestWeight(id: string, weight: number): number {
const font = BOOK_FONTS[id as BookFontId]
if (!font || font.weights.includes(weight)) return weight
return font.weights.reduce((best, w) =>
(Math.abs(w - weight) < Math.abs(best - weight) ? w : best), font.weights[0])
}
export const nearestWeight = nearestBookWeight
/** The lighter weight a travel element sets beside its figures, one the family has. */
export const lighterWeight = bookLighterWeight
@@ -0,0 +1,47 @@
import { BOOK_FONT_CATEGORIES, type BookFontCategory, type BookWeight } from '@trek/shared';
import { BOOK_FONTS, fontsIn, hasItalic, nearestWeight, type BookFontId } from './bookFonts';
/**
* The type controls' decisions, apart from their markup: which families a
* search finds, the weight a newly picked family is set at, and what the row
* and the italic button say. StudioFontPicker.tsx and StudioTypeControls.tsx
* draw them.
*/
export type FontT = (key: string, params?: Record<string, string | number>) => string;
export interface FontPick {
font: BookFontId;
weight: BookWeight;
}
/** The family, its weight moved onto one the new family has. */
export function pickFont(id: BookFontId, weight: number): FontPick {
// A family that does not ship this weight would render a synthesised bold,
// a smeared regular in print, so the weight moves to the nearest one it has.
return { font: id, weight: nearestWeight(id, weight) as BookWeight };
}
/** The families that match a search, by name, id or group, in picker order. */
export function matchFonts(query: string, groupName: (c: BookFontCategory) => string): BookFontId[] {
const q = query.trim().toLowerCase();
return BOOK_FONT_CATEGORIES.flatMap((category) => {
const group = groupName(category).toLowerCase();
return fontsIn(category).filter(
(id) => !q || BOOK_FONTS[id].name.toLowerCase().includes(q) || id.includes(q) || group.includes(q)
);
});
}
/** The weights a family has, as its row says them: one number, or the first and the last. */
export function weightSpan(id: BookFontId, t: FontT): string {
const ws = BOOK_FONTS[id].weights;
const first = ws[0] ?? 400;
const last = ws[ws.length - 1] ?? first;
return first === last ? String(first) : t('journey.studio.fonts.range', { from: first, to: last });
}
/** The italic button's words: plain where the family has a real italic, the reason where the browser slants it. */
export function italicTitle(font: string, weight: number, t: FontT): string {
return hasItalic(font, nearestWeight(font, weight)) ? t('journey.studio.italic') : t('journey.studio.italicSlanted');
}
@@ -1,4 +1,5 @@
import { ASSISTANT_PAGE_IMAGE, type BookPageSetup, type BookSpread } from '@trek/shared';
import { snapshotFontCss } from './snapshotFonts';
/**
* One Studio page as a JPEG, for the assistant to look at (journey-studio.md
@@ -126,6 +127,8 @@ export async function snapshotSpread(
hiddenPhotoIds: ReadonlySet<number>
): Promise<PageSnapshot | null> {
await picturesLoaded(root, hiddenPhotoIds);
// Only the faces the page draws travel with it (snapshotFonts.ts); without any, the library looks for itself.
const fontCss = await snapshotFontCss(root);
// A single page is drawn up to the long edge too: a larger scale renders the page sharper, it stretches no pixels.
const scale = ASSISTANT_PAGE_IMAGE.longEdge / Math.max(size.width, size.height);
const { domToBlob } = await import('modern-screenshot');
@@ -137,6 +140,7 @@ export async function snapshotSpread(
quality: ASSISTANT_PAGE_IMAGE.jpegQuality,
filter: (node) => keepNode(node, hiddenPhotoIds),
timeout: LOAD_TIMEOUT_MS,
...(fontCss ? { font: { cssText: fontCss } } : {}),
fetch: { requestInit: { credentials: 'same-origin', cache: 'force-cache' } },
});
if (image.size > ASSISTANT_PAGE_IMAGE.maxBytes) return null;
@@ -0,0 +1,190 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
coversAny,
cssWeight,
faceRulesOf,
faceUsesOf,
parseFaceRule,
parseUnicodeRange,
pickFaceRules,
snapshotFontCss,
type FaceRule,
} from './snapshotFonts';
/**
* The faces a page snapshot carries (FE-STUDIO-SNAPFONT): what the page draws
* is read off the DOM, the browser's choice of rule is repeated, and only the
* faces it would pick go into the image, each with its file inline.
*/
const BASE = 'https://trek.example/assets/app.css';
const LATIN = 'U+0000-00FF, U+0131, U+0152-0153';
const EXT = 'U+0100-02BA, U+1E00-1E9F';
const rule = (family: string, weight: number, italic: boolean, range: string, file: string): FaceRule => ({
family,
weight,
italic,
unicodeRange: range,
url: `https://trek.example/assets/${file}`,
});
const RULES = [
rule('Lora', 400, false, LATIN, 'lora-latin-400-normal.woff2'),
rule('Lora', 400, false, EXT, 'lora-latin-ext-400-normal.woff2'),
rule('Lora', 700, false, LATIN, 'lora-latin-700-normal.woff2'),
rule('Lora', 400, true, LATIN, 'lora-latin-400-italic.woff2'),
rule('Caveat', 400, false, LATIN, 'caveat-latin-400-normal.woff2'),
rule('Anton', 400, false, LATIN, 'anton-latin-400-normal.woff2'),
];
const chars = (s: string) => new Set([...s].map((c) => c.codePointAt(0) ?? 0));
const files = (picked: FaceRule[]) => picked.map((r) => r.url.split('/').pop()).sort();
function page(html: string): HTMLElement {
const root = document.createElement('div');
root.innerHTML = html;
document.body.appendChild(root);
return root;
}
afterEach(() => {
document.body.innerHTML = '';
});
describe('reading a rule', () => {
it('FE-STUDIO-SNAPFONT-001: reads family, weight, slant, range and the woff2 file of an @font-face rule', () => {
const css =
"@font-face { font-family: 'Lora'; font-style: italic; font-display: swap; font-weight: 700; " +
'src: url(./files/lora-latin-700-italic.woff2) format("woff2"), url(./files/lora-latin-700-italic.woff) format("woff"); ' +
`unicode-range: ${LATIN}; }`;
expect(parseFaceRule(css, BASE)).toEqual({
family: 'Lora',
weight: 700,
italic: true,
unicodeRange: LATIN,
url: 'https://trek.example/assets/files/lora-latin-700-italic.woff2',
});
const plain = '@font-face { font-family: "Anton"; src: url("/assets/anton.woff") format("woff"); }';
expect(parseFaceRule(plain, BASE)).toMatchObject({
weight: 400,
italic: false,
unicodeRange: '',
url: 'https://trek.example/assets/anton.woff',
});
expect(parseFaceRule('.x { color: red; }', BASE)).toBeNull();
expect(parseFaceRule('@font-face { font-family: "NoFile"; }', BASE)).toBeNull();
expect(parseFaceRule('@font-face { src: url(a.woff2); }', BASE)).toBeNull();
});
it('FE-STUDIO-SNAPFONT-002: reads weights and unicode ranges as CSS does', () => {
expect([cssWeight('bold'), cssWeight('normal'), cssWeight('300'), cssWeight('5000')]).toEqual([700, 400, 300, 400]);
expect(parseUnicodeRange('U+0000-00FF, U+0131, U+4??')).toEqual([
[0, 0xff],
[0x131, 0x131],
[0x400, 0x4ff],
]);
expect(parseUnicodeRange('U+zz, ')).toEqual([]);
expect(coversAny(LATIN, chars('Lisboa'))).toBe(true);
expect(coversAny(EXT, chars('Lisboa'))).toBe(false);
expect(coversAny(EXT, chars('Łódź'))).toBe(true);
expect(coversAny('', chars('anything'))).toBe(true);
});
});
describe('choosing the faces', () => {
it('FE-STUDIO-SNAPFONT-003: picks one rule per subset the text reaches, at the weight and slant it is set in', () => {
const uses = new Map([
['lora|700|false', chars('Porto')],
['caveat|400|false', chars('travel')],
]);
expect(files(pickFaceRules(RULES, uses))).toEqual(['caveat-latin-400-normal.woff2', 'lora-latin-700-normal.woff2']);
// Polish needs the extended subset beside the basic one.
const polish = new Map([['lora|400|false', chars('Kraków Łódź')]]);
expect(files(pickFaceRules(RULES, polish))).toEqual([
'lora-latin-400-normal.woff2',
'lora-latin-ext-400-normal.woff2',
]);
});
it('FE-STUDIO-SNAPFONT-004: falls back the way the browser does: the nearest weight, the upright face, nothing for an unknown family', () => {
expect(files(pickFaceRules(RULES, new Map([['lora|600|false', chars('a')]])))).toEqual([
'lora-latin-700-normal.woff2',
]);
expect(files(pickFaceRules(RULES, new Map([['lora|400|true', chars('a')]])))).toEqual([
'lora-latin-400-italic.woff2',
]);
expect(files(pickFaceRules(RULES, new Map([['anton|400|true', chars('a')]])))).toEqual([
'anton-latin-400-normal.woff2',
]);
expect(pickFaceRules(RULES, new Map([['georgia|400|false', chars('a')]]))).toEqual([]);
});
});
describe('reading the page', () => {
it('FE-STUDIO-SNAPFONT-005: reads every face the text under the root is set in, with its characters', () => {
const root = page(
'<p style="font-family: \'Lora\', Georgia, serif; font-weight: 700">Porto</p>' +
'<svg><text style="font-family: Caveat, cursive; font-style: italic">ab</text></svg>' +
'<p style="font-family: Lora; font-weight: bold">Té</p>' +
'<p style="font-family: Anton"> </p>'
);
const uses = faceUsesOf(root);
expect([...uses.keys()].sort()).toEqual(['caveat|400|true', 'lora|700|false']);
expect(uses.get('lora|700|false')).toEqual(chars('PortoTé'));
});
it('FE-STUDIO-SNAPFONT-006: reads the face rules of the stylesheets it may read, inside grouping rules too', () => {
const face = (family: string) => ({
cssText: `@font-face { font-family: "${family}"; src: url(/assets/${family}.woff2) format("woff2"); }`,
});
const fake = {
baseURI: 'https://trek.example/',
styleSheets: [
{
href: null,
cssRules: [face('Lora'), { cssText: '.x{}' }, { cssText: '@media print {}', cssRules: [face('Anton')] }],
},
{
href: 'https://cdn.example/a.css',
get cssRules(): never {
throw new DOMException('cross origin', 'SecurityError');
},
},
],
} as unknown as Document;
expect(faceRulesOf(fake).map((r) => [r.family, r.url])).toEqual([
['Lora', 'https://trek.example/assets/Lora.woff2'],
['Anton', 'https://trek.example/assets/Anton.woff2'],
]);
});
});
describe('the snapshot css', () => {
it('FE-STUDIO-SNAPFONT-007: inlines exactly the faces the page draws, and leaves out one that will not load', async () => {
const root = page(
'<p style="font-family: Lora; font-weight: 700">Porto</p><p style="font-family: Caveat">travel</p>'
);
const load = vi.fn(async (url: string) =>
url.includes('caveat') ? null : new Blob(['font'], { type: 'font/woff2' })
);
const css = await snapshotFontCss(root, load, RULES);
expect(load.mock.calls.map(([url]) => url.split('/').pop()).sort()).toEqual([
'caveat-latin-400-normal.woff2',
'lora-latin-700-normal.woff2',
]);
expect(css).toContain('@font-face{font-family:"Lora";font-style:normal;font-weight:700;unicode-range:U+0000-00FF');
expect(css).toContain('src:url(data:font/woff2;base64,');
expect(css).not.toContain('Caveat');
});
it('FE-STUDIO-SNAPFONT-008: answers null when the page draws no bundled face or none of its files load, so the library looks for itself', async () => {
const root = page('<p style="font-family: Georgia">Porto</p>');
expect(await snapshotFontCss(root, vi.fn(), RULES)).toBeNull();
const lora = page('<p style="font-family: Lora">Porto</p>');
const failing = vi.fn(async () => {
throw new Error('offline');
});
expect(await snapshotFontCss(lora, failing, RULES)).toBeNull();
});
});
@@ -0,0 +1,233 @@
/**
* The typefaces a page snapshot for the assistant carries, and only those.
*
* modern-screenshot draws the page as an SVG image, and an SVG image cannot
* reach the document's fonts, so every face it shows has to travel inside it.
* Left to itself the library embeds every @font-face rule of every family the
* page names: all nine weights of Montserrat, both styles, every script
* subset, woff and woff2. With thirty four book families that is megabytes of
* fonts per page for a picture whose text uses one weight of two families.
*
* So the snapshot reads what the page really draws (family, weight, slant and
* the characters set in it), picks the one rule per subset the browser would
* pick for that, and hands the library exactly those faces as data URLs. A
* page set in Lora and Caveat embeds the latin files of Lora and Caveat, and
* nothing else.
*/
/** One @font-face rule, as far as the choice of face goes. */
export interface FaceRule {
family: string;
weight: number;
italic: boolean;
/** The CSS unicode-range, or '' for a face that covers everything. */
unicodeRange: string;
/** The woff2 file, else the first file the rule names, resolved to a full URL. */
url: string;
}
/** What the page draws in one face: the characters set in it. */
type FaceUses = Map<string, Set<number>>;
const faceKey = (family: string, weight: number, italic: boolean) => `${family.toLowerCase()}|${weight}|${italic}`;
const unquote = (v: string) => v.trim().replace(/^["']|["']$/g, '');
/** A rule's descriptors by name, read from its text: `font-weight: 700` and the like. */
function descriptors(css: string): Map<string, string> {
const body = css.slice(css.indexOf('{') + 1, css.lastIndexOf('}'));
const out = new Map<string, string>();
for (const part of body.split(';')) {
const at = part.indexOf(':');
if (at > 0) out.set(part.slice(0, at).trim().toLowerCase(), part.slice(at + 1).trim());
}
return out;
}
/** A CSS weight as a number: the keywords as CSS reads them, anything else as 400. */
export function cssWeight(value: string): number {
if (value === 'bold') return 700;
const n = Number.parseInt(value, 10);
return Number.isFinite(n) && n >= 1 && n <= 1000 ? n : 400;
}
/** The file a rule's src names, the woff2 one first, resolved against where the stylesheet came from. */
function sourceOf(src: string, base: string): string | null {
const urls = [...src.matchAll(/url\((["']?)([^"')]+)\1\) ?(?:format\(["']?([\w-]+)["']?\))?/g)];
const pick = urls.find((m) => m[3] === 'woff2') ?? urls[0];
if (!pick?.[2]) return null;
try {
return new URL(pick[2], base).href;
} catch {
// A source no URL can be made of is a face the snapshot does without.
return null;
}
}
/** One @font-face rule read from its text, or null for any other rule or one that names no file. */
export function parseFaceRule(css: string, base: string): FaceRule | null {
if (!css.trimStart().toLowerCase().startsWith('@font-face')) return null;
const d = descriptors(css);
const family = unquote(d.get('font-family') ?? '');
const url = sourceOf(d.get('src') ?? '', base);
if (!family || !url) return null;
return {
family,
weight: cssWeight(d.get('font-weight') || '400'),
italic: /italic|oblique/i.test(d.get('font-style') ?? ''),
unicodeRange: d.get('unicode-range') ?? '',
url,
};
}
/** A unicode-range as code point spans: `U+0000-00FF, U+0131, U+4??` all read. */
export function parseUnicodeRange(range: string): [number, number][] {
return range
.split(',')
.map((part) => part.trim().replace(/^u\+/i, ''))
.filter(Boolean)
.flatMap((part): [number, number][] => {
if (part.includes('?')) {
return [[Number.parseInt(part.replace(/\?/g, '0'), 16), Number.parseInt(part.replace(/\?/g, 'F'), 16)]];
}
const [from, to] = part.split('-');
const a = Number.parseInt(from ?? '', 16);
const b = to === undefined ? a : Number.parseInt(to, 16);
return Number.isFinite(a) && Number.isFinite(b) ? [[a, b]] : [];
});
}
/** Whether a rule's range takes any of the characters; a rule without one takes them all. */
export function coversAny(range: string, chars: ReadonlySet<number>): boolean {
if (!range) return true;
const spans = parseUnicodeRange(range);
for (const c of chars) if (spans.some(([a, b]) => c >= a && c <= b)) return true;
return false;
}
/**
* The rules the browser would draw these uses with: per family and slant, the
* nearest weight it has (the renderer only ever asks for weights a family
* ships, so this is the exact one in practice), an upright face where there is
* no italic, and of those only the subsets whose range the text reaches.
*/
export function pickFaceRules(rules: readonly FaceRule[], uses: FaceUses): FaceRule[] {
const picked = new Map<string, FaceRule>();
for (const [key, chars] of uses) {
const [family = '', weightText = '400', italicText = 'false'] = key.split('|');
const weight = Number(weightText);
const ofFamily = rules.filter((r) => r.family.toLowerCase() === family);
const slanted = ofFamily.filter((r) => r.italic === (italicText === 'true'));
const styled = slanted.length ? slanted : ofFamily.filter((r) => !r.italic);
if (!styled.length) continue;
const nearest = styled.reduce((best, r) =>
Math.abs(r.weight - weight) < Math.abs(best.weight - weight) ? r : best
).weight;
for (const rule of styled) {
if (rule.weight === nearest && coversAny(rule.unicodeRange, chars)) picked.set(rule.url, rule);
}
}
return [...picked.values()];
}
/** The faces the text under `root` is set in, each with the characters it sets. */
export function faceUsesOf(root: Element): FaceUses {
const uses: FaceUses = new Map();
const view = root.ownerDocument.defaultView;
if (!view) return uses;
const walker = root.ownerDocument.createTreeWalker(root, 4 /* NodeFilter.SHOW_TEXT */);
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
const words = node.textContent ?? '';
const parent = node.parentElement;
if (!parent || !words.trim()) continue;
const style = view.getComputedStyle(parent);
const family = unquote(style.fontFamily.split(',')[0] ?? '');
if (!family) continue;
const key = faceKey(family, cssWeight(style.fontWeight), /italic|oblique/.test(style.fontStyle));
const chars = uses.get(key) ?? new Set<number>();
for (const ch of words) {
const code = ch.codePointAt(0);
if (code !== undefined && code > 32) chars.add(code);
}
uses.set(key, chars);
}
return uses;
}
/** Every @font-face rule the document's stylesheets hold, inside grouping rules too. */
export function faceRulesOf(doc: Document): FaceRule[] {
const out: FaceRule[] = [];
const walk = (list: CSSRuleList, base: string) => {
for (const rule of Array.from(list)) {
const face = parseFaceRule(rule.cssText, base);
if (face) out.push(face);
else if ('cssRules' in rule) walk((rule as CSSGroupingRule).cssRules, base);
}
};
for (const sheet of Array.from(doc.styleSheets)) {
let rules: CSSRuleList;
try {
rules = sheet.cssRules;
} catch {
// A stylesheet from another origin cannot be read, and holds no book face.
continue;
}
walk(rules, sheet.href ?? doc.baseURI);
}
return out;
}
/** A file as a data URL. */
function asDataUrl(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result));
reader.onerror = () => reject(reader.error ?? new Error('font read failed'));
reader.readAsDataURL(blob);
});
}
type FetchFont = (url: string) => Promise<Blob | null>;
/** A face file from this server, out of the cache when the page has already drawn it. */
const fetchFont: FetchFont = async (url) => {
if (new URL(url).origin !== window.location.origin) return null;
const res = await fetch(url, {
credentials: 'same-origin',
cache: 'force-cache',
signal: AbortSignal.timeout(8_000),
});
return res.ok ? res.blob() : null;
};
/** One face as a rule the snapshot can carry: its file inline. */
async function inlineRule(rule: FaceRule, load: FetchFont): Promise<string | null> {
try {
const blob = await load(rule.url);
if (!blob) return null;
const range = rule.unicodeRange ? `unicode-range:${rule.unicodeRange};` : '';
const family = rule.family.replace(/"/g, '');
const style = rule.italic ? 'italic' : 'normal';
return `@font-face{font-family:"${family}";font-style:${style};font-weight:${rule.weight};${range}src:url(${await asDataUrl(blob)});}`;
} catch {
// A face that cannot be fetched is drawn in its fallback; the page still goes.
return null;
}
}
/**
* The @font-face rules for the faces the page under `root` draws, with their
* files inline, ready for modern-screenshot's `font.cssText`. Null when there
* is nothing to carry, so the caller lets the library look for itself.
*/
export async function snapshotFontCss(
root: Element,
load: FetchFont = fetchFont,
available: readonly FaceRule[] = faceRulesOf(root.ownerDocument)
): Promise<string | null> {
const rules = pickFaceRules(available, faceUsesOf(root));
if (!rules.length) return null;
const inlined = await Promise.all(rules.map((rule) => inlineRule(rule, load)));
const css = inlined.filter((r): r is string => r !== null);
return css.length ? css.join('\n') : null;
}
+174
View File
@@ -0,0 +1,174 @@
/* ============================================================================
TREK Studio: the typeface picker and the weight slider.
Its own file beside studio.css, which is at its size ceiling. Same rules as
there: every selector is scoped under `.trek-dash` (dashboard.css resets
`button` at a specificity a bare class loses to), and every colour is one of
the dashboard tokens, so the picker follows the user's theme and accent.
The family names are set in their own faces and at the user's text size,
which is why they scale with --fs-scale-body rather than sitting at a fixed
pixel size: a picker is read, and a name too small to read is a name that
tells you nothing about its face.
============================================================================ */
.trek-dash .st-fontpick {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.trek-dash .st-fontpick-current,
.trek-dash .st-fontpick-row {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
min-width: 0;
text-align: start;
color: var(--ink);
transition:
background 0.14s,
border-color 0.14s,
color 0.14s;
}
.trek-dash .st-fontpick-current {
height: 40px;
padding-inline: 10px 8px;
border-radius: 8px;
border: 1px solid var(--line-2);
background: var(--surface);
}
.trek-dash .st-fontpick-current:hover {
border-color: color-mix(in oklch, var(--accent) 40%, var(--line-2));
}
.trek-dash .st-fontpick-current:focus-visible,
.trek-dash .st-fontpick-row:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
.trek-dash .st-fontpick.is-open .st-fontpick-current {
border-color: var(--accent);
}
.trek-dash .st-fontpick-face {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1.25;
font-size: calc(16px * var(--fs-scale-body, 1));
}
.trek-dash .st-fontpick-span {
flex: none;
font-size: calc(11px * var(--fs-scale-caption, 1));
color: var(--ink-3);
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.trek-dash .st-fontpick-caret {
flex: none;
color: var(--ink-3);
transition: transform 0.18s;
}
.trek-dash .st-fontpick.is-open .st-fontpick-caret {
transform: rotate(180deg);
}
/* The open list. It sits in the inspector's flow and scrolls on its own, so
the inspector around it keeps its place. */
.trek-dash .st-fontpick-panel {
display: flex;
flex-direction: column;
border-radius: 12px;
border: 1px solid var(--line);
background: color-mix(in oklch, var(--surface) 70%, transparent);
overflow: hidden;
}
.trek-dash .st-fontpick-search {
margin: 8px 8px 4px;
}
.trek-dash .st-fontpick-list {
max-height: 320px;
overflow-y: auto;
overscroll-behavior: contain;
padding: 2px 4px 6px;
}
.trek-dash .st-fontpick-group + .st-fontpick-group {
margin-top: 4px;
}
.trek-dash .st-fontpick-label {
position: sticky;
top: 0;
z-index: 1;
padding: 8px 8px 4px;
font-size: calc(10.5px * var(--fs-scale-caption, 1));
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--ink-3);
background: color-mix(in oklch, var(--surface) 92%, transparent);
}
.trek-dash .st-fontpick-row {
min-height: 38px;
padding-inline: 8px;
border-radius: 8px;
color: var(--ink-2);
}
.trek-dash .st-fontpick-row:hover {
background: var(--surface);
color: var(--ink);
}
.trek-dash .st-fontpick-row.is-on {
color: var(--ink);
background: color-mix(in oklch, var(--accent) 10%, transparent);
}
.trek-dash .st-fontpick-tick {
flex: none;
width: 14px;
display: grid;
place-items: center;
color: var(--accent);
}
.trek-dash .st-fontpick-none {
padding: 10px 8px;
margin: 0;
}
/* ----------------- weight ----------------- */
.trek-dash .st-weight {
width: 100%;
}
.trek-dash .st-weight > .st-weight-value,
.trek-dash .st-weight > .st-weight-only {
font-size: calc(11.5px * var(--fs-scale-caption, 1));
color: var(--ink-2);
white-space: nowrap;
}
.trek-dash .st-weight > .st-weight-value {
flex: none;
min-width: 84px;
text-align: end;
font-variant-numeric: tabular-nums;
}
.trek-dash .st-weight > .st-weight-only {
flex: 1;
color: var(--ink-3);
}
@media (prefers-reduced-motion: reduce) {
.trek-dash .st-fontpick-caret,
.trek-dash .st-fontpick-current,
.trek-dash .st-fontpick-row {
transition: none;
}
}
+1 -31
View File
@@ -1583,37 +1583,7 @@
flex: none;
}
/* ----------------- font picker ----------------- *
* Each family set in itself. A row of chips reading "Poppins / Lora / Bebas" in
* the interface font tells you their names and nothing about how they look,
* which is the only thing anyone is choosing between.
*/
.trek-dash .st-fonts {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 4px;
}
.trek-dash .st-font {
height: 32px;
padding: 0 8px;
border-radius: 8px;
border: 1px solid var(--line);
background: color-mix(in oklch, var(--surface) 55%, transparent);
color: var(--ink-2);
font-size: 14px;
line-height: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
min-width: 0;
transition: background .14s, border-color .14s, color .14s;
}
.trek-dash .st-font:hover { background: var(--surface); color: var(--ink); }
.trek-dash .st-font.is-on {
color: var(--ink);
border-color: color-mix(in oklch, var(--accent) 50%, transparent);
background: color-mix(in oklch, var(--accent) 10%, transparent);
}
/* The typeface picker lives in studio-fonts.css. */
.trek-dash .st-chip:disabled { opacity: .32; cursor: default; }
/* ----------------- save state ----------------- *
@@ -0,0 +1,93 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
import { APP_FACES, bookFontFile, keepInPrecache, withoutRuntimeFonts } from '../../../bookFontPrecache.js';
/**
* Which font files the service worker installs (FE-SW-FONTS): the app's own
* faces as before, the latin woff2 of the seven book families that shipped
* first, and nothing else of the book's catalogue, which waits in the
* book-fonts runtime cache for a book that uses it.
*/
// Vitest runs with the client package as its root, so cwd is stable here.
const read = (rel: string) => readFileSync(resolve(process.cwd(), rel), 'utf8');
const asset = (name: string) => `assets/${name}`;
describe('reading a font file name', () => {
it('FE-SW-FONTS-001: reads package, subset, weight and style as the build names them, and nothing else as a book face', () => {
expect(bookFontFile(asset('dm-serif-display-latin-ext-400-italic-Ab12_cD3.woff2'))).toEqual({
pkg: 'dm-serif-display',
subset: 'latin-ext',
weight: 400,
italic: true,
ext: 'woff2',
});
expect(bookFontFile(asset('dm-mono-latin-500-normal-xyz.woff'))).toMatchObject({ pkg: 'dm-mono', subset: 'latin' });
expect(bookFontFile(asset('geist-sans-latin-400-normal-abc.woff2'))).toBeNull();
expect(bookFontFile(asset('index-abc.js'))).toBeNull();
expect(bookFontFile(asset('lora.woff2'))).toBeNull();
});
});
describe('the precache', () => {
it('FE-SW-FONTS-002: keeps the faces the app draws, whatever their subset and format', () => {
expect(keepInPrecache(asset('poppins-latin-500-normal-abc.woff'))).toBe(true);
expect(keepInPrecache(asset('poppins-devanagari-700-normal-abc.woff2'))).toBe(true);
expect(keepInPrecache(asset('museomoderno-latin-800-normal-abc.woff2'))).toBe(true);
expect(keepInPrecache(asset('geist-sans-latin-600-normal-abc.woff2'))).toBe(true);
expect(keepInPrecache(asset('index-abc.js'))).toBe(true);
});
it('FE-SW-FONTS-003: keeps only the latin woff2 of the seven book families that shipped first', () => {
expect(keepInPrecache(asset('lora-latin-400-normal-abc.woff2'))).toBe(true);
expect(keepInPrecache(asset('bebas-neue-latin-400-normal-abc.woff2'))).toBe(true);
expect(keepInPrecache(asset('museomoderno-latin-500-normal-abc.woff2'))).toBe(true);
expect(keepInPrecache(asset('lora-latin-400-normal-abc.woff'))).toBe(false);
expect(keepInPrecache(asset('lora-cyrillic-400-normal-abc.woff2'))).toBe(false);
expect(keepInPrecache(asset('lora-latin-400-italic-abc.woff2'))).toBe(false);
expect(keepInPrecache(asset('eb-garamond-latin-800-normal-abc.woff2'))).toBe(false);
expect(keepInPrecache(asset('poppins-latin-900-normal-abc.woff2'))).toBe(false);
});
it('FE-SW-FONTS-004: leaves every file of the new families to the runtime cache', () => {
for (const name of [
'anton-latin-400-normal-abc.woff2',
'caveat-latin-700-normal-abc.woff2',
'fraunces-latin-ext-900-italic-abc.woff',
]) {
expect(keepInPrecache(asset(name)), name).toBe(false);
}
const manifest = [
{ url: asset('index-abc.js'), revision: null },
{ url: asset('anton-latin-400-normal-abc.woff2'), revision: null },
{ url: asset('inter-latin-400-normal-abc.woff2'), revision: null },
];
expect(withoutRuntimeFonts(manifest)).toEqual({ manifest: [manifest[0], manifest[2]], warnings: [] });
});
it('FE-SW-FONTS-005: knows the app faces main.tsx imports, so the chrome never loses one offline', () => {
const imported = [...read('src/main.tsx').matchAll(/@fontsource\/([a-z0-9-]+)\/(\d+)\.css/g)].map(
(m) => `${m[1]}/${m[2]}`
);
const declared = Object.entries(APP_FACES).flatMap(([pkg, weights]) => weights.map((w) => `${pkg}/${w}`));
expect(imported.filter((face) => !face.startsWith('geist-sans/')).sort()).toEqual(declared.sort());
});
it('FE-SW-FONTS-006: is wired into the worker, with the runtime rule the Studio fills', () => {
const config = read('vite.config.js');
expect(config).toContain('manifestTransforms: [withoutRuntimeFonts]');
const rule =
/urlPattern:\s*(\/[^\n]*woff2[^\n]*\/i),\s*\n\s*handler:\s*'CacheFirst',\s*\n\s*options:\s*\{\s*\n\s*cacheName:\s*'book-fonts'/.exec(
config
);
expect(rule).not.toBeNull();
const literal = rule?.[1] ?? '//';
const pattern = new RegExp(literal.slice(1, literal.lastIndexOf('/')), 'i');
expect(pattern.test('https://trek.example/assets/anton-latin-400-normal-abc.woff2')).toBe(true);
expect(pattern.test('https://trek.example/assets/lora-latin-400-normal-abc.woff')).toBe(true);
expect(pattern.test('https://trek.example/assets/index-abc.js')).toBe(false);
expect(pattern.test('https://trek.example/api/photos/1/file.woff2')).toBe(false);
});
});
+19 -9
View File
@@ -23,30 +23,40 @@ const STUDIO = 'src/components/Studio/bookFontFaces.ts'
// Vitest runs with the client package as its root, so cwd is stable here.
const read = (rel: string) => readFileSync(resolve(process.cwd(), rel), 'utf8')
/** Every `@fontsource/<package>/<weight>.css` a file imports. */
/** Every `@fontsource/<package>/<weight>[-italic].css` a file imports. */
function facesIn(rel: string): string[] {
return [...read(rel).matchAll(/@fontsource\/([a-z0-9-]+)\/(\d+)\.css/g)]
return [...read(rel).matchAll(/@fontsource\/([a-z0-9-]+)\/(\d+(?:-italic)?)\.css/g)]
.map(m => `${m[1]}/${m[2]}`)
}
/** @fontsource names its packages after the family, lowercased and hyphenated. */
function faceOf(id: BookFontId, weight: number): string {
return `${BOOK_FONTS[id].name.toLowerCase().replace(/ /g, '-')}/${weight}`
/** A face as the import names it: the family's package, the weight and the italic. */
function faceOf(id: BookFontId, weight: number, italic = false): string {
return `${BOOK_FONTS[id].pkg}/${weight}${italic ? '-italic' : ''}`
}
/** Every face the catalogue declares: each weight upright and each real italic. */
const declared = BOOK_FONTS_IDS.flatMap(id => [
...BOOK_FONTS[id].weights.map(w => faceOf(id, w)),
...BOOK_FONTS[id].italics.map(w => faceOf(id, w, true)),
])
describe('the bundled faces', () => {
it('loads every family the picker offers, in the weights it offers', () => {
const loaded = [...facesIn(APP), ...facesIn(STUDIO)]
for (const face of declared) {
expect(loaded, face).toContain(face)
}
})
/* @fontsource names its packages after the family, lowercased and hyphenated. */
it('takes every family from the package named after it', () => {
for (const id of BOOK_FONTS_IDS) {
for (const weight of BOOK_FONTS[id].weights) {
expect(loaded, `${BOOK_FONTS[id].name} ${weight}`).toContain(faceOf(id, weight))
}
expect(BOOK_FONTS[id].pkg, id).toBe(BOOK_FONTS[id].name.toLowerCase().replace(/ /g, '-'))
}
})
/* A weight nothing can ask for is a download nobody wanted. */
it('loads no weight the registry does not declare', () => {
const declared = BOOK_FONTS_IDS.flatMap(id => BOOK_FONTS[id].weights.map(w => faceOf(id, w)))
for (const face of facesIn(STUDIO)) {
expect(declared, face).toContain(face)
}
+15 -5
View File
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'
import { BOOK_FONTS_IDS, bookTextElementSchema } from '@trek/shared'
import {
BOOK_FONTS, BOOK_FONT_ORDER, fontStack, hasWeight, nearestWeight,
BOOK_FONTS, BOOK_FONT_ORDER, fontStack, fontsIn, hasItalic, hasWeight, nearestWeight,
} from '../../../src/components/Studio/bookFonts'
/**
@@ -21,9 +21,13 @@ describe('the registry', () => {
}
})
it('offers every family in the picker, in one order', () => {
it('offers every family in the picker, in one order, grouped by category', () => {
expect([...BOOK_FONT_ORDER].sort()).toEqual([...BOOK_FONTS_IDS].sort())
expect(new Set(BOOK_FONT_ORDER).size).toBe(BOOK_FONT_ORDER.length)
expect(BOOK_FONT_ORDER[0]).toBe('sans')
expect(BOOK_FONT_ORDER[BOOK_FONT_ORDER.length - 1]).toBe('mono')
expect(fontsIn('script')).toContain('caveat')
expect(fontsIn('script').every(id => BOOK_FONTS[id].category === 'script')).toBe(true)
})
/*
@@ -34,17 +38,17 @@ describe('the registry', () => {
it('ends every stack in a generic family', () => {
for (const id of BOOK_FONTS_IDS) {
const last = BOOK_FONTS[id].stack.split(',').pop()!.trim()
expect(['sans-serif', 'serif', 'monospace'], `${id}: ${last}`).toContain(last)
expect(['sans-serif', 'serif', 'cursive', 'monospace'], `${id}: ${last}`).toContain(last)
}
})
it('names a bundled family first in every stack', () => {
// The first entry is the one that will actually be used, so it is the one
// that has to be self-hosted.
const bundled = ['Poppins', 'Inter', 'Lora', 'EB Garamond', 'Playfair Display', 'MuseoModerno', 'Bebas Neue']
// bookFontFaces.test.ts holds every family to the package it is loaded from.
for (const id of BOOK_FONTS_IDS) {
const first = BOOK_FONTS[id].stack.split(',')[0].replace(/"/g, '').trim()
expect(bundled, `${id}: ${first}`).toContain(first)
expect(first, id).toBe(BOOK_FONTS[id].name)
}
})
@@ -98,6 +102,12 @@ describe('weights', () => {
it('moves to the nearest weight a family really has', () => {
expect(nearestWeight('bebas', 700)).toBe(400)
expect(nearestWeight('sans', 700)).toBe(700)
expect(nearestWeight('oswald', 900)).toBe(700)
})
it('knows which families have a real italic', () => {
expect(hasItalic('garamond', 400)).toBe(true)
expect(hasItalic('sans', 400)).toBe(false)
})
it('leaves an unknown family alone rather than guessing', () => {
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { act, renderHook } from '@testing-library/react'
import type { BookDocument, BookRecord } from '@trek/shared'
import { BOOK_SCHEMA_REV, type BookDocument, type BookRecord } from '@trek/shared'
/**
* Autosaving a Studio book (#1973).
@@ -851,13 +851,13 @@ describe('a book a newer Studio saved', () => {
expect(result.current.state.status).toBe('newer')
})
/* A book of today goes out exactly as it went out before the revision existed. */
it('FE-STUDIO-REV-006: sends a book of today without a revision in it', async () => {
/* A book goes out stamped with the revision of the Studio that wrote it, so an older one cannot save over it. */
it('FE-STUDIO-REV-006: sends a book stamped with the revision of this build', async () => {
const { result } = await mount()
act(() => { result.current.queueSave(doc('a'), 'T') })
await tick()
expect(api.saveBook.mock.calls[0][1].document).not.toHaveProperty('schemaRev')
expect(api.saveBook.mock.calls[0][1].document.schemaRev).toBe(BOOK_SCHEMA_REV)
})
})
+21
View File
@@ -3,6 +3,7 @@ import { defineConfig } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';
import { visualizer } from 'rollup-plugin-visualizer';
import { rtlTextAlias, plyrSpriteAlias } from './rtlTextAlias.js';
import { withoutRuntimeFonts } from './bookFontPrecache.js';
import { readFileSync } from 'node:fs';
// The version this bundle is built as, baked in at build time. The Docker build
@@ -77,6 +78,11 @@ export default defineConfig(({ mode }) => ({
// matching the globs below is fetched at service-worker install by every
// user, whether or not they ever reach the code.
globPatterns: ['**/*.{js,css,html,svg,png,woff,woff2,ttf}'],
// Except most of the book's typefaces: of thirty four families only the
// latin files of the seven the book first shipped with are installed,
// the rest wait in the book-fonts rule below for a book that uses them
// (bookFontPrecache.js).
manifestTransforms: [withoutRuntimeFonts],
// build:analyze drops a treemap next to the app; it must never end up in a
// precache manifest if someone ships that build by accident.
// The assistant's chat (@assistant-ui, about 110 kB gzip) only runs online, so
@@ -92,6 +98,21 @@ export default defineConfig(({ mode }) => ({
/^\/plugin-frame\//,
],
runtimeCaching: [
{
// The book's typefaces the precache leaves out (bookFontPrecache.js):
// fetched the first time a page is set in them, and up front for
// every face of a book the Studio opens (bookFontWarm.ts), so the
// book still reads in its own type offline. Same-origin build
// assets only; the files are content-hashed, so a cached one never
// goes stale. First in the list so no broader rule takes them.
urlPattern: /\/assets\/[^/?#]+\.woff2?(?:\?.*)?$/i,
handler: 'CacheFirst',
options: {
cacheName: 'book-fonts',
expiration: { maxEntries: 600, maxAgeSeconds: 365 * 24 * 60 * 60 },
cacheableResponse: { statuses: [200] },
},
},
{
// Carto map tiles (default provider)
// maxEntries MUST stay >= MAX_TILES in src/sync/tilePrefetcher.ts
+270
View File
@@ -33,14 +33,41 @@
"hasInstallScript": true,
"dependencies": {
"@assistant-ui/react": "0.15.25",
"@fontsource/abril-fatface": "^5.3.0",
"@fontsource/alfa-slab-one": "^5.3.0",
"@fontsource/allura": "^5.3.0",
"@fontsource/anton": "^5.3.0",
"@fontsource/archivo-black": "^5.3.0",
"@fontsource/bebas-neue": "^5.3.0",
"@fontsource/big-shoulders-display": "^5.3.0",
"@fontsource/bodoni-moda": "^5.3.0",
"@fontsource/bricolage-grotesque": "^5.3.0",
"@fontsource/caveat": "^5.3.0",
"@fontsource/cormorant-garamond": "^5.3.0",
"@fontsource/dancing-script": "^5.3.0",
"@fontsource/dm-mono": "^5.3.0",
"@fontsource/dm-serif-display": "^5.3.0",
"@fontsource/eb-garamond": "^5.3.0",
"@fontsource/fraunces": "^5.3.0",
"@fontsource/geist-sans": "^5.3.0",
"@fontsource/great-vibes": "^5.3.0",
"@fontsource/homemade-apple": "^5.3.0",
"@fontsource/inter": "^5.3.0",
"@fontsource/kaushan-script": "^5.3.0",
"@fontsource/league-gothic": "^5.3.0",
"@fontsource/lora": "^5.3.0",
"@fontsource/montserrat": "^5.3.0",
"@fontsource/museomoderno": "^5.3.0",
"@fontsource/oswald": "^5.3.0",
"@fontsource/pacifico": "^5.3.0",
"@fontsource/parisienne": "^5.3.0",
"@fontsource/permanent-marker": "^5.3.0",
"@fontsource/playfair-display": "^5.3.0",
"@fontsource/poppins": "^5.3.0",
"@fontsource/sacramento": "^5.3.0",
"@fontsource/satisfy": "^5.3.0",
"@fontsource/shrikhand": "^5.3.0",
"@fontsource/yellowtail": "^5.3.0",
"@mapbox/mapbox-gl-rtl-text": "^0.4.0",
"@maplibre/maplibre-gl-leaflet": "0.1.4",
"@simplewebauthn/browser": "^13.3.0",
@@ -3366,6 +3393,51 @@
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
"license": "MIT"
},
"node_modules/@fontsource/abril-fatface": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/abril-fatface/-/abril-fatface-5.3.0.tgz",
"integrity": "sha512-voKCJEhGGZNdlk+OS3uFRSDV/HWbs6TAy7qKe9wXq96Uzwadfksyk5eyXLa1T5FkEazBgpHRMRSFBKfA3rbKbg==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/alfa-slab-one": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/alfa-slab-one/-/alfa-slab-one-5.3.0.tgz",
"integrity": "sha512-J/ANFZ7S9CbZClr/QhMjmBtpFmmKipVkEXHj20aurR5uqJPCBChVPJn1/kx6vtrwnfnDY0kQaYSTYasSt4GruA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/allura": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/allura/-/allura-5.3.0.tgz",
"integrity": "sha512-UqloNNVxl03+psvtIXCYuo7/v2mD9XmX2HGiczhK6NmDDwbFJJDjrbHZ5tpNuVXKsMEQPc46tZu3hewYN82/YA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/anton": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/anton/-/anton-5.3.0.tgz",
"integrity": "sha512-OR1D5n124n2XRs66SbX7IjcOSptljEJE8FcDNnlni2y1/M6KpTx7cU2PIWzTSsBj4WFkHPw24On8qw3qkQZuTw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/archivo-black": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/archivo-black/-/archivo-black-5.3.0.tgz",
"integrity": "sha512-7EsTIQ+Blf96ktpzTUpI7msi+u9/AJxM/GZxOSkEubVd1jSTrFSTNxMgfpX/8rQsjZ+19a+qvRbtcTEp5J/72g==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/bebas-neue": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/bebas-neue/-/bebas-neue-5.3.0.tgz",
@@ -3375,6 +3447,78 @@
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/big-shoulders-display": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/big-shoulders-display/-/big-shoulders-display-5.3.0.tgz",
"integrity": "sha512-d4+Tcsq/WfoKeqWfB6wFdeNDsSYYnilJbSNNpf5w53MlWrGHAc9YvkAjC6id6PgFDiGaFKsXfP0RFAQtpt0bog==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/bodoni-moda": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/bodoni-moda/-/bodoni-moda-5.3.0.tgz",
"integrity": "sha512-Wt2XBCHivYxkTP3ydq/Ax+7VshwsOh/6ayA5om2t+yClCkGwLPj2Mi6OnyMANjyLcqDUWs4rlOHnc8SBLf6/pA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/bricolage-grotesque": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/bricolage-grotesque/-/bricolage-grotesque-5.3.0.tgz",
"integrity": "sha512-MdOVb/5in11IfN/IQJOExMuu6AroCIQbirl0yX7NUvKk+h0HYIKfGaVAXRS/gCPil4aFxWhjZnOw28tUwv7tFw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/caveat": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/caveat/-/caveat-5.3.0.tgz",
"integrity": "sha512-eHTfzQxFSW9ABERRLNruHoNJmKed2J7pqTUc5lp4a4POMgXGKpxmWj3d9Hz10kmAg6iuTTLe6UagbA4bnsmfQw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/cormorant-garamond": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/cormorant-garamond/-/cormorant-garamond-5.3.0.tgz",
"integrity": "sha512-weuGsCirGVWBWqpt6YUp0yLThTe4G8YO45noq8wxeJCRvEpq5lFrxNMFSTxcyOyV5k5otzJ8guDzYegdYlcLMQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/dancing-script": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/dancing-script/-/dancing-script-5.3.0.tgz",
"integrity": "sha512-/FFbz4ZCNN+eG2a6phkZB41iKmyCC6rq2blA/kG9OFeI3/tpzLNazND1bBdEnogLhpfg7o4NfauTbEEYSpSUGg==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/dm-mono": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/dm-mono/-/dm-mono-5.3.0.tgz",
"integrity": "sha512-OINjI8C1S/wpchhQxl7njZdMn4+hnDCpQ4YtvvOpKNARo+0J8O1x1IcrChxNjHOhfVv1by8C/FQoy3hXK+C1Ug==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/dm-serif-display": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/dm-serif-display/-/dm-serif-display-5.3.0.tgz",
"integrity": "sha512-ecRclUcYeto9fB7ghkB36H4MtUoaUYFjjornWYYeLCMHzaWEDPk2kIWgZOq0mKBNRxclRSieKcFeLonlMYDTKg==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/eb-garamond": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/eb-garamond/-/eb-garamond-5.3.0.tgz",
@@ -3384,6 +3528,15 @@
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/fraunces": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/fraunces/-/fraunces-5.3.0.tgz",
"integrity": "sha512-LEHTOBiZufQzAvnAe2rZ8ZknbDS28Q9kzwb0L+gZJEmjLGr8hhZ/5NuHXwDuHBWhVXYoiGGXmrb0H6Ko/RrHTg==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/geist-sans": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/geist-sans/-/geist-sans-5.3.0.tgz",
@@ -3393,6 +3546,24 @@
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/great-vibes": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/great-vibes/-/great-vibes-5.3.0.tgz",
"integrity": "sha512-1w60cXzXnC9V4y943po8044O1mqRQBiTTK75h7OpZE+1VQtx+KlAAzoIyEE5KNzu05gUpxaCQg7cbL7ITSwegQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/homemade-apple": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/homemade-apple/-/homemade-apple-5.3.0.tgz",
"integrity": "sha512-awJSYTbSY3SroC8nirEhDauHvERVvm0LI3FpUHsPZXl9Tht1xrqhiI8ro4yf3ROcvQ7CfFJ/2+DLcOHBOXhJKw==",
"license": "Apache-2.0",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/inter": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/inter/-/inter-5.3.0.tgz",
@@ -3402,6 +3573,24 @@
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/kaushan-script": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/kaushan-script/-/kaushan-script-5.3.0.tgz",
"integrity": "sha512-Kdcvr76wOGp2jgKkkmAOETmPcw/a34RU/qcGW2+gSKzkKyr03vEaLWSbSABoVKWuyuoqWoulcmC4571vq3BYvg==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/league-gothic": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/league-gothic/-/league-gothic-5.3.0.tgz",
"integrity": "sha512-gqedetX+UlaiJgLiPnOzWGB1sY3OtNhS8YMjTy2D73AcsagIqpdIizssr1MStcUYf3D/zzanECuXawIgMGZxDg==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/lora": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/lora/-/lora-5.3.0.tgz",
@@ -3411,6 +3600,15 @@
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/montserrat": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/montserrat/-/montserrat-5.3.0.tgz",
"integrity": "sha512-iQPDtZOnmM5ih4JBGaMSXisRap0ixb9bAUw2hDtY7EjVfaqiiNlKtVuJl9XclxUwtwMMHNcWXfQR6zI9x05+Tg==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/museomoderno": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/museomoderno/-/museomoderno-5.3.0.tgz",
@@ -3420,6 +3618,42 @@
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/oswald": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/oswald/-/oswald-5.3.0.tgz",
"integrity": "sha512-16r2aHActe0pH+9FLdk/74/YxXM7HpGak05kAzx3RvSToiJwGvyhv6GvckPz+YuZmvL1nxWbEop2jAXRcXYPRg==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/pacifico": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/pacifico/-/pacifico-5.3.0.tgz",
"integrity": "sha512-bWv0fHR1n36p7scRn+maaEaVeQCOq9yvfVfjyAeUzKrK4Y/3qiRAEj4hJgfxj/sjgZZGkeHyKPrbWdDaZtpCVw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/parisienne": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/parisienne/-/parisienne-5.3.0.tgz",
"integrity": "sha512-YbfjZDYy7FMTVE0HRgejkGX3T5iFfgagOYtAAAymq9GklviFAZ1GqIdlyviNe23TiR20f2K7zxsL4AECtWnkEQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/permanent-marker": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/permanent-marker/-/permanent-marker-5.3.0.tgz",
"integrity": "sha512-ZO/NtYW4SCc/iY8N3dmjWyDITcXJ/vhWZFgnwRcvzwCKKnScMrM/a2/6VHlsjCVuIgmPzNrCFbedEYhv+/jJBg==",
"license": "Apache-2.0",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/playfair-display": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/playfair-display/-/playfair-display-5.3.0.tgz",
@@ -3438,6 +3672,42 @@
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/sacramento": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/sacramento/-/sacramento-5.3.0.tgz",
"integrity": "sha512-KkqN52aTsJ0pSBva/NREqFljs0M1TwMIpNcqdSQc2EKR/mVU1CvM2dazf9eG19rHMTIssjbia83nGG705SlD1w==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/satisfy": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/satisfy/-/satisfy-5.3.0.tgz",
"integrity": "sha512-dQ+Cy85XdwYnwlzWcbkmA2Qkpxam0ZHDaGm/qoGHlyHKRVgM/BJN8RLHpRm31R0REFBQe5Yl8Ke5oTdpcKdPIA==",
"license": "Apache-2.0",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/shrikhand": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/shrikhand/-/shrikhand-5.3.0.tgz",
"integrity": "sha512-AWCCj1oNNpMK5hXfFo4JO5KyLhPrdBmpbA0wyIl4IUB05WTU0CGP2UgGX7Lcq/N8nS2+hcxzCPMSQ1R55FuMPg==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/yellowtail": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/yellowtail/-/yellowtail-5.3.0.tgz",
"integrity": "sha512-atz4CIdbP7otppxRaObJiygnkyJzIuLFpPRjWspXvXhBWLB0sk35cCu5r6gSkDomRtEWakJ8//bWbyBjJbilGg==",
"license": "Apache-2.0",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@hexagon/base64": {
"version": "1.1.28",
"resolved": "https://registry.npmjs.org/@hexagon/base64/-/base64-1.1.28.tgz",
@@ -28,8 +28,8 @@ The energy decides the rest:
- Vary the beats, never three alike in a row; a quiet page for a long story, grids for bursts.
Type scale, in points for a 210 mm page and scaled with the page width:
- Cover title in a display face, 72 to 180 pt, 12 to 30 % of the page height; title to subtitle at least 3:1. For a big cover raise type.display (up to 6.5, about 180 pt); keep type.scale between 0.9 and 1.1 so body stays 9 to 11 pt.
- Date lines in spaced caps, 7 to 9 pt, tracking 0.25 to 0.4; an accent word over a title in the contrasting face (playfair italic or display), 1.2 to 1.6 times its cap height, with contrast, an outline or a shadow.
- Body 9 to 11 pt; captions 6.5 to 8 pt with tracking 0.05 to 0.1; a display face and a body face, two typefaces at most.
- Date lines in spaced caps, 7 to 9 pt, tracking 0.25 to 0.4; an accent word over a title in a script (caveat, pacifico, vibes, marker) or the contrasting face (playfair italic), 1.2 to 1.6 times its cap height, with contrast, an outline or a shadow.
- Body 9 to 11 pt in a face whose role is body; captions 6.5 to 8 pt with tracking 0.05 to 0.1; a display face, a body face and one more at most, a script or a mono line not counted; a family sets only the weights its font id lists.
Look, judge, revise:
- Check every changed page with describe_book_page and the designId, and look at the pages that matter most with preview_book_page and the designId when you can see images; preview the cover at least twice, the first draft and the final one.
- Before every proposal answer silently: Is there one dominant element? Does the title read at thumbnail size? Does the energy match the brief? Is the palette the book's own? Is anything touching or overlapping by accident? Is text on a busy area without contrast? Does the decoration suit the energy? Does the page differ from the one before? Fix what fails with revise_book_design.
+8 -5
View File
@@ -28,7 +28,7 @@ import { MikroORM } from '@mikro-orm/core';
import { Client } from '@modelcontextprotocol/sdk/client/index';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';
import type { INestApplication } from '@nestjs/common';
import { bookWriteResultSchema } from '@trek/shared';
import { BOOK_SCHEMA_REV, bookWriteResultSchema } from '@trek/shared';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
@@ -125,6 +125,9 @@ async function journeyWithBook() {
return { owner, editor, viewer, journey, inner, everyone: [owner.id, editor.id, viewer.id].sort((a, b) => a - b) };
}
/** A revision one past what this build reads. */
const NEWER = BOOK_SCHEMA_REV + 1;
describe('Studio book over MCP and REST', () => {
it('JBE2E-001: an MCP write is what GET reads next, and a viewer is refused in the words a tool answers', async () => {
const { editor, viewer, journey, inner } = await journeyWithBook();
@@ -209,7 +212,7 @@ describe('Studio book over MCP and REST', () => {
.get(`/api/journeys/${journey.id}/book`)
.set('Cookie', authCookie(owner.id));
const row = await findRow(orm, JourneyBooks, { journey: journey.id });
const newer = JSON.stringify({ ...JSON.parse(String(row?.document)), schemaRev: 2 });
const newer = JSON.stringify({ ...JSON.parse(String(row?.document)), schemaRev: NEWER });
await updateRows(orm, JourneyBooks, { journey: journey.id }, { document: newer });
const saved = await request(app.getHttpServer())
@@ -220,7 +223,7 @@ describe('Studio book over MCP and REST', () => {
expect(saved.body).toEqual({
error: 'Book was saved by a newer version of TREK Studio',
code: 'book_schema_newer',
schemaRev: 2,
schemaRev: NEWER,
});
const tool = await callTool(owner.id, 'edit_book_page', {
@@ -249,12 +252,12 @@ describe('Studio book over MCP and REST', () => {
const saved = await request(app.getHttpServer())
.put(`/api/journeys/${journey.id}/book`)
.set('Cookie', authCookie(owner.id))
.send({ title: before.body.book.title, document: { ...document, schemaRev: 2 }, baseVersion: 1 });
.send({ title: before.body.book.title, document: { ...document, schemaRev: NEWER }, baseVersion: 1 });
expect(saved.status).toBe(409);
expect(saved.body).toEqual({
error: 'Book was saved by a newer version of TREK Studio',
code: 'book_schema_newer',
schemaRev: 2,
schemaRev: NEWER,
});
expect(sent()).toEqual([]);
const after = await findRow(orm, JourneyBooks, { journey: journey.id });
@@ -28,6 +28,7 @@ import {
undoReadsOf,
} from '../../../../../../src/nest/assistant/cards/registry';
import {
BOOK_FONTS_IDS,
bookDesignCardSchema,
MAX_CARD_CHARS,
type AssistantChangePreview,
@@ -250,7 +251,11 @@ describe('the designer in the Studio', () => {
// The cover tier carries a big title alone, and the faces named are faces the book has.
expect(BOOK_DESIGN_PROMPT).toContain('type.display (up to 6.5');
expect(BOOK_DESIGN_PROMPT).toContain('type.scale between 0.9 and 1.1');
expect(BOOK_DESIGN_PROMPT).not.toMatch(/script/i);
for (const face of ['caveat', 'pacifico', 'vibes', 'marker', 'playfair']) {
expect(BOOK_FONTS_IDS, face).toContain(face);
expect(BOOK_DESIGN_PROMPT, face).toContain(face);
}
expect(BOOK_DESIGN_PROMPT).toContain('a script or a mono line not counted');
expect(BOOK_DESIGN_PROMPT).toContain('210 mm page and scaled with the page width');
const rubric = BOOK_DESIGN_PROMPT.slice(BOOK_DESIGN_PROMPT.indexOf('answer silently'));
expect(rubric.slice(0, rubric.indexOf('Fix what fails')).match(/\?/g)).toHaveLength(8);
@@ -31,7 +31,7 @@ import {
import { createTestJourneyBooksRepo } from '../../helpers/journey-share-repos';
import { resetTestDb } from '../../helpers/test-db';
import { createTestUnitOfWork, sharedTestOrm, createTestTripsRepo, createTestPlacesRepo } from '../../helpers/test-uow';
import { normalizeBookDocument } from '@trek/shared';
import { BOOK_SCHEMA_REV, normalizeBookDocument } from '@trek/shared';
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -629,6 +629,9 @@ describe('editBook', () => {
* of a server that cannot read the book whole.
*/
describe('format revisions', () => {
/** A revision one past what this build reads. */
const NEWER = BOOK_SCHEMA_REV + 1;
/** A journey whose stored book says it was written by revision `schemaRev`. */
async function storedAt(schemaRev: number) {
const { user } = createUser(testDb);
@@ -646,7 +649,7 @@ describe('format revisions', () => {
thrown instanceof DomainError ? [thrown.getStatus(), thrown.code, thrown.toBody().code] : thrown;
it('JBOOK-011: refuses a save from a writer older than the stored book with 409 and the code, writing and sending nothing', async () => {
const { user, journey } = await storedAt(2);
const { user, journey } = await storedAt(NEWER);
const rec = await recordSends();
try {
const thrown = await catchDomainError(() =>
@@ -655,11 +658,11 @@ describe('format revisions', () => {
expect(refusalOf(thrown)).toEqual([409, 'book_schema_newer', 'book_schema_newer']);
expect(thrown instanceof DomainError && thrown.toBody()).toMatchObject({
error: 'Book was saved by a newer version of TREK Studio',
schemaRev: 2,
schemaRev: NEWER,
});
expect(rec.sent).toEqual([]);
const stored = await books.getBook(journey.id, user.id);
expect([stored?.version, stored?.document.title, stored?.document.schemaRev]).toEqual([1, 'newer', 2]);
expect([stored?.version, stored?.document.title, stored?.document.schemaRev]).toEqual([1, 'newer', NEWER]);
} finally {
rec.restore();
}
@@ -697,7 +700,7 @@ describe('format revisions', () => {
});
it('JBOOK-014: the book tools leave a book this server cannot read whole alone, before any edit runs', async () => {
const { user, journey } = await storedAt(2);
const { user, journey } = await storedAt(NEWER);
const rec = await recordSends();
try {
const edit = vi.fn(() => ({ title: 'T', document: normalizeBookDocument(doc('tool')), result: null }));
@@ -716,7 +719,7 @@ describe('format revisions', () => {
const { user, journey } = await storedAt(1);
const rec = await recordSends();
try {
const ahead = normalizeBookDocument({ ...doc('ahead'), schemaRev: 2 });
const ahead = normalizeBookDocument({ ...doc('ahead'), schemaRev: NEWER });
const thrown = await catchDomainError(() =>
books.editBook(journey.id, user.id, () => ({ title: 'T', document: ahead, result: null })),
);
@@ -34,7 +34,12 @@ import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { bookDesignAnswerSchema, bookDesignApplyResultSchema, type BookDesignAnswer } from '@trek/shared';
import {
BOOK_SCHEMA_REV,
bookDesignAnswerSchema,
bookDesignApplyResultSchema,
type BookDesignAnswer,
} from '@trek/shared';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
@@ -327,7 +332,7 @@ describe('taking a design back', () => {
const applied = await designs.apply(journey.id, owner.id, { designId: answer.design_id });
const revisionId = applied.revision_id ?? 0;
const kept = await findRow(orm, JourneyBookRevisions, { id: revisionId });
const newer = JSON.stringify({ ...JSON.parse(String(kept?.document)), schemaRev: 2 });
const newer = JSON.stringify({ ...JSON.parse(String(kept?.document)), schemaRev: BOOK_SCHEMA_REV + 1 });
await updateRows(orm, JourneyBookRevisions, { id: revisionId }, { document: newer });
t.realtime.reset();
+2 -1
View File
@@ -25,6 +25,7 @@ import {
bookStrokeStyleSchema,
bookTextAlignSchema,
bookTypesetFontSchema,
bookWeightSchema,
} from './book-op-enums';
import { bookElementIdSchema, bookGridIdSchema, bookSpreadIdSchema } from './book-op-ids';
import {
@@ -99,7 +100,7 @@ const PHOTO_PROPS = {
export const TEXT_STYLE_FIELDS = {
font: bookFontIdSchema.optional(),
size: text.size.unwrap().optional(),
weight: text.weight.unwrap().optional(),
weight: bookWeightSchema.optional(),
italic: text.italic.unwrap().optional(),
align: bookTextAlignSchema.optional(),
leading: text.leading.unwrap().optional(),
@@ -140,6 +140,12 @@ describe('book level and the page in words', () => {
const mixOf = (pages: typeof fonts) => bookLevelFindings(bookOf(pages)).filter((f) => f.code === 'font_mix');
expect(mixOf(fonts.slice(0, 3))).toEqual([]);
expect(mixOf(fonts.slice(0, 2))).toEqual([]);
// A script laid over a title and a mono line on a ticket dress a page; they are not a fourth voice.
const dressed = ['caveat', 'mono'].map((font, i) => [
text(`d-${i}`, 'Hi', { x: 230, y: 40, w: 60, h: 10 }, { font }),
]);
expect(mixOf([...fonts.slice(0, 3), ...dressed])).toEqual([]);
expect(mixOf([...fonts, ...dressed])[0]?.message).toMatch(/4 typefaces \(bebas, playfair, sans, serif\)/);
});
it('BOOKQA-010: notes colours outside the book own and the same page three times running', () => {
+12 -14
View File
@@ -1,5 +1,6 @@
import { compareCodeUnits } from '../common/compare';
import { contrastOfLuminance, deltaE, greyLuminance, luminance, parseHex, requiredContrast } from './book-colour';
import { bookFontCountsInMix, bookFontsUsed } from './book-fonts';
import type { BookPhotoInfo } from './book-ops-core';
import { BOOK_OP_LIMITS, type BookFinding } from './book-ops.schema';
import type { BookDocument, BookElement, BookFrame, BookPageSetup, BookPhotoElement, BookSpread } from './book.schema';
@@ -306,16 +307,13 @@ export function designFindings(
return sortBookFindings(ctx.out);
}
/** The typefaces a book is set in: its texts, its travel elements and its page numbers when shown. */
/**
* The typefaces that make a book's voice: its texts, its travel elements and
* its page numbers when shown, leaving out the scripts and mono faces, which
* dress a page rather than set it.
*/
function familiesOf(doc: BookDocument): string[] {
const used = new Set<string>();
for (const spread of doc.spreads) {
for (const el of spread.elements) {
if ('font' in el && (el.kind !== 'text' || el.text.trim())) used.add(el.font);
}
}
if (doc.page.pageNumbers.show) used.add(doc.page.pageNumbers.font);
return [...used].sort(compareCodeUnits);
return bookFontsUsed(doc).filter(bookFontCountsInMix).sort(compareCodeUnits);
}
/** The colours a book paints with: its type and its filled shapes, with how often each is used. */
@@ -342,10 +340,10 @@ function signatureOf(spread: BookSpread): string {
/**
* How many typefaces a book may be set in before it reads as a type sampler:
* a display face, a body face and one more, a script laid over a title or a
* face for figures. Two was the rule while the book had seven faces and no
* scripts, and it told every lively book that set its title apart to stop.
* Once fonts carry roles, script and mono faces will not count towards it.
* a display face, a body face and one more for figures or a subtitle. Two was
* the rule while the book had seven faces and no scripts, and it told every
* lively book that set its title apart to stop. Script and mono faces do not
* count towards it (`bookFontCountsInMix`).
*/
const MAX_BOOK_FAMILIES = 3;
@@ -358,7 +356,7 @@ export function bookLevelFindings(doc: BookDocument): BookFinding[] {
code: 'font_mix',
severity: 'warn',
elementIds: [],
message: `the book is set in ${families.length} typefaces (${families.join(', ')}); keep to three: a display face, a body face and one more`,
message: `the book is set in ${families.length} typefaces (${families.join(', ')}); keep to three: a display face, a body face and one more; scripts and mono faces do not count`,
});
}
const colours = [...coloursOf(doc)].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
+4 -11
View File
@@ -1,4 +1,5 @@
import { bookVisiblePart, sortBookFindings } from './book-findings-design';
import { bookFontFace } from './book-fonts';
import type { BookPhotoInfo } from './book-ops-core';
import type { BookFinding } from './book-ops.schema';
import type { BookElement, BookPageSetup, BookPhotoElement, BookSpread, BookTextElement } from './book.schema';
@@ -66,16 +67,8 @@ export function photoDpi(el: BookPhotoElement, info: BookPhotoInfo | undefined):
return Math.round(25.4 / mmPerPx);
}
/** Average letter width per em at weight 400, per family: measured on story text as the Studio sets each family. */
const LETTER_EM: Record<BookTextElement['font'], number> = {
sans: 0.507,
inter: 0.478,
serif: 0.469,
garamond: 0.383,
playfair: 0.454,
display: 0.492,
bebas: 0.339,
};
/** Average letter width per em at weight 400, per family: the catalogue's measure (book-fonts.data.ts). */
const letterEm = (font: string) => bookFontFace(font)?.letterEm ?? 0.5;
/**
* The headroom on letter width the design engine sizes a text frame with. A
@@ -121,7 +114,7 @@ function wrappedLines(para: string, perLine: number): number {
export function textHeightNeeded(el: BookTextElement, headroom = 1): number {
const sizeMm = (orDefault(el.size, 11) * 25.4) / 72;
const tracking = orDefault(el.tracking, 0);
const letter = sizeMm * ((LETTER_EM[el.font] ?? 0.5) * (el.weight >= 600 ? 1.06 : 1) * headroom + tracking);
const letter = sizeMm * (letterEm(el.font) * (el.weight >= 600 ? 1.06 : 1) * headroom + tracking);
const perLine = Math.max(1, Math.floor(el.frame.w / Math.max(letter, 0.1)));
const lines = el.text.split('\n').reduce((sum, para) => sum + wrappedLines(para.trimEnd(), perLine), 0);
return lines * sizeMm * orDefault(el.leading, 1.45);
+481
View File
@@ -0,0 +1,481 @@
/**
* The typefaces a book may be set in, and what each of them is.
*
* One catalogue for every reader of a book: the schema takes its ids, the
* Studio draws its picker and its stacks from it, the findings count its
* roles, the design engine checks its weights, and the assistant reads the
* same lines in the tool schemas. A family named in one of those places and
* missing from another is how five of the first seven fonts shipped without
* their faces (#2183), so nothing here is copied anywhere else.
*
* Every family is self-hosted through @fontsource and licensed under the SIL
* Open Font License 1.1 or the Apache License 2.0 (the typefaces in NOTICE.md),
* which both allow embedding in a printed or exported book.
*
* This file holds data only, so book.schema.ts can take the ids from it
* without importing the logic in book-fonts.ts.
*/
/** Every weight CSS names. A family offers the ones it really ships. */
export const BOOK_WEIGHTS = [100, 200, 300, 400, 500, 600, 700, 800, 900] as const;
export type BookWeight = (typeof BOOK_WEIGHTS)[number];
/**
* What a family is for, most suited first.
*
* `display` sets a cover title or a poster word, `heading` a page's title,
* `body` running text at 9 to 11 pt. A `script` is laid over a title or a
* photo, a `mono` sets tickets and coordinates. Neither of the last two
* counts towards the faces a book is set in (`font_mix`), because they are
* ornaments of a page rather than its voice.
*/
export const BOOK_FONT_ROLES = ['display', 'heading', 'body', 'script', 'mono'] as const;
export type BookFontRole = (typeof BOOK_FONT_ROLES)[number];
/** The picker's groups, in the order it shows them. */
export const BOOK_FONT_CATEGORIES = ['sans', 'serif', 'elegant', 'condensed', 'retro', 'script', 'mono'] as const;
export type BookFontCategory = (typeof BOOK_FONT_CATEGORIES)[number];
export interface BookFontFace {
/** What it is called, shown as itself in the picker. */
name: string;
/** The CSS stack. Ends in a generic, never in a font that is not bundled. */
stack: string;
/** The @fontsource package the faces come from. */
pkg: string;
category: BookFontCategory;
/** What it suits, the first being what it is for. */
roles: readonly BookFontRole[];
/**
* Weights actually loaded. Asking for 700 on a family that ships one weight
* gets a synthesised bold, which prints as a smeared version of the regular.
*/
weights: readonly BookWeight[];
/** The weights it has a real italic for. Any other italic is the browser's slant. */
italics: readonly BookWeight[];
/**
* Average letter width per em at weight 400, measured on story text from
* the face's own advance widths, for the text measure in book-findings.ts.
*/
letterEm: number;
/** Set in capitals whatever is typed. */
caps?: true;
}
const ALL = BOOK_WEIGHTS;
const ONE = [400] as const;
const MID = [400, 500, 600, 700] as const;
/**
* The families. `sans`, `serif` and `display` are the three the format started
* with and keep their names, because documents already contain them.
*/
export const BOOK_FONT_FACES = {
// ── sans ──
sans: {
name: 'Poppins',
stack: '"Poppins", system-ui, sans-serif',
pkg: 'poppins',
category: 'sans',
roles: ['heading', 'body', 'display'],
weights: ALL,
italics: [],
letterEm: 0.507,
},
inter: {
name: 'Inter',
stack: '"Inter", system-ui, sans-serif',
pkg: 'inter',
category: 'sans',
roles: ['body', 'heading'],
weights: ALL,
italics: [],
letterEm: 0.478,
},
montserrat: {
name: 'Montserrat',
stack: '"Montserrat", system-ui, sans-serif',
pkg: 'montserrat',
category: 'sans',
roles: ['heading', 'body', 'display'],
weights: ALL,
italics: [],
letterEm: 0.507,
},
// ── serif ──
serif: {
name: 'Lora',
stack: '"Lora", Georgia, serif',
pkg: 'lora',
category: 'serif',
roles: ['body', 'heading'],
weights: MID,
italics: MID,
letterEm: 0.469,
},
garamond: {
name: 'EB Garamond',
stack: '"EB Garamond", Georgia, serif',
pkg: 'eb-garamond',
category: 'serif',
roles: ['body', 'heading'],
weights: [400, 500, 600, 700, 800],
italics: [400, 500, 600, 700, 800],
letterEm: 0.383,
},
// ── elegant display serifs ──
playfair: {
name: 'Playfair Display',
stack: '"Playfair Display", Georgia, serif',
pkg: 'playfair-display',
category: 'elegant',
roles: ['display', 'heading'],
weights: [400, 500, 600, 700, 800, 900],
italics: [400, 500, 600, 700, 800, 900],
letterEm: 0.454,
},
fraunces: {
name: 'Fraunces',
stack: '"Fraunces", Georgia, serif',
pkg: 'fraunces',
category: 'elegant',
roles: ['display', 'heading', 'body'],
weights: ALL,
italics: ALL,
letterEm: 0.467,
},
cormorant: {
name: 'Cormorant Garamond',
stack: '"Cormorant Garamond", Georgia, serif',
pkg: 'cormorant-garamond',
category: 'elegant',
roles: ['display', 'heading'],
weights: [300, 400, 500, 600, 700],
italics: [300, 400, 500, 600, 700],
letterEm: 0.393,
},
dmserif: {
name: 'DM Serif Display',
stack: '"DM Serif Display", Georgia, serif',
pkg: 'dm-serif-display',
category: 'elegant',
roles: ['display'],
weights: ONE,
italics: ONE,
letterEm: 0.448,
},
bodoni: {
name: 'Bodoni Moda',
stack: '"Bodoni Moda", Georgia, serif',
pkg: 'bodoni-moda',
category: 'elegant',
roles: ['display', 'heading'],
weights: [400, 500, 600, 700, 800, 900],
italics: [400, 500, 600, 700, 800, 900],
letterEm: 0.463,
},
// ── condensed and poster ──
bebas: {
name: 'Bebas Neue',
stack: '"Bebas Neue", Impact, sans-serif',
pkg: 'bebas-neue',
category: 'condensed',
roles: ['display'],
weights: ONE,
italics: [],
letterEm: 0.339,
caps: true,
},
anton: {
name: 'Anton',
stack: '"Anton", Impact, sans-serif',
pkg: 'anton',
category: 'condensed',
roles: ['display'],
weights: ONE,
italics: [],
letterEm: 0.409,
},
oswald: {
name: 'Oswald',
stack: '"Oswald", Impact, sans-serif',
pkg: 'oswald',
category: 'condensed',
roles: ['display', 'heading'],
weights: [200, 300, 400, 500, 600, 700],
italics: [],
letterEm: 0.365,
},
league: {
name: 'League Gothic',
stack: '"League Gothic", Impact, sans-serif',
pkg: 'league-gothic',
category: 'condensed',
roles: ['display'],
weights: ONE,
italics: [],
letterEm: 0.266,
},
shoulders: {
name: 'Big Shoulders Display',
stack: '"Big Shoulders Display", Impact, sans-serif',
pkg: 'big-shoulders-display',
category: 'condensed',
roles: ['display', 'heading'],
weights: ALL,
italics: [],
letterEm: 0.304,
},
archivo: {
name: 'Archivo Black',
stack: '"Archivo Black", Impact, sans-serif',
pkg: 'archivo-black',
category: 'condensed',
roles: ['display'],
weights: ONE,
italics: [],
letterEm: 0.557,
},
// ── heavy and retro display ──
display: {
name: 'MuseoModerno',
stack: '"MuseoModerno", "Poppins", system-ui, sans-serif',
pkg: 'museomoderno',
category: 'retro',
roles: ['display', 'heading'],
weights: ALL,
italics: [],
letterEm: 0.492,
},
shrikhand: {
name: 'Shrikhand',
stack: '"Shrikhand", system-ui, sans-serif',
pkg: 'shrikhand',
category: 'retro',
roles: ['display'],
weights: ONE,
italics: [],
letterEm: 0.529,
},
alfa: {
name: 'Alfa Slab One',
stack: '"Alfa Slab One", Georgia, serif',
pkg: 'alfa-slab-one',
category: 'retro',
roles: ['display'],
weights: ONE,
italics: [],
letterEm: 0.54,
},
bricolage: {
name: 'Bricolage Grotesque',
stack: '"Bricolage Grotesque", system-ui, sans-serif',
pkg: 'bricolage-grotesque',
category: 'retro',
roles: ['display', 'heading', 'body'],
weights: [200, 300, 400, 500, 600, 700, 800],
italics: [],
letterEm: 0.471,
},
abril: {
name: 'Abril Fatface',
stack: '"Abril Fatface", Georgia, serif',
pkg: 'abril-fatface',
category: 'retro',
roles: ['display'],
weights: ONE,
italics: [],
letterEm: 0.46,
},
// ── script and handwriting ──
caveat: {
name: 'Caveat',
stack: '"Caveat", cursive',
pkg: 'caveat',
category: 'script',
roles: ['script'],
weights: MID,
italics: [],
letterEm: 0.344,
},
dancing: {
name: 'Dancing Script',
stack: '"Dancing Script", cursive',
pkg: 'dancing-script',
category: 'script',
roles: ['script'],
weights: MID,
italics: [],
letterEm: 0.363,
},
pacifico: {
name: 'Pacifico',
stack: '"Pacifico", cursive',
pkg: 'pacifico',
category: 'script',
roles: ['script'],
weights: ONE,
italics: [],
letterEm: 0.419,
},
vibes: {
name: 'Great Vibes',
stack: '"Great Vibes", cursive',
pkg: 'great-vibes',
category: 'script',
roles: ['script'],
weights: ONE,
italics: [],
letterEm: 0.284,
},
sacramento: {
name: 'Sacramento',
stack: '"Sacramento", cursive',
pkg: 'sacramento',
category: 'script',
roles: ['script'],
weights: ONE,
italics: [],
letterEm: 0.308,
},
kaushan: {
name: 'Kaushan Script',
stack: '"Kaushan Script", cursive',
pkg: 'kaushan-script',
category: 'script',
roles: ['script'],
weights: ONE,
italics: [],
letterEm: 0.396,
},
allura: {
name: 'Allura',
stack: '"Allura", cursive',
pkg: 'allura',
category: 'script',
roles: ['script'],
weights: ONE,
italics: [],
letterEm: 0.33,
},
parisienne: {
name: 'Parisienne',
stack: '"Parisienne", cursive',
pkg: 'parisienne',
category: 'script',
roles: ['script'],
weights: ONE,
italics: [],
letterEm: 0.361,
},
satisfy: {
name: 'Satisfy',
stack: '"Satisfy", cursive',
pkg: 'satisfy',
category: 'script',
roles: ['script'],
weights: ONE,
italics: [],
letterEm: 0.382,
},
yellowtail: {
name: 'Yellowtail',
stack: '"Yellowtail", cursive',
pkg: 'yellowtail',
category: 'script',
roles: ['script'],
weights: ONE,
italics: [],
letterEm: 0.333,
},
homemade: {
name: 'Homemade Apple',
stack: '"Homemade Apple", cursive',
pkg: 'homemade-apple',
category: 'script',
roles: ['script'],
weights: ONE,
italics: [],
letterEm: 0.561,
},
marker: {
name: 'Permanent Marker',
stack: '"Permanent Marker", cursive',
pkg: 'permanent-marker',
category: 'script',
roles: ['script', 'display'],
weights: ONE,
italics: [],
letterEm: 0.516,
},
// ── mono ──
mono: {
name: 'DM Mono',
stack: '"DM Mono", ui-monospace, monospace',
pkg: 'dm-mono',
category: 'mono',
roles: ['mono'],
weights: [300, 400, 500],
italics: [],
letterEm: 0.613,
},
} as const satisfies Record<string, BookFontFace>;
export type BookFontFamily = keyof typeof BOOK_FONT_FACES;
/**
* The families a book may be set in, as the schema takes them. The first
* seven keep the order they shipped in; new ones follow.
*/
export const BOOK_FONTS_IDS = [
'sans',
'inter',
'serif',
'garamond',
'playfair',
'display',
'bebas',
'montserrat',
'fraunces',
'cormorant',
'dmserif',
'bodoni',
'anton',
'oswald',
'league',
'shoulders',
'archivo',
'shrikhand',
'alfa',
'bricolage',
'abril',
'caveat',
'dancing',
'pacifico',
'vibes',
'sacramento',
'kaushan',
'allura',
'parisienne',
'satisfy',
'yellowtail',
'homemade',
'marker',
'mono',
] as const satisfies readonly BookFontFamily[];
/**
* The faces whose latin files the service worker installs with the app, so a
* book set in them opens offline before Studio was ever opened online: the
* seven families and weights the book shipped with before this catalogue grew.
* Every other face is cached the first time a book that uses it is opened.
*/
export const BOOK_FONTS_PRECACHED: Readonly<Partial<Record<BookFontFamily, readonly BookWeight[]>>> = {
sans: MID,
inter: MID,
serif: MID,
garamond: MID,
playfair: MID,
display: MID,
bebas: ONE,
};
+207
View File
@@ -0,0 +1,207 @@
import {
bookFacesUsed,
bookFontCountsInMix,
bookFontFace,
bookFontHasItalic,
bookFontHasWeight,
bookFontIndex,
bookFontRole,
bookFontSuits,
bookFontsUsed,
bookWeightWord,
isBookFontId,
nearestBookWeight,
withRealWeight,
} from './book-fonts';
import { BOOK_FONT_FACES, BOOK_FONTS_IDS, BOOK_FONTS_PRECACHED, BOOK_WEIGHTS } from './book-fonts.data';
import { bookFontIdSchema, bookWeightSchema } from './book-op-enums';
import { applyBookOps } from './book-ops';
import { blankBook } from './book-pages';
import {
bookStatsElementSchema,
bookTextElementSchema,
type BookDocument,
type BookElement,
type BookSpread,
} from './book.schema';
import { describeSpread } from './describe-spread';
import { describe, expect, it } from 'vitest';
// BKFONT-001 to BKFONT-010
/**
* The book's typefaces as one catalogue: the schema's ids, the weights and
* italics each family really ships, what each is for, and the snap the
* Studio and the page operations share, so the assistant never sets a weight
* the editor would not.
*/
const frame = { x: 230, y: 40, w: 120, h: 30 };
const text = (id: string, over: Record<string, unknown> = {}) =>
bookTextElementSchema.parse({ id, kind: 'text', frame, text: 'Lisbon', ...over }) as BookElement;
function book(elements: BookElement[]): BookDocument {
const doc = blankBook({ title: 'Lisbon', newId: (p) => `${p}-x` });
const ids = ['sp-cover', 'sp-first', 'sp-in', 'sp-last', 'sp-back'];
const spreads = doc.spreads.map((s, i) => ({ ...s, id: ids[i] as string }));
const inner = { ...(spreads[2] as BookSpread), role: 'inner' as const, elements };
return { ...doc, spreads: [spreads[0], spreads[1], inner, spreads[3], spreads[4]] as BookSpread[] };
}
let seq = 0;
const run = (doc: BookDocument, ops: Parameters<typeof applyBookOps>[1]['ops']) =>
applyBookOps(doc, { spreadId: 'sp-in', ops }, { newId: (p) => `${p}-n${++seq}` });
const inner = (doc: BookDocument) => doc.spreads[2] as BookSpread;
describe('the catalogue', () => {
it('BKFONT-001: names every family the schema takes, once, with a face, a stack ending in a generic and a weight', () => {
expect([...BOOK_FONTS_IDS].sort()).toEqual(Object.keys(BOOK_FONT_FACES).sort());
expect(new Set(BOOK_FONTS_IDS).size).toBe(BOOK_FONTS_IDS.length);
expect(BOOK_FONTS_IDS.slice(0, 7)).toEqual(['sans', 'inter', 'serif', 'garamond', 'playfair', 'display', 'bebas']);
for (const id of BOOK_FONTS_IDS) {
const face = BOOK_FONT_FACES[id];
expect(face.stack.startsWith(`"${face.name}"`), id).toBe(true);
expect(['sans-serif', 'serif', 'cursive', 'monospace'], id).toContain(face.stack.split(',').pop()?.trim());
expect(face.weights.length, id).toBeGreaterThan(0);
expect(
[...face.weights].sort((a, b) => a - b),
id,
).toEqual([...face.weights]);
for (const w of face.italics) expect(face.weights, `${id} italic ${w}`).toContain(w);
expect(face.letterEm, id).toBeGreaterThan(0.2);
expect(face.letterEm, id).toBeLessThan(0.7);
expect(face.roles.length, id).toBeGreaterThan(0);
}
});
it('BKFONT-002: has real italics for the serifs that used to be slanted by the browser', () => {
for (const id of ['serif', 'garamond', 'playfair', 'cormorant']) {
expect(bookFontHasItalic(id, 400), id).toBe(true);
}
expect(bookFontHasItalic('sans', 400)).toBe(false);
expect(bookFontHasItalic('playfair', 300)).toBe(false);
expect(bookFontHasItalic('nothing', 400)).toBe(false);
});
it('BKFONT-003: installs offline only the faces the book shipped with, each a weight the family has', () => {
for (const [id, weights] of Object.entries(BOOK_FONTS_PRECACHED)) {
for (const w of weights ?? []) expect(bookFontHasWeight(id, w), `${id} ${w}`).toBe(true);
}
expect(Object.keys(BOOK_FONTS_PRECACHED).sort()).toEqual(BOOK_FONTS_IDS.slice(0, 7).sort());
});
it('BKFONT-004: reads a family and its roles, and answers an unknown id without guessing', () => {
expect(bookFontFace('anton')?.name).toBe('Anton');
expect(bookFontFace('toString')).toBeUndefined();
expect([isBookFontId('caveat'), isBookFontId('comic')]).toEqual([true, false]);
expect([bookFontRole('caveat'), bookFontRole('mono'), bookFontRole('anton'), bookFontRole('nothing')]).toEqual([
'script',
'mono',
'display',
'body',
]);
expect([bookFontSuits('garamond', 'body'), bookFontSuits('anton', 'body')]).toEqual([true, false]);
expect([bookFontCountsInMix('caveat'), bookFontCountsInMix('mono'), bookFontCountsInMix('serif')]).toEqual([
false,
false,
true,
]);
});
});
describe('weights', () => {
it('BKFONT-005: snaps to the nearest weight a family has, the lighter on a tie, and leaves an unknown family alone', () => {
expect(nearestBookWeight('anton', 900)).toBe(400);
expect(nearestBookWeight('oswald', 100)).toBe(200);
expect(nearestBookWeight('oswald', 900)).toBe(700);
expect(nearestBookWeight('mono', 700)).toBe(500);
expect(nearestBookWeight('cormorant', 200)).toBe(300);
expect(nearestBookWeight('sans', 900)).toBe(900);
expect(nearestBookWeight('unknown', 600)).toBe(600);
expect([bookFontHasWeight('bebas', 700), bookFontHasWeight('unknown', 650)]).toEqual([false, true]);
expect(BOOK_WEIGHTS.map(bookWeightWord)).toEqual([
'thin',
'extralight',
'light',
'regular',
'medium',
'semibold',
'bold',
'extrabold',
'black',
]);
expect(bookWeightWord(450)).toBe('450');
});
it('BKFONT-006: moves a typeset element onto a real weight and hands every other element back as it was', () => {
const heavy = text('t', { font: 'anton', weight: 700 });
expect(withRealWeight(heavy)).toMatchObject({ weight: 400 });
const fine = text('t', { font: 'sans', weight: 700 });
expect(withRealWeight(fine)).toBe(fine);
const stats = bookStatsElementSchema.parse({ id: 's', kind: 'stats', frame, font: 'league' }) as BookElement;
expect(withRealWeight(stats)).toMatchObject({ weight: 400 });
const shape = { id: 'x', kind: 'shape', frame } as unknown as BookElement;
expect(withRealWeight(shape)).toBe(shape);
});
it('BKFONT-007: takes every weight from 100 to 900 in a document and nothing between them', () => {
expect(bookTextElementSchema.safeParse({ id: 't', kind: 'text', frame, weight: 100 }).success).toBe(true);
expect(bookTextElementSchema.safeParse({ id: 't', kind: 'text', frame, weight: 900 }).success).toBe(true);
expect(bookTextElementSchema.safeParse({ id: 't', kind: 'text', frame, weight: 450 }).success).toBe(false);
expect(bookWeightSchema.safeParse(800).success).toBe(true);
});
});
describe('a book and its faces', () => {
it('BKFONT-008: lists the families a book is set in and the faces it needs drawn, each once', () => {
const doc = book([
text('t1', { font: 'caveat', weight: 700 }),
text('t2', { font: 'serif', italic: true }),
text('t3', { font: 'sans', italic: true }),
text('t4', { font: 'anton', text: ' ' }),
bookStatsElementSchema.parse({ id: 's', kind: 'stats', frame, font: 'oswald' }) as BookElement,
]);
const used = bookFontsUsed(doc);
expect(used).toEqual(expect.arrayContaining(['caveat', 'serif', 'oswald']));
expect(used).not.toContain('anton');
expect(used.indexOf('serif')).toBeLessThan(used.indexOf('caveat'));
const faces = bookFacesUsed(doc);
expect(faces).toContainEqual({ font: 'caveat', weight: 700, italic: false });
expect(faces).toContainEqual({ font: 'serif', weight: 400, italic: true });
// Poppins has no italic file: its slant is the browser's, so the upright face is what loads.
expect(faces).toContainEqual({ font: 'sans', weight: 400, italic: false });
expect(faces).toContainEqual({ font: 'oswald', weight: 700, italic: false });
expect(faces).toContainEqual({ font: 'oswald', weight: 600, italic: false });
const keys = faces.map((f) => `${f.font}|${f.weight}|${f.italic}`);
expect(new Set(keys).size).toBe(keys.length);
});
});
describe('the assistant reads the same type', () => {
it('BKFONT-009: describes every family with its role and weights in the id the tools take', () => {
const index = bookFontIndex();
for (const id of BOOK_FONTS_IDS) expect(index, id).toContain(id);
expect(index).toMatch(/^display: /);
expect(index).toContain('script: caveat 400-700');
expect(index).toContain('bebas 400 caps');
expect(index).toContain('serif Lora 400-700 i');
expect(index).not.toMatch(/[\u2013\u2014\n]/);
expect(String(bookFontIdSchema.description)).toContain(index);
});
it('BKFONT-010: sets a style or a text change at a weight the family has, and says so in the page description', () => {
const doc = book([text('t1')]);
const styled = run(doc, [{ op: 'style', elementId: 't1', set: { kind: 'text', font: 'anton', weight: 900 } }]);
if (!styled.ok) throw new Error(styled.error.message);
expect(inner(styled.doc).elements[0]).toMatchObject({ font: 'anton', weight: 400 });
const retexted = run(doc, [{ op: 'text', elementId: 't1', font: 'mono', weight: 700 }]);
if (!retexted.ok) throw new Error(retexted.error.message);
expect(inner(retexted.doc).elements[0]).toMatchObject({ font: 'mono', weight: 500 });
const page = describeSpread(retexted.doc, 'sp-in')?.text ?? '';
expect(page).toContain('mono (mono) 11 pt medium');
const light = run(doc, [{ op: 'style', elementId: 't1', set: { kind: 'text', font: 'fraunces', weight: 300 } }]);
if (!light.ok) throw new Error(light.error.message);
expect(describeSpread(light.doc, 'sp-in')?.text).toContain('fraunces (display) 11 pt light');
});
});
+188
View File
@@ -0,0 +1,188 @@
import {
BOOK_FONT_CATEGORIES,
BOOK_FONT_FACES,
BOOK_FONT_ROLES,
BOOK_FONTS_IDS,
BOOK_FONTS_PRECACHED,
BOOK_WEIGHTS,
type BookFontCategory,
type BookFontFace,
type BookFontFamily,
type BookFontRole,
type BookWeight,
} from './book-fonts.data';
import type { BookDocument, BookElement } from './book.schema';
/**
* What the book's typefaces can do, read off the catalogue in
* book-fonts.data.ts: which weights and italics a family really has, what it
* is for, and which faces a book uses. Shared by the Studio, the findings,
* the design engine and the page operations, so the assistant and the editor
* snap a weight the same way.
*/
export {
BOOK_FONT_CATEGORIES,
BOOK_FONT_FACES,
BOOK_FONT_ROLES,
BOOK_FONTS_PRECACHED,
BOOK_WEIGHTS,
type BookFontCategory,
type BookFontFace,
type BookFontRole,
type BookWeight,
};
/** The family behind an id, or undefined for an id this build does not know. */
export function bookFontFace(id: string): BookFontFace | undefined {
return Object.prototype.hasOwnProperty.call(BOOK_FONT_FACES, id) ? BOOK_FONT_FACES[id as BookFontFamily] : undefined;
}
/** Whether `id` is a family of the catalogue. */
export const isBookFontId = (id: string): id is BookFontFamily => bookFontFace(id) !== undefined;
/** Whether a family ships the weight. An unknown family is not second-guessed. */
export function bookFontHasWeight(id: string, weight: number): boolean {
const face = bookFontFace(id);
return face ? (face.weights as readonly number[]).includes(weight) : true;
}
/**
* The nearest weight a family really has, the lighter one on a tie.
*
* A synthesised bold is a smeared regular in print, so a family with one
* weight gets that weight rather than a request the renderer has to fake. An
* unknown family keeps what was asked.
*/
export function nearestBookWeight(id: string, weight: number): number {
const face = bookFontFace(id);
if (!face || (face.weights as readonly number[]).includes(weight)) return weight;
return face.weights.reduce<number>(
(best, w) => (Math.abs(w - weight) < Math.abs(best - weight) ? w : best),
face.weights[0] ?? weight,
);
}
/**
* The lighter weight a travel element sets beside its figures (a unit after
* a number, a caption under it): a step under the weight, never under 400
* unless the weight itself is, and one the family has.
*/
export function bookLighterWeight(id: string, weight: number): number {
return nearestBookWeight(id, Math.min(weight, Math.max(400, weight - 100)));
}
/** Whether a family has a real italic at that weight, rather than the browser's slant. */
export function bookFontHasItalic(id: string, weight: number): boolean {
const face = bookFontFace(id);
return !!face && (face.italics as readonly number[]).includes(weight);
}
/** What a family is for: the first of its roles, `body` for an unknown one. */
export const bookFontRole = (id: string): BookFontRole => bookFontFace(id)?.roles[0] ?? 'body';
/** Whether a family suits a role at all, not only as its first. */
export function bookFontSuits(id: string, role: BookFontRole): boolean {
return bookFontFace(id)?.roles.includes(role) ?? false;
}
/**
* Whether a family counts towards the faces a book is set in. A script laid
* over a title and a mono line on a ticket are ornaments, not a third voice.
*/
export function bookFontCountsInMix(id: string): boolean {
const role = bookFontRole(id);
return role !== 'script' && role !== 'mono';
}
/** The element with its weight moved onto one its family has, when it is set in type at all. */
export function withRealWeight<T extends BookElement>(el: T): T {
if (!('font' in el) || !('weight' in el)) return el;
const weight = nearestBookWeight(el.font, el.weight);
return weight === el.weight ? el : { ...el, weight: weight as BookWeight };
}
/** One face a book is set in: the family, the weight the renderer draws and the slant. */
export interface BookFaceUse {
font: BookFontFamily;
weight: number;
italic: boolean;
}
/** The type-setting elements on a book's pages: everything that names a font, an empty text aside. */
function typeset(doc: BookDocument): Extract<BookElement, { font: string }>[] {
const out: Extract<BookElement, { font: string }>[] = [];
for (const spread of doc.spreads) {
for (const el of spread.elements) {
if ('font' in el && (el.kind !== 'text' || el.text.trim())) out.push(el);
}
}
return out;
}
/** The families a book is set in, page numbers included when shown, in catalogue order. */
export function bookFontsUsed(doc: BookDocument): BookFontFamily[] {
const used = new Set<string>(typeset(doc).map((el) => el.font));
if (doc.page.pageNumbers.show) used.add(doc.page.pageNumbers.font);
return BOOK_FONTS_IDS.filter((id) => used.has(id));
}
/**
* Every face a book needs drawn, each once: what the Studio warms into the
* offline cache when a book opens, so the book still reads in its own type
* without a connection. Travel elements set a lighter weight beside their
* figures, which is why both of those are named.
*/
export function bookFacesUsed(doc: BookDocument): BookFaceUse[] {
const seen = new Map<string, BookFaceUse>();
const add = (font: BookFontFamily, weight: number, italic: boolean) => {
const use = { font, weight: nearestBookWeight(font, weight), italic: italic && bookFontHasItalic(font, weight) };
seen.set(`${use.font}|${use.weight}|${use.italic}`, use);
};
for (const el of typeset(doc)) {
add(el.font, el.weight, el.kind === 'text' && el.italic);
if (el.kind !== 'text') add(el.font, bookLighterWeight(el.font, el.weight), false);
}
if (doc.page.pageNumbers.show) add(doc.page.pageNumbers.font, 500, false);
return [...seen.values()];
}
/** A weight as the assistant reads it, the CSS name beside the number. */
const WEIGHT_WORDS: Record<BookWeight, string> = {
100: 'thin',
200: 'extralight',
300: 'light',
400: 'regular',
500: 'medium',
600: 'semibold',
700: 'bold',
800: 'extrabold',
900: 'black',
};
export const bookWeightWord = (weight: number): string => WEIGHT_WORDS[weight as BookWeight] ?? String(weight);
/**
* The catalogue as one line per role, for the font id's description in the
* tool schemas: an id, its face and the weights it has, an i for a real
* italic, so a model picks a script for an overlay and never asks Anton for
* bold.
*/
export function bookFontIndex(): string {
const span = (ws: readonly number[]) => (ws.length === 1 ? `${ws[0]}` : `${ws[0]}-${ws[ws.length - 1]}`);
return BOOK_FONT_ROLES.map((role) => {
const ids = BOOK_FONTS_IDS.filter((id) => bookFontRole(id) === role);
if (!ids.length) return '';
const listed = ids.map((id) => {
const face = BOOK_FONT_FACES[id];
const italic = face.italics.length ? ' i' : '';
const caps = 'caps' in face ? ' caps' : '';
// The face is named only where the id does not already say it, for the size of the tool schemas.
const named = face.name.toLowerCase().startsWith(id) ? '' : ` ${face.name}`;
return `${id}${named} ${span(face.weights)}${italic}${caps}`;
});
return `${role}: ${listed.join(', ')}.`;
})
.filter(Boolean)
.join(' ');
}
+11 -4
View File
@@ -1,3 +1,4 @@
import { bookFontIndex } from './book-fonts';
import { BOOK_ICON_NAMES } from './book-icons';
import {
BOOK_BADGES,
@@ -37,14 +38,20 @@ const text = bookTextElementSchema.shape;
const shape = bookShapeElementSchema.shape;
const map = bookMapElementSchema.shape;
/** The book's typefaces, with the face each id sets. */
/**
* The book's typefaces by what they are for, each with its face, the weights
* it has and an i where it has a real italic. A weight a family lacks is set
* at its nearest one, as in the Studio.
*/
export const bookFontIdSchema = z
.enum(BOOK_FONTS_IDS)
.describe(
'Typeface: sans Poppins, inter Inter, serif Lora, garamond EB Garamond, playfair Playfair Display, display MuseoModerno, bebas Bebas Neue (caps, one weight).',
);
.describe(`Typeface by role; weights a family lacks snap to its nearest. ${bookFontIndex()}`);
/** The typeface of a travel element, where the full line above would repeat ten times. */
export const bookTypesetFontSchema = z.enum(BOOK_FONTS_IDS).describe('Typeface id, as for text.');
/** How heavy type is set, 100 thin to 900 black. */
export const bookWeightSchema = bookTextElementSchema.shape.weight
.unwrap()
.describe('Weight 100 thin to 900 black, 400 regular, 700 bold; snapped to one the family has.');
/** Every shape the Studio draws, and so every mask a photo can be cut to. */
export const bookShapeIdSchema = z
+7 -2
View File
@@ -1,6 +1,7 @@
import { relayoutSpread } from './auto/auto-book';
import type { AutoEntry, AutoInput } from './auto/auto-types';
import { bookElementPropsSchema, type BOOK_ELEMENT_OP_SCHEMAS, type BookNewElement } from './book-element-ops.schema';
import { withRealWeight } from './book-fonts';
import { bookGridElements, defaultBookGridBox, findBookGrid } from './book-grids';
import {
bookBoundWords,
@@ -138,7 +139,11 @@ function lookKeys(shape: object): string[] {
return Object.keys(shape).filter((k) => k !== 'kind');
}
/** The element with the given look fields set; millimetre fields rounded as the document stores them. */
/**
* The element with the given look fields set; millimetre fields rounded as the
* document stores them, and the weight moved onto one its family has, as the
* Studio's weight control does.
*/
function withProps(el: BookElement, props: Record<string, unknown>): BookElement {
const keys = PROP_KEYS.get(el.kind) ?? [];
const next: Record<string, unknown> = { ...el };
@@ -147,7 +152,7 @@ function withProps(el: BookElement, props: Record<string, unknown>): BookElement
if (value === undefined) continue;
next[key] = (key === 'radius' || key === 'strokeWidth') && typeof value === 'number' ? round2(value) : value;
}
return next as unknown as BookElement;
return withRealWeight(next as unknown as BookElement);
}
// ── add ────────────────────────────────────────────────────────────────────
+5 -2
View File
@@ -1,3 +1,4 @@
import { withRealWeight } from './book-fonts';
import { bookGridElements, defaultBookGridBox, findBookGrid, type BookGridDef } from './book-grids';
import { bookElementId } from './book-ids';
import { BOOK_TEXT_STYLES, applyBookTemplate, classifyBookTexts, findBookTemplate } from './book-layouts';
@@ -413,9 +414,11 @@ function opText(spread: BookSpread, op: Op<'text'>, env: Env): BookSpread {
op.elementId !== undefined
? textEl(spread, op.elementId, env)
: classifyBookTexts(roleTexts(spread))[op.role ?? 'body'];
if (existing && existing.kind === 'text') return replaceEl(spread, retext(unlocked(existing, env), op, env));
// The weight lands on one the family has, whichever of the two a change names.
if (existing && existing.kind === 'text')
return replaceEl(spread, withRealWeight(retext(unlocked(existing, env), op, env)));
withRoom(spread, 1, env);
return { ...spread, elements: [...spread.elements, newText(spread, op, env)] };
return { ...spread, elements: [...spread.elements, withRealWeight(newText(spread, op, env))] };
}
function retext(el: BookTextElement, op: Op<'text'>, env: Env): BookTextElement {
+16 -11
View File
@@ -21,6 +21,9 @@ import { describe, expect, it } from 'vitest';
const frame = { x: 12, y: 18, w: 60, h: 40 };
/** A revision one past what this build reads. */
const NEWER = BOOK_SCHEMA_REV + 1;
const doc = (over: Record<string, unknown> = {}) => ({
version: 1,
title: 'Lisbon',
@@ -40,7 +43,8 @@ const doc = (over: Record<string, unknown> = {}) => ({
describe('the revision a document was written by', () => {
it('BKREV-001: reads 1 for every document from before the field, and for anything that is not a whole number', () => {
expect(BOOK_SCHEMA_REV).toBe(1);
// Raised for the first time by the wider type: new families and weights an older reader drops.
expect(BOOK_SCHEMA_REV).toBeGreaterThanOrEqual(2);
expect(bookSchemaRev(doc())).toBe(1);
expect(bookSchemaRev(null)).toBe(1);
expect(bookSchemaRev('{"schemaRev":4}')).toBe(1);
@@ -56,33 +60,34 @@ describe('the revision a document was written by', () => {
expect(odd.success && odd.data.spreads[0]?.elements).toHaveLength(1);
});
it('BKREV-003: leaves a book saved today as it was, with no revision written into it', () => {
it('BKREV-003: a writer at revision 1 leaves a book as it was, with no revision written into it', () => {
const today = normalizeBookDocument(doc());
expect('schemaRev' in today).toBe(false);
expect(stampBookSchemaRev(today)).toBe(today);
expect(JSON.stringify(stampBookSchemaRev(today))).toBe(JSON.stringify(today));
expect(stampBookSchemaRev(today, 1)).toBe(today);
expect(JSON.stringify(stampBookSchemaRev(today, 1))).toBe(JSON.stringify(today));
expect(stampBookSchemaRev(today).schemaRev).toBe(BOOK_SCHEMA_REV);
});
});
describe('a reader older than the document', () => {
it('BKREV-004: knows the document is newer than it, read from the raw value even when the rest will not parse', () => {
expect(isBookNewerThanReader(doc({ schemaRev: 2 }))).toBe(true);
expect(isBookNewerThanReader(doc({ schemaRev: NEWER }))).toBe(true);
expect(isBookNewerThanReader(doc({ schemaRev: 1 }))).toBe(false);
expect(isBookNewerThanReader(doc())).toBe(false);
// A reader of a later revision reads the same document as its own.
expect(isBookNewerThanReader(doc({ schemaRev: 2 }), 2)).toBe(false);
const unreadable = doc({ schemaRev: 5, page: 'not a page' });
expect(isBookNewerThanReader(doc({ schemaRev: NEWER }), NEWER)).toBe(false);
const unreadable = doc({ schemaRev: NEWER + 3, page: 'not a page' });
expect(isBookNewerThanReader(unreadable)).toBe(true);
});
it('BKREV-005: reads a newer book as far as it can and says so, so nothing it dropped is saved', () => {
const sticker = { id: 'x1', kind: 'sticker', frame, stickerId: 'lemon' };
const raw = doc({ schemaRev: 2 });
const raw = doc({ schemaRev: NEWER });
const spread = (raw.spreads as { elements: unknown[] }[])[0];
if (spread) spread.elements.push(sticker);
const read = readBookDocument(raw);
expect(read.newer).toBe(true);
expect(read.document.schemaRev).toBe(2);
expect(read.document.schemaRev).toBe(NEWER);
expect(read.document.spreads[0]?.elements.map((e) => e.id)).toEqual(['t1']);
expect(readBookDocument(doc()).newer).toBe(false);
});
@@ -99,10 +104,10 @@ describe('a reader older than the document', () => {
describe('a save request carrying a newer book', () => {
it('BKREV-007: reaches the server as its revision alone, so the save is refused there rather than at the pipe', () => {
const sticker = { id: 'x1', kind: 'sticker', frame, stickerId: 'lemon' };
const raw = doc({ schemaRev: 2 });
const raw = doc({ schemaRev: NEWER });
const spread = (raw.spreads as { elements: unknown[] }[])[0];
if (spread) spread.elements.push(sticker);
expect(bookSaveRequestSchema.parse({ title: 'T', document: raw }).document).toEqual({ schemaRev: 2 });
expect(bookSaveRequestSchema.parse({ title: 'T', document: raw }).document).toEqual({ schemaRev: NEWER });
// A book of today still reads whole, revision or none.
const today = bookSaveRequestSchema.parse({ title: 'T', document: doc() }).document;
expect(today).toEqual(bookDocumentSchema.parse(doc()));
+1 -1
View File
@@ -28,7 +28,7 @@ import type { BookDocument } from './book.schema';
* saves only once that is above 1, so a book saved today stores exactly what
* it stored before this existed.
*/
export const BOOK_SCHEMA_REV = 1;
export const BOOK_SCHEMA_REV = 2;
/** The `code` a refused save carries in its body when the stored book is newer than the writer. */
export const BOOK_SCHEMA_NEWER_CODE = 'book_schema_newer';
+10 -8
View File
@@ -1,3 +1,5 @@
import { BOOK_FONTS_IDS, BOOK_WEIGHTS, type BookFontFamily } from './book-fonts.data';
import { z } from 'zod';
/**
@@ -157,15 +159,15 @@ export const BOOK_SHAPES = [
export type BookShapeId = (typeof BOOK_SHAPES)[number];
/**
* The families a book may be set in.
* The families a book may be set in, and the weights type is set at. The
* catalogue is book-fonts.data.ts: which face each id names, its weights, its
* real italics and what it is for.
*
* `sans`, `serif` and `display` are the three the format started with and are
* kept by name, so every document written so far still parses — they now point
* at bundled faces rather than at whatever the rendering machine happened to
* have installed. See client/src/components/Studio/bookFonts.ts.
* kept by name, so every document written so far still parses.
*/
export const BOOK_FONTS_IDS = ['sans', 'inter', 'serif', 'garamond', 'playfair', 'display', 'bebas'] as const;
export type BookFontFamily = (typeof BOOK_FONTS_IDS)[number];
export { BOOK_FONTS_IDS, type BookFontFamily };
const bookWeightSchema = z.literal(BOOK_WEIGHTS);
export const bookFrameSchema = z.object({
/** Millimetres from the left edge of the spread. Negative means bleed. */
@@ -230,7 +232,7 @@ export const bookTextElementSchema = z.object({
font: z.enum(BOOK_FONTS_IDS).default('sans'),
/** Points. */
size: z.number().min(4).max(200).default(11),
weight: z.union([z.literal(400), z.literal(500), z.literal(600), z.literal(700)]).default(400),
weight: bookWeightSchema.default(400),
italic: z.boolean().default(false),
align: z.enum(['left', 'center', 'right', 'justify']).default('left'),
/** Multiple of the font size. */
@@ -362,7 +364,7 @@ const typeset = {
* together, the way `textScale` moves their size. Without it the only way to
* lighten a stats block was to not use one.
*/
weight: z.union([z.literal(400), z.literal(500), z.literal(600), z.literal(700)]).default(700),
weight: bookWeightSchema.default(700),
/** Set when the journey has moved on since these values were taken. */
stale: z.boolean().default(false),
};
+5 -2
View File
@@ -1,5 +1,6 @@
import { photoDpi, spreadFindings } from './book-findings';
import { designFindings, sortBookFindings } from './book-findings-design';
import { bookFontRole, bookWeightWord, nearestBookWeight } from './book-fonts';
import { BOOK_GRIDS } from './book-grids';
import { BOOK_COVER_TEMPLATES, BOOK_TEMPLATES, type BookTemplate } from './book-layouts';
import type { BookPhotoInfo } from './book-ops-core';
@@ -85,7 +86,9 @@ function elementWords(el: BookElement, photos: readonly BookPhotoInfo[] | undefi
photos?.find((p) => p.photoId === el.photoId),
);
case 'text': {
const style = `${el.font} ${n(el.size)} pt${el.weight >= 600 ? ' bold' : ''}${el.italic ? ' italic' : ''}, ${el.align}, ${el.color}`;
const weight = nearestBookWeight(el.font, el.weight);
const set = `${el.font} (${bookFontRole(el.font)}) ${n(el.size)} pt${weight === 400 ? '' : ` ${bookWeightWord(weight)}`}`;
const style = `${set}${el.italic ? ' italic' : ''}, ${el.align}, ${el.color}`;
const bound = el.binding ? `, bound to ${el.binding.source}${el.overridden ? ' (overridden)' : ''}` : '';
return `${style}: "${head(el.text, 80)}"${bound}`;
}
@@ -110,7 +113,7 @@ type TravelElement = Extract<BookElement, { kind: 'map' | 'stats' | 'countries'
/** What a travel element shows, and how it is set: its face, ink, accent and size. */
function travelWords(el: TravelElement): string {
const set = `${el.font} ${el.weight >= 600 ? 'bold' : 'regular'}, ink ${el.color}, accent ${el.accent}, type x${n(el.textScale)}`;
const set = `${el.font} ${bookWeightWord(nearestBookWeight(el.font, el.weight))}, ink ${el.color}, accent ${el.accent}, type x${n(el.textScale)}`;
const stale = el.stale ? '; its figures are out of date with the journey' : '';
return `${travelWhat(el)}; ${set}${stale}`;
}
+4 -1
View File
@@ -1,6 +1,7 @@
import { buildBook, distributeGallery } from '../auto/auto-book';
import type { AutoEntry, AutoInput, AutoPhoto } from '../auto/auto-types';
import { bookLevelFindings, sortBookFindings } from '../book-findings-design';
import { withRealWeight } from '../book-fonts';
import { bookElementId } from '../book-ids';
import type { BookPhotoInfo } from '../book-ops-core';
import type { BookFinding } from '../book-ops.schema';
@@ -252,7 +253,9 @@ export function designBook(
const repairCtx = { page, photos: input.photos, look, newId };
const designed = [...framing, ...inner.spreads, ...closing].map((d): DesignedSpread => {
const fixed = repairSpread(d.spread, repairCtx);
return { ...d, spread: fixed.spread, findings: fixed.findings };
// Every face at a weight its family has: a travel element's bold in a one-weight poster face would be faked.
const spread = { ...fixed.spread, elements: fixed.spread.elements.map(withRealWeight) };
return { ...d, spread, findings: fixed.findings };
});
const merged = mergeDesign(doc, designed, directives.keep);
+6 -3
View File
@@ -1,5 +1,6 @@
import type { AutoEntry, AutoPhoto } from '../auto/auto-types';
import { DESIGN_TEXT_HEADROOM, MIN_PRINT_DPI, textHeightNeeded } from '../book-findings';
import { nearestBookWeight } from '../book-fonts';
import type { BookPhotoInfo } from '../book-ops-core';
import { formatBookDate } from '../book-text';
import { bookBadgeValue, bookTravelBadge, type BookTravelContext } from '../book-travel';
@@ -158,6 +159,7 @@ type TextAt = Pick<BookFrame, 'x' | 'y' | 'w'>;
/** A text in the book's look, its frame as tall as its words need. */
export function textEl(c: ComposeCtx, at: TextAt, words: string, role: TextRole, opts: TextOpts = {}): BookTextElement {
const defaultColour = role === 'caption' || role === 'meta' ? c.look.muted : c.look.ink;
const font = role === 'heading' || role === 'sub' ? c.look.heading : c.look.body;
const el: BookTextElement = {
id: c.newId('t'),
kind: 'text',
@@ -166,9 +168,10 @@ export function textEl(c: ComposeCtx, at: TextAt, words: string, role: TextRole,
opacity: 1,
locked: false,
text: words,
font: role === 'heading' || role === 'sub' ? c.look.heading : c.look.body,
font,
size: opts.size ?? c.look.sizes[role],
weight: WEIGHT[role],
// A family that lacks the role's weight is set at its nearest, never at a synthesised one.
weight: nearestBookWeight(font, WEIGHT[role]) as BookTextElement['weight'],
italic: false,
align: opts.align ?? 'left',
leading: LEADING[role],
@@ -258,7 +261,7 @@ export function titleBlock(
if (value) {
const chip = frameOf(box.x, y, scaled(c, 24), scaled(c, 7));
const badge = bookTravelBadge({ id: c.newId('bd'), frame: chip, variant: 'day', value });
els.push({ ...badge, font: c.look.heading, accent: c.look.accent });
els.push({ ...badge, font: c.look.figures, accent: c.look.accent });
y += chip.h + 4;
}
}
+3 -3
View File
@@ -161,7 +161,7 @@ export function composeSummary(
const textSide = mapSide === 'left' ? 'right' : 'left';
const els: BookElement[] = [];
const map = bookTravelMap(c.travel, stats, { id: c.newId('mp'), frame: liveBox(c, mapSide), scope: 'journey' });
els.push({ ...map, style: c.look.mapStyle, font: c.look.heading, color: c.look.ink, accent: c.look.accent });
els.push({ ...map, style: c.look.mapStyle, font: c.look.figures, color: c.look.ink, accent: c.look.accent });
const head = label(c, words, textSide);
els.push(...head.els);
const metrics = metricsOf(c, stats);
@@ -169,7 +169,7 @@ export function composeSummary(
const box = liveBox(c, textSide);
const frame = frameOf(box.x, head.bottom, box.w, Math.min(box.h * 0.6, box.y + box.h - head.bottom));
const figures = bookTravelStats(stats, { id: c.newId('st'), frame, metrics });
els.push({ ...figures, font: c.look.heading, color: c.look.ink, accent: c.look.accent });
els.push({ ...figures, font: c.look.figures, color: c.look.ink, accent: c.look.accent });
}
return els;
}
@@ -179,7 +179,7 @@ export function composeCountries(c: ComposeCtx, words: string): BookElement[] {
const head = label(c, words, 'left');
const box = liveBox(c, 'right');
const countries = bookTravelCountries(c.travel, { id: c.newId('co'), frame: box });
return [...head.els, { ...countries, font: c.look.heading, color: c.look.ink, accent: c.look.accent }];
return [...head.els, { ...countries, font: c.look.figures, color: c.look.ink, accent: c.look.accent }];
}
/**
+2 -2
View File
@@ -146,7 +146,7 @@ function listUnder(c: ComposeCtx, entry: AutoEntry, foot: Foot): BookElement | n
if (foot.top + h > foot.bottom) return null;
const labels = { pros: c.travel.labels.pros, cons: c.travel.labels.cons };
const list = bookTravelList(labels, { id: c.newId('li'), frame: frameOf(foot.x, foot.top, foot.w, h), items });
return { ...list, font: c.look.heading, color: c.look.ink, accent: c.look.accent };
return { ...list, font: c.look.figures, color: c.look.ink, accent: c.look.accent };
}
/**
@@ -293,7 +293,7 @@ function chapterMap(c: ComposeCtx, entry: AutoEntry, box: BookFrame): BookElemen
const h = box.h * 0.3;
const frame = frameOf(box.x, box.y + box.h - h, box.w, h);
const map = bookTravelMap(c.travel, stats, { id: c.newId('mp'), frame, scope: { tripId } });
const look = { style: c.look.mapStyle, font: c.look.heading, color: c.look.ink, accent: c.look.accent };
const look = { style: c.look.mapStyle, font: c.look.figures, color: c.look.ink, accent: c.look.accent };
return { ...map, ...look, pinStyle: 'dot' };
}
+28 -1
View File
@@ -1,3 +1,4 @@
import { bookFontHasWeight } from '../book-fonts';
import { bookPageSetupSchema, type BookDocument, type BookTextElement } from '../book.schema';
import { designBook, type BookDesignInput } from './design-book';
import { bookDesignDirectivesSchema, type BookDesignDirectivesInput } from './design-directives.schema';
@@ -7,7 +8,7 @@ import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
// BOOKSTY-001 to BOOKSTY-004
// BOOKSTY-001 to BOOKSTY-007
/**
* The type scale of a designed book: `type.scale` reaches a poster's sizes,
@@ -78,3 +79,29 @@ describe('the cover title', () => {
expect((big?.frame.y ?? 0) + (big?.frame.h ?? 0)).toBeLessThanOrEqual(page.pageHeight);
});
});
describe('the typefaces by their roles', () => {
it('BOOKSTY-005: keeps a body face that sets running text, and falls back to the style for one that does not', () => {
expect(lookOf({ style: 'classic', type: { body: 'garamond' } }).body).toBe('garamond');
// A poster face and a script are a title's, never a story's.
expect(lookOf({ style: 'classic', type: { body: 'anton' } }).body).toBe('sans');
expect(lookOf({ style: 'editorial', type: { body: 'caveat' } }).body).toBe('garamond');
});
it('BOOKSTY-006: sets the travel elements in the heading face, unless that is a script or a mono face', () => {
expect(lookOf({ style: 'bold' }).figures).toBe('bebas');
const script = lookOf({ style: 'journal', type: { heading: 'caveat' } });
expect([script.heading, script.figures]).toEqual(['caveat', 'garamond']);
expect(lookOf({ style: 'classic', type: { heading: 'mono', body: 'inter' } }).figures).toBe('inter');
});
it('BOOKSTY-007: sets every text and travel element at a weight its family really has', () => {
const { doc } = designBook(null, rich(), { style: 'bold', type: { heading: 'anton' } });
const typeset = doc.spreads.flatMap((s) => s.elements.filter((e) => 'weight' in e && 'font' in e));
expect(typeset.length).toBeGreaterThan(0);
for (const el of typeset) {
if ('weight' in el && 'font' in el) expect(bookFontHasWeight(el.font, el.weight), el.id).toBe(true);
}
expect(typeset.some((e) => 'font' in e && e.font === 'anton')).toBe(true);
});
});
+13 -3
View File
@@ -1,4 +1,5 @@
import { accentFromPalettes, contrastRatio, parseHex, readPalette, readableInk, toHex } from '../book-colour';
import { bookFontCountsInMix, bookFontSuits } from '../book-fonts';
import type { BookPhotoInfo } from '../book-ops-core';
import type { BookFontFamily, BookPageSetup, BookPhotoElement } from '../book.schema';
import type { BookDesignDirectives, BookDesignStyle } from './design-directives.schema';
@@ -7,8 +8,12 @@ import type { BookDesignDirectives, BookDesignStyle } from './design-directives.
* The look of a designed book: its paper, ink, accent, the two typefaces,
* the type sizes and the page grid, from the style and the directives.
*
* At most two families per book; badges, figures, maps and lists take the
* heading face. Sizes are set for a 210 mm page and scale with the page
* At most two families per book, read by their roles (book-fonts.data.ts):
* the body face has to be one that sets running text, so a poster face or a
* script asked for as the body falls back to the style's own. Badges,
* figures, maps and lists take the heading face, unless that is a script or
* a mono face, which sets a title well and a column of figures badly; then
* they take the body face. Sizes are set for a 210 mm page and scale with the page
* width, times `type.scale`, never under what a reader can read and never
* over what a text element takes. The cover title has a tier of its own,
* `display`, the heading size times `type.display`: 1 by default, so a book
@@ -31,6 +36,8 @@ export interface BookDesignLook {
onScrim: string;
heading: BookFontFamily;
body: BookFontFamily;
/** The face of the travel elements: figures, marks, maps and lists. */
figures: BookFontFamily;
/** Points. `display` is the cover title's, the heading's unless `type.display` raises it. */
sizes: { display: number; heading: number; sub: number; body: number; caption: number; meta: number };
/** The frame decoration and the slight turn a scrapbook gives its pictures. */
@@ -172,6 +179,8 @@ export function designLook(
const size = (role: keyof typeof BASE_SIZES, times = 1) =>
Math.min(MAX_PT, Math.max(FLOOR[role], round1(BASE_SIZES[role] * scale * times)));
const heading = directives.type?.heading ?? preset.heading;
const asked = directives.type?.body;
const body = asked && bookFontSuits(asked, 'body') ? asked : preset.body;
return {
style: directives.style,
paper: colours.paper,
@@ -182,7 +191,8 @@ export function designLook(
scrimOpacity: 0.6,
onScrim: '#ffffff',
heading,
body: directives.type?.body ?? preset.body,
body,
figures: bookFontCountsInMix(heading) ? heading : body,
sizes: {
display: size('heading', directives.type?.display ?? 1),
heading: size('heading'),
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -613,7 +613,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'فسيفساء',
'journey.studio.tpl.bandQuote': 'كلمات في الوسط',
'journey.studio.tpl.staggerFour': 'أربع متدرجة',
'journey.studio.weightMissing': 'هذا الخط لا يوفر هذا الوزن',
'journey.studio.mapSource': 'مصدر الخريطة',
'journey.studio.mapSourceVector': 'المخططات',
'journey.studio.mapSourceRelief': 'تضاريس',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'تغيير الخط',
'journey.studio.fonts.search': 'البحث عن خطوط',
'journey.studio.fonts.list': 'الخطوط',
'journey.studio.fonts.used': 'مستخدمة في هذا الكتاب',
'journey.studio.fonts.none': 'لا يوجد خط مطابق',
'journey.studio.fonts.range': 'من {from} إلى {to}',
'journey.studio.fonts.cat.sans': 'بدون تذييل',
'journey.studio.fonts.cat.serif': 'مذيّلة',
'journey.studio.fonts.cat.elegant': 'عناوين أنيقة',
'journey.studio.fonts.cat.condensed': 'ضيقة وملصقات',
'journey.studio.fonts.cat.retro': 'ثقيلة وريترو',
'journey.studio.fonts.cat.script': 'خط يد وزخرفي',
'journey.studio.fonts.cat.mono': 'ثابتة العرض',
'journey.studio.weight.100': 'رفيع',
'journey.studio.weight.200': 'خفيف جدًا',
'journey.studio.weight.300': 'خفيف',
'journey.studio.weight.400': 'عادي',
'journey.studio.weight.500': 'متوسط',
'journey.studio.weight.600': 'شبه عريض',
'journey.studio.weight.700': 'عريض',
'journey.studio.weight.800': 'عريض جدًا',
'journey.studio.weight.900': 'أسود',
'journey.studio.weightOnly': 'وزن واحد فقط',
'journey.studio.italicSlanted': 'مائل بالإمالة: لا يملك هذا الخط مائلًا خاصًا به',
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-2
View File
@@ -641,8 +641,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.bandQuote': 'Arada sitat',
'journey.studio.tpl.staggerFour': 'Pilləli dördlük',
'journey.studio.weightMissing': 'Bu şriftdə həmin qalınlıq mövcud deyil',
'journey.studio.mapSource': 'Xəritə mənbəyi',
'journey.studio.mapSourceVector': 'Konturlar',
'journey.studio.mapSourceRelief': 'Relyef',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'Şrifti dəyiş',
'journey.studio.fonts.search': 'Şrift axtar',
'journey.studio.fonts.list': 'Şriftlər',
'journey.studio.fonts.used': 'Bu kitabda istifadə olunanlar',
'journey.studio.fonts.none': 'Uyğun şrift yoxdur',
'journey.studio.fonts.range': '{from} ilə {to} arası',
'journey.studio.fonts.cat.sans': 'Dırnaqsız',
'journey.studio.fonts.cat.serif': 'Dırnaqlı',
'journey.studio.fonts.cat.elegant': 'Zərif başlıq',
'journey.studio.fonts.cat.condensed': 'Dar və afişa',
'journey.studio.fonts.cat.retro': 'Qalın və retro',
'journey.studio.fonts.cat.script': 'Yazı və əl yazısı',
'journey.studio.fonts.cat.mono': 'Sabit enli',
'journey.studio.weight.100': 'Nazik',
'journey.studio.weight.200': 'Çox yüngül',
'journey.studio.weight.300': 'Yüngül',
'journey.studio.weight.400': 'Adi',
'journey.studio.weight.500': 'Orta',
'journey.studio.weight.600': 'Yarımqalın',
'journey.studio.weight.700': 'Qalın',
'journey.studio.weight.800': 'Çox qalın',
'journey.studio.weight.900': 'Qara',
'journey.studio.weightOnly': 'Yalnız bir qalınlıq',
'journey.studio.italicSlanted': 'Kursiv, maili: bu şriftin öz kursivi yoxdur',
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -587,7 +587,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'Mosaico',
'journey.studio.tpl.bandQuote': 'Palavras no meio',
'journey.studio.tpl.staggerFour': 'Quatro escalonadas',
'journey.studio.weightMissing': 'Esta fonte não tem esse peso',
'journey.studio.mapSource': 'Origem do mapa',
'journey.studio.mapSourceVector': 'Contornos',
'journey.studio.mapSourceRelief': 'Relevo',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'Trocar fonte',
'journey.studio.fonts.search': 'Buscar fontes',
'journey.studio.fonts.list': 'Fontes',
'journey.studio.fonts.used': 'Usadas neste livro',
'journey.studio.fonts.none': 'Nenhuma fonte corresponde',
'journey.studio.fonts.range': '{from} a {to}',
'journey.studio.fonts.cat.sans': 'Sem serifa',
'journey.studio.fonts.cat.serif': 'Com serifa',
'journey.studio.fonts.cat.elegant': 'Títulos elegantes',
'journey.studio.fonts.cat.condensed': 'Estreita e cartaz',
'journey.studio.fonts.cat.retro': 'Pesada e retrô',
'journey.studio.fonts.cat.script': 'Caligráfica e manuscrita',
'journey.studio.fonts.cat.mono': 'Monoespaçada',
'journey.studio.weight.100': 'Ultrafino',
'journey.studio.weight.200': 'Extrafino',
'journey.studio.weight.300': 'Fino',
'journey.studio.weight.400': 'Normal',
'journey.studio.weight.500': 'Médio',
'journey.studio.weight.600': 'Seminegrito',
'journey.studio.weight.700': 'Negrito',
'journey.studio.weight.800': 'Extranegrito',
'journey.studio.weight.900': 'Preto',
'journey.studio.weightOnly': 'Apenas um peso',
'journey.studio.italicSlanted': 'Itálico, inclinado: esta fonte não tem itálico próprio',
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -115,6 +116,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -587,7 +587,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'Mosaic',
'journey.studio.tpl.bandQuote': 'Paraules al mig',
'journey.studio.tpl.staggerFour': 'Quatre esglaonades',
'journey.studio.weightMissing': 'Aquesta tipografia no té aquest gruix',
'journey.studio.mapSource': 'Origen del mapa',
'journey.studio.mapSourceVector': 'Contorns',
'journey.studio.mapSourceRelief': 'Relleu',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'Canvia la tipografia',
'journey.studio.fonts.search': 'Cerca tipografies',
'journey.studio.fonts.list': 'Tipografies',
'journey.studio.fonts.used': 'Utilitzades en aquest llibre',
'journey.studio.fonts.none': 'Cap tipografia coincideix',
'journey.studio.fonts.range': '{from} a {to}',
'journey.studio.fonts.cat.sans': 'Sense serifa',
'journey.studio.fonts.cat.serif': 'Amb serifa',
'journey.studio.fonts.cat.elegant': 'Títols elegants',
'journey.studio.fonts.cat.condensed': 'Estreta i cartell',
'journey.studio.fonts.cat.retro': 'Gruixuda i retro',
'journey.studio.fonts.cat.script': 'Cal·ligràfica i manuscrita',
'journey.studio.fonts.cat.mono': 'Monoespaiada',
'journey.studio.weight.100': 'Ultrafina',
'journey.studio.weight.200': 'Extrafina',
'journey.studio.weight.300': 'Fina',
'journey.studio.weight.400': 'Normal',
'journey.studio.weight.500': 'Mitjana',
'journey.studio.weight.600': 'Seminegreta',
'journey.studio.weight.700': 'Negreta',
'journey.studio.weight.800': 'Extranegreta',
'journey.studio.weight.900': 'Negra',
'journey.studio.weightOnly': 'Només un pes',
'journey.studio.italicSlanted': 'Cursiva, inclinada: aquesta tipografia no té cursiva pròpia',
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -591,7 +591,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'Mozaika',
'journey.studio.tpl.bandQuote': 'Slova uprostřed',
'journey.studio.tpl.staggerFour': 'Čtyři přesazené',
'journey.studio.weightMissing': 'Toto písmo tento řez nemá',
'journey.studio.mapSource': 'Zdroj mapy',
'journey.studio.mapSourceVector': 'Obrysy',
'journey.studio.mapSourceRelief': 'Reliéf',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'Změnit písmo',
'journey.studio.fonts.search': 'Hledat písma',
'journey.studio.fonts.list': 'Písma',
'journey.studio.fonts.used': 'Použitá v této knize',
'journey.studio.fonts.none': 'Žádné písmo neodpovídá',
'journey.studio.fonts.range': '{from} až {to}',
'journey.studio.fonts.cat.sans': 'Bezpatková',
'journey.studio.fonts.cat.serif': 'Patková',
'journey.studio.fonts.cat.elegant': 'Elegantní titulková',
'journey.studio.fonts.cat.condensed': 'Úzká a plakátová',
'journey.studio.fonts.cat.retro': 'Těžká a retro',
'journey.studio.fonts.cat.script': 'Psací a ručně psaná',
'journey.studio.fonts.cat.mono': 'Neproporcionální',
'journey.studio.weight.100': 'Tenké',
'journey.studio.weight.200': 'Extra lehké',
'journey.studio.weight.300': 'Lehké',
'journey.studio.weight.400': 'Běžné',
'journey.studio.weight.500': 'Střední',
'journey.studio.weight.600': 'Polotučné',
'journey.studio.weight.700': 'Tučné',
'journey.studio.weight.800': 'Extra tučné',
'journey.studio.weight.900': 'Černé',
'journey.studio.weightOnly': 'Jen jeden řez',
'journey.studio.italicSlanted': 'Kurzíva, skloněná: toto písmo nemá vlastní kurzívu',
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -588,7 +588,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'Mosaik',
'journey.studio.tpl.bandQuote': 'Worte dazwischen',
'journey.studio.tpl.staggerFour': 'Vier versetzt',
'journey.studio.weightMissing': 'Diese Schrift hat diesen Schnitt nicht',
'journey.studio.mapSource': 'Kartenquelle',
'journey.studio.mapSourceVector': 'Umrisse',
'journey.studio.mapSourceRelief': 'Relief',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'Schrift ändern',
'journey.studio.fonts.search': 'Schriften suchen',
'journey.studio.fonts.list': 'Schriften',
'journey.studio.fonts.used': 'In diesem Buch verwendet',
'journey.studio.fonts.none': 'Keine Schrift passt',
'journey.studio.fonts.range': '{from} bis {to}',
'journey.studio.fonts.cat.sans': 'Serifenlos',
'journey.studio.fonts.cat.serif': 'Serifen',
'journey.studio.fonts.cat.elegant': 'Elegante Titelschriften',
'journey.studio.fonts.cat.condensed': 'Schmal und Plakat',
'journey.studio.fonts.cat.retro': 'Kräftig und Retro',
'journey.studio.fonts.cat.script': 'Schreib- und Handschrift',
'journey.studio.fonts.cat.mono': 'Festbreite',
'journey.studio.weight.100': 'Dünn',
'journey.studio.weight.200': 'Extraleicht',
'journey.studio.weight.300': 'Leicht',
'journey.studio.weight.400': 'Normal',
'journey.studio.weight.500': 'Mittel',
'journey.studio.weight.600': 'Halbfett',
'journey.studio.weight.700': 'Fett',
'journey.studio.weight.800': 'Extrafett',
'journey.studio.weight.900': 'Schwarz',
'journey.studio.weightOnly': 'Nur ein Schnitt',
'journey.studio.italicSlanted': 'Kursiv, geneigt: diese Schrift hat keine eigene Kursive',
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -584,7 +584,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'Mosaic',
'journey.studio.tpl.bandQuote': 'Words between',
'journey.studio.tpl.staggerFour': 'Staggered four',
'journey.studio.weightMissing': 'This typeface does not ship that weight',
'journey.studio.mapSource': 'Map source',
'journey.studio.mapSourceVector': 'Outlines',
'journey.studio.mapSourceRelief': 'Relief',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'Change typeface',
'journey.studio.fonts.search': 'Search typefaces',
'journey.studio.fonts.list': 'Typefaces',
'journey.studio.fonts.used': 'Used in this book',
'journey.studio.fonts.none': 'No typeface matches',
'journey.studio.fonts.range': '{from} to {to}',
'journey.studio.fonts.cat.sans': 'Sans serif',
'journey.studio.fonts.cat.serif': 'Serif',
'journey.studio.fonts.cat.elegant': 'Elegant display',
'journey.studio.fonts.cat.condensed': 'Condensed and poster',
'journey.studio.fonts.cat.retro': 'Heavy and retro',
'journey.studio.fonts.cat.script': 'Script and handwriting',
'journey.studio.fonts.cat.mono': 'Monospace',
'journey.studio.weight.100': 'Thin',
'journey.studio.weight.200': 'Extra light',
'journey.studio.weight.300': 'Light',
'journey.studio.weight.400': 'Regular',
'journey.studio.weight.500': 'Medium',
'journey.studio.weight.600': 'Semibold',
'journey.studio.weight.700': 'Bold',
'journey.studio.weight.800': 'Extra bold',
'journey.studio.weight.900': 'Black',
'journey.studio.weightOnly': 'One weight only',
'journey.studio.italicSlanted': 'Italic, slanted: this typeface has no italic of its own',
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -587,7 +587,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'Mosaico',
'journey.studio.tpl.bandQuote': 'Palabras en medio',
'journey.studio.tpl.staggerFour': 'Cuatro escalonadas',
'journey.studio.weightMissing': 'Esta tipografía no tiene ese grosor',
'journey.studio.mapSource': 'Origen del mapa',
'journey.studio.mapSourceVector': 'Contornos',
'journey.studio.mapSourceRelief': 'Relieve',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'Cambiar tipografía',
'journey.studio.fonts.search': 'Buscar tipografías',
'journey.studio.fonts.list': 'Tipografías',
'journey.studio.fonts.used': 'Usadas en este libro',
'journey.studio.fonts.none': 'Ninguna tipografía coincide',
'journey.studio.fonts.range': '{from} a {to}',
'journey.studio.fonts.cat.sans': 'Sin serifa',
'journey.studio.fonts.cat.serif': 'Con serifa',
'journey.studio.fonts.cat.elegant': 'Títulos elegantes',
'journey.studio.fonts.cat.condensed': 'Estrecha y cartel',
'journey.studio.fonts.cat.retro': 'Gruesa y retro',
'journey.studio.fonts.cat.script': 'Caligráfica y manuscrita',
'journey.studio.fonts.cat.mono': 'Monoespaciada',
'journey.studio.weight.100': 'Ultrafina',
'journey.studio.weight.200': 'Extrafina',
'journey.studio.weight.300': 'Fina',
'journey.studio.weight.400': 'Normal',
'journey.studio.weight.500': 'Media',
'journey.studio.weight.600': 'Seminegrita',
'journey.studio.weight.700': 'Negrita',
'journey.studio.weight.800': 'Extranegrita',
'journey.studio.weight.900': 'Negra',
'journey.studio.weightOnly': 'Un solo peso',
'journey.studio.italicSlanted': 'Cursiva, inclinada: esta tipografía no tiene cursiva propia',
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -585,7 +585,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'Mosaiik',
'journey.studio.tpl.bandQuote': 'Sõnad vahel',
'journey.studio.tpl.staggerFour': 'Neli nihkega',
'journey.studio.weightMissing': 'Sellel kirjatüübil pole seda paksust',
'journey.studio.mapSource': 'Kaardi allikas',
'journey.studio.mapSourceVector': 'Kontuurid',
'journey.studio.mapSourceRelief': 'Reljeef',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'Muuda kirjatüüpi',
'journey.studio.fonts.search': 'Otsi kirjatüüpe',
'journey.studio.fonts.list': 'Kirjatüübid',
'journey.studio.fonts.used': 'Selles raamatus kasutatud',
'journey.studio.fonts.none': 'Ükski kirjatüüp ei sobi',
'journey.studio.fonts.range': '{from} kuni {to}',
'journey.studio.fonts.cat.sans': 'Seriifideta',
'journey.studio.fonts.cat.serif': 'Seriifidega',
'journey.studio.fonts.cat.elegant': 'Elegantsed pealkirjakirjad',
'journey.studio.fonts.cat.condensed': 'Kitsas ja plakat',
'journey.studio.fonts.cat.retro': 'Raske ja retro',
'journey.studio.fonts.cat.script': 'Kalligraafiline ja käekiri',
'journey.studio.fonts.cat.mono': 'Püsilaiusega',
'journey.studio.weight.100': 'Õhuke',
'journey.studio.weight.200': 'Eriti kerge',
'journey.studio.weight.300': 'Kerge',
'journey.studio.weight.400': 'Tavaline',
'journey.studio.weight.500': 'Keskmine',
'journey.studio.weight.600': 'Poolpaks',
'journey.studio.weight.700': 'Paks',
'journey.studio.weight.800': 'Eriti paks',
'journey.studio.weight.900': 'Must',
'journey.studio.weightOnly': 'Ainult üks paksus',
'journey.studio.italicSlanted': 'Kursiiv, kallutatud: sellel kirjatüübil pole oma kursiivi',
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -586,7 +586,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'Mosaïque',
'journey.studio.tpl.bandQuote': 'Mots au milieu',
'journey.studio.tpl.staggerFour': 'Quatre décalées',
'journey.studio.weightMissing': 'Cette police n’a pas cette graisse',
'journey.studio.mapSource': 'Source de la carte',
'journey.studio.mapSourceVector': 'Contours',
'journey.studio.mapSourceRelief': 'Relief',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'Changer de police',
'journey.studio.fonts.search': 'Rechercher une police',
'journey.studio.fonts.list': 'Polices',
'journey.studio.fonts.used': 'Utilisées dans ce livre',
'journey.studio.fonts.none': 'Aucune police ne correspond',
'journey.studio.fonts.range': '{from} à {to}',
'journey.studio.fonts.cat.sans': 'Sans empattements',
'journey.studio.fonts.cat.serif': 'Avec empattements',
'journey.studio.fonts.cat.elegant': 'Titrage élégant',
'journey.studio.fonts.cat.condensed': 'Étroite et affiche',
'journey.studio.fonts.cat.retro': 'Grasse et rétro',
'journey.studio.fonts.cat.script': 'Script et manuscrite',
'journey.studio.fonts.cat.mono': 'Chasse fixe',
'journey.studio.weight.100': 'Ultra-fin',
'journey.studio.weight.200': 'Extra-fin',
'journey.studio.weight.300': 'Fin',
'journey.studio.weight.400': 'Normal',
'journey.studio.weight.500': 'Moyen',
'journey.studio.weight.600': 'Demi-gras',
'journey.studio.weight.700': 'Gras',
'journey.studio.weight.800': 'Extra-gras',
'journey.studio.weight.900': 'Noir',
'journey.studio.weightOnly': 'Une seule graisse',
'journey.studio.italicSlanted': "Italique, penché : cette police n'a pas d'italique propre",
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -590,7 +590,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'Ψηφιδωτό',
'journey.studio.tpl.bandQuote': 'Λέξεις ανάμεσα',
'journey.studio.tpl.staggerFour': 'Τέσσερις σε κλιμάκωση',
'journey.studio.weightMissing': 'Αυτή η γραμματοσειρά δεν έχει αυτό το βάρος',
'journey.studio.mapSource': 'Πηγή χάρτη',
'journey.studio.mapSourceVector': 'Περιγράμματα',
'journey.studio.mapSourceRelief': 'Ανάγλυφο',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'Αλλαγή γραμματοσειράς',
'journey.studio.fonts.search': 'Αναζήτηση γραμματοσειρών',
'journey.studio.fonts.list': 'Γραμματοσειρές',
'journey.studio.fonts.used': 'Χρησιμοποιούνται σε αυτό το βιβλίο',
'journey.studio.fonts.none': 'Καμία γραμματοσειρά δεν ταιριάζει',
'journey.studio.fonts.range': '{from} έως {to}',
'journey.studio.fonts.cat.sans': 'Χωρίς πατούρες',
'journey.studio.fonts.cat.serif': 'Με πατούρες',
'journey.studio.fonts.cat.elegant': 'Κομψές τίτλων',
'journey.studio.fonts.cat.condensed': 'Στενές και αφίσας',
'journey.studio.fonts.cat.retro': 'Βαριές και ρετρό',
'journey.studio.fonts.cat.script': 'Καλλιγραφικές και χειρόγραφες',
'journey.studio.fonts.cat.mono': 'Σταθερού πλάτους',
'journey.studio.weight.100': 'Λεπτά',
'journey.studio.weight.200': 'Πολύ ελαφριά',
'journey.studio.weight.300': 'Ελαφριά',
'journey.studio.weight.400': 'Κανονικά',
'journey.studio.weight.500': 'Μεσαία',
'journey.studio.weight.600': 'Ημίμαυρα',
'journey.studio.weight.700': 'Έντονα',
'journey.studio.weight.800': 'Πολύ έντονα',
'journey.studio.weight.900': 'Μαύρα',
'journey.studio.weightOnly': 'Μόνο ένα πάχος',
'journey.studio.italicSlanted': 'Πλάγια, με κλίση: αυτή η γραμματοσειρά δεν έχει δικά της πλάγια',
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -584,7 +584,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'Mozaik',
'journey.studio.tpl.bandQuote': 'Szavak középen',
'journey.studio.tpl.staggerFour': 'Négy eltolva',
'journey.studio.weightMissing': 'Ennek a betűtípusnak nincs ilyen vastagsága',
'journey.studio.mapSource': 'Térkép forrása',
'journey.studio.mapSourceVector': 'Körvonalak',
'journey.studio.mapSourceRelief': 'Domborzat',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'Betűtípus módosítása',
'journey.studio.fonts.search': 'Betűtípusok keresése',
'journey.studio.fonts.list': 'Betűtípusok',
'journey.studio.fonts.used': 'Ebben a könyvben használt',
'journey.studio.fonts.none': 'Nincs egyező betűtípus',
'journey.studio.fonts.range': '{from} és {to} között',
'journey.studio.fonts.cat.sans': 'Talp nélküli',
'journey.studio.fonts.cat.serif': 'Talpas',
'journey.studio.fonts.cat.elegant': 'Elegáns címbetűk',
'journey.studio.fonts.cat.condensed': 'Keskeny és plakát',
'journey.studio.fonts.cat.retro': 'Vaskos és retró',
'journey.studio.fonts.cat.script': 'Írott és kézírásos',
'journey.studio.fonts.cat.mono': 'Fix szélességű',
'journey.studio.weight.100': 'Vékony',
'journey.studio.weight.200': 'Extra világos',
'journey.studio.weight.300': 'Világos',
'journey.studio.weight.400': 'Normál',
'journey.studio.weight.500': 'Közepes',
'journey.studio.weight.600': 'Félkövér',
'journey.studio.weight.700': 'Kövér',
'journey.studio.weight.800': 'Extra kövér',
'journey.studio.weight.900': 'Fekete',
'journey.studio.weightOnly': 'Csak egy vastagság',
'journey.studio.italicSlanted': 'Dőlt, döntött: ennek a betűtípusnak nincs saját dőltje',
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -576,7 +576,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'Mozaik',
'journey.studio.tpl.bandQuote': 'Kata di tengah',
'journey.studio.tpl.staggerFour': 'Empat berselang',
'journey.studio.weightMissing': 'Huruf ini tidak punya ketebalan itu',
'journey.studio.mapSource': 'Sumber peta',
'journey.studio.mapSourceVector': 'Garis luar',
'journey.studio.mapSourceRelief': 'Relief',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'Ganti jenis huruf',
'journey.studio.fonts.search': 'Cari jenis huruf',
'journey.studio.fonts.list': 'Jenis huruf',
'journey.studio.fonts.used': 'Dipakai di buku ini',
'journey.studio.fonts.none': 'Tidak ada jenis huruf yang cocok',
'journey.studio.fonts.range': '{from} sampai {to}',
'journey.studio.fonts.cat.sans': 'Tanpa kait',
'journey.studio.fonts.cat.serif': 'Berkait',
'journey.studio.fonts.cat.elegant': 'Judul elegan',
'journey.studio.fonts.cat.condensed': 'Ramping dan poster',
'journey.studio.fonts.cat.retro': 'Tebal dan retro',
'journey.studio.fonts.cat.script': 'Sambung dan tulisan tangan',
'journey.studio.fonts.cat.mono': 'Lebar tetap',
'journey.studio.weight.100': 'Tipis',
'journey.studio.weight.200': 'Sangat ringan',
'journey.studio.weight.300': 'Ringan',
'journey.studio.weight.400': 'Reguler',
'journey.studio.weight.500': 'Sedang',
'journey.studio.weight.600': 'Semi tebal',
'journey.studio.weight.700': 'Tebal',
'journey.studio.weight.800': 'Sangat tebal',
'journey.studio.weight.900': 'Hitam',
'journey.studio.weightOnly': 'Hanya satu ketebalan',
'journey.studio.italicSlanted': 'Miring, dimiringkan: jenis huruf ini tidak punya miring sendiri',
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -586,7 +586,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'Mosaico',
'journey.studio.tpl.bandQuote': 'Parole in mezzo',
'journey.studio.tpl.staggerFour': 'Quattro sfalsate',
'journey.studio.weightMissing': 'Questo carattere non ha questo peso',
'journey.studio.mapSource': 'Origine mappa',
'journey.studio.mapSourceVector': 'Contorni',
'journey.studio.mapSourceRelief': 'Rilievo',
+31
View File
@@ -0,0 +1,31 @@
import type { TranslationStrings } from '../types';
/** The Studio's typeface picker and its weights. */
const studioFonts: TranslationStrings = {
'journey.studio.fonts.change': 'Cambia carattere',
'journey.studio.fonts.search': 'Cerca caratteri',
'journey.studio.fonts.list': 'Caratteri',
'journey.studio.fonts.used': 'Usati in questo libro',
'journey.studio.fonts.none': 'Nessun carattere corrisponde',
'journey.studio.fonts.range': 'da {from} a {to}',
'journey.studio.fonts.cat.sans': 'Senza grazie',
'journey.studio.fonts.cat.serif': 'Con grazie',
'journey.studio.fonts.cat.elegant': 'Titoli eleganti',
'journey.studio.fonts.cat.condensed': 'Stretto e manifesto',
'journey.studio.fonts.cat.retro': 'Pesante e retrò',
'journey.studio.fonts.cat.script': 'Calligrafico e manoscritto',
'journey.studio.fonts.cat.mono': 'Monospaziato',
'journey.studio.weight.100': 'Sottilissimo',
'journey.studio.weight.200': 'Extrasottile',
'journey.studio.weight.300': 'Sottile',
'journey.studio.weight.400': 'Normale',
'journey.studio.weight.500': 'Medio',
'journey.studio.weight.600': 'Semigrassetto',
'journey.studio.weight.700': 'Grassetto',
'journey.studio.weight.800': 'Extragrassetto',
'journey.studio.weight.900': 'Nero',
'journey.studio.weightOnly': 'Un solo peso',
'journey.studio.italicSlanted': 'Corsivo, inclinato: questo carattere non ha un corsivo proprio',
};
export default studioFonts;
+2
View File
@@ -58,6 +58,7 @@ import settings from './settings';
import share from './share';
import shared from './shared';
import storage from './storage';
import studioFonts from './studioFonts';
import system_notice from './system_notice';
import todo from './todo';
import tourCollection from './tourCollection';
@@ -114,6 +115,7 @@ const locale = {
...todo,
...notif,
...journey,
...studioFonts,
...oauth,
...system_notice,
...transport,
-1
View File
@@ -575,7 +575,6 @@ const journey: TranslationStrings = {
'journey.studio.tpl.mosaic': 'モザイク',
'journey.studio.tpl.bandQuote': '間にことば',
'journey.studio.tpl.staggerFour': '4枚ずらし',
'journey.studio.weightMissing': 'この書体にこのウェイトはありません',
'journey.studio.mapSource': '地図のソース',
'journey.studio.mapSourceVector': '輪郭',
'journey.studio.mapSourceRelief': '陰影起伏',

Some files were not shown because too many files have changed in this diff Show More