mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 15:26:17 +00:00
feat(app): custom themes with colour pickers and CSS import/export
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
47007aa90b
commit
3e673140e4
6 files changed
+1289
-11
No files matched your search
@@ -34,7 +34,7 @@ class _SynapseAppState extends State<SynapseApp> {
|
||||
child: ListenableBuilder(
|
||||
listenable: _state,
|
||||
builder: (context, _) {
|
||||
final t = themeById(_state.themeId);
|
||||
final t = _state.resolveTheme(_state.themeId);
|
||||
final built = t == null
|
||||
? null
|
||||
: buildTheme(t.brightness, colors: t.colors);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dart:ui' show PlatformDispatcher;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../backend/graph_backend.dart';
|
||||
@@ -66,8 +68,17 @@ class AppState extends ChangeNotifier {
|
||||
_settings = settings ?? MemorySettings() {
|
||||
this.queue.onError = _writeFailed;
|
||||
final saved = _settings.load();
|
||||
final custom = saved['customThemes'];
|
||||
if (custom is List) {
|
||||
for (final j in custom) {
|
||||
final t = customThemeFromJson(j);
|
||||
if (t != null && customThemes.every((c) => c.id != t.id)) {
|
||||
customThemes.add(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
final id = saved['theme'];
|
||||
if (id is String && (id == autoThemeId || themeById(id) != null)) {
|
||||
if (id is String && (id == autoThemeId || resolveTheme(id) != null)) {
|
||||
themeId = id;
|
||||
}
|
||||
final keys = saved['keys'];
|
||||
@@ -86,8 +97,73 @@ class AppState extends ChangeNotifier {
|
||||
/// Selected theme id (`auto` follows the system).
|
||||
String themeId = autoThemeId;
|
||||
|
||||
/// The user's own themes, in creation order.
|
||||
final List<AppTheme> customThemes = [];
|
||||
|
||||
void _saveSettings() {
|
||||
_settings.save({'theme': themeId, 'keys': keymap.toJson()});
|
||||
_settings.save({
|
||||
'theme': themeId,
|
||||
'customThemes': [for (final t in customThemes) t.toJson()],
|
||||
'keys': keymap.toJson(),
|
||||
});
|
||||
}
|
||||
|
||||
/// A built-in or custom theme by id; null for `auto` and unknown ids.
|
||||
AppTheme? resolveTheme(String id) {
|
||||
final built = themeById(id);
|
||||
if (built != null) return built;
|
||||
for (final t in customThemes) {
|
||||
if (t.id == id) return t;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Duplicates theme `from` (default: the selected one; `auto` uses Paper light or dark by
|
||||
/// the platform brightness) as a new custom theme named "Custom", "Custom 2", ..., and
|
||||
/// selects it.
|
||||
AppTheme createCustomTheme({String? from}) {
|
||||
final srcId = from ?? themeId;
|
||||
final src =
|
||||
resolveTheme(srcId) ??
|
||||
themeById(
|
||||
PlatformDispatcher.instance.platformBrightness == Brightness.dark
|
||||
? 'paper-dark'
|
||||
: 'paper',
|
||||
)!;
|
||||
final names = {for (final t in customThemes) t.label};
|
||||
var label = 'Custom';
|
||||
for (var n = 2; names.contains(label); n++) {
|
||||
label = 'Custom $n';
|
||||
}
|
||||
var millis = DateTime.now().millisecondsSinceEpoch;
|
||||
while (customThemes.any((t) => t.id == 'custom-$millis')) {
|
||||
millis++;
|
||||
}
|
||||
final t = AppTheme('custom-$millis', label, src.brightness, src.colors);
|
||||
customThemes.add(t);
|
||||
themeId = t.id;
|
||||
_saveSettings();
|
||||
notifyListeners();
|
||||
return t;
|
||||
}
|
||||
|
||||
/// Replaces the custom theme with the same id (no-op for unknown ids).
|
||||
void updateCustomTheme(AppTheme t) {
|
||||
final i = customThemes.indexWhere((c) => c.id == t.id);
|
||||
if (i < 0) return;
|
||||
customThemes[i] = t;
|
||||
_saveSettings();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Removes a custom theme; if it was selected the theme goes back to `auto`.
|
||||
void deleteCustomTheme(String id) {
|
||||
final before = customThemes.length;
|
||||
customThemes.removeWhere((t) => t.id == id);
|
||||
if (customThemes.length == before) return;
|
||||
if (themeId == id) themeId = autoThemeId;
|
||||
_saveSettings();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setTheme(String id) {
|
||||
|
||||
@@ -117,7 +117,78 @@ class SynapseColors extends ThemeExtension<SynapseColors> {
|
||||
);
|
||||
|
||||
@override
|
||||
SynapseColors copyWith() => this;
|
||||
SynapseColors copyWith({
|
||||
Color? paper,
|
||||
Color? surface,
|
||||
Color? ink,
|
||||
Color? muted,
|
||||
Color? faint,
|
||||
Color? line,
|
||||
Color? accent,
|
||||
Color? accentSoft,
|
||||
Color? ref,
|
||||
Color? done,
|
||||
Color? codeBg,
|
||||
Color? highlight,
|
||||
}) => SynapseColors(
|
||||
paper: paper ?? this.paper,
|
||||
surface: surface ?? this.surface,
|
||||
ink: ink ?? this.ink,
|
||||
muted: muted ?? this.muted,
|
||||
faint: faint ?? this.faint,
|
||||
line: line ?? this.line,
|
||||
accent: accent ?? this.accent,
|
||||
accentSoft: accentSoft ?? this.accentSoft,
|
||||
ref: ref ?? this.ref,
|
||||
done: done ?? this.done,
|
||||
codeBg: codeBg ?? this.codeBg,
|
||||
highlight: highlight ?? this.highlight,
|
||||
);
|
||||
|
||||
/// The colour of `token`.
|
||||
Color of(ColorToken token) => token.get(this);
|
||||
|
||||
/// `copyWith` for one token chosen at runtime.
|
||||
SynapseColors withToken(ColorToken token, Color c) => switch (token.name) {
|
||||
'paper' => copyWith(paper: c),
|
||||
'surface' => copyWith(surface: c),
|
||||
'ink' => copyWith(ink: c),
|
||||
'muted' => copyWith(muted: c),
|
||||
'faint' => copyWith(faint: c),
|
||||
'line' => copyWith(line: c),
|
||||
'accent' => copyWith(accent: c),
|
||||
'accentSoft' => copyWith(accentSoft: c),
|
||||
'ref' => copyWith(ref: c),
|
||||
'done' => copyWith(done: c),
|
||||
'codeBg' => copyWith(codeBg: c),
|
||||
_ => copyWith(highlight: c),
|
||||
};
|
||||
|
||||
/// `{token: '#rrggbbaa'}` (CSS order, always 8 digits) for persistence.
|
||||
Map<String, String> toMap() => {
|
||||
for (final t in colorTokens) t.name: colorToHex(of(t), always8: true),
|
||||
};
|
||||
|
||||
/// Reads `toMap` output; missing or unparsable tokens come from `fallback`.
|
||||
static SynapseColors fromMap(
|
||||
Map<dynamic, dynamic> map,
|
||||
SynapseColors fallback,
|
||||
) {
|
||||
var out = fallback;
|
||||
for (final t in colorTokens) {
|
||||
final v = map[t.name];
|
||||
final c = v is String ? parseCssColor(v) : null;
|
||||
if (c != null) out = out.withToken(t, c);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is SynapseColors && colorTokens.every((t) => of(t) == other.of(t));
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hashAll(colorTokens.map(of));
|
||||
|
||||
@override
|
||||
SynapseColors lerp(SynapseColors? other, double t) {
|
||||
@@ -162,6 +233,52 @@ class AppTheme {
|
||||
final SynapseColors colors;
|
||||
}
|
||||
|
||||
extension AppThemeX on AppTheme {
|
||||
AppTheme copyWith({
|
||||
String? label,
|
||||
Brightness? brightness,
|
||||
SynapseColors? colors,
|
||||
}) => AppTheme(
|
||||
id,
|
||||
label ?? this.label,
|
||||
brightness ?? this.brightness,
|
||||
colors ?? this.colors,
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'label': label,
|
||||
'brightness': brightness == Brightness.dark ? 'dark' : 'light',
|
||||
'colors': colors.toMap(),
|
||||
};
|
||||
}
|
||||
|
||||
/// Reads a persisted custom theme; null for corrupt entries. Missing tokens come from the
|
||||
/// base palette of the theme's brightness.
|
||||
AppTheme? customThemeFromJson(Object? json) {
|
||||
if (json is! Map) return null;
|
||||
final id = json['id'];
|
||||
final label = json['label'];
|
||||
final b = json['brightness'];
|
||||
final colors = json['colors'];
|
||||
if (id is! String ||
|
||||
id.isEmpty ||
|
||||
id == autoThemeId ||
|
||||
themeById(id) != null) {
|
||||
return null;
|
||||
}
|
||||
if (label is! String || (b != 'light' && b != 'dark') || colors is! Map) {
|
||||
return null;
|
||||
}
|
||||
final brightness = b == 'dark' ? Brightness.dark : Brightness.light;
|
||||
return AppTheme(
|
||||
id,
|
||||
label,
|
||||
brightness,
|
||||
SynapseColors.fromMap(colors, baseColors(brightness)),
|
||||
);
|
||||
}
|
||||
|
||||
const autoThemeId = 'auto';
|
||||
|
||||
const appThemes = [
|
||||
@@ -177,7 +294,7 @@ const appThemes = [
|
||||
AppTheme('nord', 'Nord', Brightness.dark, SynapseColors.nord),
|
||||
];
|
||||
|
||||
/// The theme with `id`, or null for `auto` and unknown ids.
|
||||
/// The built-in theme with `id`, or null for `auto`, custom and unknown ids.
|
||||
AppTheme? themeById(String id) {
|
||||
for (final t in appThemes) {
|
||||
if (t.id == id) return t;
|
||||
@@ -185,6 +302,223 @@ AppTheme? themeById(String id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/// A colour token: its field name, CSS variable, UI label and hint.
|
||||
class ColorToken {
|
||||
const ColorToken(
|
||||
this.name,
|
||||
this.css,
|
||||
this.label,
|
||||
this.hint,
|
||||
this.get, {
|
||||
this.alpha = false,
|
||||
});
|
||||
final String name;
|
||||
final String css;
|
||||
final String label;
|
||||
final String hint;
|
||||
final Color Function(SynapseColors) get;
|
||||
|
||||
/// Whether the token is meant to be translucent (the picker shows an alpha slider).
|
||||
final bool alpha;
|
||||
}
|
||||
|
||||
final colorTokens = <ColorToken>[
|
||||
ColorToken('paper', 'paper', 'Paper', 'Page background', (c) => c.paper),
|
||||
ColorToken(
|
||||
'surface',
|
||||
'surface',
|
||||
'Surface',
|
||||
'Sidebar and panels',
|
||||
(c) => c.surface,
|
||||
),
|
||||
ColorToken('ink', 'ink', 'Ink', 'Main text', (c) => c.ink),
|
||||
ColorToken('muted', 'muted', 'Muted', 'Secondary text', (c) => c.muted),
|
||||
ColorToken(
|
||||
'faint',
|
||||
'faint',
|
||||
'Faint',
|
||||
'Bullets, placeholders, icons',
|
||||
(c) => c.faint,
|
||||
),
|
||||
ColorToken('line', 'line', 'Line', 'Borders and dividers', (c) => c.line),
|
||||
ColorToken(
|
||||
'accent',
|
||||
'accent',
|
||||
'Accent',
|
||||
'Links, focus, selection',
|
||||
(c) => c.accent,
|
||||
),
|
||||
ColorToken(
|
||||
'accentSoft',
|
||||
'accent-soft',
|
||||
'Accent soft',
|
||||
'Tinted backgrounds behind links',
|
||||
(c) => c.accentSoft,
|
||||
alpha: true,
|
||||
),
|
||||
ColorToken('ref', 'ref', 'Reference', 'Block references', (c) => c.ref),
|
||||
ColorToken('done', 'done', 'Done', 'Completed tasks', (c) => c.done),
|
||||
ColorToken(
|
||||
'codeBg',
|
||||
'code-bg',
|
||||
'Code background',
|
||||
'Inline code and code blocks',
|
||||
(c) => c.codeBg,
|
||||
),
|
||||
ColorToken(
|
||||
'highlight',
|
||||
'highlight',
|
||||
'Highlight',
|
||||
'Marked text and search hits',
|
||||
(c) => c.highlight,
|
||||
alpha: true,
|
||||
),
|
||||
];
|
||||
|
||||
/// The built-in base palette for `brightness`.
|
||||
SynapseColors baseColors(Brightness brightness) =>
|
||||
brightness == Brightness.light ? SynapseColors.light : SynapseColors.dark;
|
||||
|
||||
String _hex2(int v) => v.toRadixString(16).padLeft(2, '0');
|
||||
|
||||
/// `#rrggbb`, or `#rrggbbaa` when not opaque (CSS order); `always8` forces the alpha digits.
|
||||
String colorToHex(Color c, {bool always8 = false}) {
|
||||
final v = c.toARGB32();
|
||||
final a = (v >> 24) & 0xFF;
|
||||
final rgb =
|
||||
'${_hex2((v >> 16) & 0xFF)}${_hex2((v >> 8) & 0xFF)}${_hex2(v & 0xFF)}';
|
||||
return a == 0xFF && !always8 ? '#$rgb' : '#$rgb${_hex2(a)}';
|
||||
}
|
||||
|
||||
double? _num(String s, {double scale = 1}) {
|
||||
s = s.trim();
|
||||
if (s.endsWith('%')) {
|
||||
final v = double.tryParse(s.substring(0, s.length - 1));
|
||||
return v == null ? null : v / 100 * scale;
|
||||
}
|
||||
return double.tryParse(s);
|
||||
}
|
||||
|
||||
double? _alpha(String? s) {
|
||||
if (s == null) return 1;
|
||||
final v = _num(s);
|
||||
return v?.clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
/// Parses a CSS colour: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()/rgba()` and
|
||||
/// `hsl()/hsla()` (comma or space syntax). Returns null when it is not a valid colour.
|
||||
Color? parseCssColor(String input) {
|
||||
final s = input.trim().toLowerCase();
|
||||
if (s.startsWith('#')) {
|
||||
var h = s.substring(1);
|
||||
if (!RegExp(r'^[0-9a-f]+$').hasMatch(h)) return null;
|
||||
if (h.length == 3 || h.length == 4) {
|
||||
h = h.split('').map((c) => '$c$c').join();
|
||||
}
|
||||
if (h.length != 6 && h.length != 8) return null;
|
||||
final rgb = int.parse(h.substring(0, 6), radix: 16);
|
||||
final a = h.length == 8 ? int.parse(h.substring(6), radix: 16) : 0xFF;
|
||||
return Color((a << 24) | rgb);
|
||||
}
|
||||
final m = RegExp(r'^(rgba?|hsla?)\(([^)]*)\)$').matchAsPrefix(s);
|
||||
if (m == null) return null;
|
||||
final parts = m
|
||||
.group(2)!
|
||||
.split(RegExp(r'[\s,/]+'))
|
||||
.where((p) => p.isNotEmpty)
|
||||
.toList();
|
||||
if (parts.length != 3 && parts.length != 4) return null;
|
||||
final a = _alpha(parts.length == 4 ? parts[3] : null);
|
||||
if (a == null) return null;
|
||||
if (m.group(1)!.startsWith('rgb')) {
|
||||
final v = [for (var i = 0; i < 3; i++) _num(parts[i], scale: 255)];
|
||||
if (v.contains(null)) return null;
|
||||
int ch(double? x) => x!.round().clamp(0, 255);
|
||||
return Color.fromARGB((a * 255).round(), ch(v[0]), ch(v[1]), ch(v[2]));
|
||||
}
|
||||
final hue = double.tryParse(parts[0].replaceAll(RegExp(r'deg$'), ''));
|
||||
final sat = _num(parts[1]);
|
||||
final lig = _num(parts[2]);
|
||||
if (hue == null || sat == null || lig == null) return null;
|
||||
// `_num` leaves bare numbers as-is: treat "50" as 50 %, like "50%" (0..1 after scaling).
|
||||
double pct(String p, double v) => p.trim().endsWith('%') ? v : v / 100;
|
||||
return HSLColor.fromAHSL(
|
||||
a,
|
||||
((hue % 360) + 360) % 360,
|
||||
pct(parts[1], sat).clamp(0.0, 1.0),
|
||||
pct(parts[2], lig).clamp(0.0, 1.0),
|
||||
).toColor();
|
||||
}
|
||||
|
||||
/// The result of `parseThemeCss`.
|
||||
class ParsedTheme {
|
||||
const ParsedTheme(this.brightness, this.colors, this.errors);
|
||||
|
||||
/// From `color-scheme`, or null when the CSS does not say.
|
||||
final Brightness? brightness;
|
||||
final SynapseColors colors;
|
||||
|
||||
/// Human-readable problems; the offending lines were skipped.
|
||||
final List<String> errors;
|
||||
}
|
||||
|
||||
String _norm(String name) => name.toLowerCase().replaceAll(RegExp(r'[-_]'), '');
|
||||
|
||||
/// Serialises a theme as CSS custom properties (see `parseThemeCss`).
|
||||
String themeToCss(AppTheme t) {
|
||||
final b = StringBuffer(
|
||||
'/* Synapse theme: ${t.label.replaceAll('*/', '')} */\n:root {\n',
|
||||
);
|
||||
b.writeln(
|
||||
' color-scheme: ${t.brightness == Brightness.dark ? 'dark' : 'light'};',
|
||||
);
|
||||
for (final tok in colorTokens) {
|
||||
b.writeln(' --${tok.css}: ${colorToHex(t.colors.of(tok))};');
|
||||
}
|
||||
b.write('}\n');
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
/// Reads `--token: colour;` declarations and `color-scheme`. Comments, selectors and braces
|
||||
/// are ignored; tokens not mentioned keep their value from `fallback`.
|
||||
ParsedTheme parseThemeCss(String css, {required SynapseColors fallback}) {
|
||||
final text = css.replaceAll(RegExp(r'/\*.*?\*/', dotAll: true), '');
|
||||
final byName = {for (final t in colorTokens) _norm(t.name): t};
|
||||
var colors = fallback;
|
||||
Brightness? brightness;
|
||||
final errors = <String>[];
|
||||
for (final m in RegExp(
|
||||
r'(--[\w-]+|color-scheme)\s*:\s*([^;{}]*)',
|
||||
).allMatches(text)) {
|
||||
final name = m.group(1)!;
|
||||
final value = m.group(2)!.trim();
|
||||
if (name == 'color-scheme') {
|
||||
// The first scheme listed is the preferred one (`light dark` means light).
|
||||
final v = value.toLowerCase().trim().split(RegExp(r'\s+')).first;
|
||||
if (v == 'dark') {
|
||||
brightness = Brightness.dark;
|
||||
} else if (v == 'light') {
|
||||
brightness = Brightness.light;
|
||||
} else {
|
||||
errors.add('Unknown color-scheme "$value" (use light or dark)');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
final tok = byName[_norm(name.substring(2))];
|
||||
if (tok == null) {
|
||||
errors.add('Unknown variable $name');
|
||||
continue;
|
||||
}
|
||||
final c = parseCssColor(value);
|
||||
if (c == null) {
|
||||
errors.add('Bad colour for $name: "$value"');
|
||||
continue;
|
||||
}
|
||||
colors = colors.withToken(tok, c);
|
||||
}
|
||||
return ParsedTheme(brightness, colors, errors);
|
||||
}
|
||||
|
||||
ThemeData buildTheme(Brightness brightness, {SynapseColors? colors}) {
|
||||
final c =
|
||||
colors ??
|
||||
|
||||
@@ -5,6 +5,7 @@ import '../state/app_state.dart';
|
||||
import '../state/keymap.dart';
|
||||
import '../theme/theme.dart';
|
||||
import '../widgets/common.dart';
|
||||
import 'theme_editor.dart';
|
||||
|
||||
/// Theme picker and key bindings.
|
||||
class SettingsView extends StatelessWidget {
|
||||
@@ -53,6 +54,37 @@ class SettingsView extends StatelessWidget {
|
||||
],
|
||||
selected: app.themeId == t.id,
|
||||
),
|
||||
for (final t in app.customThemes)
|
||||
_ThemeCard(
|
||||
id: t.id,
|
||||
label: t.label,
|
||||
swatch: [
|
||||
t.colors.paper,
|
||||
t.colors.surface,
|
||||
t.colors.accent,
|
||||
t.colors.ref,
|
||||
],
|
||||
selected: app.themeId == t.id,
|
||||
onEdit: () {
|
||||
// Select it while editing so the whole app previews the edits.
|
||||
final previous = app.themeId;
|
||||
app.setTheme(t.id);
|
||||
showThemeEditor(context, t, previousThemeId: previous);
|
||||
},
|
||||
onDelete: () => app.deleteCustomTheme(t.id),
|
||||
),
|
||||
_NewThemeCard(
|
||||
onTap: () {
|
||||
final previous = app.themeId;
|
||||
final t = app.createCustomTheme();
|
||||
showThemeEditor(
|
||||
context,
|
||||
t,
|
||||
isNew: true,
|
||||
previousThemeId: previous,
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 36),
|
||||
@@ -111,8 +143,12 @@ class _ThemeCard extends StatelessWidget {
|
||||
required this.label,
|
||||
required this.swatch,
|
||||
required this.selected,
|
||||
this.onEdit,
|
||||
this.onDelete,
|
||||
});
|
||||
|
||||
final VoidCallback? onEdit;
|
||||
final VoidCallback? onDelete;
|
||||
final String id;
|
||||
final String label;
|
||||
final List<Color> swatch;
|
||||
@@ -148,13 +184,92 @@ class _ThemeCard extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
label,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
|
||||
color: colors.ink,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (onEdit != null)
|
||||
_CardAction(
|
||||
key: ValueKey('theme-edit-$id'),
|
||||
icon: Icons.edit_outlined,
|
||||
tooltip: 'Edit theme',
|
||||
onTap: onEdit!,
|
||||
),
|
||||
if (onDelete != null)
|
||||
_CardAction(
|
||||
key: ValueKey('theme-delete-$id'),
|
||||
icon: Icons.delete_outline_rounded,
|
||||
tooltip: 'Delete theme',
|
||||
onTap: onDelete!,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CardAction extends StatelessWidget {
|
||||
const _CardAction({
|
||||
super.key,
|
||||
required this.icon,
|
||||
required this.tooltip,
|
||||
required this.onTap,
|
||||
});
|
||||
final IconData icon;
|
||||
final String tooltip;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => InkResponse(
|
||||
onTap: onTap,
|
||||
radius: 14,
|
||||
child: Tooltip(
|
||||
message: tooltip,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: 4),
|
||||
child: Icon(icon, size: 16, color: context.colors.faint),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _NewThemeCard extends StatelessWidget {
|
||||
const _NewThemeCard({required this.onTap});
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
return InkWell(
|
||||
key: const ValueKey('theme-new'),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
onTap: onTap,
|
||||
child: Container(
|
||||
width: 132,
|
||||
height: 70,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: colors.line),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.add_rounded, color: colors.accent),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
|
||||
color: colors.ink,
|
||||
),
|
||||
'New theme',
|
||||
style: TextStyle(fontSize: 13, color: colors.muted),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -0,0 +1,572 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../state/app_state.dart';
|
||||
import '../theme/theme.dart';
|
||||
|
||||
/// Opens the editor for custom theme `theme`. Edits apply live (the app re-themes as you
|
||||
/// type); Cancel restores the values the theme had when the editor opened, and for a theme
|
||||
/// that was just created it deletes it again and reselects `previousThemeId`.
|
||||
Future<void> showThemeEditor(
|
||||
BuildContext context,
|
||||
AppTheme theme, {
|
||||
bool isNew = false,
|
||||
String previousThemeId = autoThemeId,
|
||||
}) {
|
||||
final narrow = MediaQuery.sizeOf(context).width < 640;
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => Dialog(
|
||||
insetPadding: narrow
|
||||
? EdgeInsets.zero
|
||||
: const EdgeInsets.symmetric(horizontal: 40, vertical: 24),
|
||||
shape: narrow ? const RoundedRectangleBorder() : null,
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: narrow ? double.infinity : 640,
|
||||
maxHeight: narrow ? double.infinity : 760,
|
||||
),
|
||||
child: ThemeEditor(
|
||||
original: theme,
|
||||
isNew: isNew,
|
||||
previousThemeId: previousThemeId,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class ThemeEditor extends StatefulWidget {
|
||||
const ThemeEditor({
|
||||
super.key,
|
||||
required this.original,
|
||||
this.isNew = false,
|
||||
this.previousThemeId = autoThemeId,
|
||||
});
|
||||
|
||||
final AppTheme original;
|
||||
final bool isNew;
|
||||
final String previousThemeId;
|
||||
|
||||
@override
|
||||
State<ThemeEditor> createState() => _ThemeEditorState();
|
||||
}
|
||||
|
||||
class _ThemeEditorState extends State<ThemeEditor> {
|
||||
late AppTheme _theme = widget.original;
|
||||
late final _name = TextEditingController(text: widget.original.label);
|
||||
late final _css = TextEditingController(text: themeToCss(widget.original));
|
||||
List<String> _errors = const [];
|
||||
bool _cssTab = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_name.dispose();
|
||||
_css.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _set(AppTheme t, {bool refreshCss = true}) {
|
||||
setState(() => _theme = t);
|
||||
if (refreshCss) _css.text = themeToCss(t);
|
||||
AppScope.read(context).updateCustomTheme(t);
|
||||
}
|
||||
|
||||
void _cancel() {
|
||||
final app = AppScope.read(context);
|
||||
if (widget.isNew) {
|
||||
app.deleteCustomTheme(widget.original.id);
|
||||
app.setTheme(widget.previousThemeId);
|
||||
} else {
|
||||
app.updateCustomTheme(widget.original);
|
||||
app.setTheme(widget.previousThemeId);
|
||||
}
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
void _applyCss() {
|
||||
final p = parseThemeCss(_css.text, fallback: _theme.colors);
|
||||
setState(() => _errors = p.errors);
|
||||
_set(
|
||||
_theme.copyWith(
|
||||
colors: p.colors,
|
||||
brightness: p.brightness ?? _theme.brightness,
|
||||
),
|
||||
refreshCss: p.errors.isEmpty,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _pick(ColorToken tok) async {
|
||||
final before = _theme.colors.of(tok);
|
||||
final c = await showDialog<Color>(
|
||||
context: context,
|
||||
builder: (_) => _ColorPickerDialog(
|
||||
token: tok,
|
||||
initial: _theme.colors.of(tok),
|
||||
onChanged: (c) =>
|
||||
_set(_theme.copyWith(colors: _theme.colors.withToken(tok, c))),
|
||||
),
|
||||
);
|
||||
// Dismissed (Esc, tap outside, back): undo the live preview.
|
||||
_set(_theme.copyWith(colors: _theme.colors.withToken(tok, c ?? before)));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final c = context.colors;
|
||||
// System back (Android) cancels, like the Cancel button.
|
||||
return PopScope(
|
||||
canPop: false,
|
||||
onPopInvokedWithResult: (didPop, _) {
|
||||
if (!didPop) _cancel();
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
widget.isNew ? 'New theme' : 'Edit theme',
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
key: const ValueKey('theme-name'),
|
||||
controller: _name,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Name',
|
||||
isDense: true,
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
onChanged: (v) {
|
||||
final label = v.trim().isEmpty ? 'Custom' : v.trim();
|
||||
_set(_theme.copyWith(label: label));
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
SegmentedButton<Brightness>(
|
||||
key: const ValueKey('theme-brightness'),
|
||||
showSelectedIcon: false,
|
||||
segments: const [
|
||||
ButtonSegment(
|
||||
value: Brightness.light,
|
||||
icon: Icon(Icons.light_mode_outlined, size: 16),
|
||||
label: Text('Light'),
|
||||
),
|
||||
ButtonSegment(
|
||||
value: Brightness.dark,
|
||||
icon: Icon(Icons.dark_mode_outlined, size: 16),
|
||||
label: Text('Dark'),
|
||||
),
|
||||
],
|
||||
selected: {_theme.brightness},
|
||||
onSelectionChanged: (s) =>
|
||||
_set(_theme.copyWith(brightness: s.first)),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_Preview(colors: _theme.colors),
|
||||
const SizedBox(height: 12),
|
||||
SegmentedButton<bool>(
|
||||
showSelectedIcon: false,
|
||||
segments: const [
|
||||
ButtonSegment(value: false, label: Text('Colors')),
|
||||
ButtonSegment(value: true, label: Text('CSS')),
|
||||
],
|
||||
selected: {_cssTab},
|
||||
onSelectionChanged: (s) => setState(() => _cssTab = s.first),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Expanded(child: _cssTab ? _cssPane(c) : _colorsPane(c)),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
TextButton(
|
||||
key: const ValueKey('theme-cancel'),
|
||||
onPressed: _cancel,
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
FilledButton(
|
||||
key: const ValueKey('theme-save'),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Save'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _colorsPane(SynapseColors c) => ListView(
|
||||
children: [
|
||||
for (final tok in colorTokens)
|
||||
ListTile(
|
||||
key: ValueKey('token-${tok.name}'),
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
onTap: () => _pick(tok),
|
||||
leading: _Swatch(_theme.colors.of(tok), c.line),
|
||||
title: Text(tok.label),
|
||||
subtitle: Text(
|
||||
tok.hint,
|
||||
style: TextStyle(color: c.muted, fontSize: 12),
|
||||
),
|
||||
trailing: Text(
|
||||
colorToHex(_theme.colors.of(tok)),
|
||||
style: TextStyle(
|
||||
fontFamily: monoFont,
|
||||
fontSize: 12,
|
||||
color: c.muted,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
Widget _cssPane(SynapseColors c) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
key: const ValueKey('theme-css'),
|
||||
controller: _css,
|
||||
expands: true,
|
||||
maxLines: null,
|
||||
minLines: null,
|
||||
textAlignVertical: TextAlignVertical.top,
|
||||
style: const TextStyle(fontFamily: monoFont, fontSize: 12.5),
|
||||
decoration: const InputDecoration(
|
||||
border: OutlineInputBorder(),
|
||||
isDense: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_errors.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Text(
|
||||
_errors.join('\n'),
|
||||
key: const ValueKey('theme-css-errors'),
|
||||
style: TextStyle(color: c.ref, fontSize: 12),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
OutlinedButton(
|
||||
key: const ValueKey('theme-css-copy'),
|
||||
onPressed: () => Clipboard.setData(ClipboardData(text: _css.text)),
|
||||
child: const Text('Copy'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
FilledButton.tonal(
|
||||
key: const ValueKey('theme-css-apply'),
|
||||
onPressed: _applyCss,
|
||||
child: const Text('Apply'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
class _Swatch extends StatelessWidget {
|
||||
const _Swatch(this.color, this.border);
|
||||
final Color color;
|
||||
final Color border;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Container(
|
||||
width: 32,
|
||||
height: 32,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: border),
|
||||
),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(7),
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
// Checker-ish backdrop so translucent colours are visible.
|
||||
Row(
|
||||
children: [
|
||||
for (final g in const [0xFFFFFFFF, 0xFF999999])
|
||||
Expanded(child: ColoredBox(color: Color(g))),
|
||||
],
|
||||
),
|
||||
ColoredBox(color: color),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// A mock page drawn with the edited colours.
|
||||
class _Preview extends StatelessWidget {
|
||||
const _Preview({required this.colors});
|
||||
final SynapseColors colors;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final c = colors;
|
||||
TextStyle s({Color? color, FontWeight? w}) => TextStyle(
|
||||
fontSize: 13.5,
|
||||
color: color ?? c.ink,
|
||||
fontWeight: w,
|
||||
height: 1.4,
|
||||
);
|
||||
Widget bullet(List<InlineSpan> spans) => Padding(
|
||||
padding: const EdgeInsets.only(top: 3),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 7, right: 8),
|
||||
child: CircleAvatar(radius: 2.5, backgroundColor: c.faint),
|
||||
),
|
||||
Expanded(
|
||||
child: Text.rich(TextSpan(children: spans, style: s())),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
return Container(
|
||||
key: const ValueKey('theme-preview'),
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: c.paper,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: c.line),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Preview page',
|
||||
style: TextStyle(
|
||||
fontFamily: titleFont,
|
||||
fontSize: 17,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: c.ink,
|
||||
),
|
||||
),
|
||||
Text('Secondary text', style: s(color: c.muted)),
|
||||
bullet([
|
||||
const TextSpan(text: 'A link to '),
|
||||
TextSpan(
|
||||
text: '[[Page]]',
|
||||
style: TextStyle(color: c.accent, backgroundColor: c.accentSoft),
|
||||
),
|
||||
const TextSpan(text: ' and '),
|
||||
TextSpan(
|
||||
text: 'marked',
|
||||
style: TextStyle(backgroundColor: c.highlight),
|
||||
),
|
||||
]),
|
||||
bullet([
|
||||
TextSpan(
|
||||
text: '((block reference))',
|
||||
style: TextStyle(color: c.ref),
|
||||
),
|
||||
]),
|
||||
bullet([
|
||||
TextSpan(
|
||||
text: 'Done task',
|
||||
style: TextStyle(
|
||||
color: c.done,
|
||||
decoration: TextDecoration.lineThrough,
|
||||
),
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 6),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
color: c.codeBg,
|
||||
child: Text(
|
||||
'let x = 1;',
|
||||
style: TextStyle(
|
||||
fontFamily: monoFont,
|
||||
fontSize: 12,
|
||||
color: c.ink,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
color: c.surface,
|
||||
child: Text('Sidebar surface', style: s(color: c.muted)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const _presets = <Color>[
|
||||
Color(0xFFFFFFFF),
|
||||
Color(0xFFFAF8F4),
|
||||
Color(0xFF23262B),
|
||||
Color(0xFF16181B),
|
||||
Color(0xFF000000),
|
||||
Color(0xFFE5484D),
|
||||
Color(0xFFF76B15),
|
||||
Color(0xFFF5B800),
|
||||
Color(0xFF30A46C),
|
||||
Color(0xFF1F7A74),
|
||||
Color(0xFF3E63DD),
|
||||
Color(0xFF8E4EC6),
|
||||
Color(0xFFD05CE3),
|
||||
Color(0xFF8E93AB),
|
||||
];
|
||||
|
||||
/// A dependency-free colour picker: hue, saturation, lightness and (optionally) alpha
|
||||
/// sliders, a hex field and preset swatches. `onChanged` fires on every change so the app
|
||||
/// can preview live; the dialog pops the final colour on Done.
|
||||
class _ColorPickerDialog extends StatefulWidget {
|
||||
const _ColorPickerDialog({
|
||||
required this.token,
|
||||
required this.initial,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final ColorToken token;
|
||||
final Color initial;
|
||||
final ValueChanged<Color> onChanged;
|
||||
|
||||
@override
|
||||
State<_ColorPickerDialog> createState() => _ColorPickerDialogState();
|
||||
}
|
||||
|
||||
class _ColorPickerDialogState extends State<_ColorPickerDialog> {
|
||||
late HSLColor _hsl = HSLColor.fromColor(widget.initial);
|
||||
late final _hex = TextEditingController(text: colorToHex(widget.initial));
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_hex.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _update(HSLColor h, {bool syncHex = true}) {
|
||||
setState(() => _hsl = h);
|
||||
final c = h.toColor();
|
||||
if (syncHex) _hex.text = colorToHex(c);
|
||||
widget.onChanged(c);
|
||||
}
|
||||
|
||||
Widget _slider(
|
||||
String label,
|
||||
double value,
|
||||
double max,
|
||||
ValueChanged<double> onChanged,
|
||||
) => Row(
|
||||
children: [
|
||||
SizedBox(width: 24, child: Text(label)),
|
||||
Expanded(
|
||||
child: Slider(
|
||||
value: value.clamp(0, max),
|
||||
max: max,
|
||||
onChanged: onChanged,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final tok = widget.token;
|
||||
return AlertDialog(
|
||||
title: Text(tok.label),
|
||||
content: SizedBox(
|
||||
width: 360,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(tok.hint),
|
||||
const SizedBox(height: 10),
|
||||
Container(
|
||||
height: 36,
|
||||
decoration: BoxDecoration(
|
||||
color: _hsl.toColor(),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: context.colors.line),
|
||||
),
|
||||
),
|
||||
_slider('H', _hsl.hue, 360, (v) => _update(_hsl.withHue(v))),
|
||||
_slider(
|
||||
'S',
|
||||
_hsl.saturation,
|
||||
1,
|
||||
(v) => _update(_hsl.withSaturation(v)),
|
||||
),
|
||||
_slider(
|
||||
'L',
|
||||
_hsl.lightness,
|
||||
1,
|
||||
(v) => _update(_hsl.withLightness(v)),
|
||||
),
|
||||
if (tok.alpha)
|
||||
_slider('A', _hsl.alpha, 1, (v) => _update(_hsl.withAlpha(v))),
|
||||
TextField(
|
||||
key: const ValueKey('picker-hex'),
|
||||
controller: _hex,
|
||||
style: const TextStyle(fontFamily: monoFont),
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Hex',
|
||||
isDense: true,
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
onChanged: (v) {
|
||||
final c = parseCssColor(v);
|
||||
if (c != null) _update(HSLColor.fromColor(c), syncHex: false);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 6,
|
||||
children: [
|
||||
for (final p in _presets)
|
||||
InkWell(
|
||||
onTap: () => _update(
|
||||
HSLColor.fromColor(p)
|
||||
.withAlpha(tok.alpha ? _hsl.alpha : 1),
|
||||
),
|
||||
child: _Swatch(p, context.colors.line),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
widget.onChanged(widget.initial);
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(_hsl.toColor()),
|
||||
child: const Text('Done'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:synapse/src/state/app_state.dart';
|
||||
import 'package:synapse/src/state/settings.dart';
|
||||
import 'package:synapse/src/theme/theme.dart';
|
||||
import 'package:synapse/src/views/settings_view.dart';
|
||||
|
||||
import 'support/memory_backend.dart';
|
||||
|
||||
void main() {
|
||||
group('theme CSS', () {
|
||||
test('round-trips every built-in theme', () {
|
||||
for (final t in appThemes) {
|
||||
final p = parseThemeCss(themeToCss(t), fallback: SynapseColors.light);
|
||||
expect(p.errors, isEmpty, reason: t.id);
|
||||
expect(p.brightness, t.brightness, reason: t.id);
|
||||
expect(p.colors, t.colors, reason: t.id);
|
||||
}
|
||||
});
|
||||
|
||||
test('writes kebab-case names and alpha only when translucent', () {
|
||||
final css = themeToCss(appThemes[1]);
|
||||
expect(css, contains('/* Synapse theme: Paper dark */'));
|
||||
expect(css, contains('color-scheme: dark;'));
|
||||
expect(css, contains('--paper: #16181b;'));
|
||||
expect(css, contains('--accent-soft: #63c2b822;'));
|
||||
});
|
||||
|
||||
test('parses every colour syntax', () {
|
||||
expect(parseCssColor('#f80'), const Color(0xFFFF8800));
|
||||
expect(parseCssColor('#f808'), const Color(0x88FF8800));
|
||||
expect(parseCssColor('#112233'), const Color(0xFF112233));
|
||||
expect(parseCssColor('#11223344'), const Color(0x44112233));
|
||||
expect(parseCssColor('rgb(255, 0, 128)'), const Color(0xFFFF0080));
|
||||
expect(parseCssColor('rgb(255 0 128 / 50%)'), const Color(0x80FF0080));
|
||||
expect(parseCssColor('rgba(0, 0, 0, 0.5)'), const Color(0x80000000));
|
||||
expect(parseCssColor('hsl(120, 100%, 50%)'), const Color(0xFF00FF00));
|
||||
expect(
|
||||
parseCssColor('hsla(240, 100%, 50%, 0.2)'),
|
||||
const Color(0x330000FF),
|
||||
);
|
||||
expect(parseCssColor('#12'), isNull);
|
||||
expect(parseCssColor('#ggg'), isNull);
|
||||
expect(parseCssColor('red'), isNull);
|
||||
expect(parseCssColor('rgb(1, 2)'), isNull);
|
||||
});
|
||||
|
||||
test('accepts camelCase, ignores selectors and reports bad lines', () {
|
||||
final p = parseThemeCss('''
|
||||
.foo, :root { /* hi */
|
||||
--accentSoft: rgba(255, 0, 0, 0.5);
|
||||
--code-bg: #000;
|
||||
--nope: #fff;
|
||||
--ink: banana;
|
||||
color-scheme: dark;
|
||||
background: red;
|
||||
}
|
||||
''', fallback: SynapseColors.light);
|
||||
expect(p.brightness, Brightness.dark);
|
||||
expect(p.colors.accentSoft, const Color(0x80FF0000));
|
||||
expect(p.colors.codeBg, const Color(0xFF000000));
|
||||
expect(p.colors.ink, SynapseColors.light.ink);
|
||||
expect(p.errors, hasLength(2));
|
||||
expect(p.errors[0], contains('--nope'));
|
||||
expect(p.errors[1], contains('--ink'));
|
||||
expect(
|
||||
parseThemeCss(
|
||||
'--paper: #fff;',
|
||||
fallback: SynapseColors.dark,
|
||||
).brightness,
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('custom themes', () {
|
||||
test('persist across restarts and skip corrupt entries', () {
|
||||
final store = MemorySettings();
|
||||
final a = AppState(MemoryBackend(), settings: store);
|
||||
final t = a.createCustomTheme(from: 'nord');
|
||||
expect(t.label, 'Custom');
|
||||
expect(a.createCustomTheme().label, 'Custom 2');
|
||||
a.updateCustomTheme(
|
||||
t.copyWith(
|
||||
label: 'Mine',
|
||||
colors: t.colors.copyWith(accent: const Color(0xFFFF0000)),
|
||||
),
|
||||
);
|
||||
a.setTheme(t.id);
|
||||
|
||||
store.data['customThemes'] = [
|
||||
...(store.data['customThemes'] as List),
|
||||
'junk',
|
||||
{'id': 'custom-x', 'label': 'x', 'brightness': 'purple', 'colors': {}},
|
||||
{'id': 'paper', 'label': 'x', 'brightness': 'dark', 'colors': {}},
|
||||
{
|
||||
'id': 'custom-partial',
|
||||
'label': 'Partial',
|
||||
'brightness': 'dark',
|
||||
'colors': {'accent': '#00ff00', 'ink': 'bad'},
|
||||
},
|
||||
];
|
||||
final b = AppState(MemoryBackend(), settings: store);
|
||||
expect(b.customThemes.map((t) => t.label), [
|
||||
'Mine',
|
||||
'Custom 2',
|
||||
'Partial',
|
||||
]);
|
||||
expect(b.themeId, t.id);
|
||||
final mine = b.resolveTheme(t.id)!;
|
||||
expect(mine.brightness, Brightness.dark);
|
||||
expect(mine.colors.accent, const Color(0xFFFF0000));
|
||||
expect(mine.colors.paper, SynapseColors.nord.paper);
|
||||
final partial = b.resolveTheme('custom-partial')!;
|
||||
expect(partial.colors.accent, const Color(0xFF00FF00));
|
||||
expect(partial.colors.ink, SynapseColors.dark.ink);
|
||||
});
|
||||
|
||||
test('deleting the selected theme falls back to auto', () {
|
||||
final store = MemorySettings();
|
||||
final a = AppState(MemoryBackend(), settings: store);
|
||||
final t = a.createCustomTheme();
|
||||
expect(a.themeId, t.id);
|
||||
a.deleteCustomTheme(t.id);
|
||||
expect(a.themeId, autoThemeId);
|
||||
expect(a.customThemes, isEmpty);
|
||||
expect(AppState(MemoryBackend(), settings: store).themeId, autoThemeId);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('settings: new theme is created, selected and editable', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(1200, 1600);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
final app = AppState(MemoryBackend());
|
||||
await tester.pumpWidget(
|
||||
AppScope(
|
||||
state: app,
|
||||
child: ListenableBuilder(
|
||||
listenable: app,
|
||||
builder: (_, _) {
|
||||
final t = app.resolveTheme(app.themeId);
|
||||
return MaterialApp(
|
||||
theme: buildTheme(
|
||||
t?.brightness ?? Brightness.light,
|
||||
colors: t?.colors,
|
||||
),
|
||||
home: const Scaffold(body: SettingsView()),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.tap(find.byKey(const ValueKey('theme-new')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(app.customThemes, hasLength(1));
|
||||
expect(app.themeId, app.customThemes.single.id);
|
||||
expect(find.byKey(const ValueKey('theme-preview')), findsOneWidget);
|
||||
|
||||
// Apply CSS from the CSS tab.
|
||||
await tester.tap(find.text('CSS'));
|
||||
await tester.pump();
|
||||
await tester.enterText(
|
||||
find.byKey(const ValueKey('theme-css')),
|
||||
':root { color-scheme: dark; --accent: #ff0000; --bogus: #fff; }',
|
||||
);
|
||||
await tester.tap(find.byKey(const ValueKey('theme-css-apply')));
|
||||
await tester.pump();
|
||||
expect(find.byKey(const ValueKey('theme-css-errors')), findsOneWidget);
|
||||
expect(app.customThemes.single.colors.accent, const Color(0xFFFF0000));
|
||||
expect(app.customThemes.single.brightness, Brightness.dark);
|
||||
|
||||
// Cancel discards a new theme and restores the previous selection.
|
||||
await tester.tap(find.byKey(const ValueKey('theme-cancel')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(app.customThemes, isEmpty);
|
||||
expect(app.themeId, autoThemeId);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user