[feature]: Support using system fonts (#304)

* [feature]: Support using system fonts

Uses the **experimental** queryLocalFonts API, when prompted, to get the fonts and do CSS.
Resolves #270 and #288 (by proxy)

Caveats/notes:
- This is experimental, and is only supported by Chrome/Chromium/Edgeium (see https://caniuse.com/?search=querylocalfonts)
- As far as I can tell, the only way to dynamically change the font (shown in https://wicg.github.io/local-font-access/#example-style-with-local-fonts) was by DOM manipulation; css variables did not seem to work
- This shows **all** fonts, including their variants (bold/italic/etc); given that the style names could be localized, not sure of a way to parse this (on my system, for instance, I had 859 different combinations)
- I made fonts a separate top-level setting because it was easier to manipulate without causing as many rerenders; feel free to put that back

* add permission chec

* add electron magic to support custom font

* restrict content types
This commit is contained in:
Kendall Garner 2023-10-22 22:25:17 +00:00 committed by GitHub
parent e6ed9229c2
commit 74cab01013
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 282 additions and 20 deletions

View file

@ -1,14 +1,27 @@
import type { IpcRendererEvent } from 'electron';
import isElectron from 'is-electron';
import { NumberInput, Select } from '/@/renderer/components';
import { FileInput, NumberInput, Select, toast } from '/@/renderer/components';
import {
SettingsSection,
SettingOption,
} from '/@/renderer/features/settings/components/settings-section';
import { useGeneralSettings, useSettingsStoreActions } from '/@/renderer/store/settings.store';
import {
useFontSettings,
useGeneralSettings,
useSettingsStoreActions,
} from '/@/renderer/store/settings.store';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { FontType } from '/@/renderer/types';
const localSettings = isElectron() ? window.electron.localSettings : null;
const ipc = isElectron() ? window.electron.ipc : null;
const FONT_OPTIONS = [
type Font = {
label: string;
value: string;
};
const FONT_OPTIONS: Font[] = [
{ label: 'Archivo', value: 'Archivo' },
{ label: 'Fredoka', value: 'Fredoka' },
{ label: 'Inter', value: 'Inter' },
@ -20,9 +33,99 @@ const FONT_OPTIONS = [
{ label: 'Work Sans', value: 'Work Sans' },
];
const FONT_TYPES: Font[] = [{ label: 'Built-in font', value: FontType.BUILT_IN }];
if (window.queryLocalFonts) {
FONT_TYPES.push({ label: 'System font', value: FontType.SYSTEM });
}
if (isElectron()) {
FONT_TYPES.push({ label: 'Custom font', value: FontType.CUSTOM });
}
export const ApplicationSettings = () => {
const settings = useGeneralSettings();
const fontSettings = useFontSettings();
const { setSettings } = useSettingsStoreActions();
const [localFonts, setLocalFonts] = useState<Font[]>([]);
const fontList = useMemo(() => {
if (fontSettings.custom) {
const newFile = new File([], fontSettings.custom.split(/(\\|\/)/g).pop()!);
newFile.path = fontSettings.custom;
return newFile;
}
return null;
}, [fontSettings.custom]);
const onFontError = useCallback(
(_: IpcRendererEvent, file: string) => {
toast.error({
message: `${file} is not a valid font file`,
});
setSettings({
font: {
...fontSettings,
custom: null,
},
});
},
[fontSettings, setSettings],
);
useEffect(() => {
if (localSettings) {
localSettings.fontError(onFontError);
return () => {
ipc!.removeAllListeners('custom-font-error');
};
}
return () => {};
}, [onFontError]);
useEffect(() => {
const getFonts = async () => {
if (
fontSettings.type === FontType.SYSTEM &&
localFonts.length === 0 &&
window.queryLocalFonts
) {
try {
// WARNING (Oct 17 2023): while this query is valid for chromium-based
// browsers, it is still experimental, and so Typescript will complain
// @ts-ignore
const status = await navigator.permissions.query({ name: 'local-fonts' });
if (status.state === 'denied') {
throw new Error('Access denied to local fonts');
}
const data = await window.queryLocalFonts();
setLocalFonts(
data.map((font) => ({
label: font.fullName,
value: font.postscriptName,
})),
);
} catch (error) {
toast.error({
message: 'An error occurred when trying to get system fonts',
});
setSettings({
font: {
...fontSettings,
type: FontType.BUILT_IN,
},
});
}
}
};
getFonts();
}, [fontSettings, localFonts, setSettings]);
const options: SettingOption[] = [
{
@ -39,24 +142,87 @@ export const ApplicationSettings = () => {
{
control: (
<Select
searchable
data={FONT_OPTIONS}
defaultValue={settings.fontContent}
data={FONT_TYPES}
value={fontSettings.type}
onChange={(e) => {
if (!e) return;
setSettings({
general: {
...settings,
fontContent: e,
font: {
...fontSettings,
type: e as FontType,
},
});
}}
/>
),
description:
'What font to use. Built-in font selects one of the fonts provided by Feishin. System font allows you to select any font provided by your OS. Custom allows you to provide your own font',
isHidden: FONT_TYPES.length === 1,
title: 'Use system font',
},
{
control: (
<Select
searchable
data={FONT_OPTIONS}
value={fontSettings.builtIn}
onChange={(e) => {
if (!e) return;
setSettings({
font: {
...fontSettings,
builtIn: e,
},
});
}}
/>
),
description: 'Sets the application content font',
isHidden: false,
isHidden: localFonts && fontSettings.type !== FontType.BUILT_IN,
title: 'Font (Content)',
},
{
control: (
<Select
searchable
data={localFonts}
value={fontSettings.system}
w={300}
onChange={(e) => {
if (!e) return;
setSettings({
font: {
...fontSettings,
system: e,
},
});
}}
/>
),
description: 'Sets the application content font',
isHidden: !localFonts || fontSettings.type !== FontType.SYSTEM,
title: 'Font (Content)',
},
{
control: (
<FileInput
accept=".ttc,.ttf,.otf,.woff,.woff2"
defaultValue={fontList}
w={300}
onChange={(e) =>
setSettings({
font: {
...fontSettings,
custom: e?.path ?? null,
},
})
}
/>
),
description: 'Path to custom font',
isHidden: fontSettings.type !== FontType.CUSTOM,
title: 'Path to custom font',
},
{
control: (
<NumberInput