Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate LESS to nested CSS #1220

Merged
merged 7 commits into from
Oct 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ jobs:
- name: apt install
run: |
sudo apt-get update
sudo apt-get install --no-install-suggests --no-install-recommends inkscape icoutils scour optipng node-less node-source-map
sudo apt-get install --no-install-suggests --no-install-recommends inkscape icoutils scour optipng

- uses: actions/[email protected]
with:
Expand Down
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ The [conventions document](./conventions.md) describes some idioms used in the c
Grab the build dependencies with:

$ sudo apt install brotli inkscape icoutils git scour optipng \
python3-dev build-essential \
node-less node-source-map
python3-dev build-essential

[Install pip](https://pip.pypa.io/en/latest/installing/#get-pip), then install [Tox](http://tox.readthedocs.org/en/latest/).
(I actually recommend installing this in your home directory, but that's outside the scope of this document.)
Expand Down
83 changes: 52 additions & 31 deletions bin/compile-static.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/python3
# Copyright © 2018, 2019, 2020, 2022 Tom Most <[email protected]>
# Copyright © 2018, 2019, 2020, 2022, 2024 Tom Most <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
Expand Down Expand Up @@ -49,13 +49,16 @@
import re
import shlex
from asyncio.subprocess import PIPE
from dataclasses import dataclass
from collections import deque
from dataclasses import dataclass, field
from pathlib import Path
from shutil import rmtree
from typing import Optional, Sequence

import brotli
import tinycss2
import zopfli.gzip
from tinycss2.ast import AtRule, ParseError

repo_root = Path(__file__).parent.parent

Expand Down Expand Up @@ -244,39 +247,57 @@ async def process_svg(svg: Path, w: Writer) -> None:
w.add_file_bytes(hashname(svg.stem, "svg", svg_bytes), svg_bytes)


async def process_less(less: Path, build_dir: Path, w: Writer) -> None:
async def process_css(css: Path, w: Writer) -> None:
"""
Convert .less to a CSS file and source map.
Process a stylesheet to inline stylesheets referenced via @include rules.
"""
css_path = build_dir / f"{less.stem}.css"
map_path = build_dir / f"{less.stem}.css.map"
await _run(
[
"/usr/bin/node",
"/usr/bin/lessc",
"--no-js",
"--strict-imports",
f"--source-map={map_path}",
str(less),
str(css_path),
]
)
css = css_path.read_bytes()
css_name = hashname(less.stem, "css", css)
map_name = f"{css_name}.map"
combiner = CombinedCss(root_dir=css.parent)
combiner.include(css.name, "utf-8")

combined = combiner.serialize().encode("utf-8")
w.add_file_bytes(hashname(css.stem, "css", combined), combined)


# We must change the source map reference on the last line when renaming
# the file.
last_line_index = css.rindex(b"\n") + 1
last_line = css[last_line_index:]
if not last_line.startswith(b"/*# sourceMappingURL="):
raise Exception("Expected sourceMappingURL comment at the end of {css_path}, but found {last_line!r}")
@dataclass
class CombinedCss:
root_dir: Path
_included: set[str] = field(default_factory=set, init=False)
_rules: list[object] = field(default_factory=list, init=False)

def include(self, path: str, protocol_encoding=None, environment_encoding=None) -> None:
if path in self._included:
# print(f"Skipping duplicate @import {path!r}")
return
else:
# TODO: Should normalize the path to avoid dupe includes
# TODO: Should verify the path is within root_dir
# print(f"Including rules from @import {path!r}")
self._included.add(path)

with (self.root_dir / path).open("rb") as f:
rules, encoding = tinycss2.parse_stylesheet_bytes(
f.read(),
protocol_encoding,
environment_encoding,
)

# ❤ copies
css = css[:last_line_index] + f"/*# sourceMappingURL={map_name} */".encode()
for rule in rules:
if rule.type == "at-rule" and rule.lower_at_keyword == "import":
# We only support the form `@import "./foo". The full syntax is quite complex:
# https://developer.mozilla.org/en-US/docs/Web/CSS/@import
[ws, urlish] = rule.prelude
assert ws.type == "whitespace"
assert urlish.type == "string"
self.include(urlish.value)
elif rule.type == "parse-error":
# Note that very little counts as a parse error in CSS, so
# this is not a useful diagnostic tool.
raise ValueError(f"Parse error in {path}: {rule.message}")
else:
self._rules.append(rule)

w.add_file_bytes(css_name, css)
w.add_file(map_name, map_path)
def serialize(self):
return tinycss2.serialize(self._rules)


async def process_glob(paths: Path, w: Writer) -> None:
Expand Down Expand Up @@ -347,7 +368,7 @@ async def _main(build_dir: Path, out_dir: Path, compress: bool) -> None:
process_svg(repo_root / "img" / "lettertype.svg", w),
process_svg(repo_root / "img" / "logotype.svg", w),
process_glob((repo_root / "vendor" / "normalize.css").glob("normalize-*.css"), w),
process_less(repo_root / "less" / "main.less", build_dir, w),
process_css(repo_root / "css" / "main.css", w),
process_fonts(repo_root, w),
)
print(w.summarize())
Expand Down
4 changes: 1 addition & 3 deletions less/Article.less → css/Article.css
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
@import "./include.less";


.article-header {
display: grid;
grid-template-columns: 1fr min-content;
Expand All @@ -17,6 +14,7 @@
.tools {
display: flex;
flex-flow: row nowrap;
--focus-offset: var(--focus-offset-in); /* Don't clip focus ring. */

.icon {
width: 2em;
Expand Down
2 changes: 0 additions & 2 deletions less/FeedView.less → css/FeedView.css
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
@import "./include.less";

.feed-header {
h1 {
margin: 1rem 0;
Expand Down
6 changes: 1 addition & 5 deletions less/GlobalBar.less → css/GlobalBar.css
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
@import "./include.less";

.yarrharr-masthead {
display: flex;
flex: 0 0 auto;
Expand Down Expand Up @@ -36,8 +34,6 @@
display: flex;
align-items: center;
justify-content: center;

.flat-button;

--focus-offset: var(--focus-offset-in); /* Don't clip focus ring. */
padding: 1rem; /* Ensure spacing between */
}
20 changes: 5 additions & 15 deletions less/ListArticle.less → css/ListArticle.css
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
@import "./include.less";

.list-article {
margin: 0.75rem 0;
}

.list-article-inner {
// max-width: var(--layout-max-width);
margin: 0 auto;
overflow: hidden;
}
Expand All @@ -14,14 +11,14 @@
display: flex;
flex-flow: row nowrap;
align-items: stretch;
--focus-offset: var(--focus-offset-in); /* Don't clip focus ring. */

.outbound {
.flat-button;
padding: ((2 * @button_border_width));
padding: calc(2 * var(--button-border-width));
flex: 1 1 100%;
width: 100%;
display: grid;
// XXX: Using grid here is starting to look a little silly.
/* XXX: Using grid here is starting to look a little silly. */
grid-template-areas:
"meta1"
"meta2";
Expand All @@ -37,12 +34,10 @@
color: var(--quiet-text-color);
text-transform: uppercase;
font-size: smaller;
// background: red;
}
.meta2 {
grid-area: meta2;
font-family: "Newsreader";
// background: blue;
}
.meta1,
.meta2 {
Expand All @@ -61,33 +56,28 @@

read-toggle,
.view-link {
flex: 0 0 @bar_height;
flex: 0 0 var(--bar-height);
}
read-toggle {
button {
.flat-button;
width: 100%;
height: 100%;
}
// background: purple;
}
.view-link {
// background: magenta;
.flat-button;
}

.outbound-icon,
read-toggle button,
.view-link {
font-size: @icon_size;
font-size: var(--icon-size);
display: flex;
flex-flow: row nowrap;
align-items: center;
justify-content: center;

.icon {
flex: 0 0 auto;
// background: white;
display: block;
align-self: center;
justify-self: center;
Expand Down
8 changes: 4 additions & 4 deletions less/StateToggle.less → css/StateToggle.css
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
fave-toggle {
button {
.flat-button;
padding: 1px 4px;
background: transparent;
border: none;
}

.inactive {
Expand All @@ -22,8 +22,8 @@ fave-toggle {

read-toggle {
button {
.flat-button;
padding: 1px 4px;
background: transparent;
border: none;
}

.inactive {
Expand Down
4 changes: 1 addition & 3 deletions less/Tabs.less → css/Tabs.css
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
@import "./include.less";

/**
* <div.tabs>
* <div.tabs-tabs>
Expand Down Expand Up @@ -29,7 +27,7 @@
border-radius: 4px 4px 0 0;
text-decoration: none;
line-height: 1.7;
padding: 0.125rem 8px 0 8px;
padding: 0.125rem 8px 2px 8px;
white-space: nowrap;
text-align: center;
text-overflow: ellipsis;
Expand Down
File renamed without changes.
Loading