Settings: per-device interface font choice

System default plus Inter, IBM Plex Sans, Source Sans 3 and Atkinson
Hyperlegible Next (OFL 1.1, bundled as on-demand assets and loaded with
FontLoader, so the web fetches only the previewed/chosen files). Stored in
shared_preferences, applied live to Material and Cupertino text themes;
RobotoMono styles unchanged. Licences registered with LicenseRegistry.
This commit is contained in:
2026-11-04 02:01:49 +00:00
parent fa6c0864db
commit 2853b18b9e
38 changed files with 1486 additions and 26 deletions
+82
View File
@@ -0,0 +1,82 @@
/// The interface typefaces a device can choose. [AppFont.system] keeps the
/// platform's own typography (Roboto on Android and the web, SF on iOS); every
/// other option is an open-licence (SIL OFL 1.1) family bundled under
/// `fonts/<directory>/` as plain assets, not under pubspec `fonts:`, so a web
/// page downloads only the family it actually shows.
enum AppFont {
system('system', 'System default', null, null, <String>[]),
inter('inter', 'Inter', 'Inter', 'inter', <String>[
'Inter-Regular.ttf',
'Inter-Medium.ttf',
'Inter-SemiBold.ttf',
'Inter-Bold.ttf',
]),
ibmPlexSans(
'ibm-plex-sans',
'IBM Plex Sans',
'IBM Plex Sans',
'ibm-plex-sans',
<String>[
'IBMPlexSans-Regular.ttf',
'IBMPlexSans-Medium.ttf',
'IBMPlexSans-SemiBold.ttf',
'IBMPlexSans-Bold.ttf',
],
),
sourceSans3(
'source-sans-3',
'Source Sans 3',
'Source Sans 3',
'source-sans-3',
<String>[
'SourceSans3-Regular.ttf',
'SourceSans3-Medium.ttf',
'SourceSans3-Semibold.ttf',
'SourceSans3-Bold.ttf',
],
),
atkinsonHyperlegible(
'atkinson-hyperlegible-next',
'Atkinson Hyperlegible Next',
'Atkinson Hyperlegible Next',
'atkinson-hyperlegible-next',
<String>[
'AtkinsonHyperlegibleNext-Regular.ttf',
'AtkinsonHyperlegibleNext-Medium.ttf',
'AtkinsonHyperlegibleNext-SemiBold.ttf',
'AtkinsonHyperlegibleNext-Bold.ttf',
],
);
const AppFont(this.id, this.label, this.family, this._directory, this._files);
/// The stored value. Stable across releases; never the display label.
final String id;
/// The picker's name for the option.
final String label;
/// The registered family name; null keeps the platform typography.
final String? family;
final String? _directory;
final List<String> _files;
/// Every weight's asset (400, 500, 600 and 700, in that order).
List<String> get assets => <String>[
for (final file in _files) 'fonts/$_directory/$file',
];
/// The regular weight alone: enough to preview the option's name.
String? get previewAsset => _files.isEmpty ? null : assets.first;
/// The licence shipped beside the files.
String? get licenseAsset =>
_directory == null ? null : 'fonts/$_directory/OFL.txt';
/// The option a stored id names; an unknown or missing id is the default.
static AppFont fromId(String? id) => AppFont.values.firstWhere(
(font) => font.id == id,
orElse: () => AppFont.system,
);
}
+156
View File
@@ -0,0 +1,156 @@
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'app_font.dart';
import 'app_font_store.dart';
/// Registers [assets] under [family]. Production reads them from the bundle;
/// tests substitute a recorder.
typedef AppFontAssetLoader =
Future<void> Function(String family, List<String> assets);
/// Loads bundled font files on demand with a [FontLoader]. On the web each
/// asset is fetched only now, when its family is first previewed or chosen.
Future<void> loadBundledFontAssets(String family, List<String> assets) async {
final loader = FontLoader(family);
for (final asset in assets) {
loader.addFont(rootBundle.load(asset));
}
await loader.load();
}
/// The device's interface font: the stored choice, the family the theme
/// actually uses, and the on-demand loading between the two.
///
/// The theme keeps the previous family (at first the platform's) until the
/// chosen files are registered, then switches once; text never lays out in a
/// family that has not loaded, so nothing reflows more than once.
class AppFontController extends ChangeNotifier {
AppFontController({
this._store = const SharedPreferencesAppFontStore(),
this._loader = loadBundledFontAssets,
});
/// The app's own controller: one per running app, shared by the theme
/// hosts and the Settings picker.
static final AppFontController instance = AppFontController();
final AppFontStore _store;
final AppFontAssetLoader _loader;
final Map<String, Future<void>> _assetLoads = <String, Future<void>>{};
final Set<String> _loadedAssets = <String>{};
AppFont _selected = AppFont.system;
AppFont _applied = AppFont.system;
bool _saveFailed = false;
AppFont? _loadFailed;
/// The option the picker shows as chosen.
AppFont get selected => _selected;
/// The option the theme uses now.
AppFont get applied => _applied;
/// The theme's family; null keeps the platform typography.
String? get family => _applied.family;
/// The chosen family's files are still downloading.
bool get loading => _selected != _applied && _loadFailed != _selected;
/// The last choice could not be stored on this device.
bool get saveFailed => _saveFailed;
/// The chosen family's files could not be loaded; the theme kept [applied].
AppFont? get loadFailed => _loadFailed;
/// Whether [font]'s regular weight is registered, so its name can be drawn
/// in its own face.
bool canPreview(AppFont font) =>
font.previewAsset == null || _loadedAssets.contains(font.previewAsset);
/// Reads the stored choice and starts loading it. With [wait], returns once
/// it is applied or after [wait], whichever is first; a slower load still
/// applies when it finishes.
Future<void> restore({Duration? wait}) async {
final font = await _store.load();
if (font == AppFont.system || font == _selected) return;
_selected = font;
notifyListeners();
final applying = _apply(font);
if (wait == null) return applying;
await Future.any<void>(<Future<void>>[
applying,
Future<void>.delayed(wait),
]);
}
/// Chooses [font], stores it, and applies it once its files are loaded.
Future<void> select(AppFont font) async {
if (font == _selected && _loadFailed != font) return;
_selected = font;
_loadFailed = null;
notifyListeners();
final saved = await _store.save(font);
if (saved == _saveFailed) {
_saveFailed = !saved;
notifyListeners();
}
await _apply(font);
}
/// Loads [font]'s regular weight for its picker row. Failures are quiet: the
/// row keeps the current face and choosing it reports the problem.
Future<void> preview(AppFont font) async {
final asset = font.previewAsset;
final family = font.family;
if (asset == null || family == null || _loadedAssets.contains(asset)) {
return;
}
try {
await _ensure(family, <String>[asset]);
} catch (_) {
return;
}
notifyListeners();
}
Future<void> _apply(AppFont font) async {
final family = font.family;
if (family != null) {
try {
await _ensure(family, font.assets);
} catch (_) {
if (_selected == font) {
_loadFailed = font;
notifyListeners();
}
return;
}
}
// A later choice supersedes this one.
if (_selected != font || _applied == font) return;
_applied = font;
notifyListeners();
}
/// Registers the assets not yet loaded or loading, in one [FontLoader], and
/// waits for all of [assets]. A failed asset can be retried.
Future<void> _ensure(String family, List<String> assets) {
final missing = assets.where((a) => !_assetLoads.containsKey(a)).toList();
if (missing.isNotEmpty) {
final load = _loader(family, missing);
for (final asset in missing) {
_assetLoads[asset] = load.then(
(_) => _loadedAssets.add(asset),
onError: (Object error, StackTrace stack) {
_assetLoads.remove(asset);
Error.throwWithStackTrace(error, stack);
},
);
}
}
return Future.wait(assets.map((a) => _assetLoads[a]!));
}
}
+23
View File
@@ -0,0 +1,23 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'app_font.dart';
bool _registered = false;
/// Adds each bundled interface font's SIL Open Font License to the
/// [LicenseRegistry]. The texts are read from the bundle only when a licence
/// page asks for them.
void registerAppFontLicenses() {
if (_registered) return;
_registered = true;
LicenseRegistry.addLicense(() async* {
for (final font in AppFont.values) {
final asset = font.licenseAsset;
if (asset == null) continue;
yield LicenseEntryWithLineBreaks(<String>[
font.label,
], await rootBundle.loadString(asset));
}
});
}
+60
View File
@@ -0,0 +1,60 @@
import 'package:shared_preferences/shared_preferences.dart';
import 'app_font.dart';
/// The device's font choice. It lives in this device's (or browser's) own
/// preferences and is never sent to a server, so a phone and a browser signed
/// in to the same server keep their own choice.
const String appFontKey = 'pipelines.next.font.v1';
/// The persistence seam for the font choice.
abstract interface class AppFontStore {
Future<AppFont> load();
/// Whether the choice is actually stored.
Future<bool> save(AppFont font);
}
/// `shared_preferences` storage. An unavailable or unreadable store means the
/// default; a failed save returns false rather than throwing.
class SharedPreferencesAppFontStore implements AppFontStore {
const SharedPreferencesAppFontStore();
@override
Future<AppFont> load() async {
try {
final preferences = await SharedPreferences.getInstance();
return AppFont.fromId(preferences.getString(appFontKey));
} catch (_) {
return AppFont.system;
}
}
@override
Future<bool> save(AppFont font) async {
try {
final preferences = await SharedPreferences.getInstance();
return await preferences.setString(appFontKey, font.id);
} catch (_) {
return false;
}
}
}
/// An in-memory store for tests and fixtures.
class MemoryAppFontStore implements AppFontStore {
MemoryAppFontStore([this.font = AppFont.system]);
AppFont font;
bool failSaves = false;
@override
Future<AppFont> load() async => font;
@override
Future<bool> save(AppFont font) async {
if (failSaves) return false;
this.font = font;
return true;
}
}
+59 -6
View File
@@ -26,11 +26,20 @@ abstract final class AppColors {
const _seed = Color(0xFF6750A4);
ThemeData appLightTheme() => ThemeData(
platform: kIsWeb ? TargetPlatform.android : null,
colorScheme: ColorScheme.fromSeed(seedColor: _seed),
pageTransitionsTheme: appPageTransitions,
);
/// [fontFamily] replaces the platform family throughout the text themes
/// (Material's, and Cupertino's for Cupertino widgets on a Material host),
/// keeping every size, weight and the text scaling; null keeps the system
/// typography.
ThemeData appLightTheme({String? fontFamily}) {
final scheme = ColorScheme.fromSeed(seedColor: _seed);
return ThemeData(
platform: kIsWeb ? TargetPlatform.android : null,
colorScheme: scheme,
pageTransitionsTheme: appPageTransitions,
fontFamily: fontFamily,
cupertinoOverrideTheme: _cupertinoOverride(fontFamily, scheme),
);
}
/// Android and iOS keep their native transitions and interactive back gestures.
/// Desktop hosts use the short horizontal slide.
@@ -80,7 +89,7 @@ class FastSlidePageTransitionsBuilder extends PageTransitionsBuilder {
}
/// Material's dark scheme with gray surfaces stepping up from the page.
ThemeData appDarkTheme() {
ThemeData appDarkTheme({String? fontFamily}) {
final scheme =
ColorScheme.fromSeed(
seedColor: _seed,
@@ -100,6 +109,8 @@ ThemeData appDarkTheme() {
colorScheme: scheme,
scaffoldBackgroundColor: scheme.surface,
pageTransitionsTheme: appPageTransitions,
fontFamily: fontFamily,
cupertinoOverrideTheme: _cupertinoOverride(fontFamily, scheme),
);
}
@@ -107,3 +118,45 @@ const appCupertinoTheme = CupertinoThemeData(
scaffoldBackgroundColor: AppColors.background,
barBackgroundColor: AppColors.bar,
);
/// [appCupertinoTheme] with every Cupertino text role in [fontFamily]; null
/// keeps the system typography.
CupertinoThemeData appCupertinoThemeWith({String? fontFamily}) =>
fontFamily == null
? appCupertinoTheme
: appCupertinoTheme.copyWith(textTheme: appCupertinoTextTheme(fontFamily));
/// The stock Cupertino text roles (sizes, weights, colours) in [fontFamily].
/// Action roles take [primaryColor], as the stock roles do.
CupertinoTextThemeData appCupertinoTextTheme(
String fontFamily, {
Color primaryColor = CupertinoColors.systemBlue,
}) {
final base = CupertinoTextThemeData(primaryColor: primaryColor);
TextStyle face(TextStyle style) => style.copyWith(fontFamily: fontFamily);
return CupertinoTextThemeData(
textStyle: face(base.textStyle),
actionTextStyle: face(base.actionTextStyle),
actionSmallTextStyle: face(base.actionSmallTextStyle),
tabLabelTextStyle: face(base.tabLabelTextStyle),
navTitleTextStyle: face(base.navTitleTextStyle),
navLargeTitleTextStyle: face(base.navLargeTitleTextStyle),
navActionTextStyle: face(base.navActionTextStyle),
pickerTextStyle: face(base.pickerTextStyle),
dateTimePickerTextStyle: face(base.dateTimePickerTextStyle),
);
}
/// Cupertino widgets on a Material host derive their theme from Material's;
/// only the family is overridden, with Material's primary for actions.
NoDefaultCupertinoThemeData? _cupertinoOverride(
String? fontFamily,
ColorScheme scheme,
) => fontFamily == null
? null
: CupertinoThemeData(
textTheme: appCupertinoTextTheme(
fontFamily,
primaryColor: scheme.primary,
),
);