Files
EnragedAntelope 3ccd87219d Release 0.16.1: picker keeps its search text; New tab survives fix-only releases
- Picker search box shows the remembered query on reopen, selected so the first keystroke replaces it
- Frontend regression test for close/reopen
- New tab and ribbons follow the newest release that added entries (NEW_RELEASE), so 0.16.1 keeps showing "New in 0.16.0"
- stamp_versions.py --stamp lists the current version in RELEASES even with no new entries
- Bump to 0.16.1; regenerated data/versions.py, js/stylebook_data.js, docs/gallery/index.html
- README, ARCHITECTURE.md, AGENTS.md updated
2026-09-27 22:55:42 -04:00

313 lines
14 KiB
Python

"""Generate the frontend's data files from the Python data layer.
Writes two files, both generated in full, both containing nothing
hand-written. The gallery code lives in ``js/stylebook_gallery.js`` and
this script never touches it.
**Why two files.** ComfyUI discovers frontend extensions by globbing
``**/*.js`` under every pack's web directory and importing every hit
(``server.py``, ``get_extensions``). It does not care whether a file
registers an extension -- a ``.js`` file in ``js/`` is parsed at app
start no matter what. The style corpus is roughly 300 KB of that, and
every ComfyUI user paid for it on every load, including the ones with no
Stylebook node on the canvas.
So the corpus moved to ``js/stylebook_data.json``, which the glob does
not match and which the gallery fetches the first time a picker opens.
What stays in ``js/stylebook_data.js`` is only what the *node* needs
before any dialog exists: the axis-to-modifier map that gates the
Modifier widget, the category tables the tab strip names, and the
counts. That is a couple of kilobytes.
Moving it to a ``.mjs`` module and using a dynamic ``import()`` would
have been tidier to read, but a module import is subject to the server's
MIME type for the extension, and ``mimetypes`` on Windows takes its
answer from the registry. ``fetch`` + ``response.json()`` enforces no
MIME type at all.
An earlier revision generated into the middle of a hand-edited file and
overwrote the whole thing, silently deleting the ``export`` statements
the gallery imported. That broke the entire frontend, and ``--check``
still passed, because it only compared the generated block against a
fresh render of itself. Keeping generated and hand-written code in
separate files removes that failure mode entirely.
Usage:
python scripts/generate_js_data.py # write both files
python scripts/generate_js_data.py --check # verify (CI gate)
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
# A maintainer's own local user_styles.json must never reach a shipped
# artifact. Set before `data` is ever imported below, since data/user_data.py
# reads this once at merge time.
os.environ.setdefault("STYLEBOOK_IGNORE_USER_STYLES", "1")
TARGET = ROOT / "js" / "stylebook_data.js"
BULK_TARGET = ROOT / "js" / "stylebook_data.json"
PREVIEW_INDEX = ROOT / "js" / "previews" / "index.json"
HEADER = """\
// Generated by scripts/generate_js_data.py. Do not edit by hand.
// Regenerate after changing anything under data/:
// python scripts/generate_js_data.py
//
// This entire file is generated. Hand-written frontend code belongs in
// stylebook_gallery.js, which the generator never touches.
//
// Only what a node needs before any dialog exists lives here. The style,
// artist and modifier corpus is in stylebook_data.json, fetched the first
// time a picker opens -- ComfyUI imports every .js under a pack's web
// directory at app start, so a 300 KB one is a tax on every user.
"""
def _js(value: object) -> str:
"""Render a Python value as JSON, which is valid JS for these shapes."""
return json.dumps(value, ensure_ascii=False)
def _preview_sprites() -> dict:
"""Reshape the preview index into responsive sprite coordinates.
The gallery sizes its tiles with a CSS grid, so they are not a fixed
pixel width. CSS percentage ``background-size`` is measured against
the element rather than the image, which means a tile grid can only
be addressed in grid units: an atlas that is ``cols`` tiles wide is
scaled to ``cols * 100%`` of the tile, and each tile is then reached
with a percentage position. Emitting column/row indices instead of
pixels keeps that arithmetic on this side and shrinks the payload.
"""
if not PREVIEW_INDEX.is_file():
return {}
raw = json.loads(PREVIEW_INDEX.read_text(encoding="utf-8"))
out: dict[str, dict] = {}
for category, entry in raw.get("categories", {}).items():
tiles = entry.get("tiles", {})
if not tiles:
continue
first = next(iter(tiles.values()))
tile_w, tile_h = first.get("w", 256), first.get("h", 256)
if not tile_w or not tile_h:
continue
cols = max(t["x"] + t["w"] for t in tiles.values()) // tile_w
rows = max(t["y"] + t["h"] for t in tiles.values()) // tile_h
out[category] = {
"atlas": entry.get("atlas", f"{category}.webp"),
# Content hash of the atlas, appended to its URL as ?v=<rev>.
# The filename is stable, so without this a browser holding a
# cached atlas composites these fresh offsets over stale
# pixels and draws visibly wrong tiles. An index written
# before "rev" existed omits it and the consumers fall back
# to the bare URL.
"rev": entry.get("rev", ""),
"cols": cols,
"rows": rows,
"tiles": {
sid: [t["x"] // tile_w, t["y"] // tile_h]
for sid, t in tiles.items()
},
}
return {"model": raw.get("model", ""), "categories": out}
def new_release() -> str:
"""The release the "New" tab shows: the newest one that added entries.
Not the pyproject version -- a fix-only release stamps nothing, and
naming it would empty the tab the moment it shipped.
"""
from data.versions import ADDED_IN, RELEASES
used = {v for stamps in ADDED_IN.values() for v in stamps.values()}
return next((v for v in reversed(RELEASES) if v in used), "")
def generate() -> tuple[str, str]:
from data.artists import (
ARTIST_CATEGORIES, ARTIST_CATEGORY_LABELS, ARTISTS,
)
from data.modifiers import (AXES, AXIS_LABELS, MODIFIERS,
MODIFIERS_BY_AXIS)
from data.ordering import label_sort_key
from data.styles import CATEGORIES, CATEGORY_LABELS, STYLES
from data.versions import ADDED_IN, RELEASES
styles_by_category: dict[str, dict[str, list]] = {}
for category in CATEGORIES:
# Alphabetical, not data order. Data order buried each release's
# additions at the bottom of their category, and made the "All"
# tab a concatenation of categories rather than a browsable list.
ids = sorted(
(sid for sid, rec in STYLES.items() if rec.get("category") == category),
key=lambda sid: label_sort_key(STYLES[sid]["label"]),
)
styles_by_category[category] = {
"ids": ids,
"labels": [STYLES[sid]["label"] for sid in ids],
# The release each style first shipped in, so the gallery can
# sort by newest and filter to "New" without a second lookup
# table. data/versions.py is the source; CI keeps it complete.
"added": [ADDED_IN["styles"].get(sid, "") for sid in ids],
# Who the style is named after, when it is named after
# somebody. Shown in the tile tooltip so the promise the tile
# makes is visible before the render, not just to a maintainer.
"namesakes": [STYLES[sid].get("namesake", "") for sid in ids],
# Aliases power gallery search. The search box has always
# claimed to match them; now it actually can.
"aliases": [list(STYLES[sid].get("aliases", [])) for sid in ids],
# The setting a style imposes on your subject, or "" for the
# great majority that only change how it is rendered. Drives
# the gallery's scene badge.
"scenes": [STYLES[sid].get("scene", "") for sid in ids],
"depicts": [STYLES[sid].get("depicts", "") for sid in ids],
}
artists = sorted(ARTISTS.values(), key=lambda rec: label_sort_key(rec["label"]))
modifiers_by_axis = {
axis: [MODIFIERS[mid]["label"]
for mid in MODIFIERS_BY_AXIS.get(axis, []) if mid in MODIFIERS]
for axis in AXES
}
# The picker shows what each modifier actually does. A list of names
# like "Split Tone" or "Bleach Bypass" tells you nothing on its own.
modifier_records = [
{
"label": MODIFIERS[mid]["label"],
# The record id, carried alongside the label because a modifier
# is addressed by *label* everywhere in the pack -- so the
# picker item's id is the label, and the preview atlas (keyed by
# stable record id, like every other atlas) cannot be reached
# with it. Labels can be reworded; ids cannot.
"mid": mid,
"axis": axis,
"detail": MODIFIERS[mid].get("prose", ""),
"aliases": list(MODIFIERS[mid].get("aliases", [])),
"added": ADDED_IN["modifiers"].get(mid, ""),
}
for axis in AXES
for mid in MODIFIERS_BY_AXIS.get(axis, [])
if mid in MODIFIERS
]
artist_ids_by_label = {rec["label"]: aid for aid, rec in ARTISTS.items()}
preview_index = _preview_sprites()
all_labels = sorted(
(rec["label"] for rec in STYLES.values()), key=label_sort_key
)
lines = [
HEADER,
f"export const CATEGORIES = {_js(list(CATEGORIES))};",
"// Display names. Title-casing the id gives \"Three D Digital\".",
f"export const CATEGORY_LABELS = {_js(CATEGORY_LABELS)};",
"",
f"export const STYLE_COUNT = {len(STYLES)};",
f"export const ARTIST_COUNT = {len(ARTISTS)};",
"",
"// The newest release that added entries, and every release, oldest",
"// first. The gallery's \"New\" tab means NEW_RELEASE; the",
"// newest-first sort ranks by position in RELEASES rather than",
"// parsing version strings in JavaScript.",
f"export const NEW_RELEASE = {_js(new_release())};",
f"export const RELEASES = {_js(list(RELEASES))};",
"",
"// The axis-to-modifier map gates the Modifier node's dropdown as",
"// soon as the node exists, before any dialog is opened, so unlike",
"// the corpus it genuinely has to be here.",
f"export const MODIFIER_AXES = {_js(list(AXES))};",
"// Display names, same reason as CATEGORY_LABELS: title-casing",
"// \"color_grade\" gives \"Color Grade\" and this pack spells it",
"// \"Colour Grade\" on every surface a person reads.",
f"export const MODIFIER_AXIS_LABELS = {_js(AXIS_LABELS)};",
f"export const MODIFIER_LABELS_BY_AXIS = {_js(modifiers_by_axis)};",
"",
"// The category tabs for the artist picker, in offer order, plus",
"// their display names. Derived from the data so a category added",
"// by a user_styles.json artist still gets a tab.",
f"export const ARTIST_CATEGORY_ORDER = {_js(list(ARTIST_CATEGORIES))};",
f"export const ARTIST_CATEGORY_LABELS = {_js(ARTIST_CATEGORY_LABELS)};",
"",
"// Everything else -- 600-plus styles, 800-plus artist descriptors,",
"// every modifier and the sprite index -- is in stylebook_data.json,",
"// fetched by the gallery the first time a picker opens.",
f"export const BULK_DATA_FILE = {_js(BULK_TARGET.name)};",
"",
]
bulk = {
# Per-category ids, labels, aliases, scenes, release stamps and
# namesakes as parallel arrays.
"STYLE_DATA_BY_CATEGORY": styles_by_category,
# Every style label, in data/ordering.py's order -- the same order
# the node's own dropdown uses. The gallery sorts with
# Intl.Collator rather than reading this, because it also has to
# place entries from a user_styles.json this generator never saw.
# That makes one rule in two languages, so
# tests/frontend/gallery.test.mjs asserts that re-sorting this list
# with the JS comparator changes nothing.
"ALL_STYLE_LABELS": all_labels,
"ARTIST_LABELS": [r["label"] for r in artists],
"ARTIST_CATEGORIES": [r.get("category", "") for r in artists],
"ARTIST_ALIASES": [list(r.get("aliases", [])) for r in artists],
# Descriptors are what actually make an artist choosable: the name
# alone means nothing if you do not already know the work.
"ARTIST_DESCRIPTORS": [r.get("descriptor", "") for r in artists],
"ARTIST_ADDED": [
ADDED_IN["artists"].get(artist_ids_by_label.get(r["label"], ""), "")
for r in artists
],
"MODIFIER_RECORDS": modifier_records,
# Sprite-sheet coordinates for the gallery thumbnails. Empty when
# previews have not been built, in which case the gallery falls
# back to lettered placeholder tiles.
"PREVIEW_INDEX": preview_index,
}
return "\n".join(lines), json.dumps(bulk, ensure_ascii=False, sort_keys=True)
def main() -> int:
parser = argparse.ArgumentParser(description="Generate frontend JS data.")
parser.add_argument("--check", action="store_true",
help="Verify only; exit non-zero if stale.")
args = parser.parse_args()
expected, expected_bulk = generate()
pairs = ((TARGET, expected), (BULK_TARGET, expected_bulk))
if args.check:
for path, want in pairs:
if not path.is_file():
print(f"FAIL: {path.name} does not exist. "
f"Run: python scripts/generate_js_data.py")
return 1
if path.read_text(encoding="utf-8") != want:
print(f"FAIL: {path.name} is stale. "
"Run: python scripts/generate_js_data.py")
return 1
print("PASS: generated frontend data is current.")
return 0
for path, want in pairs:
path.write_text(want, encoding="utf-8", newline="\n")
print(f"Written: js/{path.name} ({len(want):,} bytes)")
return 0
if __name__ == "__main__":
sys.exit(main())