Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25b7436911 | ||
|
|
24321e7f6d |
@@ -8,12 +8,14 @@ investigation notes, 1.5.0+ — the reasoning for every item in the release list
|
||||
|
||||
## Current state
|
||||
|
||||
_Last verified: 2026-11-01_
|
||||
_Last verified: 2026-11-14_
|
||||
|
||||
- **Status:** in active development; main is v2.4.0 (`pyproject.toml`); 2.0.0 was the seed epoch (every seed resolves differently from 1.x, by design). Published to the Comfy Registry via `.github/workflows/publish_action.yml`, which fires on a `pyproject.toml` version change on `main` - bump the version on every functional commit or the release never ships. CI (`.github/workflows/ci.yml`) is deliberately dependency-free, has a Windows leg, and `publish-node` needs it (1.8.0).
|
||||
- **Works:** the constraint engine resolving dropdowns into coherent prose plus structured JSON, seed-reproducible; the four preset layer nodes (Archetype, Creature, Modifier, Cosplayer); searchable dropdown widgets, live preview, the `franchise_filter`, the `random_pool` scope-composing filter, and the save/load vault in `js/` (an atomic overwrite, a disk-change-aware cache fingerprint, and Windows-reserved-name handling as of 1.5.5); a searchable **in-node roster picker** (`js/identity_forge_picker.js`) on the Cosplayer/Archetype/Creature nodes — trait facets, gender and franchise filters, cross-tab search, opt-in gallery thumbnails, backed by a generated `js/identity_forge_roster.json` search index; Stylebook interop, the composition axis, and the **Turnaround** reference-set node (which emits every camera view of one resolved character as a list, so one queue renders the set) and its face-side sibling the **Expression Sheet** (1.10.0: one view per curated expression/mood/smile triple); a free-text `held_item` on the Modifier node; a jsdom frontend suite alongside the Python one; generated reference docs and JS data, and a committed field-marginals baseline (`scripts/sweep_marginals.py`, 1.5.5 — catches a value drawing far more or less often than intended), plus a reachability gate (`--unreachable`, 1.8.0: every pool value some gender can draw, or a reasoned exception in `tests/fixtures/unreachable_by_design.json`), all with `--check` modes wired into the gate. A cosplay entry may render as a **person in a costume**, as a **mascot suit** (`covers_face` + `covers_body` + `mask`), or — since 0.95.0 — as the **beast itself** (`body_plan: "feral"`, which emits the Creature node's Species & Anatomy payload instead of a costume); see architecture.md → "Animal characters split four ways". `scripts/render_gallery.py` renders a roster entry's gallery image by driving a running ComfyUI over HTTP and publishes it to `gh-pages`, and `gallery/render_manifest.json` + `--check` fail CI when an entry's text changes without a re-render (architecture.md → "The gallery render pipeline"). Since 0.97.0 every roster entry also carries a **release stamp** (`data/versions.py`, written by `scripts/stamp_versions.py`, gated in CI), which is what lets the three sample gallery pages offer **A–Z / Newest first** and a **New in `<version>`** filter. Since 2.0.0: a **`gaze`** field drawn last with `pose` (both with live constraint rules; architecture.md -> "pose and gaze draw last"), opt-in **`costume_back`** for Turnaround back views, **per-garment `{slot}` variation** in the outfit corpus on its own seed stream, and a gallery hash over **resolved prose** so an engine change marks images stale. Since 2.3.0: the **Outfit Sheet** and **Age Progression** sheet nodes (they release the fields a pin refuses via `lock_clash` rather than override them; architecture.md -> "Sheets that change the person"), and picker previews served through a **server-side gallery cache** (`nodes/gallery_cache.py`) so they work under ComfyUI `--offline`.
|
||||
- **Status:** in active development; main is v2.6.0 (`pyproject.toml`); 2.0.0 was the seed epoch (every seed resolves differently from 1.x, by design). Published to the Comfy Registry via `.github/workflows/publish_action.yml`, which fires on a `pyproject.toml` version change on `main` - bump the version on every functional commit or the release never ships. CI (`.github/workflows/ci.yml`) is deliberately dependency-free, has a Windows leg, and `publish-node` needs it (1.8.0).
|
||||
- **Works:** the constraint engine resolving dropdowns into coherent prose plus structured JSON, seed-reproducible; the four preset layer nodes (Archetype, Creature, Modifier, Cosplayer); searchable dropdown widgets, live preview, the `franchise_filter`, the `random_pool` scope-composing filter, and the save/load vault in `js/` (an atomic overwrite, a disk-change-aware cache fingerprint, and Windows-reserved-name handling as of 1.5.5); a searchable **in-node roster picker** (`js/identity_forge_picker.js`) on the Cosplayer/Archetype/Creature nodes - trait facets, gender and franchise filters, cross-tab search, opt-in gallery thumbnails, backed by a generated `js/identity_forge_roster.json` search index; Stylebook interop, the composition axis, and the **Turnaround** reference-set node (which emits every camera view of one resolved character as a list, so one queue renders the set) and its face-side sibling the **Expression Sheet** (1.10.0: one view per curated expression/mood/smile triple); a free-text `held_item` on the Modifier node; a jsdom frontend suite alongside the Python one; generated reference docs and JS data, and a committed field-marginals baseline (`scripts/sweep_marginals.py`, 1.5.5 - catches a value drawing far more or less often than intended), plus a reachability gate (`--unreachable`, 1.8.0: every pool value some gender can draw, or a reasoned exception in `tests/fixtures/unreachable_by_design.json`), all with `--check` modes wired into the gate. A cosplay entry may render as a **person in a costume**, as a **mascot suit** (`covers_face` + `covers_body` + `mask`), or - since 0.95.0 - as the **beast itself** (`body_plan: "feral"`, which emits the Creature node's Species & Anatomy payload instead of a costume); see architecture.md -> "Animal characters split four ways". `scripts/render_gallery.py` renders a roster entry's gallery image by driving a running ComfyUI over HTTP and publishes it to `gh-pages`, and `gallery/render_manifest.json` + `--check` fail CI when an entry's text changes without a re-render (architecture.md -> "The gallery render pipeline"). Since 0.97.0 every roster entry also carries a **release stamp** (`data/versions.py`, written by `scripts/stamp_versions.py`, gated in CI), which is what lets the three sample gallery pages offer **A-Z / Newest first** and a **New in `<version>`** filter. Since 2.0.0: a **`gaze`** field drawn last with `pose` (both with live constraint rules; architecture.md -> "pose and gaze draw last"), opt-in **`costume_back`** for Turnaround back views, **per-garment `{slot}` variation** in the outfit corpus on its own seed stream, and a gallery hash over **resolved prose** so an engine change marks images stale. Since 2.3.0: the **Outfit Sheet** and **Age Progression** sheet nodes (they release the fields a pin refuses via `lock_clash` rather than override them; architecture.md -> "Sheets that change the person"), and picker previews served through a **server-side gallery cache** (`nodes/gallery_cache.py`) so they work under ComfyUI `--offline`. Since 2.6.0: the **Scene Sheet** node (one person in several places, dressed for each), `pin_framing()` for every sheet's framing pin, picker stars, a seeded random pick on Vault Load, example workflows for every sheet, and one `gallery/shared/` copy of the gallery page assets.
|
||||
- **In progress:** roster and coherence curation is the ongoing work, not a milestone - each release adds characters/creatures/archetypes and closes coherence bugs found by rendering them. `docs/suggested-additions.md` is the live backlog (under consideration / decided against / still to consider). Next: more `costume_back` entries (2.3.0 covered the first caped and back-emblem heroes; continue with the rest of the capes) and more slotted corpus phrases; both are seed-safe additions now (a slot draws from its own stream; a back text touches only back views).
|
||||
- **Recent releases** — one line each. **This list is a pointer, not a changelog:** the reasoning for every item is in `docs/history.md` (the sections are named there per release) and the full messages are in `git log`. Keep roughly the last eight and let older ones drop off; do not let an entry grow into a paragraph.
|
||||
- **2.6.0** - Audit fixes: framing pins release what they refuse (`pin_framing`), the Outfit Sheet busts the cache, user archetypes keep lists and variants and user cosplayers keep alternates, back views and `subject`, gallery cache offline back-off and raster-only, roll route ignores non-text values, case-only vault rename, shared gallery page assets, ruff pinned, example workflows and node contracts tested. Adds the Scene Sheet node, picker stars, a random saved character on Vault Load, and Turnaround / Expression / Scene Sheet example workflows. Random characters unchanged. See docs/history.md -> "2.6.0".
|
||||
- **2.5.0** - Picker search: word-start, accent-insensitive matching with quoted phrases and a one-way `SEARCH_ALSO` synonym/compound list, every description field indexed (eyes, alternate costumes, back view, anatomy), a type-to-filter franchise box, cosplayer-only filters hidden on Archetype/Creature, reopening on the current pick, and a Queue each button for a filtered set. Frontend and roster index only; random characters unchanged. See docs/history.md -> "2.5.0".
|
||||
- **2.4.0** - Figure Skater on the ice with standing poses (Hockey Goalie, Roller Derby, Carhop, Scuba Diver and Samurai pose locks too), several archetypes moved to a location that fits them, four new venues (wrestling ring, tennis court, pit lane, racecourse paddock), no leaning or perching in open landscapes, no blank-backdrop composition indoors, Indie Sleaze men's costumes split from the women's, a man keeps a locked eyeliner, 1980s New Wave women draw 80s makeup, a prop in each hand drops one-handed poses, and Yoda, Ahsoka, Piccolo, Bane and the Star Wars guards no longer draw a random human under the costume. Anthropomorphic creatures render as one clothed hybrid (Monsters/Aliens lead "humanoid X", an optional per-creature `anthro` text block, and the optional Krea2T Enhancer in the gallery renderer). Random characters move (marginals re-baselined). See docs/history.md -> "2.4.0".
|
||||
- **2.3.0** - Picker previews through a server-side cache (they now show under `--offline`, with a Clear cached previews button), Outfit Sheet and Age Progression nodes (shared `replay_base` / `release_fields` helpers in the Turnaround module), an Aztec Noble archetype, and `costume_back` for caped and back-emblem heroes. Random characters unchanged (the Archetype node's Random pick moves, as with any archetype addition). See docs/history.md -> "2.3.0".
|
||||
- **2.2.0** - Cyberpunk roster (David Martinez, Panam and Rebecca rebuilt to canon; new Maine, Kiwi, Talia Yang, Adam Smasher, Song So Mi with a weighted netrunner alternate), Volcana, four period court archetypes (Rococo Courtier, Medieval Monarch, Ottoman Court, Heian Court) and a Female variant for Ancient Roman Patrician, a `tattoos` lock kept in Essentials, a costume-named earring or necklace suppressing the random one, a `gilded palace throne room` location, tattoo and piercing locks on eleven period archetypes, a franchise filter in the roster picker, and four punk/pinup outfit-corpus phrases (the location and the outfits move random seeds). See docs/history.md -> "2.2.0".
|
||||
@@ -21,7 +23,6 @@ _Last verified: 2026-11-01_
|
||||
- **2.0.0** - Seed epoch: a `gaze` field (the old `looking` poses) drawn last with a deferred `pose` (`_repair_pose` retired), women's hair-length and 75/80 age weights, a portrait rig gated out of everyday interiors (`studio_shape` / `studio_mood` split), per-garment `{slot}` variation, opt-in `costume_back` for Turnaround back views, no "Name (Name)" label, an article for noun expressions, and a prose-based gallery hash (existing tiles accepted with `--rehash`, no full re-render). See docs/history.md -> "2.0.0".
|
||||
- **1.11.0** - Roster release: new cosplayers (incl. Birdie, Vecna on the mascot route), retro archetypes (Carhop at a new drive-in location, Zoot Suit men's only), four creatures, a `_GALLERY_SHOT` framing pin, Lola Bunny's paws, Tellarite's canon text (snout still unrendered). Random characters move only through the new location (about 5% of seeds, those drawing an urban outdoor place). Corinthian, Feyd-Rautha, barreleye, vampire squid and the pachuca variant declined on the render bar. See docs/history.md -> "1.11.0".
|
||||
- **1.10.0** - Expression Sheet node, free-text `held_item` on the Modifier, legwear dropped from prose in leg-cropping shots, "a coat of fur" no longer read as a pocketed garment, an overload drift test, and a gallery gate that fails on rendered-but-unpublished images (`--publish-pending`). Random characters unchanged; Bartok (now feral), Lola Bunny and Tasmanian Devil repaired and re-rendered (Tellarite deferred to 1.11.0). See docs/history.md -> "1.10.0".
|
||||
- **1.8.0** — Picker trait facets read structured `traits` (Poison Ivy is no longer "Tiny"); ethnicity and skin tone lock only in Full character / Full preset; a seventh `subject_text` output (person and outfit, no scene); colour and pattern modifiers reach a generated outfit; widgets_values saved in schema order for headless tools; `--unreachable` gate; publish depends on CI with a Windows leg; new cosplayers (incl. The Invisibles), three archetypes and a stegosaurus; the duplicate Julia Carpenter entry folded into one. See docs/history.md → "1.8.0".
|
||||
- **Known gaps / next steps:** two deliberate, open items — not to be re-litigated without a fresh case (the old pockets-allowlist gap was measured and closed in 1.10.0): (1) the Turnaround node's back view still draws a costume's front-facing detail (e.g. a chest emblem) on the back for any entry without a `costume_back` (opt-in since 2.0.0, so far only a handful of flagship heroes); never parse the front text for back clauses (the regex-over-prose trap), add `costume_back` to the entry instead. (2) Costume text that asserts a body trait against an unpinned random field (e.g. "on a hulking frame" beside a random, unlocked `build`) — the `signature`/`physique` split that causes it is deliberate; measure again from scratch before touching it, a naive regex sweep has reported a wrong count here before. `docs/suggested-additions.md` is the live backlog for roster/field-option candidates.
|
||||
- **Deep docs:** `docs/architecture.md` (deep reference — read before engine or data changes), `docs/history.md` (per-release investigation notes, 1.5.0+), `docs/usage.md`, `docs/cosplayer-notes.md`, `docs/creature-notes.md`, `docs/suggested-additions.md` (backlog), `docs/reference/*.md` (generated).
|
||||
|
||||
@@ -64,6 +65,10 @@ python -m unittest discover -s tests -t . -v
|
||||
# NOT the maintainer's denylist checker, which lives outside this repo.
|
||||
python scripts/check_public_safety.py
|
||||
|
||||
# Lint. pyproject.toml pins ruff to the CI version (required-version); another
|
||||
# local ruff refuses to run, so call the pinned one:
|
||||
uvx ruff@0.15.11 check .
|
||||
|
||||
# Frontend jsdom suite (separate toolchain: npm ci once, then this)
|
||||
npm run test:frontend
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ The Cosplayer node is where Identity Forge really shines. Most character wildcar
|
||||
|
||||
Ask a plain wildcard for Chun-Li and your prompt says `Chun-Li`. Ask this Cosplayer node and you get: *the blue qipao with gold trim, brown tights, white cross-laced boots, and spiked bracelets.* The look renders even on checkpoints that have never heard of the character.
|
||||
|
||||
**Find one fast:** open the in-node picker to browse and search the whole roster without leaving the node — trait facets (Giant, Masked, Mascot/full-suit, Beast), Female/Male and franchise filters, and optional thumbnail previews (fetched once by your ComfyUI server and cached on disk, so they still show when ComfyUI runs with `--offline`). The picker remembers your search, tab and facet while the workflow is open, so you can pick, close and come back to the same filtered view; reloading starts fresh.
|
||||
**Find one fast:** open the in-node picker to browse and search the whole roster without leaving the node - trait facets (Giant, Masked, Mascot/full-suit, Beast), Female/Male and a type-to-filter franchise box, a **Queue each** button that runs every match in turn, starred favourites, and optional thumbnail previews (fetched once by your ComfyUI server and cached on disk, so they still show when ComfyUI runs with `--offline`). The picker remembers your search, tab and facet while the workflow is open, so you can pick, close and come back to the same filtered view, scrolled to your current pick; reloading starts fresh. Search rules are in [docs/usage.md](docs/usage.md#searching-the-picker).
|
||||
|
||||
**Characters from every major franchise:** Marvel, DC, Star Wars, anime, video games, fantasy, sci-fi, horror. Each one with multiple costume variants where applicable (Harley Quinn's three iconic looks, Catwoman's different suits, etc.). Characters rotate between variants by seed, so the same name yields a different signature costume each roll.
|
||||
|
||||
@@ -46,12 +46,13 @@ The **Expression Sheet** node is its face-side sibling: the same resolved charac
|
||||
expression (neutral, smile, laughing, surprised, serious, sad, and more), with only the expression,
|
||||
mood and smile changing. See [docs/usage.md](docs/usage.md#expression-sheets).
|
||||
|
||||
Two more sheets work the same way. The **Outfit Sheet** keeps the person and redresses them once per
|
||||
outfit style (casual, business formal, evening formal and so on) on a plain studio backdrop, and the
|
||||
**Age Progression** node shows the same person at several ages, greying natural hair as they age.
|
||||
See [docs/usage.md](docs/usage.md#outfit-sheets) and [docs/usage.md](docs/usage.md#age-progression).
|
||||
Ready-made workflows for both are in [example_workflows/](example_workflows/) and in ComfyUI's
|
||||
template browser under Identity Forge.
|
||||
Three more sheets work the same way. The **Outfit Sheet** keeps the person and redresses them once per
|
||||
outfit style (casual, business formal, evening formal and so on) on a plain studio backdrop, the
|
||||
**Scene Sheet** shows them in several places (park, coffee shop, office, beach...), dressed for each,
|
||||
and the **Age Progression** node shows the same person at several ages, greying natural hair as they age.
|
||||
See [docs/usage.md](docs/usage.md#outfit-sheets), [docs/usage.md](docs/usage.md#scene-sheets) and
|
||||
[docs/usage.md](docs/usage.md#age-progression). Ready-made workflows are in
|
||||
[example_workflows/](example_workflows/) and in ComfyUI's template browser under Identity Forge.
|
||||
|
||||
### Additional layers
|
||||
|
||||
@@ -143,10 +144,11 @@ randomized identities, so your own results will vary:
|
||||
| **Cosplayer** | Fictional characters (Spider-Man, 2B, She-Hulk, Zelda…) as a *cosplay look* — the costume on a random, optionally cross-gender person. An in-node picker browses and searches the whole roster with trait facets and thumbnails. |
|
||||
| **Creature** | Render the character as a non-human form (animal, insect, marine, reptile, bird, monster, alien, mythic, plant), across all classes or one, hybridized slot-by-slot. Generic species only — a *named* fictional beast (Appa, Toothless) is a Cosplayer entry. Also has the in-node roster picker. |
|
||||
| **Modifier** | Prepend a custom descriptor to one field (`footwear: sci-fi`) or a whole group (`Clothing: weathered`). An optional `held_item` box sets a free-text prop ("a red paper umbrella"). |
|
||||
| **Vault Save / Load** | Save a generated character (with a thumbnail) to a local vault; recall it later as a chainable preset, with a Manage Vault gallery. |
|
||||
| **Vault Save / Load** | Save a generated character (with a thumbnail) to a local vault; recall it later as a chainable preset (or a seeded random pick of your saves), with a Manage Vault gallery. |
|
||||
| **Turnaround** | A reference-sheet builder: wire Identity Forge's `prompt_json` in and it emits front / three-quarter / profile / back as a **list**, so one queue renders the whole set of the same person. It only moves the camera - the character and the scene stay configured on Identity Forge. |
|
||||
| **Expression Sheet** | The same idea for the face: wire `prompt_json` in and it emits one prompt per expression (Basic 6, Full 10 or Smiles 3) as a **list**. Only expression, mood and smile change (plus the gaze, if you pick one to hold). |
|
||||
| **Outfit Sheet** | Wire `prompt_json` in and it emits one prompt per outfit style (Range 6, Everyday 4, Work to evening 4 or Every style) as a **list**: the same person redressed, on a studio backdrop or in their own scene; `outfit_seed` re-rolls every outfit for the same person. Makeup, jewellery and hair styling follow the outfit; face and body stay. A cosplay or full-suit character gives a single view. |
|
||||
| **Scene Sheet** | Wire `prompt_json` in and it emits the same person in several places (Everyday 6, Indoors 4, Outdoors 4 or Studio backdrops 3) as a **list**, with light and season redrawn for each place. By default each place picks a fitting outfit; "Keep the outfit" keeps the clothes and skips places they do not suit. A cosplay character keeps the costume. |
|
||||
| **Age Progression** | Wire `prompt_json` in and it emits the same person at several ages (Life stages 4, Decades 6 or Young and old 2) as a **list**. Natural hair greys with age; dyed, vivid and costume hair stay as they are. A masked character gives a single view. |
|
||||
|
||||
---
|
||||
|
||||
+7
-4
@@ -1,6 +1,6 @@
|
||||
"""comfyui-identity-forge — V3 custom node pack entrypoint.
|
||||
|
||||
Exposes eleven nodes:
|
||||
Exposes twelve nodes:
|
||||
|
||||
* ``IdentityForge`` — a multi-field character description randomizer with a
|
||||
constraint engine and dual prose/JSON output.
|
||||
@@ -19,6 +19,8 @@ Exposes eleven nodes:
|
||||
character, several outfit styles, as a list.
|
||||
* ``IdentityForgeAgeProgression`` - one resolved character at several ages, as a
|
||||
list.
|
||||
* ``IdentityForgeSceneSheet`` - one resolved character in several places, as a
|
||||
list.
|
||||
* ``IdentityForgeVaultSave`` — save a generated character to a local vault.
|
||||
* ``IdentityForgeVaultLoad`` — recall a saved character as a chainable preset.
|
||||
|
||||
@@ -49,6 +51,7 @@ try:
|
||||
from .nodes.identity_forge_expression_sheet import IdentityForgeExpressionSheet
|
||||
from .nodes.identity_forge_outfit_sheet import IdentityForgeOutfitSheet
|
||||
from .nodes.identity_forge_age_progression import IdentityForgeAgeProgression
|
||||
from .nodes.identity_forge_scene_sheet import IdentityForgeSceneSheet
|
||||
from .nodes.identity_forge_vault_save import IdentityForgeVaultSave
|
||||
from .nodes.identity_forge_vault_load import IdentityForgeVaultLoad
|
||||
except ImportError: # pragma: no cover
|
||||
@@ -61,6 +64,7 @@ except ImportError: # pragma: no cover
|
||||
from nodes.identity_forge_expression_sheet import IdentityForgeExpressionSheet
|
||||
from nodes.identity_forge_outfit_sheet import IdentityForgeOutfitSheet
|
||||
from nodes.identity_forge_age_progression import IdentityForgeAgeProgression
|
||||
from nodes.identity_forge_scene_sheet import IdentityForgeSceneSheet
|
||||
from nodes.identity_forge_vault_save import IdentityForgeVaultSave
|
||||
from nodes.identity_forge_vault_load import IdentityForgeVaultLoad
|
||||
|
||||
@@ -205,8 +209,7 @@ def _register_roll_route() -> None:
|
||||
if error is not None:
|
||||
return error
|
||||
widgets, seed = body.get("widgets"), body.get("seed")
|
||||
if (not isinstance(widgets, dict) or not isinstance(seed, int)
|
||||
or not all(isinstance(v, (str, int, float)) for v in widgets.values())):
|
||||
if not isinstance(widgets, dict) or not isinstance(seed, int) or isinstance(seed, bool):
|
||||
return web.json_response(
|
||||
{"error": "expected {'widgets': {name: value}, 'seed': int}"}, status=400)
|
||||
return web.json_response({"values": roll_field_values(widgets, seed)})
|
||||
@@ -282,7 +285,7 @@ class IdentityForgeExtension(ComfyExtension):
|
||||
return [IdentityForge, IdentityForgeArchetype, IdentityForgeCosplayer,
|
||||
IdentityForgeCreature, IdentityForgeModifier, IdentityForgeTurnaround,
|
||||
IdentityForgeExpressionSheet, IdentityForgeOutfitSheet,
|
||||
IdentityForgeAgeProgression,
|
||||
IdentityForgeAgeProgression, IdentityForgeSceneSheet,
|
||||
IdentityForgeVaultSave, IdentityForgeVaultLoad]
|
||||
|
||||
|
||||
|
||||
+85
-12
@@ -67,8 +67,8 @@ Reload the node / restart ComfyUI to apply. Notes:
|
||||
* For the three gender-specific fields (``bust``, ``facial_hair``,
|
||||
``makeup_style``) custom options may not survive a live gender switch in the UI.
|
||||
* ``archetypes`` adds presets to the Archetype node (same ``{field: value}``
|
||||
shape as the built-ins; ``outfit_description`` may use ``{slot}`` costume
|
||||
placeholders). ``cosplayers`` adds characters to the Cosplayer node (keys:
|
||||
shape as the built-ins, list values and a ``variants`` block included;
|
||||
``outfit_description`` may use ``{slot}`` costume placeholders). ``cosplayers`` adds characters to the Cosplayer node (keys:
|
||||
``franchise``, ``gender`` Female/Male, ``costume`` text, optional ``prop`` (a
|
||||
signature held item, voiced as "holding …" when the node's prop toggle is on),
|
||||
optional ``signature`` / ``physique`` ``{field: value}`` maps). A user entry whose name matches a
|
||||
@@ -98,9 +98,14 @@ The file is parsed as plain JSON — no code is executed.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
#: 2.6.0: messages go to the logger like the rest of the pack (ComfyUI owns the
|
||||
#: handlers); the logger name replaces the old '[IdentityForge]' prefix.
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
#: Default location of the user file: the pack root, next to __init__.py.
|
||||
USER_OPTIONS_PATH = Path(__file__).resolve().parents[1] / "user_options.json"
|
||||
|
||||
@@ -214,7 +219,7 @@ def apply_user_options(
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (ValueError, OSError) as exc: # malformed JSON or unreadable
|
||||
print(f"[IdentityForge] Ignoring {path.name}: {exc}")
|
||||
_LOG.warning(f"Ignoring {path.name}: {exc}")
|
||||
return 0
|
||||
if not isinstance(data, dict):
|
||||
return 0
|
||||
@@ -229,7 +234,7 @@ def apply_user_options(
|
||||
added += _apply_outfits(outfits, field_definitions, outfit_descriptions)
|
||||
|
||||
if added:
|
||||
print(f"[IdentityForge] Loaded {added} custom option(s) from {path.name}.")
|
||||
_LOG.info(f"Loaded {added} custom option(s) from {path.name}.")
|
||||
return added
|
||||
|
||||
|
||||
@@ -244,7 +249,7 @@ def _load_user_section(path: Path, section: str) -> dict[str, Any]:
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (ValueError, OSError) as exc:
|
||||
print(f"[IdentityForge] Ignoring {path.name}: {exc}")
|
||||
_LOG.warning(f"Ignoring {path.name}: {exc}")
|
||||
return {}
|
||||
block = data.get(section) if isinstance(data, dict) else None
|
||||
return block if isinstance(block, dict) else {}
|
||||
@@ -257,6 +262,24 @@ def _clean_field_map(value: Any) -> dict[str, str]:
|
||||
return {f: v for f, v in value.items() if isinstance(f, str) and isinstance(v, str) and v}
|
||||
|
||||
|
||||
def _clean_preset(value: Any) -> dict[str, Any]:
|
||||
"""An archetype field map: ``{field: text}`` or ``{field: [text, ...]}`` (2.6.0).
|
||||
|
||||
A list is a seed-picked choice, as in the built-ins; non-text entries are dropped.
|
||||
"""
|
||||
if not isinstance(value, dict):
|
||||
return {}
|
||||
out: dict[str, Any] = {}
|
||||
for field, v in value.items():
|
||||
if not isinstance(field, str):
|
||||
continue
|
||||
if isinstance(v, str) and v:
|
||||
out[field] = v
|
||||
elif isinstance(v, list) and (items := [x for x in v if isinstance(x, str) and x]):
|
||||
out[field] = items
|
||||
return out
|
||||
|
||||
|
||||
def apply_user_archetypes(archetypes: dict[str, dict], path: Path | None = None) -> int:
|
||||
"""Merge the ``archetypes`` section of ``user_options.json`` in place.
|
||||
|
||||
@@ -269,15 +292,24 @@ def apply_user_archetypes(archetypes: dict[str, dict], path: Path | None = None)
|
||||
path = path or USER_OPTIONS_PATH
|
||||
added = 0
|
||||
for name, preset in _load_user_section(path, "archetypes").items():
|
||||
if not isinstance(name, str) or not name:
|
||||
if not isinstance(name, str) or not name or not isinstance(preset, dict):
|
||||
continue
|
||||
cleaned = _clean_field_map(preset)
|
||||
cleaned: dict[str, Any] = _clean_preset(preset)
|
||||
variants = preset.get("variants")
|
||||
if isinstance(variants, dict):
|
||||
kept = {g: v for g in ("Female", "Male") if (v := _clean_preset(variants.get(g)))}
|
||||
if kept:
|
||||
cleaned["variants"] = kept
|
||||
if not cleaned:
|
||||
continue
|
||||
dropped = sorted(set(preset) - set(cleaned))
|
||||
if dropped:
|
||||
_LOG.warning("Archetype %r: ignored %s (values must be text, a list of text, "
|
||||
"or a variants block).", name, ", ".join(dropped))
|
||||
archetypes[name] = cleaned
|
||||
added += 1
|
||||
if added:
|
||||
print(f"[IdentityForge] Loaded {added} custom archetype(s) from {path.name}.")
|
||||
_LOG.info(f"Loaded {added} custom archetype(s) from {path.name}.")
|
||||
return added
|
||||
|
||||
|
||||
@@ -320,13 +352,34 @@ def apply_user_creatures(creatures: dict[str, dict], path: Path | None = None) -
|
||||
creatures[name] = record
|
||||
added += 1
|
||||
continue
|
||||
print(f"[IdentityForge] Skipping creature {name!r}: needs class, palette, "
|
||||
_LOG.warning(f"Skipping creature {name!r}: needs class, palette, "
|
||||
f"head, eyes and integument.")
|
||||
if added:
|
||||
print(f"[IdentityForge] Loaded {added} custom creature(s) from {path.name}.")
|
||||
_LOG.info(f"Loaded {added} custom creature(s) from {path.name}.")
|
||||
return added
|
||||
|
||||
|
||||
def _clean_looks(value: Any) -> list[Any]:
|
||||
"""Alternate looks (2.6.0): plain costume strings, or overlay dicts with a costume.
|
||||
|
||||
An overlay may also set the per-look keys the built-ins use (``mask``,
|
||||
``signature``, ``covers_face`` and so on); ``tests/validate_data.py`` reports a
|
||||
key the node does not read.
|
||||
"""
|
||||
if not isinstance(value, list):
|
||||
return []
|
||||
looks: list[Any] = []
|
||||
for look in value:
|
||||
if isinstance(look, str) and look:
|
||||
looks.append(look)
|
||||
elif isinstance(look, dict) and isinstance(look.get("costume"), str) and look["costume"]:
|
||||
overlay = {k: v for k, v in look.items() if isinstance(k, str)}
|
||||
if "signature" in overlay:
|
||||
overlay["signature"] = _clean_field_map(overlay["signature"])
|
||||
looks.append(overlay)
|
||||
return looks
|
||||
|
||||
|
||||
def apply_user_cosplayers(cosplayers: dict[str, dict], path: Path | None = None) -> int:
|
||||
"""Merge the ``cosplayers`` section of ``user_options.json`` in place.
|
||||
|
||||
@@ -366,10 +419,30 @@ def apply_user_cosplayers(cosplayers: dict[str, dict], path: Path | None = None)
|
||||
# Optional free-text keys follow the built-in schema: OMITTED when unused,
|
||||
# never stored as "" (validate_data treats an empty string as an error and
|
||||
# a present-but-empty 'mask' as a mask/covers_face mismatch).
|
||||
for optional_key in ("mask", "prop", "eyes", "skin"):
|
||||
for optional_key in ("mask", "prop", "eyes", "skin", "costume_back"):
|
||||
value = entry.get(optional_key)
|
||||
if isinstance(value, str) and value:
|
||||
record[optional_key] = value
|
||||
# 2.6.0: the lead noun for a non-human head, voiced "a short <subject>", so an
|
||||
# article or trailing full stop the user typed would be doubled; drop them.
|
||||
subject = entry.get("subject")
|
||||
if isinstance(subject, str):
|
||||
words = subject.strip().rstrip(".,").split()
|
||||
if words and words[0].lower() in ("a", "an", "the"):
|
||||
words = words[1:]
|
||||
if words:
|
||||
record["subject"] = " ".join(words)
|
||||
looks = _clean_looks(entry.get("costumes"))
|
||||
if looks:
|
||||
record["costumes"] = looks
|
||||
weights = entry.get("costume_weights")
|
||||
if (isinstance(weights, list) and len(weights) == 1 + len(looks)
|
||||
and all(isinstance(w, (int, float)) and not isinstance(w, bool)
|
||||
and w > 0 for w in weights)):
|
||||
record["costume_weights"] = weights
|
||||
elif weights is not None:
|
||||
_LOG.warning("Cosplayer %r: ignored costume_weights (needs one positive "
|
||||
"number per look: the costume, then each alternate).", name)
|
||||
# Advanced bool flags, likewise omitted unless explicitly true so user
|
||||
# records mirror the built-in shape (built-ins never carry a False flag).
|
||||
for flag in ("covers_body", "covers_hair", "bald", "body_paint"):
|
||||
@@ -378,5 +451,5 @@ def apply_user_cosplayers(cosplayers: dict[str, dict], path: Path | None = None)
|
||||
cosplayers[name] = record
|
||||
added += 1
|
||||
if added:
|
||||
print(f"[IdentityForge] Loaded {added} custom cosplayer(s) from {path.name}.")
|
||||
_LOG.info(f"Loaded {added} custom cosplayer(s) from {path.name}.")
|
||||
return added
|
||||
|
||||
+26
-3
@@ -90,6 +90,9 @@ sample render per roster entry to GitHub Pages. Full detail in
|
||||
`tests/test_gallery.py::CopiesStayInSyncTests` fails until it is. `BatchLauncherTests`
|
||||
guards the `.bat` launchers (every exit pauses, no parenthesised `if` blocks, ASCII
|
||||
only, CRLF via `.gitattributes`).
|
||||
- **The page assets are not copies (2.6.0).** `style.css` and `gallery.js` live once in
|
||||
`gallery/shared/`; each page links `../shared/` and every `publish.py` stages that folder
|
||||
to `gh-pages`. Details in gallery/README.md -> "Editing the page files".
|
||||
- Adding a fourth gallery is a folder copy plus one config block per file; the checklist
|
||||
is at the bottom of `gallery/README.md`.
|
||||
|
||||
@@ -322,6 +325,21 @@ fixed replay seed.
|
||||
than the character turns dark hair salt and pepper (silver from 70), any other colour silver;
|
||||
a grey-haired character shown younger gets a natural colour drawn once at age 20 with hair
|
||||
colour released. A face-covering character, or one with no numeric age, gives one view.
|
||||
- **Every framing pin goes through `pin_framing()` (2.6.0).** It sets `shot_type` and
|
||||
releases what that framing refuses (a standing pose in a close-up), with a per-character
|
||||
`character_seed(..., "framing")`. Before 2.6.0 the Expression Sheet pinned a close-up and
|
||||
released nothing, and the one-view paths of Age Progression and the Outfit Sheet returned
|
||||
before their release step, so a masked or suited character kept a pose its framing
|
||||
excludes. `tests/test_sheet_framing.py` holds all three paths.
|
||||
- **Scene Sheet (2.6.0):** pins `location` per view and releases the scene drawn against the
|
||||
old place (`location_setting`, lighting, composition, season). By default it also releases
|
||||
the Clothing group so each place dresses the person again; "Keep the outfit" keeps it and
|
||||
skips any place that refuses it. A place that refuses pose, gaze, framing or the
|
||||
`_RESTYLED` styling redraws that field for the view (`_RESTAGED`); refusing anything else
|
||||
(age, body, a held item, a pinned framing) skips the place. A cosplay or a full-body suit
|
||||
never has its clothing released. The view seed is `character_seed(doc, "scene|<place>")`.
|
||||
Measured over 60 characters per sheet: dress mode kept every place with no clash; keep
|
||||
mode skipped about 30% of everyday places, mostly the beach and the trail.
|
||||
|
||||
### Vault recall and the control sentinels (1.0.0)
|
||||
|
||||
@@ -358,9 +376,14 @@ each of these. The Turnaround shipped its first draft missing the last two.
|
||||
4. `fingerprint_inputs` returning NaN **if** any widget sets `control_after_generate` —
|
||||
see "Seeded nodes re-roll every queue" below. The trigger is the auto-advancing
|
||||
widget, not the presence of a seed.
|
||||
5. A tooltip on **every** input. There is no lint for this; the frontend fixture records
|
||||
widget names and defaults, not help text, so only `tests/test_*.py` can hold the line
|
||||
(`test_every_widget_carries_a_tooltip`).
|
||||
5. A tooltip on **every** input and output. There is no lint for this; the frontend fixture
|
||||
records widget names and defaults, not help text. Since 2.6.0
|
||||
`tests/test_node_contracts.py` walks every class in `nodes/` and checks both tooltips and
|
||||
item 4, so a new node is covered without being listed (the Outfit Sheet had shipped with
|
||||
an auto-advancing `outfit_seed` and no cache buster).
|
||||
6. An example workflow, if the node is meant to be wired by hand: build it in a real
|
||||
frontend, then `tests/test_example_workflows.py` checks every pack node's
|
||||
`widgets_values` count and combo values against the fixture.
|
||||
|
||||
## fields.py — the field engine
|
||||
|
||||
|
||||
@@ -1702,3 +1702,67 @@ hall: the Giza plateau adds clashes with its locked spotlight and evening-formal
|
||||
|
||||
Random characters move through the open-landscape pose rule, the indoor composition rule and
|
||||
the new venues; the marginals baseline was rewritten for those three.
|
||||
|
||||
## 2.5.0 - picker search
|
||||
|
||||
**Substring search was noisy.** "bow" matched every "elbow-length" glove and "rainbow", "hat"
|
||||
matched "that", "red" matched "layered". Tokens now match from a word's start (a name still
|
||||
matches anywhere). Measured on the roster: "bow" 167 to 111 entries, "hat" 224 to 149, "red"
|
||||
1378 to 770. Word-start alone lost real compounds ("suit" missed 235 "bodysuit" entries,
|
||||
"sword" missed longswords), so `SEARCH_ALSO` lists the compounds the roster actually uses, plus
|
||||
a few synonyms (pants/trousers, gray/grey). One-way on purpose, so a specific word stays
|
||||
specific. A matcher on word endings was rejected: it brought "necklace" for "lace", "earring"
|
||||
for "ring" and "ponytail" for "tail".
|
||||
|
||||
**Accents fold** on both sides (Unicode NFD, plus a few letters NFD keeps, such as ø and ß), so a plain US keyboard finds Día de los Muertos.
|
||||
|
||||
**Description text that was not searched:** `eyes`, the alternate looks in `costumes`,
|
||||
`subject`, `skin`, `costume_back`, `prop_costume` and `anatomy` now go into the roster index.
|
||||
|
||||
**The franchise dropdown** was a native select of hundreds of names that only jumped by first
|
||||
letter. It is a type-to-filter box with the franchises as suggestions. It and the trait facet
|
||||
only match cosplayers, so the Archetype and Creature pickers no longer show them (nor gender on
|
||||
Creature, whose entries have none).
|
||||
|
||||
**Lost place after a pick.** Reopening rebuilt the grid at the top. It now scrolls to, and
|
||||
outlines, the entry the node holds.
|
||||
|
||||
**Queue each** queues one run per matching entry through `app.queuePrompt`, setting the widget
|
||||
before each call and restoring the pick after. It shows only while filtering, so the whole
|
||||
roster cannot be queued by accident, and asks for confirmation with the count.
|
||||
|
||||
Frontend only plus the generated roster index: no schema, data or seed change.
|
||||
|
||||
## 2.6.0 - audit fixes, Scene Sheet, picker stars, random vault pick
|
||||
|
||||
**Framing pins replayed clashes.** The Expression Sheet pinned a close-up and kept the
|
||||
character's own pose ("standing with arms crossed" in a head-and-shoulders view), and the
|
||||
one-view paths of Age Progression and the Outfit Sheet returned before releasing anything.
|
||||
Measured before the fix: 314 of 400 expression views and 200 of 300 one-view replays voiced a
|
||||
value the framing refuses. `pin_framing()` now does it for every sheet; 0 after.
|
||||
|
||||
**The Outfit Sheet never busted the cache.** Its `outfit_seed` auto-advances, which is the
|
||||
ComfyUI#11905 case, but it had no `fingerprint_inputs`. Fixed, and
|
||||
`tests/test_node_contracts.py` now walks every node class for this and for tooltips on every
|
||||
input and output (the main node and the preset outputs had none).
|
||||
|
||||
**User presets lost data.** A user archetype dropped list values and `variants`; a user
|
||||
cosplayer dropped `costumes`, `costume_weights`, `costume_back` and `subject`. All are kept
|
||||
now (weights only when they fit the look count), and anything ignored is logged by key
|
||||
instead of vanishing. `data/user_options.py` logs instead of printing.
|
||||
|
||||
**Smaller fixes.** The gallery cache retried the network on every request once offline with
|
||||
a stale copy (it now backs off by touching the copy) and accepted any `image/*` (now raster
|
||||
only, so no SVG). The roll route returned a 500 on a numeric widget value. A case-only vault
|
||||
rename was a no-op on Windows, and the 120-character name cut could leave a trailing dot. The
|
||||
three galleries' `style.css` and `gallery.js` copies are one set in `gallery/shared/`. Ruff is
|
||||
pinned in `pyproject.toml` to the CI version, and the example workflows are checked against
|
||||
the node schemas.
|
||||
|
||||
**Additions.** The Scene Sheet node (one person in several places, dressed for each by
|
||||
default; see architecture.md -> "Sheets that change the person"), starred favourites in the
|
||||
picker, a seeded `(random saved character)` on Vault Load, and example workflows for the
|
||||
Turnaround, Expression Sheet and Scene Sheet (derived from the Outfit Sheet one and
|
||||
re-serialized by a real frontend).
|
||||
|
||||
Random characters unchanged: no data or engine draw changed.
|
||||
|
||||
@@ -29,7 +29,14 @@ Nothing is open; the last row (the Tellarite snout) closed in 2.1.0 with the `su
|
||||
tight-shot legwear, free-text `held_item` and expression-sheet rows in 1.10.0, see
|
||||
`docs/history.md`):
|
||||
|
||||
Empty: the gaze field and the noun-expression article both shipped in 2.0.0.
|
||||
The gaze field and the noun-expression article both shipped in 2.0.0. Open, from the 2.5.0
|
||||
picker-search review (maintainer is considering them):
|
||||
|
||||
- **Random from these** - a picker button that queues one run with a random pick from the
|
||||
filtered set, a lighter option than Queue each.
|
||||
- **Plural search** - "boots" does not find a costume that says "boot" (word-start matching
|
||||
already covers the reverse). Rare in practice; a naive trailing-s strip turns "glasses" into
|
||||
"glass".
|
||||
|
||||
**Researched and skipped — do not re-survey.** Valorant, Apex Legends,
|
||||
Monster Hunter, Skyrim, Splatoon, FNAF, Among Us, Minecraft, Mortal Shell. Each is an armoured,
|
||||
@@ -77,6 +84,8 @@ Closed with a reason. Reopen only with a **new** argument, not a repeat of the r
|
||||
|---|---|
|
||||
| A negative and/or tags output | Maintainer: not needed. (The subject/scene half of the same row shipped at 1.8.0 as `subject_text`.) |
|
||||
| An on-node readout of the resolved prompt | Maintainer: not needed. |
|
||||
| Saved picker searches (a remembered list of frequent filters) (2.5.0) | Maintainer: not wanted. |
|
||||
| Hair-colour and era filters in the picker (2.5.0) | Maintainer: not wanted; word search covers them. |
|
||||
| A pair / group node (two or more resolved characters in one prompt) (2.3.0 plan) | Maintainer: deferred, not refused. Most current t2i models blend or swap traits between two described people in one prompt, so the output would not match the characters. Reopen if models hold separate subjects reliably. |
|
||||
|
||||
### Individual characters
|
||||
|
||||
+61
-2
@@ -106,7 +106,9 @@ optional sections:
|
||||
Buckets are `unisex`
|
||||
(always eligible) plus `female` / `male`, chosen by the `wardrobe` control; any subset works.
|
||||
- **`archetypes`** adds presets to the Archetype node (same `{field: value}` shape as the
|
||||
built-ins; `outfit_description` may use `{slot}` placeholders).
|
||||
built-ins; `outfit_description` may use `{slot}` placeholders). A value may be a list, one
|
||||
picked per seed (`"hair_color": ["copper", "auburn"]`), and a `"variants"` object holds
|
||||
separate `"Female"` / `"Male"` looks. Anything else is skipped with a warning in the log.
|
||||
- **`cosplayers`** adds characters to the Cosplayer node. `costume` (worn items only) is required;
|
||||
`franchise`/`gender` are optional; `signature` (both modes) and `physique` (Full character) are
|
||||
`{field: value}` maps. An optional `"prop"` string adds a signature held item; an optional
|
||||
@@ -117,7 +119,12 @@ optional sections:
|
||||
bare skin, suppresses jewellery/nails), `"covers_hair": true` (hood/cowl hides the hair while
|
||||
the face shows), `"bald": true` (fully hairless head), `"body_paint": true` (the skin itself is
|
||||
the costume colour; add `"skin": "warm green"` to name the colour when it isn't obvious from
|
||||
the costume text). Word a full-body colour skin-native — `"smooth, flawless <colour> skin"` —
|
||||
the costume text). Four more keys match the built-ins: `"costumes"` (a list of alternate
|
||||
looks, each a costume string or an object with its own `"costume"` plus per-look keys such
|
||||
as `"mask"` or `"signature"`; one look is picked per seed), `"costume_weights"` (one
|
||||
positive number per look, the main costume first), `"costume_back"` (the costume seen from
|
||||
behind, used by the Turnaround's back views) and `"subject"` (a lead noun for a non-human
|
||||
head, such as `"pig-headed alien"`). Word a full-body colour skin-native - `"smooth, flawless <colour> skin"` -
|
||||
not as "body paint"/"dye", which t2i models render as a streaky coat over a human tone; the
|
||||
skin-native marker is auto-detected, so the flag is only needed for other phrasings. See the
|
||||
worked examples in
|
||||
@@ -208,6 +215,7 @@ their usual costume text in every view.
|
||||
Everything else belongs on the Identity Forge node - it owns the character and the scene,
|
||||
the Turnaround owns only the camera. For a clean reference sheet, set that node's
|
||||
`location_setting` to `Studio / solid backdrop` and lock `composition` to `centered symmetry`.
|
||||
A ready-made workflow is `example_workflows/Identity Forge - Turnaround.json`.
|
||||
|
||||
## Expression sheets
|
||||
|
||||
@@ -226,6 +234,7 @@ Image's `filename_prefix`), and it owns only the face's emotion: `expression`, `
|
||||
Each view sets a fixed, curated expression/mood/smile combination, so a sheet is
|
||||
deterministic and no two views land on the same face. A face-covering character (a mascot
|
||||
head, a full helmet) has no visible expression, so the sheet emits one view, `1-masked`.
|
||||
A ready-made workflow is `example_workflows/Identity Forge - Expression Sheet.json`.
|
||||
|
||||
## Outfit sheets
|
||||
|
||||
@@ -251,6 +260,25 @@ character or a full-body suit has its costume, so the sheet emits one view as re
|
||||
A ready-made workflow is `example_workflows/Identity Forge - Outfit Sheet.json` (also in
|
||||
ComfyUI's template browser).
|
||||
|
||||
## Scene sheets
|
||||
|
||||
The **Identity Forge Scene Sheet** node (2.6.0) is wired like the Turnaround and shows the same
|
||||
person in several places.
|
||||
|
||||
- **`sheet`** - `Everyday (6)` (city park, coffee shop, living room, office, beach, forest trail),
|
||||
`Indoors (4)`, `Outdoors (4)` or `Studio backdrops (3)`.
|
||||
- **`framing`** - `Cowboy (mid-thigh up)` by default, so the place shows around the person;
|
||||
`Unspecified` keeps the character's own framing.
|
||||
- **`clothes`** - `Dress for each place` (default) picks a new outfit that suits each place.
|
||||
`Keep the outfit` keeps the character's clothes and skips any place they do not suit, so that
|
||||
sheet can be shorter, or a single view as resolved if no place fits.
|
||||
|
||||
Lighting, composition and season are drawn again for each place. A pose, gaze, makeup,
|
||||
jewellery or hair styling a place refuses is redrawn for that view; anything else a place
|
||||
refuses (age, body, a held item) skips it. The face and body never change. A cosplay character
|
||||
or a full-body suit keeps the costume. Labels read `1-sunny-city-park` and so on. A ready-made
|
||||
workflow is `example_workflows/Identity Forge - Scene Sheet.json`.
|
||||
|
||||
## Age progression
|
||||
|
||||
The **Identity Forge Age Progression** node shows the same person at several ages.
|
||||
@@ -266,6 +294,37 @@ Dyed or vivid scopes, cosplay hair and covered hair are left alone. A face-cover
|
||||
emits one view as resolved. Labels read `1-age-20` and so on. A ready-made workflow is
|
||||
`example_workflows/Identity Forge - Age Progression.json`.
|
||||
|
||||
## Searching the picker
|
||||
|
||||
- **Words match from their start.** `bow` finds a bow tie or a bowler hat, not "elbow" or
|
||||
"rainbow". A name still matches anywhere (`man` finds Batman). Several words must all match,
|
||||
in any order; put a phrase in quotes (`"bow tie"`) to match it as written.
|
||||
- **Accents are optional.** `dia` and `día` both find Día de los Muertos; `pokemon` finds
|
||||
Pokémon. The same holds in the franchise box.
|
||||
- **Everything in an entry's description is searched:** name, franchise, costume, alternate
|
||||
costumes, back view, mask, prop, eyes, hair and body text.
|
||||
- **A few words also find their synonyms and compounds:** `pants` finds trousers, slacks and
|
||||
jeans, `suit` finds bodysuits and jumpsuits, `sword` finds katanas, `gray` finds grey. The
|
||||
list is `SEARCH_ALSO` in `js/identity_forge_picker.js`; it is one-way (`jeans` does not
|
||||
find slacks).
|
||||
- **Franchise box (Cosplayer node):** type part of a name. `star` keeps Star Wars and Star
|
||||
Trek; picking a suggestion, or typing a full name, keeps that franchise only. Trait, gender
|
||||
and franchise filters only appear on nodes where they can narrow something.
|
||||
- **Your place is kept.** Reopening the picker scrolls to the character the node holds (outlined),
|
||||
with the same search and filters, so you can pick, queue, and come back to the next one.
|
||||
- **Queue each (N)** appears while you are filtering: it queues one run per matching entry the
|
||||
node can take, then puts your original pick back. Each run uses the rest of the workflow as it
|
||||
stands, so a seed set to randomize gives each one a new person.
|
||||
- **Star your favourites (2.6.0).** Click the star on a card (or press S on the focused card),
|
||||
then tick **Starred only** to see just those. Stars are kept in this browser, shared by all
|
||||
three pickers, and work with every other filter and with Queue each.
|
||||
|
||||
## Recalling a random saved character
|
||||
|
||||
Vault Load's `character` list ends with `(random saved character)` once anything is saved
|
||||
(2.6.0). It picks one saved character by the node's `seed`: the same seed and vault give the
|
||||
same pick, and `randomize` gives a different one each queue.
|
||||
|
||||
## Preview images in the picker
|
||||
|
||||
"Show preview images" in the roster picker is off by default. When it is on, your ComfyUI
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+7
-6
@@ -74,12 +74,13 @@ is the right failure mode — it has no image on `gh-pages` either.
|
||||
|
||||
## Editing the page files
|
||||
|
||||
`gallery.js` and `style.css` are copies too, exactly like the four `.py` scripts. `style.css` is
|
||||
byte-identical across all three and `gallery.js` differs **only** in its header banner;
|
||||
`PageAssetsStayInSyncTests` in `tests/test_gallery.py` fails until a change has landed in all
|
||||
three. It also checks that every `$('#id')` the script reaches for exists in that gallery's
|
||||
`index.html` — a lookup returning `null` is how the "Clear search" button sat dead for several
|
||||
releases without anyone noticing.
|
||||
`gallery.js` and `style.css` exist once, in `gallery/shared/` (2.6.0; they used to be three
|
||||
copies). Each `index.html` links `../shared/`, and every `publish.py` stages that folder to
|
||||
`gallery/shared/` on `gh-pages` beside its own page, so a fix lands once and any gallery's
|
||||
publish ships it to all three. `SharedPageAssetsTests` in `tests/test_gallery.py` fails if a
|
||||
per-gallery copy comes back. It also checks that every `$('#id')` the script reaches for exists
|
||||
in each gallery's `index.html` - a lookup returning `null` is how the "Clear search" button sat
|
||||
dead for several releases without anyone noticing.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Identity Forge — Archetype Sample Gallery</title>
|
||||
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><rect width='32' height='32' rx='7' fill='%231a1a2e'/><circle cx='16' cy='13' r='6.5' fill='%235b8def'/><path d='M6 27c1.5-5 5.5-7.5 10-7.5S24.5 22 26 27Z' fill='%237aa5ff'/></svg>">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<link rel="stylesheet" href="../shared/style.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -78,6 +78,6 @@
|
||||
</p>
|
||||
</footer>
|
||||
|
||||
<script src="gallery.js"></script>
|
||||
<script src="../shared/gallery.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -48,14 +48,17 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
# === GALLERY CONFIG — the only part that differs between the three copies ====
|
||||
GALLERY_KIND = "archetypes"
|
||||
GALLERY_TITLE = "themed archetype"
|
||||
PAGE_FILES = ["index.html", "style.css", "gallery.js",
|
||||
"Krea2_IdentityForge_ArchetypeCycle.json"]
|
||||
PAGE_FILES = ["index.html", "Krea2_IdentityForge_ArchetypeCycle.json"]
|
||||
# ============================================================================
|
||||
|
||||
from build_manifest import entry_names, generate_manifest, normalize_name # noqa: E402
|
||||
from build_gallery_images import optimize_image # noqa: E402
|
||||
|
||||
GALLERY_SRC_DIR = Path(__file__).resolve().parent
|
||||
#: 2.6.0: the page assets all three galleries share, published to gallery/shared/.
|
||||
SHARED_SRC_DIR = GALLERY_SRC_DIR.parent / "shared"
|
||||
SHARED_FILES = ["style.css", "gallery.js"]
|
||||
SHARED_REL_DIR = "gallery/shared"
|
||||
BRANCH = "gh-pages"
|
||||
REL_DIR = f"gallery/{GALLERY_KIND}"
|
||||
|
||||
@@ -247,9 +250,15 @@ def main() -> int:
|
||||
(worktree / REL_DIR / fname).write_text(
|
||||
src.read_text(encoding="utf-8"), encoding="utf-8", newline="")
|
||||
|
||||
for fname in SHARED_FILES:
|
||||
target = worktree / SHARED_REL_DIR / fname
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text((SHARED_SRC_DIR / fname).read_text(encoding="utf-8"),
|
||||
encoding="utf-8", newline="")
|
||||
|
||||
# -A, not a bare add: a plain `git add` stages additions and
|
||||
# modifications but NOT deletions, so a prune would be silently undone.
|
||||
run("git", "add", "-A", REL_DIR, cwd=worktree)
|
||||
run("git", "add", "-A", REL_DIR, SHARED_REL_DIR, cwd=worktree)
|
||||
if not run("git", "status", "--porcelain", cwd=worktree):
|
||||
print("\nNothing changed on the branch.")
|
||||
return 0
|
||||
|
||||
@@ -1,588 +0,0 @@
|
||||
/* =============================================================
|
||||
Identity Forge - Sample Gallery Styles
|
||||
Shared verbatim by the cosplay, archetype and creature galleries;
|
||||
see gallery/README.md before editing (a fix lands three times).
|
||||
Dark theme, tuned for browsing a large lazy-loaded grid.
|
||||
============================================================= */
|
||||
|
||||
/* --- CSS Variables --- */
|
||||
:root {
|
||||
--bg-primary: #1a1a2e;
|
||||
--bg-secondary: #16213e;
|
||||
--bg-card: #1e2a3a;
|
||||
--bg-card-hover: #253545;
|
||||
--bg-input: #0f1824;
|
||||
--text-primary: #e8e8f0;
|
||||
--text-secondary: #9098a8;
|
||||
--text-muted: #606878;
|
||||
--accent: #5b8def;
|
||||
--accent-hover: #7aa5ff;
|
||||
--accent-glow: rgba(91, 141, 239, 0.15);
|
||||
--border: #2a3a50;
|
||||
--border-hover: #4a6a90;
|
||||
--shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
--shadow-hover: 0 4px 16px rgba(0, 0, 0, 0.4);
|
||||
--radius: 8px;
|
||||
--transition: 0.2s ease;
|
||||
--max-width: 1400px;
|
||||
--card-min-width: 200px;
|
||||
--card-max-width: 280px;
|
||||
}
|
||||
|
||||
/* --- Reset & Base --- */
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
html {
|
||||
font-size: 16px;
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
background: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
line-height: 1.5;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
a { color: var(--accent); text-decoration: none; }
|
||||
a:hover { color: var(--accent-hover); }
|
||||
|
||||
/* --- Header --- */
|
||||
.gallery-header {
|
||||
text-align: center;
|
||||
padding: 2.5rem 1rem 1.5rem;
|
||||
max-width: var(--max-width);
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.gallery-header h1 {
|
||||
font-size: 1.75rem;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
margin-bottom: 0.5rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.header-subtitle {
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.95rem;
|
||||
max-width: 700px;
|
||||
margin: 0 auto 1rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.header-subtitle strong {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.header-links {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.header-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
padding: 0.5rem 1.25rem;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
color: var(--text-primary);
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
transition: all var(--transition);
|
||||
}
|
||||
|
||||
.header-link:hover {
|
||||
background: var(--bg-card-hover);
|
||||
border-color: var(--accent);
|
||||
color: var(--accent-hover);
|
||||
}
|
||||
|
||||
/* --- Controls --- */
|
||||
.gallery-controls {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
background: var(--bg-primary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding: 0.75rem 1rem;
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
.search-bar {
|
||||
max-width: 600px;
|
||||
margin: 0 auto 0.5rem;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.search-bar input {
|
||||
width: 100%;
|
||||
padding: 0.6rem 1rem;
|
||||
padding-right: 2.5rem;
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
color: var(--text-primary);
|
||||
font-size: 0.95rem;
|
||||
transition: border-color var(--transition), box-shadow var(--transition);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.search-bar input:focus {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
|
||||
.search-bar input::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.search-clear {
|
||||
position: absolute;
|
||||
right: 0.5rem;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
font-size: 1.25rem;
|
||||
cursor: pointer;
|
||||
padding: 0.25rem 0.5rem;
|
||||
line-height: 1;
|
||||
transition: color var(--transition);
|
||||
}
|
||||
|
||||
.search-clear:hover { color: var(--text-primary); }
|
||||
.search-clear.hidden { display: none; }
|
||||
|
||||
.stats-bar {
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.stats-missing {
|
||||
color: #c9a44b;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.stats-missing:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* --- Grid --- */
|
||||
.gallery-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(var(--card-min-width), 1fr));
|
||||
gap: 0.75rem;
|
||||
padding: 1rem;
|
||||
max-width: var(--max-width);
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* --- Card --- */
|
||||
.gallery-card {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
transition: all var(--transition);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.gallery-card:hover {
|
||||
background: var(--bg-card-hover);
|
||||
border-color: var(--border-hover);
|
||||
box-shadow: var(--shadow-hover);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.gallery-card:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.card-image-wrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 2 / 3;
|
||||
background: var(--bg-input);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.card-image-wrapper img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
transition: opacity 0.3s ease, transform 0.3s ease;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.card-image-wrapper img.loaded {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.card-image-wrapper img:hover {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
/* Placeholder for missing images */
|
||||
.card-image-wrapper.placeholder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--bg-input);
|
||||
}
|
||||
|
||||
.placeholder-icon {
|
||||
font-size: 2rem;
|
||||
color: var(--text-muted);
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.card-name {
|
||||
padding: 0.5rem 0.6rem;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
text-align: center;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* Missing image card styling */
|
||||
.gallery-card.missing {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.gallery-card.missing:hover {
|
||||
opacity: 0.75;
|
||||
transform: none;
|
||||
border-color: var(--border);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.missing-badge {
|
||||
position: absolute;
|
||||
top: 0.25rem;
|
||||
right: 0.25rem;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
color: #c9a44b;
|
||||
font-size: 0.65rem;
|
||||
padding: 0.15rem 0.4rem;
|
||||
border-radius: 3px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* --- Loading --- */
|
||||
.loading-indicator {
|
||||
text-align: center;
|
||||
padding: 3rem 1rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.loading-indicator.hidden { display: none; }
|
||||
|
||||
.spinner {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border: 3px solid var(--border);
|
||||
border-top-color: var(--accent);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
margin: 0 auto 0.75rem;
|
||||
}
|
||||
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
/* --- No Results --- */
|
||||
.no-results {
|
||||
text-align: center;
|
||||
padding: 3rem 1rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.no-results.hidden { display: none; }
|
||||
|
||||
.btn-secondary {
|
||||
margin-top: 0.75rem;
|
||||
padding: 0.5rem 1.25rem;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
color: var(--text-primary);
|
||||
cursor: pointer;
|
||||
font-size: 0.9rem;
|
||||
transition: all var(--transition);
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: var(--bg-card-hover);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
/* --- Lightbox --- */
|
||||
.lightbox {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
background: rgba(0, 0, 0, 0.92);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: fadeIn 0.2s ease;
|
||||
}
|
||||
|
||||
.lightbox.hidden { display: none; }
|
||||
|
||||
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
|
||||
|
||||
.lightbox-content {
|
||||
position: relative;
|
||||
max-width: 90vw;
|
||||
max-height: 90vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.lightbox-content img {
|
||||
max-width: 90vw;
|
||||
max-height: 80vh;
|
||||
object-fit: contain;
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.lightbox-name {
|
||||
margin-top: 0.75rem;
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.lightbox-close {
|
||||
position: fixed;
|
||||
top: 1rem;
|
||||
right: 1.5rem;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: none;
|
||||
color: var(--text-primary);
|
||||
font-size: 2rem;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
z-index: 1001;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background var(--transition);
|
||||
}
|
||||
|
||||
.lightbox-close:hover { background: rgba(255, 255, 255, 0.2); }
|
||||
|
||||
.lightbox-nav {
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: none;
|
||||
color: var(--text-primary);
|
||||
font-size: 2.5rem;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
z-index: 1001;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background var(--transition), opacity var(--transition);
|
||||
}
|
||||
|
||||
.lightbox-nav:hover { background: rgba(255, 255, 255, 0.2); }
|
||||
.lightbox-nav:disabled { opacity: 0.3; cursor: default; }
|
||||
|
||||
.lightbox-prev { left: 1rem; }
|
||||
.lightbox-next { right: 1rem; }
|
||||
|
||||
/* --- Footer --- */
|
||||
.gallery-footer {
|
||||
text-align: center;
|
||||
padding: 2rem 1rem;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.8rem;
|
||||
border-top: 1px solid var(--border);
|
||||
margin-top: 2rem;
|
||||
}
|
||||
|
||||
/* --- Keyboard shortcut hint --- */
|
||||
.keyboard-hint {
|
||||
position: fixed;
|
||||
bottom: 1rem;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
color: var(--text-muted);
|
||||
font-size: 0.7rem;
|
||||
padding: 0.4rem 0.8rem;
|
||||
border-radius: var(--radius);
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease;
|
||||
z-index: 999;
|
||||
}
|
||||
|
||||
.keyboard-hint.visible { opacity: 1; }
|
||||
|
||||
/* --- Responsive --- */
|
||||
@media (max-width: 600px) {
|
||||
.gallery-header h1 { font-size: 1.35rem; }
|
||||
.header-subtitle { font-size: 0.85rem; }
|
||||
.gallery-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
.card-name { font-size: 0.72rem; padding: 0.35rem 0.4rem; }
|
||||
.lightbox-prev { left: 0.25rem; }
|
||||
.lightbox-next { right: 0.25rem; }
|
||||
.lightbox-nav { font-size: 2rem; width: 40px; height: 40px; }
|
||||
}
|
||||
|
||||
/* --- Reduced motion --- */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
html { scroll-behavior: auto; }
|
||||
}
|
||||
|
||||
/* --- View controls: sort + "new in" filter (0.97.0) --------------------- */
|
||||
/* Both children are hidden by gallery.js unless the manifest actually supports
|
||||
them, so an older manifest renders the row empty rather than showing a control
|
||||
that cannot do anything. */
|
||||
.view-controls {
|
||||
max-width: 600px;
|
||||
margin: 0 auto 0.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.view-controls:empty { display: none; }
|
||||
|
||||
.sort-group {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.sort-group[hidden] { display: none; }
|
||||
|
||||
.sort-label {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.sort-select {
|
||||
padding: 0.3rem 1.6rem 0.3rem 0.6rem;
|
||||
background-color: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
color: var(--text-primary);
|
||||
font: inherit;
|
||||
font-size: 0.82rem;
|
||||
cursor: pointer;
|
||||
transition: border-color var(--transition);
|
||||
/* Native select arrows are unstyleable and render light-on-light in a dark
|
||||
control on some platforms, so the arrow is drawn here instead. */
|
||||
-webkit-appearance: none;
|
||||
-moz-appearance: none;
|
||||
appearance: none;
|
||||
background-image: linear-gradient(45deg, transparent 50%, var(--text-secondary) 50%),
|
||||
linear-gradient(135deg, var(--text-secondary) 50%, transparent 50%);
|
||||
background-position: right 0.75rem center, right 0.5rem center;
|
||||
background-size: 5px 5px, 5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
|
||||
.sort-select:hover { border-color: var(--border-hover); }
|
||||
|
||||
.sort-select:focus-visible {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
|
||||
/* The select's own dropdown list is painted by the OS, which does not inherit
|
||||
the page's dark palette -- name the colours so the options are legible. */
|
||||
.sort-select option {
|
||||
background: var(--bg-card);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.filter-chip {
|
||||
padding: 0.3rem 0.7rem;
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
color: var(--text-secondary);
|
||||
font: inherit;
|
||||
font-size: 0.78rem;
|
||||
cursor: pointer;
|
||||
transition: background var(--transition), border-color var(--transition),
|
||||
color var(--transition);
|
||||
}
|
||||
|
||||
.filter-chip[hidden] { display: none; }
|
||||
.filter-chip:hover { border-color: var(--border-hover); color: var(--text-primary); }
|
||||
|
||||
.filter-chip:focus-visible {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
|
||||
.filter-chip.is-active,
|
||||
.stats-missing .is-active {
|
||||
background: var(--accent-glow);
|
||||
border-color: var(--accent);
|
||||
color: var(--accent-hover);
|
||||
}
|
||||
|
||||
/* "new" corner tag on a card added in this release. Sits opposite the existing
|
||||
.missing-badge so the two can never overlap on one card. */
|
||||
.new-badge {
|
||||
position: absolute;
|
||||
top: 0.4rem;
|
||||
left: 0.4rem;
|
||||
z-index: 2;
|
||||
padding: 0.1rem 0.4rem;
|
||||
border-radius: 999px;
|
||||
background: var(--accent);
|
||||
color: #0f1824;
|
||||
font-size: 0.62rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
pointer-events: none;
|
||||
}
|
||||
@@ -1,488 +0,0 @@
|
||||
/* =============================================================
|
||||
Identity Forge — Cosplay Gallery Script
|
||||
Lazy-loading image grid with search, lightbox, keyboard nav.
|
||||
============================================================= */
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// ── State ──────────────────────────────────────────────
|
||||
const state = {
|
||||
entries: [], // Full list from manifest
|
||||
filtered: [], // Currently filtered subset
|
||||
lightboxIndex: -1, // Current lightbox position in filtered[]
|
||||
observer: null, // IntersectionObserver for lazy loading
|
||||
searchTerm: '',
|
||||
sort: 'az', // 'az' | 'new'
|
||||
onlyMissing: false, // "N missing images" toggle
|
||||
onlyNew: false, // "New in <version>" toggle
|
||||
version: '', // Pack version this manifest was built from
|
||||
rank: new Map(), // release -> position in the release list
|
||||
};
|
||||
|
||||
// Sorting by name is locale-aware and numeric-aware, so "Spider-Man 2" lands
|
||||
// after "Spider-Man" rather than between "Spider-Man 1" and "Spider-Man 10".
|
||||
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
|
||||
|
||||
// Remembering the sort is a per-viewer convenience, not state anyone else sees,
|
||||
// so it lives in localStorage -- which throws outright in some privacy modes,
|
||||
// hence the try/catch on BOTH sides.
|
||||
const SORT_KEY = 'if-gallery-sort';
|
||||
function loadSort() {
|
||||
try {
|
||||
const saved = localStorage.getItem(SORT_KEY);
|
||||
if (saved === 'az' || saved === 'new') return saved;
|
||||
} catch (e) { /* private mode, blocked site data - fall through */ }
|
||||
return 'az';
|
||||
}
|
||||
function saveSort(value) {
|
||||
try { localStorage.setItem(SORT_KEY, value); } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
/* An entry's release, ranked by POSITION in the manifest's release list rather
|
||||
than by comparing the version strings -- "0.10.0" sorts before "0.9.0" as
|
||||
text. An unstamped entry (a user-added one) ranks -1, i.e. oldest. */
|
||||
function rankOf(entry) {
|
||||
const r = state.rank.get(entry.added);
|
||||
return r === undefined ? -1 : r;
|
||||
}
|
||||
|
||||
function isNew(entry) {
|
||||
return Boolean(state.version) && entry.added === state.version;
|
||||
}
|
||||
|
||||
// ── DOM refs ───────────────────────────────────────────
|
||||
const $ = (sel) => document.querySelector(sel);
|
||||
const grid = $('#gallery-grid');
|
||||
const searchInput = $('#search');
|
||||
const searchClear = $('#search-clear');
|
||||
const sortSelect = $('#sort');
|
||||
const sortGroup = $('#sort-group');
|
||||
const newFilterBtn = $('#filter-new');
|
||||
const countVisible = $('#count-visible');
|
||||
const countTotal = $('#count-total');
|
||||
const statsMissing = $('#stats-missing');
|
||||
const loadingEl = $('#loading');
|
||||
const noResults = $('#no-results');
|
||||
const clearFiltersBtn = $('#clear-search-btn');
|
||||
const lightbox = $('#lightbox');
|
||||
const lightboxImg = $('#lightbox-img');
|
||||
const lightboxName = $('#lightbox-name');
|
||||
const lightboxClose = $('#lightbox-close');
|
||||
const lightboxPrev = $('#lightbox-prev');
|
||||
const lightboxNext = $('#lightbox-next');
|
||||
|
||||
// ── Load manifest ──────────────────────────────────────
|
||||
async function loadManifest() {
|
||||
try {
|
||||
const resp = await fetch('manifest.json');
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
||||
const data = await resp.json();
|
||||
state.entries = data.entries || [];
|
||||
state.version = data.version || '';
|
||||
// schema_version 1 manifests carry neither field. Everything below then
|
||||
// sees every entry as unstamped, the sort control stays hidden, and the
|
||||
// page behaves exactly as it did before -- no error, no empty control.
|
||||
(data.releases || []).forEach((release, i) => state.rank.set(release, i));
|
||||
state.filtered = [...state.entries];
|
||||
return data;
|
||||
} catch (err) {
|
||||
console.error('Failed to load manifest:', err);
|
||||
loadingEl.innerHTML = '<p style="color:#e06060">⚠ Failed to load gallery data. Please try refreshing.</p>';
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Render ─────────────────────────────────────────────
|
||||
function render() {
|
||||
// Clear grid
|
||||
grid.innerHTML = '';
|
||||
|
||||
// Fires for ANY active narrowing, not just a search. Before 0.97.0 only a
|
||||
// search could empty the grid; the two toggles can too, and an empty grid with
|
||||
// no explanation reads as a broken page.
|
||||
if (state.filtered.length === 0 && isNarrowed()) {
|
||||
noResults.classList.remove('hidden');
|
||||
} else {
|
||||
noResults.classList.add('hidden');
|
||||
}
|
||||
|
||||
// Build cards
|
||||
const fragment = document.createDocumentFragment();
|
||||
state.filtered.forEach((entry, idx) => {
|
||||
const card = createCard(entry, idx);
|
||||
fragment.appendChild(card);
|
||||
});
|
||||
grid.appendChild(fragment);
|
||||
|
||||
// Update stats
|
||||
countVisible.textContent = state.filtered.length;
|
||||
countTotal.textContent = state.entries.length;
|
||||
|
||||
// Update missing count
|
||||
const missingCount = state.entries.filter(e => !e.has_image).length;
|
||||
if (missingCount > 0) {
|
||||
statsMissing.innerHTML = `<span role="button" tabindex="0" title="Show missing entries" id="show-missing-btn">${missingCount} missing image${missingCount !== 1 ? 's' : ''}</span>`;
|
||||
const btn = $('#show-missing-btn');
|
||||
if (btn) {
|
||||
btn.setAttribute('aria-pressed', String(state.onlyMissing));
|
||||
btn.classList.toggle('is-active', state.onlyMissing);
|
||||
btn.addEventListener('click', toggleMissing);
|
||||
btn.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleMissing(); }
|
||||
});
|
||||
}
|
||||
} else {
|
||||
statsMissing.textContent = '';
|
||||
}
|
||||
|
||||
// Re-observe lazy images
|
||||
observeNewImages();
|
||||
}
|
||||
|
||||
function createCard(entry) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'gallery-card' + (entry.has_image ? '' : ' missing');
|
||||
card.setAttribute('role', 'listitem');
|
||||
card.setAttribute('tabindex', '0');
|
||||
card.setAttribute('aria-label', entry.name + (entry.has_image ? '' : ' (no image)'));
|
||||
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'card-image-wrapper';
|
||||
|
||||
if (entry.has_image) {
|
||||
const img = document.createElement('img');
|
||||
img.setAttribute('data-src', entry.image);
|
||||
img.alt = entry.name;
|
||||
img.loading = 'lazy';
|
||||
// Inline tiny placeholder color to avoid layout shift
|
||||
img.style.backgroundColor = '#1a2a3a';
|
||||
wrapper.appendChild(img);
|
||||
} else {
|
||||
wrapper.classList.add('placeholder');
|
||||
wrapper.innerHTML = '<span class="placeholder-icon" aria-hidden="true">📷</span>';
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'missing-badge';
|
||||
badge.textContent = 'no image';
|
||||
card.appendChild(badge);
|
||||
}
|
||||
|
||||
if (isNew(entry)) {
|
||||
const tag = document.createElement('span');
|
||||
tag.className = 'new-badge';
|
||||
tag.textContent = 'new';
|
||||
tag.title = 'Added in ' + entry.added;
|
||||
card.appendChild(tag);
|
||||
}
|
||||
|
||||
const nameEl = document.createElement('div');
|
||||
nameEl.className = 'card-name';
|
||||
nameEl.textContent = entry.name;
|
||||
nameEl.title = entry.name + (entry.added ? ' - added in ' + entry.added : '');
|
||||
|
||||
card.appendChild(wrapper);
|
||||
card.appendChild(nameEl);
|
||||
|
||||
// Click handler
|
||||
if (entry.has_image) {
|
||||
card.addEventListener('click', () => openLightbox(entry.name));
|
||||
card.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
openLightbox(entry.name);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
// ── Lazy Loading ───────────────────────────────────────
|
||||
function observeNewImages() {
|
||||
// Disconnect previous observer
|
||||
if (state.observer) state.observer.disconnect();
|
||||
|
||||
state.observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (entry.isIntersecting) {
|
||||
const img = entry.target;
|
||||
const src = img.getAttribute('data-src');
|
||||
if (src) {
|
||||
img.src = src;
|
||||
img.removeAttribute('data-src');
|
||||
img.addEventListener('load', () => img.classList.add('loaded'));
|
||||
img.addEventListener('error', () => {
|
||||
// On error, show placeholder
|
||||
img.parentElement.classList.add('placeholder');
|
||||
img.remove();
|
||||
});
|
||||
}
|
||||
state.observer.unobserve(img);
|
||||
}
|
||||
});
|
||||
},
|
||||
{
|
||||
rootMargin: '200px 0px',
|
||||
threshold: 0.01,
|
||||
}
|
||||
);
|
||||
|
||||
// Observe all images with data-src
|
||||
grid.querySelectorAll('img[data-src]').forEach((img) => {
|
||||
state.observer.observe(img);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Search ─────────────────────────────────────────────
|
||||
function debounce(fn, delay) {
|
||||
let timer;
|
||||
return function (...args) {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => fn.apply(this, args), delay);
|
||||
};
|
||||
}
|
||||
|
||||
/* The single place `state.filtered` is computed. Search, the two toggles and
|
||||
the sort all funnel through here, so they compose instead of overwriting one
|
||||
another -- searching used to clear a "missing images" view, and vice versa. */
|
||||
function applyView() {
|
||||
let list = state.entries;
|
||||
if (state.onlyMissing) list = list.filter((e) => !e.has_image);
|
||||
if (state.onlyNew) list = list.filter(isNew);
|
||||
if (state.searchTerm) {
|
||||
list = list.filter((e) => e.name.toLowerCase().includes(state.searchTerm));
|
||||
}
|
||||
|
||||
// The manifest is already name-sorted, so A-Z needs no work; sorting a copy
|
||||
// matters only for 'new', but both branches copy so `filtered` is never an
|
||||
// alias of `entries`.
|
||||
list = [...list];
|
||||
if (state.sort === 'new') {
|
||||
list.sort((a, b) => rankOf(b) - rankOf(a) || collator.compare(a.name, b.name));
|
||||
}
|
||||
state.filtered = list;
|
||||
|
||||
searchClear.classList.toggle('hidden', !state.searchTerm);
|
||||
if (newFilterBtn) newFilterBtn.setAttribute('aria-pressed', String(state.onlyNew));
|
||||
render();
|
||||
}
|
||||
|
||||
function doSearch(term) {
|
||||
state.searchTerm = term.trim().toLowerCase();
|
||||
applyView();
|
||||
}
|
||||
|
||||
function isNarrowed() {
|
||||
return Boolean(state.searchTerm) || state.onlyMissing || state.onlyNew;
|
||||
}
|
||||
|
||||
/* Resets every narrowing at once. The button for this shipped in the markup from
|
||||
the start but was never wired to anything -- a dead control, and the only exit
|
||||
from a filtered empty state that does not require guessing which control caused
|
||||
it. The sort is deliberately NOT reset: it is a view preference, not a filter. */
|
||||
function clearFilters() {
|
||||
state.searchTerm = '';
|
||||
state.onlyMissing = false;
|
||||
state.onlyNew = false;
|
||||
searchInput.value = '';
|
||||
if (newFilterBtn) newFilterBtn.classList.remove('is-active');
|
||||
applyView();
|
||||
}
|
||||
|
||||
const debouncedSearch = debounce(doSearch, 150);
|
||||
|
||||
searchInput.addEventListener('input', () => {
|
||||
debouncedSearch(searchInput.value);
|
||||
});
|
||||
|
||||
searchClear.addEventListener('click', () => {
|
||||
searchInput.value = '';
|
||||
doSearch('');
|
||||
searchInput.focus();
|
||||
});
|
||||
|
||||
if (clearFiltersBtn) {
|
||||
clearFiltersBtn.addEventListener('click', () => {
|
||||
clearFilters();
|
||||
searchInput.focus();
|
||||
});
|
||||
}
|
||||
|
||||
// ── Show missing ───────────────────────────────────────
|
||||
/* Was: it planted the literal text "missing entries" in the search box, which
|
||||
looked like a query the viewer had typed and could not be un-typed without
|
||||
clearing a real search. It is a toggle now, and it composes with the rest. */
|
||||
function toggleMissing() {
|
||||
state.onlyMissing = !state.onlyMissing;
|
||||
applyView();
|
||||
}
|
||||
|
||||
// ── Lightbox ───────────────────────────────────────────
|
||||
function openLightbox(name) {
|
||||
// Find entry index in filtered list
|
||||
state.lightboxIndex = state.filtered.findIndex(
|
||||
(e) => e.name === name && e.has_image
|
||||
);
|
||||
if (state.lightboxIndex === -1) return;
|
||||
updateLightbox();
|
||||
lightbox.classList.remove('hidden');
|
||||
document.body.style.overflow = 'hidden';
|
||||
lightboxClose.focus();
|
||||
window.addEventListener('keydown', handleLightboxKey);
|
||||
}
|
||||
|
||||
function closeLightbox() {
|
||||
lightbox.classList.add('hidden');
|
||||
document.body.style.overflow = '';
|
||||
state.lightboxIndex = -1;
|
||||
window.removeEventListener('keydown', handleLightboxKey);
|
||||
|
||||
// Refocus the card that was open
|
||||
const name = lightboxName.textContent;
|
||||
const cards = grid.querySelectorAll('.gallery-card');
|
||||
cards.forEach((card) => {
|
||||
if (card.querySelector('.card-name')?.textContent === name) {
|
||||
card.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function updateLightbox() {
|
||||
const entry = state.filtered[state.lightboxIndex];
|
||||
if (!entry) return;
|
||||
|
||||
lightboxImg.src = entry.image;
|
||||
lightboxImg.alt = entry.name;
|
||||
lightboxName.textContent = entry.name;
|
||||
|
||||
// Update nav button states
|
||||
lightboxPrev.disabled = state.lightboxIndex <= 0;
|
||||
lightboxNext.disabled = state.lightboxIndex >= state.filtered.length - 1;
|
||||
}
|
||||
|
||||
function lightboxPrevImage() {
|
||||
// Find previous entry with an image
|
||||
let idx = state.lightboxIndex - 1;
|
||||
while (idx >= 0) {
|
||||
if (state.filtered[idx].has_image) {
|
||||
state.lightboxIndex = idx;
|
||||
updateLightbox();
|
||||
return;
|
||||
}
|
||||
idx--;
|
||||
}
|
||||
}
|
||||
|
||||
function lightboxNextImage() {
|
||||
let idx = state.lightboxIndex + 1;
|
||||
while (idx < state.filtered.length) {
|
||||
if (state.filtered[idx].has_image) {
|
||||
state.lightboxIndex = idx;
|
||||
updateLightbox();
|
||||
return;
|
||||
}
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
|
||||
function handleLightboxKey(e) {
|
||||
switch (e.key) {
|
||||
case 'Escape':
|
||||
closeLightbox();
|
||||
break;
|
||||
case 'ArrowLeft':
|
||||
e.preventDefault();
|
||||
lightboxPrevImage();
|
||||
break;
|
||||
case 'ArrowRight':
|
||||
e.preventDefault();
|
||||
lightboxNextImage();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
lightboxClose.addEventListener('click', closeLightbox);
|
||||
lightboxPrev.addEventListener('click', lightboxPrevImage);
|
||||
lightboxNext.addEventListener('click', lightboxNextImage);
|
||||
|
||||
lightbox.addEventListener('click', (e) => {
|
||||
if (e.target === lightbox) closeLightbox();
|
||||
});
|
||||
|
||||
// ── Keyboard shortcut hint ─────────────────────────────
|
||||
document.addEventListener('keydown', (e) => {
|
||||
// Ctrl+K or / to focus search
|
||||
if ((e.ctrlKey && e.key === 'k') || (e.key === '/' && document.activeElement !== searchInput)) {
|
||||
e.preventDefault();
|
||||
searchInput.focus();
|
||||
searchInput.select();
|
||||
}
|
||||
});
|
||||
|
||||
// ── Sort & filter controls ─────────────────────────────
|
||||
/* Both controls are HIDDEN unless the manifest actually supports them: a sort
|
||||
with nothing to sort by, or a "New in ..." filter that is always present and
|
||||
sometimes empty, only teaches a viewer to ignore the control row. */
|
||||
function setupSortControls() {
|
||||
const stamped = state.rank.size > 0
|
||||
&& state.entries.some((e) => e.added);
|
||||
|
||||
if (sortGroup) sortGroup.hidden = !stamped;
|
||||
if (sortSelect) {
|
||||
if (stamped) {
|
||||
state.sort = loadSort();
|
||||
sortSelect.value = state.sort;
|
||||
sortSelect.addEventListener('change', () => {
|
||||
state.sort = sortSelect.value === 'new' ? 'new' : 'az';
|
||||
saveSort(state.sort);
|
||||
applyView();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (newFilterBtn) {
|
||||
const anyNew = stamped && state.entries.some(isNew);
|
||||
newFilterBtn.hidden = !anyNew;
|
||||
if (anyNew) {
|
||||
newFilterBtn.textContent = 'New in ' + state.version;
|
||||
newFilterBtn.addEventListener('click', () => {
|
||||
state.onlyNew = !state.onlyNew;
|
||||
newFilterBtn.classList.toggle('is-active', state.onlyNew);
|
||||
applyView();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Init ───────────────────────────────────────────────
|
||||
async function init() {
|
||||
try {
|
||||
const manifest = await loadManifest();
|
||||
loadingEl.classList.add('hidden');
|
||||
|
||||
// Update stats
|
||||
countTotal.textContent = manifest.total_entries || state.entries.length;
|
||||
|
||||
setupSortControls();
|
||||
applyView();
|
||||
|
||||
// Focus search on load if no hash
|
||||
if (!window.location.hash) {
|
||||
// Don't auto-focus on mobile to avoid keyboard popup
|
||||
if (window.innerWidth > 768) {
|
||||
searchInput.focus();
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
loadingEl.innerHTML = '<p style="color:#e06060">⚠ Failed to load gallery.</p>';
|
||||
}
|
||||
}
|
||||
|
||||
// Start when DOM is ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Identity Forge — Cosplay Sample Gallery</title>
|
||||
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><rect width='32' height='32' rx='7' fill='%231a1a2e'/><circle cx='16' cy='13' r='6.5' fill='%235b8def'/><path d='M6 27c1.5-5 5.5-7.5 10-7.5S24.5 22 26 27Z' fill='%237aa5ff'/></svg>">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<link rel="stylesheet" href="../shared/style.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -78,6 +78,6 @@
|
||||
</p>
|
||||
</footer>
|
||||
|
||||
<script src="gallery.js"></script>
|
||||
<script src="../shared/gallery.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -48,14 +48,17 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
# === GALLERY CONFIG — the only part that differs between the three copies ====
|
||||
GALLERY_KIND = "cosplay"
|
||||
GALLERY_TITLE = "cosplay character"
|
||||
PAGE_FILES = ["index.html", "style.css", "gallery.js",
|
||||
"Krea2_IdentityForge_CharacterCycle.json"]
|
||||
PAGE_FILES = ["index.html", "Krea2_IdentityForge_CharacterCycle.json"]
|
||||
# ============================================================================
|
||||
|
||||
from build_manifest import entry_names, generate_manifest, normalize_name # noqa: E402
|
||||
from build_gallery_images import optimize_image # noqa: E402
|
||||
|
||||
GALLERY_SRC_DIR = Path(__file__).resolve().parent
|
||||
#: 2.6.0: the page assets all three galleries share, published to gallery/shared/.
|
||||
SHARED_SRC_DIR = GALLERY_SRC_DIR.parent / "shared"
|
||||
SHARED_FILES = ["style.css", "gallery.js"]
|
||||
SHARED_REL_DIR = "gallery/shared"
|
||||
BRANCH = "gh-pages"
|
||||
REL_DIR = f"gallery/{GALLERY_KIND}"
|
||||
|
||||
@@ -247,9 +250,15 @@ def main() -> int:
|
||||
(worktree / REL_DIR / fname).write_text(
|
||||
src.read_text(encoding="utf-8"), encoding="utf-8", newline="")
|
||||
|
||||
for fname in SHARED_FILES:
|
||||
target = worktree / SHARED_REL_DIR / fname
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text((SHARED_SRC_DIR / fname).read_text(encoding="utf-8"),
|
||||
encoding="utf-8", newline="")
|
||||
|
||||
# -A, not a bare add: a plain `git add` stages additions and
|
||||
# modifications but NOT deletions, so a prune would be silently undone.
|
||||
run("git", "add", "-A", REL_DIR, cwd=worktree)
|
||||
run("git", "add", "-A", REL_DIR, SHARED_REL_DIR, cwd=worktree)
|
||||
if not run("git", "status", "--porcelain", cwd=worktree):
|
||||
print("\nNothing changed on the branch.")
|
||||
return 0
|
||||
|
||||
@@ -1,588 +0,0 @@
|
||||
/* =============================================================
|
||||
Identity Forge - Sample Gallery Styles
|
||||
Shared verbatim by the cosplay, archetype and creature galleries;
|
||||
see gallery/README.md before editing (a fix lands three times).
|
||||
Dark theme, tuned for browsing a large lazy-loaded grid.
|
||||
============================================================= */
|
||||
|
||||
/* --- CSS Variables --- */
|
||||
:root {
|
||||
--bg-primary: #1a1a2e;
|
||||
--bg-secondary: #16213e;
|
||||
--bg-card: #1e2a3a;
|
||||
--bg-card-hover: #253545;
|
||||
--bg-input: #0f1824;
|
||||
--text-primary: #e8e8f0;
|
||||
--text-secondary: #9098a8;
|
||||
--text-muted: #606878;
|
||||
--accent: #5b8def;
|
||||
--accent-hover: #7aa5ff;
|
||||
--accent-glow: rgba(91, 141, 239, 0.15);
|
||||
--border: #2a3a50;
|
||||
--border-hover: #4a6a90;
|
||||
--shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
--shadow-hover: 0 4px 16px rgba(0, 0, 0, 0.4);
|
||||
--radius: 8px;
|
||||
--transition: 0.2s ease;
|
||||
--max-width: 1400px;
|
||||
--card-min-width: 200px;
|
||||
--card-max-width: 280px;
|
||||
}
|
||||
|
||||
/* --- Reset & Base --- */
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
html {
|
||||
font-size: 16px;
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
background: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
line-height: 1.5;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
a { color: var(--accent); text-decoration: none; }
|
||||
a:hover { color: var(--accent-hover); }
|
||||
|
||||
/* --- Header --- */
|
||||
.gallery-header {
|
||||
text-align: center;
|
||||
padding: 2.5rem 1rem 1.5rem;
|
||||
max-width: var(--max-width);
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.gallery-header h1 {
|
||||
font-size: 1.75rem;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
margin-bottom: 0.5rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.header-subtitle {
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.95rem;
|
||||
max-width: 700px;
|
||||
margin: 0 auto 1rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.header-subtitle strong {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.header-links {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.header-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
padding: 0.5rem 1.25rem;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
color: var(--text-primary);
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
transition: all var(--transition);
|
||||
}
|
||||
|
||||
.header-link:hover {
|
||||
background: var(--bg-card-hover);
|
||||
border-color: var(--accent);
|
||||
color: var(--accent-hover);
|
||||
}
|
||||
|
||||
/* --- Controls --- */
|
||||
.gallery-controls {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
background: var(--bg-primary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding: 0.75rem 1rem;
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
.search-bar {
|
||||
max-width: 600px;
|
||||
margin: 0 auto 0.5rem;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.search-bar input {
|
||||
width: 100%;
|
||||
padding: 0.6rem 1rem;
|
||||
padding-right: 2.5rem;
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
color: var(--text-primary);
|
||||
font-size: 0.95rem;
|
||||
transition: border-color var(--transition), box-shadow var(--transition);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.search-bar input:focus {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
|
||||
.search-bar input::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.search-clear {
|
||||
position: absolute;
|
||||
right: 0.5rem;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
font-size: 1.25rem;
|
||||
cursor: pointer;
|
||||
padding: 0.25rem 0.5rem;
|
||||
line-height: 1;
|
||||
transition: color var(--transition);
|
||||
}
|
||||
|
||||
.search-clear:hover { color: var(--text-primary); }
|
||||
.search-clear.hidden { display: none; }
|
||||
|
||||
.stats-bar {
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.stats-missing {
|
||||
color: #c9a44b;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.stats-missing:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* --- Grid --- */
|
||||
.gallery-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(var(--card-min-width), 1fr));
|
||||
gap: 0.75rem;
|
||||
padding: 1rem;
|
||||
max-width: var(--max-width);
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* --- Card --- */
|
||||
.gallery-card {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
transition: all var(--transition);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.gallery-card:hover {
|
||||
background: var(--bg-card-hover);
|
||||
border-color: var(--border-hover);
|
||||
box-shadow: var(--shadow-hover);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.gallery-card:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.card-image-wrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 2 / 3;
|
||||
background: var(--bg-input);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.card-image-wrapper img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
transition: opacity 0.3s ease, transform 0.3s ease;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.card-image-wrapper img.loaded {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.card-image-wrapper img:hover {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
/* Placeholder for missing images */
|
||||
.card-image-wrapper.placeholder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--bg-input);
|
||||
}
|
||||
|
||||
.placeholder-icon {
|
||||
font-size: 2rem;
|
||||
color: var(--text-muted);
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.card-name {
|
||||
padding: 0.5rem 0.6rem;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
text-align: center;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* Missing image card styling */
|
||||
.gallery-card.missing {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.gallery-card.missing:hover {
|
||||
opacity: 0.75;
|
||||
transform: none;
|
||||
border-color: var(--border);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.missing-badge {
|
||||
position: absolute;
|
||||
top: 0.25rem;
|
||||
right: 0.25rem;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
color: #c9a44b;
|
||||
font-size: 0.65rem;
|
||||
padding: 0.15rem 0.4rem;
|
||||
border-radius: 3px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* --- Loading --- */
|
||||
.loading-indicator {
|
||||
text-align: center;
|
||||
padding: 3rem 1rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.loading-indicator.hidden { display: none; }
|
||||
|
||||
.spinner {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border: 3px solid var(--border);
|
||||
border-top-color: var(--accent);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
margin: 0 auto 0.75rem;
|
||||
}
|
||||
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
/* --- No Results --- */
|
||||
.no-results {
|
||||
text-align: center;
|
||||
padding: 3rem 1rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.no-results.hidden { display: none; }
|
||||
|
||||
.btn-secondary {
|
||||
margin-top: 0.75rem;
|
||||
padding: 0.5rem 1.25rem;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
color: var(--text-primary);
|
||||
cursor: pointer;
|
||||
font-size: 0.9rem;
|
||||
transition: all var(--transition);
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: var(--bg-card-hover);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
/* --- Lightbox --- */
|
||||
.lightbox {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
background: rgba(0, 0, 0, 0.92);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: fadeIn 0.2s ease;
|
||||
}
|
||||
|
||||
.lightbox.hidden { display: none; }
|
||||
|
||||
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
|
||||
|
||||
.lightbox-content {
|
||||
position: relative;
|
||||
max-width: 90vw;
|
||||
max-height: 90vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.lightbox-content img {
|
||||
max-width: 90vw;
|
||||
max-height: 80vh;
|
||||
object-fit: contain;
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.lightbox-name {
|
||||
margin-top: 0.75rem;
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.lightbox-close {
|
||||
position: fixed;
|
||||
top: 1rem;
|
||||
right: 1.5rem;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: none;
|
||||
color: var(--text-primary);
|
||||
font-size: 2rem;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
z-index: 1001;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background var(--transition);
|
||||
}
|
||||
|
||||
.lightbox-close:hover { background: rgba(255, 255, 255, 0.2); }
|
||||
|
||||
.lightbox-nav {
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: none;
|
||||
color: var(--text-primary);
|
||||
font-size: 2.5rem;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
z-index: 1001;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background var(--transition), opacity var(--transition);
|
||||
}
|
||||
|
||||
.lightbox-nav:hover { background: rgba(255, 255, 255, 0.2); }
|
||||
.lightbox-nav:disabled { opacity: 0.3; cursor: default; }
|
||||
|
||||
.lightbox-prev { left: 1rem; }
|
||||
.lightbox-next { right: 1rem; }
|
||||
|
||||
/* --- Footer --- */
|
||||
.gallery-footer {
|
||||
text-align: center;
|
||||
padding: 2rem 1rem;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.8rem;
|
||||
border-top: 1px solid var(--border);
|
||||
margin-top: 2rem;
|
||||
}
|
||||
|
||||
/* --- Keyboard shortcut hint --- */
|
||||
.keyboard-hint {
|
||||
position: fixed;
|
||||
bottom: 1rem;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
color: var(--text-muted);
|
||||
font-size: 0.7rem;
|
||||
padding: 0.4rem 0.8rem;
|
||||
border-radius: var(--radius);
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease;
|
||||
z-index: 999;
|
||||
}
|
||||
|
||||
.keyboard-hint.visible { opacity: 1; }
|
||||
|
||||
/* --- Responsive --- */
|
||||
@media (max-width: 600px) {
|
||||
.gallery-header h1 { font-size: 1.35rem; }
|
||||
.header-subtitle { font-size: 0.85rem; }
|
||||
.gallery-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
.card-name { font-size: 0.72rem; padding: 0.35rem 0.4rem; }
|
||||
.lightbox-prev { left: 0.25rem; }
|
||||
.lightbox-next { right: 0.25rem; }
|
||||
.lightbox-nav { font-size: 2rem; width: 40px; height: 40px; }
|
||||
}
|
||||
|
||||
/* --- Reduced motion --- */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
html { scroll-behavior: auto; }
|
||||
}
|
||||
|
||||
/* --- View controls: sort + "new in" filter (0.97.0) --------------------- */
|
||||
/* Both children are hidden by gallery.js unless the manifest actually supports
|
||||
them, so an older manifest renders the row empty rather than showing a control
|
||||
that cannot do anything. */
|
||||
.view-controls {
|
||||
max-width: 600px;
|
||||
margin: 0 auto 0.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.view-controls:empty { display: none; }
|
||||
|
||||
.sort-group {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.sort-group[hidden] { display: none; }
|
||||
|
||||
.sort-label {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.sort-select {
|
||||
padding: 0.3rem 1.6rem 0.3rem 0.6rem;
|
||||
background-color: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
color: var(--text-primary);
|
||||
font: inherit;
|
||||
font-size: 0.82rem;
|
||||
cursor: pointer;
|
||||
transition: border-color var(--transition);
|
||||
/* Native select arrows are unstyleable and render light-on-light in a dark
|
||||
control on some platforms, so the arrow is drawn here instead. */
|
||||
-webkit-appearance: none;
|
||||
-moz-appearance: none;
|
||||
appearance: none;
|
||||
background-image: linear-gradient(45deg, transparent 50%, var(--text-secondary) 50%),
|
||||
linear-gradient(135deg, var(--text-secondary) 50%, transparent 50%);
|
||||
background-position: right 0.75rem center, right 0.5rem center;
|
||||
background-size: 5px 5px, 5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
|
||||
.sort-select:hover { border-color: var(--border-hover); }
|
||||
|
||||
.sort-select:focus-visible {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
|
||||
/* The select's own dropdown list is painted by the OS, which does not inherit
|
||||
the page's dark palette -- name the colours so the options are legible. */
|
||||
.sort-select option {
|
||||
background: var(--bg-card);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.filter-chip {
|
||||
padding: 0.3rem 0.7rem;
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
color: var(--text-secondary);
|
||||
font: inherit;
|
||||
font-size: 0.78rem;
|
||||
cursor: pointer;
|
||||
transition: background var(--transition), border-color var(--transition),
|
||||
color var(--transition);
|
||||
}
|
||||
|
||||
.filter-chip[hidden] { display: none; }
|
||||
.filter-chip:hover { border-color: var(--border-hover); color: var(--text-primary); }
|
||||
|
||||
.filter-chip:focus-visible {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
|
||||
.filter-chip.is-active,
|
||||
.stats-missing .is-active {
|
||||
background: var(--accent-glow);
|
||||
border-color: var(--accent);
|
||||
color: var(--accent-hover);
|
||||
}
|
||||
|
||||
/* "new" corner tag on a card added in this release. Sits opposite the existing
|
||||
.missing-badge so the two can never overlap on one card. */
|
||||
.new-badge {
|
||||
position: absolute;
|
||||
top: 0.4rem;
|
||||
left: 0.4rem;
|
||||
z-index: 2;
|
||||
padding: 0.1rem 0.4rem;
|
||||
border-radius: 999px;
|
||||
background: var(--accent);
|
||||
color: #0f1824;
|
||||
font-size: 0.62rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
pointer-events: none;
|
||||
}
|
||||
@@ -1,488 +0,0 @@
|
||||
/* =============================================================
|
||||
Identity Forge — Creature Gallery Script
|
||||
Lazy-loading image grid with search, lightbox, keyboard nav.
|
||||
============================================================= */
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// ── State ──────────────────────────────────────────────
|
||||
const state = {
|
||||
entries: [], // Full list from manifest
|
||||
filtered: [], // Currently filtered subset
|
||||
lightboxIndex: -1, // Current lightbox position in filtered[]
|
||||
observer: null, // IntersectionObserver for lazy loading
|
||||
searchTerm: '',
|
||||
sort: 'az', // 'az' | 'new'
|
||||
onlyMissing: false, // "N missing images" toggle
|
||||
onlyNew: false, // "New in <version>" toggle
|
||||
version: '', // Pack version this manifest was built from
|
||||
rank: new Map(), // release -> position in the release list
|
||||
};
|
||||
|
||||
// Sorting by name is locale-aware and numeric-aware, so "Spider-Man 2" lands
|
||||
// after "Spider-Man" rather than between "Spider-Man 1" and "Spider-Man 10".
|
||||
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
|
||||
|
||||
// Remembering the sort is a per-viewer convenience, not state anyone else sees,
|
||||
// so it lives in localStorage -- which throws outright in some privacy modes,
|
||||
// hence the try/catch on BOTH sides.
|
||||
const SORT_KEY = 'if-gallery-sort';
|
||||
function loadSort() {
|
||||
try {
|
||||
const saved = localStorage.getItem(SORT_KEY);
|
||||
if (saved === 'az' || saved === 'new') return saved;
|
||||
} catch (e) { /* private mode, blocked site data - fall through */ }
|
||||
return 'az';
|
||||
}
|
||||
function saveSort(value) {
|
||||
try { localStorage.setItem(SORT_KEY, value); } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
/* An entry's release, ranked by POSITION in the manifest's release list rather
|
||||
than by comparing the version strings -- "0.10.0" sorts before "0.9.0" as
|
||||
text. An unstamped entry (a user-added one) ranks -1, i.e. oldest. */
|
||||
function rankOf(entry) {
|
||||
const r = state.rank.get(entry.added);
|
||||
return r === undefined ? -1 : r;
|
||||
}
|
||||
|
||||
function isNew(entry) {
|
||||
return Boolean(state.version) && entry.added === state.version;
|
||||
}
|
||||
|
||||
// ── DOM refs ───────────────────────────────────────────
|
||||
const $ = (sel) => document.querySelector(sel);
|
||||
const grid = $('#gallery-grid');
|
||||
const searchInput = $('#search');
|
||||
const searchClear = $('#search-clear');
|
||||
const sortSelect = $('#sort');
|
||||
const sortGroup = $('#sort-group');
|
||||
const newFilterBtn = $('#filter-new');
|
||||
const countVisible = $('#count-visible');
|
||||
const countTotal = $('#count-total');
|
||||
const statsMissing = $('#stats-missing');
|
||||
const loadingEl = $('#loading');
|
||||
const noResults = $('#no-results');
|
||||
const clearFiltersBtn = $('#clear-search-btn');
|
||||
const lightbox = $('#lightbox');
|
||||
const lightboxImg = $('#lightbox-img');
|
||||
const lightboxName = $('#lightbox-name');
|
||||
const lightboxClose = $('#lightbox-close');
|
||||
const lightboxPrev = $('#lightbox-prev');
|
||||
const lightboxNext = $('#lightbox-next');
|
||||
|
||||
// ── Load manifest ──────────────────────────────────────
|
||||
async function loadManifest() {
|
||||
try {
|
||||
const resp = await fetch('manifest.json');
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
||||
const data = await resp.json();
|
||||
state.entries = data.entries || [];
|
||||
state.version = data.version || '';
|
||||
// schema_version 1 manifests carry neither field. Everything below then
|
||||
// sees every entry as unstamped, the sort control stays hidden, and the
|
||||
// page behaves exactly as it did before -- no error, no empty control.
|
||||
(data.releases || []).forEach((release, i) => state.rank.set(release, i));
|
||||
state.filtered = [...state.entries];
|
||||
return data;
|
||||
} catch (err) {
|
||||
console.error('Failed to load manifest:', err);
|
||||
loadingEl.innerHTML = '<p style="color:#e06060">⚠ Failed to load gallery data. Please try refreshing.</p>';
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Render ─────────────────────────────────────────────
|
||||
function render() {
|
||||
// Clear grid
|
||||
grid.innerHTML = '';
|
||||
|
||||
// Fires for ANY active narrowing, not just a search. Before 0.97.0 only a
|
||||
// search could empty the grid; the two toggles can too, and an empty grid with
|
||||
// no explanation reads as a broken page.
|
||||
if (state.filtered.length === 0 && isNarrowed()) {
|
||||
noResults.classList.remove('hidden');
|
||||
} else {
|
||||
noResults.classList.add('hidden');
|
||||
}
|
||||
|
||||
// Build cards
|
||||
const fragment = document.createDocumentFragment();
|
||||
state.filtered.forEach((entry, idx) => {
|
||||
const card = createCard(entry, idx);
|
||||
fragment.appendChild(card);
|
||||
});
|
||||
grid.appendChild(fragment);
|
||||
|
||||
// Update stats
|
||||
countVisible.textContent = state.filtered.length;
|
||||
countTotal.textContent = state.entries.length;
|
||||
|
||||
// Update missing count
|
||||
const missingCount = state.entries.filter(e => !e.has_image).length;
|
||||
if (missingCount > 0) {
|
||||
statsMissing.innerHTML = `<span role="button" tabindex="0" title="Show missing entries" id="show-missing-btn">${missingCount} missing image${missingCount !== 1 ? 's' : ''}</span>`;
|
||||
const btn = $('#show-missing-btn');
|
||||
if (btn) {
|
||||
btn.setAttribute('aria-pressed', String(state.onlyMissing));
|
||||
btn.classList.toggle('is-active', state.onlyMissing);
|
||||
btn.addEventListener('click', toggleMissing);
|
||||
btn.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleMissing(); }
|
||||
});
|
||||
}
|
||||
} else {
|
||||
statsMissing.textContent = '';
|
||||
}
|
||||
|
||||
// Re-observe lazy images
|
||||
observeNewImages();
|
||||
}
|
||||
|
||||
function createCard(entry) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'gallery-card' + (entry.has_image ? '' : ' missing');
|
||||
card.setAttribute('role', 'listitem');
|
||||
card.setAttribute('tabindex', '0');
|
||||
card.setAttribute('aria-label', entry.name + (entry.has_image ? '' : ' (no image)'));
|
||||
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'card-image-wrapper';
|
||||
|
||||
if (entry.has_image) {
|
||||
const img = document.createElement('img');
|
||||
img.setAttribute('data-src', entry.image);
|
||||
img.alt = entry.name;
|
||||
img.loading = 'lazy';
|
||||
// Inline tiny placeholder color to avoid layout shift
|
||||
img.style.backgroundColor = '#1a2a3a';
|
||||
wrapper.appendChild(img);
|
||||
} else {
|
||||
wrapper.classList.add('placeholder');
|
||||
wrapper.innerHTML = '<span class="placeholder-icon" aria-hidden="true">📷</span>';
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'missing-badge';
|
||||
badge.textContent = 'no image';
|
||||
card.appendChild(badge);
|
||||
}
|
||||
|
||||
if (isNew(entry)) {
|
||||
const tag = document.createElement('span');
|
||||
tag.className = 'new-badge';
|
||||
tag.textContent = 'new';
|
||||
tag.title = 'Added in ' + entry.added;
|
||||
card.appendChild(tag);
|
||||
}
|
||||
|
||||
const nameEl = document.createElement('div');
|
||||
nameEl.className = 'card-name';
|
||||
nameEl.textContent = entry.name;
|
||||
nameEl.title = entry.name + (entry.added ? ' - added in ' + entry.added : '');
|
||||
|
||||
card.appendChild(wrapper);
|
||||
card.appendChild(nameEl);
|
||||
|
||||
// Click handler
|
||||
if (entry.has_image) {
|
||||
card.addEventListener('click', () => openLightbox(entry.name));
|
||||
card.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
openLightbox(entry.name);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
// ── Lazy Loading ───────────────────────────────────────
|
||||
function observeNewImages() {
|
||||
// Disconnect previous observer
|
||||
if (state.observer) state.observer.disconnect();
|
||||
|
||||
state.observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (entry.isIntersecting) {
|
||||
const img = entry.target;
|
||||
const src = img.getAttribute('data-src');
|
||||
if (src) {
|
||||
img.src = src;
|
||||
img.removeAttribute('data-src');
|
||||
img.addEventListener('load', () => img.classList.add('loaded'));
|
||||
img.addEventListener('error', () => {
|
||||
// On error, show placeholder
|
||||
img.parentElement.classList.add('placeholder');
|
||||
img.remove();
|
||||
});
|
||||
}
|
||||
state.observer.unobserve(img);
|
||||
}
|
||||
});
|
||||
},
|
||||
{
|
||||
rootMargin: '200px 0px',
|
||||
threshold: 0.01,
|
||||
}
|
||||
);
|
||||
|
||||
// Observe all images with data-src
|
||||
grid.querySelectorAll('img[data-src]').forEach((img) => {
|
||||
state.observer.observe(img);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Search ─────────────────────────────────────────────
|
||||
function debounce(fn, delay) {
|
||||
let timer;
|
||||
return function (...args) {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => fn.apply(this, args), delay);
|
||||
};
|
||||
}
|
||||
|
||||
/* The single place `state.filtered` is computed. Search, the two toggles and
|
||||
the sort all funnel through here, so they compose instead of overwriting one
|
||||
another -- searching used to clear a "missing images" view, and vice versa. */
|
||||
function applyView() {
|
||||
let list = state.entries;
|
||||
if (state.onlyMissing) list = list.filter((e) => !e.has_image);
|
||||
if (state.onlyNew) list = list.filter(isNew);
|
||||
if (state.searchTerm) {
|
||||
list = list.filter((e) => e.name.toLowerCase().includes(state.searchTerm));
|
||||
}
|
||||
|
||||
// The manifest is already name-sorted, so A-Z needs no work; sorting a copy
|
||||
// matters only for 'new', but both branches copy so `filtered` is never an
|
||||
// alias of `entries`.
|
||||
list = [...list];
|
||||
if (state.sort === 'new') {
|
||||
list.sort((a, b) => rankOf(b) - rankOf(a) || collator.compare(a.name, b.name));
|
||||
}
|
||||
state.filtered = list;
|
||||
|
||||
searchClear.classList.toggle('hidden', !state.searchTerm);
|
||||
if (newFilterBtn) newFilterBtn.setAttribute('aria-pressed', String(state.onlyNew));
|
||||
render();
|
||||
}
|
||||
|
||||
function doSearch(term) {
|
||||
state.searchTerm = term.trim().toLowerCase();
|
||||
applyView();
|
||||
}
|
||||
|
||||
function isNarrowed() {
|
||||
return Boolean(state.searchTerm) || state.onlyMissing || state.onlyNew;
|
||||
}
|
||||
|
||||
/* Resets every narrowing at once. The button for this shipped in the markup from
|
||||
the start but was never wired to anything -- a dead control, and the only exit
|
||||
from a filtered empty state that does not require guessing which control caused
|
||||
it. The sort is deliberately NOT reset: it is a view preference, not a filter. */
|
||||
function clearFilters() {
|
||||
state.searchTerm = '';
|
||||
state.onlyMissing = false;
|
||||
state.onlyNew = false;
|
||||
searchInput.value = '';
|
||||
if (newFilterBtn) newFilterBtn.classList.remove('is-active');
|
||||
applyView();
|
||||
}
|
||||
|
||||
const debouncedSearch = debounce(doSearch, 150);
|
||||
|
||||
searchInput.addEventListener('input', () => {
|
||||
debouncedSearch(searchInput.value);
|
||||
});
|
||||
|
||||
searchClear.addEventListener('click', () => {
|
||||
searchInput.value = '';
|
||||
doSearch('');
|
||||
searchInput.focus();
|
||||
});
|
||||
|
||||
if (clearFiltersBtn) {
|
||||
clearFiltersBtn.addEventListener('click', () => {
|
||||
clearFilters();
|
||||
searchInput.focus();
|
||||
});
|
||||
}
|
||||
|
||||
// ── Show missing ───────────────────────────────────────
|
||||
/* Was: it planted the literal text "missing entries" in the search box, which
|
||||
looked like a query the viewer had typed and could not be un-typed without
|
||||
clearing a real search. It is a toggle now, and it composes with the rest. */
|
||||
function toggleMissing() {
|
||||
state.onlyMissing = !state.onlyMissing;
|
||||
applyView();
|
||||
}
|
||||
|
||||
// ── Lightbox ───────────────────────────────────────────
|
||||
function openLightbox(name) {
|
||||
// Find entry index in filtered list
|
||||
state.lightboxIndex = state.filtered.findIndex(
|
||||
(e) => e.name === name && e.has_image
|
||||
);
|
||||
if (state.lightboxIndex === -1) return;
|
||||
updateLightbox();
|
||||
lightbox.classList.remove('hidden');
|
||||
document.body.style.overflow = 'hidden';
|
||||
lightboxClose.focus();
|
||||
window.addEventListener('keydown', handleLightboxKey);
|
||||
}
|
||||
|
||||
function closeLightbox() {
|
||||
lightbox.classList.add('hidden');
|
||||
document.body.style.overflow = '';
|
||||
state.lightboxIndex = -1;
|
||||
window.removeEventListener('keydown', handleLightboxKey);
|
||||
|
||||
// Refocus the card that was open
|
||||
const name = lightboxName.textContent;
|
||||
const cards = grid.querySelectorAll('.gallery-card');
|
||||
cards.forEach((card) => {
|
||||
if (card.querySelector('.card-name')?.textContent === name) {
|
||||
card.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function updateLightbox() {
|
||||
const entry = state.filtered[state.lightboxIndex];
|
||||
if (!entry) return;
|
||||
|
||||
lightboxImg.src = entry.image;
|
||||
lightboxImg.alt = entry.name;
|
||||
lightboxName.textContent = entry.name;
|
||||
|
||||
// Update nav button states
|
||||
lightboxPrev.disabled = state.lightboxIndex <= 0;
|
||||
lightboxNext.disabled = state.lightboxIndex >= state.filtered.length - 1;
|
||||
}
|
||||
|
||||
function lightboxPrevImage() {
|
||||
// Find previous entry with an image
|
||||
let idx = state.lightboxIndex - 1;
|
||||
while (idx >= 0) {
|
||||
if (state.filtered[idx].has_image) {
|
||||
state.lightboxIndex = idx;
|
||||
updateLightbox();
|
||||
return;
|
||||
}
|
||||
idx--;
|
||||
}
|
||||
}
|
||||
|
||||
function lightboxNextImage() {
|
||||
let idx = state.lightboxIndex + 1;
|
||||
while (idx < state.filtered.length) {
|
||||
if (state.filtered[idx].has_image) {
|
||||
state.lightboxIndex = idx;
|
||||
updateLightbox();
|
||||
return;
|
||||
}
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
|
||||
function handleLightboxKey(e) {
|
||||
switch (e.key) {
|
||||
case 'Escape':
|
||||
closeLightbox();
|
||||
break;
|
||||
case 'ArrowLeft':
|
||||
e.preventDefault();
|
||||
lightboxPrevImage();
|
||||
break;
|
||||
case 'ArrowRight':
|
||||
e.preventDefault();
|
||||
lightboxNextImage();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
lightboxClose.addEventListener('click', closeLightbox);
|
||||
lightboxPrev.addEventListener('click', lightboxPrevImage);
|
||||
lightboxNext.addEventListener('click', lightboxNextImage);
|
||||
|
||||
lightbox.addEventListener('click', (e) => {
|
||||
if (e.target === lightbox) closeLightbox();
|
||||
});
|
||||
|
||||
// ── Keyboard shortcut hint ─────────────────────────────
|
||||
document.addEventListener('keydown', (e) => {
|
||||
// Ctrl+K or / to focus search
|
||||
if ((e.ctrlKey && e.key === 'k') || (e.key === '/' && document.activeElement !== searchInput)) {
|
||||
e.preventDefault();
|
||||
searchInput.focus();
|
||||
searchInput.select();
|
||||
}
|
||||
});
|
||||
|
||||
// ── Sort & filter controls ─────────────────────────────
|
||||
/* Both controls are HIDDEN unless the manifest actually supports them: a sort
|
||||
with nothing to sort by, or a "New in ..." filter that is always present and
|
||||
sometimes empty, only teaches a viewer to ignore the control row. */
|
||||
function setupSortControls() {
|
||||
const stamped = state.rank.size > 0
|
||||
&& state.entries.some((e) => e.added);
|
||||
|
||||
if (sortGroup) sortGroup.hidden = !stamped;
|
||||
if (sortSelect) {
|
||||
if (stamped) {
|
||||
state.sort = loadSort();
|
||||
sortSelect.value = state.sort;
|
||||
sortSelect.addEventListener('change', () => {
|
||||
state.sort = sortSelect.value === 'new' ? 'new' : 'az';
|
||||
saveSort(state.sort);
|
||||
applyView();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (newFilterBtn) {
|
||||
const anyNew = stamped && state.entries.some(isNew);
|
||||
newFilterBtn.hidden = !anyNew;
|
||||
if (anyNew) {
|
||||
newFilterBtn.textContent = 'New in ' + state.version;
|
||||
newFilterBtn.addEventListener('click', () => {
|
||||
state.onlyNew = !state.onlyNew;
|
||||
newFilterBtn.classList.toggle('is-active', state.onlyNew);
|
||||
applyView();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Init ───────────────────────────────────────────────
|
||||
async function init() {
|
||||
try {
|
||||
const manifest = await loadManifest();
|
||||
loadingEl.classList.add('hidden');
|
||||
|
||||
// Update stats
|
||||
countTotal.textContent = manifest.total_entries || state.entries.length;
|
||||
|
||||
setupSortControls();
|
||||
applyView();
|
||||
|
||||
// Focus search on load if no hash
|
||||
if (!window.location.hash) {
|
||||
// Don't auto-focus on mobile to avoid keyboard popup
|
||||
if (window.innerWidth > 768) {
|
||||
searchInput.focus();
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
loadingEl.innerHTML = '<p style="color:#e06060">⚠ Failed to load gallery.</p>';
|
||||
}
|
||||
}
|
||||
|
||||
// Start when DOM is ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Identity Forge — Creature Sample Gallery</title>
|
||||
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><rect width='32' height='32' rx='7' fill='%231a1a2e'/><circle cx='16' cy='13' r='6.5' fill='%235b8def'/><path d='M6 27c1.5-5 5.5-7.5 10-7.5S24.5 22 26 27Z' fill='%237aa5ff'/></svg>">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<link rel="stylesheet" href="../shared/style.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -78,6 +78,6 @@
|
||||
</p>
|
||||
</footer>
|
||||
|
||||
<script src="gallery.js"></script>
|
||||
<script src="../shared/gallery.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -48,14 +48,17 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
# === GALLERY CONFIG — the only part that differs between the three copies ====
|
||||
GALLERY_KIND = "creatures"
|
||||
GALLERY_TITLE = "creature form"
|
||||
PAGE_FILES = ["index.html", "style.css", "gallery.js",
|
||||
"Krea2_IdentityForge_CreatureCycle.json"]
|
||||
PAGE_FILES = ["index.html", "Krea2_IdentityForge_CreatureCycle.json"]
|
||||
# ============================================================================
|
||||
|
||||
from build_manifest import entry_names, generate_manifest, normalize_name # noqa: E402
|
||||
from build_gallery_images import optimize_image # noqa: E402
|
||||
|
||||
GALLERY_SRC_DIR = Path(__file__).resolve().parent
|
||||
#: 2.6.0: the page assets all three galleries share, published to gallery/shared/.
|
||||
SHARED_SRC_DIR = GALLERY_SRC_DIR.parent / "shared"
|
||||
SHARED_FILES = ["style.css", "gallery.js"]
|
||||
SHARED_REL_DIR = "gallery/shared"
|
||||
BRANCH = "gh-pages"
|
||||
REL_DIR = f"gallery/{GALLERY_KIND}"
|
||||
|
||||
@@ -247,9 +250,15 @@ def main() -> int:
|
||||
(worktree / REL_DIR / fname).write_text(
|
||||
src.read_text(encoding="utf-8"), encoding="utf-8", newline="")
|
||||
|
||||
for fname in SHARED_FILES:
|
||||
target = worktree / SHARED_REL_DIR / fname
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text((SHARED_SRC_DIR / fname).read_text(encoding="utf-8"),
|
||||
encoding="utf-8", newline="")
|
||||
|
||||
# -A, not a bare add: a plain `git add` stages additions and
|
||||
# modifications but NOT deletions, so a prune would be silently undone.
|
||||
run("git", "add", "-A", REL_DIR, cwd=worktree)
|
||||
run("git", "add", "-A", REL_DIR, SHARED_REL_DIR, cwd=worktree)
|
||||
if not run("git", "status", "--porcelain", cwd=worktree):
|
||||
print("\nNothing changed on the branch.")
|
||||
return 0
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/* =============================================================
|
||||
Identity Forge — Archetype Gallery Script
|
||||
Identity Forge - Sample Gallery Script
|
||||
One file for the cosplay, archetype and creature galleries.
|
||||
Lazy-loading image grid with search, lightbox, keyboard nav.
|
||||
============================================================= */
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* =============================================================
|
||||
Identity Forge - Sample Gallery Styles
|
||||
Shared verbatim by the cosplay, archetype and creature galleries;
|
||||
see gallery/README.md before editing (a fix lands three times).
|
||||
One file for the cosplay, archetype and creature galleries
|
||||
(gallery/shared/, published next to each page; see gallery/README.md).
|
||||
Dark theme, tuned for browsing a large lazy-loaded grid.
|
||||
============================================================= */
|
||||
|
||||
@@ -202,6 +202,28 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* 2.6.0: the star sits over the art's top-right corner. */
|
||||
.if-picker-tile {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.if-picker-star {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
right: 6px;
|
||||
padding: 0 4px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--descrip-text, #999);
|
||||
font-size: 18px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.if-picker-star.on {
|
||||
color: #f5c518;
|
||||
}
|
||||
|
||||
.if-picker-tile:hover {
|
||||
filter: brightness(1.15);
|
||||
}
|
||||
@@ -211,6 +233,16 @@
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
/* 2.5.0: the entry the node currently holds. */
|
||||
.if-picker-tile.current {
|
||||
border-color: var(--if-picker-accent, #5c9eff);
|
||||
box-shadow: inset 0 0 0 1px var(--if-picker-accent, #5c9eff);
|
||||
}
|
||||
|
||||
.if-picker-franchise {
|
||||
width: 170px;
|
||||
}
|
||||
|
||||
.if-picker-tile-disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
|
||||
+325
-51
@@ -122,15 +122,90 @@ function tabLabel(tab) {
|
||||
return tab === TAB_ALL ? "All" : KIND_LABEL[tab] || tab;
|
||||
}
|
||||
|
||||
// --- search: substring, multi-token AND, case-insensitive -------------------
|
||||
// --- search: word-start, multi-token AND, case-insensitive -------------------
|
||||
//
|
||||
// 2.5.0: a token matches where a WORD starts in the description ("bow" finds
|
||||
// "bow tie" and "bowler hat", no longer "elbow" or "rainbow"), or anywhere in
|
||||
// the entry's name. A quoted phrase ("bow tie") is one token. SEARCH_ALSO widens
|
||||
// a few words to their synonyms and to the compounds the roster really uses
|
||||
// (scripts measured: "suit" alone missed 235 "bodysuit" entries under word-start).
|
||||
// Directional on purpose: "pants" finds trousers, "jeans" does not find slacks.
|
||||
|
||||
const SEARCH_ALSO = {
|
||||
pants: ["trousers", "slacks", "jeans", "sweatpants", "breeches"],
|
||||
trousers: ["pants", "slacks"],
|
||||
suit: ["bodysuit", "jumpsuit", "catsuit", "supersuit", "tracksuit", "spacesuit", "swimsuit", "wetsuit", "plugsuit", "batsuit", "exosuit"],
|
||||
sword: ["longsword", "greatsword", "broadsword", "katana", "sabre", "saber", "rapier", "scimitar", "cutlass"],
|
||||
coat: ["waistcoat", "tailcoat", "overcoat", "greatcoat", "raincoat", "trenchcoat", "longcoat"],
|
||||
dress: ["minidress", "sundress", "gown"],
|
||||
skirt: ["miniskirt", "overskirt"],
|
||||
shirt: ["sweatshirt", "undershirt", "overshirt"],
|
||||
glasses: ["sunglasses", "spectacles", "eyeglasses"],
|
||||
gun: ["shotgun", "handgun", "minigun", "railgun", "pistol", "rifle", "revolver", "blaster"],
|
||||
band: ["headband", "armband", "wristband", "hairband"],
|
||||
sweater: ["jumper", "pullover"],
|
||||
sneakers: ["trainers"],
|
||||
trainers: ["sneakers"],
|
||||
gray: ["grey"],
|
||||
grey: ["gray"],
|
||||
blonde: ["blond"],
|
||||
armor: ["armour"],
|
||||
armour: ["armor"],
|
||||
color: ["colour"],
|
||||
colour: ["color"],
|
||||
mustache: ["moustache"],
|
||||
moustache: ["mustache"],
|
||||
saber: ["sabre"],
|
||||
sabre: ["saber"],
|
||||
robot: ["android", "droid", "cyborg", "mech"],
|
||||
};
|
||||
|
||||
// Accents and special letters fold to their plain-keyboard form on both sides,
|
||||
// so "dia", "día" and "Día" all find Día de los Muertos, "pokemon" finds Pokémon.
|
||||
const FOLD_EXTRA = { "ø": "o", "æ": "ae", "œ": "oe", "ß": "ss", "ł": "l", "đ": "d", "ð": "d", "þ": "th", "ı": "i" };
|
||||
|
||||
function fold(text) {
|
||||
return String(text || "").toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "")
|
||||
.replace(/[øæœßłđðþı]/g, (c) => FOLD_EXTRA[c]);
|
||||
}
|
||||
|
||||
const foldedEntries = new WeakMap(); // entry -> { name, haystack }, folded once
|
||||
|
||||
function foldedEntry(entry) {
|
||||
let f = foldedEntries.get(entry);
|
||||
if (!f) {
|
||||
f = { name: fold(entry.name), haystack: fold(entry.haystack) };
|
||||
foldedEntries.set(entry, f);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
function tokenize(query) {
|
||||
return String(query || "").trim().toLowerCase().split(/\s+/).filter(Boolean);
|
||||
const tokens = [];
|
||||
for (const m of fold(query).matchAll(/"([^"]*)"|(\S+)/g)) {
|
||||
const token = (m[1] ?? m[2]).trim().replace(/\s+/g, " ");
|
||||
if (token) tokens.push(token);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const tokenPatterns = new Map(); // token -> RegExp, built once per distinct token
|
||||
|
||||
function tokenPattern(token) {
|
||||
let re = tokenPatterns.get(token);
|
||||
if (!re) {
|
||||
const words = [token, ...(SEARCH_ALSO[token] || [])].map(escapeRegExp);
|
||||
re = new RegExp("(?:^|[^a-z0-9])(?:" + words.join("|") + ")");
|
||||
tokenPatterns.set(token, re);
|
||||
}
|
||||
return re;
|
||||
}
|
||||
|
||||
function matchesQuery(entry, tokens) {
|
||||
if (!tokens.length) return true;
|
||||
return tokens.every((token) => entry.haystack.includes(token));
|
||||
const { name, haystack } = foldedEntry(entry);
|
||||
return tokens.every((token) => name.includes(token) || tokenPattern(token).test(haystack));
|
||||
}
|
||||
|
||||
// --- trait facets -------------------------------------------------------------
|
||||
@@ -177,8 +252,21 @@ function matchesGender(entry, gender) {
|
||||
}
|
||||
|
||||
// Franchise filter (2.2.0). Only cosplayers carry a franchise, so picking one
|
||||
// narrows to cosplayers. Options come from the loaded roster, grouped by category.
|
||||
const FRANCHISE_ALL = "All franchises";
|
||||
// narrows to cosplayers. 2.5.0: a type-to-filter box (there are hundreds of
|
||||
// franchises) with the franchises as suggestions. Text that names a franchise
|
||||
// exactly keeps only that one; any other text keeps every franchise containing it
|
||||
// ("star" -> Star Wars and Star Trek). Empty means all.
|
||||
const FRANCHISE_ALL = "";
|
||||
let pickerSerial = 0; // unique datalist ids, one per picker
|
||||
|
||||
function franchiseMatcher(text, entries) {
|
||||
const q = fold(text).trim();
|
||||
if (!q) return null;
|
||||
const exact = entries.some((e) => e.franchise && fold(e.franchise) === q);
|
||||
return exact
|
||||
? (e) => Boolean(e.franchise) && fold(e.franchise) === q
|
||||
: (e) => Boolean(e.franchise) && fold(e.franchise).includes(q);
|
||||
}
|
||||
|
||||
function franchiseGroups(entries) {
|
||||
const groups = new Map();
|
||||
@@ -258,6 +346,39 @@ function savePreviewPref(value) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- starred entries (2.6.0) -------------------------------------------------
|
||||
// A per-browser favourites list, keyed "kind:name" so one set serves every
|
||||
// picker. localStorage can be missing or throw (private window, blocked site
|
||||
// data); stars then last only until the page reloads.
|
||||
|
||||
const STARRED_KEY = "identity_forge.picker.starred";
|
||||
let starred = null;
|
||||
|
||||
function starKey(entry) {
|
||||
return entry.kind + ":" + entry.name;
|
||||
}
|
||||
|
||||
function starredSet() {
|
||||
if (starred) return starred;
|
||||
starred = new Set();
|
||||
try {
|
||||
const saved = JSON.parse(window.localStorage.getItem(STARRED_KEY) || "[]");
|
||||
if (Array.isArray(saved)) for (const key of saved) if (typeof key === "string") starred.add(key);
|
||||
} catch (_) { /* unreadable or blocked storage: start empty */ }
|
||||
return starred;
|
||||
}
|
||||
|
||||
function toggleStar(entry) {
|
||||
const set = starredSet();
|
||||
const key = starKey(entry);
|
||||
if (set.has(key)) set.delete(key);
|
||||
else set.add(key);
|
||||
try {
|
||||
window.localStorage.setItem(STARRED_KEY, JSON.stringify([...set]));
|
||||
} catch (_) { /* best-effort, see above */ }
|
||||
return set.has(key);
|
||||
}
|
||||
|
||||
//: kind -> Promise<Map<name, image-relative-path>>, held ONLY while a fetch
|
||||
//: for that kind is in flight -- cleared the instant it settles, success or
|
||||
//: failure, via `.finally()`. This is deliberately NOT a cache of the
|
||||
@@ -359,6 +480,7 @@ class IdentityForgePicker {
|
||||
this.facet = FACET_ALL;
|
||||
this.gender = GENDER_ANY;
|
||||
this.franchise = FRANCHISE_ALL;
|
||||
this.starredOnly = false;
|
||||
this.showPreviews = loadPreviewPref();
|
||||
this.focusIndex = 0;
|
||||
this.visible = [];
|
||||
@@ -370,6 +492,9 @@ class IdentityForgePicker {
|
||||
open() {
|
||||
if (this.overlay) return;
|
||||
this.previousFocus = document.activeElement;
|
||||
// 2.5.0: reopen on the node's current pick, so a long filtered list keeps
|
||||
// its place between picks instead of jumping back to the top.
|
||||
this._revealCurrent = true;
|
||||
try {
|
||||
this.build();
|
||||
document.body.appendChild(this.overlay);
|
||||
@@ -488,12 +613,7 @@ class IdentityForgePicker {
|
||||
search.setAttribute("aria-label", "Search the roster by name, franchise, or trait");
|
||||
search.addEventListener("input", (event) => {
|
||||
this.query = event.target.value || "";
|
||||
this.focusIndex = 0;
|
||||
if (this._searchTimer) clearTimeout(this._searchTimer);
|
||||
this._searchTimer = setTimeout(() => {
|
||||
this._searchTimer = null;
|
||||
this.renderGrid();
|
||||
}, 80);
|
||||
this.scheduleRender();
|
||||
});
|
||||
search.value = this.query; // restore the surviving query (see close())
|
||||
this.searchInput = search;
|
||||
@@ -537,15 +657,23 @@ class IdentityForgePicker {
|
||||
});
|
||||
this.genderSelect = genderSelect;
|
||||
|
||||
const franchiseSelect = document.createElement("select");
|
||||
franchiseSelect.className = "if-picker-facet";
|
||||
franchiseSelect.setAttribute("aria-label", "Filter by franchise");
|
||||
franchiseSelect.addEventListener("change", () => {
|
||||
this.franchise = franchiseSelect.value;
|
||||
this.focusIndex = 0;
|
||||
this.renderGrid();
|
||||
const franchiseInput = document.createElement("input");
|
||||
franchiseInput.type = "search";
|
||||
franchiseInput.className = "if-picker-facet if-picker-franchise";
|
||||
franchiseInput.placeholder = "Franchise...";
|
||||
franchiseInput.spellcheck = false;
|
||||
franchiseInput.autocomplete = "off";
|
||||
franchiseInput.setAttribute("aria-label", "Filter by franchise (type part of a name)");
|
||||
const franchiseList = document.createElement("datalist");
|
||||
franchiseList.id = "if-picker-franchises-" + ++pickerSerial;
|
||||
franchiseInput.setAttribute("list", franchiseList.id);
|
||||
franchiseInput.value = this.franchise;
|
||||
franchiseInput.addEventListener("input", () => {
|
||||
this.franchise = franchiseInput.value;
|
||||
this.scheduleRender();
|
||||
});
|
||||
this.franchiseSelect = franchiseSelect;
|
||||
this.franchiseInput = franchiseInput;
|
||||
this.franchiseList = franchiseList;
|
||||
this.fillFranchiseOptions();
|
||||
|
||||
const previewLabel = document.createElement("label");
|
||||
@@ -561,6 +689,20 @@ class IdentityForgePicker {
|
||||
previewLabel.append(previewCheckbox, document.createTextNode(" Show preview images"));
|
||||
this.previewCheckbox = previewCheckbox;
|
||||
|
||||
const starredLabel = document.createElement("label");
|
||||
starredLabel.className = "if-picker-preview-toggle";
|
||||
starredLabel.title = "Star an entry with the star on its card (or the S key).";
|
||||
const starredCheckbox = document.createElement("input");
|
||||
starredCheckbox.type = "checkbox";
|
||||
starredCheckbox.checked = this.starredOnly;
|
||||
starredCheckbox.addEventListener("change", () => {
|
||||
this.starredOnly = starredCheckbox.checked;
|
||||
this.focusIndex = 0;
|
||||
this.renderGrid();
|
||||
});
|
||||
starredLabel.append(starredCheckbox, document.createTextNode(" Starred only"));
|
||||
this.starredCheckbox = starredCheckbox;
|
||||
|
||||
const close = document.createElement("button");
|
||||
close.type = "button";
|
||||
close.className = "if-picker-btn if-picker-close";
|
||||
@@ -568,7 +710,25 @@ class IdentityForgePicker {
|
||||
close.setAttribute("aria-label", "Close (" + this.config.title + ")");
|
||||
close.addEventListener("click", () => this.close());
|
||||
|
||||
header.append(search, facet, genderSelect, franchiseSelect, count, previewLabel, close);
|
||||
// 2.5.0: queue one run per matching character, so a filtered set can be
|
||||
// cycled through in one go. Shown only while filtering (never the whole roster).
|
||||
const queueAll = document.createElement("button");
|
||||
queueAll.type = "button";
|
||||
queueAll.className = "if-picker-btn if-picker-queue-all";
|
||||
queueAll.title = "Queue one run for each matching entry, then put your current pick back.";
|
||||
queueAll.addEventListener("click", () => this.queueEach());
|
||||
this.queueAllButton = queueAll;
|
||||
|
||||
// 2.5.0: trait and franchise filters match cosplayers only, and creatures carry
|
||||
// no gender, so a node shows only the filters that can narrow what it can pick.
|
||||
const kind = this.config.kind;
|
||||
header.append(
|
||||
search,
|
||||
...(kind === "cosplayer" ? [facet] : []),
|
||||
...(kind !== "creature" ? [genderSelect] : []),
|
||||
...(kind === "cosplayer" ? [franchiseInput, franchiseList] : []),
|
||||
count, queueAll, starredLabel, previewLabel, close,
|
||||
);
|
||||
|
||||
const notice = document.createElement("div");
|
||||
notice.className = "if-picker-notice";
|
||||
@@ -629,7 +789,9 @@ class IdentityForgePicker {
|
||||
footer.className = "if-picker-footer";
|
||||
footer.textContent =
|
||||
"Searches roster entries (cosplayers, archetypes, creatures) — not the randomizable "
|
||||
+ "field pools on the main node. Arrow keys move, Enter selects, Escape closes.";
|
||||
+ "field pools on the main node. Words match from their start; \"quote a phrase\"; "
|
||||
+ "a few words also find synonyms (pants finds trousers). "
|
||||
+ "Arrow keys move, Enter selects, Escape closes.";
|
||||
|
||||
dialog.append(header, notice, links, tabs, grid, footer);
|
||||
overlay.appendChild(dialog);
|
||||
@@ -697,7 +859,16 @@ class IdentityForgePicker {
|
||||
else if (event.key === "ArrowUp") next = this.focusIndex - columns;
|
||||
else if (event.key === "Home") next = 0;
|
||||
else if (event.key === "End") next = lastIndex;
|
||||
else if (event.key === "Enter") {
|
||||
else if ((event.key === "s" || event.key === "S") && !/^(INPUT|SELECT|TEXTAREA)$/.test(event.target.tagName)) {
|
||||
const entry = this.visible[this.focusIndex];
|
||||
if (entry) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggleStar(entry);
|
||||
this.renderGrid();
|
||||
}
|
||||
return;
|
||||
} else if (event.key === "Enter") {
|
||||
const entry = this.visible[this.focusIndex];
|
||||
if (entry) {
|
||||
event.preventDefault();
|
||||
@@ -722,11 +893,11 @@ class IdentityForgePicker {
|
||||
return Math.max(1, Math.floor(width / 210));
|
||||
}
|
||||
|
||||
highlight() {
|
||||
highlight(block = "nearest") {
|
||||
if (!this.grid) return;
|
||||
const next = this.visible.length ? this.grid.children[this.focusIndex] || null : null;
|
||||
if (this._focused === next) {
|
||||
if (next && next.scrollIntoView) next.scrollIntoView({ block: "nearest" });
|
||||
if (next && next.scrollIntoView) next.scrollIntoView({ block });
|
||||
return;
|
||||
}
|
||||
if (this._focused) {
|
||||
@@ -737,7 +908,7 @@ class IdentityForgePicker {
|
||||
if (next) {
|
||||
next.classList.add("focused");
|
||||
next.setAttribute("aria-selected", "true");
|
||||
if (next.scrollIntoView) next.scrollIntoView({ block: "nearest" });
|
||||
if (next.scrollIntoView) next.scrollIntoView({ block });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -796,30 +967,103 @@ class IdentityForgePicker {
|
||||
if (this.gender !== GENDER_ANY) {
|
||||
list = list.filter((entry) => matchesGender(entry, this.gender));
|
||||
}
|
||||
if (this.franchise !== FRANCHISE_ALL) {
|
||||
list = list.filter((entry) => entry.franchise === this.franchise);
|
||||
const inFranchise = franchiseMatcher(this.franchise, roster);
|
||||
if (inFranchise) list = list.filter(inFranchise);
|
||||
if (this.starredOnly) {
|
||||
const set = starredSet();
|
||||
list = list.filter((entry) => set.has(starKey(entry)));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/** (Re)build the franchise dropdown; a no-op until the roster has loaded. */
|
||||
/** Fill the franchise suggestions (category as the label); a no-op until the roster has loaded. */
|
||||
fillFranchiseOptions() {
|
||||
const select = this.franchiseSelect;
|
||||
if (!select || (roster && select.options.length > 1)) return;
|
||||
const all = document.createElement("option");
|
||||
all.value = all.textContent = FRANCHISE_ALL;
|
||||
select.replaceChildren(all);
|
||||
for (const [category, names] of franchiseGroups(roster || [])) {
|
||||
const group = document.createElement("optgroup");
|
||||
group.label = category;
|
||||
const list = this.franchiseList;
|
||||
if (!list || !roster || list.options.length) return;
|
||||
for (const [category, names] of franchiseGroups(roster)) {
|
||||
for (const name of names) {
|
||||
const option = document.createElement("option");
|
||||
option.value = option.textContent = name;
|
||||
group.appendChild(option);
|
||||
option.value = name;
|
||||
option.label = category;
|
||||
list.appendChild(option);
|
||||
}
|
||||
select.appendChild(group);
|
||||
}
|
||||
select.value = this.franchise;
|
||||
}
|
||||
|
||||
/** Re-render shortly after typing stops, so each keystroke does not rebuild the grid. */
|
||||
scheduleRender() {
|
||||
this.focusIndex = 0;
|
||||
if (this._searchTimer) clearTimeout(this._searchTimer);
|
||||
this._searchTimer = setTimeout(() => {
|
||||
this._searchTimer = null;
|
||||
this.renderGrid();
|
||||
}, 80);
|
||||
}
|
||||
|
||||
/** The visible entries this node can take -- what "Queue each" runs. */
|
||||
queueableEntries() {
|
||||
return this.visible.filter((entry) => entry.kind === this.config.kind);
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue one run per matching entry, then restore the node's own pick.
|
||||
* Each app.queuePrompt() call snapshots the graph, so setting the widget and
|
||||
* awaiting the call in turn gives one job per character.
|
||||
*/
|
||||
async queueEach() {
|
||||
const entries = this.queueableEntries();
|
||||
const node = this.config.node;
|
||||
const widget = findWidget(node, this.config.targetWidgetName);
|
||||
if (!entries.length || !widget || this._queueing) return;
|
||||
if (typeof app.queuePrompt !== "function") {
|
||||
alert("This ComfyUI frontend does not expose app.queuePrompt, so runs cannot be queued from here.");
|
||||
return;
|
||||
}
|
||||
const noun = entries.length === 1 ? "run" : "runs";
|
||||
if (!confirm("Queue " + entries.length + " " + noun + ", one for each matching entry?")) return;
|
||||
this._queueing = true;
|
||||
const original = widget.value;
|
||||
const button = this.queueAllButton;
|
||||
let queued = 0;
|
||||
try {
|
||||
for (const entry of entries) {
|
||||
widget.value = entry.name;
|
||||
// false = ComfyUI was already building another prompt and only queued ours
|
||||
// for later, when the widget would hold a different name. Stop rather than
|
||||
// queue the wrong character.
|
||||
if ((await app.queuePrompt(0, 1)) === false) break;
|
||||
queued += 1;
|
||||
if (button && button.isConnected) button.textContent = "Queued " + queued + " / " + entries.length;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[IdentityForgePicker] queueing failed", error);
|
||||
} finally {
|
||||
setWidgetValue(node, widget, original);
|
||||
this.resyncFranchiseFilter();
|
||||
if (typeof node.setDirtyCanvas === "function") node.setDirtyCanvas(true, true);
|
||||
this._queueing = false;
|
||||
if (queued < entries.length) {
|
||||
alert("Queued " + queued + " of " + entries.length + " runs; the rest were not queued.");
|
||||
}
|
||||
this.updateQueueButton();
|
||||
}
|
||||
}
|
||||
|
||||
updateQueueButton() {
|
||||
const button = this.queueAllButton;
|
||||
if (!button || this._queueing) return;
|
||||
const n = this.isFiltering() ? this.queueableEntries().length : 0;
|
||||
button.style.display = n ? "" : "none";
|
||||
button.textContent = "Queue each (" + n + ")";
|
||||
}
|
||||
|
||||
/** Re-run franchise_filter's callback so the node's pick stays in its combo list. */
|
||||
resyncFranchiseFilter() {
|
||||
if (!this.config.franchiseFilterWidgetName) return;
|
||||
const filterWidget = findWidget(this.config.node, this.config.franchiseFilterWidgetName);
|
||||
if (filterWidget && typeof filterWidget.callback === "function") {
|
||||
filterWidget.callback(filterWidget.value);
|
||||
}
|
||||
}
|
||||
|
||||
/** The grid's contents: the query/facet matches, narrowed to the active tab. */
|
||||
@@ -841,7 +1085,7 @@ class IdentityForgePicker {
|
||||
/** True while anything is narrowing the roster -- when the counts are worth showing. */
|
||||
isFiltering() {
|
||||
return Boolean(tokenize(this.query).length) || this.facet !== FACET_ALL
|
||||
|| this.gender !== GENDER_ANY || this.franchise !== FRANCHISE_ALL;
|
||||
|| this.gender !== GENDER_ANY || Boolean(String(this.franchise).trim()) || this.starredOnly;
|
||||
}
|
||||
|
||||
renderGrid() {
|
||||
@@ -863,6 +1107,19 @@ class IdentityForgePicker {
|
||||
if (this.count) {
|
||||
this.count.textContent = this.visible.length + (this.visible.length === 1 ? " result" : " results");
|
||||
}
|
||||
this.updateQueueButton();
|
||||
|
||||
const current = findWidget(this.config.node, this.config.targetWidgetName)?.value;
|
||||
let reveal = false;
|
||||
// Only once the dialog is on the page: build() renders before it is attached.
|
||||
if (this._revealCurrent && this.overlay && this.overlay.isConnected) {
|
||||
this._revealCurrent = false;
|
||||
const index = this.visible.findIndex((e) => e.kind === this.config.kind && e.name === current);
|
||||
if (index > -1) {
|
||||
this.focusIndex = index;
|
||||
reveal = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.visible.length) {
|
||||
const empty = document.createElement("div");
|
||||
@@ -871,7 +1128,9 @@ class IdentityForgePicker {
|
||||
// answer -- say whether the same query hits another category, and make
|
||||
// getting there one click rather than a hunt across the tab strip.
|
||||
const elsewhere = this.activeTab === TAB_ALL ? 0 : matching.length;
|
||||
if (this.query && this.activeTab === TAB_ALL) {
|
||||
if (this.starredOnly && !starredSet().size) {
|
||||
empty.textContent = "Nothing starred yet. Click the star on a card (or press S) to keep it here.";
|
||||
} else if (this.query && this.activeTab === TAB_ALL) {
|
||||
empty.textContent = 'Nothing matches "' + this.query + '".';
|
||||
} else if (this.query) {
|
||||
empty.textContent = 'No ' + tabLabel(this.activeTab).toLowerCase()
|
||||
@@ -923,10 +1182,12 @@ class IdentityForgePicker {
|
||||
|
||||
const fragment = document.createDocumentFragment();
|
||||
this.visible.forEach((entry, index) => {
|
||||
fragment.appendChild(this.buildTile(entry, index));
|
||||
const tile = this.buildTile(entry, index);
|
||||
if (entry.kind === this.config.kind && entry.name === current) tile.classList.add("current");
|
||||
fragment.appendChild(tile);
|
||||
});
|
||||
this.grid.appendChild(fragment);
|
||||
this.highlight();
|
||||
this.highlight(reveal ? "center" : "nearest");
|
||||
|
||||
if (this.showPreviews) {
|
||||
// One manifest fetch per kind actually shown, not per card.
|
||||
@@ -999,7 +1260,24 @@ class IdentityForgePicker {
|
||||
chips.appendChild(span);
|
||||
}
|
||||
|
||||
tile.append(art, name, sub, chips);
|
||||
const star = document.createElement("button");
|
||||
star.type = "button";
|
||||
star.tabIndex = -1; // keyboard users press S on the focused card instead
|
||||
star.className = "if-picker-star";
|
||||
const paintStar = (on) => {
|
||||
star.textContent = String.fromCharCode(on ? 0x2605 : 0x2606); // filled / outline star
|
||||
star.classList.toggle("on", on);
|
||||
star.setAttribute("aria-pressed", on ? "true" : "false");
|
||||
star.setAttribute("aria-label", (on ? "Unstar " : "Star ") + entry.name);
|
||||
};
|
||||
paintStar(starredSet().has(starKey(entry)));
|
||||
star.addEventListener("click", (event) => {
|
||||
event.stopPropagation(); // starring is not picking
|
||||
paintStar(toggleStar(entry));
|
||||
if (this.starredOnly) this.renderGrid();
|
||||
});
|
||||
|
||||
tile.append(art, star, name, sub, chips);
|
||||
|
||||
if (!selectable) {
|
||||
tile.title = "Browsing only — open the " + KIND_LABEL[entry.kind].slice(0, -1)
|
||||
@@ -1026,12 +1304,7 @@ class IdentityForgePicker {
|
||||
// its own current value recomputes that rule with the new selection,
|
||||
// reusing the exact logic in identity_forge_cosplayer.js rather than
|
||||
// duplicating it.
|
||||
if (this.config.franchiseFilterWidgetName) {
|
||||
const filterWidget = findWidget(node, this.config.franchiseFilterWidgetName);
|
||||
if (filterWidget && typeof filterWidget.callback === "function") {
|
||||
filterWidget.callback(filterWidget.value);
|
||||
}
|
||||
}
|
||||
this.resyncFranchiseFilter();
|
||||
if (typeof node.setDirtyCanvas === "function") node.setDirtyCanvas(true, true);
|
||||
} catch (error) {
|
||||
console.error("[IdentityForgePicker] selection failed", error);
|
||||
@@ -1276,5 +1549,6 @@ export const __testing = {
|
||||
roster = null;
|
||||
rosterPromise = null;
|
||||
manifestFetches.clear();
|
||||
starred = null;
|
||||
},
|
||||
};
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -26,6 +26,9 @@ const NO_CHARACTERS = "(no characters saved)";
|
||||
//: yet" are different situations that used to render identically, so a failed
|
||||
//: fetch was indistinguishable from an empty vault.
|
||||
const VAULT_UNAVAILABLE = "(vault unavailable — press Refresh)";
|
||||
//: 2.6.0: mirrors _RANDOM in nodes/identity_forge_vault_load.py; last option
|
||||
//: whenever the vault has entries, so Refresh must keep it.
|
||||
const RANDOM_CHARACTER = "(random saved character)";
|
||||
//: First widget this file adds; its presence is the re-entry guard in
|
||||
//: `setupVaultLoad`. See js/identity_forge.js.
|
||||
const REFRESH_LABEL = "🔄 Refresh";
|
||||
@@ -87,7 +90,7 @@ function updatePreview(node) {
|
||||
if (!el) return;
|
||||
const w = getCharacterWidget(node);
|
||||
const name = w && w.value;
|
||||
if (!name || name === NO_CHARACTERS) {
|
||||
if (!name || name === NO_CHARACTERS || name === RANDOM_CHARACTER) {
|
||||
el.style.display = "none";
|
||||
el.removeAttribute("src");
|
||||
return;
|
||||
@@ -104,7 +107,7 @@ function applyCharacterList(node, characters) {
|
||||
list = [VAULT_UNAVAILABLE];
|
||||
} else {
|
||||
const names = characters.map((c) => (typeof c === "string" ? c : c.name));
|
||||
list = names.length ? names : [NO_CHARACTERS];
|
||||
list = names.length ? [...names, RANDOM_CHARACTER] : [NO_CHARACTERS];
|
||||
}
|
||||
setComboValues(w, list);
|
||||
if (!list.includes(w.value)) w.value = list[0];
|
||||
|
||||
@@ -43,6 +43,7 @@ MAX_MANIFEST_BYTES = 8 * 1024 * 1024
|
||||
TIMEOUT = 15
|
||||
|
||||
_ETAG = ".etag"
|
||||
_RASTER = (".jpg", ".jpeg", ".png", ".webp")
|
||||
|
||||
|
||||
class GalleryError(Exception):
|
||||
@@ -103,7 +104,10 @@ def _fetch(url: str, path: Path, max_age: float, limit: int,
|
||||
except (OSError, GalleryError, ValueError) as exc: # URLError is an OSError
|
||||
failure = exc
|
||||
if path.is_file():
|
||||
return path # offline or failing: what we had before
|
||||
# Offline or failing: serve what we had, and wait out another max_age before
|
||||
# retrying, or every thumbnail request would wait out a timeout again (2.6.0).
|
||||
os.utime(path)
|
||||
return path
|
||||
raise GalleryError(f"{url} unavailable and not cached: {failure}")
|
||||
|
||||
|
||||
@@ -150,6 +154,9 @@ def _listed_images(kind: str, root: Path, opener=None) -> "frozenset[str]":
|
||||
def image_path(kind: str, relative: str, root: Path, opener=None) -> Path:
|
||||
"""The cached file for one manifest-listed image, downloading it if needed."""
|
||||
_check_kind(kind)
|
||||
# Served from ComfyUI's own origin, so only raster images: an SVG can carry script.
|
||||
if not relative.lower().endswith(_RASTER):
|
||||
raise GalleryError(f"{relative!r} is not a raster image")
|
||||
if relative not in _listed_images(kind, root, opener):
|
||||
raise GalleryError(f"{relative!r} is not in the {kind} manifest")
|
||||
target = (root / kind / relative).resolve()
|
||||
|
||||
+10
-5
@@ -4926,9 +4926,11 @@ def roll_field_values(widgets: dict[str, Any], seed: int) -> dict[str, str]:
|
||||
|
||||
1.7.0: "Roll + lock all" used to pick each dropdown uniformly in JS, so it ignored
|
||||
the weights and could lock a pair the engine forbids. Fields the run left absent
|
||||
are omitted; the frontend locks those to "None".
|
||||
are omitted; the frontend locks those to "None". Every input the button sends is a
|
||||
dropdown, so non-text values are dropped (2.6.0: ``{"age": 3.5}`` raised a 500).
|
||||
"""
|
||||
_, json_output, _ = run_identity_forge({**widgets, "seed": seed})
|
||||
text = {name: value for name, value in widgets.items() if isinstance(value, str)}
|
||||
_, json_output, _ = run_identity_forge({**text, "seed": seed})
|
||||
return {name: value for name, value in _parse_archetype_json(json_output).items()
|
||||
if name in FIELD_DEFINITIONS and name not in _HIDDEN_FIELDS
|
||||
and name not in _CONTROL_FIELDS}
|
||||
@@ -5102,10 +5104,13 @@ if _COMFY_AVAILABLE:
|
||||
"natural-language prose and structured JSON.",
|
||||
inputs=inputs,
|
||||
outputs=[
|
||||
io.String.Output(display_name="prompt_text"),
|
||||
io.String.Output(display_name="prompt_json"),
|
||||
io.String.Output(display_name="prompt_text",
|
||||
tooltip="The full description as prose. Wire into CLIPTextEncode."),
|
||||
io.String.Output(display_name="prompt_json",
|
||||
tooltip="The resolved character as JSON. Wire into a sheet node, Vault Save, or another Identity Forge's 'archetype_json' to reuse the person."),
|
||||
# Appended last (1.8.0) so links on slots 0 and 1 stay intact.
|
||||
io.String.Output(display_name="subject_text"),
|
||||
io.String.Output(display_name="subject_text",
|
||||
tooltip="The person and outfit only, without the scene, lighting or framing."),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@@ -40,14 +40,14 @@ try:
|
||||
from .identity_forge import FIELD_DEFINITIONS
|
||||
from .identity_forge_turnaround import (
|
||||
_FRAMINGS, _forge_class, _unwrap, document_fields, document_meta,
|
||||
character_seed, parse_document, release_fields, replay_base,
|
||||
character_seed, parse_document, pin_framing, release_fields, replay_base,
|
||||
)
|
||||
except ImportError: # pragma: no cover - standalone/test context
|
||||
from data.constraints import FIELD_FAMILIES, lock_clash
|
||||
from nodes.identity_forge import FIELD_DEFINITIONS
|
||||
from nodes.identity_forge_turnaround import (
|
||||
_FRAMINGS, _forge_class, _unwrap, document_fields, document_meta,
|
||||
character_seed, parse_document, release_fields, replay_base,
|
||||
character_seed, parse_document, pin_framing, release_fields, replay_base,
|
||||
)
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
@@ -115,14 +115,11 @@ def resolve_age_progression(
|
||||
meta = document_meta(document)
|
||||
fields = document_fields(document)
|
||||
base = replay_base(character_json)
|
||||
# A close-up refuses a horizon-line composition and a full-standing pose. 2.6.0:
|
||||
# the one-view path below replays the released document too, not the original.
|
||||
pin_framing(base, document, character_json, _FRAMINGS.get(framing_name, ""))
|
||||
# Released fields (skin detail at 70, say) redraw per character, not one shared draw.
|
||||
base["seed"] = character_seed(character_json, "age")
|
||||
framing = _FRAMINGS.get(framing_name, "")
|
||||
if framing:
|
||||
base["shot_type"] = framing
|
||||
# A close-up refuses a horizon-line composition and a full-standing pose.
|
||||
release_fields(document, {name for name, value in fields.items()
|
||||
if lock_clash("shot_type", framing, {name: value})})
|
||||
|
||||
character_age = fields.get("age", "")
|
||||
if meta.get("covers_face") or not character_age.isdigit():
|
||||
|
||||
@@ -269,7 +269,10 @@ if _COMFY_AVAILABLE:
|
||||
"through unchanged.",
|
||||
),
|
||||
],
|
||||
outputs=[io.String.Output(display_name="character_json")],
|
||||
outputs=[io.String.Output(
|
||||
display_name="character_json",
|
||||
tooltip="The preset as JSON. Wire into Identity Forge's 'archetype_json', or into another preset's 'upstream' to stack them.",
|
||||
)],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -1035,7 +1035,10 @@ if _COMFY_AVAILABLE:
|
||||
"a specific character is picked.",
|
||||
),
|
||||
],
|
||||
outputs=[io.String.Output(display_name="character_json")],
|
||||
outputs=[io.String.Output(
|
||||
display_name="character_json",
|
||||
tooltip="The preset as JSON. Wire into Identity Forge's 'archetype_json', or into another preset's 'upstream' to stack them.",
|
||||
)],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -477,7 +477,10 @@ if _COMFY_AVAILABLE:
|
||||
"upstream through unchanged.",
|
||||
),
|
||||
],
|
||||
outputs=[io.String.Output(display_name="character_json")],
|
||||
outputs=[io.String.Output(
|
||||
display_name="character_json",
|
||||
tooltip="The preset as JSON. Wire into Identity Forge's 'archetype_json', or into another preset's 'upstream' to stack them.",
|
||||
)],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -34,10 +34,12 @@ except ImportError: # pragma: no cover - exercised only outside ComfyUI
|
||||
_COMFY_AVAILABLE = False
|
||||
|
||||
try:
|
||||
from .identity_forge_turnaround import _FRAMINGS, _forge_class, _unwrap, replay_base
|
||||
from .identity_forge_turnaround import (
|
||||
_FRAMINGS, _forge_class, _unwrap, parse_document, pin_framing, replay_base,
|
||||
)
|
||||
except ImportError: # pragma: no cover - standalone/test context
|
||||
from nodes.identity_forge_turnaround import (
|
||||
_FRAMINGS, _forge_class, _unwrap, replay_base,
|
||||
_FRAMINGS, _forge_class, _unwrap, parse_document, pin_framing, replay_base,
|
||||
)
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
@@ -90,9 +92,9 @@ def resolve_expression_sheet(
|
||||
forge = _forge_class()
|
||||
# The Turnaround's replay recipe (schema defaults, then the document).
|
||||
base = replay_base(character_json)
|
||||
framing = _FRAMINGS.get(framing_name, "")
|
||||
if framing:
|
||||
base["shot_type"] = framing
|
||||
# 2.6.0: a close-up refuses a standing pose; release it rather than voice both.
|
||||
pin_framing(base, parse_document(character_json), character_json,
|
||||
_FRAMINGS.get(framing_name, ""))
|
||||
if gaze_name in _GAZES and gaze_name != _KEEP_GAZE:
|
||||
base["gaze"] = gaze_name
|
||||
|
||||
|
||||
@@ -228,7 +228,10 @@ if _COMFY_AVAILABLE:
|
||||
"signature prop. Leave empty for none.",
|
||||
),
|
||||
],
|
||||
outputs=[io.String.Output(display_name="character_json")],
|
||||
outputs=[io.String.Output(
|
||||
display_name="character_json",
|
||||
tooltip="The preset as JSON. Wire into Identity Forge's 'archetype_json', or into another preset's 'upstream' to stack them.",
|
||||
)],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -41,14 +41,14 @@ try:
|
||||
from .identity_forge import FIELD_DEFINITIONS
|
||||
from .identity_forge_turnaround import (
|
||||
_FRAMINGS, _KEEP_POSE, _NEUTRAL_POSES, _forge_class, _unwrap, document_fields,
|
||||
character_seed, document_meta, parse_document, release_fields, replay_base,
|
||||
character_seed, document_meta, parse_document, pin_framing, release_fields, replay_base,
|
||||
)
|
||||
except ImportError: # pragma: no cover - standalone/test context
|
||||
from data.constraints import lock_clash
|
||||
from nodes.identity_forge import FIELD_DEFINITIONS
|
||||
from nodes.identity_forge_turnaround import (
|
||||
_FRAMINGS, _KEEP_POSE, _NEUTRAL_POSES, _forge_class, _unwrap, document_fields,
|
||||
character_seed, document_meta, parse_document, release_fields, replay_base,
|
||||
character_seed, document_meta, parse_document, pin_framing, release_fields, replay_base,
|
||||
)
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
@@ -114,9 +114,9 @@ def resolve_outfit_sheet(
|
||||
document = parse_document(character_json)
|
||||
meta = document_meta(document)
|
||||
base = replay_base(character_json)
|
||||
framing = _FRAMINGS.get(framing_name, "")
|
||||
if framing:
|
||||
base["shot_type"] = framing
|
||||
# 2.6.0: released before the one-view path below, which used to replay the
|
||||
# framing's clashes (a standing pose in a close-up) unchanged.
|
||||
pin_framing(base, document, character_json, _FRAMINGS.get(framing_name, ""))
|
||||
if pose_name != _KEEP_POSE:
|
||||
base["pose"] = pose_name
|
||||
|
||||
@@ -130,9 +130,6 @@ def resolve_outfit_sheet(
|
||||
if backdrop:
|
||||
released |= _SCENE
|
||||
base["location"] = backdrop
|
||||
if framing:
|
||||
released |= {name for name, value in document_fields(document).items()
|
||||
if lock_clash("shot_type", framing, {name: value})}
|
||||
release_fields(document, released)
|
||||
base["archetype_json"] = json.dumps(document)
|
||||
# What the outfit must agree with: everything the replay keeps, plus the pins.
|
||||
@@ -259,8 +256,12 @@ if _COMFY_AVAILABLE:
|
||||
],
|
||||
)
|
||||
|
||||
# No fingerprint_inputs: every seed is derived, nothing auto-advances (see
|
||||
# Turnaround), so the node is a pure function of its inputs.
|
||||
@classmethod
|
||||
def fingerprint_inputs(cls, **kwargs: Any) -> Any:
|
||||
# 2.6.0: outfit_seed auto-advances (control_after_generate), and
|
||||
# ComfyUI#11905 can serve a stale cached result for that; NaN never equals
|
||||
# itself, so the node always re-runs. Identical prompts keep downstream cached.
|
||||
return float("nan")
|
||||
|
||||
@classmethod
|
||||
def execute(cls, **kwargs: Any) -> "io.NodeOutput":
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
"""IdentityForgeSceneSheet node - one resolved character, a row of places (2.6.0).
|
||||
|
||||
The location-side sibling of :mod:`nodes.identity_forge_outfit_sheet`, built the same
|
||||
way (read the Turnaround's docstring first): it takes a **resolved** character
|
||||
(Identity Forge's ``prompt_json``), re-runs the engine over it once per place and
|
||||
emits the prompts as a **list**.
|
||||
|
||||
**Ownership line.** This node owns the place. Each view pins one ``location`` and
|
||||
releases the scene drawn against the old one (lighting, composition, season), so the
|
||||
engine lights and dates the new place itself. The person never changes.
|
||||
|
||||
A place a live rule refuses (``lock_clash``) is handled by what refuses it, as in the
|
||||
Outfit Sheet: stance and styling a person changes with the setting (pose, gaze,
|
||||
framing, makeup, jewellery, hair styling, see :data:`_RESTAGED`) are released and
|
||||
redrawn for that view; anything else (age, body, a locked held item) skips the place
|
||||
and logs it. Clothing follows the ``clothes`` input: by default every place dresses
|
||||
the person again (beach clothes on the beach, office clothes in the office); "Keep the
|
||||
outfit" keeps it and skips a place that refuses it. A cosplayer or a body-covering
|
||||
character always keeps their costume.
|
||||
|
||||
Text-only, zero new dependencies.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
from comfy_api.latest import io # type: ignore[import-not-found]
|
||||
_COMFY_AVAILABLE: bool = True
|
||||
except ImportError: # pragma: no cover - exercised only outside ComfyUI
|
||||
_COMFY_AVAILABLE = False
|
||||
|
||||
try:
|
||||
from ..data.constraints import lock_clash
|
||||
from .identity_forge_outfit_sheet import _CLOTHING, _RESTYLED, _single_view
|
||||
from .identity_forge_turnaround import (
|
||||
_FRAMINGS, _forge_class, _unwrap, character_seed, document_fields, document_meta,
|
||||
parse_document, release_fields, replay_base,
|
||||
)
|
||||
except ImportError: # pragma: no cover - standalone/test context
|
||||
from data.constraints import lock_clash
|
||||
from nodes.identity_forge_outfit_sheet import _CLOTHING, _RESTYLED, _single_view
|
||||
from nodes.identity_forge_turnaround import (
|
||||
_FRAMINGS, _forge_class, _unwrap, character_seed, document_fields, document_meta,
|
||||
parse_document, release_fields, replay_base,
|
||||
)
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
#: The selectable sheets, in display order. Exact ``location`` pool values.
|
||||
_SHEETS: "dict[str, tuple[str, ...]]" = {
|
||||
"Everyday (6)": ("sunny city park", "cozy corner coffee shop",
|
||||
"modern open-concept living room", "corporate open office",
|
||||
"wide sandy beach", "forest trail"),
|
||||
"Indoors (4)": ("cozy corner coffee shop", "modern open-concept living room",
|
||||
"cozy bookstore with reading nooks", "dimly lit cocktail lounge"),
|
||||
"Outdoors (4)": ("sunny city park", "wide sandy beach", "forest trail",
|
||||
"neon-lit city street"),
|
||||
"Studio backdrops (3)": ("seamless grey studio backdrop", "solid white studio backdrop",
|
||||
"solid black studio backdrop"),
|
||||
}
|
||||
|
||||
_DRESS = "Dress for each place"
|
||||
_KEEP_OUTFIT = "Keep the outfit (skip places that refuse it)"
|
||||
|
||||
#: Drawn against the place, so released with it (``location_setting`` too: a recorded
|
||||
#: "Indoor" must not fight a pinned beach).
|
||||
_SCENE: "frozenset[str]" = frozenset(
|
||||
{"location", "location_setting", "lighting", "composition", "season"})
|
||||
|
||||
#: What a person changes with the setting; a place that refuses one of these redraws
|
||||
#: it for that view instead of being skipped.
|
||||
_RESTAGED: "frozenset[str]" = _RESTYLED | {"pose", "gaze", "shot_type"}
|
||||
|
||||
|
||||
def resolve_scene_sheet(
|
||||
character_json: str, sheet_name: str, framing_name: str, clothes: str = _DRESS,
|
||||
) -> "tuple[list[str], list[str]]":
|
||||
"""Render one resolved character once per place. Returns ``(prompts, labels)``."""
|
||||
forge = _forge_class()
|
||||
document = parse_document(character_json)
|
||||
base = replay_base(character_json)
|
||||
if not document:
|
||||
return [str(_unwrap(forge.execute(**base))[0])], ["1-as-resolved"]
|
||||
|
||||
framing = _FRAMINGS.get(framing_name, "")
|
||||
if framing:
|
||||
base["shot_type"] = framing
|
||||
redress = clothes != _KEEP_OUTFIT and not _single_view(document_meta(document))
|
||||
release_fields(document, set(_SCENE) | (set(_CLOTHING) if redress else set()))
|
||||
# What the place must agree with: everything the replay keeps, plus the framing pin.
|
||||
context = document_fields(document)
|
||||
pinned = {"shot_type": framing} if framing else {}
|
||||
context.update(pinned)
|
||||
|
||||
prompts: "list[str]" = []
|
||||
labels: "list[str]" = []
|
||||
for place in _SHEETS.get(sheet_name, _SHEETS["Everyday (6)"]):
|
||||
refused = {name for name, value in context.items()
|
||||
if lock_clash("location", place, {name: value})}
|
||||
blocked = (refused - _RESTAGED) | (refused & set(pinned))
|
||||
if blocked:
|
||||
_LOG.info("Scene sheet: skipping '%s', which this character's %s refuses.",
|
||||
place, ", ".join(sorted(blocked)))
|
||||
continue
|
||||
view_document = json.loads(json.dumps(document))
|
||||
release_fields(view_document, refused)
|
||||
view = {**base, "location": place, "archetype_json": json.dumps(view_document),
|
||||
"seed": character_seed(character_json, f"scene|{place}")}
|
||||
prompts.append(str(_unwrap(forge.execute(**view))[0]))
|
||||
labels.append(f"{len(prompts)}-{place.replace(' ', '-')}")
|
||||
if not prompts:
|
||||
_LOG.warning("Every place in this sheet clashes with the character; "
|
||||
"emitting one view as resolved.")
|
||||
return [str(_unwrap(forge.execute(**replay_base(character_json)))[0])], \
|
||||
["1-as-resolved"]
|
||||
return prompts, labels
|
||||
|
||||
|
||||
if _COMFY_AVAILABLE:
|
||||
|
||||
class IdentityForgeSceneSheet(io.ComfyNode): # type: ignore[misc, valid-type]
|
||||
"""Emit one resolved character in several places, as a list."""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls) -> "io.Schema":
|
||||
return io.Schema(
|
||||
node_id="IdentityForgeSceneSheet",
|
||||
display_name="Identity Forge Scene Sheet",
|
||||
category="conditioning/character",
|
||||
description=(
|
||||
"One character, several places, from a single queue. Wire Identity "
|
||||
"Forge's 'prompt_json' in; the 'prompt' output is a LIST, so "
|
||||
"everything downstream runs once per place. The person stays "
|
||||
"exactly as resolved; the place, its light and season change, and "
|
||||
"by default the clothes are chosen again to suit each place."
|
||||
),
|
||||
inputs=[
|
||||
io.String.Input(
|
||||
"character_json",
|
||||
default="",
|
||||
force_input=True,
|
||||
tooltip="Connect Identity Forge's 'prompt_json' output. Every "
|
||||
"view is the same person, shown in a different place.",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"sheet",
|
||||
options=list(_SHEETS),
|
||||
default="Everyday (6)",
|
||||
tooltip="Which places to emit, and so how many images one queue "
|
||||
"makes. Everyday (6) = city park, coffee shop, living "
|
||||
"room, office, beach, forest trail. A place that clashes "
|
||||
"with the character is skipped.",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"framing",
|
||||
options=list(_FRAMINGS),
|
||||
default="Cowboy (mid-thigh up)",
|
||||
tooltip="How much of the subject each view frames. A wider "
|
||||
"shot shows more of the place. 'Unspecified' keeps the "
|
||||
"character's own framing (redrawn where a place "
|
||||
"refuses it).",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"clothes",
|
||||
options=[_DRESS, _KEEP_OUTFIT],
|
||||
default=_DRESS,
|
||||
tooltip="'Dress for each place' picks a new outfit that suits "
|
||||
"every place. 'Keep the outfit' keeps the character's "
|
||||
"clothes and skips any place they do not fit (no "
|
||||
"evening gown on a forest trail). A cosplayer always "
|
||||
"keeps their costume.",
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
io.String.Output(
|
||||
display_name="prompt",
|
||||
is_output_list=True,
|
||||
tooltip="One prompt per place, as a list. Wire into "
|
||||
"CLIPTextEncode.",
|
||||
),
|
||||
io.String.Output(
|
||||
display_name="view_label",
|
||||
is_output_list=True,
|
||||
tooltip="Matching list of sortable names ('1-sunny-city-park', "
|
||||
"...). Wire into Save Image's filename_prefix.",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
# No fingerprint_inputs: every seed is derived, nothing auto-advances (see
|
||||
# Turnaround), so the node is a pure function of its inputs.
|
||||
|
||||
@classmethod
|
||||
def execute(cls, **kwargs: Any) -> "io.NodeOutput":
|
||||
prompts, labels = resolve_scene_sheet(
|
||||
kwargs.get("character_json", ""),
|
||||
kwargs.get("sheet", "Everyday (6)"),
|
||||
kwargs.get("framing", "Cowboy (mid-thigh up)"),
|
||||
kwargs.get("clothes", _DRESS),
|
||||
)
|
||||
return io.NodeOutput(prompts, labels)
|
||||
@@ -58,9 +58,11 @@ except ImportError: # pragma: no cover — exercised only outside ComfyUI
|
||||
|
||||
|
||||
try:
|
||||
from ..data.constraints import lock_clash
|
||||
from ..data.cosplayers import COSPLAYERS
|
||||
from .identity_forge import FIELD_DEFINITIONS
|
||||
except ImportError: # pragma: no cover — standalone/test context
|
||||
from data.constraints import lock_clash
|
||||
from data.cosplayers import COSPLAYERS
|
||||
from nodes.identity_forge import FIELD_DEFINITIONS
|
||||
|
||||
@@ -296,6 +298,27 @@ def release_fields(document: "dict[str, Any]", names: "set[str]") -> None:
|
||||
meta["omitted"] = [n for n in meta["omitted"] if n not in names]
|
||||
|
||||
|
||||
def pin_framing(base: "dict[str, Any]", document: "dict[str, Any]", character_json: str,
|
||||
framing: str) -> None:
|
||||
"""Pin ``framing`` on the replay kwargs and release every kept field it refuses.
|
||||
|
||||
2.6.0: a sheet that pins a framing must also let go of what the framing excludes
|
||||
(a standing pose in a close-up, "the subject small in the frame" at chest height),
|
||||
or the replay voices both. Released fields redraw from a per-character seed, so
|
||||
every character does not land on the same replacement pose. ``document`` is
|
||||
released in place and becomes the replayed preset.
|
||||
"""
|
||||
if not framing:
|
||||
return
|
||||
base["shot_type"] = framing
|
||||
refused = {name for name, value in document_fields(document).items()
|
||||
if lock_clash("shot_type", framing, {name: value})}
|
||||
if refused:
|
||||
release_fields(document, refused)
|
||||
base["archetype_json"] = json.dumps(document)
|
||||
base["seed"] = character_seed(character_json, "framing")
|
||||
|
||||
|
||||
#: Rotations that show the costume's back, where a roster entry's ``costume_back``
|
||||
#: replaces its front-facing costume text (2.0.0).
|
||||
_BACK_OF_COSTUME: "frozenset[str]" = frozenset({_BACK, _REAR_THREE_QUARTER})
|
||||
|
||||
@@ -26,6 +26,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
|
||||
import json
|
||||
import random
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -58,6 +59,21 @@ except ImportError: # pragma: no cover — exercised only outside ComfyUI
|
||||
#: Shown in the combo when the vault is empty (kept stable so saved workflows match).
|
||||
_NO_CHARACTERS = "(no characters saved)"
|
||||
|
||||
#: 2.6.0: last combo option when the vault has entries; ``seed`` picks one of them.
|
||||
#: Appended, never first, so the default (the first saved name) is unchanged.
|
||||
_RANDOM = "(random saved character)"
|
||||
|
||||
|
||||
def resolve_selection(vault_root: Path | str, character: str, seed: int) -> str:
|
||||
"""The entry name ``character`` stands for: itself, or a seeded pick for
|
||||
:data:`_RANDOM` (the same seed and vault give the same pick)."""
|
||||
if character != _RANDOM:
|
||||
return character
|
||||
names = list_character_names(vault_root)
|
||||
if not names:
|
||||
return _NO_CHARACTERS
|
||||
return names[random.Random(seed).randrange(len(names))]
|
||||
|
||||
|
||||
def _is_entry(path: Path) -> bool:
|
||||
"""A folder is a character iff it holds a ``character.json``."""
|
||||
@@ -175,9 +191,18 @@ def rename_character(vault_root: Path | str, old: str, new: str) -> str:
|
||||
if not sanitize_name(new):
|
||||
raise ValueError(f"Unusable new name: {new!r}.")
|
||||
dst = _entry_dir(root, new)
|
||||
if dst.exists() and dst != src:
|
||||
wanted = sanitize_name(new)
|
||||
if dst == src and src.name != wanted:
|
||||
# 2.6.0: a case-only rename ("bob" -> "Bob") on a case-insensitive filesystem
|
||||
# resolves to the same folder, so a direct rename did nothing; go via a temp name.
|
||||
dst = src.with_name(wanted)
|
||||
hop = src.with_name(f".{src.name}.renaming")
|
||||
src.rename(hop)
|
||||
hop.rename(dst)
|
||||
elif dst.exists() and dst != src:
|
||||
raise ValueError(f"A character named {dst.name!r} already exists.")
|
||||
src.rename(dst)
|
||||
else:
|
||||
src.rename(dst)
|
||||
# Keep the sidecar's display_name in step with the folder.
|
||||
meta_path = dst / _META_FILE
|
||||
try:
|
||||
@@ -235,7 +260,8 @@ if _COMFY_AVAILABLE:
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls) -> "io.Schema":
|
||||
names = list_character_names(_vault_root()) or [_NO_CHARACTERS]
|
||||
saved = list_character_names(_vault_root())
|
||||
names = saved + [_RANDOM] if saved else [_NO_CHARACTERS]
|
||||
return io.Schema(
|
||||
node_id="IdentityForgeVaultLoad",
|
||||
display_name="Identity Forge Vault Load",
|
||||
@@ -252,7 +278,8 @@ if _COMFY_AVAILABLE:
|
||||
options=names,
|
||||
default=names[0],
|
||||
tooltip="Saved character to recall. Click Refresh after saving new "
|
||||
"ones, or Manage Vault to browse with thumbnails.",
|
||||
"ones, or Manage Vault to browse with thumbnails. "
|
||||
"'(random saved character)' picks one by 'seed'.",
|
||||
),
|
||||
io.String.Input(
|
||||
"upstream",
|
||||
@@ -262,8 +289,22 @@ if _COMFY_AVAILABLE:
|
||||
tooltip="Optional: connect another preset's character_json here to "
|
||||
"stack presets. This saved character wins on overlap.",
|
||||
),
|
||||
# 2.6.0: appended last so older workflows' widgets_values still line up.
|
||||
io.Int.Input(
|
||||
"seed",
|
||||
default=0,
|
||||
min=0,
|
||||
max=0xFFFFFFFFFFFFFFFF,
|
||||
control_after_generate=True,
|
||||
tooltip="Only used with '(random saved character)': picks which "
|
||||
"saved character to recall. Set the control to "
|
||||
"'randomize' for a different one every queue.",
|
||||
),
|
||||
],
|
||||
outputs=[io.String.Output(display_name="character_json")],
|
||||
outputs=[io.String.Output(
|
||||
display_name="character_json",
|
||||
tooltip="The preset as JSON. Wire into Identity Forge's 'archetype_json', or into another preset's 'upstream' to stack them.",
|
||||
)],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -271,11 +312,17 @@ if _COMFY_AVAILABLE:
|
||||
# 1.5.5: see _character_fingerprint. Folds the SELECTED entry's
|
||||
# mtime+size into the cache key so an Overwrite/rename/delete that
|
||||
# left the `character` widget unchanged still invalidates the cache.
|
||||
# 2.6.0: a random pick rides an auto-advancing seed, which ComfyUI#11905
|
||||
# can serve stale from cache; NaN never equals itself, so it always re-runs
|
||||
# (cheap: one file read, and identical output keeps downstream cached).
|
||||
if kwargs.get("character") == _RANDOM:
|
||||
return float("nan")
|
||||
return _character_fingerprint(_vault_root(), kwargs.get("character", _NO_CHARACTERS))
|
||||
|
||||
@classmethod
|
||||
def execute(cls, **kwargs: Any) -> "io.NodeOutput":
|
||||
character = kwargs.get("character", _NO_CHARACTERS)
|
||||
character = resolve_selection(_vault_root(), kwargs.get("character", _NO_CHARACTERS),
|
||||
int(kwargs.get("seed", 0) or 0))
|
||||
own = "{}"
|
||||
if character and character != _NO_CHARACTERS:
|
||||
own, _ = load_character(_vault_root(), character)
|
||||
|
||||
@@ -92,7 +92,9 @@ def sanitize_name(raw: str) -> str:
|
||||
name = re.sub(r"\s+", " ", name).strip().strip(".").strip()
|
||||
if name in {"", ".", ".."}:
|
||||
return ""
|
||||
name = name[:120].strip()
|
||||
# 2.6.0: re-strip dots after the cut too; Windows drops a trailing dot from a
|
||||
# folder name, so the saved folder and the returned name used to differ.
|
||||
name = name[:120].rstrip(". ")
|
||||
if name.split(".", 1)[0].upper() in _WINDOWS_RESERVED_NAMES:
|
||||
name += "_"
|
||||
return name
|
||||
|
||||
+7
-2
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "comfyui-identity-forge"
|
||||
version = "2.4.0"
|
||||
description = "Create believable, coherent people, cosplayers and creatures from dropdowns - no prompt engineering required. A constraint engine keeps every trait sensible and a seed makes any result reproducible. Cosplay characters carry a hand-written, canon-checked costume description - garments, colours, masks, markings, signature props - that renders on any checkpoint, and are searchable from an in-node picker with trait facets, gender and franchise filters, and thumbnail previews that are cached on disk so they also show offline. Sheet nodes build one-queue reference sets of the same resolved character: Turnaround (camera views), Expression Sheet, Outfit Sheet (one look per outfit style) and Age Progression (the character across ages). Public galleries showcase every entry with a sample render and its exact workflow. Optional preset layers add themed archetypes, creature/monster/alien hybridization, per-element style modifiers, and a save/load character vault."
|
||||
version = "2.6.0"
|
||||
description = "Create believable, coherent people, cosplayers and creatures from dropdowns - no prompt engineering required. A constraint engine keeps every trait sensible and a seed makes any result reproducible. Cosplay characters carry a hand-written, canon-checked costume description - garments, colours, masks, markings, signature props - that renders on any checkpoint, and are searchable from an in-node picker with trait facets, gender and franchise filters, and thumbnail previews that are cached on disk so they also show offline. Sheet nodes build one-queue reference sets of the same resolved character: Turnaround (camera views), Expression Sheet, Outfit Sheet (one look per outfit style), Scene Sheet (the character in several places) and Age Progression (the character across ages). Public galleries showcase every entry with a sample render and its exact workflow. Optional preset layers add themed archetypes, creature/monster/alien hybridization, per-element style modifiers, and a save/load character vault."
|
||||
license = { text = "MIT" }
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
@@ -20,6 +20,11 @@ PublisherId = "enragedantelope"
|
||||
DisplayName = "Identity Forge"
|
||||
requires-comfyui = ">=0.25.0"
|
||||
|
||||
[tool.ruff]
|
||||
# Matches the version CI installs (.github/workflows/ci.yml); a different local ruff
|
||||
# reports a different rule set, so it refuses to run instead. Bump both together.
|
||||
required-version = "==0.15.11"
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
# The test and preview scripts prepend the repo root onto sys.path so they can be
|
||||
# run standalone (``python tests/...``); those imports necessarily follow the shim,
|
||||
|
||||
@@ -48,6 +48,7 @@ from nodes.identity_forge_modifier import IdentityForgeModifier # noqa: E402
|
||||
from nodes.identity_forge_turnaround import IdentityForgeTurnaround # noqa: E402
|
||||
from nodes.identity_forge_expression_sheet import IdentityForgeExpressionSheet # noqa: E402
|
||||
from nodes.identity_forge_outfit_sheet import IdentityForgeOutfitSheet # noqa: E402
|
||||
from nodes.identity_forge_scene_sheet import IdentityForgeSceneSheet # noqa: E402
|
||||
from nodes.identity_forge_age_progression import IdentityForgeAgeProgression # noqa: E402
|
||||
from nodes.identity_forge_vault_load import ( # noqa: E402
|
||||
IdentityForgeVaultLoad, _NO_CHARACTERS,
|
||||
@@ -66,6 +67,7 @@ _NODE_CLASSES = {
|
||||
"IdentityForgeTurnaround": IdentityForgeTurnaround,
|
||||
"IdentityForgeExpressionSheet": IdentityForgeExpressionSheet,
|
||||
"IdentityForgeOutfitSheet": IdentityForgeOutfitSheet,
|
||||
"IdentityForgeSceneSheet": IdentityForgeSceneSheet,
|
||||
"IdentityForgeAgeProgression": IdentityForgeAgeProgression,
|
||||
"IdentityForgeVaultLoad": IdentityForgeVaultLoad,
|
||||
"IdentityForgeVaultSave": IdentityForgeVaultSave,
|
||||
|
||||
@@ -251,6 +251,17 @@ def _cosplayer_traits(entry: dict) -> list[str]:
|
||||
return traits
|
||||
|
||||
|
||||
def _text_leaves(value) -> list[str]:
|
||||
"""Every string inside a nested dict/list value, in order."""
|
||||
if isinstance(value, str):
|
||||
return [value]
|
||||
if isinstance(value, dict):
|
||||
value = list(value.values())
|
||||
if isinstance(value, list):
|
||||
return [s for v in value for s in _text_leaves(v)]
|
||||
return []
|
||||
|
||||
|
||||
def _cosplayer_roster_entry(
|
||||
name: str, entry: dict, franchise_categories: dict[str, str], default_category: str,
|
||||
) -> dict:
|
||||
@@ -270,6 +281,10 @@ def _cosplayer_roster_entry(
|
||||
aliases = entry.get("aliases")
|
||||
if aliases:
|
||||
haystack_parts.extend(aliases)
|
||||
# 2.5.0: every other piece of descriptive text is searchable too, including
|
||||
# each alternate look in `costumes`.
|
||||
for key in ("eyes", "subject", "skin", "costume_back", "prop_costume", "anatomy", "costumes"):
|
||||
haystack_parts.extend(_text_leaves(entry.get(key)))
|
||||
roster = {
|
||||
"kind": "cosplayer",
|
||||
"name": name,
|
||||
|
||||
@@ -7542,6 +7542,41 @@
|
||||
]
|
||||
}
|
||||
],
|
||||
"IdentityForgeSceneSheet": [
|
||||
{
|
||||
"name": "sheet",
|
||||
"default": "Everyday (6)",
|
||||
"type": "combo",
|
||||
"options": [
|
||||
"Everyday (6)",
|
||||
"Indoors (4)",
|
||||
"Outdoors (4)",
|
||||
"Studio backdrops (3)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "framing",
|
||||
"default": "Cowboy (mid-thigh up)",
|
||||
"type": "combo",
|
||||
"options": [
|
||||
"Full body",
|
||||
"Cowboy (mid-thigh up)",
|
||||
"Waist up",
|
||||
"Chest up",
|
||||
"Head and shoulders",
|
||||
"Unspecified"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "clothes",
|
||||
"default": "Dress for each place",
|
||||
"type": "combo",
|
||||
"options": [
|
||||
"Dress for each place",
|
||||
"Keep the outfit (skip places that refuse it)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"IdentityForgeAgeProgression": [
|
||||
{
|
||||
"name": "stages",
|
||||
@@ -7575,6 +7610,22 @@
|
||||
"options": [
|
||||
"(no characters saved)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "seed",
|
||||
"default": 0,
|
||||
"type": "INT"
|
||||
},
|
||||
{
|
||||
"name": "control_after_generate",
|
||||
"type": "combo",
|
||||
"default": "randomize",
|
||||
"options": [
|
||||
"fixed",
|
||||
"increment",
|
||||
"decrement",
|
||||
"randomize"
|
||||
]
|
||||
}
|
||||
],
|
||||
"IdentityForgeVaultSave": [
|
||||
|
||||
+144
-10
@@ -281,30 +281,164 @@ test("the gender filter keeps that gender plus entries that suit either", async
|
||||
}
|
||||
});
|
||||
|
||||
test("the franchise filter lists roster franchises by category and keeps only that franchise", async () => {
|
||||
test("starring a card keeps it under Starred only, persists, and never picks it (2.6.0)", async () => {
|
||||
resetDom();
|
||||
__testing.__resetForTests();
|
||||
window.localStorage.removeItem("identity_forge.picker.starred");
|
||||
const stub = installFetchStub(rosterOkHandler);
|
||||
try {
|
||||
const picker = await openPicker();
|
||||
const widget = picker.config.node.widgets.find((w) => w.name === picker.config.targetWidgetName);
|
||||
const before = widget.value;
|
||||
const tile = picker.grid.children[1];
|
||||
const name = tile.dataset.ifName;
|
||||
tile.querySelector(".if-picker-star").click();
|
||||
assert.equal(widget.value, before, "the star click must not select the entry");
|
||||
assert.equal(tile.querySelector(".if-picker-star").getAttribute("aria-pressed"), "true");
|
||||
assert.deepEqual(JSON.parse(window.localStorage.getItem("identity_forge.picker.starred")),
|
||||
[picker.config.kind + ":" + name]);
|
||||
|
||||
picker.starredCheckbox.click();
|
||||
assert.deepEqual(picker.visible.map((e) => e.name), [name]);
|
||||
assert.ok(picker.isFiltering());
|
||||
|
||||
// A fresh session reads the stars back from storage.
|
||||
__testing.__resetForTests();
|
||||
picker.close();
|
||||
const again = await openPicker();
|
||||
again.starredOnly = true;
|
||||
again.renderGrid();
|
||||
assert.deepEqual(again.visible.map((e) => e.name), [name]);
|
||||
again.grid.children[0].querySelector(".if-picker-star").click(); // unstar
|
||||
assert.equal(again.visible.length, 0);
|
||||
assert.match(again.grid.textContent, /Nothing starred yet/);
|
||||
again.close();
|
||||
} finally {
|
||||
window.localStorage.removeItem("identity_forge.picker.starred");
|
||||
stub.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("the franchise box suggests every franchise, keeps an exact name only, and part of a name broadly", async () => {
|
||||
resetDom();
|
||||
__testing.__resetForTests();
|
||||
const stub = installFetchStub(rosterOkHandler);
|
||||
try {
|
||||
const picker = await openPicker();
|
||||
const select = picker.franchiseSelect;
|
||||
assert.ok(select.querySelectorAll("optgroup").length > 1, "options are grouped by category");
|
||||
const franchise = REAL_ROSTER.find((e) => e.franchise).franchise;
|
||||
assert.ok([...select.options].some((o) => o.value === franchise));
|
||||
select.value = franchise;
|
||||
select.dispatchEvent(new window.Event("change"));
|
||||
const franchises = new Set(REAL_ROSTER.filter((e) => e.franchise).map((e) => e.franchise));
|
||||
assert.equal(picker.franchiseList.options.length, franchises.size, "one suggestion per franchise");
|
||||
assert.ok(picker.franchiseList.options[0].label, "suggestions carry their category");
|
||||
|
||||
const input = picker.franchiseInput;
|
||||
input.value = "star wars";
|
||||
input.dispatchEvent(new window.Event("input"));
|
||||
picker.renderGrid();
|
||||
assert.ok(picker.visible.length > 0);
|
||||
assert.ok(picker.visible.every((e) => e.franchise === franchise));
|
||||
assert.ok(picker.visible.every((e) => e.franchise === "Star Wars"), "an exact name (any case) keeps that franchise only");
|
||||
|
||||
picker.franchise = "star";
|
||||
picker.renderGrid();
|
||||
const hit = new Set(picker.visible.map((e) => e.franchise));
|
||||
assert.ok(hit.has("Star Wars") && hit.has("Star Trek"), "part of a name keeps every franchise containing it");
|
||||
|
||||
picker.close();
|
||||
picker.open();
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
assert.equal(picker.franchiseSelect.value, franchise, "the choice survives a reopen");
|
||||
await flush();
|
||||
assert.equal(picker.franchiseInput.value, "star", "the text survives a reopen");
|
||||
picker.close();
|
||||
} finally {
|
||||
stub.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("archetype and creature pickers hide the cosplayer-only filters", async () => {
|
||||
resetDom();
|
||||
__testing.__resetForTests();
|
||||
const stub = installFetchStub(rosterOkHandler);
|
||||
try {
|
||||
for (const [kind, widget, gender] of [["archetype", "archetype", true], ["creature", "creature", false]]) {
|
||||
const picker = await openPicker(kind, widget);
|
||||
const header = picker.overlay.querySelector(".if-picker-header");
|
||||
assert.ok(!header.contains(picker.franchiseInput), kind + ": no franchise box");
|
||||
assert.ok(!header.contains(picker.facetSelect), kind + ": no trait facet");
|
||||
assert.equal(header.contains(picker.genderSelect), gender, kind + ": gender only where entries have one");
|
||||
picker.close();
|
||||
}
|
||||
const cos = await openPicker();
|
||||
const header = cos.overlay.querySelector(".if-picker-header");
|
||||
assert.ok(header.contains(cos.franchiseInput) && header.contains(cos.facetSelect) && header.contains(cos.genderSelect));
|
||||
cos.close();
|
||||
} finally {
|
||||
stub.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("search matches from a word's start, quoted phrases, and the SEARCH_ALSO synonyms", () => {
|
||||
const find = (q) => REAL_ROSTER.filter((e) => __testing.matchesQuery(e, __testing.tokenize(q)));
|
||||
const elbowOnly = (e) => /elbow|rainbow/.test(e.haystack) && !/(^|[^a-z0-9])bow/.test(e.haystack)
|
||||
&& !e.name.toLowerCase().includes("bow");
|
||||
assert.ok(REAL_ROSTER.some(elbowOnly), "sanity: some entries mention bow only inside elbow/rainbow");
|
||||
assert.ok(!find("bow").some(elbowOnly), '"bow" must not match inside "elbow" or "rainbow"');
|
||||
assert.ok(find("man").some((e) => e.name === "Batman"), "a name still matches anywhere");
|
||||
assert.deepEqual(__testing.tokenize('red "bow tie"'), ["red", "bow tie"]);
|
||||
for (const q of ["dia de los", "día", "DÍA"]) {
|
||||
assert.ok(find(q).some((e) => e.name === "Día de los Muertos"), `"${q}" finds Día de los Muertos`);
|
||||
}
|
||||
assert.equal(__testing.tokenize("Øyvind Straße")[1], "strasse");
|
||||
assert.ok(find('"bow tie"').length > 0 && find('"bow tie"').length < find("bow").length);
|
||||
const trousersOnly = REAL_ROSTER.filter((e) => /(^|[^a-z0-9])trousers/.test(e.haystack) && !/pants/.test(e.haystack));
|
||||
assert.ok(trousersOnly.length > 0, "sanity");
|
||||
const pants = new Set(find("pants"));
|
||||
assert.ok(trousersOnly.every((e) => pants.has(e)), '"pants" finds trousers');
|
||||
assert.ok(find("suit").some((e) => /bodysuit/.test(e.haystack) && !/(^|[^a-z0-9])suit/.test(e.haystack)),
|
||||
'"suit" finds bodysuits');
|
||||
});
|
||||
|
||||
test("reopening lands on the node's current pick, marked, instead of the top of the list", async () => {
|
||||
resetDom();
|
||||
__testing.__resetForTests();
|
||||
const stub = installFetchStub(rosterOkHandler);
|
||||
try {
|
||||
const picker = await openPicker();
|
||||
const target = picker.visible[40];
|
||||
picker.select(target);
|
||||
picker.open();
|
||||
await flush();
|
||||
assert.equal(picker.visible[picker.focusIndex].name, target.name);
|
||||
const tile = picker.grid.children[picker.focusIndex];
|
||||
assert.ok(tile.classList.contains("current") && tile.classList.contains("focused"));
|
||||
picker.close();
|
||||
} finally {
|
||||
stub.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("Queue each queues one run per matching entry, then restores the pick", async () => {
|
||||
resetDom();
|
||||
__testing.__resetForTests();
|
||||
const stub = installFetchStub(rosterOkHandler);
|
||||
const seen = [];
|
||||
try {
|
||||
const picker = await openPicker();
|
||||
assert.equal(picker.queueAllButton.style.display, "none", "hidden with no filter: never the whole roster");
|
||||
const widget = picker.config.node.widgets.find((w) => w.name === "character");
|
||||
widget.value = "None";
|
||||
app.queuePrompt = async () => { seen.push(widget.value); return true; };
|
||||
picker.franchise = "Star Wars";
|
||||
picker.tabs.querySelector('[data-tab="__all__"]').click(); // mixed kinds: only cosplayers queue
|
||||
const expected = picker.visible.filter((e) => e.kind === "cosplayer").map((e) => e.name);
|
||||
assert.ok(expected.length > 1);
|
||||
assert.equal(picker.queueAllButton.textContent, "Queue each (" + expected.length + ")");
|
||||
await picker.queueEach();
|
||||
assert.deepEqual(seen, expected);
|
||||
assert.equal(widget.value, "None", "the original pick is put back");
|
||||
picker.close();
|
||||
} finally {
|
||||
delete app.queuePrompt;
|
||||
stub.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("while filtering, every tab shows its own match count so other kinds stay discoverable", async () => {
|
||||
resetDom();
|
||||
__testing.__resetForTests();
|
||||
|
||||
@@ -64,11 +64,12 @@ test("both picker buttons and the inline preview DOM widget are present, buttons
|
||||
assert.equal(preview.options?.serialize, false);
|
||||
});
|
||||
|
||||
test("refresh populates the character combo from the vault characters route", async () => {
|
||||
test("refresh populates the character combo, keeping the random option last (2.6.0)", async () => {
|
||||
const node = await setup();
|
||||
const charW = node.widgets.find((w) => w.name === "character");
|
||||
assert.ok(charW);
|
||||
assert.deepEqual(charW.options.values, SAMPLE_CHARACTERS.map((c) => c.name));
|
||||
assert.deepEqual(charW.options.values,
|
||||
[...SAMPLE_CHARACTERS.map((c) => c.name), "(random saved character)"]);
|
||||
});
|
||||
|
||||
test("an empty vault falls back to the no-characters sentinel, matching the Python default", async () => {
|
||||
|
||||
@@ -2661,6 +2661,45 @@ class UserPresetExtensionTests(unittest.TestCase):
|
||||
self.assertNotIn("Broken", store)
|
||||
self.assertNotIn("Empty", store)
|
||||
|
||||
def test_archetypes_keep_list_values_and_variants(self):
|
||||
# 2.6.0: both are built-in shapes; they used to be dropped silently.
|
||||
from data.user_options import apply_user_archetypes
|
||||
store = {}
|
||||
f = self._write({"archetypes": {
|
||||
"Listy": {"gender": "Female", "hair_color": ["copper", 7, "auburn"], "x": []},
|
||||
"Paired": {"variants": {"Female": {"age": "25"}, "Male": {"age": "30"},
|
||||
"Other": {"age": "40"}}},
|
||||
}})
|
||||
with self.assertLogs("data.user_options", "WARNING") as logs:
|
||||
self.assertEqual(apply_user_archetypes(store, path=f), 2)
|
||||
self.assertEqual(store["Listy"], {"gender": "Female", "hair_color": ["copper", "auburn"]})
|
||||
self.assertEqual(store["Paired"],
|
||||
{"variants": {"Female": {"age": "25"}, "Male": {"age": "30"}}})
|
||||
self.assertIn("'Listy': ignored x", logs.output[0])
|
||||
|
||||
def test_cosplayers_keep_alternates_back_and_subject(self):
|
||||
from data.user_options import apply_user_cosplayers
|
||||
store = {}
|
||||
f = self._write({"cosplayers": {
|
||||
"Alt": {"costume": "a red suit", "costume_back": "a red suit with a cape",
|
||||
"costumes": ["a blue suit", {"costume": "a gold suit", "mask": "a gold helm",
|
||||
"signature": {"hair_color": "white", "n": 1}},
|
||||
{"mask": "no costume key"}, ""],
|
||||
"costume_weights": [2, 1, 1], "subject": " A pig-headed alien. "},
|
||||
"Bad Weights": {"costume": "a robe", "costumes": ["a cloak"],
|
||||
"costume_weights": [1]},
|
||||
}})
|
||||
with self.assertLogs("data.user_options", "WARNING"):
|
||||
apply_user_cosplayers(store, path=f)
|
||||
alt = store["Alt"]
|
||||
self.assertEqual(alt["costume_back"], "a red suit with a cape")
|
||||
self.assertEqual(alt["subject"], "pig-headed alien")
|
||||
self.assertEqual(alt["costumes"], ["a blue suit", {
|
||||
"costume": "a gold suit", "mask": "a gold helm", "signature": {"hair_color": "white"}}])
|
||||
self.assertEqual(alt["costume_weights"], [2, 1, 1])
|
||||
self.assertNotIn("costume_weights", store["Bad Weights"])
|
||||
self.assertEqual(store["Bad Weights"]["costumes"], ["a cloak"])
|
||||
|
||||
def test_cosplayers_merge_requires_costume_and_defaults(self):
|
||||
from data.user_options import apply_user_cosplayers
|
||||
store = {}
|
||||
@@ -2972,6 +3011,12 @@ class RollAndLockTests(unittest.TestCase):
|
||||
for f in fields:
|
||||
self.assertEqual(again.get(f, "None"), widgets[f], f"{gender} @{seed}: {f}")
|
||||
|
||||
def test_non_text_widget_values_are_ignored(self):
|
||||
# 2.6.0: the route passes JSON through, and {"age": 3.5} crashed the engine.
|
||||
from nodes.identity_forge import roll_field_values
|
||||
self.assertEqual(roll_field_values({"age": 3.5, "hair_color": 7, "gender": True}, 4),
|
||||
roll_field_values({}, 4))
|
||||
|
||||
|
||||
class FeetOutOfFrameTests(unittest.TestCase):
|
||||
"""1.7.0: a framing that crops the feet drops the footwear clause from the prose.
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Example workflows stay loadable against the current node schemas (2.6.0).
|
||||
|
||||
``widgets_values`` is positional: a widget added, removed or reordered in a node's
|
||||
``define_schema()`` shifts every later value in a saved workflow, and a combo option
|
||||
that was renamed loads as an invalid value. Nothing caught that for the shipped
|
||||
``example_workflows/`` until this test, which checks every pack node in them against
|
||||
the committed frontend fixture (``tests/frontend/fixtures/nodes.json``, itself gated
|
||||
against the live schemas by ``scripts/dump_frontend_fixtures.py --check``).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WORKFLOWS = sorted((ROOT / "example_workflows").glob("*.json"))
|
||||
FIXTURE = json.loads((ROOT / "tests" / "frontend" / "fixtures" / "nodes.json")
|
||||
.read_text(encoding="utf-8"))
|
||||
|
||||
#: The Vault Load combo lists the user's own saved characters, so any name is valid.
|
||||
_FREE_COMBOS = {("IdentityForgeVaultLoad", "character")}
|
||||
|
||||
|
||||
class ExampleWorkflowWidgetTests(unittest.TestCase):
|
||||
def test_there_are_example_workflows(self):
|
||||
self.assertTrue(WORKFLOWS)
|
||||
|
||||
def test_pack_nodes_match_the_schema(self):
|
||||
for path in WORKFLOWS:
|
||||
workflow = json.loads(path.read_text(encoding="utf-8"))
|
||||
for node in workflow["nodes"]:
|
||||
widgets = FIXTURE.get(node["type"])
|
||||
if widgets is None:
|
||||
self.assertFalse(node["type"].startswith("IdentityForge"),
|
||||
f"{path.name}: {node['type']} missing from the fixture")
|
||||
continue
|
||||
values = node.get("widgets_values") or []
|
||||
with self.subTest(workflow=path.name, node=node["id"]):
|
||||
self.assertEqual(len(values), len(widgets),
|
||||
f"{node['type']}: widget count changed")
|
||||
for widget, value in zip(widgets, values):
|
||||
if widget["type"] != "combo" or (node["type"], widget["name"]) in _FREE_COMBOS:
|
||||
continue
|
||||
self.assertIn(value, widget["options"],
|
||||
f"{node['type']}.{widget['name']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+32
-34
@@ -113,8 +113,7 @@ class CopiesStayInSyncTests(unittest.TestCase):
|
||||
|
||||
def test_every_gallery_ships_the_full_script_set(self):
|
||||
for kind in KINDS:
|
||||
for name in SCRIPTS + ("update_gallery.bat", "index.html",
|
||||
"style.css", "gallery.js"):
|
||||
for name in SCRIPTS + ("update_gallery.bat", "index.html"):
|
||||
self.assertTrue((GALLERY_ROOT / kind / name).is_file(),
|
||||
f"gallery/{kind}/{name} is missing")
|
||||
|
||||
@@ -457,43 +456,42 @@ class SourceMatchingTests(unittest.TestCase):
|
||||
self.assertNotIn(published_only, {supplied})
|
||||
|
||||
|
||||
class PageAssetsStayInSyncTests(unittest.TestCase):
|
||||
"""The three PAGE files are copies too, and nothing pinned them (0.97.0).
|
||||
class SharedPageAssetsTests(unittest.TestCase):
|
||||
"""2.6.0: ``style.css`` and ``gallery.js`` exist once, in ``gallery/shared/``.
|
||||
|
||||
``CopiesStayInSyncTests`` covers the four ``.py`` scripts. It never covered
|
||||
``gallery.js`` or ``style.css``, which are also maintained as copies -- and an
|
||||
audit found the consequence: all three shipped a ``style.css`` whose header
|
||||
comment claimed to be the *cosplay* sheet, because the file had been copied
|
||||
twice and the header never re-read.
|
||||
They used to be three copies held together by drift tests; an audit found a
|
||||
stylesheet header claiming to be the cosplay sheet inside the other two. Now
|
||||
each page links ``../shared/`` and ``publish.py`` stages the folder beside it.
|
||||
"""
|
||||
|
||||
def test_gallery_js_is_identical_outside_its_header_comment(self):
|
||||
bodies = {}
|
||||
SHARED = GALLERY_ROOT / "shared"
|
||||
|
||||
def test_one_copy_and_every_page_links_it(self):
|
||||
for name in ("style.css", "gallery.js"):
|
||||
self.assertTrue((self.SHARED / name).is_file(), name)
|
||||
for kind in KINDS:
|
||||
text = (GALLERY_ROOT / kind / "gallery.js").read_text(encoding="utf-8")
|
||||
# The leading /* ... */ banner names the gallery; everything after it
|
||||
# must match byte for byte.
|
||||
self.assertTrue(text.startswith("/*"), f"{kind}: no header banner")
|
||||
bodies[kind] = text[text.index("*/") + 2:]
|
||||
for kind in KINDS[1:]:
|
||||
self.assertEqual(
|
||||
bodies["cosplay"], bodies[kind],
|
||||
f"gallery/{kind}/gallery.js has drifted from gallery/cosplay/"
|
||||
f"gallery.js -- port the change to all three (gallery/README.md).")
|
||||
with self.subTest(kind):
|
||||
html = (GALLERY_ROOT / kind / "index.html").read_text(encoding="utf-8")
|
||||
self.assertIn('href="../shared/style.css"', html)
|
||||
self.assertIn('src="../shared/gallery.js"', html)
|
||||
for name in ("style.css", "gallery.js"):
|
||||
self.assertFalse((GALLERY_ROOT / kind / name).exists(),
|
||||
f"gallery/{kind}/{name} is a stale copy")
|
||||
|
||||
def test_style_css_is_byte_identical(self):
|
||||
base = (GALLERY_ROOT / "cosplay" / "style.css").read_text(encoding="utf-8")
|
||||
for kind in KINDS[1:]:
|
||||
self.assertEqual(
|
||||
base, (GALLERY_ROOT / kind / "style.css").read_text(encoding="utf-8"),
|
||||
f"gallery/{kind}/style.css has drifted from gallery/cosplay/style.css")
|
||||
def test_every_publish_copy_stages_the_shared_folder(self):
|
||||
for kind in KINDS:
|
||||
pub = load(kind, "publish")
|
||||
with self.subTest(kind):
|
||||
self.assertEqual(pub.SHARED_SRC_DIR, self.SHARED)
|
||||
self.assertEqual(pub.SHARED_REL_DIR, "gallery/shared")
|
||||
for name in pub.SHARED_FILES:
|
||||
self.assertTrue((self.SHARED / name).is_file(), name)
|
||||
|
||||
def test_the_shared_stylesheet_does_not_claim_to_be_one_gallery(self):
|
||||
# The bug this pins: a header saying "Cosplay Gallery Styles" inside the
|
||||
# creature and archetype copies, which is how the drift went unnoticed.
|
||||
head = (GALLERY_ROOT / "cosplay" / "style.css").read_text(
|
||||
encoding="utf-8")[:600].lower()
|
||||
self.assertNotIn("cosplay gallery styles", head)
|
||||
def test_the_shared_assets_name_no_single_gallery(self):
|
||||
for name in ("style.css", "gallery.js"):
|
||||
head = (self.SHARED / name).read_text(encoding="utf-8")[:600].lower()
|
||||
for kind in ("cosplay gallery", "creature gallery", "archetype gallery"):
|
||||
self.assertNotIn(kind, head, name)
|
||||
|
||||
def test_every_page_ships_the_sort_controls(self):
|
||||
for kind in KINDS:
|
||||
@@ -512,7 +510,7 @@ class PageAssetsStayInSyncTests(unittest.TestCase):
|
||||
# A `$('#id')` that resolves to null is how a control silently does
|
||||
# nothing -- the dead "Clear search" button shipped that way for releases.
|
||||
for kind in KINDS:
|
||||
js = (GALLERY_ROOT / kind / "gallery.js").read_text(encoding="utf-8")
|
||||
js = (self.SHARED / "gallery.js").read_text(encoding="utf-8")
|
||||
html = (GALLERY_ROOT / kind / "index.html").read_text(encoding="utf-8")
|
||||
queried = set(re.findall(r"\$\('#([\w-]+)'\)", js))
|
||||
for element_id in sorted(queried - self.INJECTED_IDS):
|
||||
|
||||
@@ -45,6 +45,7 @@ class _Opener:
|
||||
self.not_modified = False
|
||||
self.image_type = "image/jpeg"
|
||||
self.image_body = b"\xff\xd8jpeg"
|
||||
self.manifest = _MANIFEST
|
||||
|
||||
def __call__(self, request):
|
||||
url = request.full_url
|
||||
@@ -54,7 +55,7 @@ class _Opener:
|
||||
if self.not_modified and request.get_header("If-none-match"):
|
||||
raise urllib.error.HTTPError(url, 304, "Not Modified", Message(), None)
|
||||
if url.endswith("manifest.json"):
|
||||
return _Response(_MANIFEST, "application/json")
|
||||
return _Response(self.manifest, "application/json")
|
||||
return _Response(self.image_body, self.image_type)
|
||||
|
||||
|
||||
@@ -96,6 +97,25 @@ class GalleryCacheTests(unittest.TestCase):
|
||||
self.assertEqual(
|
||||
gc.image_path("cosplay", "images/AKI.jpeg", self.root, self.opener), image)
|
||||
|
||||
def test_offline_backs_off_instead_of_retrying_every_request(self):
|
||||
# 2.6.0: a failed refresh renews the cached copy, so the next requests do not
|
||||
# each wait out a network timeout again.
|
||||
image = gc.image_path("cosplay", "images/AKI.jpeg", self.root, self.opener)
|
||||
self._age(image, gc.IMAGE_MAX_AGE + 5)
|
||||
self._age(self.root / "cosplay" / "manifest.json", gc.MANIFEST_MAX_AGE + 5)
|
||||
self.opener.offline = True
|
||||
before = len(self.opener.calls)
|
||||
for _ in range(5):
|
||||
gc.image_path("cosplay", "images/AKI.jpeg", self.root, self.opener)
|
||||
self.assertEqual(len(self.opener.calls) - before, 2, "one manifest + one image try")
|
||||
|
||||
def test_svg_is_never_served(self):
|
||||
self.opener.manifest = json.dumps({"entries": [{"image": "images/x.svg"}]}).encode()
|
||||
self.opener.image_type, self.opener.image_body = "image/svg+xml", b"<svg/>"
|
||||
with self.assertRaises(gc.GalleryError):
|
||||
gc.image_path("cosplay", "images/x.svg", self.root, self.opener)
|
||||
self.assertFalse((self.root / "cosplay" / "images" / "x.svg").exists())
|
||||
|
||||
def test_offline_with_nothing_cached_is_an_error(self):
|
||||
self.opener.offline = True
|
||||
with self.assertRaises(gc.GalleryError):
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Contracts every node class in ``nodes/`` keeps (2.6.0).
|
||||
|
||||
These were per-node tests (the Turnaround's tooltip check) or memory-only rules, and
|
||||
the Outfit Sheet shipped in 2.3.0 with an auto-advancing ``outfit_seed`` and no cache
|
||||
buster. Walking every module means a new node is covered without anyone listing it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import inspect
|
||||
import math
|
||||
import pkgutil
|
||||
import unittest
|
||||
|
||||
import nodes
|
||||
|
||||
|
||||
def _node_classes():
|
||||
found = {}
|
||||
for info in pkgutil.iter_modules(nodes.__path__):
|
||||
module = importlib.import_module(f"nodes.{info.name}")
|
||||
for _, cls in inspect.getmembers(module, inspect.isclass):
|
||||
if cls.__module__ == module.__name__ and "define_schema" in cls.__dict__:
|
||||
found[cls.__name__] = cls
|
||||
return found
|
||||
|
||||
|
||||
class NodeContractTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.classes = _node_classes()
|
||||
|
||||
def test_every_node_is_found(self):
|
||||
self.assertIn("IdentityForgeSceneSheet", self.classes)
|
||||
self.assertGreaterEqual(len(self.classes), 12)
|
||||
|
||||
def test_every_input_and_output_carries_a_tooltip(self):
|
||||
for name, cls in self.classes.items():
|
||||
schema = cls.define_schema()
|
||||
for spec in schema.inputs:
|
||||
self.assertTrue((spec.tooltip or "").strip(), f"{name}.{spec.id}")
|
||||
for output in schema.outputs:
|
||||
self.assertTrue((output.tooltip or "").strip(),
|
||||
f"{name} output {output.display_name}")
|
||||
|
||||
def test_an_auto_advancing_widget_busts_the_cache(self):
|
||||
"""ComfyUI#11905 can serve a cached result after a control_after_generate
|
||||
widget advances; such a node must define fingerprint_inputs (NaN when it
|
||||
matters, see the seeded nodes and Vault Load's random pick)."""
|
||||
for name, cls in self.classes.items():
|
||||
if any(getattr(spec, "control_after_generate", None)
|
||||
for spec in cls.define_schema().inputs):
|
||||
self.assertIn("fingerprint_inputs", cls.__dict__, name)
|
||||
|
||||
def test_outfit_sheet_and_a_random_vault_pick_always_rerun(self):
|
||||
self.assertTrue(math.isnan(
|
||||
self.classes["IdentityForgeOutfitSheet"].fingerprint_inputs(outfit_seed=3)))
|
||||
self.assertTrue(math.isnan(self.classes["IdentityForgeVaultLoad"].fingerprint_inputs(
|
||||
character="(random saved character)", seed=3)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Scene Sheet (2.6.0): one resolved character, a row of places."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from data.constraints import lock_clash
|
||||
from nodes import identity_forge_scene_sheet as scene
|
||||
from nodes.identity_forge import FIELD_DEFINITIONS, run_identity_forge
|
||||
from nodes.identity_forge_turnaround import _forge_class, _unwrap, document_fields, parse_document
|
||||
|
||||
_FACE = {name for name, field in FIELD_DEFINITIONS.items() if field.get("group") == "Face"}
|
||||
|
||||
|
||||
class _Spy:
|
||||
"""Records the resolved document of every view the sheet renders."""
|
||||
|
||||
def __init__(self):
|
||||
self.forge = _forge_class()
|
||||
self.views: "list[tuple[str | None, dict]]" = []
|
||||
|
||||
def execute(self, **kwargs):
|
||||
out = self.forge.execute(**kwargs)
|
||||
self.views.append((kwargs.get("location"),
|
||||
document_fields(parse_document(_unwrap(out)[1]))))
|
||||
return out
|
||||
|
||||
|
||||
def _run(document, sheet="Everyday (6)", clothes=scene._DRESS):
|
||||
spy = _Spy()
|
||||
with mock.patch.object(scene, "_forge_class", lambda: spy):
|
||||
prompts, labels = scene.resolve_scene_sheet(
|
||||
document, sheet, "Cowboy (mid-thigh up)", clothes)
|
||||
return prompts, labels, spy.views
|
||||
|
||||
|
||||
class SceneSheetTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
logging.disable(logging.WARNING)
|
||||
cls.characters = [run_identity_forge({"seed": seed})[1] for seed in range(8)]
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
logging.disable(logging.NOTSET)
|
||||
|
||||
def _assert_coherent(self, views):
|
||||
for place, fields in views:
|
||||
self.assertEqual(fields["location"], place)
|
||||
for name, value in fields.items():
|
||||
if name != "location":
|
||||
self.assertFalse(lock_clash("location", place, {name: value}),
|
||||
f"{place} vs {name}={value}")
|
||||
|
||||
def test_dress_for_each_place(self):
|
||||
for document in self.characters:
|
||||
prompts, labels, views = _run(document)
|
||||
self.assertEqual(len(prompts), len(scene._SHEETS["Everyday (6)"]))
|
||||
self.assertEqual(labels[0], "1-sunny-city-park")
|
||||
self._assert_coherent(views)
|
||||
self.assertEqual(len({f.get("outfit_description") for _, f in views}), len(views))
|
||||
original = document_fields(parse_document(document))
|
||||
for _, fields in views:
|
||||
self.assertEqual({k: fields.get(k) for k in _FACE},
|
||||
{k: original.get(k) for k in _FACE})
|
||||
|
||||
def test_keep_the_outfit_skips_places_that_refuse_it(self):
|
||||
skipped = 0
|
||||
for document in self.characters:
|
||||
outfit = document_fields(parse_document(document))["outfit_description"]
|
||||
prompts, _, views = _run(document, clothes=scene._KEEP_OUTFIT)
|
||||
if views and views[0][0] is not None:
|
||||
self._assert_coherent(views)
|
||||
self.assertEqual({f["outfit_description"] for _, f in views}, {outfit})
|
||||
skipped += len(scene._SHEETS["Everyday (6)"]) - len(prompts)
|
||||
self.assertGreater(skipped, 0, "no place refused any kept outfit")
|
||||
|
||||
def test_a_cosplayer_keeps_the_costume(self):
|
||||
doc = json.loads(self.characters[0])
|
||||
doc["_meta"]["cosplay_of"] = "Test Hero"
|
||||
outfit = document_fields(doc)["outfit_description"]
|
||||
_, _, views = _run(json.dumps(doc))
|
||||
self.assertTrue(views)
|
||||
for place, fields in views:
|
||||
if place is not None:
|
||||
self.assertEqual(fields["outfit_description"], outfit)
|
||||
|
||||
def test_malformed_input_emits_one_view(self):
|
||||
prompts, labels, _ = _run("not json")
|
||||
self.assertEqual(labels, ["1-as-resolved"])
|
||||
self.assertEqual(len(prompts), 1)
|
||||
|
||||
def test_every_sheet_names_real_places(self):
|
||||
pool = set(FIELD_DEFINITIONS["location"]["female_options"])
|
||||
for name, places in scene._SHEETS.items():
|
||||
self.assertTrue(set(places) <= pool, name)
|
||||
self.assertIn(f"({len(places)})", name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,90 @@
|
||||
"""2.6.0: a sheet that pins a framing releases what the framing refuses.
|
||||
|
||||
Before 2.6.0 the Expression Sheet pinned a close-up and kept "standing with arms crossed",
|
||||
and the one-view paths of the Age Progression and Outfit Sheet did the same. Every path
|
||||
now goes through ``pin_framing``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import unittest
|
||||
|
||||
from data.constraints import lock_clash
|
||||
from nodes.identity_forge import run_identity_forge
|
||||
from nodes.identity_forge_age_progression import resolve_age_progression
|
||||
from nodes.identity_forge_expression_sheet import resolve_expression_sheet
|
||||
from nodes.identity_forge_outfit_sheet import resolve_outfit_sheet
|
||||
from nodes.identity_forge_turnaround import _FRAMINGS, document_fields, parse_document
|
||||
|
||||
_CLOSE_UP = "Head and shoulders"
|
||||
|
||||
|
||||
def _clashing_characters(count: int):
|
||||
"""Documents whose own values include something a close-up refuses."""
|
||||
framing = _FRAMINGS[_CLOSE_UP]
|
||||
found = []
|
||||
for seed in range(200):
|
||||
_, document, _ = run_identity_forge({"seed": seed, "shot_type": "full body shot"})
|
||||
fields = document_fields(parse_document(document))
|
||||
refused = {value for name, value in fields.items()
|
||||
if lock_clash("shot_type", framing, {name: value})}
|
||||
if refused:
|
||||
found.append((seed, document, refused))
|
||||
if len(found) == count:
|
||||
return found
|
||||
raise AssertionError("no seed draws a value a close-up refuses")
|
||||
|
||||
|
||||
def _with_meta(document: str, **meta) -> str:
|
||||
doc = json.loads(document)
|
||||
doc["_meta"].update(meta)
|
||||
return json.dumps(doc)
|
||||
|
||||
|
||||
class SheetFramingTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
logging.disable(logging.WARNING)
|
||||
cls.characters = _clashing_characters(6)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
logging.disable(logging.NOTSET)
|
||||
|
||||
def _assert_released(self, prompts, refused, seed):
|
||||
for prompt in prompts:
|
||||
for value in refused:
|
||||
self.assertNotIn(value, prompt, f"seed {seed}")
|
||||
|
||||
def test_expression_sheet(self):
|
||||
for seed, document, refused in self.characters:
|
||||
prompts, _ = resolve_expression_sheet(document, "Smiles (3)", _CLOSE_UP)
|
||||
self._assert_released(prompts, refused, seed)
|
||||
|
||||
def test_age_progression_one_view_path(self):
|
||||
for seed, document, refused in self.characters:
|
||||
prompts, labels = resolve_age_progression(
|
||||
_with_meta(document, covers_face=True), "Life stages (4)", _CLOSE_UP)
|
||||
self.assertEqual(labels, ["1-as-resolved"])
|
||||
self._assert_released(prompts, refused, seed)
|
||||
|
||||
def test_outfit_sheet_one_view_path(self):
|
||||
for seed, document, refused in self.characters:
|
||||
prompts, labels = resolve_outfit_sheet(
|
||||
_with_meta(document, covers_body=True), "Range (6)",
|
||||
"Keep the character's scene", _CLOSE_UP, "Keep the character's pose")
|
||||
self.assertEqual(labels, ["1-as-resolved"])
|
||||
self._assert_released(prompts, refused, seed)
|
||||
|
||||
def test_released_pose_differs_between_characters(self):
|
||||
# The replacement is drawn per character, not from one shared replay seed.
|
||||
poses = set()
|
||||
for _, document, _ in self.characters:
|
||||
prompts, _ = resolve_expression_sheet(document, "Smiles (3)", _CLOSE_UP)
|
||||
poses.add(prompts[0].split(". Set in")[0][-80:])
|
||||
self.assertGreater(len(poses), 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -76,6 +76,12 @@ class SanitizeTests(unittest.TestCase):
|
||||
def test_collapses_whitespace_and_trims_dots(self):
|
||||
self.assertEqual(sanitize_name(" hi there.. "), "hi there")
|
||||
|
||||
def test_length_cap_never_leaves_a_trailing_dot(self):
|
||||
# 2.6.0: a cut landing just after a dot kept it; Windows then drops it from
|
||||
# the folder name, so the saved folder and the returned name differed.
|
||||
name = sanitize_name("a" * 119 + ".b")
|
||||
self.assertEqual(name, "a" * 119)
|
||||
|
||||
def test_rejects_traversal_and_empty(self):
|
||||
self.assertEqual(sanitize_name(".."), "")
|
||||
self.assertEqual(sanitize_name("///"), "")
|
||||
@@ -256,6 +262,15 @@ class RoundTripTests(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
rename_character(self.root, "ghost", "C")
|
||||
|
||||
def test_case_only_rename(self):
|
||||
# 2.6.0: on a case-insensitive filesystem "bob" and "Bob" resolve to one
|
||||
# folder, and the rename reported success without changing anything.
|
||||
save_character(self.root, "bob", SAMPLE_JSON)
|
||||
self.assertEqual(rename_character(self.root, "bob", "Bob"), "Bob")
|
||||
self.assertEqual(list_character_names(self.root), ["Bob"])
|
||||
meta = json.loads((self.root / "Bob" / "meta.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(meta["display_name"], "Bob")
|
||||
|
||||
|
||||
|
||||
class VaultRecallControlDeferralTests(unittest.TestCase):
|
||||
@@ -399,6 +414,17 @@ class FingerprintTests(unittest.TestCase):
|
||||
_NO_FINGERPRINT)
|
||||
self.assertEqual(_character_fingerprint(self.root, "ghost"), _NO_FINGERPRINT)
|
||||
|
||||
def test_random_pick_is_seeded_and_lands_on_a_saved_entry(self):
|
||||
from nodes.identity_forge_vault_load import _NO_CHARACTERS, _RANDOM, resolve_selection
|
||||
self.assertEqual(resolve_selection(self.root, "X", 5), "X")
|
||||
for name in ("X", "Y", "Z"):
|
||||
save_character(self.root, name, SAMPLE_JSON)
|
||||
picks = {resolve_selection(self.root, _RANDOM, seed) for seed in range(40)}
|
||||
self.assertEqual(picks, set(list_character_names(self.root)))
|
||||
self.assertEqual(resolve_selection(self.root, _RANDOM, 7),
|
||||
resolve_selection(self.root, _RANDOM, 7))
|
||||
self.assertEqual(resolve_selection(self.root / "empty", _RANDOM, 7), _NO_CHARACTERS)
|
||||
|
||||
def test_unchanged_file_gives_the_same_fingerprint(self):
|
||||
save_character(self.root, "X", SAMPLE_JSON)
|
||||
self.assertEqual(_character_fingerprint(self.root, "X"),
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"_comment_archetypes": "'archetypes' adds presets to the Archetype node. Same {field: value} shape as the built-ins; outfit_description may use {slot} placeholders (color, fabric, metal, gem, fur, flower, ...). A name matching a built-in overrides it. A custom value used here (like Sky Pirate's expression/location below) should also be listed under 'fields' above so it becomes a real option. Run 'python tests/validate_data.py' to check your field values.",
|
||||
"_comment_archetypes": "'archetypes' adds presets to the Archetype node. Same {field: value} shape as the built-ins: a value may be a list (one is picked per seed), and a 'variants' object gives separate 'Female' / 'Male' looks; outfit_description may use {slot} placeholders (color, fabric, metal, gem, fur, flower, ...). A name matching a built-in overrides it. A custom value used here (like Sky Pirate's expression/location below) should also be listed under 'fields' above so it becomes a real option. Run 'python tests/validate_data.py' to check your field values.",
|
||||
"archetypes": {
|
||||
"Sky Pirate": {
|
||||
"gender": "Female",
|
||||
@@ -59,11 +59,17 @@
|
||||
"_comment_mask": "For a fully masked head set 'covers_face': true AND put the head covering in a separate 'mask' string (kept OUT of 'costume'). covers_face hides the randomized face/hair; the mask is appended to the costume by default but kept apart so the node's 'Unmask (show face)' toggle can drop it and reveal the random head. Omit both when the face is visible.",
|
||||
"_comment_required": "Only 'costume' is required in a cosplayer entry. Everything else is optional \u2014 copy an example below, rename it, and keep just the keys you need.",
|
||||
"_comment_advanced": "Optional advanced flags (all default off; only add one when it is true): 'covers_body': true = a full hard suit/armor hides bare skin, so jewelry/nails are suppressed. 'covers_hair': true = a hood/cowl hides the hair while the face shows. 'bald': true = fully hairless head (also clears facial hair). 'body_paint': true = the skin itself is the costume color; optionally add 'skin': 'warm green' to name the color when it is not obvious from the costume text. Word a full-body color as the character's own skin ('smooth, flawless deep green skin') rather than 'body paint' or 'dye' -- paint wording renders as a streaky coat over a human tone; the skin-native wording is auto-detected, so the flag is only needed for other phrasings.",
|
||||
"_comment_alternates": "Optional per-cosplayer extras: 'costumes' is a list of alternate looks (a costume string, or an object with its own 'costume' plus per-look keys such as 'mask' or 'signature'); one look is picked per seed. 'costume_weights' gives one positive number per look, the main costume first. 'costume_back' is the costume seen from behind, used by the Turnaround's back views. 'subject' is a lead noun for a non-human head, with no article ('pig-headed alien').",
|
||||
"cosplayers": {
|
||||
"Custom Hero (My OC)": {
|
||||
"franchise": "Original",
|
||||
"gender": "Female",
|
||||
"costume": "a teal-and-silver bodysuit with a star emblem, white gloves, and white boots",
|
||||
"costume_back": "a teal-and-silver bodysuit with a silver stripe down the spine, white gloves, and white boots",
|
||||
"costumes": [
|
||||
"a black-and-gold stealth bodysuit with a dim star emblem, black gloves, and black boots"
|
||||
],
|
||||
"costume_weights": [3, 1],
|
||||
"signature": {
|
||||
"hair_color": "electric blue",
|
||||
"hair_length": "long",
|
||||
|
||||
Reference in New Issue
Block a user