Use dict instead of tuple for variables

This commit is contained in:
Matthias Metelka 2022-10-20 11:06:03 +02:00
parent eceb426831
commit 2f2f00adc0
7 changed files with 67 additions and 42 deletions

View file

@ -101,12 +101,11 @@ def backend_color_to_aqt_color(color: BrowserRow.Color.V) -> tuple[str, str] | N
return adjusted_bg_color(temp_color) return adjusted_bg_color(temp_color)
def adjusted_bg_color(color: tuple[str, str]) -> tuple[str, str]: def adjusted_bg_color(color: dict[str, str]) -> dict:
if color: if color:
return ( color.day = color.day.lighter(150).name()
QColor(color[0]).lighter(150).name(), color.night = color.night.darker(150).name()
QColor(color[1]).darker(150).name(), return color
)
else: else:
return None return None

View file

@ -37,11 +37,15 @@ with open(input_svg, "r") as f:
elif f"{prefix}-dark.svg" in path: elif f"{prefix}-dark.svg" in path:
dark_svg = path dark_svg = path
for (idx, filename) in enumerate((light_svg, dark_svg)): def substitute(data: str, filename: str, mode: str) -> None:
data = svg_data
if "fill" in data: if "fill" in data:
data = re.sub(r"fill=\"#.+?\"", f'fill="{color[idx]}"', data) data = re.sub(r"fill=\"#.+?\"", f'fill="{color[mode]}"', data)
else: else:
data = re.sub(r"<svg", f'<svg fill="{color[idx]}"', data, 1) data = re.sub(r"<svg", f'<svg fill="{color[mode]}"', data, 1)
with open(filename, "w") as f: with open(filename, "w") as f:
f.write(data) f.write(data)
substitute(svg_data, light_svg, "light")
substitute(svg_data, dark_svg, "dark")

View file

@ -6,7 +6,6 @@ from aqt import colors
from aqt.qt import * from aqt.qt import *
from aqt.theme import theme_manager from aqt.theme import theme_manager
class Switch(QAbstractButton): class Switch(QAbstractButton):
"""A horizontal slider to toggle between two states which can be denoted by strings and/or QIcons. """A horizontal slider to toggle between two states which can be denoted by strings and/or QIcons.
@ -19,8 +18,8 @@ class Switch(QAbstractButton):
radius: int = 10, radius: int = 10,
left_label: str = "", left_label: str = "",
right_label: str = "", right_label: str = "",
left_color: tuple[str, str] = colors.ACCENT_CARD, left_color: dict[str, str] = colors.ACCENT_CARD,
right_color: tuple[str, str] = colors.ACCENT_NOTE, right_color: dict[str, str] = colors.ACCENT_NOTE,
parent: QWidget = None, parent: QWidget = None,
) -> None: ) -> None:
super().__init__(parent=parent) super().__init__(parent=parent)

View file

