Merge pull request #390 from Luca-Timo/feat/self-hosted-fonts
feat(branding): self-hosted webfonts with filesystem scanner
This commit is contained in:
@@ -0,0 +1,293 @@
|
||||
const fs = require('fs');
|
||||
const fsPromises = fs.promises;
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
// Silence the logger so test output stays clean. Capture calls so the
|
||||
// "warning logged" assertions can still verify behaviour.
|
||||
jest.mock('../../src/utils/logger', () => ({
|
||||
warn: jest.fn(),
|
||||
info: jest.fn(),
|
||||
error: jest.fn(),
|
||||
debug: jest.fn()
|
||||
}));
|
||||
|
||||
const logger = require('../../src/utils/logger');
|
||||
|
||||
let bundledRoot;
|
||||
let userRoot;
|
||||
let fontsService;
|
||||
|
||||
/**
|
||||
* Create a font family folder with the given weights (and optional meta.json).
|
||||
* @param {string} root absolute path to the bundled or user root
|
||||
* @param {string} folderName e.g. "Inter" or "Playfair-Display"
|
||||
* @param {Array<number>|Array<string>} weights numeric weights (creates `<w>.woff2`)
|
||||
* or filenames to create directly
|
||||
* @param {Object|null} meta optional meta.json contents (object) or null
|
||||
*/
|
||||
async function makeFamily(root, folderName, weights, meta = null) {
|
||||
const dir = path.join(root, folderName);
|
||||
await fsPromises.mkdir(dir, { recursive: true });
|
||||
for (const w of weights) {
|
||||
const fname = typeof w === 'number' ? `${w}.woff2` : w;
|
||||
await fsPromises.writeFile(path.join(dir, fname), Buffer.from([]));
|
||||
}
|
||||
if (meta !== null) {
|
||||
await fsPromises.writeFile(
|
||||
path.join(dir, 'meta.json'),
|
||||
typeof meta === 'string' ? meta : JSON.stringify(meta)
|
||||
);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
bundledRoot = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'picpeak-fonts-bundled-'));
|
||||
userRoot = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'picpeak-fonts-user-'));
|
||||
|
||||
process.env.PICPEAK_BUNDLED_FONTS_ROOT = bundledRoot;
|
||||
// The user root resolves under STORAGE_PATH/fonts, so STORAGE_PATH must
|
||||
// point at the parent of userRoot — we name the leaf "fonts" ourselves.
|
||||
const storageParent = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'picpeak-fonts-storage-'));
|
||||
await fsPromises.rename(userRoot, path.join(storageParent, 'fonts'));
|
||||
userRoot = path.join(storageParent, 'fonts');
|
||||
process.env.STORAGE_PATH = storageParent;
|
||||
|
||||
// Re-require fresh after env is set so module-level constants (none here,
|
||||
// but cache state is module-level) start clean.
|
||||
jest.resetModules();
|
||||
fontsService = require('../../src/services/fontsService');
|
||||
fontsService.clearFontsCache();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
fontsService.clearFontsCache();
|
||||
await fsPromises.rm(bundledRoot, { recursive: true, force: true }).catch(() => {});
|
||||
// userRoot's parent is the actual mkdtemp; remove it.
|
||||
await fsPromises.rm(path.dirname(userRoot), { recursive: true, force: true }).catch(() => {});
|
||||
delete process.env.PICPEAK_BUNDLED_FONTS_ROOT;
|
||||
delete process.env.STORAGE_PATH;
|
||||
});
|
||||
|
||||
describe('fontsService.listFonts', () => {
|
||||
describe('roots', () => {
|
||||
test('empty bundled root + missing user root → []', async () => {
|
||||
// delete user root so it triggers ENOENT
|
||||
await fsPromises.rm(path.dirname(userRoot), { recursive: true, force: true });
|
||||
const fonts = await fontsService.listFonts();
|
||||
expect(fonts).toEqual([]);
|
||||
});
|
||||
|
||||
test('missing bundled root (ENOENT) → [], does not throw', async () => {
|
||||
await fsPromises.rm(bundledRoot, { recursive: true, force: true });
|
||||
const fonts = await fontsService.listFonts();
|
||||
expect(fonts).toEqual([]);
|
||||
});
|
||||
|
||||
test('non-directory entries at the root are skipped', async () => {
|
||||
await fsPromises.writeFile(path.join(bundledRoot, 'README.md'), 'hi');
|
||||
await makeFamily(bundledRoot, 'Inter', [400, 700]);
|
||||
const fonts = await fontsService.listFonts();
|
||||
expect(fonts.map((f) => f.family)).toEqual(['Inter']);
|
||||
});
|
||||
|
||||
test('hidden folders are skipped', async () => {
|
||||
await makeFamily(bundledRoot, '.git', [400]);
|
||||
await makeFamily(bundledRoot, '.DS_Store', [400]);
|
||||
await makeFamily(bundledRoot, 'Inter', [400]);
|
||||
const fonts = await fontsService.listFonts();
|
||||
expect(fonts.map((f) => f.family)).toEqual(['Inter']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('weight parsing', () => {
|
||||
test('three weight files → sorted ascending', async () => {
|
||||
await makeFamily(bundledRoot, 'Inter', [700, 400, 600]);
|
||||
const [inter] = await fontsService.listFonts();
|
||||
expect(inter.weights).toEqual([400, 600, 700]);
|
||||
});
|
||||
|
||||
test('non-numeric filenames are ignored', async () => {
|
||||
await makeFamily(bundledRoot, 'Inter', ['bold.woff2', 'regular.woff2', '400.woff2', '700.woff2']);
|
||||
const [inter] = await fontsService.listFonts();
|
||||
expect(inter.weights).toEqual([400, 700]);
|
||||
});
|
||||
|
||||
test('non-.woff2 files are ignored', async () => {
|
||||
await makeFamily(bundledRoot, 'Inter', ['400.ttf', '400.woff', '400.woff2', '700.otf']);
|
||||
const [inter] = await fontsService.listFonts();
|
||||
expect(inter.weights).toEqual([400]);
|
||||
});
|
||||
|
||||
test('weight values out of range (sub-1 / over-1000) are ignored', async () => {
|
||||
await makeFamily(bundledRoot, 'Inter', [0, 400, 1001, 700]);
|
||||
const [inter] = await fontsService.listFonts();
|
||||
expect(inter.weights).toEqual([400, 700]);
|
||||
});
|
||||
|
||||
test('family folder with no usable .woff2 files is silently skipped', async () => {
|
||||
await makeFamily(bundledRoot, 'NoWeights', ['readme.txt', 'bold.ttf']);
|
||||
await makeFamily(bundledRoot, 'Inter', [400]);
|
||||
const fonts = await fontsService.listFonts();
|
||||
expect(fonts.map((f) => f.family)).toEqual(['Inter']);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Skipping NoWeights')
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('folder name → display family', () => {
|
||||
test('hyphens become spaces', async () => {
|
||||
await makeFamily(bundledRoot, 'Playfair-Display', [400]);
|
||||
const [pd] = await fontsService.listFonts();
|
||||
expect(pd.family).toBe('Playfair Display');
|
||||
});
|
||||
|
||||
test('case is preserved', async () => {
|
||||
await makeFamily(bundledRoot, 'IBM-Plex-Sans', [400]);
|
||||
const [ibm] = await fontsService.listFonts();
|
||||
expect(ibm.family).toBe('IBM Plex Sans');
|
||||
});
|
||||
});
|
||||
|
||||
describe('user-overrides-bundled', () => {
|
||||
test('user folder of the same family wins; weights come from user', async () => {
|
||||
await makeFamily(bundledRoot, 'Inter', [400, 600, 700]);
|
||||
await makeFamily(userRoot, 'Inter', [400, 900]); // different weights
|
||||
const [inter] = await fontsService.listFonts();
|
||||
expect(inter.weights).toEqual([400, 900]);
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
expect.stringContaining('overrides bundled default')
|
||||
);
|
||||
});
|
||||
|
||||
test('user-only family is included', async () => {
|
||||
await makeFamily(userRoot, 'Lobster', [400]);
|
||||
const fonts = await fontsService.listFonts();
|
||||
expect(fonts.map((f) => f.family)).toEqual(['Lobster']);
|
||||
});
|
||||
|
||||
test('case-insensitive duplicate within the same root → second skipped, warning', async () => {
|
||||
// Two different folder names both producing the family "Inter".
|
||||
// On case-insensitive filesystems (APFS) this can't actually happen at
|
||||
// the FS layer; we simulate by using two different display names that
|
||||
// normalize identically. "Inter" and "INTER" lowercase to the same key.
|
||||
await makeFamily(bundledRoot, 'Inter', [400]);
|
||||
await makeFamily(bundledRoot, 'INTER', [700]);
|
||||
const fonts = await fontsService.listFonts();
|
||||
expect(fonts).toHaveLength(1);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Duplicate family')
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('meta.json — generic fallback', () => {
|
||||
test('valid generic="serif"', async () => {
|
||||
await makeFamily(bundledRoot, 'Playfair-Display', [400], { generic: 'serif' });
|
||||
const [pd] = await fontsService.listFonts();
|
||||
expect(pd.generic).toBe('serif');
|
||||
});
|
||||
|
||||
test('valid generic="cursive"', async () => {
|
||||
await makeFamily(bundledRoot, 'Comic-Neue', [400], { generic: 'cursive' });
|
||||
const [cn] = await fontsService.listFonts();
|
||||
expect(cn.generic).toBe('cursive');
|
||||
});
|
||||
|
||||
test('valid generic="monospace"', async () => {
|
||||
await makeFamily(bundledRoot, 'Fira-Mono', [400], { generic: 'monospace' });
|
||||
const [fm] = await fontsService.listFonts();
|
||||
expect(fm.generic).toBe('monospace');
|
||||
});
|
||||
|
||||
test('missing meta.json → defaults to sans-serif (no warning)', async () => {
|
||||
await makeFamily(bundledRoot, 'Inter', [400]);
|
||||
const [inter] = await fontsService.listFonts();
|
||||
expect(inter.generic).toBe('sans-serif');
|
||||
// No warning for the missing-file case (it's the normal path).
|
||||
const noisy = (logger.warn.mock.calls || []).filter((c) =>
|
||||
String(c[0]).includes('meta.json')
|
||||
);
|
||||
expect(noisy).toEqual([]);
|
||||
});
|
||||
|
||||
test('invalid generic value → defaults to sans-serif, warning logged', async () => {
|
||||
await makeFamily(bundledRoot, 'Inter', [400], { generic: 'bogus' });
|
||||
const [inter] = await fontsService.listFonts();
|
||||
expect(inter.generic).toBe('sans-serif');
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('invalid generic "bogus"')
|
||||
);
|
||||
});
|
||||
|
||||
test('malformed JSON → defaults to sans-serif, warning logged', async () => {
|
||||
await makeFamily(bundledRoot, 'Inter', [400], '{ this is not json');
|
||||
const [inter] = await fontsService.listFonts();
|
||||
expect(inter.generic).toBe('sans-serif');
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('not valid JSON')
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('result shape', () => {
|
||||
test('every family is { family, weights, generic }', async () => {
|
||||
await makeFamily(bundledRoot, 'Inter', [400, 700]);
|
||||
await makeFamily(bundledRoot, 'Playfair-Display', [400], { generic: 'serif' });
|
||||
const fonts = await fontsService.listFonts();
|
||||
for (const f of fonts) {
|
||||
expect(f).toEqual({
|
||||
family: expect.any(String),
|
||||
weights: expect.any(Array),
|
||||
generic: expect.stringMatching(/^(sans-serif|serif|cursive|monospace)$/)
|
||||
});
|
||||
expect(f.weights.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
test('output sorted alphabetically by family', async () => {
|
||||
await makeFamily(bundledRoot, 'Zilla-Slab', [400]);
|
||||
await makeFamily(bundledRoot, 'Alpha-Sans', [400]);
|
||||
await makeFamily(bundledRoot, 'Mid-Pack', [400]);
|
||||
const fonts = await fontsService.listFonts();
|
||||
expect(fonts.map((f) => f.family)).toEqual([
|
||||
'Alpha Sans',
|
||||
'Mid Pack',
|
||||
'Zilla Slab'
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cache', () => {
|
||||
test('cache hit: second call within TTL does not re-readdir', async () => {
|
||||
await makeFamily(bundledRoot, 'Inter', [400]);
|
||||
const spy = jest.spyOn(fsPromises, 'readdir');
|
||||
await fontsService.listFonts();
|
||||
const callsAfterFirst = spy.mock.calls.length;
|
||||
await fontsService.listFonts();
|
||||
expect(spy.mock.calls.length).toBe(callsAfterFirst);
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test('clearFontsCache forces a fresh scan on the next call', async () => {
|
||||
await makeFamily(bundledRoot, 'Inter', [400]);
|
||||
await fontsService.listFonts();
|
||||
|
||||
// Add a new family AFTER the cache was populated.
|
||||
await makeFamily(bundledRoot, 'Roboto', [400]);
|
||||
|
||||
// Without clearing, listFonts returns the stale cache.
|
||||
const stale = await fontsService.listFonts();
|
||||
expect(stale.map((f) => f.family)).toEqual(['Inter']);
|
||||
|
||||
// After clear, the new family appears.
|
||||
fontsService.clearFontsCache();
|
||||
const fresh = await fontsService.listFonts();
|
||||
expect(fresh.map((f) => f.family)).toEqual(['Inter', 'Roboto']);
|
||||
});
|
||||
});
|
||||
});
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"generic": "cursive"
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,114 @@
|
||||
This directory bundles the following typefaces, each licensed under the
|
||||
SIL Open Font License v1.1.
|
||||
------------------------------------------------------------
|
||||
Per-font copyright notices
|
||||
------------------------------------------------------------
|
||||
Inter
|
||||
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
|
||||
Noto Sans
|
||||
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic)
|
||||
Poppins
|
||||
Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins)
|
||||
Jost
|
||||
Copyright 2020 The Jost Project Authors (https://github.com/indestructible-type/Jost)
|
||||
Montserrat
|
||||
Copyright 2011 The Montserrat Project Authors (https://github.com/JulietaUla/Montserrat)
|
||||
Playfair Display
|
||||
Copyright 2017 The Playfair Display Project Authors (https://github.com/clauseggers/Playfair)
|
||||
IBM Plex Sans
|
||||
Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
|
||||
Comic Neue
|
||||
Copyright (c) 2014 by Craig Rozynski. All rights reserved.
|
||||
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"generic": "serif"
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -449,6 +449,34 @@ app.use('/thumbnails', require('./src/middleware/photoAuth'), setCorsHeaders, se
|
||||
// Static file serving for uploads (public - logos, favicons)
|
||||
app.use('/uploads', setCorsHeaders, secureStatic(path.join(storagePath, 'uploads')));
|
||||
|
||||
// Static file serving for self-hosted webfonts (public — gallery visitors
|
||||
// load these via @font-face). Replaces the previous Google Fonts CDN
|
||||
// dependency, which leaked visitor IPs to a third party (LG München 2022
|
||||
// GDPR ruling).
|
||||
//
|
||||
// Two mounts in priority order:
|
||||
// 1. STORAGE_PATH/fonts/ — runtime user additions (drop a folder, restart)
|
||||
// 2. backend/assets/fonts/ — bundled defaults baked into the image
|
||||
// Express evaluates handlers in order, so user-supplied files win on overlap.
|
||||
//
|
||||
// We deliberately do NOT set `immutable` on these responses. The filenames
|
||||
// are stable (e.g. Inter/400.woff2), so an admin replacing the file on disk
|
||||
// must be able to roll out the change to clients. With max-age + Last-Modified
|
||||
// (set by express.static from file mtime), browsers send If-Modified-Since
|
||||
// after expiry and pick up the new version automatically. See docs/fonts.md
|
||||
// "Replacing an existing font" for the documented rollout strategy.
|
||||
const fontStaticOpts = { maxAge: '7d' };
|
||||
app.use(
|
||||
'/fonts',
|
||||
setCorsHeaders,
|
||||
secureStatic(path.join(storagePath, 'fonts'), fontStaticOpts)
|
||||
);
|
||||
app.use(
|
||||
'/fonts',
|
||||
setCorsHeaders,
|
||||
secureStatic(path.resolve(__dirname, 'assets/fonts'), fontStaticOpts)
|
||||
);
|
||||
|
||||
// Debug endpoint to check IP detection (only in development)
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
app.get('/api/debug/ip', (req, res) => {
|
||||
@@ -563,6 +591,7 @@ app.use('/api/v1', require('./src/routes/v1/events'));
|
||||
|
||||
app.use('/api/invite', require('./src/routes/acceptInvite'));
|
||||
app.use('/api/public/settings', require('./src/routes/publicSettings'));
|
||||
app.use('/api/public/fonts', require('./src/routes/publicFonts'));
|
||||
app.use('/api/public', require('./src/routes/publicCMS'));
|
||||
app.use('/api/images', require('./src/routes/protectedImages'));
|
||||
app.use('/api/secure-images', secureImagesRoutes);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
const express = require('express');
|
||||
const { listFonts } = require('../services/fontsService');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* GET /api/public/fonts
|
||||
*
|
||||
* Returns the list of self-hosted font families discovered under
|
||||
* STORAGE_PATH/fonts/. No authentication — gallery visitors need this
|
||||
* to render the chosen theme font.
|
||||
*/
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
const fonts = await listFonts();
|
||||
res.json({ fonts });
|
||||
} catch (error) {
|
||||
logger.error('Failed to list fonts', { error: error.message });
|
||||
res.status(500).json({ error: 'Failed to list fonts' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,223 @@
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
/**
|
||||
* Filesystem-driven font scanner.
|
||||
*
|
||||
* Scans two locations for self-hosted webfonts and merges the results:
|
||||
*
|
||||
* 1. backend/assets/fonts/ — bundled defaults shipped with the repo
|
||||
* and baked into the Docker image. Visitors get a working font
|
||||
* picker out of the box, no external CDN, no GDPR exposure.
|
||||
*
|
||||
* 2. STORAGE_PATH/fonts/ — optional runtime additions. Admins drop
|
||||
* a folder here (via Docker volume / SFTP) and the family appears
|
||||
* in the picker after the cache TTL expires or the backend restarts.
|
||||
* User additions WIN over bundled defaults of the same family name —
|
||||
* this lets a deployment override e.g. with extra weights or a newer
|
||||
* version without forking the repo.
|
||||
*
|
||||
* Folder layout in either location:
|
||||
*
|
||||
* <Family-Name>/<weight>.woff2
|
||||
* <Family-Name>/meta.json (optional)
|
||||
*
|
||||
* - Folder name → display family with hyphens replaced by spaces:
|
||||
* "Playfair-Display" → "Playfair Display"
|
||||
* - Weight files must be named "<integer>.woff2" (e.g. 400.woff2).
|
||||
* Other names are ignored, family entry still includes its other weights.
|
||||
* - Optional meta.json: { "generic": "sans-serif" | "serif" | "cursive" | "monospace" }
|
||||
* Tells the picker which CSS generic family to use as a fallback when
|
||||
* building the font-family string. Defaults to "sans-serif" if absent
|
||||
* or invalid. Avoids hardcoding family-name → generic lookups in the
|
||||
* frontend, so any new family folder works without code changes.
|
||||
*
|
||||
* Result is cached in memory for FONTS_CACHE_TTL_MS so frequent
|
||||
* /api/public/fonts hits don't hit disk per request. New folders dropped
|
||||
* into a mount become visible after the TTL or on backend restart.
|
||||
*
|
||||
* Pattern mirrors backend/src/services/uploadSettings.js.
|
||||
*/
|
||||
|
||||
const FONTS_CACHE_TTL_MS = 30_000;
|
||||
const VALID_GENERICS = new Set(['sans-serif', 'serif', 'cursive', 'monospace']);
|
||||
const DEFAULT_GENERIC = 'sans-serif';
|
||||
|
||||
let cachedFonts = null;
|
||||
let fontsCacheExpiresAt = 0;
|
||||
|
||||
function getBundledFontsRoot() {
|
||||
// Test seam: the unit test suite points this at an isolated temp dir so it
|
||||
// can populate fixtures without polluting the real backend/assets tree.
|
||||
if (process.env.PICPEAK_BUNDLED_FONTS_ROOT) {
|
||||
return process.env.PICPEAK_BUNDLED_FONTS_ROOT;
|
||||
}
|
||||
// backend/src/services/fontsService.js → backend/assets/fonts
|
||||
return path.resolve(__dirname, '../../assets/fonts');
|
||||
}
|
||||
|
||||
function getUserFontsRoot() {
|
||||
const storagePath = process.env.STORAGE_PATH || path.join(__dirname, '../../../storage');
|
||||
return path.join(storagePath, 'fonts');
|
||||
}
|
||||
|
||||
function familyDisplayName(folderName) {
|
||||
return folderName.replace(/-/g, ' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to read meta.json from the family folder. Returns the validated
|
||||
* generic class or DEFAULT_GENERIC. Missing file → silent default.
|
||||
* Unreadable / malformed / invalid value → warning + default.
|
||||
*/
|
||||
async function readFamilyMeta(folderAbs, folderName) {
|
||||
const metaPath = path.join(folderAbs, 'meta.json');
|
||||
let raw;
|
||||
try {
|
||||
raw = await fs.readFile(metaPath, 'utf8');
|
||||
} catch (err) {
|
||||
if (err.code === 'ENOENT') return DEFAULT_GENERIC;
|
||||
logger.warn(`[fonts] Could not read meta.json for ${folderName}: ${err.message}`);
|
||||
return DEFAULT_GENERIC;
|
||||
}
|
||||
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch (err) {
|
||||
logger.warn(`[fonts] meta.json for ${folderName} is not valid JSON: ${err.message}`);
|
||||
return DEFAULT_GENERIC;
|
||||
}
|
||||
|
||||
const generic = parsed && typeof parsed.generic === 'string' ? parsed.generic : null;
|
||||
if (generic && VALID_GENERICS.has(generic)) {
|
||||
return generic;
|
||||
}
|
||||
if (generic) {
|
||||
logger.warn(
|
||||
`[fonts] meta.json for ${folderName} has invalid generic "${generic}"; ` +
|
||||
`expected one of ${Array.from(VALID_GENERICS).join(', ')}. Falling back to ${DEFAULT_GENERIC}.`
|
||||
);
|
||||
}
|
||||
return DEFAULT_GENERIC;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one family folder and return { family, weights, generic } or null
|
||||
* if the folder has no usable .woff2 files.
|
||||
*/
|
||||
async function readFamilyFolder(rootAbs, folderName) {
|
||||
const folderAbs = path.join(rootAbs, folderName);
|
||||
let entries;
|
||||
try {
|
||||
entries = await fs.readdir(folderAbs, { withFileTypes: true });
|
||||
} catch (err) {
|
||||
logger.warn(`[fonts] Could not read family folder ${folderName} in ${rootAbs}: ${err.message}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const weights = [];
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile()) continue;
|
||||
if (!entry.name.toLowerCase().endsWith('.woff2')) continue;
|
||||
const stem = entry.name.slice(0, -'.woff2'.length);
|
||||
if (!/^\d+$/.test(stem)) continue; // ignore non-numeric weight names
|
||||
const weight = parseInt(stem, 10);
|
||||
if (weight < 1 || weight > 1000) continue;
|
||||
weights.push(weight);
|
||||
}
|
||||
|
||||
if (weights.length === 0) {
|
||||
logger.warn(`[fonts] Skipping ${folderName} in ${rootAbs}: no usable <weight>.woff2 files`);
|
||||
return null;
|
||||
}
|
||||
|
||||
weights.sort((a, b) => a - b);
|
||||
const generic = await readFamilyMeta(folderAbs, folderName);
|
||||
return { family: familyDisplayName(folderName), weights, generic };
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan one root directory and return its families as a Map keyed by
|
||||
* lowercased family name (for case-insensitive de-dup against the other
|
||||
* root). Missing directory → empty Map (not an error).
|
||||
*/
|
||||
async function scanRoot(rootAbs) {
|
||||
let entries;
|
||||
try {
|
||||
entries = await fs.readdir(rootAbs, { withFileTypes: true });
|
||||
} catch (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
return new Map();
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const result = new Map();
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
if (entry.name.startsWith('.')) continue;
|
||||
|
||||
const family = await readFamilyFolder(rootAbs, entry.name);
|
||||
if (!family) continue;
|
||||
|
||||
const lc = family.family.toLowerCase();
|
||||
if (result.has(lc)) {
|
||||
logger.warn(
|
||||
`[fonts] Duplicate family ${family.family} within ${rootAbs}; ` +
|
||||
`keeping the first encountered folder`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
result.set(lc, family);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* List all available font families (bundled + user additions, merged).
|
||||
* Cached for FONTS_CACHE_TTL_MS.
|
||||
*
|
||||
* @returns {Promise<Array<{ family: string, weights: number[], generic: string }>>}
|
||||
*/
|
||||
async function listFonts() {
|
||||
if (Date.now() < fontsCacheExpiresAt && cachedFonts !== null) {
|
||||
return cachedFonts;
|
||||
}
|
||||
|
||||
const bundled = await scanRoot(getBundledFontsRoot());
|
||||
const userAdded = await scanRoot(getUserFontsRoot());
|
||||
|
||||
// User additions override bundled families of the same name.
|
||||
const merged = new Map(bundled);
|
||||
for (const [lc, family] of userAdded) {
|
||||
if (merged.has(lc)) {
|
||||
logger.info(
|
||||
`[fonts] User-supplied ${family.family} overrides bundled default`
|
||||
);
|
||||
}
|
||||
merged.set(lc, family);
|
||||
}
|
||||
|
||||
const families = Array.from(merged.values()).sort((a, b) =>
|
||||
a.family.localeCompare(b.family)
|
||||
);
|
||||
|
||||
cachedFonts = families;
|
||||
fontsCacheExpiresAt = Date.now() + FONTS_CACHE_TTL_MS;
|
||||
return cachedFonts;
|
||||
}
|
||||
|
||||
function clearFontsCache() {
|
||||
cachedFonts = null;
|
||||
fontsCacheExpiresAt = 0;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
listFonts,
|
||||
clearFontsCache,
|
||||
getBundledFontsRoot,
|
||||
getUserFontsRoot
|
||||
};
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
# Self-hosted webfonts
|
||||
|
||||
PicPeak ships with a curated set of webfonts baked into the backend image and serves them from your own origin. **No requests go to `fonts.googleapis.com` or any third-party CDN** — guest IPs stay private, which is important for GDPR compliance (LG München 2022).
|
||||
|
||||
The font picker in the admin theme customizer is **data-driven**: whatever the backend finds on disk, the picker offers. This page documents the conventions and the workflow for adding your own families.
|
||||
|
||||
## What ships out of the box
|
||||
|
||||
The Docker image bundles 8 OFL-licensed families at `backend/assets/fonts/`:
|
||||
|
||||
- Comic Neue
|
||||
- IBM Plex Sans
|
||||
- Inter (the default)
|
||||
- Jost
|
||||
- Montserrat
|
||||
- Noto Sans
|
||||
- Playfair Display
|
||||
- Poppins
|
||||
|
||||
These appear in the admin theme customizer with no configuration.
|
||||
|
||||
## Adding your own font (drop a folder, restart)
|
||||
|
||||
You don't need to fork the repo. Place a font folder in your runtime storage volume — the same volume that holds events, thumbnails, etc. — and it appears in the picker after the next backend restart (or within ~30 seconds of being added, whichever comes first).
|
||||
|
||||
### 1. Choose where on the host
|
||||
|
||||
Bind-mount target inside the container is `/app/storage/fonts/` (the env var `STORAGE_PATH` controls the prefix; defaults to `/app/storage`). On the host, that's wherever your `docker-compose.yml` mounts `${APP_STORAGE}` from — typically `./storage/`.
|
||||
|
||||
### 2. Folder layout
|
||||
|
||||
```
|
||||
storage/fonts/
|
||||
└── <Family-Name>/
|
||||
├── 400.woff2
|
||||
├── 600.woff2
|
||||
├── 700.woff2
|
||||
└── meta.json (optional)
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- **Folder name** = display family name with spaces replaced by hyphens. The scanner turns `Roboto-Slab/` → `Roboto Slab`. Use the exact upstream family name; capitalisation is preserved.
|
||||
- **File names** are `<weight>.woff2` where `<weight>` is an integer (100-900). Other names are ignored. The picker doesn't expose individual weights, but the runtime injects all available weights in the `@font-face` block so headings (semibold/bold) render correctly.
|
||||
- **Format** must be `.woff2`. Other formats are ignored. WOFF2 is universally supported and the smallest on the wire.
|
||||
- **No italics** in v1 (the picker doesn't expose them). Italic files in the folder are silently ignored.
|
||||
- **`meta.json`** (optional) tells the picker which CSS generic family to fall back to while the font file is loading (and permanently if the file ever 404s). Shape: `{ "generic": "sans-serif" | "serif" | "cursive" | "monospace" }`. Defaults to `sans-serif` if absent. Add this for serif fonts (e.g. Playfair Display) and cursive/display fonts (e.g. Comic Neue, Lobster) so visitors don't briefly see Helvetica during the font fetch.
|
||||
|
||||
### 3. Where to download fonts
|
||||
|
||||
For Google-Fonts-licensed families, use [google-webfonts-helper](https://gwfh.mranftl.com/fonts):
|
||||
|
||||
1. Pick the family.
|
||||
2. Charsets section → **Latin** only (uncheck others unless you actually need them; Cyrillic alone roughly doubles file size).
|
||||
3. Styles section → **400, 600, 700** at minimum (these match what the picker uses).
|
||||
4. Click "Download files" — you'll get a ZIP containing the `.woff2` files plus the family's OFL license.
|
||||
5. Rename the files to `400.woff2`, `600.woff2`, `700.woff2` and drop them in `storage/fonts/<Family-Name>/`.
|
||||
6. Keep the OFL license file alongside (the static handler serves anything in the folder, so `/fonts/<Family-Name>/OFL.txt` is publicly available — this satisfies OFL §2's "license must be included with all copies").
|
||||
|
||||
For non-Google fonts, ensure you have the right to redistribute. SIL Open Font License (OFL), Apache 2.0, and most "free for commercial use" web licenses allow this.
|
||||
|
||||
### 4. Activation
|
||||
|
||||
Either:
|
||||
|
||||
- **Restart the backend container** (immediate), or
|
||||
- **Wait ~30 seconds** for the in-memory cache to expire and the next `/api/public/fonts` request to re-scan.
|
||||
|
||||
Refresh the admin customizer; the new family appears in the body and heading dropdowns.
|
||||
|
||||
> **Note:** The admin customizer caches the fonts list separately for 5 minutes (React Query staleTime). After the backend picks up a new family, hard-reload the customizer page (⌘+Shift+R / Ctrl+Shift+R) to see it immediately, or wait up to 5 minutes for the frontend cache to expire on its own. The two caches serve different purposes — the backend avoids disk hits per request; the frontend avoids network hits per re-render — so we keep them independent and document the worst case rather than try to synchronise them.
|
||||
|
||||
## How it works
|
||||
|
||||
- **Scanner**: `backend/src/services/fontsService.js` reads two locations and merges them: `backend/assets/fonts/` (bundled) + `STORAGE_PATH/fonts/` (user). User additions override bundled families of the same name. Cached for 30 s.
|
||||
- **Listing endpoint**: `GET /api/public/fonts` returns `{ fonts: [{ family, weights, generic }, ...] }`.
|
||||
- **Static serving**: `GET /fonts/<Family-Name>/<weight>.woff2` returns the actual file. Path-traversal protected. `Cache-Control: max-age=7d` — clients revalidate via `If-Modified-Since` after expiry, so replacing a file on disk eventually rolls out without admin action (see "Replacing an existing font" below).
|
||||
- **Lazy injection**: `frontend/src/contexts/ThemeContext.tsx` watches `theme.fontFamily` / `theme.headingFontFamily` and injects exactly one `@font-face` block per family the page actually uses, into a single `<style id="self-hosted-fonts">` element. Other families are not loaded for that visitor.
|
||||
- **Bootstrap**: `frontend/src/index.css` ships static `@font-face` blocks for Inter so the very first paint already has the default body font.
|
||||
|
||||
## Caveats and edge cases
|
||||
|
||||
- **Empty folder** (no `<weight>.woff2` files) → silently skipped, warning in backend logs.
|
||||
- **Two folders that normalize to the same family** on case-insensitive filesystems (macOS APFS) → second is skipped, warning logged.
|
||||
- **Weight files with non-numeric names** (e.g. `bold.woff2`, `regular.woff2`) → ignored; family entry still includes its other weights.
|
||||
- **Removing the `Inter/` folder** → the very-first-paint bootstrap CSS in `index.css` will 404 the font requests; browsers fall back to the next family in `--font-family` (Noto Sans → system-ui). Cosmetic only; no other breakage.
|
||||
- **Variable fonts** are not supported in v1. Each weight must be a separate file.
|
||||
- **Italics** are not exposed in the picker.
|
||||
- **Per-option dropdown previews** (each font name rendered in its own face inside the picker) are not supported in v1. Browser support for styling `<option>` elements is inconsistent — Safari ignores it in the popup entirely, and Chrome/Firefox were unreliable in testing. A future improvement is to replace the native `<select>` with a custom dropdown component or to render a separate "preview text" box below the picker.
|
||||
|
||||
### Replacing an existing font
|
||||
|
||||
Browsers cache font files for up to 7 days. When you overwrite an existing weight file (e.g. swap your `Inter/400.woff2` for a different cut), some visitors may keep seeing the old face for up to a week, even after a backend restart.
|
||||
|
||||
Two ways to roll out a replacement:
|
||||
|
||||
1. **Wait it out.** Without `immutable` on the cache header, browsers send `If-Modified-Since` once the 7-day window expires; the backend responds based on file mtime, so the new file gets picked up automatically the next time each client revisits the gallery.
|
||||
2. **Force-bust the cache by renaming the family folder.** Move `Inter/` → `Inter-v2/` (with the new file inside) and update the affected event themes to use `Inter v2`. The new folder is served from a new URL, so caches don't apply and every client picks up the new face on next page load. This is the right approach when you need an immediate, gallery-wide rollout.
|
||||
|
||||
The first option is fine for cosmetic touch-ups; the second is what to do when a font replacement is genuinely urgent.
|
||||
|
||||
## License
|
||||
|
||||
The bundled fonts are all SIL Open Font License v1.1 (OFL). The license text and per-font copyright notices live at `backend/assets/fonts/LICENSE-OFL.txt` and are publicly served at `/fonts/LICENSE-OFL.txt`.
|
||||
|
||||
If you redistribute the PicPeak Docker image, you redistribute these fonts too — you must keep the LICENSE-OFL.txt file accessible. The default static handler does this for you.
|
||||
@@ -122,6 +122,24 @@ server {
|
||||
proxy_cache_valid 404 1m;
|
||||
}
|
||||
|
||||
# Self-hosted webfonts proxy (bundled families + admin user additions).
|
||||
# ^~ modifier stops regex matching, ensuring fonts are proxied to the
|
||||
# backend (which scans backend/assets/fonts and STORAGE_PATH/fonts) and
|
||||
# NOT served locally — the .woff2 files do not exist in the frontend image.
|
||||
location ^~ /fonts {
|
||||
set $backend_upstream backend;
|
||||
proxy_pass http://$backend_upstream:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# Fonts rarely change; cache aggressively (matches backend Cache-Control).
|
||||
proxy_cache_valid 200 302 7d;
|
||||
proxy_cache_valid 404 1m;
|
||||
}
|
||||
|
||||
# Dynamic robots.txt served by backend
|
||||
location = /robots.txt {
|
||||
set $backend_upstream backend;
|
||||
|
||||
@@ -4,9 +4,43 @@ import { Button, Card, Input } from '../common';
|
||||
import { ThemeConfig, GALLERY_THEME_PRESETS, GalleryLayoutType, HeaderStyleType, HeroDividerStyle } from '../../types/theme.types';
|
||||
import type { EnabledTemplate } from '../../services/cssTemplates.service';
|
||||
import { settingsService } from '../../services/settings.service';
|
||||
import { fontsService, extractFamilyName, type FontDefinition } from '../../services/fonts.service';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
/**
|
||||
* Build the CSS font-family value for a scanned font, using the generic
|
||||
* fallback the backend supplied (from each family's optional meta.json).
|
||||
* Defaults to 'sans-serif' when the backend doesn't report one — keeps
|
||||
* compatibility with backends that predate the generic field.
|
||||
*/
|
||||
function buildFontFamilyValue(font: FontDefinition): string {
|
||||
const generic = font.generic ?? 'sans-serif';
|
||||
// Always quote the family name (covers multi-word like 'Playfair Display').
|
||||
return `'${font.family}', ${generic}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Match a saved CSS font-family string against the available scanned families
|
||||
* and return the canonical option value the dropdown renders. Handles both
|
||||
* legacy unquoted strings ("Inter, sans-serif") and the new quoted format
|
||||
* ("'Inter', sans-serif"), so events saved before this change still show the
|
||||
* right option as selected.
|
||||
*/
|
||||
function resolveFontDropdownValue(
|
||||
saved: string | undefined,
|
||||
available: FontDefinition[] | undefined,
|
||||
fallback: string
|
||||
): string {
|
||||
if (!saved) return fallback;
|
||||
const family = extractFamilyName(saved);
|
||||
if (!family) return saved; // generic family like "system-ui, sans-serif"
|
||||
const match = (available || []).find(
|
||||
(f) => f.family.toLowerCase() === family.toLowerCase()
|
||||
);
|
||||
return match ? buildFontFamilyValue(match) : saved;
|
||||
}
|
||||
|
||||
interface ThemeCustomizerEnhancedProps {
|
||||
value: ThemeConfig;
|
||||
onChange: (theme: ThemeConfig) => void;
|
||||
@@ -100,6 +134,15 @@ export const ThemeCustomizerEnhanced: React.FC<ThemeCustomizerEnhancedProps> = (
|
||||
staleTime: 60000,
|
||||
});
|
||||
|
||||
// Fetch the list of self-hosted font families discovered by the backend
|
||||
// scanner. Used to populate the body / heading font dropdowns. Cached
|
||||
// 5 minutes — fonts rarely change without a backend restart.
|
||||
const { data: availableFonts } = useQuery<FontDefinition[]>({
|
||||
queryKey: ['fonts'],
|
||||
queryFn: () => fontsService.list(),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
});
|
||||
|
||||
const thumbnailWidth = parseInt(allSettings?.thumbnail_width) || 300;
|
||||
const thumbnailHeight = parseInt(allSettings?.thumbnail_height) || 300;
|
||||
const isBetaLayout = BETA_LAYOUTS.includes(localTheme.galleryLayout as GalleryLayoutType);
|
||||
@@ -929,17 +972,27 @@ export const ThemeCustomizerEnhanced: React.FC<ThemeCustomizerEnhancedProps> = (
|
||||
{t('branding.bodyFont')}
|
||||
</label>
|
||||
<select
|
||||
value={localTheme.fontFamily || 'Inter, sans-serif'}
|
||||
value={resolveFontDropdownValue(
|
||||
localTheme.fontFamily,
|
||||
availableFonts,
|
||||
// Fallback when no fontFamily is saved yet: prefer the
|
||||
// scanned Inter (with its real generic), else a bare CSS
|
||||
// string when the backend hasn't loaded yet.
|
||||
(availableFonts || []).find((f) => f.family === 'Inter')
|
||||
? buildFontFamilyValue(
|
||||
(availableFonts || []).find((f) => f.family === 'Inter')!
|
||||
)
|
||||
: "'Inter', sans-serif"
|
||||
)}
|
||||
onChange={(e) => handleChange('fontFamily', e.target.value)}
|
||||
className="w-full px-3 py-2 border border-neutral-300 dark:border-neutral-600 rounded-lg bg-white dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100"
|
||||
>
|
||||
<option value="Inter, sans-serif">Inter</option>
|
||||
<option value="system-ui, sans-serif">System UI</option>
|
||||
<option value="Georgia, serif">Georgia</option>
|
||||
<option value="'Playfair Display', serif">Playfair Display</option>
|
||||
<option value="'Montserrat', sans-serif">Montserrat</option>
|
||||
<option value="'IBM Plex Sans', sans-serif">IBM Plex Sans</option>
|
||||
<option value="'Comic Neue', cursive">Comic Neue</option>
|
||||
{(availableFonts || []).map((f) => (
|
||||
<option key={f.family} value={buildFontFamilyValue(f)}>
|
||||
{f.family}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -948,15 +1001,21 @@ export const ThemeCustomizerEnhanced: React.FC<ThemeCustomizerEnhancedProps> = (
|
||||
{t('branding.headingFont')}
|
||||
</label>
|
||||
<select
|
||||
value={localTheme.headingFontFamily || localTheme.fontFamily || 'Inter, sans-serif'}
|
||||
value={resolveFontDropdownValue(
|
||||
localTheme.headingFontFamily,
|
||||
availableFonts,
|
||||
''
|
||||
)}
|
||||
onChange={(e) => handleChange('headingFontFamily', e.target.value)}
|
||||
className="w-full px-3 py-2 border border-neutral-300 dark:border-neutral-600 rounded-lg bg-white dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100"
|
||||
>
|
||||
<option value="">{t('branding.sameAsBody')}</option>
|
||||
<option value="'Playfair Display', serif">Playfair Display</option>
|
||||
<option value="'Montserrat', sans-serif">Montserrat</option>
|
||||
<option value="Georgia, serif">Georgia</option>
|
||||
<option value="'IBM Plex Sans', sans-serif">IBM Plex Sans</option>
|
||||
<option value="system-ui, sans-serif">System UI</option>
|
||||
{(availableFonts || []).map((f) => (
|
||||
<option key={f.family} value={buildFontFamilyValue(f)}>
|
||||
{f.family}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,60 @@
|
||||
import React, { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { ThemeConfig, EventTheme, GALLERY_THEME_PRESETS } from '../types/theme.types';
|
||||
import { fontsService, extractFamilyName, type FontDefinition } from '../services/fonts.service';
|
||||
|
||||
// Self-hosted font loader. Resolves the available-fonts list once (cached for
|
||||
// 5 minutes) and lazily injects @font-face blocks into <head> only for the
|
||||
// families a page actually uses. Avoids preloading every available font on
|
||||
// every gallery view.
|
||||
const FONTS_LIST_TTL_MS = 5 * 60 * 1000;
|
||||
let fontsListPromise: Promise<FontDefinition[]> | null = null;
|
||||
let fontsListExpiresAt = 0;
|
||||
const injectedFamilies = new Set<string>();
|
||||
const FONT_STYLE_ID = 'self-hosted-fonts';
|
||||
|
||||
function getFontsList(): Promise<FontDefinition[]> {
|
||||
if (fontsListPromise && Date.now() < fontsListExpiresAt) {
|
||||
return fontsListPromise;
|
||||
}
|
||||
fontsListPromise = fontsService.list().catch((err) => {
|
||||
console.error('Failed to load fonts list:', err);
|
||||
return [];
|
||||
});
|
||||
fontsListExpiresAt = Date.now() + FONTS_LIST_TTL_MS;
|
||||
return fontsListPromise;
|
||||
}
|
||||
|
||||
function ensureFontFaceLoaded(family: string, weights: number[]): void {
|
||||
if (injectedFamilies.has(family)) return;
|
||||
injectedFamilies.add(family);
|
||||
|
||||
let styleEl = document.getElementById(FONT_STYLE_ID) as HTMLStyleElement | null;
|
||||
if (!styleEl) {
|
||||
styleEl = document.createElement('style');
|
||||
styleEl.id = FONT_STYLE_ID;
|
||||
document.head.appendChild(styleEl);
|
||||
}
|
||||
|
||||
// Folder name on disk = family name with hyphens. URL-encode in case of
|
||||
// unusual characters (the scanner already restricts to subdirectory names,
|
||||
// so this is belt-and-braces).
|
||||
const folderName = family.replace(/ /g, '-');
|
||||
const blocks = weights.map(
|
||||
(w) => `@font-face{font-family:'${family}';font-style:normal;font-weight:${w};font-display:swap;src:url('/fonts/${encodeURIComponent(folderName)}/${w}.woff2') format('woff2');}`
|
||||
);
|
||||
styleEl.textContent += '\n' + blocks.join('\n');
|
||||
}
|
||||
|
||||
async function loadFontForFamily(cssFontFamily: string | undefined | null): Promise<void> {
|
||||
const family = extractFamilyName(cssFontFamily);
|
||||
if (!family) return;
|
||||
if (injectedFamilies.has(family)) return;
|
||||
const fonts = await getFontsList();
|
||||
const match = fonts.find((f) => f.family.toLowerCase() === family.toLowerCase());
|
||||
if (!match) return; // unknown family — browser falls back to the CSS generic
|
||||
ensureFontFaceLoaded(match.family, match.weights);
|
||||
}
|
||||
|
||||
function resolveColorMode(mode: 'light' | 'dark' | 'auto' | undefined): 'light' | 'dark' {
|
||||
if (mode === 'dark') return 'dark';
|
||||
@@ -85,10 +139,15 @@ export const ThemeProvider: React.FC<ThemeProviderProps> = ({
|
||||
|
||||
if (themeConfig.fontFamily) {
|
||||
root.style.setProperty('--font-family', themeConfig.fontFamily);
|
||||
// Lazily inject the @font-face for this family if we haven't already.
|
||||
// Fire-and-forget: the CSS variable is set immediately, the font file
|
||||
// streams in afterward and `font-display: swap` reflows on arrival.
|
||||
void loadFontForFamily(themeConfig.fontFamily);
|
||||
}
|
||||
|
||||
|
||||
if (themeConfig.headingFontFamily) {
|
||||
root.style.setProperty('--heading-font-family', themeConfig.headingFontFamily);
|
||||
void loadFontForFamily(themeConfig.headingFontFamily);
|
||||
}
|
||||
|
||||
if (themeConfig.borderRadius) {
|
||||
|
||||
+11
-1
@@ -1,4 +1,14 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Noto+Sans:wght@300;400;500;600;700&family=Poppins:wght@400;500;600;700&display=swap');
|
||||
/*
|
||||
* Self-hosted Inter is bootstrapped here so the very first paint —
|
||||
* before React mounts and runs the dynamic @font-face injector — has
|
||||
* the default body font available. Replaces the previous Google Fonts
|
||||
* @import that leaked visitor IPs to fonts.googleapis.com (LG München
|
||||
* 2022 GDPR ruling). All other families are injected on-demand by
|
||||
* frontend/src/contexts/ThemeContext.tsx based on the active theme.
|
||||
*/
|
||||
@font-face { font-family: 'Inter'; font-style: normal; font-weight: 400; font-display: swap; src: url('/fonts/Inter/400.woff2') format('woff2'); }
|
||||
@font-face { font-family: 'Inter'; font-style: normal; font-weight: 600; font-display: swap; src: url('/fonts/Inter/600.woff2') format('woff2'); }
|
||||
@font-face { font-family: 'Inter'; font-style: normal; font-weight: 700; font-display: swap; src: url('/fonts/Inter/700.woff2') format('woff2'); }
|
||||
|
||||
/* Import image protection styles */
|
||||
@import './styles/image-protection.css';
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { api } from '../config/api';
|
||||
|
||||
export interface FontDefinition {
|
||||
family: string;
|
||||
weights: number[];
|
||||
// CSS generic to use as a fallback when building font-family strings.
|
||||
// Optional in the type so older backends without this field still work;
|
||||
// callers must default to 'sans-serif' when undefined.
|
||||
generic?: 'sans-serif' | 'serif' | 'cursive' | 'monospace';
|
||||
}
|
||||
|
||||
export interface FontsListResponse {
|
||||
fonts: FontDefinition[];
|
||||
}
|
||||
|
||||
export const fontsService = {
|
||||
/**
|
||||
* List all self-hosted font families discovered by the backend scanner.
|
||||
* Cached aggressively at the React Query layer; the underlying endpoint
|
||||
* is also TTL-cached on the backend.
|
||||
*/
|
||||
async list(): Promise<FontDefinition[]> {
|
||||
const res = await api.get<FontsListResponse>('/public/fonts');
|
||||
return res.data.fonts;
|
||||
}
|
||||
};
|
||||
|
||||
const GENERIC_FAMILIES = new Set([
|
||||
'sans-serif',
|
||||
'serif',
|
||||
'monospace',
|
||||
'cursive',
|
||||
'fantasy',
|
||||
'system-ui',
|
||||
'ui-sans-serif',
|
||||
'ui-serif',
|
||||
'ui-monospace',
|
||||
'ui-rounded'
|
||||
]);
|
||||
|
||||
/**
|
||||
* Extract the primary font family name from a CSS font-family string.
|
||||
*
|
||||
* "'Jost', sans-serif" → "Jost"
|
||||
* "Inter, sans-serif" → "Inter"
|
||||
* "'Playfair Display', serif" → "Playfair Display"
|
||||
* "system-ui, sans-serif" → null (generic, no @font-face needed)
|
||||
* undefined / "" / "sans-serif" → null
|
||||
*/
|
||||
export function extractFamilyName(cssFontFamily: string | undefined | null): string | null {
|
||||
if (!cssFontFamily) return null;
|
||||
const first = cssFontFamily.split(',')[0]?.trim();
|
||||
if (!first) return null;
|
||||
// Strip surrounding single or double quotes
|
||||
const unquoted = first.replace(/^['"]|['"]$/g, '').trim();
|
||||
if (!unquoted) return null;
|
||||
if (GENERIC_FAMILIES.has(unquoted.toLowerCase())) return null;
|
||||
return unquoted;
|
||||
}
|
||||
Reference in New Issue
Block a user