refactor: clarify CSS cascade conversion and archive resource processing
This commit is contained in:
+130
-97
@@ -202,12 +202,8 @@ def _font_names(value):
|
||||
return names
|
||||
|
||||
|
||||
def analyze_css(source: str, font_size_px: float = 16) -> Analysis:
|
||||
result = Analysis()
|
||||
balance = _balanced(source)
|
||||
if balance:
|
||||
result.errors.append(balance)
|
||||
return result
|
||||
def _collect_cascade(source: str, result: Analysis):
|
||||
"""Choose core declarations by importance, specificity and source order."""
|
||||
winners = {target: {} for target in SELECTORS}
|
||||
for order, node in enumerate(css.parse_stylesheet(source, skip_comments=False, skip_whitespace=False)):
|
||||
if node.type == "error":
|
||||
@@ -254,100 +250,137 @@ def analyze_css(source: str, font_size_px: float = 16) -> Analysis:
|
||||
rank = (declaration.important, specificity, order, position)
|
||||
if prop not in winners[target] or rank >= winners[target][prop][0]:
|
||||
winners[target][prop] = (rank, _text(declaration.value))
|
||||
for target, entries in winners.items():
|
||||
props = {key: value[1] for key, value in entries.items()}
|
||||
rule = {}
|
||||
def read(prop, convert):
|
||||
if prop not in props or props[prop].lower() in ("inherit", "unset", "revert"):
|
||||
return
|
||||
try:
|
||||
convert(props[prop])
|
||||
except (ValueError, KeyError, TypeError):
|
||||
result.notes.append(f"{LABELS[target]}的 {prop}: {props[prop]} 仅保留为 CSS")
|
||||
def choice(prop, key, options):
|
||||
read(prop, lambda value: rule.update({key: options[value.lower()]}))
|
||||
def sized(value):
|
||||
amount, unit = _length(value, ("pt", "px"))
|
||||
if not 0 < amount <= 200:
|
||||
raise ValueError
|
||||
rule.update(font_size=amount, font_size_unit=unit)
|
||||
read("font-size", sized)
|
||||
def families(value):
|
||||
if re.sub(r"\s+", "", value) == re.sub(r"\s+", "", FONT_EXPRESSION):
|
||||
for key, variable in FONT_VARIABLES.items():
|
||||
if variable in props:
|
||||
rule[key] = _font_names(props[variable])[0]
|
||||
else:
|
||||
names = _font_names(value)
|
||||
rule.update(english_font_family=names[0], chinese_font_family=names[1] if len(names) > 1 and names[1] not in ("serif", "sans-serif", "monospace") else names[0])
|
||||
read("font-family", families)
|
||||
choice("font-weight", "bold", {"bold": True, "700": True, "normal": False, "400": False})
|
||||
choice("font-style", "italic", {"italic": True, "normal": False})
|
||||
choice("text-align", "alignment", {name: name for name in ("left", "center", "right", "justify")})
|
||||
def color(value):
|
||||
if value.lower() in ("currentcolor", "var(--reader-text-color, #23272f)"):
|
||||
rule["font_color"] = "auto"
|
||||
return
|
||||
rgba = parse_color(value)
|
||||
if rgba is None or isinstance(rgba, str) or rgba.alpha != 1:
|
||||
raise ValueError
|
||||
rule["font_color"] = "#" + "".join(f"{round(v * 255):02x}" for v in rgba[:3])
|
||||
read("color", color)
|
||||
def tracking(value):
|
||||
amount, unit = (0, "pt") if value == "normal" else _length(value, ("pt", "px"), negative=True)
|
||||
amount *= .75 if unit == "px" else 1
|
||||
if abs(amount) > 100:
|
||||
raise ValueError
|
||||
rule["letter_spacing"] = amount
|
||||
read("letter-spacing", tracking)
|
||||
def line(value):
|
||||
if value == "normal":
|
||||
amount, mode = 1, "multiple"
|
||||
elif re.fullmatch(r"(?:\d+(?:\.\d*)?|\.\d+)%?", value):
|
||||
amount = float(value.rstrip("%")) / (100 if value.endswith("%") else 1)
|
||||
mode = "multiple"
|
||||
else:
|
||||
amount, unit = _length(value, ("pt", "px"))
|
||||
amount *= .75 if unit == "px" else 1
|
||||
mode = "at_least" if props.get("--mdhelper-line-spacing-mode") == "at-least" else "exact"
|
||||
if not .1 <= amount <= 500:
|
||||
raise ValueError
|
||||
rule.update(line_height_value=amount, line_spacing_mode=mode)
|
||||
read("line-height", line)
|
||||
for side, prefix in (("left", "left_indent"), ("right", "right_indent"), ("top", "space_before"), ("bottom", "space_after")):
|
||||
def margin(value, prefix=prefix):
|
||||
amount, unit = _length(value, ("em", "pt", "px", "cm") if "indent" in prefix else ("em", "pt", "px", "lh", "cm"))
|
||||
if unit == "px":
|
||||
amount, unit = amount * .75, "pt"
|
||||
if unit == "cm" and "indent" not in prefix:
|
||||
amount, unit = amount * 72 / 2.54, "pt"
|
||||
if amount > (200 if "indent" in prefix else 1000):
|
||||
raise ValueError
|
||||
rule.update({prefix + "_value": amount, prefix + "_unit": "line" if unit == "lh" else unit})
|
||||
read("margin-" + side, margin)
|
||||
def indent(value):
|
||||
amount, unit = _length(value, ("em", "pt", "px"), negative=True)
|
||||
if unit != "em":
|
||||
points = font_points({**resolved_rules({}, font_size_px=font_size_px)[target], **rule})
|
||||
amount = amount * (.75 if unit == "px" else 1) / points
|
||||
if abs(amount) > 100:
|
||||
raise ValueError
|
||||
rule.update(indent_mode="none" if not amount else "first" if amount > 0 else "hanging", indent_value=abs(amount))
|
||||
read("text-indent", indent)
|
||||
for field, modern, legacy, yes in (("keep_with_next", "break-after", "page-break-after", ("avoid", "avoid-page")),
|
||||
("keep_lines_together", "break-inside", "page-break-inside", ("avoid", "avoid-page")),
|
||||
("page_break_before", "break-before", "page-break-before", ("page", "always"))):
|
||||
candidates = [name for name in (modern, legacy) if name in entries]
|
||||
return winners
|
||||
|
||||
|
||||
class _CoreRuleReader:
|
||||
"""Convert one target's winning CSS values to editable/Word style fields."""
|
||||
def __init__(self, target, entries, result, font_size_px):
|
||||
self.target, self.entries, self.result = target, entries, result
|
||||
self.font_size_px = font_size_px
|
||||
self.props = {key: value[1] for key, value in entries.items()}
|
||||
self.rule = {}
|
||||
|
||||
def parse(self):
|
||||
self.read('font-size', self.sized)
|
||||
self.read('font-family', self.families)
|
||||
self.choice('font-weight', 'bold', {'bold': True, '700': True, 'normal': False, '400': False})
|
||||
self.choice('font-style', 'italic', {'italic': True, 'normal': False})
|
||||
self.choice('text-align', 'alignment', {name: name for name in ('left', 'center', 'right', 'justify')})
|
||||
self.read('color', self.color)
|
||||
self.read('letter-spacing', self.tracking)
|
||||
self.read('line-height', self.line)
|
||||
for side, prefix in (('left', 'left_indent'), ('right', 'right_indent'), ('top', 'space_before'), ('bottom', 'space_after')):
|
||||
self.read('margin-' + side, lambda value, prefix=prefix: self.margin(value, prefix))
|
||||
self.read('text-indent', self.indent)
|
||||
self.pagination()
|
||||
self.choice('--mdhelper-contextual-spacing', 'contextual_spacing', {'true': True, 'false': False})
|
||||
return self.rule
|
||||
|
||||
def pagination(self):
|
||||
breaks = (
|
||||
('keep_with_next', 'break-after', 'page-break-after', ('avoid', 'avoid-page')),
|
||||
('keep_lines_together', 'break-inside', 'page-break-inside', ('avoid', 'avoid-page')),
|
||||
('page_break_before', 'break-before', 'page-break-before', ('page', 'always')),
|
||||
)
|
||||
for field, modern, legacy, yes in breaks:
|
||||
candidates = [name for name in (modern, legacy) if name in self.entries]
|
||||
if candidates:
|
||||
prop = max(candidates, key=lambda name: entries[name][0])
|
||||
choice(prop, field, {**{v: True for v in yes}, "auto": False})
|
||||
widow_values = [props[p] for p in ("widows", "orphans") if p in props]
|
||||
prop = max(candidates, key=lambda name: self.entries[name][0])
|
||||
self.choice(prop, field, {**{v: True for v in yes}, 'auto': False})
|
||||
widow_values = [self.props[p] for p in ('widows', 'orphans') if p in self.props]
|
||||
if widow_values:
|
||||
if all(v == "1" for v in widow_values) or all(v == "2" for v in widow_values):
|
||||
rule["widow_control"] = widow_values[0] == "2"
|
||||
if all((v == '1' for v in widow_values)) or all((v == '2' for v in widow_values)):
|
||||
self.rule['widow_control'] = widow_values[0] == '2'
|
||||
else:
|
||||
result.notes.append(f"{LABELS[target]}的 widows/orphans 仅保留为 CSS")
|
||||
choice("--mdhelper-contextual-spacing", "contextual_spacing", {"true": True, "false": False})
|
||||
self.result.notes.append(f'{LABELS[self.target]}的 widows/orphans 仅保留为 CSS')
|
||||
|
||||
def read(self, prop, convert):
|
||||
if prop not in self.props or self.props[prop].lower() in ('inherit', 'unset', 'revert'):
|
||||
return
|
||||
try:
|
||||
convert(self.props[prop])
|
||||
except (ValueError, KeyError, TypeError):
|
||||
self.result.notes.append(f'{LABELS[self.target]}的 {prop}: {self.props[prop]} 仅保留为 CSS')
|
||||
|
||||
def choice(self, prop, key, options):
|
||||
self.read(prop, lambda value: self.rule.update({key: options[value.lower()]}))
|
||||
|
||||
def sized(self, value):
|
||||
amount, unit = _length(value, ('pt', 'px'))
|
||||
if not 0 < amount <= 200:
|
||||
raise ValueError
|
||||
self.rule.update(font_size=amount, font_size_unit=unit)
|
||||
|
||||
def families(self, value):
|
||||
if re.sub('\\s+', '', value) == re.sub('\\s+', '', FONT_EXPRESSION):
|
||||
for key, variable in FONT_VARIABLES.items():
|
||||
if variable in self.props:
|
||||
self.rule[key] = _font_names(self.props[variable])[0]
|
||||
else:
|
||||
names = _font_names(value)
|
||||
chinese = names[1] if len(names) > 1 and names[1] not in ('serif', 'sans-serif', 'monospace') else names[0]
|
||||
self.rule.update(english_font_family=names[0], chinese_font_family=chinese)
|
||||
|
||||
def color(self, value):
|
||||
if value.lower() in ('currentcolor', 'var(--reader-text-color, #23272f)'):
|
||||
self.rule['font_color'] = 'auto'
|
||||
return
|
||||
rgba = parse_color(value)
|
||||
if rgba is None or isinstance(rgba, str) or rgba.alpha != 1:
|
||||
raise ValueError
|
||||
self.rule['font_color'] = '#' + ''.join((f'{round(v * 255):02x}' for v in rgba[:3]))
|
||||
|
||||
def tracking(self, value):
|
||||
amount, unit = (0, 'pt') if value == 'normal' else _length(value, ('pt', 'px'), negative=True)
|
||||
amount *= 0.75 if unit == 'px' else 1
|
||||
if abs(amount) > 100:
|
||||
raise ValueError
|
||||
self.rule['letter_spacing'] = amount
|
||||
|
||||
def line(self, value):
|
||||
if value == 'normal':
|
||||
amount, mode = (1, 'multiple')
|
||||
elif re.fullmatch('(?:\\d+(?:\\.\\d*)?|\\.\\d+)%?', value):
|
||||
amount = float(value.rstrip('%')) / (100 if value.endswith('%') else 1)
|
||||
mode = 'multiple'
|
||||
else:
|
||||
amount, unit = _length(value, ('pt', 'px'))
|
||||
amount *= 0.75 if unit == 'px' else 1
|
||||
mode = 'at_least' if self.props.get('--mdhelper-line-spacing-mode') == 'at-least' else 'exact'
|
||||
if not 0.1 <= amount <= 500:
|
||||
raise ValueError
|
||||
self.rule.update(line_height_value=amount, line_spacing_mode=mode)
|
||||
|
||||
def indent(self, value):
|
||||
amount, unit = _length(value, ('em', 'pt', 'px'), negative=True)
|
||||
if unit != 'em':
|
||||
points = font_points({**resolved_rules({}, font_size_px=self.font_size_px)[self.target], **self.rule})
|
||||
amount = amount * (0.75 if unit == 'px' else 1) / points
|
||||
if abs(amount) > 100:
|
||||
raise ValueError
|
||||
self.rule.update(indent_mode='none' if not amount else 'first' if amount > 0 else 'hanging', indent_value=abs(amount))
|
||||
|
||||
def margin(self, value, prefix):
|
||||
amount, unit = _length(value, ('em', 'pt', 'px', 'cm') if 'indent' in prefix else ('em', 'pt', 'px', 'lh', 'cm'))
|
||||
if unit == 'px':
|
||||
amount, unit = (amount * 0.75, 'pt')
|
||||
if unit == 'cm' and 'indent' not in prefix:
|
||||
amount, unit = (amount * 72 / 2.54, 'pt')
|
||||
if amount > (200 if 'indent' in prefix else 1000):
|
||||
raise ValueError
|
||||
self.rule.update({prefix + '_value': amount, prefix + '_unit': 'line' if unit == 'lh' else unit})
|
||||
|
||||
|
||||
def analyze_css(source: str, font_size_px: float = 16) -> Analysis:
|
||||
result = Analysis()
|
||||
balance = _balanced(source)
|
||||
if balance:
|
||||
result.errors.append(balance)
|
||||
return result
|
||||
winners = _collect_cascade(source, result)
|
||||
for target, entries in winners.items():
|
||||
rule = _CoreRuleReader(target, entries, result, font_size_px).parse()
|
||||
if rule:
|
||||
result.rules[target] = rule
|
||||
result.notes = list(dict.fromkeys(result.notes))
|
||||
|
||||
Reference in New Issue
Block a user