@ -31,16 +31,15 @@ from aqt.qt import (
@dataclass @dataclass
class ColoredIcon: class ColoredIcon:
path: str path: str
# (day, night) color: dict[str, str]
color: tuple[str, str]
def current_color(self, night_mode: bool) -> str: def current_color(self, night_mode: bool) -> str:
if night_mode: if night_mode:
return self.color[1] return self.color.get("dark", "")
else: else:
return self.color[0] return self.color.get("light", "")
def with_color(self, color: tuple[str, str]) -> ColoredIcon: def with_color(self, color: dict[str, str]) -> ColoredIcon:
return ColoredIcon(path=self.path, color=color) return ColoredIcon(path=self.path, color=color)
@ -178,12 +177,11 @@ class ThemeManager:
"Returns body classes used when showing a card." "Returns body classes used when showing a card."
return f"card card{card_ord+1} {self.body_class(night_mode)}" return f"card card{card_ord+1} {self.body_class(night_mode)}"
def var(self, vars: tuple[str, str]) -> str: def var(self, vars: dict[str, str]) -> str:
"""Given day/night colors/props, return the correct one for the current theme.""" """Given day/night colors/props, return the correct one for the current theme."""
idx = 1 if self.night_mode else 0 return vars["dark" if self.night_mode else "light"]
return vars[idx]
def qcolor(self, colors: tuple[str, str]) -> QColor: def qcolor(self, colors: dict[str, str]) -> QColor:
return QColor(self.var(colors)) return QColor(self.var(colors))
def _determine_night_mode(self) -> bool: def _determine_night_mode(self) -> bool:

View file

@ -453,8 +453,8 @@ div[contenteditable="true"]:focus {{
body {{ zoom: {zoom}; background-color: var(--canvas); }} body {{ zoom: {zoom}; background-color: var(--canvas); }}
html {{ {font} }} html {{ {font} }}
{button_style} {button_style}
:root {{ --canvas: {colors.CANVAS[0]} }} :root {{ --canvas: {colors.CANVAS["light"]} }}
:root[class*=night-mode] {{ --canvas: {colors.CANVAS[1]} }} :root[class*=night-mode] {{ --canvas: {colors.CANVAS["dark"]} }}
""" """
def stdHtml( def stdHtml(

View file

@ -1,10 +1,10 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# Copyright: Ankitects Pty Ltd and contributors # Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html # License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import json import json
import re import re
import sys import sys
import pprint
# bazel genrule "srcs" # bazel genrule "srcs"
root_vars_css = sys.argv[1] root_vars_css = sys.argv[1]
@ -13,17 +13,30 @@ root_vars_css = sys.argv[1]
colors_py = sys.argv[2] colors_py = sys.argv[2]
props_py = sys.argv[3] props_py = sys.argv[3]
class Var(str):
def __new__(self, value: str, comment: str):
self.comment = comment
return str.__new__(self, value)
def comment(self):
return self.comment
colors = {} colors = {}
props = {} props = {}
reached_props = False reached_props = False
comment = ""
for line in re.split(r"[;\{\}]", open(root_vars_css).read()): for line in re.split(r"[;\{\}]|\*\/", open(root_vars_css).read()):
line = line.strip() line = line.strip()
if not line: if not line:
continue continue
if "props" in line: if line.startswith("/*!"):
reached_props = True if "props" in line:
reached_props = True
else:
comment = re.match(r"\/\*!\s*(.*)$", line)[1]
continue
m = re.match(r"--(.+):(.+)$", line) m = re.match(r"--(.+):(.+)$", line)
@ -38,39 +51,47 @@ for line in re.split(r"[;\{\}]", open(root_vars_css).read()):
print("failed to match", line) print("failed to match", line)
continue continue
var = m.group(1) var = m.group(1).replace("-", "_").upper()
val = m.group(2) val = m.group(2)
if reached_props: if reached_props:
props.setdefault(var, []).append(val) if not var in props:
props.setdefault(var, {})["comment"] = comment
props[var]["light"] = val
else:
props[var]["dark"] = val
else: else:
colors.setdefault(var, []).append(val) if not var in colors:
colors.setdefault(var, {})["comment"] = comment
colors[var]["light"] = val
else:
colors[var]["dark"] = val
comment = ""
copyright_notice = """\ copyright_notice = """\
# Copyright: Ankitects Pty Ltd and contributors # Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html # License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html\n
""" """
with open(colors_py, "w") as buf: with open(colors_py, "w") as buf:
buf.write(copyright_notice) buf.write(copyright_notice)
buf.write("# this file is auto-generated from _root-vars.scss\n") buf.write("# This file was automatically generated from _root-vars.scss\n")
for color, val in colors.items(): for color, val in colors.items():
day = val[0] if not "dark" in val:
night = val[1] if len(val) > 1 else day val["dark"] = val.light
color = color.replace("-", "_").upper() buf.write(f'{color} = {pprint.pformat(val, width=50, sort_dicts=False)}\n')
buf.write(f'{color} = ("{day}", "{night}")\n')
with open(props_py, "w") as buf: with open(props_py, "w") as buf:
buf.write(copyright_notice) buf.write(copyright_notice)
buf.write("# this file is auto-generated from _root-vars.scss\n") buf.write("# This file was automatically generated from _root-vars.scss\n")
for prop, val in props.items(): for prop, val in props.items():
day = val[0] if not "dark" in val:
night = val[1] if len(val) > 1 else day val["dark"] = val.light
prop = prop.replace("-", "_").upper() buf.write(f'{prop} = {pprint.pformat(val, width=50, sort_dicts=False)}\n')
buf.write(f'{prop} = ("{day}", "{night}")\n')

View file

@ -9,11 +9,13 @@
:root { :root {
$colors: map.get($vars, colors); $colors: map.get($vars, colors);
@each $name, $val in create-vars-from-map($colors, light) { @each $name, $val in create-vars-from-map($colors, light) {
/*! #{$name} */
#{$name}: #{$val}; #{$name}: #{$val};
} }
color-scheme: light; color-scheme: light;
&.night-mode { &.night-mode {
@each $name, $val in create-vars-from-map($colors, dark) { @each $name, $val in create-vars-from-map($colors, dark) {
/*! #{$name} */
#{$name}: #{$val}; #{$name}: #{$val};
} }
color-scheme: dark; color-scheme: dark;
@ -24,10 +26,12 @@
:root { :root {
$props: map.get($vars, props); $props: map.get($vars, props);
@each $name, $val in create-vars-from-map($props, light) { @each $name, $val in create-vars-from-map($props, light) {
#{$name}: #{$val}; /*! #{$name} */ /*! #{$name} */
#{$name}: #{$val};
} }
&.night-mode { &.night-mode {
@each $name, $val in create-vars-from-map($props, dark) { @each $name, $val in create-vars-from-map($props, dark) {
/*! #{$name} */
#{$name}: #{$val}; #{$name}: #{$val};
} }
} }