Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27cbf5fa26 | ||
|
|
fc920b4d3c | ||
|
|
d604deb6a5 | ||
|
|
8cf40241cf | ||
|
|
72e96ec73f | ||
|
|
5d593a1700 | ||
|
|
81495ea530 | ||
|
|
494b53192d | ||
|
|
8c0f3e418e | ||
|
|
d2f548d0e2 | ||
|
|
7e36bb02c6 | ||
|
|
3a5e46cd9d | ||
|
|
757116dc54 | ||
|
|
05334d3e05 | ||
|
|
2d68c61f4a | ||
|
|
c6d8834a42 | ||
|
|
99d3b21334 | ||
|
|
e9a9d51ea3 | ||
|
|
0572eec472 | ||
|
|
c7f4d91a10 | ||
|
|
45a9092bbc | ||
|
|
2dfed26c1e | ||
|
|
5585583765 | ||
|
|
c4a761d071 | ||
|
|
736e152167 | ||
|
|
a2756f6c0a | ||
|
|
15c3474519 | ||
|
|
87382e650e | ||
|
|
f240aeaf05 | ||
|
|
911e9839a4 | ||
|
|
cc6d76da3f | ||
|
|
6bd6140ae9 | ||
|
|
433930d005 | ||
|
|
d381cc4b06 | ||
|
|
f52d4271dc | ||
|
|
6cf4990513 | ||
|
|
ffd0a5e709 | ||
|
|
845e03c877 | ||
|
|
de361d3fab | ||
|
|
548b63edc9 | ||
|
|
51286b3273 | ||
|
|
157606b082 | ||
|
|
2f40c921eb | ||
|
|
4b69068ace | ||
|
|
0e1b36f6e4 | ||
|
|
dafb7d879c | ||
|
|
6332ed1e4f | ||
|
|
d9e4a7c262 | ||
|
|
0765df3579 | ||
|
|
2b00a5970c | ||
|
|
22b6597ec7 | ||
|
|
c421675102 | ||
|
|
021b411e3c | ||
|
|
312e1575ae | ||
|
|
9e8cd23fe5 | ||
|
|
a769c0e496 | ||
|
|
99125a63d7 | ||
|
|
2768570660 | ||
|
|
12d6f99104 | ||
|
|
97a50ff452 | ||
|
|
b712394648 | ||
|
|
72d9a17f89 | ||
|
|
01de4f0f10 | ||
|
|
7f4b7b93f1 | ||
|
|
a3a0e3f95b | ||
|
|
890d868e16 | ||
|
|
530714e62b | ||
|
|
dd1d5d429f | ||
|
|
1f07d6eb13 | ||
|
|
e5b3edba43 | ||
|
|
4b53aca434 | ||
|
|
6981314fb5 | ||
|
|
b3c4270f6c | ||
|
|
54b525cfa0 | ||
|
|
06bb1b39d7 | ||
|
|
77fc32d760 | ||
|
|
d221ea479f | ||
|
|
b09400ecd6 | ||
|
|
685d6593fd | ||
|
|
4fc3cd84d0 | ||
|
|
88e75ac60c | ||
|
|
7bf39d9337 | ||
|
|
ea188af729 | ||
|
|
385e7b7778 | ||
|
|
e5cc122341 | ||
|
|
09227b216c | ||
|
|
8f388adc55 | ||
|
|
2f08c138ac | ||
|
|
6cbff32827 | ||
|
|
7e26211fa5 | ||
|
|
61288c5c2e | ||
|
|
22f7dedcf2 | ||
|
|
96c65a7d1b | ||
|
|
1224d35010 | ||
|
|
78f831ad69 | ||
|
|
acb5848da3 | ||
|
|
2c6de11c8c | ||
|
|
fe6f6ec451 | ||
|
|
0f4ba28105 | ||
|
|
727bd089a4 | ||
|
|
470133f953 | ||
|
|
388af28a2b | ||
|
|
7c18fcc208 | ||
|
|
4cf497b507 | ||
|
|
51eabadc36 | ||
|
|
96b4141aed | ||
|
|
963c36fc18 | ||
|
|
59e51d34c0 | ||
|
|
4e746ce2aa | ||
|
|
8d6d4e4b10 | ||
|
|
7f07f99951 | ||
|
|
e35ebb25a7 | ||
|
|
693f7191d0 | ||
|
|
2896e11d26 | ||
|
|
dd793c536e | ||
|
|
6c4589315a | ||
|
|
3f6b856eec | ||
|
|
bbc7556af2 | ||
|
|
5064f084a3 | ||
|
|
67761fbba8 | ||
|
|
630129bc32 | ||
|
|
ba170939e8 | ||
|
|
fd3c3805b6 | ||
|
|
7cb2da2468 | ||
|
|
aa1ae66821 | ||
|
|
f922a872cc | ||
|
|
23486ff1ef | ||
|
|
2fa4618ef9 | ||
|
|
50211e510b | ||
|
|
d7a72d7434 | ||
|
|
7d443ba00b | ||
|
|
1787b6041c | ||
|
|
fd4c501871 | ||
|
|
9fb653f7ee | ||
|
|
3f45b26396 | ||
|
|
44d0ca2261 | ||
|
|
699dedade0 | ||
|
|
a64e56d083 | ||
|
|
5a83e61fd1 | ||
|
|
c268e75c20 | ||
|
|
e63be54081 | ||
|
|
ecebd55654 | ||
|
|
78297c4179 | ||
|
|
bb5f6b8658 | ||
|
|
a059b48635 | ||
|
|
9ef1fb698a | ||
|
|
1b32a8a110 | ||
|
|
31b011b8fb | ||
|
|
a2e93fe7e4 | ||
|
|
1e42f9b5aa | ||
|
|
67199b5dba | ||
|
|
74c7331b7e | ||
|
|
00b735d32f | ||
|
|
a1fe6956d1 | ||
|
|
fe2423f5b4 | ||
|
|
6c20f53cc6 | ||
|
|
936a13913e | ||
|
|
290e7a81f5 | ||
|
|
327e7cc762 | ||
|
|
830776efd1 | ||
|
|
bdcf85ccd4 | ||
|
|
d42b7ca1d8 | ||
|
|
fcde3b31d6 | ||
|
|
ea4ed059c3 | ||
|
|
f670c3db76 | ||
|
|
af95f08ef4 | ||
|
|
70283ce4d3 | ||
|
|
bab87cd3c2 | ||
|
|
7545ade87d | ||
|
|
651ca65228 | ||
|
|
d524d142b5 | ||
|
|
da2239dca5 | ||
|
|
9d372b1d8f | ||
|
|
7aab09d6bc | ||
|
|
2295ce0f81 | ||
|
|
8ea15719bd | ||
|
|
d03936478c | ||
|
|
8dcef0f3d9 | ||
|
|
8912937a9a | ||
|
|
d4e6d0c112 | ||
|
|
696711dca1 | ||
|
|
b54302d546 | ||
|
|
0bd4382cf0 | ||
|
|
ed10b881b7 | ||
|
|
cbf102b8a0 | ||
|
|
be70a5f149 | ||
|
|
7d2bd63912 | ||
|
|
6f69304796 | ||
|
|
6802f11497 | ||
|
|
f888acdcd3 | ||
|
|
41fae1e41b | ||
|
|
bf61f649fa | ||
|
|
fc9d8a85a2 | ||
|
|
6f664ce9e9 | ||
|
|
5d715fba99 | ||
|
|
e98aca30b3 | ||
|
|
df76abdbb0 | ||
|
|
8568aa2c1e | ||
|
|
aba4e8c8ac | ||
|
|
ff6825cedd | ||
|
|
0ede205530 | ||
|
|
a738618dd3 | ||
|
|
8dcebdcc55 | ||
|
|
1b3e4aa61f | ||
|
|
0281b8e321 | ||
|
|
58c5b27922 | ||
|
|
4a34c9bbdd |
@@ -1,8 +1,12 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
# Every branch, not just main. The pre-commit hook now scopes its checks to
|
||||
# the files that changed (see .husky/pre-commit), which is only safe because
|
||||
# the full suite runs here on every push — previously a feature branch got no
|
||||
# remote verification at all until a PR was opened.
|
||||
push:
|
||||
branches: [main]
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
name: Discord announce
|
||||
|
||||
# Two channels, deliberately asymmetric.
|
||||
#
|
||||
# staff — posts AUTOMATICALLY when semantic-release publishes a release.
|
||||
# The post carries a link back to this workflow, so the review and
|
||||
# the publish button are the same artefact.
|
||||
# public — only ever from a manual run. A release can never announce itself
|
||||
# to everyone without someone having read it first.
|
||||
#
|
||||
# Deliberately a SEPARATE workflow from release.yml: a Discord outage, a
|
||||
# rotated webhook or a rate limit must never fail a release that already
|
||||
# shipped. Re-run this job instead.
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
description: "Where to post."
|
||||
required: true
|
||||
type: choice
|
||||
default: staff
|
||||
options: [staff, public]
|
||||
since:
|
||||
description: "Roll up every release after this tag (e.g. v2.10.2). Blank = latest release only."
|
||||
required: false
|
||||
type: string
|
||||
dry_run:
|
||||
description: "Print the message instead of posting it."
|
||||
required: false
|
||||
type: boolean
|
||||
default: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
announce:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: "22"
|
||||
# setup-node sniffs the lockfile and tries to prime a pnpm cache,
|
||||
# which fails because pnpm is never installed here. It is not needed:
|
||||
# the announce script has no dependencies at all — plain ESM and the
|
||||
# global fetch built into Node 18+. Nothing is installed, so there is
|
||||
# nothing to cache.
|
||||
package-manager-cache: false
|
||||
|
||||
# A `release` event always posts, and always to staff. A dispatch honours
|
||||
# both inputs, with dry_run defaulting to true so a manual run cannot
|
||||
# surprise anyone.
|
||||
- name: Announce
|
||||
env:
|
||||
DISCORD_WEBHOOK_STAFF: ${{ secrets.DISCORD_WEBHOOK_STAFF }}
|
||||
DISCORD_WEBHOOK_PUBLIC: ${{ secrets.DISCORD_WEBHOOK_PUBLIC }}
|
||||
# Kept so an existing single-webhook setup keeps working as staff.
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||
DISCORD_ROLE_ID: ${{ secrets.DISCORD_ROLE_ID }}
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
GITHUB_EVENT_NAME: ${{ github.event_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
ARGS=""
|
||||
|
||||
if [ "${{ github.event_name }}" = "release" ]; then
|
||||
ARGS="--version ${{ github.event.release.tag_name }} --channel staff --post"
|
||||
else
|
||||
ARGS="--channel ${{ inputs.channel }}"
|
||||
if [ -n "${{ inputs.since }}" ]; then
|
||||
ARGS="$ARGS --since ${{ inputs.since }}"
|
||||
fi
|
||||
if [ "${{ inputs.dry_run }}" = "false" ]; then
|
||||
ARGS="$ARGS --post"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "Running: discord-announce.mjs $ARGS"
|
||||
node scripts/discord-announce.mjs $ARGS
|
||||
@@ -3,6 +3,25 @@ name: Release
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# Tooling-only pushes must not be able to cut a release, whatever their
|
||||
# commit type says.
|
||||
#
|
||||
# 2.13.0 shipped as an empty release because three commits touching only
|
||||
# `scripts/` and `.github/` were typed `feat(announce)` / `fix(announce)`.
|
||||
# Both are release-triggering, so semantic-release did exactly what it was
|
||||
# told — every user on 2.12.0 was offered an update with a blank changelog.
|
||||
# Relying on remembering to type those `ci:` had already failed once.
|
||||
#
|
||||
# Neither path is part of what a user installs: `scripts/` is dev tooling
|
||||
# and `.github/` is CI. GitHub skips the run only when EVERY changed file
|
||||
# matches, so a push that touches shipped code alongside a workflow still
|
||||
# releases correctly.
|
||||
#
|
||||
# `docs/**` is deliberately NOT here — `docs(readme)` is configured to bump
|
||||
# a patch, and `docs/release-notes/next.md` is the release body itself.
|
||||
paths-ignore:
|
||||
- 'scripts/**'
|
||||
- '.github/**'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
@@ -52,6 +52,9 @@ Thumbs.db
|
||||
/docs/*
|
||||
!/docs/help/
|
||||
!/docs/import-export-contract.md
|
||||
# Curated release highlights — read by .releaserc.js at release time, so it
|
||||
# must be tracked (the release step commits the cleared file back).
|
||||
!/docs/release-notes/
|
||||
|
||||
# Semantic release
|
||||
.releaserc.local.js
|
||||
@@ -62,3 +65,4 @@ Thumbs.db
|
||||
# DB location control — per-contributor sidecar config + root-location DB dir
|
||||
db-config.json
|
||||
/db/
|
||||
.tmp-check/
|
||||
|
||||
+64
-14
@@ -1,18 +1,68 @@
|
||||
# Lint + typecheck + frontend tests
|
||||
pnpm lint || exit 1
|
||||
pnpm typecheck || exit 1
|
||||
pnpm test || exit 1
|
||||
# Pre-commit gate, scoped to what actually changed.
|
||||
#
|
||||
# This used to run the whole CI suite on every commit — lint, typecheck, the
|
||||
# full 4000-test vitest run, a build, the size gate, ruff and the full pytest
|
||||
# suite — about 4.5 minutes regardless of whether the commit touched one Vue
|
||||
# file or one markdown file. CI (.github/workflows/ci.yml) now runs on every
|
||||
# push, not just main, so the local hook's job is to catch mistakes fast rather
|
||||
# than re-prove the whole tree.
|
||||
#
|
||||
# Measured on this machine:
|
||||
# lint 11s · typecheck 18s · full vitest 150s · build 10s · size 2s
|
||||
# ruff 0s · full pytest 76s · vitest scoped to changed files ~30s
|
||||
#
|
||||
# So a frontend-only commit drops from ~4.5min to ~70s, a Python-only commit
|
||||
# skips the JS half, and a docs-only commit exits immediately.
|
||||
#
|
||||
# Escape hatch: `WP_FULL=1 git commit …` runs everything, unscoped.
|
||||
|
||||
# Bundle size budget — build the extension chunk and run the size check so
|
||||
# regressions get caught locally before the CI flags them on PR. Skips when
|
||||
# js/ output already matches the source by mtime to keep repeat commits fast.
|
||||
pnpm build:extension || exit 1
|
||||
pnpm size || exit 1
|
||||
staged=$(git diff --cached --name-only --diff-filter=ACMR)
|
||||
[ -z "$staged" ] && exit 0
|
||||
|
||||
# Python checks — only if ruff/pytest reachable on PATH
|
||||
if command -v ruff >/dev/null 2>&1; then
|
||||
ruff check . || exit 1
|
||||
has() { echo "$staged" | grep -qE "$1"; }
|
||||
|
||||
FRONT=0
|
||||
PY=0
|
||||
# Anything that can change the bundle or its types.
|
||||
has '^(src/|scripts/|package\.json|pnpm-lock\.yaml|vite\.|tsconfig|eslint)' && FRONT=1
|
||||
# Anything the Python suites cover.
|
||||
has '(\.py$|^(engine/|wp_nodes/|wp_api/|tests/|pyproject\.toml))' && PY=1
|
||||
|
||||
if [ "$WP_FULL" = "1" ]; then
|
||||
FRONT=1
|
||||
PY=1
|
||||
fi
|
||||
if command -v pytest >/dev/null 2>&1; then
|
||||
pytest -q || exit 1
|
||||
|
||||
if [ "$FRONT" = "1" ]; then
|
||||
pnpm lint || exit 1
|
||||
pnpm typecheck || exit 1
|
||||
|
||||
# Only the tests reachable from the staged sources. `vitest related` walks
|
||||
# the import graph, so a change to a shared module still pulls in every
|
||||
# dependent suite — narrower than the full run, not weaker for the code
|
||||
# being committed. CI still runs the whole suite with coverage.
|
||||
if [ "$WP_FULL" = "1" ]; then
|
||||
pnpm test || exit 1
|
||||
else
|
||||
changed_src=$(echo "$staged" | grep -E '^src/.*\.(ts|vue)$' | tr '\n' ' ')
|
||||
if [ -n "$changed_src" ]; then
|
||||
# shellcheck disable=SC2086
|
||||
pnpm exec vitest related --run $changed_src || exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Bundle budget — cheap, and a regression here stays invisible until release.
|
||||
pnpm build:extension || exit 1
|
||||
pnpm size || exit 1
|
||||
fi
|
||||
|
||||
if [ "$PY" = "1" ]; then
|
||||
if command -v ruff >/dev/null 2>&1; then
|
||||
ruff check . || exit 1
|
||||
fi
|
||||
if command -v pytest >/dev/null 2>&1; then
|
||||
pytest -q || exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
exit 0
|
||||
|
||||
+38
-14
@@ -18,6 +18,21 @@
|
||||
* notes shrink to just the meaningful changes (typically <50 entries
|
||||
* per release).
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
|
||||
// Curated, human-readable highlights for the NEXT release. A maintainer
|
||||
// writes plain-language "what changed for you" bullets here before merging a
|
||||
// release; if the file is empty/absent the release body simply falls back to
|
||||
// the auto-generated grouped changelog. The file is read at release time (in
|
||||
// CI) and cleared by the prepare step below so highlights never repeat.
|
||||
const HIGHLIGHTS_FILE = "docs/release-notes/next.md";
|
||||
let highlights = "";
|
||||
try {
|
||||
highlights = fs.readFileSync(HIGHLIGHTS_FILE, "utf8").trim();
|
||||
} catch {
|
||||
/* no curated highlights for this release */
|
||||
}
|
||||
|
||||
export default {
|
||||
branches: ["main"],
|
||||
plugins: [
|
||||
@@ -69,24 +84,30 @@ export default {
|
||||
],
|
||||
},
|
||||
writerOpts: {
|
||||
// headerPartial puts a fixed "TL;DR + useful links" block at
|
||||
// the very top of every release body, so the first ~600
|
||||
// chars GitHub renders above the "Read more" fold on the
|
||||
// releases list view stay useful no matter how long the
|
||||
// changelog gets. {{version}} expands to the new tag.
|
||||
// The body IS the curated notes. See docs/release-notes/next.md for
|
||||
// the structure and the rules that keep it short.
|
||||
//
|
||||
// The per-commit list used to be inlined here inside a <details>.
|
||||
// It was dropped: with the hidden-type filter already applied it
|
||||
// said the same things as the curated notes, only worse, and it grew
|
||||
// linearly with the release (81 entries for this one). A compare
|
||||
// link is strictly more useful -- diffable, searchable, one line.
|
||||
headerPartial:
|
||||
"## 🎉 Wildcard Pipeline {{version}}\n\n" +
|
||||
"📖 [Docs (wiki)](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki) · " +
|
||||
"💬 [Discord](https://discord.gg/BFYR9WQdVR) · " +
|
||||
"📦 [Install via ComfyUI Manager](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki/Quick-Start) · " +
|
||||
"🐛 [Issues](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues)\n\n" +
|
||||
"<details>\n" +
|
||||
"<summary><b>📋 Full changelog</b> — click to expand the per-commit list</summary>\n\n",
|
||||
// footerPartial closes the <details> wrapper so the wall of
|
||||
// commits stays collapsed by default. GitHub renders
|
||||
// <details> natively in markdown — readers click to expand
|
||||
// when they actually need the per-commit log.
|
||||
footerPartial: "\n</details>",
|
||||
(highlights ? `${highlights}\n\n` : ""),
|
||||
// Compare link instead of the commit dump.
|
||||
footerPartial:
|
||||
"\n---\n\n**Full changelog:** " +
|
||||
"[{{previousTag}}…{{currentTag}}]" +
|
||||
"(https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/compare/{{previousTag}}...{{currentTag}})\n",
|
||||
// Render no commit sections. The curated notes above ARE the release
|
||||
// notes; commits still drive the version bump (see commit-analyzer)
|
||||
// and still live in git -- they are simply not restated here.
|
||||
transform: () => false,
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -102,14 +123,17 @@ export default {
|
||||
// @semantic-release/github plugin can attach it to the
|
||||
// release. Zip is built AFTER versioning so the file lands
|
||||
// with the right version in its name.
|
||||
// 3. Clear the consumed highlights file so the next release starts
|
||||
// from a clean slate (the content already lives in this release's
|
||||
// notes + CHANGELOG.md).
|
||||
prepareCmd:
|
||||
"node -e \"const fs=require('fs');const p=JSON.parse(fs.readFileSync('package.json'));p.version='${nextRelease.version}';fs.writeFileSync('package.json',JSON.stringify(p,null,2)+'\\n');const t=fs.readFileSync('pyproject.toml','utf8').replace(/^version = \\\".+?\\\"/m,'version = \\\"${nextRelease.version}\\\"');fs.writeFileSync('pyproject.toml',t);\" && node scripts/pack-release.mjs ${nextRelease.version}",
|
||||
"node -e \"const fs=require('fs');const p=JSON.parse(fs.readFileSync('package.json'));p.version='${nextRelease.version}';fs.writeFileSync('package.json',JSON.stringify(p,null,2)+'\\n');const t=fs.readFileSync('pyproject.toml','utf8').replace(/^version = \\\".+?\\\"/m,'version = \\\"${nextRelease.version}\\\"');fs.writeFileSync('pyproject.toml',t);\" && node -e \"require('fs').writeFileSync('docs/release-notes/next.md','')\" && node scripts/pack-release.mjs ${nextRelease.version}",
|
||||
},
|
||||
],
|
||||
[
|
||||
"@semantic-release/git",
|
||||
{
|
||||
assets: ["CHANGELOG.md", "package.json", "pyproject.toml"],
|
||||
assets: ["CHANGELOG.md", "package.json", "pyproject.toml", "docs/release-notes/next.md"],
|
||||
// Plain message — `${nextRelease.notes}` here would expand to
|
||||
// the entire changelog, which on a divergent history (where
|
||||
// semantic-release can't find the last tag in main's first-
|
||||
|
||||
+472
@@ -1,3 +1,475 @@
|
||||
## 🎉 Wildcard Pipeline 2.13.2
|
||||
|
||||
📖 [Docs (wiki)](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki) · 💬 [Discord](https://discord.gg/BFYR9WQdVR) · 📦 [Install via ComfyUI Manager](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki/Quick-Start) · 🐛 [Issues](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues)
|
||||
|
||||
### Firefox: the editor no longer dies when you insert a nested reference
|
||||
|
||||
Picking a wildcard from the `@` autocomplete could take down the whole editor —
|
||||
the field stopped accepting text, Backspace did nothing, and Save and Cancel
|
||||
stopped responding until the page was reloaded. Select-all then cut inside an
|
||||
option value did the same thing.
|
||||
|
||||
Both were the same cause. Firefox removes the empty text nodes that Vue uses to
|
||||
mark where each chip and text run begins and ends, and once they are gone any
|
||||
edit that adds or removes a chip runs off the end of the field's contents.
|
||||
Chromium keeps those markers, which is why this only ever happened on Firefox
|
||||
and never reproduced during development.
|
||||
|
||||
The editor now notices when those markers have been removed and rebuilds the
|
||||
field instead of tripping over them. This affects every rich text field —
|
||||
option values, combine templates, derivation rules and injector bindings, on
|
||||
the canvas and in the manager alike.
|
||||
|
||||
### Your library is protected against version mismatches
|
||||
|
||||
If a database has been through migrations that this build does not recognise —
|
||||
after downgrading, hand-installing an older copy, or switching versions in
|
||||
ComfyUI Manager — Wildcard Pipeline now stops with a clear message instead of
|
||||
quietly reading a library it does not understand. Previously it carried on, and
|
||||
every later edit was written through assumptions that no longer held.
|
||||
|
||||
### Release archives now include the interface translations
|
||||
|
||||
The release zip was missing `locales/`, so node names, descriptions and setting
|
||||
labels fell back to raw identifiers for anyone installing from it. Installs
|
||||
from ComfyUI Manager and the Comfy Registry were unaffected.
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
**Full changelog:** [v2.13.1…v2.13.2](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/compare/v2.13.1...v2.13.2)
|
||||
|
||||
## 🎉 Wildcard Pipeline 2.13.1
|
||||
|
||||
📖 [Docs (wiki)](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki) · 💬 [Discord](https://discord.gg/BFYR9WQdVR) · 📦 [Install via ComfyUI Manager](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki/Quick-Start) · 🐛 [Issues](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues)
|
||||
|
||||
A security fix for the database location setting. Update when you can.
|
||||
|
||||
> **Already on 2.13.0?** This is the same release. 2.13.0 reached GitHub but not the
|
||||
> ComfyUI Registry, so it never arrived for anyone installing through ComfyUI Manager.
|
||||
> 2.13.1 is that same build under a version number the registry will accept — nothing
|
||||
> in it differs.
|
||||
|
||||
### Highlights
|
||||
|
||||
- **The "move the database" setting could be abused to touch other files.** Changing the database location schedules a file copy or move that runs the next time ComfyUI starts. The two paths were only checked for being absolute, not for being database locations — so a request sent to your ComfyUI port could have scheduled a copy or move between any two files on the machine, including reading a file by copying it somewhere this plugin serves over HTTP. ComfyUI's API has no authentication, so anything that can reach the port could do this. Both paths are now restricted to the three locations the database is actually allowed to live in. Moving your database between those locations works exactly as before.
|
||||
|
||||
- **What's new now shows the releases you skipped.** The page only ever showed the newest release, so updating across two versions meant the middle one's notes were simply gone — 2.12.0 was current for about an hour before this release replaced it. The last few releases are now listed underneath, collapsed, each with its own notes. **All releases** also goes to the releases index now instead of to the single release it was labelled against.
|
||||
|
||||
<!-- /modal -->
|
||||
|
||||
### Upgrade notes
|
||||
|
||||
Nothing to do beyond updating. No settings change, and any database move you had queued still runs normally.
|
||||
|
||||
If you expose ComfyUI beyond your own machine, this one is worth taking promptly — the affected setting is reachable without a login on every install of 2.11.0 and 2.12.0.
|
||||
|
||||
<!--
|
||||
HOW TO WRITE THIS FILE
|
||||
|
||||
Order, and nothing else:
|
||||
|
||||
Headline one sentence, what this release is about
|
||||
### Highlights 4-5 max
|
||||
<!- /modal -> the update dialog stops rendering here
|
||||
<details> Also in this… grouped one-liners, collapsed
|
||||
### Upgrade notes only when the reader must act; delete otherwise
|
||||
— keep this OUTSIDE the <details>, it needs seeing
|
||||
|
||||
This file IS the release body — the compare link is appended automatically and
|
||||
the per-commit list is deliberately not included. It is consumed at release
|
||||
time and cleared afterwards, so anything left here ships.
|
||||
|
||||
RULES
|
||||
|
||||
1. Highlights are capped at 4-5. The cap is the mechanism: it is what keeps a
|
||||
6-commit release and an 80-commit release roughly the same height. If a
|
||||
sixth feels essential, something else was not a highlight.
|
||||
|
||||
2. A highlight passes one of three tests:
|
||||
- new capability — you can do something you could not before
|
||||
- wall removed — something that blocked you now works
|
||||
- surprising — behaviour changed in a way you should not meet alone
|
||||
Polish, truncation, layout and invisible perf fail all three.
|
||||
|
||||
3. Commit count is NOT a test. The categories icon picker was two commits and a
|
||||
real feature; `ui` was nine commits and almost entirely polish.
|
||||
|
||||
4. The tail is grouped by area, one line each, no bold-lead paragraphs. Group
|
||||
names are free-form — use whatever the release actually contains. It sits in
|
||||
a <details> so a long release does not double the page; put the count in the
|
||||
summary so the reader knows what they are opening. That number is written by
|
||||
hand here and can drift — the update dialog computes its own from the same
|
||||
bullets, so if the two disagree, this one is wrong. Note also that collapsed
|
||||
text is not reliably reachable by browser find-in-page, which is the cost.
|
||||
|
||||
5. Write what changed for the user, not what changed in the code. Name the
|
||||
symptom, not the fix: "the field went blank" beats "guarded a null deref".
|
||||
|
||||
6. Perf belongs in the tail WITH its numbers, so the people it affects
|
||||
recognise themselves. "Performance improvements" tells nobody anything.
|
||||
|
||||
7. Security fixes say what an attacker could have done, in plain language, and
|
||||
whether the reader must act. Never ship one as "hardening" or "internal
|
||||
improvements" — someone deciding whether to update tonight needs the facts,
|
||||
and vagueness reads as a cover-up once the diff is public anyway.
|
||||
-->
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
**Full changelog:** [v2.13.0…v2.13.1](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/compare/v2.13.0...v2.13.1)
|
||||
|
||||
## 🎉 Wildcard Pipeline 2.13.0
|
||||
|
||||
📖 [Docs (wiki)](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki) · 💬 [Discord](https://discord.gg/BFYR9WQdVR) · 📦 [Install via ComfyUI Manager](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki/Quick-Start) · 🐛 [Issues](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues)
|
||||
|
||||
A security fix for the database location setting. Update when you can.
|
||||
|
||||
### Highlights
|
||||
|
||||
- **The "move the database" setting could be abused to touch other files.** Changing the database location schedules a file copy or move that runs the next time ComfyUI starts. The two paths were only checked for being absolute, not for being database locations — so a request sent to your ComfyUI port could have scheduled a copy or move between any two files on the machine, including reading a file by copying it somewhere this plugin serves over HTTP. ComfyUI's API has no authentication, so anything that can reach the port could do this. Both paths are now restricted to the three locations the database is actually allowed to live in. Moving your database between those locations works exactly as before.
|
||||
|
||||
- **What's new now shows the releases you skipped.** The page only ever showed the newest release, so updating across two versions meant the middle one's notes were simply gone — 2.12.0 was current for about an hour before this release replaced it. The last few releases are now listed underneath, collapsed, each with its own notes. **All releases** also goes to the releases index now instead of to the single release it was labelled against.
|
||||
|
||||
<!-- /modal -->
|
||||
|
||||
### Upgrade notes
|
||||
|
||||
Nothing to do beyond updating. No settings change, and any database move you had queued still runs normally.
|
||||
|
||||
If you expose ComfyUI beyond your own machine, this one is worth taking promptly — the affected setting is reachable without a login on every install of 2.11.0 and 2.12.0.
|
||||
|
||||
<!--
|
||||
HOW TO WRITE THIS FILE
|
||||
|
||||
Order, and nothing else:
|
||||
|
||||
Headline one sentence, what this release is about
|
||||
### Highlights 4-5 max
|
||||
<!- /modal -> the update dialog stops rendering here
|
||||
<details> Also in this… grouped one-liners, collapsed
|
||||
### Upgrade notes only when the reader must act; delete otherwise
|
||||
— keep this OUTSIDE the <details>, it needs seeing
|
||||
|
||||
This file IS the release body — the compare link is appended automatically and
|
||||
the per-commit list is deliberately not included. It is consumed at release
|
||||
time and cleared afterwards, so anything left here ships.
|
||||
|
||||
RULES
|
||||
|
||||
1. Highlights are capped at 4-5. The cap is the mechanism: it is what keeps a
|
||||
6-commit release and an 80-commit release roughly the same height. If a
|
||||
sixth feels essential, something else was not a highlight.
|
||||
|
||||
2. A highlight passes one of three tests:
|
||||
- new capability — you can do something you could not before
|
||||
- wall removed — something that blocked you now works
|
||||
- surprising — behaviour changed in a way you should not meet alone
|
||||
Polish, truncation, layout and invisible perf fail all three.
|
||||
|
||||
3. Commit count is NOT a test. The categories icon picker was two commits and a
|
||||
real feature; `ui` was nine commits and almost entirely polish.
|
||||
|
||||
4. The tail is grouped by area, one line each, no bold-lead paragraphs. Group
|
||||
names are free-form — use whatever the release actually contains. It sits in
|
||||
a <details> so a long release does not double the page; put the count in the
|
||||
summary so the reader knows what they are opening. That number is written by
|
||||
hand here and can drift — the update dialog computes its own from the same
|
||||
bullets, so if the two disagree, this one is wrong. Note also that collapsed
|
||||
text is not reliably reachable by browser find-in-page, which is the cost.
|
||||
|
||||
5. Write what changed for the user, not what changed in the code. Name the
|
||||
symptom, not the fix: "the field went blank" beats "guarded a null deref".
|
||||
|
||||
6. Perf belongs in the tail WITH its numbers, so the people it affects
|
||||
recognise themselves. "Performance improvements" tells nobody anything.
|
||||
|
||||
7. Security fixes say what an attacker could have done, in plain language, and
|
||||
whether the reader must act. Never ship one as "hardening" or "internal
|
||||
improvements" — someone deciding whether to update tonight needs the facts,
|
||||
and vagueness reads as a cover-up once the diff is public anyway.
|
||||
-->
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
**Full changelog:** [v2.12.0…v2.13.0](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/compare/v2.12.0...v2.13.0)
|
||||
|
||||
## 🎉 Wildcard Pipeline 2.12.0
|
||||
|
||||
📖 [Docs (wiki)](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki) · 💬 [Discord](https://discord.gg/BFYR9WQdVR) · 📦 [Install via ComfyUI Manager](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki/Quick-Start) · 🐛 [Issues](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues)
|
||||
|
||||
Full support for ComfyUI's Nodes 2.0 renderer, and a pass over everything to do with knowing where a value came from.
|
||||
|
||||
### Highlights
|
||||
|
||||
- **Every node works under Nodes 2.0.** ComfyUI's new Vue renderer changed how nodes are laid out, sized and scrolled, and our widgets were built against the old one. Nodes now render, resize, scroll and merge their wires correctly under both renderers — including switching between them with a workflow already open.
|
||||
- **See where a variable or reference comes from.** Hover any `$var` or `@{ref}` chip and the card names the module that writes it, the node it lives in, and — for references — the pool it resolves against and how many options currently match. Variables produced by a Context Injector, by a sibling module, or by another node are all attributed instead of reading "binds at runtime".
|
||||
- **The `@` and `$` pickers were rebuilt.** Rows carry an identity so two similarly-named entries are tellable apart, pools supplied by a node are marked as such, and the sub-category filter panel is redesigned — chips reflect the parsed expression, and exception values get a picker of real option values instead of a free-text box.
|
||||
- **Wildcard options and fixed values became editable at scale.** A pinned search bar, tag filtering, drag-to-reorder, and bulk edit that can move rows to top or bottom and add or remove sub-categories across a selection.
|
||||
- **Text editing in options no longer breaks.** Cut, paste and select-all could leave a field stuck, mangled, or typing into the wrong place, and a selection would skip over chips. Keystrokes also no longer escape a modal into ComfyUI's global shortcuts — pressing a plain letter could trigger a node-definition refresh and freeze the page.
|
||||
|
||||
<!-- /modal -->
|
||||
|
||||
<details>
|
||||
<summary><b>Also in this release</b> — 26 smaller changes</summary>
|
||||
|
||||
**Sequences and seeds**
|
||||
|
||||
- Lock a frame's seed or bypass it straight from its chip on the Context Loop — shift-click to lock, alt-click to bypass — instead of opening the per-iteration seeds dialog
|
||||
- The Seed List gets the same frame chips; clicking one locks its seed, and frames bypassed by a wired Context Loop are shown but not editable there, since that setting belongs to the loop
|
||||
- The frame grid collapses, and scrolls once it outgrows four rows, so a hundred-frame loop no longer owns the canvas. Collapsed state is saved with the workflow, and the header keeps reporting how many frames are locked or bypassed
|
||||
|
||||
**Library and organisation**
|
||||
|
||||
- Categories get an icon picker, and the icon follows the category everywhere it appears
|
||||
- Export and import pickers gain cross-bucket search and per-row detail (`$variable`, option counts)
|
||||
- Copy payload emits an importable envelope, stamped with its schema version
|
||||
- Re-link matches bundles on child content rather than only a stored hash, and offers itself for modules that have no hash at all
|
||||
- An unlinked bundle now reads as missing rather than modified, and reset-to-snapshot refuses to empty one
|
||||
|
||||
**Chips and references**
|
||||
|
||||
- Nested `@{uuid}` references are discovered even when written outside a wildcard payload
|
||||
- Reference hovers name the pool they counted and flag drift against the library
|
||||
- Wildcard option chips get the same hover card as every other surface
|
||||
- Sub-category filter state is derived from the parsed expression, so the chips match what the filter actually does
|
||||
- A reference to a module you have deleted from the library now reads as broken. It used to keep the deleted module's name and colour, and its hover card quoted the option count the module had before it was deleted — the node badge said the reference was broken while the chip inside the editor disagreed
|
||||
|
||||
**The manager**
|
||||
|
||||
- **What's new** moved to its own page, reached from the topbar with a dot when there is something unread. It is also the only place to read the notes for the version you are running — the update pill only exists while a newer one is available
|
||||
- The update check no longer burns through GitHub's hourly allowance. It was making one request per page load per consumer, so a few dozen reloads could exhaust the quota for everything else on that connection; results are now reused for six hours and a refusal is honoured rather than retried
|
||||
|
||||
**Editing and layout**
|
||||
|
||||
- Fixed-value and combine fields grow with their content, with a corner grip that stays reachable and a manual drag that overrides the auto height
|
||||
- A scrollable field no longer hands its scroll to the page behind it
|
||||
- Rule previews truncate with an ellipsis instead of being clipped or faded, and long values wrap
|
||||
- Tag menus stay inside the viewport, keep their own scroll, and fold by axis
|
||||
- Dropdowns say "type to filter", which they have always supported
|
||||
- The save shortcut reads `Ctrl` on Windows and Linux instead of a Mac-only glyph
|
||||
- Test-runner histogram rows are banded so a row reads across its columns, and its module picker survives duplicate names
|
||||
|
||||
**Performance and correctness**
|
||||
|
||||
- Canvas polling is roughly eight times cheaper on a large graph — the walkers now share one parse instead of re-parsing a 294 KB widget value ten times per node every cycle (~21% of a core down to ~2.6%)
|
||||
- Wildcard snapshots refresh when the window regains focus instead of waiting out a timer, and expire so the canvas stops drifting from the library
|
||||
- The Prompt Cleaner no longer rewrites `embedding:name` or `<lora:name:1.0>` references — punctuation stripping renamed embeddings ending in `_`, and fuzzy dedupe dropped one of two versioned files
|
||||
- Variable override counts report writers rather than write statements, so a module that creates a variable is no longer described as overriding writes that never happened
|
||||
|
||||
</details>
|
||||
|
||||
<!--
|
||||
HOW TO WRITE THIS FILE
|
||||
|
||||
Order, and nothing else:
|
||||
|
||||
Headline one sentence, what this release is about
|
||||
### Highlights 4-5 max
|
||||
<!- /modal -> the update dialog stops rendering here
|
||||
<details> Also in this… grouped one-liners, collapsed
|
||||
### Upgrade notes only when the reader must act; delete otherwise
|
||||
— keep this OUTSIDE the <details>, it needs seeing
|
||||
|
||||
This file IS the release body — the compare link is appended automatically and
|
||||
the per-commit list is deliberately not included. It is consumed at release
|
||||
time and cleared afterwards, so anything left here ships.
|
||||
|
||||
RULES
|
||||
|
||||
1. Highlights are capped at 4-5. The cap is the mechanism: it is what keeps a
|
||||
6-commit release and an 80-commit release roughly the same height. If a
|
||||
sixth feels essential, something else was not a highlight.
|
||||
|
||||
2. A highlight passes one of three tests:
|
||||
- new capability — you can do something you could not before
|
||||
- wall removed — something that blocked you now works
|
||||
- surprising — behaviour changed in a way you should not meet alone
|
||||
Polish, truncation, layout and invisible perf fail all three.
|
||||
|
||||
3. Commit count is NOT a test. The categories icon picker was two commits and a
|
||||
real feature; `ui` was nine commits and almost entirely polish.
|
||||
|
||||
4. The tail is grouped by area, one line each, no bold-lead paragraphs. Group
|
||||
names are free-form — use whatever the release actually contains. It sits in
|
||||
a <details> so a long release does not double the page; put the count in the
|
||||
summary so the reader knows what they are opening. That number is written by
|
||||
hand here and can drift — the update dialog computes its own from the same
|
||||
bullets, so if the two disagree, this one is wrong. Note also that collapsed
|
||||
text is not reliably reachable by browser find-in-page, which is the cost.
|
||||
|
||||
5. Write what changed for the user, not what changed in the code. Name the
|
||||
symptom, not the fix: "the field went blank" beats "guarded a null deref".
|
||||
|
||||
6. Perf belongs in the tail WITH its numbers, so the people it affects
|
||||
recognise themselves. "Performance improvements" tells nobody anything.
|
||||
-->
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
**Full changelog:** [v2.11.0…v2.12.0](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/compare/v2.11.0...v2.12.0)
|
||||
|
||||
## 🎉 Wildcard Pipeline 2.11.0
|
||||
|
||||
📖 [Docs (wiki)](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki) · 💬 [Discord](https://discord.gg/BFYR9WQdVR) · 📦 [Install via ComfyUI Manager](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki/Quick-Start) · 🐛 [Issues](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues)
|
||||
|
||||
### ✨ What's new
|
||||
|
||||
A correctness fix for held modules on multi-frame runs, plus a set of tools for reconnecting workflow items to your library.
|
||||
|
||||
- **Held modules stay held for the whole run.** On a multi-frame sequence, a module set to **Hold across run** could quietly re-roll after the first frame — a held outfit or location would change mid-sequence — and every frame after the first filled the debug panel with constraint warnings. Held picks now carry through every frame, so constraints that depend on them keep applying, cross-node holds stay put, and the warning flood is gone.
|
||||
- **Re-link items that lost their library connection.** When a re-import gives a library entry a new id, the copy in your workflow stops matching it: no drift, no **Edit library entry in SPA**, and saving creates a duplicate. **Push to library** now offers **Re-link to an existing library entry** when it finds one holding the same content — picking it automatically when there's exactly one match, or letting you choose from a list you can search by name *or* id. Works for bundles too.
|
||||
- **Disconnected items now show as drifted** instead of looking like local-only rows. That means the **refresh drifted** button reconnects them in one click, and the library link, drift dot and refresh action all start working again.
|
||||
- **"Reset to library snapshot" can no longer empty a bundle.** If the bundle wasn't linked to a library entry, or the snapshot came back empty, reset used to replace your modules with nothing. It now refuses and explains why, leaving the bundle untouched.
|
||||
- **Importing content you already have offers to link it.** When an import contains an item identical to one already in your library under a different id, it's flagged **IN LIBRARY** with the matching entry named, and you can either link to it — references follow to the existing entry — or import the copy anyway. Nothing is linked or overwritten without you choosing.
|
||||
- **Every edit modal shows the item's id.** A small chip in the header, click to copy — the same id that `@{...}` references, constraint sources and library rows all match on.
|
||||
- **Nested references and variables render as chips** in derivation rule values and constraint exceptions, instead of showing raw text inside `{a|b}` braces. Exception values also get a proper picker of real option values rather than a free-text box.
|
||||
- **Hover any reference chip** to see what it resolves to: its id, its sub-category filter in plain language, and how many options currently match — read live from your library, so the count moves when the library does.
|
||||
- **Search by id.** Pasting an 8-character id into a search box now finds the item, in the manager lists and in the remap / reattach pickers. Previously only names matched, which was useless when two entries shared one.
|
||||
- **Long values wrap** in the derivation override boxes instead of being clipped at the edge of the field.
|
||||
|
||||
---
|
||||
|
||||
<details>
|
||||
<summary><b>📋 Full changelog</b> — click to expand the per-commit list</summary>
|
||||
|
||||
|
||||
* Merge pull request #11 from DumiFlex/fix/held-constraint-registration ([fd4c501](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/fd4c501)), closes [#11](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/11)
|
||||
* docs(release-notes): summarise held-module fix + library re-link tooling ([9fb653f](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/9fb653f))
|
||||
* chore(size): raise total bundle budget to 461 KB ([3f45b26](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/3f45b26))
|
||||
* fix(bundle): never let "Reset to library snapshot" silently empty a bundle ([78297c4](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/78297c4))
|
||||
* fix(chips): render nested refs + vars in derivation and exception surfaces ([a64e56d](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/a64e56d)), closes [label/#option](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/option)
|
||||
* fix(engine): carry held modules' frame-0 constraint state to later frames ([1b32a8a](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/1b32a8a))
|
||||
* fix(linkage): surface drift for a library-uuid module with an empty local hash ([bb5f6b8](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/bb5f6b8))
|
||||
* fix(search): match modules, bundles and templates by id as well as name ([44d0ca2](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/44d0ca2))
|
||||
* feat(chips): hover card on nested-ref and variable chips ([699deda](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/699deda))
|
||||
* feat(editors): show module identity in edit-modal headers + wrap long values ([5a83e61](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/5a83e61))
|
||||
* feat(import): link-to-existing decision for content duplicates (D3b core) ([e63be54](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/e63be54)), closes [#2](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/2)
|
||||
* feat(import): surface content duplicates as a resolvable conflict row (D3b) ([c268e75](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/c268e75))
|
||||
* feat(relink): content-aware library re-link for detached bundle instances ([ecebd55](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/ecebd55))
|
||||
* feat(relink): content-aware library re-link for detached module rows ([a059b48](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/a059b48))
|
||||
* feat(relink): content-aware re-link match + apply helpers (pure) ([9ef1fb6](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/9ef1fb6))
|
||||
|
||||
</details>
|
||||
|
||||
## 🎉 Wildcard Pipeline 2.10.2
|
||||
|
||||
📖 [Docs (wiki)](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki) · 💬 [Discord](https://discord.gg/BFYR9WQdVR) · 📦 [Install via ComfyUI Manager](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki/Quick-Start) · 🐛 [Issues](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues)
|
||||
|
||||
### ✨ What's new
|
||||
|
||||
A bug-fix release for the in-app updater and name validation.
|
||||
|
||||
- **Fixed an updater downgrade.** On 2.10.0, clicking **Update Now** could install an *older* version — it asked ComfyUI Manager for "latest" against a stale cache. The updater now installs the exact new version and refuses to ever move backwards.
|
||||
- **The update badge appears right away** after **Check now** — no page refresh needed.
|
||||
- **Cleaner release notes** in the update dialog (proper formatting instead of raw `<details>` tags).
|
||||
- **Names are validated as you rename them.** Renaming a sub-category or a variable now enforces the same rules as creating one, so invalid names (spaces, reserved characters) are caught immediately instead of failing later on save.
|
||||
|
||||
---
|
||||
|
||||
<details>
|
||||
<summary><b>📋 Full changelog</b> — click to expand the per-commit list</summary>
|
||||
|
||||
|
||||
* Merge pull request #10 from DumiFlex/fix/updater-downgrade ([a2e93fe](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/a2e93fe)), closes [#10](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/10)
|
||||
* fix(manager): prevent updater downgrade, fix pill reactivity + release notes ([1e42f9b](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/1e42f9b))
|
||||
|
||||
</details>
|
||||
|
||||
## 🎉 Wildcard Pipeline 2.10.1
|
||||
|
||||
📖 [Docs (wiki)](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki) · 💬 [Discord](https://discord.gg/BFYR9WQdVR) · 📦 [Install via ComfyUI Manager](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki/Quick-Start) · 🐛 [Issues](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues)
|
||||
|
||||
<details>
|
||||
<summary><b>📋 Full changelog</b> — click to expand the per-commit list</summary>
|
||||
|
||||
|
||||
* Merge pull request #9 from DumiFlex/fix/subcat-rename-validation ([74c7331](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/74c7331)), closes [#9](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/9) [#7](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/7)
|
||||
* fix(manager): validate names on rename via shared validators (#7) ([00b735d](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/00b735d)), closes [#7](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/7)
|
||||
|
||||
</details>
|
||||
|
||||
## 🎉 Wildcard Pipeline 2.10.0
|
||||
|
||||
📖 [Docs (wiki)](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki) · 💬 [Discord](https://discord.gg/BFYR9WQdVR) · 📦 [Install via ComfyUI Manager](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki/Quick-Start) · 🐛 [Issues](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues)
|
||||
|
||||
<details>
|
||||
<summary><b>📋 Full changelog</b> — click to expand the per-commit list</summary>
|
||||
|
||||
|
||||
* Merge pull request #8 from DumiFlex/feat/manager-qol ([fe2423f](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/fe2423f)), closes [#8](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/8)
|
||||
* feat(loop): add optional bypass toggle to seed-lock row ([d524d14](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/d524d14))
|
||||
* feat(loop): dashed border on bypassed edit-frame chips ([70283ce](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/70283ce))
|
||||
* feat(loop): emit only non-bypassed frames with pinned identity ([9d372b1](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/9d372b1))
|
||||
* feat(loop): mirror bypass_frames in the ts config type ([da2239d](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/da2239d))
|
||||
* feat(loop): mirror the loop's bypassed frames in the seed list UI ([f670c3d](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/f670c3d))
|
||||
* feat(loop): opt-in bypass column in the per-iteration modal ([651ca65](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/651ca65))
|
||||
* feat(loop): parse bypass_frames in the loop config ([7aab09d](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/7aab09d))
|
||||
* feat(loop): purple wash + dashed bar on bypassed seed rows ([ea4ed05](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/ea4ed05))
|
||||
* feat(loop): wire per-frame bypass through the loop widget ([7545ade](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/7545ade))
|
||||
* feat(manager): add checkOnLaunch update preference to uiStore ([d42b7ca](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/d42b7ca))
|
||||
* feat(manager): add ComfyUI Manager update composable ([327e7cc](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/327e7cc))
|
||||
* feat(manager): add safe markdown renderer for release notes ([830776e](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/830776e))
|
||||
* feat(manager): add UpdateDialog with changelog + Manager-driven update ([290e7a8](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/290e7a8))
|
||||
* feat(manager): add Updates settings card with check-on-launch + check now ([6c20f53](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/6c20f53))
|
||||
* feat(manager): bulk select + delete for exceptions + derivation rules (#11) ([ed10b88](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/ed10b88)), closes [#11](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/11)
|
||||
* feat(manager): bulk select + delete for fixed-values (#11) ([cbf102b](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/cbf102b)), closes [#11](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/11)
|
||||
* feat(manager): drag-and-drop file import (#5) ([d4e6d0c](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/d4e6d0c)), closes [#5](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/5)
|
||||
* feat(manager): move Target reach above the constraint rule matrix (#10a) ([d039364](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/d039364)), closes [#10a](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/10a)
|
||||
* feat(manager): open UpdateDialog from the topbar update pill ([936a139](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/936a139))
|
||||
* feat(manager): per-branch collapse + collapse-all for derivation rules (#9) ([8ea1571](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/8ea1571)), closes [#9](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/9)
|
||||
* feat(manager): per-kind quick-select presets + import-tab mirror (#1) ([8912937](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/8912937)), closes [#1](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/1)
|
||||
* feat(manager): per-rule branch collapse + collapse rules/branches by default ([fcde3b3](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/fcde3b3))
|
||||
* feat(manager): relevant + colour-coded bulk sub-category menus ([be70a5f](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/be70a5f)), closes [#3](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/3) [#4](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/4) [#3](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/3)
|
||||
* feat(manager): rework release check to launch-once + manual, expose release notes ([bdcf85c](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/bdcf85c))
|
||||
* feat(manager): sticky list headers across editors ([6802f11](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/6802f11))
|
||||
* fix(loop): parse parity + edge coverage from final review ([bab87cd](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/bab87cd))
|
||||
* fix(loop): seed list mirrors the loop's bypassed frames ([af95f08](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/af95f08))
|
||||
* fix(manager): count templates in the import loaded-bar total ([2295ce0](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/2295ce0))
|
||||
* fix(manager): detect bundle collisions on import instead of blind-adding (#6) ([b54302d](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/b54302d)), closes [#6](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/6)
|
||||
* fix(manager): fresh dates for imported adds (#12) + live counts after import (#7) ([696711d](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/696711d)), closes [#12](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/12) [#7](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/7) [#12](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/12) [#7](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues/7)
|
||||
* fix(manager): keep bulk-edit toolbar stuck with sticky card header ([6f69304](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/6f69304))
|
||||
* fix(manager): resolve inline multi-pick {N-M$$sep$$…} in the test runner ([8dcef0f](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/8dcef0f))
|
||||
* fix(manager): sticky-header subpixel bleed + confusing weight validation ([0bd4382](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/0bd4382))
|
||||
* test(engine): un-skip pipeline trace tests after handler migration ([7d2bd63](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/7d2bd63))
|
||||
|
||||
</details>
|
||||
|
||||
## 🎉 Wildcard Pipeline 2.9.0
|
||||
|
||||
📖 [Docs (wiki)](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki) · 💬 [Discord](https://discord.gg/BFYR9WQdVR) · 📦 [Install via ComfyUI Manager](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki/Quick-Start) · 🐛 [Issues](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues)
|
||||
|
||||
<details>
|
||||
<summary><b>📋 Full changelog</b> — click to expand the per-commit list</summary>
|
||||
|
||||
|
||||
* fix(derivation-modal): absolute max-height for the rules scroll (revert flex) ([5d715fb](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/5d715fb))
|
||||
* fix(derivation-modal): pin rule cards so the rule list actually scrolls ([fc9d8a8](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/fc9d8a8))
|
||||
* fix(derivation-modal): scroll the rule LIST, not the whole modal ([6f664ce](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/6f664ce))
|
||||
* fix(derivation-modal): scroll the rules region, pin header + footer ([e98aca3](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/e98aca3))
|
||||
* fix(engine): derivation hold freezes each branch roll, not the branch choice ([df76abd](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/df76abd))
|
||||
* fix(engine): hold the resolved VALUE across iterations, not just the seed ([58c5b27](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/58c5b27))
|
||||
* fix(injector): keep custom pin labels with the socket on drag-reorder ([41fae1e](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/41fae1e))
|
||||
* fix(injector): persist custom pin labels durably across collapse + reload ([8568aa2](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/8568aa2))
|
||||
* fix(injector): reconstruct collapsed-wire labels from data, not the dead stash ([0ede205](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/0ede205))
|
||||
* fix(injector): repair collapse-wire labels corrupted across a reload ([0281b8e](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/0281b8e))
|
||||
* fix(injector): right-align the type pill on label-less ref/slot rows ([bf61f64](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/bf61f64))
|
||||
* docs(spa): describe hold as a value freeze (constrained picks + nested refs) ([1b3e4aa](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/1b3e4aa))
|
||||
* docs(spa): document per-iteration overrides, seed scope + lock-previous ([4a34c9b](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/4a34c9b))
|
||||
* docs(spa): mention the right-click Hold toggle shortcut ([a738618](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/a738618))
|
||||
* docs(spa): note derivation supports Hold across run ([aba4e8c](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/aba4e8c))
|
||||
* feat(context): quick Hold toggle in the module row context menu ([8dcebdc](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/8dcebdc))
|
||||
* feat(engine): derivation honors seed_scope=hold (freeze frame-0 output) ([ff6825c](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/commit/ff6825c))
|
||||
|
||||
</details>
|
||||
|
||||
## 🎉 Wildcard Pipeline 2.8.0
|
||||
|
||||
📖 [Docs (wiki)](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki) · 💬 [Discord](https://discord.gg/BFYR9WQdVR) · 📦 [Install via ComfyUI Manager](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki/Quick-Start) · 🐛 [Issues](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/issues)
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="public/images/docs/flow-intro.svg" alt="Modules resolve inside WP Context → named $variables → WP Prompt Assembler → CLIP" />
|
||||
<img src="public/images/docs/flow-intro.svg" alt="Wildcard, Fixed Values, Combine, Derivation and Constraint modules resolve inside WP Context, which emits named $variables that fill the WP Prompt Assembler template, which CLIP Encode turns into conditioning" />
|
||||
</p>
|
||||
|
||||
## What it does
|
||||
@@ -33,6 +33,7 @@ Stock ComfyUI prompt nodes either take a single literal string or pick from a fl
|
||||
- **Persistent library** — a manager SPA backed by SQLite stores reusable modules, frozen bundles, prompt templates, and a category tree. Browse / edit / fork / push from the canvas.
|
||||
- **Inspector** — `WP Debug` shows the post-run snapshot, per-module trace, per-wildcard picks, and the conflict-scanner warnings.
|
||||
- **Type-coercion helpers** — `WP Var → Int / Float / Bool` parse typed values out of any `$variable` so wildcards can drive image width, step count, sampler cfg, conditional switches.
|
||||
- **Works on both renderers** — the legacy canvas and ComfyUI's Nodes 2.0 Vue renderer, including switching between them with a workflow already open.
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -105,7 +106,7 @@ Full module reference: [Modules wiki page](https://github.com/DumiFlex/ComfyUI-W
|
||||
## Looping a chain — one click, N coherent prompts
|
||||
|
||||
<p align="center">
|
||||
<img src="public/images/docs/flow-loop.svg" alt="WP Context Loop + WP Seed List → KSampler — both lists fan out in lockstep" />
|
||||
<img src="public/images/docs/flow-loop.svg" alt="WP Context Loop drives WP Context and the Prompt Assembler; CLIP Encode turns each prompt into conditioning for KSampler, while WP Seed List supplies the matching seed directly" />
|
||||
</p>
|
||||
|
||||
Drop `WP Context Loop` before your `WP Context` and pair it with `WP Seed List` for distinct sampler seeds. Both lists fan out in lockstep so iteration N's prompt always pairs with seed N. Each iteration carries its own `$iteration` / `$iteration_total` for in-template labelling (`frame 1 of 4 — a fox`). See [Concepts → Seeds and loops](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/wiki/Concepts#seeds-and-loops).
|
||||
@@ -145,7 +146,7 @@ See [Nodes → WP Debug](https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/w
|
||||
|
||||
## Status
|
||||
|
||||
Active development. Versioned releases with [semantic-release](https://github.com/semantic-release/semantic-release) — every merged commit on `main` either ships a release or stays as `next` until the next breaking / feature change rolls one. Bundle-size + test gates run on every PR.
|
||||
Active development. Versioned releases with [semantic-release](https://github.com/semantic-release/semantic-release) — every merged commit on `main` either ships a release or stays as `next` until the next breaking / feature change rolls one. Bundle-size + test gates run on every branch push and PR.
|
||||
|
||||
## Contributing
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Prompt-syntax atoms the cleaner must not rewrite.
|
||||
|
||||
The cleaner's rules treat a prompt as prose or as a comma-separated tag list.
|
||||
That is the right model for tags, and the wrong one for the handful of tokens
|
||||
that are *addresses* rather than words — `embedding:name` and `<lora:name:1.0>`
|
||||
resolve to a file on disk, so a single edited character silently changes what
|
||||
the sampler loads, or loads nothing at all.
|
||||
|
||||
Two rules were provably destructive (P3 #31, pinned by
|
||||
`tests/engine/cleaner/test_embedding_roundtrip.py`):
|
||||
|
||||
* punctuation stripping — `_` and `-` are in the stripped set, so
|
||||
`embedding:bad_prompt_` (a real published shape) became
|
||||
`embedding:bad_prompt`. ComfyUI resolves a missing embedding to nothing,
|
||||
so the negative prompt quietly stopped working, with no error.
|
||||
* fuzzy dedupe — versioned names are near-identical strings and the
|
||||
threshold is 0.9, so `embedding:badhandv4, embedding:badhandv5` lost the
|
||||
second. Two different files, one silently dropped.
|
||||
|
||||
This widens the cleaner's remit from "text" to "knows a little prompt syntax",
|
||||
which the findings called out as the cost of fixing it. The alternative was
|
||||
leaving a rule that corrupts a file reference without saying so.
|
||||
|
||||
Deliberately narrow: only the well-known forms, and only whole tokens. Anything
|
||||
not matched here keeps its existing treatment.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
# `embedding:name`, optionally weighted / parenthesised by the caller. The name
|
||||
# runs to the next separator: whitespace, comma, or a closing paren/angle.
|
||||
_EMBEDDING_RE = re.compile(r"\bembedding:[^\s,)\]>]+", re.IGNORECASE)
|
||||
|
||||
# `<lora:name:1.0>` and the siblings that share its shape. Matched whole, so
|
||||
# internal punctuation and decimal weights are untouchable.
|
||||
_ANGLE_RE = re.compile(
|
||||
r"<\s*(?:lora|lyco|locon|hypernet|embedding)\s*:[^>]*>",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def contains_atom(text: str) -> bool:
|
||||
"""True when `text` carries a file-reference token cleaning must preserve."""
|
||||
if not text:
|
||||
return False
|
||||
return bool(_EMBEDDING_RE.search(text) or _ANGLE_RE.search(text))
|
||||
|
||||
|
||||
def ends_with_atom(text: str) -> bool:
|
||||
"""True when `text` ENDS in an atom, so trimming its trailing edge would
|
||||
eat part of the reference. Used by the text-mode punctuation pass, which
|
||||
trims the whole string rather than per-tag."""
|
||||
if not text:
|
||||
return False
|
||||
stripped = text.rstrip()
|
||||
for pattern in (_EMBEDDING_RE, _ANGLE_RE):
|
||||
for match in pattern.finditer(stripped):
|
||||
if match.end() == len(stripped):
|
||||
return True
|
||||
return False
|
||||
@@ -8,6 +8,7 @@
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from engine.cleaner.atoms import contains_atom
|
||||
from engine.cleaner.types import RuleResult
|
||||
|
||||
_FUZZY_THRESHOLD = 0.9
|
||||
@@ -74,7 +75,17 @@ def apply_fuzzy(text: str, mode: str, config: dict) -> RuleResult:
|
||||
for tag in tags:
|
||||
key = tag.casefold()
|
||||
is_dup = False
|
||||
# Versioned file references are near-identical strings by design --
|
||||
# `embedding:badhandv4` vs `...v5` scores well above the 0.9 threshold
|
||||
# while naming two different files. Exact dedupe still collapses a
|
||||
# genuinely repeated one; only the FUZZY pass is held back.
|
||||
tag_is_atom = contains_atom(tag)
|
||||
for kept_tag in kept:
|
||||
if tag_is_atom or contains_atom(kept_tag):
|
||||
if key == kept_tag.casefold():
|
||||
is_dup = True
|
||||
break
|
||||
continue
|
||||
if _ratio(key, kept_tag.casefold()) >= _FUZZY_THRESHOLD:
|
||||
is_dup = True
|
||||
break
|
||||
|
||||
@@ -14,6 +14,7 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from engine.cleaner.atoms import contains_atom, ends_with_atom
|
||||
from engine.cleaner.types import RuleResult
|
||||
|
||||
_PUNCT_CHARS = r".,:;!?\-_"
|
||||
@@ -37,6 +38,13 @@ def apply(text: str, mode: str, config: dict) -> RuleResult:
|
||||
if _PURE_PUNCT_RE.match(tag):
|
||||
stripped += 1
|
||||
continue
|
||||
# `embedding:name` / `<lora:name:1.0>` are file references, and
|
||||
# `_` and `-` are in the stripped set — trimming an edge renames
|
||||
# the file. ComfyUI resolves a missing embedding to nothing, so
|
||||
# the damage is silent. See engine/cleaner/atoms.py.
|
||||
if contains_atom(tag):
|
||||
kept.append(tag)
|
||||
continue
|
||||
edged, changed = _strip_edges(tag)
|
||||
if changed:
|
||||
stripped += 1
|
||||
@@ -44,7 +52,14 @@ def apply(text: str, mode: str, config: dict) -> RuleResult:
|
||||
kept.append(edged)
|
||||
out = ", ".join(kept)
|
||||
else:
|
||||
out, changed = _strip_edges(text)
|
||||
if changed:
|
||||
stripped += 1
|
||||
# Text mode trims the whole string's edges rather than per tag, so the
|
||||
# only risk is a prompt that ENDS in an atom.
|
||||
if ends_with_atom(text):
|
||||
out = _LEADING_PUNCT_RE.sub("", text)
|
||||
if out != text:
|
||||
stripped += 1
|
||||
else:
|
||||
out, changed = _strip_edges(text)
|
||||
if changed:
|
||||
stripped += 1
|
||||
return {"text": out, "stats": {"stripped": stripped}}
|
||||
|
||||
+107
-9
@@ -14,6 +14,7 @@ import graph.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import re
|
||||
import sqlite3
|
||||
@@ -26,6 +27,24 @@ _SQL_DIR = Path(__file__).parent / "migrations_sql"
|
||||
_VERSION_RE = re.compile(r"^(\d{3})_.+\.(sql|py)$")
|
||||
|
||||
|
||||
class SchemaAheadError(RuntimeError):
|
||||
"""The database was migrated by a build this one cannot safely read.
|
||||
|
||||
Raised instead of letting the runner's "skip anything already applied"
|
||||
rule quietly hand a foreign schema to code that expects its own.
|
||||
"""
|
||||
|
||||
|
||||
def _checksum(path: Path) -> str:
|
||||
"""sha256 of a migration file's bytes.
|
||||
|
||||
Bytes, not parsed content: a `.py` migration's behaviour lives in code the
|
||||
runner `exec`s, so any edit at all is a different migration regardless of
|
||||
whether the SQL it emits looks the same.
|
||||
"""
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def _migrations_table_exists(conn: sqlite3.Connection) -> bool:
|
||||
row = conn.execute(
|
||||
"SELECT name FROM sqlite_master "
|
||||
@@ -75,8 +94,93 @@ def _load_py_migration(path: Path) -> Callable[[sqlite3.Connection], object]:
|
||||
return up # type: ignore[no-any-return]
|
||||
|
||||
|
||||
def head_version() -> int:
|
||||
"""Highest migration version this build ships."""
|
||||
pairs = _discover()
|
||||
return pairs[-1][0] if pairs else 0
|
||||
|
||||
|
||||
def _has_checksum_column(conn: sqlite3.Connection) -> bool:
|
||||
cur = conn.execute("PRAGMA table_info(migrations);")
|
||||
return any(row[1] == "checksum" for row in cur.fetchall())
|
||||
|
||||
|
||||
def _record(conn: sqlite3.Connection, version: int, mig_file: Path) -> None:
|
||||
"""Insert the applied-migration row, with a checksum when we can store one.
|
||||
|
||||
Migration 017 is what adds the column, so on a fresh database every
|
||||
migration before it inserts without one. Those rows stay NULL forever —
|
||||
see the 017 docblock for why backfilling them would defeat the check.
|
||||
"""
|
||||
if _has_checksum_column(conn):
|
||||
conn.execute(
|
||||
"INSERT INTO migrations(version, applied_at, checksum) VALUES(?, ?, ?);",
|
||||
(version, now_iso(), _checksum(mig_file)),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
"INSERT INTO migrations(version, applied_at) VALUES(?, ?);",
|
||||
(version, now_iso()),
|
||||
)
|
||||
|
||||
|
||||
def assert_schema_compatible(conn: sqlite3.Connection) -> None:
|
||||
"""Refuse to touch a database some other build's migrations shaped.
|
||||
|
||||
Two distinct failures, both silent before this existed:
|
||||
|
||||
1. The database is AHEAD — migrated by a newer build. Every migration is
|
||||
`<= MAX(version)`, so the runner does nothing and the caller reads a
|
||||
schema it has never seen.
|
||||
2. The database is at the SAME version but a DIFFERENT shape, because a
|
||||
migration file changed after it had already run somewhere. Version
|
||||
numbers match, so nothing compares anything.
|
||||
|
||||
Both are cumulative: each subsequent write goes through code whose
|
||||
assumptions about the row shape are wrong. Raising is recoverable;
|
||||
continuing is not.
|
||||
"""
|
||||
if not _migrations_table_exists(conn):
|
||||
return
|
||||
|
||||
applied = current_version(conn)
|
||||
head = head_version()
|
||||
if applied > head:
|
||||
raise SchemaAheadError(
|
||||
f"This database was migrated to version {applied}, but this build only "
|
||||
f"knows up to {head}. It was almost certainly written by a newer "
|
||||
f"version of Wildcard Pipeline. Reading it here could corrupt your "
|
||||
f"library — install the newer version again, or restore a backup."
|
||||
)
|
||||
|
||||
if not _has_checksum_column(conn):
|
||||
return
|
||||
|
||||
known = dict(_discover())
|
||||
rows = conn.execute(
|
||||
"SELECT version, checksum FROM migrations WHERE checksum IS NOT NULL;"
|
||||
).fetchall()
|
||||
for version, checksum in rows:
|
||||
mig_file = known.get(int(version))
|
||||
# Unknown version is the `applied > head` case, already handled above.
|
||||
if mig_file is None:
|
||||
continue
|
||||
if _checksum(mig_file) != checksum:
|
||||
raise SchemaAheadError(
|
||||
f"Migration {int(version):03d} was applied by a build whose copy of "
|
||||
f"it differs from this one's. The version numbers match but the "
|
||||
f"schemas may not, so this build cannot safely read your library. "
|
||||
f"Restore a backup taken before that build ran."
|
||||
)
|
||||
|
||||
|
||||
def migrate(conn: sqlite3.Connection) -> None:
|
||||
"""Apply all pending migrations. Safe to call repeatedly."""
|
||||
"""Apply all pending migrations. Safe to call repeatedly.
|
||||
|
||||
Guards first: applying this build's migrations on top of a schema another
|
||||
build shaped is how a mismatch becomes permanent.
|
||||
"""
|
||||
assert_schema_compatible(conn)
|
||||
applied = current_version(conn)
|
||||
for version, mig_file in _discover():
|
||||
if version <= applied:
|
||||
@@ -85,10 +189,7 @@ def migrate(conn: sqlite3.Connection) -> None:
|
||||
up = _load_py_migration(mig_file)
|
||||
with conn:
|
||||
up(conn)
|
||||
conn.execute(
|
||||
"INSERT INTO migrations(version, applied_at) VALUES(?, ?);",
|
||||
(version, now_iso()),
|
||||
)
|
||||
_record(conn, version, mig_file)
|
||||
else:
|
||||
sql = mig_file.read_text(encoding="utf-8")
|
||||
with conn:
|
||||
@@ -96,7 +197,4 @@ def migrate(conn: sqlite3.Connection) -> None:
|
||||
stmt = stmt.strip()
|
||||
if stmt:
|
||||
conn.execute(stmt)
|
||||
conn.execute(
|
||||
"INSERT INTO migrations(version, applied_at) VALUES(?, ?);",
|
||||
(version, now_iso()),
|
||||
)
|
||||
_record(conn, version, mig_file)
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Migration 017 — record WHICH migration ran, not just how many.
|
||||
|
||||
``migrations`` tracked only ``version``, and the runner skips anything
|
||||
``<= MAX(version)``. That makes an integer the entire identity of a
|
||||
schema, which it is not:
|
||||
|
||||
- A build whose head is 015 opened against a DB migrated to 016 skips
|
||||
every migration, finds nothing to do, and reads a schema it has never
|
||||
seen. Additive columns survive; a shape change does not.
|
||||
- Worse, two builds can both call something "016" and mean different
|
||||
things — a reworked migration, a hand-edited file, a branch that never
|
||||
shipped. The version matches, so nothing anywhere notices.
|
||||
|
||||
Both are silent, and both corrupt cumulatively: every subsequent write
|
||||
goes through code whose assumptions about the row shape are wrong.
|
||||
|
||||
``checksum`` fixes it by storing the sha256 of the migration file that
|
||||
actually ran. ``assert_schema_compatible`` then compares applied
|
||||
checksums against the files this build ships, so a divergence is a
|
||||
loud, recoverable error instead of silence.
|
||||
|
||||
Nullable on purpose: rows applied before this migration existed have no
|
||||
recorded checksum and cannot retroactively grow one. The guard skips
|
||||
them rather than guessing — a NULL means "unknown", never "mismatched".
|
||||
|
||||
Idempotent via ``PRAGMA table_info`` so tests that rewind the
|
||||
``migrations`` table can re-run it against a populated DB.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
|
||||
|
||||
def _has_column(conn: sqlite3.Connection, table: str, column: str) -> bool:
|
||||
cur = conn.execute(f"PRAGMA table_info({table});")
|
||||
return any(row[1] == column for row in cur.fetchall())
|
||||
|
||||
|
||||
def up(conn: sqlite3.Connection) -> None:
|
||||
if not _has_column(conn, "migrations", "checksum"):
|
||||
conn.execute("ALTER TABLE migrations ADD COLUMN checksum TEXT;")
|
||||
@@ -382,7 +382,15 @@ class ModuleRepository:
|
||||
.replace("%", "\\%")
|
||||
.replace("_", "\\_")
|
||||
)
|
||||
clauses.append("name LIKE ? ESCAPE '\\' COLLATE NOCASE")
|
||||
# Match the name OR the uuid — searching by id is the fast path for
|
||||
# debugging library linkage (finding the row a workflow's @{id} /
|
||||
# constraint source/target points at). NOCASE so an 8-hex id typed
|
||||
# in any case still matches.
|
||||
clauses.append(
|
||||
"(name LIKE ? ESCAPE '\\' COLLATE NOCASE "
|
||||
"OR id LIKE ? ESCAPE '\\' COLLATE NOCASE)"
|
||||
)
|
||||
params.append(f"%{escaped}%")
|
||||
params.append(f"%{escaped}%")
|
||||
if favorites_only:
|
||||
clauses.append("is_favorite = 1")
|
||||
@@ -767,7 +775,15 @@ class BundleRepository:
|
||||
.replace("%", "\\%")
|
||||
.replace("_", "\\_")
|
||||
)
|
||||
clauses.append("name LIKE ? ESCAPE '\\' COLLATE NOCASE")
|
||||
# Match the name OR the uuid — searching by id is the fast path for
|
||||
# debugging library linkage (finding the row a workflow's @{id} /
|
||||
# constraint source/target points at). NOCASE so an 8-hex id typed
|
||||
# in any case still matches.
|
||||
clauses.append(
|
||||
"(name LIKE ? ESCAPE '\\' COLLATE NOCASE "
|
||||
"OR id LIKE ? ESCAPE '\\' COLLATE NOCASE)"
|
||||
)
|
||||
params.append(f"%{escaped}%")
|
||||
params.append(f"%{escaped}%")
|
||||
if favorites_only:
|
||||
clauses.append("is_favorite = 1")
|
||||
@@ -951,7 +967,15 @@ class TemplateRepository:
|
||||
.replace("%", "\\%")
|
||||
.replace("_", "\\_")
|
||||
)
|
||||
clauses.append("name LIKE ? ESCAPE '\\' COLLATE NOCASE")
|
||||
# Match the name OR the uuid — searching by id is the fast path for
|
||||
# debugging library linkage (finding the row a workflow's @{id} /
|
||||
# constraint source/target points at). NOCASE so an 8-hex id typed
|
||||
# in any case still matches.
|
||||
clauses.append(
|
||||
"(name LIKE ? ESCAPE '\\' COLLATE NOCASE "
|
||||
"OR id LIKE ? ESCAPE '\\' COLLATE NOCASE)"
|
||||
)
|
||||
params.append(f"%{escaped}%")
|
||||
params.append(f"%{escaped}%")
|
||||
if favorites_only:
|
||||
clauses.append("is_favorite = 1")
|
||||
|
||||
@@ -102,6 +102,12 @@ class CombineHandler(ModuleHandler):
|
||||
# Both feed derive_module_rng(seed, output_var) so locking with
|
||||
# locked_seed = chain_seed reproduces the unlocked roll exactly.
|
||||
if instance.get("seed_scope") == "hold":
|
||||
# Held: reuse the frame-0 resolved value verbatim (from the
|
||||
# pipeline's base pass) so a held combine's alternation stays
|
||||
# frozen across the whole run, nested refs included.
|
||||
_hb = ctx.get("__wp_hold_base_ctx__")
|
||||
if isinstance(_hb, dict) and output_var in _hb:
|
||||
return {output_var: _hb[output_var]}
|
||||
chain_seed = int(ctx.get("__wp_node_seed_hold__", ctx.get("__wp_node_seed__", 0)) or 0)
|
||||
else:
|
||||
chain_seed = int(ctx.get("__wp_node_seed__", 0) or 0)
|
||||
|
||||
@@ -295,8 +295,30 @@ class DerivationHandler(ModuleHandler):
|
||||
# action.value across runs; without lock the chain seed
|
||||
# propagates per-queue. Falls back to the host ctx's RNG when
|
||||
# the ctx wasn't built with `__wp_rng__` (legacy callers).
|
||||
# seed_scope == "hold" freezes the DICE per branch, NOT which branch
|
||||
# fires. The conditions still pick a branch live each iteration, so a
|
||||
# varying input can switch IF→ELIF and we use THAT branch — but every
|
||||
# branch's inline {a|b} / @{} roll is frozen to its frame-0 value via
|
||||
# the constant hold seed, keyed PER BRANCH (see _branch_resolve_ctx).
|
||||
# So each branch's value is identical every iteration it fires and
|
||||
# equals the value it WOULD have had at frame 0, independent of which
|
||||
# other branches fired. (Contrast wildcard/combine/fixed_values hold,
|
||||
# which freeze the whole resolved VALUE because a constraint can
|
||||
# reshape their pool; a derivation branch's pool is fixed, so a frozen
|
||||
# seed alone is enough — and freezing the branch SELECTION would be
|
||||
# wrong: the user wants the chosen branch to follow the inputs.)
|
||||
_hold = False
|
||||
effective_seed = 0
|
||||
module_id = "derivation"
|
||||
ctx_local: dict[str, Any] = {}
|
||||
if isinstance(ctx, dict) and "__wp_rng__" in ctx:
|
||||
chain_seed = int(ctx.get("__wp_node_seed__", 0) or 0)
|
||||
_hold = instance.get("seed_scope") == "hold"
|
||||
if _hold:
|
||||
chain_seed = int(
|
||||
ctx.get("__wp_node_seed_hold__", ctx.get("__wp_node_seed__", 0)) or 0
|
||||
)
|
||||
else:
|
||||
chain_seed = int(ctx.get("__wp_node_seed__", 0) or 0)
|
||||
locked_seed = instance.get("locked_seed")
|
||||
effective_seed = (
|
||||
int(locked_seed) if isinstance(locked_seed, (int, float))
|
||||
@@ -309,6 +331,19 @@ class DerivationHandler(ModuleHandler):
|
||||
else:
|
||||
resolve_ctx = build_resolve_ctx(ctx, surface="derivation")
|
||||
|
||||
def _branch_resolve_ctx(branch_key: str) -> Any:
|
||||
# Non-hold (or no rng): the shared rng stream — existing
|
||||
# behaviour, branch values draw in fire order. Hold: an
|
||||
# INDEPENDENT rng per branch (keyed by rule:branch) so its value
|
||||
# is frozen to its frame-0 roll regardless of which other
|
||||
# branches drew before it in the shared stream.
|
||||
if not _hold:
|
||||
return resolve_ctx
|
||||
rng_b = derive_module_rng(effective_seed, f"{module_id}::{branch_key}")
|
||||
return build_resolve_ctx(
|
||||
{**ctx_local, "__wp_rng__": rng_b}, surface="derivation"
|
||||
)
|
||||
|
||||
# Tier-D instance overrides (2026-05-10 cycle).
|
||||
disabled_rule_ids = set(instance.get("disabled_rule_ids") or [])
|
||||
disabled_branch_keys = set(instance.get("disabled_branch_keys") or [])
|
||||
@@ -364,7 +399,9 @@ class DerivationHandler(ModuleHandler):
|
||||
action = {**action, "value": action_override}
|
||||
|
||||
pair = _apply_action(
|
||||
action, ctx, resolve_ctx, carrier_key=branch_carrier_key(rule_id, bi)
|
||||
action, ctx,
|
||||
_branch_resolve_ctx(branch_carrier_key(rule_id, bi)),
|
||||
carrier_key=branch_carrier_key(rule_id, bi),
|
||||
)
|
||||
if pair is not None:
|
||||
out[pair[0]] = pair[1]
|
||||
@@ -387,7 +424,9 @@ class DerivationHandler(ModuleHandler):
|
||||
if isinstance(action_override, str):
|
||||
action = {**action, "value": action_override}
|
||||
pair = _apply_action(
|
||||
action, ctx, resolve_ctx, carrier_key=branch_carrier_key(rule_id, "else")
|
||||
action, ctx,
|
||||
_branch_resolve_ctx(branch_carrier_key(rule_id, "else")),
|
||||
carrier_key=branch_carrier_key(rule_id, "else"),
|
||||
)
|
||||
if pair is not None:
|
||||
out[pair[0]] = pair[1]
|
||||
|
||||
@@ -151,6 +151,14 @@ class FixedValuesHandler(ModuleHandler):
|
||||
|
||||
# Effective seed selection (mirrors WildcardHandler + CombineHandler):
|
||||
if instance.get("seed_scope") == "hold":
|
||||
# Held: reuse each name's frame-0 resolved value verbatim (from the
|
||||
# pipeline's base pass) so a held fixed-values alternation stays
|
||||
# frozen across the whole run.
|
||||
_hb = ctx.get("__wp_hold_base_ctx__")
|
||||
if isinstance(_hb, dict):
|
||||
_names = [n for n in ((v.get("name") or "").strip() for v in values) if n]
|
||||
if _names and all(n in _hb for n in _names):
|
||||
return {n: _hb[n] for n in _names}
|
||||
chain_seed = int(
|
||||
ctx.get("__wp_node_seed_hold__", ctx.get("__wp_node_seed__", 0)) or 0
|
||||
)
|
||||
|
||||
@@ -211,7 +211,7 @@ class WalkResult:
|
||||
walk_overflow: list[WalkOverflow] = field(default_factory=list)
|
||||
|
||||
|
||||
def _extract_at_uuid_refs(payload: dict[str, Any]) -> set[str]:
|
||||
def extract_at_uuid_refs(payload: dict[str, Any]) -> set[str]:
|
||||
"""Collect all ``@{8hex}`` refs referenced inside a payload's
|
||||
string-typed leaves. Uses ``tokenize_text`` exclusively — only
|
||||
canonical 8-hex-char refs (spec §2.4) are followed.
|
||||
@@ -260,6 +260,41 @@ def _row_to_snapshot_entry(
|
||||
}
|
||||
|
||||
|
||||
def ref_seed_uuids(modules: Iterable[Any] | None) -> set[str]:
|
||||
"""Every ``@{uuid}`` target referenced by ANY module in a node's list.
|
||||
|
||||
A catalog is synthesised from wildcard modules only, and
|
||||
``walk_transitive_refs`` follows refs found in wildcard payloads only. That
|
||||
covers a ref authored inside a wildcard option, but ``@{uuid}`` is legal on
|
||||
other surfaces too — most notably a derivation rule's action value, and the
|
||||
per-instance ``action_value_overrides`` / ``condition_value_overrides`` the
|
||||
edit modal writes when a user retargets a branch on the canvas.
|
||||
|
||||
Refs on those surfaces were never discovered, so their target reached the
|
||||
catalog only by coincidence — when the user happened to ALSO have that
|
||||
wildcard picked in the same node. Removing the wildcard from the node (a
|
||||
reasonable thing to do once a derivation references it by uuid) dropped it
|
||||
with nothing to put it back, and every such ref resolved to ``unknown_ref``
|
||||
→ empty string no matter what the live library held.
|
||||
|
||||
Seeds therefore come from each module's ``payload`` AND its ``instance``:
|
||||
the instance is where a canvas-side retarget lives, and it is not part of
|
||||
the library payload the walker would otherwise see.
|
||||
|
||||
Tolerant of malformed rows — a corrupt widget value must never break a
|
||||
graph run.
|
||||
"""
|
||||
seeds: set[str] = set()
|
||||
for module in modules or []:
|
||||
if not isinstance(module, dict):
|
||||
continue
|
||||
for key in ("payload", "instance"):
|
||||
value = module.get(key)
|
||||
if isinstance(value, dict):
|
||||
seeds |= extract_at_uuid_refs(value)
|
||||
return seeds
|
||||
|
||||
|
||||
def walk_transitive_refs(
|
||||
root_uuids: Iterable[str],
|
||||
*,
|
||||
@@ -347,7 +382,7 @@ def walk_transitive_refs(
|
||||
continue
|
||||
|
||||
new_ancestors = ancestors | {uuid}
|
||||
for child_uuid in _extract_at_uuid_refs(row["payload"]):
|
||||
for child_uuid in extract_at_uuid_refs(row["payload"]):
|
||||
queue.append((child_uuid, depth + 1, uuid, new_ancestors))
|
||||
|
||||
# After walk: re-stamp every dep's parent list (BFS may have accumulated
|
||||
|
||||
@@ -646,6 +646,13 @@ class WildcardHandler(ModuleHandler):
|
||||
# relies on: the user sees a roll, locks it, captures the
|
||||
# current chain seed, future runs reproduce the same roll.
|
||||
if instance.get("seed_scope") == "hold":
|
||||
# Held: reuse the frame-0 fully-resolved value verbatim (from the
|
||||
# pipeline's base pass). Skips the pick AND nested-ref resolution,
|
||||
# so a constrained or @{}-bearing wildcard stays frozen across the
|
||||
# whole run — "green jeans" on frame 1 stays "green jeans".
|
||||
_hb = ctx.get("__wp_hold_base_ctx__")
|
||||
if isinstance(_hb, dict) and binding in _hb:
|
||||
return {binding: _hb[binding]}
|
||||
chain_seed = int(ctx.get("__wp_node_seed_hold__", ctx.get("__wp_node_seed__", 0)) or 0)
|
||||
else:
|
||||
chain_seed = int(ctx.get("__wp_node_seed__", 0) or 0)
|
||||
|
||||
@@ -236,6 +236,18 @@ def _extract_static_meta(
|
||||
return meta
|
||||
|
||||
|
||||
def _module_seed_scope(module: object) -> str | None:
|
||||
"""Read a module's base ``instance.seed_scope`` ("hold"/"vary"/None).
|
||||
Works for both dict and object module shapes. seed_scope is a base-only
|
||||
setting (disabled in per-frame edit mode), so the base instance is
|
||||
authoritative."""
|
||||
inst = module.get("instance") if isinstance(module, dict) else getattr(module, "instance", None)
|
||||
if isinstance(inst, dict):
|
||||
s = inst.get("seed_scope")
|
||||
return s if isinstance(s, str) else None
|
||||
return None
|
||||
|
||||
|
||||
class PipelineEngine:
|
||||
"""Runs an ordered list of modules against a context dict."""
|
||||
|
||||
@@ -263,6 +275,66 @@ class PipelineEngine:
|
||||
# one-shot consumed-set.
|
||||
ctx.setdefault("__wp_constraint_hits__", {})
|
||||
|
||||
# "Hold the value" base pass. A module on seed_scope=hold must resolve
|
||||
# to its frame-0 (loop_index=0) value on EVERY iteration — INCLUDING
|
||||
# nested @{} refs, which resolve_text bakes into the stored value.
|
||||
# Re-resolving each iteration (the old seed-swap) failed for
|
||||
# constrained wildcards (the constraint reshapes the pool per
|
||||
# iteration) and for nested refs. So when a loop is driving
|
||||
# (loop_index != 0) and any module holds, resolve the chain ONCE at
|
||||
# loop_index=0 with the constant hold seed; held handlers copy their
|
||||
# resolved value from this base context verbatim. The deepcopy keeps
|
||||
# the throwaway pass's warnings/trace/constraint-state off the real
|
||||
# ctx. loop_index=0 here means the recursive run skips its own base
|
||||
# pass — no infinite recursion.
|
||||
_any_hold = any(_module_seed_scope(m) == "hold" for m in modules)
|
||||
if loop_index != 0 and _any_hold:
|
||||
import copy as _copy
|
||||
|
||||
_hb = int(ctx.get("__wp_node_seed_hold__", 0) or 0)
|
||||
base_ctx = PipelineEngine().run(
|
||||
modules,
|
||||
ctx=_copy.deepcopy(ctx),
|
||||
seed=_hb,
|
||||
hold_seed=_hb,
|
||||
loop_index=0,
|
||||
)
|
||||
ctx["__wp_hold_base_ctx__"] = base_ctx
|
||||
|
||||
# Held wildcards copy their frozen VALUE from the base pass but
|
||||
# early-return before `_record_pick` (wildcard_handler), so their
|
||||
# frame-0 pick never lands in the real ctx. Downstream constraints
|
||||
# then can't find the held source — they mis-fire (spurious
|
||||
# source_missing / never_applied warnings) and, cross-node, leave a
|
||||
# held target UNCONSTRAINED (the held-outfit drift: kimono at
|
||||
# frame 0, unconstrained pick on frames 2+). Carry the base pass's
|
||||
# pick + hit state for held modules into the real ctx HERE, before
|
||||
# the per-module loop, so the registration is present for this
|
||||
# node's constraints AND flows downstream (via __wp_picks__ /
|
||||
# __wp_constraints__ carry-over) into the next node's base pass.
|
||||
# The value-freeze path in the wildcard handler is untouched.
|
||||
_base_picks = base_ctx.get("__wp_picks__")
|
||||
if isinstance(_base_picks, dict):
|
||||
_real_picks = ctx.setdefault("__wp_picks__", {})
|
||||
if isinstance(_real_picks, dict):
|
||||
for _m in modules:
|
||||
if _module_seed_scope(_m) != "hold":
|
||||
continue
|
||||
_mid = (
|
||||
_m.get("id", "") if isinstance(_m, dict)
|
||||
else getattr(_m, "id", "")
|
||||
)
|
||||
if _mid and _mid in _base_picks and _mid not in _real_picks:
|
||||
_real_picks[_mid] = _base_picks[_mid]
|
||||
_base_hits = base_ctx.get("__wp_constraint_hits__")
|
||||
if isinstance(_base_hits, dict):
|
||||
_real_hits = ctx.setdefault("__wp_constraint_hits__", {})
|
||||
if isinstance(_real_hits, dict):
|
||||
for _cid, _n in _base_hits.items():
|
||||
_real_hits[_cid] = max(
|
||||
int(_real_hits.get(_cid, 0) or 0), int(_n or 0)
|
||||
)
|
||||
|
||||
for index, module in enumerate(modules):
|
||||
# Normalise id/type/enabled reads to work for both dicts and objects.
|
||||
if isinstance(module, dict):
|
||||
|
||||
@@ -391,6 +391,7 @@ def ref_option_pool(tok: Token, ctx: ResolveContext) -> list[dict]:
|
||||
filter_expr = tok.meta.get("filter_expr")
|
||||
exclude_null = bool(tok.meta.get("exclude_null"))
|
||||
if (isinstance(filter_expr, str) and filter_expr.strip()) or exclude_null:
|
||||
pool_total = len(options)
|
||||
ast = _parse_subcat(filter_expr) if isinstance(filter_expr, str) else None
|
||||
options = [
|
||||
o for o in options
|
||||
@@ -404,6 +405,41 @@ def ref_option_pool(tok: Token, ctx: ResolveContext) -> list[dict]:
|
||||
)
|
||||
]
|
||||
if not options:
|
||||
# "Matched no options" on its own is true and useless — it cannot
|
||||
# tell a wrong filter from a right filter aimed at a stale pool.
|
||||
# Report WHICH pool was searched, how big it was, and what tags it
|
||||
# actually offers, so the panel answers the question instead of
|
||||
# restating the symptom.
|
||||
available = sorted({
|
||||
t
|
||||
for o in (payload_dict.get("options", []) if isinstance(payload_dict, dict)
|
||||
else module.get("options", []))
|
||||
if isinstance(o, dict)
|
||||
for t in (o.get("sub_categories") or [])
|
||||
if isinstance(t, str)
|
||||
})
|
||||
pool_origin = module.get("pool_origin")
|
||||
library_count = module.get("library_option_count")
|
||||
detail = {
|
||||
"uuid": uuid,
|
||||
"filter_expr": filter_expr,
|
||||
"exclude_null": exclude_null,
|
||||
"pool_total": pool_total,
|
||||
"available_sub_categories": available,
|
||||
}
|
||||
if pool_origin:
|
||||
detail["pool_origin"] = pool_origin
|
||||
if isinstance(library_count, int):
|
||||
detail["library_option_count"] = library_count
|
||||
where = (
|
||||
"this node's copy" if pool_origin == "node"
|
||||
else "the library" if pool_origin == "library"
|
||||
else "the pool"
|
||||
)
|
||||
drift = (
|
||||
f"; the library now has {library_count}"
|
||||
if isinstance(library_count, int) else ""
|
||||
)
|
||||
_push_warning(
|
||||
ctx,
|
||||
type="ref_subcategory_empty_pool",
|
||||
@@ -412,14 +448,12 @@ def ref_option_pool(tok: Token, ctx: ResolveContext) -> list[dict]:
|
||||
source_field="",
|
||||
position=tok.start,
|
||||
token_index=None,
|
||||
detail={
|
||||
"uuid": uuid,
|
||||
"filter_expr": filter_expr,
|
||||
"exclude_null": exclude_null,
|
||||
},
|
||||
detail=detail,
|
||||
message=(
|
||||
f"@{{{uuid}:{filter_expr or ''}"
|
||||
f"{'!null' if exclude_null else ''}}} matched no options"
|
||||
f"{'!null' if exclude_null else ''}}} matched no options — "
|
||||
f"searched {where} ({pool_total} option"
|
||||
f"{'' if pool_total == 1 else 's'}){drift}"
|
||||
),
|
||||
)
|
||||
return []
|
||||
|
||||
+4
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "comfyui-wildcard-pipeline",
|
||||
"version": "2.8.0",
|
||||
"version": "2.13.2",
|
||||
"private": true,
|
||||
"description": "Modular procedural prompt generation for ComfyUI",
|
||||
"author": "DumiFlex",
|
||||
@@ -13,6 +13,7 @@
|
||||
"build:manager": "vite build --mode manager",
|
||||
"build": "pnpm build:extension && pnpm build:manager",
|
||||
"docs:copy": "node scripts/copy-help-docs.mjs",
|
||||
"docs:figures": "node scripts/build-flow-figures.mjs",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"lint": "eslint \"src/**/*.{ts,vue}\"",
|
||||
"size": "node scripts/check-bundle-size.mjs",
|
||||
@@ -24,7 +25,8 @@
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage --passWithNoTests",
|
||||
"test:py": "pytest",
|
||||
"prepare": "husky"
|
||||
"prepare": "husky",
|
||||
"announce": "node scripts/discord-announce.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"pinia": "^2.2.6",
|
||||
|
||||
+131
-127
@@ -1,130 +1,134 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 980 280" role="img" aria-label="WP Context emits resolved variables, Prompt Assembler fills them, CLIP Encode produces conditioning">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 202" width="880" height="202" role="img" aria-label="Wildcard, Fixed Values, Combine, Derivation and Constraint modules resolve inside WP Context, which emits resolved dollar-variables that fill the WP Prompt Assembler template, which CLIP Encode turns into conditioning">
|
||||
<style><![CDATA[
|
||||
.bg { fill: #14161e; }
|
||||
.panel { fill: #1a1d2a; }
|
||||
.border-cyan { stroke: #3a8fb7; }
|
||||
.border-violet { stroke: #7c6ad6; }
|
||||
.border-neutral { stroke: #6a6a6a; }
|
||||
.border-dim { stroke: #353841; }
|
||||
.ico-cyan { fill: #7ec8e3; }
|
||||
.ico-violet { fill: #c4b5fd; }
|
||||
.ico-neutral { fill: #aab; }
|
||||
.name { fill: #d6d8e0; font: 600 13px 'Inter', system-ui, sans-serif; }
|
||||
.sub { fill: #6f7384; font: 400 10px ui-monospace, monospace; }
|
||||
.arrow-lbl { fill: #6f7384; font: 600 10px 'Inter', system-ui, sans-serif; letter-spacing: 1px; text-transform: uppercase; }
|
||||
.arrow-line { stroke: #4a4d55; stroke-width: 2; fill: none; }
|
||||
.arrow-head { fill: #4a4d55; }
|
||||
.modules-header { fill: #6f7384; font: 600 10px 'Inter', system-ui, sans-serif; letter-spacing: 1px; text-transform: uppercase; }
|
||||
.pill-bg { fill: #1a1d2a; }
|
||||
.pill-stroke-wc { stroke: #b29cf2; }
|
||||
.pill-stroke-fv { stroke: #2dd4bf; }
|
||||
.pill-stroke-cb { stroke: #6ad28b; }
|
||||
.pill-stroke-dv { stroke: #f4a261; }
|
||||
.pill-stroke-cs { stroke: #ec96b8; }
|
||||
.pill-stroke-var { stroke: #c4b5fd; }
|
||||
.pill-text-wc { fill: #b29cf2; }
|
||||
.pill-text-fv { fill: #2dd4bf; }
|
||||
.pill-text-cb { fill: #6ad28b; }
|
||||
.pill-text-dv { fill: #f4a261; }
|
||||
.pill-text-cs { fill: #ec96b8; }
|
||||
.pill-text-var { fill: #c4b5fd; }
|
||||
.pill-text { font: 500 10px 'Inter', system-ui, sans-serif; }
|
||||
.pill { fill-opacity: 0.12; stroke-width: 1; }
|
||||
.resolved { fill: #6f7384; font: 600 9.5px 'Inter', system-ui, sans-serif; letter-spacing: 1px; text-transform: uppercase; }
|
||||
.down-arrow { stroke: #4a4d55; stroke-width: 1.5; fill: none; }
|
||||
.frame, .card, .pill, .chip { stroke-width: 1; }
|
||||
.cap { font: 400 10px 'Segoe UI', -apple-system, BlinkMacSystemFont, system-ui, sans-serif; letter-spacing: .06em; }
|
||||
.feeder { font: 400 10.5px 'Segoe UI', -apple-system, BlinkMacSystemFont, system-ui, sans-serif; }
|
||||
.nm { font: 600 12px 'Segoe UI', -apple-system, BlinkMacSystemFont, system-ui, sans-serif; }
|
||||
.id { font: 400 9.5px 'JetBrains Mono', Consolas, Monaco, 'Courier New', monospace; }
|
||||
.lbl, .varcap { font: 400 9.5px 'Segoe UI', -apple-system, BlinkMacSystemFont, system-ui, sans-serif; letter-spacing: .05em; }
|
||||
.chipt { font: 400 10.5px 'JetBrains Mono', Consolas, Monaco, 'Courier New', monospace; }
|
||||
|
||||
.frame { fill: #1e1e1e; stroke: #3a3a3a; }
|
||||
.card { fill: #232323; stroke: #4a4a4a; }
|
||||
.card--wp { stroke: #2dd4bf; stroke-opacity: .55; }
|
||||
.ico--wp { color: #2dd4bf; }
|
||||
.ico--ext { color: #aaaaaa; }
|
||||
.ico--wildcard { color: #a78bfa; }
|
||||
.ico--fixed { color: #22d3ee; }
|
||||
.ico--combine { color: #34d399; }
|
||||
.ico--derivation { color: #fbbf24; }
|
||||
.ico--constraint { color: #f472b6; }
|
||||
.pill { fill: #232323; stroke: #3a3a3a; }
|
||||
.feeder { fill: #aaaaaa; }
|
||||
.nm { fill: #dddddd; }
|
||||
.id, .lbl, .cap, .varcap { fill: #666666; }
|
||||
.ln { stroke: #4a4a4a; }
|
||||
.wash { stop-color: #2dd4bf; }
|
||||
.flow0 { stop-color: #4a4a4a; }
|
||||
.head { fill: #4a4a4a; }
|
||||
.chip { fill: #232323; }
|
||||
.chip--a { stroke: #8b5cf6; stroke-opacity: .4; }
|
||||
.chip--b { stroke: #22d3ee; stroke-opacity: .4; }
|
||||
.chip--c { stroke: #34d399; stroke-opacity: .4; }
|
||||
.chipt--a { fill: #c4b5fd; }
|
||||
.chipt--b { fill: #67e8f9; }
|
||||
.chipt--c { fill: #86efac; }
|
||||
@media (prefers-color-scheme: light) {
|
||||
.frame { fill: #f5f5f5; stroke: #b0b0b0; }
|
||||
.card { fill: #ffffff; stroke: #999999; }
|
||||
.card--wp { stroke: #0f766e; stroke-opacity: .55; }
|
||||
.ico--wp { color: #0f766e; }
|
||||
.ico--ext { color: #555555; }
|
||||
.ico--wildcard { color: #6d28d9; }
|
||||
.ico--fixed { color: #1d4ed8; }
|
||||
.ico--combine { color: #065f46; }
|
||||
.ico--derivation { color: #92400e; }
|
||||
.ico--constraint { color: #9d174d; }
|
||||
.pill { fill: #ffffff; stroke: #b0b0b0; }
|
||||
.feeder { fill: #555555; }
|
||||
.nm { fill: #1a1a1a; }
|
||||
.id, .lbl, .cap, .varcap { fill: #888888; }
|
||||
.ln { stroke: #999999; }
|
||||
.wash { stop-color: #0f766e; }
|
||||
.flow0 { stop-color: #999999; }
|
||||
.head { fill: #999999; }
|
||||
.chip { fill: #ffffff; }
|
||||
.chip--a { stroke: #8b5cf6; stroke-opacity: .4; }
|
||||
.chip--b { stroke: #22d3ee; stroke-opacity: .4; }
|
||||
.chip--c { stroke: #34d399; stroke-opacity: .4; }
|
||||
.chipt--a { fill: #6d28d9; }
|
||||
.chipt--b { fill: #1d4ed8; }
|
||||
.chipt--c { fill: #065f46; }
|
||||
}
|
||||
]]></style>
|
||||
|
||||
<rect class="bg" width="980" height="280" rx="8" />
|
||||
|
||||
<!-- MODULES INSIDE THE CONTEXT header -->
|
||||
<text class="modules-header" x="490" y="28" text-anchor="middle">Modules inside the context</text>
|
||||
|
||||
<!-- Module kind pills row -->
|
||||
<g transform="translate(245, 42)">
|
||||
<!-- Wildcard -->
|
||||
<rect class="pill pill-stroke-wc" x="0" y="0" width="76" height="22" rx="11" fill="#b29cf2" />
|
||||
<text class="pill-text pill-text-wc" x="38" y="15" text-anchor="middle">✦ Wildcard</text>
|
||||
<!-- Fixed Values -->
|
||||
<rect class="pill pill-stroke-fv" x="84" y="0" width="92" height="22" rx="11" fill="#2dd4bf" />
|
||||
<text class="pill-text pill-text-fv" x="130" y="15" text-anchor="middle">⌘ Fixed Values</text>
|
||||
<!-- Combine -->
|
||||
<rect class="pill pill-stroke-cb" x="184" y="0" width="76" height="22" rx="11" fill="#6ad28b" />
|
||||
<text class="pill-text pill-text-cb" x="222" y="15" text-anchor="middle">⇄ Combine</text>
|
||||
<!-- Derivation -->
|
||||
<rect class="pill pill-stroke-dv" x="268" y="0" width="84" height="22" rx="11" fill="#f4a261" />
|
||||
<text class="pill-text pill-text-dv" x="310" y="15" text-anchor="middle">⇆ Derivation</text>
|
||||
<!-- Constraint -->
|
||||
<rect class="pill pill-stroke-cs" x="360" y="0" width="84" height="22" rx="11" fill="#ec96b8" />
|
||||
<text class="pill-text pill-text-cs" x="402" y="15" text-anchor="middle">⊥ Constraint</text>
|
||||
</g>
|
||||
|
||||
<!-- Down arrow indicating these go INTO the Context -->
|
||||
<path class="down-arrow" d="M 490 78 L 490 96 M 484 90 L 490 96 L 496 90" />
|
||||
|
||||
<!-- ===== Main flow row at y≈170 ===== -->
|
||||
|
||||
<!-- WP Context box -->
|
||||
<g transform="translate(40, 130)">
|
||||
<rect class="panel border-cyan" x="0" y="0" width="160" height="100" rx="10" stroke-width="2" />
|
||||
<text class="ico-cyan" x="80" y="32" text-anchor="middle" font-size="20">⌬</text>
|
||||
<text class="name" x="80" y="58" text-anchor="middle">WP Context</text>
|
||||
<text class="sub" x="80" y="78" text-anchor="middle">rolls + resolves</text>
|
||||
</g>
|
||||
|
||||
<!-- EMITS arrow -->
|
||||
<g transform="translate(210, 180)">
|
||||
<text class="arrow-lbl" x="50" y="-12" text-anchor="middle">Emits</text>
|
||||
<line class="arrow-line" x1="0" y1="0" x2="92" y2="0" />
|
||||
<polygon class="arrow-head" points="92,-5 100,0 92,5" />
|
||||
</g>
|
||||
|
||||
<!-- Resolved vars cluster (no box; chips on transparent) -->
|
||||
<g transform="translate(320, 160)">
|
||||
<!-- $subject -->
|
||||
<rect class="pill pill-stroke-var" x="0" y="0" width="68" height="22" rx="11" fill="#c4b5fd" />
|
||||
<text class="pill-text pill-text-var" x="34" y="15" text-anchor="middle">$subject</text>
|
||||
<!-- $style -->
|
||||
<rect class="pill pill-stroke-var" x="76" y="0" width="52" height="22" rx="11" fill="#c4b5fd" />
|
||||
<text class="pill-text pill-text-var" x="102" y="15" text-anchor="middle">$style</text>
|
||||
<!-- $lighting (second row, centered) -->
|
||||
<rect class="pill pill-stroke-var" x="32" y="30" width="72" height="22" rx="11" fill="#c4b5fd" />
|
||||
<text class="pill-text pill-text-var" x="68" y="45" text-anchor="middle">$lighting</text>
|
||||
<!-- RESOLVED $VARS caption -->
|
||||
<text class="resolved" x="64" y="72" text-anchor="middle">Resolved $vars</text>
|
||||
</g>
|
||||
|
||||
<!-- FILLS arrow -->
|
||||
<g transform="translate(465, 180)">
|
||||
<text class="arrow-lbl" x="50" y="-12" text-anchor="middle">Fills</text>
|
||||
<line class="arrow-line" x1="0" y1="0" x2="92" y2="0" />
|
||||
<polygon class="arrow-head" points="92,-5 100,0 92,5" />
|
||||
</g>
|
||||
|
||||
<!-- Prompt Assembler box -->
|
||||
<g transform="translate(575, 130)">
|
||||
<rect class="panel border-violet" x="0" y="0" width="184" height="100" rx="10" stroke-width="2" />
|
||||
<text class="ico-violet" x="92" y="32" text-anchor="middle" font-size="20">≡</text>
|
||||
<text class="name" x="92" y="58" text-anchor="middle">Prompt Assembler</text>
|
||||
<text class="sub" x="92" y="78" text-anchor="middle">"a $style portrait…"</text>
|
||||
</g>
|
||||
|
||||
<!-- PROMPT arrow -->
|
||||
<g transform="translate(770, 180)">
|
||||
<text class="arrow-lbl" x="40" y="-12" text-anchor="middle">Prompt</text>
|
||||
<line class="arrow-line" x1="0" y1="0" x2="72" y2="0" />
|
||||
<polygon class="arrow-head" points="72,-5 80,0 72,5" />
|
||||
</g>
|
||||
|
||||
<!-- CLIP Encode box -->
|
||||
<g transform="translate(860, 130)">
|
||||
<rect class="panel border-neutral" x="0" y="0" width="88" height="100" rx="10" stroke-width="2" />
|
||||
<text class="ico-neutral" x="44" y="32" text-anchor="middle" font-size="20">⚡</text>
|
||||
<text class="name" x="44" y="58" text-anchor="middle">CLIP</text>
|
||||
<text class="sub" x="44" y="78" text-anchor="middle">conditioning</text>
|
||||
</g>
|
||||
|
||||
<!-- Caption -->
|
||||
<text class="resolved" x="490" y="260" text-anchor="middle" style="text-transform:none; letter-spacing:0;">
|
||||
Modules resolve inside WP Context → named $variables → WP Prompt Assembler → CLIP
|
||||
</text>
|
||||
<defs>
|
||||
<!-- Mirrors the SPA frame wash. The CSS is an ellipse 120 percent of the
|
||||
width by 100 percent of the HEIGHT, anchored top-left — so it spans
|
||||
the whole panel. Squashing it by the aspect ratio instead pins it to
|
||||
the corner and leaves the rest looking flat. -->
|
||||
<radialGradient id="wash" cx="0" cy="0" r="1" gradientTransform="scale(1.2 1)">
|
||||
<stop class="wash" offset="0" stop-opacity="0.10"/>
|
||||
<stop class="wash" offset="0.6" stop-opacity="0.02"/>
|
||||
<stop class="wash" offset="1" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="flowv" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop class="flow0" offset="0" stop-opacity="0"/>
|
||||
<stop class="flow0" offset="0.25" stop-opacity="1"/>
|
||||
<stop class="flow0" offset="0.8" stop-opacity="1"/>
|
||||
<stop class="flow0" offset="1" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="flow" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop class="flow0" offset="0" stop-opacity="0"/>
|
||||
<stop class="flow0" offset="0.2" stop-opacity="1"/>
|
||||
<stop class="flow0" offset="0.8" stop-opacity="1"/>
|
||||
<stop class="flow0" offset="1" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect class="frame" x="0.5" y="0.5" width="879" height="201" rx="12"/>
|
||||
<rect x="0.5" y="0.5" width="879" height="201" rx="12" fill="url(#wash)"/>
|
||||
<text class="cap" x="440" y="30" text-anchor="middle">MODULES INSIDE THE CONTEXT</text>
|
||||
<rect class="pill" x="214.69" y="40" width="77.68" height="21" rx="10.5"/>
|
||||
<g class="ico--wildcard"><g fill="currentColor" transform="translate(224.69 45.5) scale(0.4166666666666667)"><path fill-rule="evenodd" clip-rule="evenodd" d="M18.8923 5.29743L20.1462 5.71539C20.4197 5.80656 20.4197 6.19343 20.1462 6.2846L18.8923 6.70256C18.8027 6.73242 18.7324 6.80272 18.7026 6.8923L18.2846 8.14618C18.1934 8.41969 17.8066 8.41969 17.7154 8.14618L17.2974 6.8923C17.2676 6.80272 17.1973 6.73242 17.1077 6.70256L15.8538 6.2846C15.5803 6.19343 15.5803 5.80656 15.8538 5.71539L17.1077 5.29743C17.1973 5.26757 17.2676 5.19728 17.2974 5.1077L17.7154 3.85381C17.8066 3.5803 18.1934 3.5803 18.2846 3.85381L18.7026 5.1077C18.7324 5.19728 18.8027 5.26757 18.8923 5.29743ZM9.19361 5.04743C9.45192 4.27248 10.5481 4.2725 10.8064 5.04743L12.3429 9.65707L16.9526 11.1936C17.7275 11.4519 17.7275 12.5481 16.9526 12.8064L12.3429 14.3429L10.8064 18.9526C10.5481 19.7275 9.45192 19.7275 9.19361 18.9526L7.65706 14.3429L3.04742 12.8064C2.27247 12.5481 2.27249 11.4519 3.04742 11.1936L7.65706 9.65707L9.19361 5.04743ZM9.99999 7.37171L8.97731 10.4397C8.89271 10.6935 8.69354 10.8927 8.43973 10.9773L5.3717 12L8.43973 13.0227C8.69354 13.1073 8.89271 13.3064 8.97731 13.5603L9.99999 16.6283L11.0227 13.5603C11.1073 13.3064 11.3064 13.1073 11.5603 13.0227L14.6283 12L11.5603 10.9773C11.3064 10.8927 11.1073 10.6935 11.0227 10.4397L9.99999 7.37171ZM20.1462 17.7154L18.8923 17.2974C18.8027 17.2676 18.7324 17.1973 18.7026 17.1077L18.2846 15.8538C18.1934 15.5803 17.8066 15.5803 17.7154 15.8538L17.2974 17.1077C17.2676 17.1973 17.1973 17.2676 17.1077 17.2974L15.8538 17.7154C15.5803 17.8066 15.5803 18.1934 15.8538 18.2846L17.1077 18.7026C17.1973 18.7324 17.2676 18.8027 17.2974 18.8923L17.7154 20.1462C17.8066 20.4197 18.1934 20.4197 18.2846 20.1462L18.7026 18.8923C18.7324 18.8027 18.8027 18.7324 18.8923 18.7026L20.1462 18.2846C20.4197 18.1934 20.4197 17.8066 20.1462 17.7154Z"/></g></g>
|
||||
<text class="feeder" x="238.69" y="54">Wildcard</text>
|
||||
<rect class="pill" x="298.37" y="40" width="99.52" height="21" rx="10.5"/>
|
||||
<g class="ico--fixed"><g fill="currentColor" transform="translate(308.37 45.5) scale(0.4166666666666667)"><path d="M12.32,19.98c-.58,0-1.16-.22-1.6-.66l-6.48-6.47c-.14-.14-.22-.33-.22-.53V4.77c0-.41,.34-.75,.75-.75h7.54c.2,0,.39,.08,.53,.22l6.48,6.48c.87,.88,.87,2.31,0,3.19,0,0,0,0,0,0l-5.41,5.41c-.44,.44-1.02,.66-1.6,.66Zm-6.8-7.97l6.26,6.25c.3,.29,.78,.29,1.07,0l5.41-5.41c.29-.29,.29-.77,0-1.07l-6.26-6.26H5.52v6.48Zm13.27,1.37h0Zm-10.29-3.63c-.69,0-1.25-.56-1.25-1.25s.56-1.25,1.25-1.25,1.25,.56,1.25,1.25-.56,1.25-1.25,1.25Z"/></g></g>
|
||||
<text class="feeder" x="322.37" y="54">Fixed Values</text>
|
||||
<rect class="pill" x="403.89" y="40" width="72.22" height="21" rx="10.5"/>
|
||||
<g class="ico--combine"><g fill="currentColor" transform="translate(413.89 45.5) scale(0.4166666666666667)"><g id="link"><path d="M7.23,18.25A4,4,0,0,1,4.4,17.09a4.23,4.23,0,0,1,.15-5.95L8.31,7.35A4.44,4.44,0,0,1,11.42,6,4,4,0,0,1,14.25,7.2a4.25,4.25,0,0,1-.15,6l-1.26,1.26a.75.75,0,1,1-1.06-1.06L13,12.1a2.73,2.73,0,0,0,.14-3.84,2.77,2.77,0,0,0-3.8.15L5.61,12.19A2.74,2.74,0,0,0,5.46,16a2.5,2.5,0,0,0,2,.71.74.74,0,0,1,.81.67.75.75,0,0,1-.67.82Z"/><path d="M12.58,18A4,4,0,0,1,9.75,16.8a4.25,4.25,0,0,1,.15-6l1.26-1.26a.75.75,0,1,1,1.06,1.06L11,11.9a2.73,2.73,0,0,0-.14,3.84,2.77,2.77,0,0,0,3.8-.15l3.77-3.78A2.74,2.74,0,0,0,18.54,8a2.5,2.5,0,0,0-2-.71.74.74,0,0,1-.81-.67.75.75,0,0,1,.67-.82A4,4,0,0,1,19.6,6.91a4.23,4.23,0,0,1-.15,5.95l-3.76,3.79A4.44,4.44,0,0,1,12.58,18Z"/></g></g></g>
|
||||
<text class="feeder" x="427.89" y="54">Combine</text>
|
||||
<rect class="pill" x="482.11" y="40" width="88.6" height="21" rx="10.5"/>
|
||||
<g class="ico--derivation"><g fill="currentColor" transform="translate(492.11 45.5) scale(0.4166666666666667)"><path d="M19.75,16c0,.41-.34,.75-.75,.75H6.81l1.22,1.22c.29,.29,.29,.77,0,1.06-.15,.15-.34,.22-.53,.22s-.38-.07-.53-.22l-2.5-2.5c-.07-.07-.12-.15-.16-.24-.08-.18-.08-.39,0-.57,.04-.09,.09-.17,.16-.24l2.5-2.5c.29-.29,.77-.29,1.06,0s.29,.77,0,1.06l-1.22,1.22h12.19c.41,0,.75,.34,.75,.75ZM5,8.75h12.19l-1.22,1.22c-.29,.29-.29,.77,0,1.06,.15,.15,.34,.22,.53,.22s.38-.07,.53-.22l2.5-2.5c.07-.07,.12-.15,.16-.24,.08-.18,.08-.39,0-.57-.04-.09-.09-.17-.16-.24l-2.5-2.5c-.29-.29-.77-.29-1.06,0s-.29,.77,0,1.06l1.22,1.22H5c-.41,0-.75,.34-.75,.75s.34,.75,.75,.75Z"/></g></g>
|
||||
<text class="feeder" x="506.11" y="54">Derivation</text>
|
||||
<rect class="pill" x="576.71" y="40" width="88.6" height="21" rx="10.5"/>
|
||||
<g class="ico--constraint"><g fill="currentColor" transform="translate(586.71 45.5) scale(0.4166666666666667)"><g id="filter"><path d="M14,20.5H10a.76.76,0,0,1-.75-.75V12L3.9,4.69a.73.73,0,0,1-.07-.78A.76.76,0,0,1,4.5,3.5h15a.76.76,0,0,1,.67.41.73.73,0,0,1-.07.78L14.75,12v7.75A.76.76,0,0,1,14,20.5ZM10.75,19h2.5V11.75a.71.71,0,0,1,.15-.44L18,5H6l4.62,6.31a.71.71,0,0,1,.15.44Z"/></g></g></g>
|
||||
<text class="feeder" x="600.71" y="54">Constraint</text>
|
||||
<g class="ico--ext"><g fill="currentColor" transform="translate(434 72) scale(0.5)"><g id="angle-down"><path d="M12,14.5a.74.74,0,0,1-.53-.22L8,10.78A.75.75,0,0,1,9,9.72l3,3,3-3A.75.75,0,0,1,16,10.78l-3.5,3.5A.74.74,0,0,1,12,14.5Z"/></g></g></g>
|
||||
<rect class="card card--wp" x="50" y="104" width="124" height="66" rx="10"/>
|
||||
<g class="ico ico--wp"><g fill="currentColor" transform="translate(104 115) scale(0.6666666666666666)"><g id="sitemap"><path d="M13.5,9.75h-3A1.76,1.76,0,0,1,8.75,8V5A1.76,1.76,0,0,1,10.5,3.25h3A1.76,1.76,0,0,1,15.25,5V8A1.76,1.76,0,0,1,13.5,9.75Zm-3-5a.25.25,0,0,0-.25.25V8a.25.25,0,0,0,.25.25h3A.25.25,0,0,0,13.75,8V5a.25.25,0,0,0-.25-.25Z"/><path d="M6,19.75H4A1.76,1.76,0,0,1,2.25,18V16A1.76,1.76,0,0,1,4,14.25H6A1.76,1.76,0,0,1,7.75,16v2A1.76,1.76,0,0,1,6,19.75Zm-2-4a.25.25,0,0,0-.25.25v2a.25.25,0,0,0,.25.25H6A.25.25,0,0,0,6.25,18V16A.25.25,0,0,0,6,15.75Z"/><path d="M13,19.75H11A1.76,1.76,0,0,1,9.25,18V16A1.76,1.76,0,0,1,11,14.25h2A1.76,1.76,0,0,1,14.75,16v2A1.76,1.76,0,0,1,13,19.75Zm-2-4a.25.25,0,0,0-.25.25v2a.25.25,0,0,0,.25.25h2a.25.25,0,0,0,.25-.25V16a.25.25,0,0,0-.25-.25Z"/><path d="M20,19.75H18A1.76,1.76,0,0,1,16.25,18V16A1.76,1.76,0,0,1,18,14.25h2A1.76,1.76,0,0,1,21.75,16v2A1.76,1.76,0,0,1,20,19.75Zm-2-4a.25.25,0,0,0-.25.25v2a.25.25,0,0,0,.25.25h2a.25.25,0,0,0,.25-.25V16a.25.25,0,0,0-.25-.25Z"/><path d="M19,15.75a.76.76,0,0,1-.75-.75V13a.25.25,0,0,0-.25-.25H6a.25.25,0,0,0-.25.25v2a.75.75,0,0,1-1.5,0V13A1.76,1.76,0,0,1,6,11.25H18A1.76,1.76,0,0,1,19.75,13v2A.76.76,0,0,1,19,15.75Z"/><path d="M12,15.75a.76.76,0,0,1-.75-.75V9a.75.75,0,0,1,1.5,0v6A.76.76,0,0,1,12,15.75Z"/></g></g></g>
|
||||
<text class="nm" x="112" y="147" text-anchor="middle">WP Context</text>
|
||||
<text class="id" x="112" y="161" text-anchor="middle">rolls + resolves</text>
|
||||
<text class="lbl" x="226" y="128" text-anchor="middle">EMITS</text>
|
||||
<rect fill="url(#flow)" x="182" y="136.2" width="82" height="1.6"/>
|
||||
<path class="head" d="M264 132.5 L270 137 L264 141.5 Z"/>
|
||||
<rect class="chip chip--a" x="287.4" y="102" width="64.4" height="19" rx="9.5"/>
|
||||
<text class="chipt chipt--a" x="319.59999999999997" y="115" text-anchor="middle">$subject</text>
|
||||
<rect class="chip chip--b" x="356.79999999999995" y="102" width="51.8" height="19" rx="9.5"/>
|
||||
<text class="chipt chipt--b" x="382.69999999999993" y="115" text-anchor="middle">$style</text>
|
||||
<rect class="chip chip--c" x="312.65" y="126" width="70.69999999999999" height="19" rx="9.5"/>
|
||||
<text class="chipt chipt--c" x="348" y="139" text-anchor="middle">$lighting</text>
|
||||
<text class="varcap" x="348" y="164" text-anchor="middle">RESOLVED $VARS</text>
|
||||
<text class="lbl" x="457" y="128" text-anchor="middle">FILLS</text>
|
||||
<rect fill="url(#flow)" x="426" y="136.2" width="56" height="1.6"/>
|
||||
<path class="head" d="M482 132.5 L488 137 L482 141.5 Z"/>
|
||||
<rect class="card card--wp" x="496" y="104" width="140" height="66" rx="10"/>
|
||||
<g class="ico ico--wp"><g fill="currentColor" transform="translate(558 115) scale(0.6666666666666666)"><g id="align-left"><path d="M13.93,11h-10a.75.75,0,1,1,0-1.5h10a.75.75,0,0,1,0,1.5Z"/><path d="M20.07,7h-16a.75.75,0,0,1,0-1.5h16a.75.75,0,0,1,0,1.5Z"/><path d="M20.07,15h-16a.75.75,0,0,1,0-1.5h16a.75.75,0,0,1,0,1.5Z"/><path d="M13.93,19h-10a.75.75,0,1,1,0-1.5h10a.75.75,0,0,1,0,1.5Z"/></g></g></g>
|
||||
<text class="nm" x="566" y="147" text-anchor="middle">Prompt Assembler</text>
|
||||
<text class="id" x="566" y="161" text-anchor="middle">"A $style portrait…"</text>
|
||||
<text class="lbl" x="673" y="128" text-anchor="middle">PROMPT</text>
|
||||
<rect fill="url(#flow)" x="644" y="136.2" width="52" height="1.6"/>
|
||||
<path class="head" d="M696 132.5 L702 137 L696 141.5 Z"/>
|
||||
<rect class="card card--ext" x="710" y="104" width="124" height="66" rx="10"/>
|
||||
<g class="ico ico--ext"><g fill="currentColor" transform="translate(764 115) scale(0.6666666666666666)"><g id="bolt"><path d="M11.09,21.5a.67.67,0,0,1-.24,0,.83.83,0,0,1-.59-.81v-.11l.9-6.35H6.82a.8.8,0,0,1-.71-.43.85.85,0,0,1,0-.86l2-3.49,4.1-6.52a.79.79,0,0,1,.92-.35.83.83,0,0,1,.59.81v.11l-.9,6.35h4.35a.8.8,0,0,1,.71.43.85.85,0,0,1,0,.86l-2,3.49-4.1,6.52A.79.79,0,0,1,11.09,21.5Zm-.53-1.21h0Zm-2.63-7.6h4a.84.84,0,0,1,.83.85v.11l-.59,4.14,2.5-4,1.44-2.48h-4a.84.84,0,0,1-.83-.85v-.11l.59-4.14-2.5,4Zm-.57,1Zm9.28-3.34ZM13.44,3.7h0Z"/></g></g></g>
|
||||
<text class="nm" x="772" y="147" text-anchor="middle">CLIP Encode</text>
|
||||
<text class="id" x="772" y="161" text-anchor="middle">conditioning</text>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 6.7 KiB After Width: | Height: | Size: 14 KiB |
@@ -1,102 +1,132 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 980 240" role="img" aria-label="WP Context Loop emits N prompts and feeds WP Seed List N seeds; both fan out into KSampler in lockstep">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 286" width="880" height="286" role="img" aria-label="WP Context Loop drives WP Context and the Prompt Assembler to produce N prompts, CLIP Encode turns them into conditioning for KSampler, and WP Seed List supplies the matching seed for each iteration directly to KSampler">
|
||||
<style><![CDATA[
|
||||
.bg { fill: #14161e; }
|
||||
.panel { fill: #1a1d2a; }
|
||||
.border-loop { stroke: #7c6ad6; }
|
||||
.border-ctx { stroke: #3a8fb7; }
|
||||
.border-asm { stroke: #7c6ad6; }
|
||||
.border-seed { stroke: #3a8fb7; }
|
||||
.border-k { stroke: #6a6a6a; }
|
||||
.ico-loop { fill: #c4b5fd; }
|
||||
.ico-ctx { fill: #7ec8e3; }
|
||||
.ico-asm { fill: #c4b5fd; }
|
||||
.ico-seed { fill: #7ec8e3; }
|
||||
.ico-k { fill: #aab; }
|
||||
.name { fill: #d6d8e0; font: 600 13px 'Inter', system-ui, sans-serif; }
|
||||
.sub { fill: #6f7384; font: 400 10px ui-monospace, monospace; }
|
||||
.arrow-lbl { fill: #6f7384; font: 600 10px 'Inter', system-ui, sans-serif; letter-spacing: 1px; text-transform: uppercase; }
|
||||
.arrow-line { stroke: #4a4d55; stroke-width: 2; fill: none; }
|
||||
.arrow-line-dim { stroke: #353841; stroke-width: 2; fill: none; stroke-dasharray: 5 4; }
|
||||
.arrow-head { fill: #4a4d55; }
|
||||
.caption { fill: #6f7384; font: 500 11px 'Inter', system-ui, sans-serif; }
|
||||
.frame, .card, .pill, .chip { stroke-width: 1; }
|
||||
.cap { font: 400 10px 'Segoe UI', -apple-system, BlinkMacSystemFont, system-ui, sans-serif; letter-spacing: .06em; }
|
||||
.feeder { font: 400 10.5px 'Segoe UI', -apple-system, BlinkMacSystemFont, system-ui, sans-serif; }
|
||||
.nm { font: 600 12px 'Segoe UI', -apple-system, BlinkMacSystemFont, system-ui, sans-serif; }
|
||||
.id { font: 400 9.5px 'JetBrains Mono', Consolas, Monaco, 'Courier New', monospace; }
|
||||
.lbl, .varcap { font: 400 9.5px 'Segoe UI', -apple-system, BlinkMacSystemFont, system-ui, sans-serif; letter-spacing: .05em; }
|
||||
.chipt { font: 400 10.5px 'JetBrains Mono', Consolas, Monaco, 'Courier New', monospace; }
|
||||
|
||||
.frame { fill: #1e1e1e; stroke: #3a3a3a; }
|
||||
.card { fill: #232323; stroke: #4a4a4a; }
|
||||
.card--wp { stroke: #2dd4bf; stroke-opacity: .55; }
|
||||
.ico--wp { color: #2dd4bf; }
|
||||
.ico--ext { color: #aaaaaa; }
|
||||
.ico--wildcard { color: #a78bfa; }
|
||||
.ico--fixed { color: #22d3ee; }
|
||||
.ico--combine { color: #34d399; }
|
||||
.ico--derivation { color: #fbbf24; }
|
||||
.ico--constraint { color: #f472b6; }
|
||||
.pill { fill: #232323; stroke: #3a3a3a; }
|
||||
.feeder { fill: #aaaaaa; }
|
||||
.nm { fill: #dddddd; }
|
||||
.id, .lbl, .cap, .varcap { fill: #666666; }
|
||||
.ln { stroke: #4a4a4a; }
|
||||
.wash { stop-color: #2dd4bf; }
|
||||
.flow0 { stop-color: #4a4a4a; }
|
||||
.head { fill: #4a4a4a; }
|
||||
.chip { fill: #232323; }
|
||||
.chip--a { stroke: #8b5cf6; stroke-opacity: .4; }
|
||||
.chip--b { stroke: #22d3ee; stroke-opacity: .4; }
|
||||
.chip--c { stroke: #34d399; stroke-opacity: .4; }
|
||||
.chipt--a { fill: #c4b5fd; }
|
||||
.chipt--b { fill: #67e8f9; }
|
||||
.chipt--c { fill: #86efac; }
|
||||
@media (prefers-color-scheme: light) {
|
||||
.frame { fill: #f5f5f5; stroke: #b0b0b0; }
|
||||
.card { fill: #ffffff; stroke: #999999; }
|
||||
.card--wp { stroke: #0f766e; stroke-opacity: .55; }
|
||||
.ico--wp { color: #0f766e; }
|
||||
.ico--ext { color: #555555; }
|
||||
.ico--wildcard { color: #6d28d9; }
|
||||
.ico--fixed { color: #1d4ed8; }
|
||||
.ico--combine { color: #065f46; }
|
||||
.ico--derivation { color: #92400e; }
|
||||
.ico--constraint { color: #9d174d; }
|
||||
.pill { fill: #ffffff; stroke: #b0b0b0; }
|
||||
.feeder { fill: #555555; }
|
||||
.nm { fill: #1a1a1a; }
|
||||
.id, .lbl, .cap, .varcap { fill: #888888; }
|
||||
.ln { stroke: #999999; }
|
||||
.wash { stop-color: #0f766e; }
|
||||
.flow0 { stop-color: #999999; }
|
||||
.head { fill: #999999; }
|
||||
.chip { fill: #ffffff; }
|
||||
.chip--a { stroke: #8b5cf6; stroke-opacity: .4; }
|
||||
.chip--b { stroke: #22d3ee; stroke-opacity: .4; }
|
||||
.chip--c { stroke: #34d399; stroke-opacity: .4; }
|
||||
.chipt--a { fill: #6d28d9; }
|
||||
.chipt--b { fill: #1d4ed8; }
|
||||
.chipt--c { fill: #065f46; }
|
||||
}
|
||||
]]></style>
|
||||
|
||||
<rect class="bg" width="980" height="240" rx="8" />
|
||||
|
||||
<!-- WP Context Loop -->
|
||||
<g transform="translate(30, 70)">
|
||||
<rect class="panel border-loop" x="0" y="0" width="160" height="100" rx="10" stroke-width="2" />
|
||||
<text class="ico-loop" x="80" y="32" text-anchor="middle" font-size="20">↺</text>
|
||||
<text class="name" x="80" y="58" text-anchor="middle">WP Context Loop</text>
|
||||
<text class="sub" x="80" y="78" text-anchor="middle">N prompts</text>
|
||||
</g>
|
||||
|
||||
<!-- Loop splits into TWO lanes -->
|
||||
|
||||
<!-- Lane A: loop_config → Seed List → seed[] -->
|
||||
<g transform="translate(200, 60)">
|
||||
<text class="arrow-lbl" x="50" y="-6" text-anchor="middle">loop_config</text>
|
||||
<line class="arrow-line" x1="0" y1="6" x2="92" y2="6" />
|
||||
<polygon class="arrow-head" points="92,1 100,6 92,11" />
|
||||
</g>
|
||||
<g transform="translate(310, 30)">
|
||||
<rect class="panel border-seed" x="0" y="0" width="160" height="80" rx="10" stroke-width="2" />
|
||||
<text class="ico-seed" x="80" y="28" text-anchor="middle" font-size="18">#</text>
|
||||
<text class="name" x="80" y="50" text-anchor="middle">WP Seed List</text>
|
||||
<text class="sub" x="80" y="68" text-anchor="middle">N seeds</text>
|
||||
</g>
|
||||
|
||||
<!-- Lane B: context → WP Context -->
|
||||
<g transform="translate(200, 160)">
|
||||
<text class="arrow-lbl" x="50" y="-6" text-anchor="middle">context</text>
|
||||
<line class="arrow-line" x1="0" y1="6" x2="92" y2="6" />
|
||||
<polygon class="arrow-head" points="92,1 100,6 92,11" />
|
||||
</g>
|
||||
<g transform="translate(310, 130)">
|
||||
<rect class="panel border-ctx" x="0" y="0" width="160" height="80" rx="10" stroke-width="2" />
|
||||
<text class="ico-ctx" x="80" y="28" text-anchor="middle" font-size="18">⌬</text>
|
||||
<text class="name" x="80" y="50" text-anchor="middle">WP Context</text>
|
||||
<text class="sub" x="80" y="68" text-anchor="middle">module stack</text>
|
||||
</g>
|
||||
|
||||
<!-- WP Context → Prompt Assembler -->
|
||||
<g transform="translate(480, 160)">
|
||||
<line class="arrow-line" x1="0" y1="6" x2="62" y2="6" />
|
||||
<polygon class="arrow-head" points="62,1 70,6 62,11" />
|
||||
</g>
|
||||
|
||||
<!-- Prompt Assembler -->
|
||||
<g transform="translate(560, 130)">
|
||||
<rect class="panel border-asm" x="0" y="0" width="160" height="80" rx="10" stroke-width="2" />
|
||||
<text class="ico-asm" x="80" y="28" text-anchor="middle" font-size="18">≡</text>
|
||||
<text class="name" x="80" y="50" text-anchor="middle">Prompt Assembler</text>
|
||||
<text class="sub" x="80" y="68" text-anchor="middle">N prompts</text>
|
||||
</g>
|
||||
|
||||
<!-- Seed List → KSampler (top lane) -->
|
||||
<g transform="translate(480, 60)">
|
||||
<text class="arrow-lbl" x="180" y="-6" text-anchor="middle">seed[]</text>
|
||||
<path class="arrow-line" d="M 0 6 L 360 6 L 360 64" />
|
||||
<polygon class="arrow-head" points="355,59 360,67 365,59" />
|
||||
</g>
|
||||
|
||||
<!-- Assembler → KSampler (bottom lane joining top arrow at sampler) -->
|
||||
<g transform="translate(730, 160)">
|
||||
<text class="arrow-lbl" x="40" y="-6" text-anchor="middle">prompt[]</text>
|
||||
<line class="arrow-line" x1="0" y1="6" x2="62" y2="6" />
|
||||
<polygon class="arrow-head" points="62,1 70,6 62,11" />
|
||||
</g>
|
||||
|
||||
<!-- KSampler -->
|
||||
<g transform="translate(810, 130)">
|
||||
<rect class="panel border-k" x="0" y="0" width="140" height="80" rx="10" stroke-width="2" />
|
||||
<text class="ico-k" x="70" y="28" text-anchor="middle" font-size="18">⚡</text>
|
||||
<text class="name" x="70" y="50" text-anchor="middle">KSampler</text>
|
||||
<text class="sub" x="70" y="68" text-anchor="middle">N unique images</text>
|
||||
</g>
|
||||
|
||||
<!-- Caption -->
|
||||
<text class="caption" x="490" y="225" text-anchor="middle">
|
||||
Loop emits N prompts · Seed List emits N seeds · both lists fan out into the sampler in lockstep — iteration N's prompt pairs with seed N
|
||||
</text>
|
||||
<defs>
|
||||
<!-- Mirrors the SPA frame wash. The CSS is an ellipse 120 percent of the
|
||||
width by 100 percent of the HEIGHT, anchored top-left — so it spans
|
||||
the whole panel. Squashing it by the aspect ratio instead pins it to
|
||||
the corner and leaves the rest looking flat. -->
|
||||
<radialGradient id="wash" cx="0" cy="0" r="1" gradientTransform="scale(1.2 1)">
|
||||
<stop class="wash" offset="0" stop-opacity="0.10"/>
|
||||
<stop class="wash" offset="0.6" stop-opacity="0.02"/>
|
||||
<stop class="wash" offset="1" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="flowv" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop class="flow0" offset="0" stop-opacity="0"/>
|
||||
<stop class="flow0" offset="0.25" stop-opacity="1"/>
|
||||
<stop class="flow0" offset="0.8" stop-opacity="1"/>
|
||||
<stop class="flow0" offset="1" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="flow" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop class="flow0" offset="0" stop-opacity="0"/>
|
||||
<stop class="flow0" offset="0.2" stop-opacity="1"/>
|
||||
<stop class="flow0" offset="0.8" stop-opacity="1"/>
|
||||
<stop class="flow0" offset="1" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect class="frame" x="0.5" y="0.5" width="879" height="285" rx="12"/>
|
||||
<rect x="0.5" y="0.5" width="879" height="285" rx="12" fill="url(#wash)"/>
|
||||
<text class="cap" x="440" y="30" text-anchor="middle">BOTH LISTS FAN OUT IN LOCKSTEP — ITERATION N MEETS SEED N</text>
|
||||
<rect class="card card--wp" x="48.199999999999996" y="54" width="127.60000000000001" height="66" rx="10"/>
|
||||
<g class="ico ico--wp"><g fill="currentColor" transform="translate(104 65) scale(0.6666666666666666)"><g id="refresh"><path d="M12,20.75a7.25,7.25,0,0,1,0-14.5h2.5a.75.75,0,0,1,0,1.5H12a5.75,5.75,0,1,0,5.75,5.75.75.75,0,0,1,1.5,0A7.26,7.26,0,0,1,12,20.75Z"/><path d="M12,10.75a.74.74,0,0,1-.53-.22.75.75,0,0,1,0-1.06L13.94,7,11.47,4.53a.75.75,0,1,1,1.06-1.06l3,3a.75.75,0,0,1,0,1.06l-3,3A.74.74,0,0,1,12,10.75Z"/></g></g></g>
|
||||
<text class="nm" x="112" y="97" text-anchor="middle">WP Context Loop</text>
|
||||
<text class="id" x="112" y="111" text-anchor="middle">N iterations</text>
|
||||
<rect class="card card--wp" x="50" y="158" width="124" height="66" rx="10"/>
|
||||
<g class="ico ico--wp"><g fill="currentColor" transform="translate(104 169) scale(0.6666666666666666)"><g id="list"><path d="M19,12.75H8a.75.75,0,0,1,0-1.5H19a.75.75,0,0,1,0,1.5Z"/><path d="M19,8.25H8a.75.75,0,0,1,0-1.5H19a.75.75,0,0,1,0,1.5Z"/><path d="M19,17.25H8a.75.75,0,0,1,0-1.5H19a.75.75,0,0,1,0,1.5Z"/><path d="M5,8.5a1,1,0,0,1-.38-.07,1.46,1.46,0,0,1-.33-.22A1,1,0,0,1,4,7.5a1.05,1.05,0,0,1,.29-.71.93.93,0,0,1,.33-.21,1,1,0,0,1,.76,0,1,1,0,0,1,.33.21A1.05,1.05,0,0,1,6,7.5a1,1,0,0,1-.29.71,1.46,1.46,0,0,1-.33.22A1,1,0,0,1,5,8.5Z"/><path d="M5,13a1,1,0,0,1-.38-.08,1.15,1.15,0,0,1-.33-.21A1,1,0,0,1,4,12a1.05,1.05,0,0,1,.29-.71,1.15,1.15,0,0,1,.33-.21A1,1,0,0,1,5.2,11l.18.06.18.09a1.58,1.58,0,0,1,.15.12A1.05,1.05,0,0,1,6,12a1,1,0,0,1-1,1Z"/><path d="M5,17.5a1,1,0,0,1-.38-.07,1.46,1.46,0,0,1-.33-.22,1.15,1.15,0,0,1-.21-.33.94.94,0,0,1,0-.76,1.15,1.15,0,0,1,.21-.33,1,1,0,0,1,1.09-.21,1,1,0,0,1,.33.21,1.15,1.15,0,0,1,.21.33.94.94,0,0,1,0,.76,1.15,1.15,0,0,1-.21.33A1,1,0,0,1,5,17.5Z"/></g></g></g>
|
||||
<text class="nm" x="112" y="201" text-anchor="middle">WP Seed List</text>
|
||||
<text class="id" x="112" y="215" text-anchor="middle">N seeds</text>
|
||||
<rect class="card card--wp" x="278" y="54" width="124" height="66" rx="10"/>
|
||||
<g class="ico ico--wp"><g fill="currentColor" transform="translate(332 65) scale(0.6666666666666666)"><g id="sitemap"><path d="M13.5,9.75h-3A1.76,1.76,0,0,1,8.75,8V5A1.76,1.76,0,0,1,10.5,3.25h3A1.76,1.76,0,0,1,15.25,5V8A1.76,1.76,0,0,1,13.5,9.75Zm-3-5a.25.25,0,0,0-.25.25V8a.25.25,0,0,0,.25.25h3A.25.25,0,0,0,13.75,8V5a.25.25,0,0,0-.25-.25Z"/><path d="M6,19.75H4A1.76,1.76,0,0,1,2.25,18V16A1.76,1.76,0,0,1,4,14.25H6A1.76,1.76,0,0,1,7.75,16v2A1.76,1.76,0,0,1,6,19.75Zm-2-4a.25.25,0,0,0-.25.25v2a.25.25,0,0,0,.25.25H6A.25.25,0,0,0,6.25,18V16A.25.25,0,0,0,6,15.75Z"/><path d="M13,19.75H11A1.76,1.76,0,0,1,9.25,18V16A1.76,1.76,0,0,1,11,14.25h2A1.76,1.76,0,0,1,14.75,16v2A1.76,1.76,0,0,1,13,19.75Zm-2-4a.25.25,0,0,0-.25.25v2a.25.25,0,0,0,.25.25h2a.25.25,0,0,0,.25-.25V16a.25.25,0,0,0-.25-.25Z"/><path d="M20,19.75H18A1.76,1.76,0,0,1,16.25,18V16A1.76,1.76,0,0,1,18,14.25h2A1.76,1.76,0,0,1,21.75,16v2A1.76,1.76,0,0,1,20,19.75Zm-2-4a.25.25,0,0,0-.25.25v2a.25.25,0,0,0,.25.25h2a.25.25,0,0,0,.25-.25V16a.25.25,0,0,0-.25-.25Z"/><path d="M19,15.75a.76.76,0,0,1-.75-.75V13a.25.25,0,0,0-.25-.25H6a.25.25,0,0,0-.25.25v2a.75.75,0,0,1-1.5,0V13A1.76,1.76,0,0,1,6,11.25H18A1.76,1.76,0,0,1,19.75,13v2A.76.76,0,0,1,19,15.75Z"/><path d="M12,15.75a.76.76,0,0,1-.75-.75V9a.75.75,0,0,1,1.5,0v6A.76.76,0,0,1,12,15.75Z"/></g></g></g>
|
||||
<text class="nm" x="340" y="97" text-anchor="middle">WP Context</text>
|
||||
<text class="id" x="340" y="111" text-anchor="middle">module stack</text>
|
||||
<rect class="card card--wp" x="499.08" y="54" width="133.84" height="66" rx="10"/>
|
||||
<g class="ico ico--wp"><g fill="currentColor" transform="translate(558 65) scale(0.6666666666666666)"><g id="align-left"><path d="M13.93,11h-10a.75.75,0,1,1,0-1.5h10a.75.75,0,0,1,0,1.5Z"/><path d="M20.07,7h-16a.75.75,0,0,1,0-1.5h16a.75.75,0,0,1,0,1.5Z"/><path d="M20.07,15h-16a.75.75,0,0,1,0-1.5h16a.75.75,0,0,1,0,1.5Z"/><path d="M13.93,19h-10a.75.75,0,1,1,0-1.5h10a.75.75,0,0,1,0,1.5Z"/></g></g></g>
|
||||
<text class="nm" x="566" y="97" text-anchor="middle">Prompt Assembler</text>
|
||||
<text class="id" x="566" y="111" text-anchor="middle">N prompts</text>
|
||||
<rect class="card card--ext" x="504" y="158" width="124" height="66" rx="10"/>
|
||||
<g class="ico ico--ext"><g fill="currentColor" transform="translate(558 169) scale(0.6666666666666666)"><g id="bolt"><path d="M11.09,21.5a.67.67,0,0,1-.24,0,.83.83,0,0,1-.59-.81v-.11l.9-6.35H6.82a.8.8,0,0,1-.71-.43.85.85,0,0,1,0-.86l2-3.49,4.1-6.52a.79.79,0,0,1,.92-.35.83.83,0,0,1,.59.81v.11l-.9,6.35h4.35a.8.8,0,0,1,.71.43.85.85,0,0,1,0,.86l-2,3.49-4.1,6.52A.79.79,0,0,1,11.09,21.5Zm-.53-1.21h0Zm-2.63-7.6h4a.84.84,0,0,1,.83.85v.11l-.59,4.14,2.5-4,1.44-2.48h-4a.84.84,0,0,1-.83-.85v-.11l.59-4.14-2.5,4Zm-.57,1Zm9.28-3.34ZM13.44,3.7h0Z"/></g></g></g>
|
||||
<text class="nm" x="566" y="201" text-anchor="middle">CLIP Encode</text>
|
||||
<text class="id" x="566" y="215" text-anchor="middle">N conditionings</text>
|
||||
<rect class="card card--ext" x="710" y="158" width="124" height="66" rx="10"/>
|
||||
<g class="ico ico--ext"><g fill="currentColor" transform="translate(764 169) scale(0.6666666666666666)"><g id="image"><path d="M18,4.25H6A2.75,2.75,0,0,0,3.25,7V17A2.75,2.75,0,0,0,6,19.75H18A2.75,2.75,0,0,0,20.75,17V7A2.75,2.75,0,0,0,18,4.25ZM6,5.75H18A1.25,1.25,0,0,1,19.25,7v8.19l-2.72-2.72a.7.7,0,0,0-.56-.22.79.79,0,0,0-.55.27l-1.29,1.55-4.6-4.6A.7.7,0,0,0,9,9.25a.79.79,0,0,0-.55.27L4.75,13.93V7A1.25,1.25,0,0,1,6,5.75ZM4.75,17v-.73l4.3-5.16,4.12,4.12-2.52,3H6A1.25,1.25,0,0,1,4.75,17ZM18,18.25H12.6l3.45-4.14,3.15,3.15A1.23,1.23,0,0,1,18,18.25Z"/></g></g></g>
|
||||
<text class="nm" x="772" y="201" text-anchor="middle">KSampler</text>
|
||||
<text class="id" x="772" y="215" text-anchor="middle">N images</text>
|
||||
<text class="lbl" x="226.9" y="78" text-anchor="middle">CONTEXT</text>
|
||||
<rect fill="url(#flow)" x="183.8" y="86.2" width="80.19999999999999" height="1.6"/>
|
||||
<path class="head" d="M264 82.5 L270 87 L264 91.5 Z"/>
|
||||
<text class="lbl" x="122" y="143">LOOP_CONFIG</text>
|
||||
<rect fill="url(#flowv)" x="111.2" y="120" width="1.6" height="32"/>
|
||||
<path class="head" d="M108 152 L112 158 L116 152 Z"/>
|
||||
<text class="lbl" x="450.53999999999996" y="78" text-anchor="middle">$VARS</text>
|
||||
<rect fill="url(#flow)" x="410" y="86.2" width="75.07999999999998" height="1.6"/>
|
||||
<path class="head" d="M485.08 82.5 L491.08 87 L485.08 91.5 Z"/>
|
||||
<text class="lbl" x="576" y="141">PROMPT</text>
|
||||
<rect fill="url(#flowv)" x="565.2" y="120" width="1.6" height="32"/>
|
||||
<path class="head" d="M562 152 L566 158 L570 152 Z"/>
|
||||
<text class="lbl" x="669" y="182" text-anchor="middle">COND</text>
|
||||
<rect fill="url(#flow)" x="636" y="190.2" width="60" height="1.6"/>
|
||||
<path class="head" d="M696 186.5 L702 191 L696 195.5 Z"/>
|
||||
<path class="ln" fill="none" d="M112 224 V 252 H 772 V 230"/>
|
||||
<path class="head" d="M768 230 L772 224 L776 230 Z"/>
|
||||
<text class="lbl" x="420" y="244" text-anchor="middle">SEED[]</text>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 4.9 KiB After Width: | Height: | Size: 11 KiB |
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "comfyui-wildcard-pipeline"
|
||||
version = "2.8.0"
|
||||
version = "2.13.2"
|
||||
description = "Modular procedural prompt generation for ComfyUI — wildcards, constraints, derivations, and context pipelines."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
/**
|
||||
* Generate the README flow figures.
|
||||
*
|
||||
* The SPA draws these as Vue + CSS with PrimeIcons webfont glyphs
|
||||
* (`src/manager/components/docs/PipelineDiagram.vue`, framed by
|
||||
* `DocFigure.vue`). A README can run neither: GitHub serves the file through
|
||||
* `<img>`, so there is no component runtime and no icon font.
|
||||
*
|
||||
* So this reproduces that figure in SVG, deriving every value from the real
|
||||
* component rather than approximating it by eye:
|
||||
*
|
||||
* frame --wp-bg-1 / --wp-border, radius --wp-radius-lg (12)
|
||||
* card --wp-bg-2, --wp-border-strong, radius 10, min-width 120,
|
||||
* column layout: icon 16 / name 12 semibold / id 9.5 mono dim
|
||||
* WP card border tinted with --wp-node, icon in --wp-node
|
||||
* feeders pills, --wp-bg-2 + --wp-border, 10.5px, icon in the kind colour
|
||||
* labels 9.5px uppercase, letter-spacing .04em, --wp-text-dim
|
||||
* var chips mono 10.5px, pill, per-chip accent border
|
||||
*
|
||||
* Icons are the REAL PrimeIcons paths from `primeicons/raw-svg` — the same
|
||||
* source the webfont is built from — so the README shows the same glyphs the
|
||||
* app does.
|
||||
*
|
||||
* Both themes ship in one file: GitHub honours `prefers-color-scheme` inside
|
||||
* an SVG served to `<img>`, so the light block below mirrors the SPA's light
|
||||
* theme rather than washing the dark one out.
|
||||
*
|
||||
* Run: node scripts/build-flow-figures.mjs
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const ICON_DIR = "node_modules/primeicons/raw-svg";
|
||||
const OUT_DIR = "public/images/docs";
|
||||
|
||||
/* ── tokens, lifted from src/components/shared/theme.css + manager tokens ── */
|
||||
const DARK = {
|
||||
frameBg: "#1e1e1e", frameBd: "#3a3a3a",
|
||||
cardBg: "#232323", cardBd: "#4a4a4a",
|
||||
node: "#2dd4bf",
|
||||
text: "#dddddd", muted: "#aaaaaa", dim: "#666666",
|
||||
wildcard: "#a78bfa", fixed: "#22d3ee", combine: "#34d399",
|
||||
derivation: "#fbbf24", constraint: "#f472b6",
|
||||
chipA: "#c4b5fd", chipAb: "#8b5cf6",
|
||||
chipB: "#67e8f9", chipBb: "#22d3ee",
|
||||
chipC: "#86efac", chipCb: "#34d399",
|
||||
};
|
||||
const LIGHT = {
|
||||
frameBg: "#f5f5f5", frameBd: "#b0b0b0",
|
||||
cardBg: "#ffffff", cardBd: "#999999",
|
||||
node: "#0f766e",
|
||||
text: "#1a1a1a", muted: "#555555", dim: "#888888",
|
||||
wildcard: "#6d28d9", fixed: "#1d4ed8", combine: "#065f46",
|
||||
derivation: "#92400e", constraint: "#9d174d",
|
||||
chipA: "#6d28d9", chipAb: "#8b5cf6",
|
||||
chipB: "#1d4ed8", chipBb: "#22d3ee",
|
||||
chipC: "#065f46", chipCb: "#34d399",
|
||||
};
|
||||
|
||||
const SANS = "'Segoe UI', -apple-system, BlinkMacSystemFont, system-ui, sans-serif";
|
||||
const MONO = "'JetBrains Mono', Consolas, Monaco, 'Courier New', monospace";
|
||||
|
||||
/** Rough advance width. Good enough to size pills; every label is centred, so
|
||||
* a few px of slop never misaligns text against its box. */
|
||||
const textW = (s, px, mono = false) => s.length * px * (mono ? 0.6 : 0.52);
|
||||
|
||||
/** Inner markup of a PrimeIcon, scaled to `size` and centred on (cx, cy).
|
||||
*
|
||||
* Colour comes from the wrapping `<g fill="currentColor">`, NOT from rewriting
|
||||
* each path. Most PrimeIcons declare no `fill` at all (only `sparkles` does),
|
||||
* so a rewrite-what-exists approach leaves them at SVG's default black — which
|
||||
* is exactly how every node icon came out black while the feeder pills, whose
|
||||
* icons happened to carry fills, coloured correctly.
|
||||
*
|
||||
* `fill="none"` is preserved: on the icons that use it, it marks the part that
|
||||
* is deliberately hollow, and filling it would blob the glyph.
|
||||
*/
|
||||
function icon(name, cx, cy, size) {
|
||||
const raw = fs.readFileSync(path.join(ICON_DIR, `${name}.svg`), "utf8");
|
||||
const inner = raw
|
||||
.replace(/^[\s\S]*?<svg[^>]*>/, "")
|
||||
.replace(/<\/svg>\s*$/, "")
|
||||
.replace(/\s(?:width|height)="[^"]*"/g, "")
|
||||
// Drop concrete fills so the group's currentColor wins; keep `none`.
|
||||
.replace(/\sfill="(?!none)[^"]*"/g, "")
|
||||
.replace(/\sstroke="(?!none)[^"]*"/g, ' stroke="currentColor"')
|
||||
.trim();
|
||||
const s = size / 24;
|
||||
return `<g fill="currentColor" transform="translate(${cx - size / 2} ${cy - size / 2}) scale(${s})">${inner}</g>`;
|
||||
}
|
||||
|
||||
/** A node card. Vertical, centred: icon, name, mono subtitle — the SPA's
|
||||
* `.wp-doc-diagram__node-box`. `wp` cards take the teal node accent. */
|
||||
function card(cx, top, label, sub, iconName, kind = "wp") {
|
||||
const w = Math.max(124, textW(label, 12) + 34, textW(sub, 9.5, true) + 26);
|
||||
const h = 66;
|
||||
const x = cx - w / 2;
|
||||
return {
|
||||
w, h,
|
||||
svg: [
|
||||
`<rect class="card card--${kind}" x="${x}" y="${top}" width="${w}" height="${h}" rx="10"/>`,
|
||||
`<g class="ico ico--${kind}">${icon(iconName, cx, top + 19, 16)}</g>`,
|
||||
`<text class="nm" x="${cx}" y="${top + 43}" text-anchor="middle">${label}</text>`,
|
||||
`<text class="id" x="${cx}" y="${top + 57}" text-anchor="middle">${sub}</text>`,
|
||||
].join("\n "),
|
||||
};
|
||||
}
|
||||
|
||||
/** Labelled connector, matching `.wp-doc-diagram__arrow`: uppercase label
|
||||
* above a hairline that ends in a small solid head. */
|
||||
function connector(x1, x2, y, label) {
|
||||
const mid = (x1 + x2) / 2;
|
||||
return [
|
||||
label ? `<text class="lbl" x="${mid}" y="${y - 9}" text-anchor="middle">${label}</text>` : "",
|
||||
// Gradient fill, not a stroke: the SPA's `.wp-doc-diagram__arrow-ln` fades
|
||||
// in and out at both ends so a connector reads as a flow rather than a
|
||||
// drawn border. It has to be a RECT — a horizontal <line> has a zero-height
|
||||
// bounding box, so an objectBoundingBox gradient on it collapses and the
|
||||
// line disappears entirely, leaving a floating arrowhead.
|
||||
`<rect fill="url(#flow)" x="${x1}" y="${y - 0.8}" width="${x2 - 6 - x1}" height="1.6"/>`,
|
||||
`<path class="head" d="M${x2 - 6} ${y - 4.5} L${x2} ${y} L${x2 - 6} ${y + 4.5} Z"/>`,
|
||||
].join("\n ");
|
||||
}
|
||||
|
||||
/** Pill row of the five module kinds — `.wp-doc-diagram__feeder`. */
|
||||
function feeders(cx, y) {
|
||||
const items = [
|
||||
["sparkles", "Wildcard", "wildcard"],
|
||||
["tag", "Fixed Values", "fixed"],
|
||||
["link", "Combine", "combine"],
|
||||
["arrow-right-arrow-left", "Derivation", "derivation"],
|
||||
["filter", "Constraint", "constraint"],
|
||||
];
|
||||
const gap = 6;
|
||||
const pills = items.map(([ico, label, kind]) => {
|
||||
const w = 9 + 10 + 6 + textW(label, 10.5) + 9;
|
||||
return { ico, label, kind, w };
|
||||
});
|
||||
const total = pills.reduce((a, p) => a + p.w, 0) + gap * (pills.length - 1);
|
||||
let x = cx - total / 2;
|
||||
const out = pills.map((p) => {
|
||||
const s = [
|
||||
`<rect class="pill" x="${x}" y="${y}" width="${p.w}" height="21" rx="10.5"/>`,
|
||||
`<g class="ico--${p.kind}">${icon(p.ico, x + 15, y + 10.5, 10)}</g>`,
|
||||
`<text class="feeder" x="${x + 24}" y="${y + 14}">${p.label}</text>`,
|
||||
].join("\n ");
|
||||
x += p.w + gap;
|
||||
return s;
|
||||
});
|
||||
return out.join("\n ");
|
||||
}
|
||||
|
||||
/** The `$vars` stage: chips over a small uppercase caption. */
|
||||
function varBag(cx, top) {
|
||||
const chips = [["$subject", "a"], ["$style", "b"], ["$lighting", "c"]];
|
||||
const gap = 5;
|
||||
const sized = chips.map(([t, v]) => ({ t, v, w: textW(t, 10.5, true) + 14 }));
|
||||
// Two rows, mirroring the SPA's 150px-capped wrapping bag.
|
||||
const row1 = sized.slice(0, 2);
|
||||
const row2 = sized.slice(2);
|
||||
const line = (items, y) => {
|
||||
const total = items.reduce((a, c) => a + c.w, 0) + gap * (items.length - 1);
|
||||
let x = cx - total / 2;
|
||||
return items.map((c) => {
|
||||
const s = [
|
||||
`<rect class="chip chip--${c.v}" x="${x}" y="${y}" width="${c.w}" height="19" rx="9.5"/>`,
|
||||
`<text class="chipt chipt--${c.v}" x="${x + c.w / 2}" y="${y + 13}" text-anchor="middle">${c.t}</text>`,
|
||||
].join("\n ");
|
||||
x += c.w + gap;
|
||||
return s;
|
||||
}).join("\n ");
|
||||
};
|
||||
return [
|
||||
line(row1, top),
|
||||
line(row2, top + 24),
|
||||
`<text class="varcap" x="${cx}" y="${top + 62}" text-anchor="middle">RESOLVED $VARS</text>`,
|
||||
].join("\n ");
|
||||
}
|
||||
|
||||
function themeBlock(t, prefix = "") {
|
||||
return `
|
||||
${prefix}.frame { fill: ${t.frameBg}; stroke: ${t.frameBd}; }
|
||||
${prefix}.card { fill: ${t.cardBg}; stroke: ${t.cardBd}; }
|
||||
${prefix}.card--wp { stroke: ${t.node}; stroke-opacity: .55; }
|
||||
${prefix}.ico--wp { color: ${t.node}; }
|
||||
${prefix}.ico--ext { color: ${t.muted}; }
|
||||
${prefix}.ico--wildcard { color: ${t.wildcard}; }
|
||||
${prefix}.ico--fixed { color: ${t.fixed}; }
|
||||
${prefix}.ico--combine { color: ${t.combine}; }
|
||||
${prefix}.ico--derivation { color: ${t.derivation}; }
|
||||
${prefix}.ico--constraint { color: ${t.constraint}; }
|
||||
${prefix}.pill { fill: ${t.cardBg}; stroke: ${t.frameBd}; }
|
||||
${prefix}.feeder { fill: ${t.muted}; }
|
||||
${prefix}.nm { fill: ${t.text}; }
|
||||
${prefix}.id, ${prefix}.lbl, ${prefix}.cap, ${prefix}.varcap { fill: ${t.dim}; }
|
||||
${prefix}.ln { stroke: ${t.cardBd}; }
|
||||
${prefix}.wash { stop-color: ${t.node}; }
|
||||
${prefix}.flow0 { stop-color: ${t.cardBd}; }
|
||||
${prefix}.head { fill: ${t.cardBd}; }
|
||||
${prefix}.chip { fill: ${t.cardBg}; }
|
||||
${prefix}.chip--a { stroke: ${t.chipAb}; stroke-opacity: .4; }
|
||||
${prefix}.chip--b { stroke: ${t.chipBb}; stroke-opacity: .4; }
|
||||
${prefix}.chip--c { stroke: ${t.chipCb}; stroke-opacity: .4; }
|
||||
${prefix}.chipt--a { fill: ${t.chipA}; }
|
||||
${prefix}.chipt--b { fill: ${t.chipB}; }
|
||||
${prefix}.chipt--c { fill: ${t.chipC}; }`;
|
||||
}
|
||||
|
||||
function shell(w, h, label, body) {
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" role="img" aria-label="${label}">
|
||||
<style><![CDATA[
|
||||
.frame, .card, .pill, .chip { stroke-width: 1; }
|
||||
.cap { font: 400 10px ${SANS}; letter-spacing: .06em; }
|
||||
.feeder { font: 400 10.5px ${SANS}; }
|
||||
.nm { font: 600 12px ${SANS}; }
|
||||
.id { font: 400 9.5px ${MONO}; }
|
||||
.lbl, .varcap { font: 400 9.5px ${SANS}; letter-spacing: .05em; }
|
||||
.chipt { font: 400 10.5px ${MONO}; }
|
||||
${themeBlock(DARK)}
|
||||
@media (prefers-color-scheme: light) {${themeBlock(LIGHT, " ")}
|
||||
}
|
||||
]]></style>
|
||||
<defs>
|
||||
<!-- Mirrors the SPA frame wash. The CSS is an ellipse 120 percent of the
|
||||
width by 100 percent of the HEIGHT, anchored top-left — so it spans
|
||||
the whole panel. Squashing it by the aspect ratio instead pins it to
|
||||
the corner and leaves the rest looking flat. -->
|
||||
<radialGradient id="wash" cx="0" cy="0" r="1" gradientTransform="scale(1.2 1)">
|
||||
<stop class="wash" offset="0" stop-opacity="0.10"/>
|
||||
<stop class="wash" offset="0.6" stop-opacity="0.02"/>
|
||||
<stop class="wash" offset="1" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="flowv" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop class="flow0" offset="0" stop-opacity="0"/>
|
||||
<stop class="flow0" offset="0.25" stop-opacity="1"/>
|
||||
<stop class="flow0" offset="0.8" stop-opacity="1"/>
|
||||
<stop class="flow0" offset="1" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="flow" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop class="flow0" offset="0" stop-opacity="0"/>
|
||||
<stop class="flow0" offset="0.2" stop-opacity="1"/>
|
||||
<stop class="flow0" offset="0.8" stop-opacity="1"/>
|
||||
<stop class="flow0" offset="1" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect class="frame" x="0.5" y="0.5" width="${w - 1}" height="${h - 1}" rx="12"/>
|
||||
<rect x="0.5" y="0.5" width="${w - 1}" height="${h - 1}" rx="12" fill="url(#wash)"/>
|
||||
${body}
|
||||
</svg>
|
||||
`;
|
||||
}
|
||||
|
||||
/* ── figure 1 — what the pipeline does ─────────────────────────────────── */
|
||||
function buildIntro() {
|
||||
const W = 880;
|
||||
const H = 202;
|
||||
const cx = W / 2;
|
||||
const rowTop = 104;
|
||||
const midY = rowTop + 33;
|
||||
|
||||
const ctx = card(112, rowTop, "WP Context", "rolls + resolves", "sitemap");
|
||||
const asm = card(566, rowTop, "Prompt Assembler", '"A $style portrait…"', "align-left");
|
||||
const clip = card(772, rowTop, "CLIP Encode", "conditioning", "bolt", "ext");
|
||||
const varsCx = 348;
|
||||
|
||||
const body = [
|
||||
`<text class="cap" x="${cx}" y="30" text-anchor="middle">MODULES INSIDE THE CONTEXT</text>`,
|
||||
feeders(cx, 40),
|
||||
`<g class="ico--ext">${icon("angle-down", cx, 78, 12)}</g>`,
|
||||
ctx.svg,
|
||||
connector(112 + ctx.w / 2 + 8, varsCx - 78, midY, "EMITS"),
|
||||
varBag(varsCx, rowTop - 2),
|
||||
connector(varsCx + 78, 566 - asm.w / 2 - 8, midY, "FILLS"),
|
||||
asm.svg,
|
||||
connector(566 + asm.w / 2 + 8, 772 - clip.w / 2 - 8, midY, "PROMPT"),
|
||||
clip.svg,
|
||||
].join("\n ");
|
||||
|
||||
return shell(
|
||||
W,
|
||||
H,
|
||||
"Wildcard, Fixed Values, Combine, Derivation and Constraint modules resolve inside WP Context, which emits resolved dollar-variables that fill the WP Prompt Assembler template, which CLIP Encode turns into conditioning",
|
||||
body,
|
||||
);
|
||||
}
|
||||
|
||||
/* ── figure 2 — looping a chain ────────────────────────────────────────────
|
||||
* The old figure ran the assembled prompt straight into KSampler. It does not
|
||||
* go there: text is encoded first and only conditioning reaches the sampler.
|
||||
* Seeds are the one thing that DOES arrive directly, so they get their own
|
||||
* lane BELOW the text path rather than cutting through it. */
|
||||
function buildLoop() {
|
||||
const W = 880;
|
||||
const H = 286;
|
||||
const cx = W / 2;
|
||||
const r1 = 54;
|
||||
const r2 = 158;
|
||||
const mid1 = r1 + 33;
|
||||
const mid2 = r2 + 33;
|
||||
const laneY = 252;
|
||||
|
||||
const loop = card(112, r1, "WP Context Loop", "N iterations", "refresh");
|
||||
const seeds = card(112, r2, "WP Seed List", "N seeds", "list");
|
||||
const ctx = card(340, r1, "WP Context", "module stack", "sitemap");
|
||||
const asm = card(566, r1, "Prompt Assembler", "N prompts", "align-left");
|
||||
const clip = card(566, r2, "CLIP Encode", "N conditionings", "bolt", "ext");
|
||||
const ks = card(772, r2, "KSampler", "N images", "image", "ext");
|
||||
|
||||
const body = [
|
||||
`<text class="cap" x="${cx}" y="30" text-anchor="middle">BOTH LISTS FAN OUT IN LOCKSTEP — ITERATION N MEETS SEED N</text>`,
|
||||
loop.svg, seeds.svg, ctx.svg, asm.svg, clip.svg, ks.svg,
|
||||
connector(112 + loop.w / 2 + 8, 340 - ctx.w / 2 - 8, mid1, "CONTEXT"),
|
||||
// WP_ContextLoop has a `loop_config` side-output and WP_SeedList takes it
|
||||
// as an optional input, so the seed list mirrors the loop's count,
|
||||
// strategy and base seed. That link is what makes the caption's "lockstep"
|
||||
// true; without it the two read as unrelated sources.
|
||||
`<text class="lbl" x="122" y="${(r1 + 66 + r2) / 2 + 4}">LOOP_CONFIG</text>`,
|
||||
`<rect fill="url(#flowv)" x="111.2" y="${r1 + 66}" width="1.6" height="${r2 - 6 - (r1 + 66)}"/>`,
|
||||
`<path class="head" d="M108 ${r2 - 6} L112 ${r2} L116 ${r2 - 6} Z"/>`,
|
||||
connector(340 + ctx.w / 2 + 8, 566 - asm.w / 2 - 8, mid1, "$VARS"),
|
||||
// assembler drops straight down into the encoder
|
||||
`<text class="lbl" x="576" y="141">PROMPT</text>`,
|
||||
`<rect fill="url(#flowv)" x="565.2" y="${r1 + 66}" width="1.6" height="${r2 - 6 - (r1 + 66)}"/>`,
|
||||
`<path class="head" d="M562 ${r2 - 6} L566 ${r2} L570 ${r2 - 6} Z"/>`,
|
||||
connector(566 + clip.w / 2 + 8, 772 - ks.w / 2 - 8, mid2, "COND"),
|
||||
// seeds take their own lane under the text path and rise into the sampler
|
||||
`<path class="ln" fill="none" d="M112 ${r2 + 66} V ${laneY} H 772 V ${r2 + 72}"/>`,
|
||||
`<path class="head" d="M768 ${r2 + 72} L772 ${r2 + 66} L776 ${r2 + 72} Z"/>`,
|
||||
`<text class="lbl" x="420" y="${laneY - 8}" text-anchor="middle">SEED[]</text>`,
|
||||
].join("\n ");
|
||||
|
||||
return shell(
|
||||
W,
|
||||
H,
|
||||
"WP Context Loop drives WP Context and the Prompt Assembler to produce N prompts, CLIP Encode turns them into conditioning for KSampler, and WP Seed List supplies the matching seed for each iteration directly to KSampler",
|
||||
body,
|
||||
);
|
||||
}
|
||||
|
||||
fs.writeFileSync(path.join(OUT_DIR, "flow-intro.svg"), buildIntro());
|
||||
fs.writeFileSync(path.join(OUT_DIR, "flow-loop.svg"), buildLoop());
|
||||
console.log("wrote flow-intro.svg + flow-loop.svg");
|
||||
@@ -215,7 +215,39 @@ const ENTRY_LIMIT = 30 * 1024; // 30 KB
|
||||
// per-frame seed under control_after_generate=randomize) plus the modal
|
||||
// Lock-button resolver (lock-seed-ctx provide/inject into SeedLockControls).
|
||||
// Landed exactly at the 448 ceiling (458752/458752); bump for headroom.
|
||||
const TOTAL_LIMIT = 449 * 1024; // 449 KB
|
||||
// Bumped 449 -> 450 KB on 2026-06-28 for the row context-menu Hold toggle.
|
||||
// Adds HOLD_KINDS + isHoldable + toggleHold to ContextWidget plus the quick
|
||||
// "Hold across run" / "Release hold" menu item (2-click seed_scope toggle,
|
||||
// base-only with a frame-active disabled hint) in the lazy ContextWidget
|
||||
// chunk; entry stays put. Measured 459909 bytes (133 over the 449 ceiling);
|
||||
// minimal bump.
|
||||
// Bumped 450 -> 453 KB on 2026-07-21 for loop bypass frames (#13): the
|
||||
// `bypass_frames` config field + the SeedLockRow bypass toggle, the
|
||||
// SeedListModal opt-in bypass column, and the ContextLoopWidget "N bypassed"
|
||||
// badge. Config field alone landed 34 bytes over 450; the ~3 KB headroom
|
||||
// covers the UI additions in the same feature.
|
||||
// Bumped 453 -> 461 KB on 2026-07-23 for the chip-UX + library-linkage feature
|
||||
// set (issues #1-#9). Workstream B (RefChip hover card: uuid + filter reads-as
|
||||
// + live "N of M options match" from the extended preview-resolver) landed the
|
||||
// canvas within 10 bytes of the 453 ceiling; the +8 KB gives the remaining
|
||||
// workstreams D (library re-link UI) and E (nested-ref propagation) room in the
|
||||
// same approved feature set. Explicitly approved.
|
||||
// Bumped 461 -> 468 KB on 2026-07-30 for the QoL sweep (P0+P1). The bulk is UI
|
||||
// that had to grow: export/import row detail per entity kind, the category
|
||||
// IconPicker, the feedback modal, cross-bucket search, collapsible tag pools,
|
||||
// and finally `collectUpstreamProducers` + the var-chip producer card, which
|
||||
// tipped it 180 bytes over. Explicitly approved by the maintainer, who asked
|
||||
// for the budget to be raised as needed rather than features trimmed to fit.
|
||||
// Bumped 468 -> 490 KB on 2026-08-02 for the `@`/`$` autocomplete + sub-category
|
||||
// filter redesign. The popover rows carry structure now (icon, uuid, option /
|
||||
// axis / tag facts, and for `$` the producer line and override badge) instead
|
||||
// of one line of text, and the shared filter panel that follows adds the
|
||||
// axis-grouped palette with collapse + search, the live match count and the
|
||||
// zero-match / unknown-term states. Sized with headroom deliberately: the
|
||||
// previous bump left 179 bytes free, which meant every subsequent change had
|
||||
// to argue with the gate. Explicitly approved by the maintainer, who asked for
|
||||
// the budget to be raised as needed rather than features trimmed to fit.
|
||||
const TOTAL_LIMIT = 490 * 1024; // 490 KB
|
||||
|
||||
function gzipSize(path) {
|
||||
return gzipSync(readFileSync(path)).length;
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Post a release announcement to Discord.
|
||||
*
|
||||
* Derives the message from the release notes that already exist — there is
|
||||
* nothing extra to write. Run by `.github/workflows/discord-announce.yml` when
|
||||
* a release is published, and runnable by hand for the catch-up case.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/discord-announce.mjs --version v2.12.0 # dry run
|
||||
* node scripts/discord-announce.mjs --version v2.12.0 --post # → staff
|
||||
* node scripts/discord-announce.mjs --version v2.12.0 --post --channel public
|
||||
* node scripts/discord-announce.mjs --since v2.10.2 --post # catch-up
|
||||
* node scripts/discord-announce.mjs --notes-file docs/release-notes/next.md \
|
||||
* --version v2.12.0 # preview
|
||||
*
|
||||
* DRY RUN IS THE DEFAULT. `--post` is required to send anything, so previewing
|
||||
* an announcement can never accidentally publish one.
|
||||
*
|
||||
* Environment:
|
||||
* DISCORD_WEBHOOK_STAFF staff / pre-announcement channel (the default)
|
||||
* DISCORD_WEBHOOK_PUBLIC public announcement channel (--channel public only)
|
||||
* DISCORD_WEBHOOK_URL legacy fallback for the staff webhook
|
||||
* DISCORD_ROLE_ID optional; pinged as <@&ID>, PUBLIC channel only
|
||||
* DISCORD_USERNAME optional; overrides the posting name
|
||||
* DISCORD_AVATAR_URL optional; overrides the posting avatar (raster only)
|
||||
* GITHUB_TOKEN optional; raises the API rate limit for --since
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
import { buildPayload, buildRollupPayload, normalizeRoleId } from "./lib/discord-notes.mjs";
|
||||
|
||||
const REPO = "DumiFlex/ComfyUI-Wildcard-Pipeline";
|
||||
|
||||
/**
|
||||
* Two channels, deliberately asymmetric.
|
||||
*
|
||||
* `staff` posts automatically on every release and carries a link to publish
|
||||
* the same message onward — it is the review step. `public` only ever runs
|
||||
* from a deliberate manual dispatch, so a release can never announce itself to
|
||||
* everyone without someone having read it first.
|
||||
*/
|
||||
const CHANNELS = {
|
||||
staff: ["DISCORD_WEBHOOK_STAFF", "DISCORD_WEBHOOK_URL"],
|
||||
public: ["DISCORD_WEBHOOK_PUBLIC"],
|
||||
};
|
||||
|
||||
function webhookFor(channel) {
|
||||
for (const name of CHANNELS[channel]) {
|
||||
if (process.env[name]) return { url: process.env[name], via: name };
|
||||
}
|
||||
return { url: null, via: CHANNELS[channel][0] };
|
||||
}
|
||||
|
||||
function arg(name, fallback = undefined) {
|
||||
const i = process.argv.indexOf(`--${name}`);
|
||||
if (i === -1) return fallback;
|
||||
const next = process.argv[i + 1];
|
||||
return next && !next.startsWith("--") ? next : true;
|
||||
}
|
||||
|
||||
function ghHeaders() {
|
||||
const h = { Accept: "application/vnd.github+json", "User-Agent": "wp-discord-announce" };
|
||||
if (process.env.GITHUB_TOKEN) h.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`;
|
||||
return h;
|
||||
}
|
||||
|
||||
async function fetchRelease(tag) {
|
||||
const url = tag
|
||||
? `https://api.github.com/repos/${REPO}/releases/tags/${tag}`
|
||||
: `https://api.github.com/repos/${REPO}/releases/latest`;
|
||||
const res = await fetch(url, { headers: ghHeaders() });
|
||||
if (!res.ok) throw new Error(`GitHub ${res.status} fetching ${tag ?? "latest"}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/** Releases newer than `sinceTag`, newest first. Drafts and prereleases skipped. */
|
||||
async function fetchReleasesSince(sinceTag) {
|
||||
const res = await fetch(`https://api.github.com/repos/${REPO}/releases?per_page=100`, {
|
||||
headers: ghHeaders(),
|
||||
});
|
||||
if (!res.ok) throw new Error(`GitHub ${res.status} listing releases`);
|
||||
const all = (await res.json()).filter((r) => !r.draft && !r.prerelease);
|
||||
const idx = all.findIndex((r) => r.tag_name === sinceTag);
|
||||
if (idx === -1) throw new Error(`No release tagged ${sinceTag}`);
|
||||
return all.slice(0, idx);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const post = arg("post", false) === true;
|
||||
const channel = arg("channel", "staff");
|
||||
if (channel !== "staff" && channel !== "public") {
|
||||
console.error(`Unknown --channel "${channel}". Use staff or public.`);
|
||||
process.exit(1);
|
||||
}
|
||||
// Belt to the workflow's braces. The workflow only passes `--channel public`
|
||||
// on a manual dispatch, but a release event reaching this line with public
|
||||
// selected would announce to everyone with nobody having read it.
|
||||
if (channel === "public" && process.env.GITHUB_EVENT_NAME === "release") {
|
||||
console.error("Refusing to post to the public channel from a release event.");
|
||||
process.exit(1);
|
||||
}
|
||||
// Only the public post pings. A role ping in the staff channel on every
|
||||
// release is noise in a room that already exists to watch releases.
|
||||
const rawRole = channel === "public" ? process.env.DISCORD_ROLE_ID : undefined;
|
||||
const roleId = normalizeRoleId(rawRole);
|
||||
// `buildPayload` drops a malformed id either way, but silence would leave
|
||||
// someone wondering why the ping never fired.
|
||||
if (rawRole && rawRole.trim() && !roleId) {
|
||||
console.warn(
|
||||
`DISCORD_ROLE_ID is not a valid role id (${JSON.stringify(rawRole)}) — posting without a ping.`,
|
||||
);
|
||||
}
|
||||
// Undefined falls through to the defaults in discord-notes.mjs — an empty
|
||||
// env var must not blank the identity and hand the post back to the
|
||||
// webhook's own name.
|
||||
const username = process.env.DISCORD_USERNAME || undefined;
|
||||
const avatarUrl = process.env.DISCORD_AVATAR_URL || undefined;
|
||||
const since = arg("since");
|
||||
const notesFile = arg("notes-file");
|
||||
let version = arg("version");
|
||||
|
||||
let payload;
|
||||
|
||||
if (typeof since === "string") {
|
||||
const releases = await fetchReleasesSince(since);
|
||||
if (!releases.length) {
|
||||
console.error(`Nothing published after ${since} — nothing to announce.`);
|
||||
process.exit(0);
|
||||
}
|
||||
payload = buildRollupPayload({
|
||||
releases: releases.map((r) => ({ version: r.tag_name, body: r.body ?? "" })),
|
||||
sinceVersion: since,
|
||||
releaseUrl: releases[0].html_url,
|
||||
roleId,
|
||||
username,
|
||||
avatarUrl,
|
||||
channel,
|
||||
});
|
||||
} else if (typeof notesFile === "string") {
|
||||
// Local preview against unreleased notes. No network, so the compare link
|
||||
// is unknown and simply omitted.
|
||||
payload = buildPayload({
|
||||
version: version || "(unreleased)",
|
||||
body: readFileSync(notesFile, "utf8"),
|
||||
roleId,
|
||||
username,
|
||||
avatarUrl,
|
||||
channel,
|
||||
});
|
||||
} else {
|
||||
const rel = await fetchRelease(typeof version === "string" ? version : undefined);
|
||||
version = rel.tag_name;
|
||||
payload = buildPayload({
|
||||
version,
|
||||
body: rel.body ?? "",
|
||||
releaseUrl: rel.html_url,
|
||||
roleId,
|
||||
username,
|
||||
avatarUrl,
|
||||
channel,
|
||||
});
|
||||
}
|
||||
|
||||
if (!post) {
|
||||
console.log("--- DRY RUN (pass --post to send) ---\n");
|
||||
// Identity is part of what a preview is for: it is the thing that was
|
||||
// wrong on the first real post, and it is invisible in the embed body.
|
||||
console.log(`channel: ${channel}`);
|
||||
console.log(`posting as: ${payload.username}`);
|
||||
console.log(`avatar: ${payload.avatar_url}`);
|
||||
console.log("");
|
||||
console.log(payload.embeds[0].title);
|
||||
console.log("-".repeat(60));
|
||||
console.log(payload.embeds[0].description);
|
||||
console.log("-".repeat(60));
|
||||
console.log(`${payload.embeds[0].description.length} / 4096 chars`);
|
||||
return;
|
||||
}
|
||||
|
||||
const { url: webhook, via } = webhookFor(channel);
|
||||
if (!webhook) {
|
||||
console.error(`${via} is not set — refusing to post to the ${channel} channel.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const res = await fetch(`${webhook}?wait=true`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
console.error(`Discord ${res.status}: ${await res.text()}`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`Announced ${payload.embeds[0].title} → ${channel}`);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* Release notes → Discord message.
|
||||
*
|
||||
* The announcement is DERIVED, never authored. `docs/release-notes/next.md` is
|
||||
* already written by hand for every release and already is the GitHub release
|
||||
* body — so the only reason a Discord post was a separate chore is that nothing
|
||||
* transformed one into the other. Nothing here asks for new prose.
|
||||
*
|
||||
* Discord is not a markdown renderer in the way GitHub is, and the gaps are
|
||||
* specific rather than general:
|
||||
*
|
||||
* - Masked links `[text](url)` render ONLY inside an embed. In plain message
|
||||
* content they show as literal brackets, which is why the notes go in an
|
||||
* embed and the message content stays a bare ping.
|
||||
* - There are no tables. A pipe table degrades into unreadable pipes.
|
||||
* - `<details>` is HTML; it shows as raw tags.
|
||||
* - Embed description caps at 4096 characters, and the whole payload at 6000.
|
||||
*/
|
||||
|
||||
/** Everything below this marker is the long tail; the SPA modal cuts here too. */
|
||||
const MODAL_CUT = /<!--\s*\/modal\s*-->/i;
|
||||
|
||||
/** Discord's hard cap on a single embed description. */
|
||||
export const EMBED_DESCRIPTION_LIMIT = 4096;
|
||||
|
||||
/** Accent purple, matching `--wp-accent-500` in the manager. */
|
||||
export const BRAND_COLOR = 0x8b5cf6;
|
||||
|
||||
/**
|
||||
* Who the post appears to be from.
|
||||
*
|
||||
* A webhook posts under whatever name and avatar it was created with — the
|
||||
* Discord default is a generic name like "Captain Hook" and a placeholder
|
||||
* image, which is what an announcement went out as. `username` and
|
||||
* `avatar_url` override that PER MESSAGE, so the identity lives here rather
|
||||
* than in a webhook's settings: it stays right if the webhook is ever rotated
|
||||
* or recreated, and it is the same in every channel the automation posts to.
|
||||
*/
|
||||
export const WEBHOOK_USERNAME = "Wildcard Pipeline";
|
||||
|
||||
/**
|
||||
* Discord fetches this server-side, so it has to be a public raster URL — an
|
||||
* SVG will not render, which rules out the repo's `favicon.svg`. Pinned to
|
||||
* `main` rather than a tag so replacing the logo does not need a code change.
|
||||
*/
|
||||
export const WEBHOOK_AVATAR_URL =
|
||||
"https://raw.githubusercontent.com/DumiFlex/ComfyUI-Wildcard-Pipeline/main/public/images/web-app-manifest-512x512.png";
|
||||
|
||||
/**
|
||||
* A role id we are willing to turn into a ping, or `undefined`.
|
||||
*
|
||||
* An unset secret was always safe, but a MALFORMED one was not: any truthy
|
||||
* string went straight into `<@&…>`, so a stray space produced a literal
|
||||
* `<@& >` at the top of the announcement and a pasted mention produced
|
||||
* `<@&<@&123>>`. Both render as visible junk in the most public message the
|
||||
* project sends.
|
||||
*
|
||||
* Accepts a bare snowflake or the `<@&123>` form, since "Copy ID" and copying
|
||||
* the mention text are equally easy mistakes to make. Anything else is
|
||||
* rejected rather than guessed at — a ping that silently does not happen is a
|
||||
* much smaller problem than a broken one that does.
|
||||
*/
|
||||
export function normalizeRoleId(raw) {
|
||||
if (typeof raw !== "string" && typeof raw !== "number") return undefined;
|
||||
const trimmed = String(raw).trim();
|
||||
if (!trimmed) return undefined;
|
||||
const unwrapped = trimmed.replace(/^<@&(\d+)>$/, "$1");
|
||||
// Discord snowflakes are 17-20 digits today; the range leaves room without
|
||||
// accepting arbitrary numbers.
|
||||
return /^\d{17,20}$/.test(unwrapped) ? unwrapped : undefined;
|
||||
}
|
||||
|
||||
/** Where the manual "publish to the public channel" run is started. */
|
||||
export const DISPATCH_URL =
|
||||
"https://github.com/DumiFlex/ComfyUI-Wildcard-Pipeline/actions/workflows/discord-announce.yml";
|
||||
|
||||
/**
|
||||
* Split a release body into the part worth announcing and what is left behind.
|
||||
*
|
||||
* The cut is the same one the in-app update dialog makes, for the same reason:
|
||||
* an announcement is an interruption and should stay short. The tail is not
|
||||
* discarded silently — `tailCount` lets the message say how much it is not
|
||||
* showing, so a big release does not read as a small one.
|
||||
*/
|
||||
export function splitBody(md) {
|
||||
const at = String(md ?? "").search(MODAL_CUT);
|
||||
if (at === -1) return { head: String(md ?? ""), tail: "", tailCount: 0 };
|
||||
const head = md.slice(0, at);
|
||||
// Count against comment-stripped text, NOT details-stripped text. The
|
||||
// "Also in this release" bullets live INSIDE the <details> block, so
|
||||
// stripping it first counts nothing real — while the authoring guidance in
|
||||
// the trailing HTML comment contains bullets of its own that must not be
|
||||
// counted. Getting this backwards reported a 26-change release as 3.
|
||||
const tail = stripComments(md.slice(at));
|
||||
const tailCount = (tail.match(/^\s*[-*]\s+\S/gm) ?? []).length;
|
||||
return { head, tail, tailCount };
|
||||
}
|
||||
|
||||
function stripDetails(md) {
|
||||
return md.replace(/<details[\s\S]*?<\/details>/gi, "");
|
||||
}
|
||||
|
||||
function stripComments(md) {
|
||||
return md.replace(/<!--[\s\S]*?-->/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop the header block the GitHub template prepends.
|
||||
*
|
||||
* It is a row of links to the wiki, Discord and the issue tracker. On Discord
|
||||
* the Discord link is noise, and the rest belong in the embed's own fields
|
||||
* rather than buried in the body.
|
||||
*/
|
||||
function stripTemplateHeader(md) {
|
||||
return md
|
||||
.replace(/^\s*##\s*🎉[^\n]*\n/, "")
|
||||
.replace(/^\s*(?:📖|💬|📦|🐛)[^\n]*\n/gm, "");
|
||||
}
|
||||
|
||||
/** Pipe tables have no Discord equivalent; each row becomes a bullet. */
|
||||
function tablesToBullets(md) {
|
||||
const lines = md.split("\n");
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
const isRow = /^\s*\|.*\|\s*$/.test(line);
|
||||
if (!isRow) { out.push(line); continue; }
|
||||
// Separator row (|---|---|) carries no content.
|
||||
if (/^\s*\|[\s:|-]+\|\s*$/.test(line)) continue;
|
||||
const cells = line.trim().slice(1, -1).split("|").map((c) => c.trim());
|
||||
if (!cells.some(Boolean)) continue;
|
||||
out.push(`- ${cells.filter(Boolean).join(" — ")}`);
|
||||
}
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Headings become bold lines.
|
||||
*
|
||||
* Discord does render `#`-style headings now, but at sizes chosen for chat
|
||||
* rather than for a dense embed — an `##` inside an embed is larger than the
|
||||
* embed title above it. Bold keeps the hierarchy legible without competing.
|
||||
*/
|
||||
function headingsToBold(md) {
|
||||
return md.replace(/^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$/gm, (_m, text) => `**${text.trim()}**`);
|
||||
}
|
||||
|
||||
/** Horizontal rules have no embed equivalent and read as stray dashes. */
|
||||
function stripRules(md) {
|
||||
return md.replace(/^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/gm, "");
|
||||
}
|
||||
|
||||
/** Collapse the blank lines the earlier passes leave behind. */
|
||||
function tidy(md) {
|
||||
return md.replace(/\n{3,}/g, "\n\n").replace(/[ \t]+$/gm, "").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Truncate at a bullet boundary rather than mid-sentence.
|
||||
*
|
||||
* A hard slice at 4096 can cut inside a link or a bold run, which Discord then
|
||||
* renders as broken markup — worse than saying less.
|
||||
*/
|
||||
export function clampToLimit(text, limit = EMBED_DESCRIPTION_LIMIT, suffix = "\n\n…") {
|
||||
if (text.length <= limit) return text;
|
||||
const room = limit - suffix.length;
|
||||
const slice = text.slice(0, room);
|
||||
const cut = Math.max(slice.lastIndexOf("\n- "), slice.lastIndexOf("\n\n"));
|
||||
return (cut > room * 0.5 ? slice.slice(0, cut) : slice).trimEnd() + suffix;
|
||||
}
|
||||
|
||||
/** Full markdown → Discord-embed markdown. */
|
||||
export function toDiscordMarkdown(md) {
|
||||
return tidy(
|
||||
stripRules(
|
||||
headingsToBold(
|
||||
tablesToBullets(
|
||||
stripTemplateHeader(stripComments(stripDetails(String(md ?? "")))),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the description for one release.
|
||||
*
|
||||
* `tailCount` is appended rather than dropped: a release whose highlights are
|
||||
* three bullets and whose tail is forty changes should not look like a quiet
|
||||
* week.
|
||||
*/
|
||||
export function buildDescription(body, { compareUrl } = {}) {
|
||||
const { head, tailCount } = splitBody(body);
|
||||
let out = toDiscordMarkdown(head);
|
||||
if (tailCount > 0) {
|
||||
const line = `*…plus ${tailCount} smaller change${tailCount === 1 ? "" : "s"}*`;
|
||||
out += `\n\n${compareUrl ? `[${line.slice(1, -1)}](${compareUrl})` : line}`;
|
||||
}
|
||||
return clampToLimit(out);
|
||||
}
|
||||
|
||||
/**
|
||||
* One release → a Discord webhook payload.
|
||||
*
|
||||
* `allowed_mentions` is always explicit. A webhook with no restriction will
|
||||
* happily resolve an `@everyone` that happened to appear in release notes, and
|
||||
* the notes are not written with that in mind.
|
||||
*/
|
||||
export function buildPayload({
|
||||
version,
|
||||
body,
|
||||
releaseUrl,
|
||||
compareUrl,
|
||||
roleId: rawRoleId,
|
||||
username = WEBHOOK_USERNAME,
|
||||
avatarUrl = WEBHOOK_AVATAR_URL,
|
||||
channel = "staff",
|
||||
installHint = 'ComfyUI Manager → search "Wildcard Pipeline" → Update → restart ComfyUI',
|
||||
}) {
|
||||
const description = buildDescription(body, { compareUrl });
|
||||
// Normalised HERE rather than at the call site so every caller — CLI,
|
||||
// roll-up, future ones — gets the same guarantee.
|
||||
const roleId = normalizeRoleId(rawRoleId);
|
||||
return {
|
||||
username,
|
||||
avatar_url: avatarUrl,
|
||||
content: roleId ? `<@&${roleId}>` : "",
|
||||
allowed_mentions: { parse: [], roles: roleId ? [roleId] : [] },
|
||||
embeds: [
|
||||
{
|
||||
title: `Wildcard Pipeline ${version}`,
|
||||
url: releaseUrl || undefined,
|
||||
description,
|
||||
color: BRAND_COLOR,
|
||||
fields: reviewFields(channel),
|
||||
footer: { text: installHint },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The staff copy carries its own publish button; the public copy does not.
|
||||
*
|
||||
* This is what makes the staff channel a review step rather than a duplicate
|
||||
* feed: the post you are reading is the post that will go out, and the link to
|
||||
* send it is attached to it. Without that, "go and publish it" is a separate
|
||||
* instruction living in someone's head.
|
||||
*
|
||||
* Returned as `undefined` for the public channel rather than an empty array —
|
||||
* Discord rejects `fields: []` on some client versions, and an empty field
|
||||
* block would render as dead space in the announcement everyone sees.
|
||||
*/
|
||||
function reviewFields(channel) {
|
||||
if (channel !== "staff") return undefined;
|
||||
return [
|
||||
{
|
||||
name: "Ready to go public?",
|
||||
value:
|
||||
`[Run the workflow](${DISPATCH_URL}) with **channel: public** and ` +
|
||||
"**dry_run: false** to post this to the announcement channel.",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Several releases → one catch-up payload.
|
||||
*
|
||||
* For the case that actually happens: announcements skipped for a few versions,
|
||||
* then one post covering the gap. Each release keeps its own heading so readers
|
||||
* can tell which version brought what, and the newest goes first because that is
|
||||
* the one people are deciding whether to install.
|
||||
*
|
||||
* `releases` is newest-first: `{ version, body }`.
|
||||
*/
|
||||
export function buildRollupPayload({
|
||||
releases, sinceVersion, releaseUrl, roleId, installHint, username, avatarUrl,
|
||||
channel = "staff",
|
||||
}) {
|
||||
const latest = releases[0];
|
||||
const sections = releases.map((r) => {
|
||||
const { head } = splitBody(r.body);
|
||||
const text = toDiscordMarkdown(head);
|
||||
return `**${r.version}**\n${text}`;
|
||||
});
|
||||
const joined = sections.join("\n\n");
|
||||
const base = buildPayload({
|
||||
version: latest?.version ?? "",
|
||||
body: "",
|
||||
releaseUrl,
|
||||
roleId,
|
||||
installHint,
|
||||
username,
|
||||
avatarUrl,
|
||||
channel,
|
||||
});
|
||||
base.embeds[0].title = sinceVersion
|
||||
? `Wildcard Pipeline ${latest?.version ?? ""} — everything since ${sinceVersion}`
|
||||
: `Wildcard Pipeline ${latest?.version ?? ""}`;
|
||||
base.embeds[0].description = clampToLimit(joined);
|
||||
return base;
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
DISPATCH_URL,
|
||||
normalizeRoleId,
|
||||
splitBody,
|
||||
toDiscordMarkdown,
|
||||
buildDescription,
|
||||
buildPayload,
|
||||
buildRollupPayload,
|
||||
clampToLimit,
|
||||
EMBED_DESCRIPTION_LIMIT,
|
||||
} from "./discord-notes.mjs";
|
||||
|
||||
/**
|
||||
* The announcement is derived from notes that already exist, so the risk is not
|
||||
* "does it write good copy" — it is "does it mangle copy that was already
|
||||
* fine". Most of these pin a Discord-specific rendering gap.
|
||||
*/
|
||||
|
||||
const REAL_SHAPE = `## 🎉 Wildcard Pipeline v2.11.0
|
||||
|
||||
📖 [Docs (wiki)](https://x/wiki) · 💬 [Discord](https://discord.gg/x) · 📦 [Install](https://x/q) · 🐛 [Issues](https://x/i)
|
||||
|
||||
### ✨ What's new
|
||||
|
||||
A correctness fix for held modules, plus tools for reconnecting workflow items.
|
||||
|
||||
- **Held modules stay held.** A module set to **Hold across run** could re-roll.
|
||||
- **Search by id.** Pasting an 8-character id now finds the item.
|
||||
|
||||
<!-- /modal -->
|
||||
|
||||
### Also in this release
|
||||
|
||||
- Wire collapse survives a live renderer switch
|
||||
- Modal keystrokes no longer escape
|
||||
|
||||
---
|
||||
|
||||
**Full changelog:** [v2.10.2…v2.11.0](https://x/compare)
|
||||
`;
|
||||
|
||||
describe("splitBody", () => {
|
||||
it("cuts at the modal marker and counts what is left behind", () => {
|
||||
const { head, tailCount } = splitBody(REAL_SHAPE);
|
||||
expect(head).toContain("Held modules stay held");
|
||||
expect(head).not.toContain("Also in this release");
|
||||
expect(tailCount).toBe(2);
|
||||
});
|
||||
|
||||
it("treats a body with no marker as all highlights", () => {
|
||||
const { head, tailCount } = splitBody("- one\n- two");
|
||||
expect(head).toBe("- one\n- two");
|
||||
expect(tailCount).toBe(0);
|
||||
});
|
||||
|
||||
it("survives an empty or missing body", () => {
|
||||
expect(splitBody("").head).toBe("");
|
||||
expect(splitBody(undefined).head).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toDiscordMarkdown", () => {
|
||||
it("drops the GitHub template header — the Discord link is noise on Discord", () => {
|
||||
const out = toDiscordMarkdown(REAL_SHAPE);
|
||||
expect(out).not.toContain("🎉 Wildcard Pipeline");
|
||||
expect(out).not.toContain("discord.gg");
|
||||
expect(out).not.toContain("Docs (wiki)");
|
||||
});
|
||||
|
||||
it("keeps masked links, which DO render inside an embed", () => {
|
||||
expect(toDiscordMarkdown("see [the docs](https://x/d)")).toContain("[the docs](https://x/d)");
|
||||
});
|
||||
|
||||
it("turns headings into bold — an embed h2 outsizes the embed title", () => {
|
||||
const out = toDiscordMarkdown("### What's new\nbody");
|
||||
expect(out).toContain("**What's new**");
|
||||
expect(out).not.toMatch(/^#/m);
|
||||
});
|
||||
|
||||
it("converts tables to bullets, since Discord has none", () => {
|
||||
const out = toDiscordMarkdown("| Item | Result |\n| --- | --- |\n| #29 | shipped |");
|
||||
expect(out).toContain("- Item — Result");
|
||||
expect(out).toContain("- #29 — shipped");
|
||||
expect(out).not.toContain("|");
|
||||
});
|
||||
|
||||
it("strips <details>, which renders as raw tags", () => {
|
||||
const out = toDiscordMarkdown("keep\n<details><summary>x</summary>\n- hidden\n</details>");
|
||||
expect(out).toContain("keep");
|
||||
expect(out).not.toContain("hidden");
|
||||
expect(out).not.toContain("<details>");
|
||||
});
|
||||
|
||||
it("strips HTML comments and horizontal rules", () => {
|
||||
const out = toDiscordMarkdown("a\n\n<!-- note -->\n\n---\n\nb");
|
||||
expect(out).not.toContain("note");
|
||||
expect(out).not.toMatch(/^-{3,}$/m);
|
||||
expect(out).toContain("a");
|
||||
expect(out).toContain("b");
|
||||
});
|
||||
|
||||
it("leaves bold, italics and bullets alone", () => {
|
||||
const out = toDiscordMarkdown("- **bold** and *italic* and `code`");
|
||||
expect(out).toBe("- **bold** and *italic* and `code`");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildDescription", () => {
|
||||
// A three-bullet highlights section over a forty-change release should not
|
||||
// read as a quiet week.
|
||||
it("says how much it is not showing", () => {
|
||||
const out = buildDescription(REAL_SHAPE);
|
||||
expect(out).toMatch(/plus 2 smaller changes/);
|
||||
});
|
||||
|
||||
it("links the tail to the compare view when there is one", () => {
|
||||
const out = buildDescription(REAL_SHAPE, { compareUrl: "https://x/compare" });
|
||||
expect(out).toContain("](https://x/compare)");
|
||||
});
|
||||
|
||||
// The "Also in this release" bullets live INSIDE a <details> block, and the
|
||||
// file ends with an authoring comment that contains bullets of its own.
|
||||
// Stripping details before counting reported a real 26-change release as 3.
|
||||
it("counts the bullets inside <details>, and ignores those in comments", () => {
|
||||
const body = [
|
||||
"- highlight",
|
||||
"<!-- /modal -->",
|
||||
"<details><summary>Also in this release — 3 smaller changes</summary>",
|
||||
"- one",
|
||||
"- two",
|
||||
"- three",
|
||||
"</details>",
|
||||
"<!--",
|
||||
" - not a change, this is authoring guidance",
|
||||
" - nor is this",
|
||||
"-->",
|
||||
].join("\n");
|
||||
expect(splitBody(body).tailCount).toBe(3);
|
||||
expect(buildDescription(body)).toMatch(/plus 3 smaller changes/);
|
||||
});
|
||||
|
||||
it("says nothing about a tail that does not exist", () => {
|
||||
expect(buildDescription("- only this")).not.toMatch(/smaller change/);
|
||||
});
|
||||
|
||||
it("uses the singular for one", () => {
|
||||
expect(buildDescription("- a\n<!-- /modal -->\n- b")).toMatch(/1 smaller change\b/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clampToLimit", () => {
|
||||
it("leaves anything under the cap untouched", () => {
|
||||
expect(clampToLimit("short")).toBe("short");
|
||||
});
|
||||
|
||||
// A hard slice can land inside a link or a bold run, which Discord then
|
||||
// renders as broken markup — worse than saying less.
|
||||
it("cuts at a bullet boundary, not mid-markup", () => {
|
||||
const body = Array.from({ length: 400 }, (_, i) => `- item ${i} with some text`).join("\n");
|
||||
const out = clampToLimit(body);
|
||||
expect(out.length).toBeLessThanOrEqual(EMBED_DESCRIPTION_LIMIT);
|
||||
expect(out.endsWith("…")).toBe(true);
|
||||
expect(out.split("\n").at(-3)).toMatch(/^- item \d+ with some text$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPayload", () => {
|
||||
it("puts the notes in an embed, because masked links need one", () => {
|
||||
const p = buildPayload({ version: "v2.12.0", body: REAL_SHAPE, releaseUrl: "https://x/r" });
|
||||
expect(p.embeds).toHaveLength(1);
|
||||
expect(p.embeds[0].title).toBe("Wildcard Pipeline v2.12.0");
|
||||
expect(p.embeds[0].url).toBe("https://x/r");
|
||||
expect(p.embeds[0].footer.text).toMatch(/ComfyUI Manager/);
|
||||
});
|
||||
|
||||
// Release notes are not written with @everyone in mind, and a webhook will
|
||||
// happily resolve one that slipped in.
|
||||
it("never lets the notes mention anyone by accident", () => {
|
||||
const p = buildPayload({ version: "v1", body: "ping @everyone please" });
|
||||
expect(p.allowed_mentions.parse).toEqual([]);
|
||||
expect(p.allowed_mentions.roles).toEqual([]);
|
||||
});
|
||||
|
||||
/**
|
||||
* An unset secret was always safe. A MALFORMED one was not: any truthy string
|
||||
* went straight into `<@&…>`, so a stray space produced a literal `<@& >`
|
||||
* at the top of the most public message the project sends.
|
||||
*/
|
||||
describe("role ping", () => {
|
||||
const content = (roleId) => buildPayload({ version: "v1", body: "x", roleId }).content;
|
||||
|
||||
it("stays silent for every flavour of absent", () => {
|
||||
expect(content(undefined)).toBe("");
|
||||
expect(content(null)).toBe("");
|
||||
expect(content("")).toBe("");
|
||||
expect(content(" ")).toBe("");
|
||||
});
|
||||
|
||||
it("refuses anything that is not a snowflake, rather than guessing", () => {
|
||||
expect(content("not-an-id")).toBe("");
|
||||
expect(content("12345")).toBe(""); // too short
|
||||
expect(content("1234567890123456789012")).toBe(""); // too long
|
||||
expect(content("123abc456def78901")).toBe("");
|
||||
});
|
||||
|
||||
it("never emits a half-formed mention", () => {
|
||||
for (const bad of [" ", "not-an-id", "<@&>", "@everyone"]) {
|
||||
expect(content(bad)).not.toContain("<@&");
|
||||
}
|
||||
});
|
||||
|
||||
// "Copy ID" and copying the mention text are equally easy mistakes.
|
||||
it("accepts a pasted mention as well as a bare id", () => {
|
||||
expect(content("123456789012345678")).toBe("<@&123456789012345678>");
|
||||
expect(content("<@&123456789012345678>")).toBe("<@&123456789012345678>");
|
||||
expect(content(" 123456789012345678 ")).toBe("<@&123456789012345678>");
|
||||
});
|
||||
|
||||
it("keeps allowed_mentions in step with the content", () => {
|
||||
const bad = buildPayload({ version: "v1", body: "x", roleId: "junk" });
|
||||
expect(bad.allowed_mentions.roles).toEqual([]);
|
||||
const good = buildPayload({ version: "v1", body: "x", roleId: "123456789012345678" });
|
||||
expect(good.allowed_mentions.roles).toEqual(["123456789012345678"]);
|
||||
expect(good.allowed_mentions.parse).toEqual([]);
|
||||
});
|
||||
|
||||
it("normalizeRoleId is the single decision point", () => {
|
||||
expect(normalizeRoleId("<@&123456789012345678>")).toBe("123456789012345678");
|
||||
expect(normalizeRoleId("nope")).toBeUndefined();
|
||||
expect(normalizeRoleId(undefined)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
it("pings only the configured role, and only when configured", () => {
|
||||
expect(buildPayload({ version: "v1", body: "x" }).content).toBe("");
|
||||
const p = buildPayload({ version: "v1", body: "x", roleId: "123456789012345678" });
|
||||
expect(p.content).toBe("<@&123456789012345678>");
|
||||
expect(p.allowed_mentions.roles).toEqual(["123456789012345678"]);
|
||||
});
|
||||
|
||||
// A webhook posts under whatever name and avatar it was created with —
|
||||
// Discord's default is a generic name ("Captain Hook") and a placeholder
|
||||
// image, which is exactly what v2.12.0 went out as.
|
||||
it("posts under the project's own name and avatar, not the webhook's", () => {
|
||||
const p = buildPayload({ version: "v1", body: "x" });
|
||||
expect(p.username).toBe("Wildcard Pipeline");
|
||||
expect(p.avatar_url).toMatch(/^https:\/\/.+\.png$/);
|
||||
});
|
||||
|
||||
it("uses a raster avatar — Discord will not render an SVG", () => {
|
||||
expect(buildPayload({ version: "v1", body: "x" }).avatar_url).not.toMatch(/\.svg$/i);
|
||||
});
|
||||
|
||||
it("lets a caller override the identity", () => {
|
||||
const p = buildPayload({
|
||||
version: "v1", body: "x", username: "WP Staff", avatarUrl: "https://x/a.png",
|
||||
});
|
||||
expect(p.username).toBe("WP Staff");
|
||||
expect(p.avatar_url).toBe("https://x/a.png");
|
||||
});
|
||||
|
||||
/**
|
||||
* Two channels, deliberately asymmetric. The staff copy is the review step,
|
||||
* so it carries the button that publishes it onward; the public copy is the
|
||||
* announcement itself and must not tell readers how to re-send it.
|
||||
*/
|
||||
it("gives the staff copy a publish link, so review and button are one thing", () => {
|
||||
const p = buildPayload({ version: "v1", body: "x", channel: "staff" });
|
||||
const field = p.embeds[0].fields[0];
|
||||
expect(field.value).toContain(DISPATCH_URL);
|
||||
expect(field.value).toMatch(/channel.*public/i);
|
||||
});
|
||||
|
||||
it("defaults to the staff copy — the safe one to send by accident", () => {
|
||||
expect(buildPayload({ version: "v1", body: "x" }).embeds[0].fields).toBeTruthy();
|
||||
});
|
||||
|
||||
it("leaves the public copy without the publish link", () => {
|
||||
const p = buildPayload({ version: "v1", body: "x", channel: "public" });
|
||||
// `undefined`, not `[]` — an empty field block renders as dead space.
|
||||
expect(p.embeds[0].fields).toBeUndefined();
|
||||
});
|
||||
|
||||
it("stays inside the embed description cap", () => {
|
||||
const huge = Array.from({ length: 900 }, (_, i) => `- change ${i}`).join("\n");
|
||||
const p = buildPayload({ version: "v1", body: huge });
|
||||
expect(p.embeds[0].description.length).toBeLessThanOrEqual(EMBED_DESCRIPTION_LIMIT);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildRollupPayload", () => {
|
||||
// The case that actually happens: several versions skipped, then one post.
|
||||
it("labels each version so readers can tell what came from where", () => {
|
||||
const p = buildRollupPayload({
|
||||
releases: [
|
||||
{ version: "v2.12.0", body: "- newest thing" },
|
||||
{ version: "v2.11.0", body: "- older thing" },
|
||||
],
|
||||
sinceVersion: "v2.10.2",
|
||||
releaseUrl: "https://x/r",
|
||||
});
|
||||
expect(p.embeds[0].title).toBe("Wildcard Pipeline v2.12.0 — everything since v2.10.2");
|
||||
expect(p.embeds[0].description).toContain("**v2.12.0**");
|
||||
expect(p.embeds[0].description).toContain("**v2.11.0**");
|
||||
});
|
||||
|
||||
it("carries the channel through a roll-up", () => {
|
||||
const staff = buildRollupPayload({
|
||||
releases: [{ version: "v2.12.0", body: "- x" }], sinceVersion: "v2.11.0", channel: "staff",
|
||||
});
|
||||
const pub = buildRollupPayload({
|
||||
releases: [{ version: "v2.12.0", body: "- x" }], sinceVersion: "v2.11.0", channel: "public",
|
||||
});
|
||||
expect(staff.embeds[0].fields).toBeTruthy();
|
||||
expect(pub.embeds[0].fields).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps the identity on a roll-up too", () => {
|
||||
const p = buildRollupPayload({
|
||||
releases: [{ version: "v2.12.0", body: "- x" }],
|
||||
sinceVersion: "v2.10.2",
|
||||
});
|
||||
expect(p.username).toBe("Wildcard Pipeline");
|
||||
expect(p.avatar_url).toMatch(/\.png$/);
|
||||
});
|
||||
|
||||
it("leads with the newest, which is what people decide to install", () => {
|
||||
const p = buildRollupPayload({
|
||||
releases: [
|
||||
{ version: "v2.12.0", body: "- newest" },
|
||||
{ version: "v2.11.0", body: "- older" },
|
||||
],
|
||||
sinceVersion: "v2.10.2",
|
||||
});
|
||||
const d = p.embeds[0].description;
|
||||
expect(d.indexOf("**v2.12.0**")).toBeLessThan(d.indexOf("**v2.11.0**"));
|
||||
});
|
||||
|
||||
it("drops each release's own tail so a roll-up does not become a changelog", () => {
|
||||
const p = buildRollupPayload({
|
||||
releases: [{ version: "v2.12.0", body: "- kept\n<!-- /modal -->\n- dropped" }],
|
||||
sinceVersion: "v2.11.0",
|
||||
});
|
||||
expect(p.embeds[0].description).toContain("kept");
|
||||
expect(p.embeds[0].description).not.toContain("dropped");
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,7 @@
|
||||
* - web/ (built manager SPA)
|
||||
* - public/ (favicons + doc images referenced by the SPA)
|
||||
* - docs/help/ (per-node help markdown the canvas reads)
|
||||
* - locales/ (node display names + settings labels ComfyUI reads)
|
||||
* - README.md
|
||||
* - LICENSE
|
||||
*
|
||||
@@ -59,8 +60,55 @@ const SHIP_PATHS = [
|
||||
"web",
|
||||
"public",
|
||||
"docs/help",
|
||||
// ComfyUI reads `custom_nodes/<pack>/locales/<lang>/` for node display
|
||||
// names, descriptions and settings labels (app/custom_node_manager.py).
|
||||
// The registry archive picks this up automatically because it ships
|
||||
// everything git-tracked that `.comfyignore` doesn't exclude; this list is
|
||||
// hand-maintained, so it did not. The two artifacts silently disagreed —
|
||||
// see DEV_ONLY below for the guard that now stops that recurring.
|
||||
"locales",
|
||||
];
|
||||
|
||||
/**
|
||||
* Top-level tracked entries that deliberately do NOT ship.
|
||||
*
|
||||
* Exists to make the ship list total: every top-level path in git is either
|
||||
* shipped or listed here, and `assertShipListIsTotal` fails the release if a
|
||||
* new one appears in neither. Without it, adding a runtime directory and
|
||||
* forgetting this file produces a zip that installs and silently misbehaves —
|
||||
* which is exactly how `locales/` went missing.
|
||||
*/
|
||||
const DEV_ONLY = new Set([
|
||||
".comfyignore", ".gitattributes", ".github", ".gitignore", ".husky", ".npmrc",
|
||||
".releaserc.js", "CHANGELOG.md", "CLAUDE.md", "config", "conftest.py",
|
||||
"eslint.config.js", "package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml",
|
||||
"scripts", "src", "tests", "tsconfig.json", "tsconfig.node.json",
|
||||
"vite.config.mts", "vitest.config.ts",
|
||||
]);
|
||||
|
||||
function assertShipListIsTotal() {
|
||||
const ls = spawnSync("git", ["ls-files"], { cwd: root, encoding: "utf8" });
|
||||
if (ls.status !== 0) {
|
||||
console.warn("pack-release: `git ls-files` unavailable — skipping ship-list completeness check");
|
||||
return;
|
||||
}
|
||||
// A ship path may name a subtree (`docs/help`); its top-level segment is
|
||||
// what makes the parent directory "accounted for".
|
||||
const covered = new Set(SHIP_PATHS.map((p) => p.split("/")[0]));
|
||||
const tracked = new Set(
|
||||
ls.stdout.split("\n").map((line) => line.trim().split("/")[0]).filter(Boolean),
|
||||
);
|
||||
const unaccounted = [...tracked].filter((e) => !covered.has(e) && !DEV_ONLY.has(e)).sort();
|
||||
if (unaccounted.length > 0) {
|
||||
console.error("pack-release: top-level paths in git that are neither shipped nor dev-only:");
|
||||
for (const p of unaccounted) console.error(` - ${p}`);
|
||||
console.error("Add each to SHIP_PATHS (ships to users) or DEV_ONLY (stays in the repo).");
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
assertShipListIsTotal();
|
||||
|
||||
// Sanity: every path must exist before zipping. If `js/` or `web/`
|
||||
// is missing the release would ship a broken bundle — catch here so the
|
||||
// release workflow fails fast rather than uploading a half-baked zip.
|
||||
@@ -93,6 +141,13 @@ const args = [
|
||||
];
|
||||
|
||||
const result = spawnSync("zip", args, { stdio: "inherit", cwd: root });
|
||||
if (result.error?.code === "ENOENT") {
|
||||
// Windows has no `zip` by default, so a maintainer running this locally
|
||||
// otherwise gets a bare "exited with status null".
|
||||
console.error("pack-release: the `zip` CLI was not found on PATH.");
|
||||
console.error("The release workflow runs on ubuntu-latest where it is always present.");
|
||||
process.exit(1);
|
||||
}
|
||||
if (result.status !== 0) {
|
||||
console.error(`pack-release: zip exited with status ${result.status}`);
|
||||
process.exit(result.status ?? 1);
|
||||
|
||||
@@ -260,7 +260,7 @@ async function submit(mode: "update" | "new") {
|
||||
font-family: inherit;
|
||||
}
|
||||
.wp-stm-input:focus { outline: 1px solid var(--wp-accent-500, var(--wp-accent)); }
|
||||
.wp-stm-input--multi { resize: vertical; min-height: 46px; }
|
||||
.wp-stm-input--multi { resize: vertical; overscroll-behavior: contain; min-height: 46px; }
|
||||
.wp-stm-select { cursor: pointer; }
|
||||
.wp-stm-preview {
|
||||
margin: 0;
|
||||
|
||||
@@ -174,7 +174,7 @@ function onCancel(): void {
|
||||
padding: 8px 10px;
|
||||
font-family: var(--wp-font-mono, ui-monospace, "JetBrains Mono", monospace);
|
||||
font-size: 12px;
|
||||
resize: vertical;
|
||||
resize: vertical; overscroll-behavior: contain;
|
||||
box-sizing: border-box;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import ContextLoopWidget from "./ContextLoopWidget.vue";
|
||||
import SeedListModal from "../shared/SeedListModal.vue";
|
||||
import { emptyContextLoopConfig } from "./types";
|
||||
import { currentFrame } from "./frame-cursor";
|
||||
import { deriveLoopSeeds } from "../shared/seed-derive";
|
||||
|
||||
describe("ContextLoopWidget", () => {
|
||||
it("renders defaults — hash chip active, both switches off, internal toggles on", () => {
|
||||
@@ -148,3 +149,158 @@ describe("ContextLoopWidget frame selector", () => {
|
||||
expect(currentFrame.value).toBe(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ContextLoopWidget bypass (#13)", () => {
|
||||
it("shows an N-bypassed badge on the seeds button", () => {
|
||||
const cfg = { ...emptyContextLoopConfig(), bypass_frames: [1, 3] };
|
||||
const w = mount(ContextLoopWidget, { props: { modelValue: cfg, count: 5 } });
|
||||
expect(w.find('[data-test="loop-seeds-bypass-badge"]').text()).toMatch(/2 bypassed/i);
|
||||
});
|
||||
it("marks bypassed edit-frame chips with a dashed-border class", () => {
|
||||
const cfg = { ...emptyContextLoopConfig(), bypass_frames: [1, 3] };
|
||||
const w = mount(ContextLoopWidget, { props: { modelValue: cfg, count: 5 } });
|
||||
// frame index 1 -> chip #2 (data-test loop-frame-2)
|
||||
expect(w.find('[data-test="loop-frame-2"]').classes()).toContain("wp-fchips__chip--bypassed");
|
||||
expect(w.find('[data-test="loop-frame-4"]').classes()).toContain("wp-fchips__chip--bypassed");
|
||||
expect(w.find('[data-test="loop-frame-1"]').classes()).not.toContain("wp-fchips__chip--bypassed");
|
||||
});
|
||||
|
||||
it("has no bypass badge when none are bypassed", () => {
|
||||
const w = mount(ContextLoopWidget, { props: { modelValue: emptyContextLoopConfig(), count: 5 } });
|
||||
expect(w.find('[data-test="loop-seeds-bypass-badge"]').exists()).toBe(false);
|
||||
});
|
||||
it("writes bypass changes from the modal back into the config", async () => {
|
||||
const cfg = { ...emptyContextLoopConfig(), bypass_frames: [] };
|
||||
const w = mount(ContextLoopWidget, { props: { modelValue: cfg, count: 4 } });
|
||||
await w.get('[data-test="loop-seeds-btn"]').trigger("click");
|
||||
w.findComponent(SeedListModal).vm.$emit("update:bypassFrames", [2]);
|
||||
const calls = w.emitted("update:modelValue")!;
|
||||
const last = calls[calls.length - 1][0] as typeof cfg;
|
||||
expect(last.bypass_frames).toEqual([2]);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Modifier-click on the frame chips. Both states were already visible here but
|
||||
* only changeable inside the modal, two clicks away and covering the node you
|
||||
* were reading.
|
||||
*/
|
||||
describe("ContextLoopWidget frame chip modifier-clicks", () => {
|
||||
beforeEach(() => { currentFrame.value = null; });
|
||||
|
||||
function fw(cfgPatch: Partial<ReturnType<typeof emptyContextLoopConfig>> = {}, count = 4) {
|
||||
return mount(ContextLoopWidget, {
|
||||
props: { modelValue: { ...emptyContextLoopConfig(), ...cfgPatch }, count, baseSeed: 42 },
|
||||
});
|
||||
}
|
||||
const lastEmit = (w: ReturnType<typeof fw>) => {
|
||||
const calls = w.emitted("update:modelValue");
|
||||
return calls?.[calls.length - 1]?.[0] as ReturnType<typeof emptyContextLoopConfig>;
|
||||
};
|
||||
|
||||
it("shift-click locks the frame to the seed it would have used", async () => {
|
||||
const w = fw();
|
||||
await w.find('[data-test="loop-frame-3"]').trigger("click", { shiftKey: true });
|
||||
const next = lastEmit(w);
|
||||
// Frame index 2, and the value must be a real derived seed — not a
|
||||
// placeholder, or the lock would silently change the output it froze.
|
||||
expect(Object.keys(next.seed_locks!)).toEqual(["2"]);
|
||||
expect(Number.isInteger(next.seed_locks!["2"])).toBe(true);
|
||||
});
|
||||
|
||||
it("shift-click on a locked frame unlocks it", async () => {
|
||||
const w = fw({ seed_locks: { "2": 777 } });
|
||||
await w.find('[data-test="loop-frame-3"]').trigger("click", { shiftKey: true });
|
||||
expect(lastEmit(w).seed_locks).toEqual({});
|
||||
});
|
||||
|
||||
it("the chip-lock value matches what the modal's Lock all would write", async () => {
|
||||
const w = fw();
|
||||
await w.find('[data-test="loop-frame-2"]').trigger("click", { shiftKey: true });
|
||||
const chipValue = lastEmit(w).seed_locks!["1"];
|
||||
expect(chipValue).toBe(deriveLoopSeeds(42, 4, "hash_index")[1]);
|
||||
});
|
||||
|
||||
it("alt-click bypasses a frame, and again re-enables it", async () => {
|
||||
const w = fw();
|
||||
await w.find('[data-test="loop-frame-2"]').trigger("click", { altKey: true });
|
||||
expect(lastEmit(w).bypass_frames).toEqual([1]);
|
||||
|
||||
const w2 = fw({ bypass_frames: [1] });
|
||||
await w2.find('[data-test="loop-frame-2"]').trigger("click", { altKey: true });
|
||||
expect(lastEmit(w2).bypass_frames).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps bypassed indices sorted so the config does not churn", async () => {
|
||||
const w = fw({ bypass_frames: [3] });
|
||||
await w.find('[data-test="loop-frame-2"]').trigger("click", { altKey: true });
|
||||
expect(lastEmit(w).bypass_frames).toEqual([1, 3]);
|
||||
});
|
||||
|
||||
it("refuses to bypass the last running frame — a loop needs one", async () => {
|
||||
const w = fw({ bypass_frames: [0, 1, 2] }, 4);
|
||||
await w.find('[data-test="loop-frame-4"]').trigger("click", { altKey: true });
|
||||
expect(w.emitted("update:modelValue")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("still lets the last running frame be re-enabled and locked", async () => {
|
||||
const w = fw({ bypass_frames: [0, 1, 2] }, 4);
|
||||
await w.find('[data-test="loop-frame-1"]').trigger("click", { altKey: true });
|
||||
expect(lastEmit(w).bypass_frames).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
// Moving the editor to another frame as a side effect of locking one is the
|
||||
// kind of surprise that makes people stop trusting a shortcut.
|
||||
it("a modifier click never also moves the edit cursor", async () => {
|
||||
const w = fw();
|
||||
await w.find('[data-test="loop-frame-3"]').trigger("click", { shiftKey: true });
|
||||
expect(currentFrame.value).toBe(null);
|
||||
await w.find('[data-test="loop-frame-2"]').trigger("click", { altKey: true });
|
||||
expect(currentFrame.value).toBe(null);
|
||||
});
|
||||
|
||||
it("a plain click still just selects the frame", async () => {
|
||||
const w = fw();
|
||||
await w.find('[data-test="loop-frame-3"]').trigger("click");
|
||||
expect(currentFrame.value).toBe(2);
|
||||
expect(w.emitted("update:modelValue")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("base takes no modifiers — it has no seed and nothing to bypass", async () => {
|
||||
const w = fw();
|
||||
await w.find('[data-test="loop-frame-base"]').trigger("click", { shiftKey: true });
|
||||
await w.find('[data-test="loop-frame-base"]').trigger("click", { altKey: true });
|
||||
expect(w.emitted("update:modelValue")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("marks locked chips so the state is readable without the modal", () => {
|
||||
const w = fw({ seed_locks: { "1": 123 } });
|
||||
expect(w.find('[data-test="loop-frame-2"]').classes()).toContain("wp-fchips__chip--locked");
|
||||
expect(w.find('[data-test="loop-frame-1"]').classes()).not.toContain("wp-fchips__chip--locked");
|
||||
});
|
||||
|
||||
it("a frame can be both locked and bypassed", () => {
|
||||
const w = fw({ seed_locks: { "1": 123 }, bypass_frames: [1] });
|
||||
const chip = w.find('[data-test="loop-frame-2"]');
|
||||
expect(chip.classes()).toContain("wp-fchips__chip--locked");
|
||||
expect(chip.classes()).toContain("wp-fchips__chip--bypassed");
|
||||
});
|
||||
|
||||
it("ignores non-numeric lock keys rather than rendering a NaN state", () => {
|
||||
const w = fw({ seed_locks: { junk: 1, "1": 123 } as Record<string, number> });
|
||||
expect(w.find('[data-test="loop-frame-2"]').classes()).toContain("wp-fchips__chip--locked");
|
||||
});
|
||||
|
||||
it("advertises the combos in the widget, not just in tooltips", () => {
|
||||
const w = fw();
|
||||
expect(w.find('[data-test="loop-frames-hint"]').text()).toMatch(/shift/i);
|
||||
expect(w.find('[data-test="loop-frames-hint"]').text()).toMatch(/alt|option/i);
|
||||
});
|
||||
|
||||
it("the tooltip names the action the next click will take", () => {
|
||||
const w = fw({ seed_locks: { "1": 123 }, bypass_frames: [1] });
|
||||
const t = w.find('[data-test="loop-frame-2"]').attributes("title")!;
|
||||
expect(t).toMatch(/unlock/i);
|
||||
expect(t).toMatch(/re-enable/i);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,7 +15,10 @@
|
||||
import { computed, ref } from "vue";
|
||||
import type { ContextLoopConfig, LoopStrategy } from "./types";
|
||||
import SeedListModal from "../shared/SeedListModal.vue";
|
||||
import { deriveLoopSeeds } from "../shared/seed-derive";
|
||||
import { pushToast } from "../shared/toast-store";
|
||||
import { currentFrame, setFrame } from "./frame-cursor";
|
||||
import FrameChips from "../shared/FrameChips.vue";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
@@ -37,6 +40,10 @@ const props = withDefaults(
|
||||
|
||||
const emit = defineEmits<{ "update:modelValue": [next: ContextLoopConfig] }>();
|
||||
|
||||
/** Frame-grid collapse. Owned by the widget glue so it can persist to
|
||||
* `node.properties` and survive a workflow save. */
|
||||
const chipsCollapsed = defineModel<boolean>("chipsCollapsed", { default: false });
|
||||
|
||||
const STRATEGIES: { id: LoopStrategy; label: string; hint: string }[] = [
|
||||
{ id: "hash_index", label: "hash", hint: "Independent per-iteration; recommended for varied results." },
|
||||
{ id: "sequential", label: "sequential", hint: "base, base+1, base+2, … Predictable diffs." },
|
||||
@@ -55,9 +62,6 @@ const OVERRIDE_SEED_TOOLTIP =
|
||||
|
||||
const isMuted = computed<boolean>(() => props.nodeMode === 2);
|
||||
const isBypassed = computed<boolean>(() => props.nodeMode === 4);
|
||||
const frameChips = computed(() =>
|
||||
Array.from({ length: Math.max(1, props.count ?? 1) }, (_, i) => i),
|
||||
);
|
||||
|
||||
const seedsOpen = ref(false);
|
||||
const lockedCount = computed(() => Object.keys(props.modelValue.seed_locks ?? {}).length);
|
||||
@@ -66,6 +70,74 @@ function onSeedLocks(next: Record<string, number>): void {
|
||||
emit("update:modelValue", { ...props.modelValue, seed_locks: next });
|
||||
}
|
||||
|
||||
const bypassedCount = computed(() => (props.modelValue.bypass_frames ?? []).length);
|
||||
/** 0-based bypassed frame indices — drives the dashed border on edit-frame
|
||||
* chips so bypassed frames read at a glance without opening the modal. */
|
||||
const bypassSet = computed(() => new Set(props.modelValue.bypass_frames ?? []));
|
||||
function onBypassFrames(next: number[]): void {
|
||||
emit("update:modelValue", { ...props.modelValue, bypass_frames: next });
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* Modifier-click on a frame chip — lock / bypass without the modal.
|
||||
*
|
||||
* Both states were already VISIBLE on the chips but only CHANGEABLE two clicks
|
||||
* away, inside a modal that covers the node you are reading. Toggling a couple
|
||||
* of frames is the common case; the modal earns its place for the bulk
|
||||
* operations (lock all, paste a series, out-of-range locks) and keeps them.
|
||||
*
|
||||
* Modifier choice: Alt and Shift both survive the trip. Ctrl is out because on
|
||||
* macOS Ctrl-click IS a right-click, so the combo would open a context menu
|
||||
* instead. Alt for bypass follows the seed modal's existing Alt-click-for-a-
|
||||
* variant idiom on its Copy button.
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
/** 0-based locked frame indices. Keys are strings in the config; anything
|
||||
* non-numeric is ignored rather than becoming `NaN` in the set. */
|
||||
const lockSet = computed(() => {
|
||||
const out = new Set<number>();
|
||||
for (const k of Object.keys(props.modelValue.seed_locks ?? {})) {
|
||||
const n = Number(k);
|
||||
if (Number.isInteger(n)) out.add(n);
|
||||
}
|
||||
return out;
|
||||
});
|
||||
|
||||
/** The seed series this loop WOULD produce — the same values "Lock all" in
|
||||
* the modal writes, so a chip-lock and a modal-lock agree. */
|
||||
const derivedSeeds = computed(() =>
|
||||
deriveLoopSeeds(props.baseSeed, Math.max(1, props.count ?? 1), props.modelValue.strategy),
|
||||
);
|
||||
|
||||
/** In-range frames that are still running. Bypassing the last one would leave
|
||||
* the loop with nothing to execute, so the modal forbids it and so do we. */
|
||||
const activeFrameCount = computed(() => {
|
||||
let n = 0;
|
||||
for (let i = 0; i < Math.max(1, props.count ?? 1); i++) if (!bypassSet.value.has(i)) n++;
|
||||
return n;
|
||||
});
|
||||
|
||||
function toggleFrameLock(i: number): void {
|
||||
const next = { ...(props.modelValue.seed_locks ?? {}) };
|
||||
if (lockSet.value.has(i)) delete next[String(i)];
|
||||
else next[String(i)] = derivedSeeds.value[i] ?? props.baseSeed;
|
||||
emit("update:modelValue", { ...props.modelValue, seed_locks: next });
|
||||
}
|
||||
|
||||
function toggleFrameBypass(i: number): void {
|
||||
const on = bypassSet.value.has(i);
|
||||
if (!on && activeFrameCount.value <= 1) {
|
||||
// Silence here would read as a broken click, and the reason is not
|
||||
// guessable from the chip.
|
||||
pushToast("A loop needs at least one running frame.", { severity: "warning" });
|
||||
return;
|
||||
}
|
||||
const next = new Set(bypassSet.value);
|
||||
if (on) next.delete(i);
|
||||
else next.add(i);
|
||||
onBypassFrames([...next].sort((a, b) => a - b));
|
||||
}
|
||||
|
||||
function pickStrategy(s: LoopStrategy): void {
|
||||
if (props.modelValue.strategy === s) return;
|
||||
emit("update:modelValue", { ...props.modelValue, strategy: s });
|
||||
@@ -133,19 +205,26 @@ function toggleTotalInternal(): void {
|
||||
Per-iteration seeds
|
||||
<span class="wp-loop__seedbtn-fill" />
|
||||
<span v-if="lockedCount" class="wp-loop__seedbtn-badge" data-test="loop-seeds-badge">{{ lockedCount }} locked</span>
|
||||
<span v-if="bypassedCount" class="wp-loop__seedbtn-badge" data-test="loop-seeds-bypass-badge">{{ bypassedCount }} bypassed</span>
|
||||
<svg class="wp-loop__seedbtn-chev" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M9 6l6 6-6 6" /></svg>
|
||||
</button>
|
||||
|
||||
<div class="wp-loop__section">
|
||||
<div class="wp-loop__label">edit frame</div>
|
||||
<div class="wp-loop__chips wp-loop__chips--frames" role="radiogroup" aria-label="Edit frame">
|
||||
<button type="button" class="wp-loop__chip" :class="{ 'wp-loop__chip--active': currentFrame === null }"
|
||||
data-test="loop-frame-base" role="radio" :aria-checked="currentFrame === null" @click="setFrame(null)">base</button>
|
||||
<button v-for="i in frameChips" :key="i" type="button" class="wp-loop__chip"
|
||||
:class="{ 'wp-loop__chip--active': currentFrame === i }"
|
||||
:data-test="`loop-frame-${i + 1}`" role="radio" :aria-checked="currentFrame === i" @click="setFrame(i)">#{{ i + 1 }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- `base` is not a frame: it has no seed to lock and nothing to bypass,
|
||||
so it takes no modifiers. -->
|
||||
<FrameChips
|
||||
label="edit frame"
|
||||
:count="Math.max(1, count ?? 1)"
|
||||
:locked="[...lockSet]"
|
||||
:bypassed="[...bypassSet]"
|
||||
v-model:collapsed="chipsCollapsed"
|
||||
:current="currentFrame"
|
||||
selectable
|
||||
show-base
|
||||
bypass-interactive
|
||||
@select="setFrame"
|
||||
@toggle-lock="toggleFrameLock"
|
||||
@toggle-bypass="toggleFrameBypass"
|
||||
/>
|
||||
|
||||
<div
|
||||
class="wp-loop__row"
|
||||
@@ -224,8 +303,9 @@ function toggleTotalInternal(): void {
|
||||
<SeedListModal v-if="seedsOpen" :node-name="'WP Context Loop'" :base-seed="baseSeed"
|
||||
:count="count" :strategy="modelValue.strategy" :seed-locks="modelValue.seed_locks ?? {}"
|
||||
:previous-seeds="previousSeeds"
|
||||
:bypass-frames="modelValue.bypass_frames ?? []"
|
||||
:override-hint="!modelValue.override_seed ? 'These seeds apply only when Override Context seed is on.' : ''"
|
||||
@update:seed-locks="onSeedLocks" @close="seedsOpen = false" />
|
||||
@update:seed-locks="onSeedLocks" @update:bypass-frames="onBypassFrames" @close="seedsOpen = false" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -249,14 +329,7 @@ function toggleTotalInternal(): void {
|
||||
}
|
||||
|
||||
.wp-loop__chips { display: flex; gap: 4px; }
|
||||
/* Frame chips ONLY (the strategy row has 3 fixed chips that must stay one
|
||||
row + show full labels): grid so 15+ frame chips WRAP instead of
|
||||
overflowing the node. auto-fill keeps a uniform cell width; the last row
|
||||
grows to 1fr to fill it. */
|
||||
.wp-loop__chips--frames {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(38px, 1fr));
|
||||
}
|
||||
/* Strategy chips only — the per-frame grid now lives in FrameChips.vue. */
|
||||
.wp-loop__chip {
|
||||
flex: 1;
|
||||
padding: 4px 6px;
|
||||
|
||||
@@ -31,6 +31,7 @@ describe("parseContextLoopConfig", () => {
|
||||
iteration_internal: false,
|
||||
total_internal: false,
|
||||
seed_locks: {},
|
||||
bypass_frames: [],
|
||||
};
|
||||
expect(parseContextLoopConfig(JSON.stringify(cfg))).toEqual(cfg);
|
||||
});
|
||||
@@ -44,6 +45,7 @@ describe("parseContextLoopConfig", () => {
|
||||
iteration_internal: true,
|
||||
total_internal: true,
|
||||
seed_locks: {},
|
||||
bypass_frames: [],
|
||||
};
|
||||
expect(parseContextLoopConfig(JSON.stringify(cfg))).toEqual(cfg);
|
||||
});
|
||||
@@ -68,6 +70,7 @@ describe("parseContextLoopConfig", () => {
|
||||
iteration_internal: false,
|
||||
total_internal: true,
|
||||
seed_locks: {},
|
||||
bypass_frames: [],
|
||||
};
|
||||
const round = parseContextLoopConfig(serializeContextLoopConfig(cfg));
|
||||
expect(round).toEqual(cfg);
|
||||
@@ -89,3 +92,22 @@ describe("ContextLoopConfig seed_locks", () => {
|
||||
expect(parseContextLoopConfig(serializeContextLoopConfig(cfg)).seed_locks).toEqual({ "0": 7 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("bypass_frames parse", () => {
|
||||
it("defaults to empty", () => {
|
||||
expect(emptyContextLoopConfig().bypass_frames).toEqual([]);
|
||||
expect(parseContextLoopConfig("{}").bypass_frames).toEqual([]);
|
||||
});
|
||||
it("dedups + sorts, keeps out-of-range, drops junk + negatives", () => {
|
||||
expect(parseContextLoopConfig('{"bypass_frames":[3,1,3,0]}').bypass_frames).toEqual([0, 1, 3]);
|
||||
expect(parseContextLoopConfig('{"bypass_frames":[2,-1,"x",2,999]}').bypass_frames).toEqual([2, 999]);
|
||||
});
|
||||
it("drops coercible non-numbers, not coerce them (Python parity)", () => {
|
||||
// true/"3"/null would coerce to 1/3/0 under Number() — must be dropped.
|
||||
expect(parseContextLoopConfig('{"bypass_frames":[true,"3",null,2]}').bypass_frames).toEqual([2]);
|
||||
});
|
||||
it("malformed collapses to empty", () => {
|
||||
expect(parseContextLoopConfig('{"bypass_frames":"nope"}').bypass_frames).toEqual([]);
|
||||
expect(parseContextLoopConfig("not json").bypass_frames).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -23,6 +23,10 @@ export interface ContextLoopConfig {
|
||||
/** 0-based iteration index (stringified) -> pinned seed. Unlocked
|
||||
* indices re-derive from base+strategy. Empty by default. */
|
||||
seed_locks: Record<string, number>;
|
||||
/** 0-based iteration indices to bypass (skip generation + overrides).
|
||||
* Sorted, deduped, non-negative. Out-of-range (>= count) entries are
|
||||
* kept and re-apply if count grows. Empty by default. */
|
||||
bypass_frames: number[];
|
||||
}
|
||||
|
||||
const STRATEGIES = new Set<LoopStrategy>(["sequential", "hash_index", "prime_stride"]);
|
||||
@@ -36,6 +40,7 @@ export function emptyContextLoopConfig(): ContextLoopConfig {
|
||||
iteration_internal: true,
|
||||
total_internal: true,
|
||||
seed_locks: {},
|
||||
bypass_frames: [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -71,6 +76,18 @@ export function parseContextLoopConfig(raw: string | null | undefined): ContextL
|
||||
}
|
||||
out.seed_locks = locks;
|
||||
}
|
||||
if (Array.isArray(obj.bypass_frames)) {
|
||||
const frames = new Set<number>();
|
||||
for (const x of obj.bypass_frames) {
|
||||
// Type-guard before accepting — do NOT coerce. Mirrors the Python
|
||||
// `_parse_config` (which rejects non-int via isinstance), so both
|
||||
// parsers degrade corrupt widget JSON identically (`true`, `"3"`,
|
||||
// `null` are dropped on both sides, not coerced to 1/3/0).
|
||||
if (typeof x !== "number" || !Number.isInteger(x) || x < 0) continue;
|
||||
frames.add(x);
|
||||
}
|
||||
out.bypass_frames = [...frames].sort((a, b) => a - b);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
import { computed, nextTick, ref, watch } from "vue";
|
||||
import ModalShell from "../shared/ModalShell.vue";
|
||||
import ConfirmDialog from "../shared/ConfirmDialog.vue";
|
||||
import { api } from "../../manager/api/client";
|
||||
@@ -165,14 +165,15 @@ function onKeydown(ev: KeyboardEvent) {
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => window.addEventListener("keydown", onKeydown));
|
||||
onUnmounted(() => window.removeEventListener("keydown", onKeydown));
|
||||
// Keys arrive from ModalShell (@keydown below) rather than window: the modal
|
||||
// shield stops inside-modal keys at the overlay so they cannot reach ComfyUI's
|
||||
// global shortcuts, so a window listener here would never fire.
|
||||
|
||||
const alreadyAddedSet = computed(() => new Set(props.alreadyAddedIds ?? []));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ModalShell :visible="visible" @close="emit('close')">
|
||||
<ModalShell :visible="visible" @close="emit('close')" @keydown="onKeydown">
|
||||
<div class="wp-bp" role="dialog">
|
||||
<header class="wp-bp__head">
|
||||
<div class="wp-bp__head-text">
|
||||
|
||||
@@ -3,6 +3,7 @@ import { flushPromises, mount } from "@vue/test-utils";
|
||||
import ContextWidget from "./ContextWidget.vue";
|
||||
import { baseCodename } from "../../extension/node-codename";
|
||||
import { _resetForTests as resetDriftStore } from "./drift-store";
|
||||
import { currentFrame } from "../context-loop/frame-cursor";
|
||||
|
||||
beforeEach(() => {
|
||||
// Phase 5.5.4 — the picker now fetches the library on mount. Stub
|
||||
@@ -207,6 +208,75 @@ describe("ContextWidget drift dot", () => {
|
||||
expect(wrapper.find(".wp-mod-dot--missing").exists()).toBe(false);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it("shows drift for an empty-hash module whose uuid IS in the live library", async () => {
|
||||
// Repro: a workflow whose embedded module carries payload_hash "" (a
|
||||
// malformed/legacy/builder-emitted copy) but whose uuid exists in the
|
||||
// library. It must NOT be treated as inline/verdict-less — surface it as
|
||||
// drift so the bulk "refresh drifted" button can relink it.
|
||||
resetDriftStore();
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (url: string) => {
|
||||
if (typeof url === "string" && url.includes("/wp/api/modules/hashes")) {
|
||||
return new Response(JSON.stringify({ hashes: { bbbbbbbb: { type: "wildcard", payload_hash: "h-LIVE" } } }), { status: 200 });
|
||||
}
|
||||
return new Response("{}", { status: 200 });
|
||||
}),
|
||||
);
|
||||
const initialJson = JSON.stringify({
|
||||
version: 1,
|
||||
modules: [
|
||||
{
|
||||
id: "bbbbbbbb", type: "wildcard", enabled: true,
|
||||
meta: { name: "wc", description: "", tags: [] }, entries: [],
|
||||
payload: { options: [] }, payload_hash: "",
|
||||
},
|
||||
],
|
||||
});
|
||||
const wrapper = mount(ContextWidget, {
|
||||
attachTo: document.body,
|
||||
props: { nodeId: 98, initialJson, upstreamVars: [], onChange: () => {} },
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(wrapper.find(".wp-mod-dot--drift").exists()).toBe(true);
|
||||
});
|
||||
expect(wrapper.find(".wp-mod-dot--missing").exists()).toBe(false);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it("leaves a genuinely inline module (empty hash, uuid NOT in library) verdict-less", async () => {
|
||||
resetDriftStore();
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (url: string) => {
|
||||
if (typeof url === "string" && url.includes("/wp/api/modules/hashes")) {
|
||||
return new Response(JSON.stringify({ hashes: { somethingelse: { type: "wildcard", payload_hash: "h-LIVE" } } }), { status: 200 });
|
||||
}
|
||||
return new Response("{}", { status: 200 });
|
||||
}),
|
||||
);
|
||||
const initialJson = JSON.stringify({
|
||||
version: 1,
|
||||
modules: [
|
||||
{
|
||||
id: "cccccccc", type: "wildcard", enabled: true,
|
||||
meta: { name: "inline", description: "", tags: [] }, entries: [],
|
||||
payload: { options: [] }, payload_hash: "",
|
||||
},
|
||||
],
|
||||
});
|
||||
const wrapper = mount(ContextWidget, {
|
||||
attachTo: document.body,
|
||||
props: { nodeId: 97, initialJson, upstreamVars: [], onChange: () => {} },
|
||||
});
|
||||
// Give the poll a beat to land, then assert no drift/missing badges.
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
expect(wrapper.find(".wp-mod-dot--drift").exists()).toBe(false);
|
||||
expect(wrapper.find(".wp-mod-dot--missing").exists()).toBe(false);
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ContextWidget bulk refresh", () => {
|
||||
@@ -648,6 +718,105 @@ describe("ContextWidget bundle ops via ctxmenu", () => {
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it("Reset REFUSES (keeps children) when the instance isn't library-linked", async () => {
|
||||
resetDriftStore();
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response("{}", { status: 200 })));
|
||||
const bundleUid = "buidEMPTY001";
|
||||
const initialJson = JSON.stringify({
|
||||
version: 1,
|
||||
modules: [
|
||||
{
|
||||
id: "dddddddd", type: "wildcard", enabled: true,
|
||||
meta: { name: "LocallyEdited" }, entries: [],
|
||||
payload: { var_binding: "v", options: [{ id: "o2", value: "y", weight: 2 }] },
|
||||
payload_hash: "h-edited", bundle_origin: bundleUid,
|
||||
},
|
||||
],
|
||||
bundles: [
|
||||
{
|
||||
_uid: bundleUid, library_id: "", start_idx: 0, end_idx: 0,
|
||||
enabled: true, collapsed: false, inserted_at_hash: "", name: "Unlinked", color: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
const onChange = vi.fn();
|
||||
const wrapper = mount(ContextWidget, {
|
||||
attachTo: document.body,
|
||||
props: { nodeId: 305, initialJson, upstreamVars: [], onChange },
|
||||
});
|
||||
await flushPromises();
|
||||
onChange.mockClear();
|
||||
|
||||
const header = document.querySelector(`[data-bundle-uid="${bundleUid}"][data-bundle-header]`);
|
||||
expect(header).toBeTruthy();
|
||||
header!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
|
||||
await flushPromises();
|
||||
const items = Array.from(document.querySelectorAll(".wp-ctxmenu__item")) as HTMLElement[];
|
||||
const reset = items.find((el) => el.textContent?.includes("Reset to library snapshot"));
|
||||
expect(reset).toBeTruthy();
|
||||
reset!.click();
|
||||
await flushPromises();
|
||||
|
||||
// Refused — the live child is untouched, no destructive empty commit.
|
||||
expect(wrapper.find('[data-module-id="dddddddd"]').exists()).toBe(true);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it("Reset REFUSES (keeps children) when the library snapshot comes back empty", async () => {
|
||||
resetDriftStore();
|
||||
const fetchSpy = vi.fn(async (url: string, init?: RequestInit) => {
|
||||
if (typeof url === "string" && url.match(/\/wp\/api\/bundles\/bn_empty$/) && (!init || init.method === "GET")) {
|
||||
return new Response(JSON.stringify({
|
||||
id: "bn_empty", name: "EmptySnap", description: "", color: null,
|
||||
category_id: null, tags: [], is_favorite: false,
|
||||
children: [], payload_hash: "ph-empty", version: 1, created_at: "", updated_at: "",
|
||||
}), { status: 200 });
|
||||
}
|
||||
return new Response("{}", { status: 200 });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchSpy);
|
||||
const bundleUid = "buidEMPTY002";
|
||||
const initialJson = JSON.stringify({
|
||||
version: 1,
|
||||
modules: [
|
||||
{
|
||||
id: "dddddddd", type: "wildcard", enabled: true,
|
||||
meta: { name: "LocallyEdited" }, entries: [],
|
||||
payload: { var_binding: "v", options: [{ id: "o2", value: "y", weight: 2 }] },
|
||||
payload_hash: "h-edited", bundle_origin: bundleUid,
|
||||
},
|
||||
],
|
||||
bundles: [
|
||||
{
|
||||
_uid: bundleUid, library_id: "bn_empty", start_idx: 0, end_idx: 0,
|
||||
enabled: true, collapsed: false, inserted_at_hash: "ph-old", name: "EmptySnap", color: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
const onChange = vi.fn();
|
||||
const wrapper = mount(ContextWidget, {
|
||||
attachTo: document.body,
|
||||
props: { nodeId: 306, initialJson, upstreamVars: [], onChange },
|
||||
});
|
||||
await flushPromises();
|
||||
onChange.mockClear();
|
||||
|
||||
const header = document.querySelector(`[data-bundle-uid="${bundleUid}"][data-bundle-header]`);
|
||||
expect(header).toBeTruthy();
|
||||
header!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
|
||||
await flushPromises();
|
||||
const items = Array.from(document.querySelectorAll(".wp-ctxmenu__item")) as HTMLElement[];
|
||||
const reset = items.find((el) => el.textContent?.includes("Reset to library snapshot"));
|
||||
expect(reset).toBeTruthy();
|
||||
reset!.click();
|
||||
await flushPromises();
|
||||
|
||||
// The empty snapshot must NOT wipe the live child.
|
||||
expect(wrapper.find('[data-module-id="dddddddd"]').exists()).toBe(true);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it("Reset re-adds children removed since insert (bundle end_idx grew via reconcile)", async () => {
|
||||
resetDriftStore();
|
||||
// Library has TWO children; in-graph bundle currently has ONE
|
||||
@@ -728,6 +897,124 @@ describe("ContextWidget bundle ops via ctxmenu", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("ContextWidget Hold toggle via ctxmenu", () => {
|
||||
beforeEach(() => {
|
||||
// Hold is base-level; pin the shared frame cursor to base so the
|
||||
// menu item isn't disabled by a leftover edit-frame from another test.
|
||||
currentFrame.value = null;
|
||||
});
|
||||
afterEach(() => {
|
||||
currentFrame.value = null;
|
||||
});
|
||||
|
||||
it("Hold across run stamps seed_scope=hold; reopening offers Release hold which flips back to vary", async () => {
|
||||
resetDriftStore();
|
||||
const onChange = vi.fn();
|
||||
const initialJson = JSON.stringify({
|
||||
version: 1,
|
||||
modules: [
|
||||
{
|
||||
id: "aaaaaaaa", type: "wildcard", enabled: true,
|
||||
meta: { name: "Hair" }, entries: [],
|
||||
payload: { options: [], var_binding: "hair" }, payload_hash: "h-A",
|
||||
},
|
||||
],
|
||||
});
|
||||
const wrapper = mount(ContextWidget, {
|
||||
attachTo: document.body,
|
||||
props: { nodeId: 410, initialJson, upstreamVars: [], onChange },
|
||||
});
|
||||
await flushPromises();
|
||||
onChange.mockClear();
|
||||
|
||||
// Un-held module → item reads "Hold across run" and is enabled.
|
||||
await wrapper.find('[data-module-id="aaaaaaaa"]').trigger("contextmenu");
|
||||
await flushPromises();
|
||||
let items = Array.from(document.querySelectorAll(".wp-ctxmenu__item")) as HTMLElement[];
|
||||
const hold = items.find((el) => el.textContent?.includes("Hold across run"));
|
||||
expect(hold, "Hold item should appear for a wildcard row").toBeTruthy();
|
||||
expect(hold!.classList.contains("wp-ctxmenu__item--disabled")).toBe(false);
|
||||
hold!.click();
|
||||
await flushPromises();
|
||||
|
||||
const afterHold = onChange.mock.calls[onChange.mock.calls.length - 1][0] as string;
|
||||
expect(JSON.parse(afterHold).modules[0].instance.seed_scope).toBe("hold");
|
||||
|
||||
// Held module → label swaps to "Release hold"; clicking it varies again.
|
||||
await wrapper.find('[data-module-id="aaaaaaaa"]').trigger("contextmenu");
|
||||
await flushPromises();
|
||||
items = Array.from(document.querySelectorAll(".wp-ctxmenu__item")) as HTMLElement[];
|
||||
const release = items.find((el) => el.textContent?.includes("Release hold"));
|
||||
expect(release, "Held row should offer Release hold").toBeTruthy();
|
||||
release!.click();
|
||||
await flushPromises();
|
||||
|
||||
const afterRelease = onChange.mock.calls[onChange.mock.calls.length - 1][0] as string;
|
||||
expect(JSON.parse(afterRelease).modules[0].instance.seed_scope).toBe("vary");
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it("disables the Hold item when a loop edit-frame is active (hold is base-only)", async () => {
|
||||
resetDriftStore();
|
||||
const initialJson = JSON.stringify({
|
||||
version: 1,
|
||||
modules: [
|
||||
{
|
||||
id: "aaaaaaaa", type: "wildcard", enabled: true,
|
||||
meta: { name: "Hair" }, entries: [],
|
||||
payload: { options: [], var_binding: "hair" }, payload_hash: "h-A",
|
||||
},
|
||||
],
|
||||
});
|
||||
const wrapper = mount(ContextWidget, {
|
||||
attachTo: document.body,
|
||||
props: { nodeId: 412, initialJson, upstreamVars: [], onChange: () => {} },
|
||||
});
|
||||
await flushPromises();
|
||||
currentFrame.value = 0; // user is editing frame #0 of a loop
|
||||
|
||||
await wrapper.find('[data-module-id="aaaaaaaa"]').trigger("contextmenu");
|
||||
await flushPromises();
|
||||
const items = Array.from(document.querySelectorAll(".wp-ctxmenu__item")) as HTMLElement[];
|
||||
const hold = items.find((el) => el.textContent?.includes("Hold across run"));
|
||||
expect(hold, "Hold item still present while a frame is active").toBeTruthy();
|
||||
expect(hold!.classList.contains("wp-ctxmenu__item--disabled")).toBe(true);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it("omits the Hold item for a constraint row (seed_scope not honored)", async () => {
|
||||
resetDriftStore();
|
||||
const initialJson = JSON.stringify({
|
||||
version: 1,
|
||||
modules: [
|
||||
{ id: "aaaaaaaa", type: "wildcard", enabled: true, meta: { name: "Hair" }, entries: [], payload: { options: [], var_binding: "hair" } },
|
||||
{ id: "bbbbbbbb", type: "wildcard", enabled: true, meta: { name: "Outfit" }, entries: [], payload: { options: [], var_binding: "outfit" } },
|
||||
{
|
||||
id: "cccccccc", type: "constraint", enabled: true,
|
||||
meta: { name: "Hair × Outfit" }, entries: [],
|
||||
payload: {
|
||||
source_wildcard_id: "aaaaaaaa", target_wildcard_id: "bbbbbbbb",
|
||||
matrix: { blonde: { casual: { mode: "allow", factor: 1 } } }, exceptions: [],
|
||||
}, payload_hash: "h",
|
||||
},
|
||||
],
|
||||
});
|
||||
const wrapper = mount(ContextWidget, {
|
||||
attachTo: document.body,
|
||||
props: { nodeId: 411, initialJson, upstreamVars: [], onChange: () => {} },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
await wrapper.find('[data-module-id="cccccccc"]').trigger("contextmenu");
|
||||
await flushPromises();
|
||||
const items = Array.from(document.querySelectorAll(".wp-ctxmenu__item")) as HTMLElement[];
|
||||
expect(items.length).toBeGreaterThan(0);
|
||||
expect(items.find((el) => el.textContent?.includes("Hold across run"))).toBeUndefined();
|
||||
expect(items.find((el) => el.textContent?.includes("Release hold"))).toBeUndefined();
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ContextWidget summaryFor — constraint", () => {
|
||||
it("renders $src → $tgt · NxM with sibling lookup", async () => {
|
||||
resetDriftStore();
|
||||
@@ -947,6 +1234,64 @@ function mountWithModules(stubs: StubModule[]) {
|
||||
});
|
||||
}
|
||||
|
||||
// ── D3a: library re-link (onPushSaved path) ──────────────────────────────────
|
||||
|
||||
describe("ContextWidget module re-link", () => {
|
||||
it("re-links a detached row + follows a sibling constraint's source_wildcard_id", async () => {
|
||||
const onChange = vi.fn();
|
||||
const wrapper = mount(ContextWidget, {
|
||||
props: {
|
||||
nodeId: 9100,
|
||||
initialJson: JSON.stringify({
|
||||
version: 1,
|
||||
modules: [
|
||||
{
|
||||
id: "dead0001", type: "wildcard", enabled: true,
|
||||
meta: { name: "hair", description: "", tags: [] }, entries: [],
|
||||
payload: { options: [{ id: "o1", value: "red" }] }, payload_hash: "HASH_A",
|
||||
},
|
||||
{
|
||||
id: "c1", type: "constraint", enabled: true,
|
||||
meta: { name: "cn", description: "", tags: [] }, entries: [],
|
||||
payload: { source_wildcard_id: "dead0001", target_wildcard_id: "w2", matrix: {} },
|
||||
payload_hash: "HC",
|
||||
},
|
||||
],
|
||||
}),
|
||||
upstreamVars: [],
|
||||
onChange,
|
||||
},
|
||||
});
|
||||
// Let the initial parse settle (its suppressWatch cycle) so the relink
|
||||
// change below isn't coalesced into the swallowed first watcher tick.
|
||||
await flushPromises();
|
||||
onChange.mockClear();
|
||||
|
||||
// Two PushToLibraryModal instances exist: ModuleEditModal's (bound to
|
||||
// onPushToLibrarySaved, draft=null here) and ContextWidget's own (bound to
|
||||
// onPushSaved, the right-click path). The latter is last in DFS order.
|
||||
const ptls = wrapper.findAllComponents({ name: "PushToLibraryModal" });
|
||||
expect(ptls.length).toBeGreaterThan(0);
|
||||
const ptl = ptls[ptls.length - 1];
|
||||
ptl.vm.$emit("saved", {
|
||||
mode: "relink", id: "live0001", origId: "dead0001",
|
||||
payload_hash: "HASH_A", name: "hair", bundles_updated: [],
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
const calls = onChange.mock.calls;
|
||||
const lastJson = calls[calls.length - 1]?.[0] as string;
|
||||
const parsed = JSON.parse(lastJson) as {
|
||||
modules: Array<{ id: string; type: string; payload: Record<string, unknown> }>;
|
||||
};
|
||||
const wc = parsed.modules.find((m) => m.type === "wildcard");
|
||||
const con = parsed.modules.find((m) => m.type === "constraint");
|
||||
expect(wc?.id).toBe("live0001");
|
||||
expect(con?.payload.source_wildcard_id).toBe("live0001");
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Sibling badge (Phase B: lives in summary line, not header) ────────────
|
||||
//
|
||||
// Phase A shipped the badge in the header always-visible. Phase B
|
||||
@@ -1150,6 +1495,56 @@ describe("ContextWidget status badges", () => {
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it("an UNLINKED bundle reads as missing, not modified", async () => {
|
||||
// A bundle with no `library_id` could never be MISSING (that check
|
||||
// early-returned false without one), so its only badge was MODIFIED —
|
||||
// diffing its children against a snapshot baseline from a library entry
|
||||
// that isn't there. "Modified against what?" had no answer.
|
||||
resetDriftStore();
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (url: string) => {
|
||||
if (typeof url === "string" && url.includes("/hashes")) {
|
||||
return new Response(JSON.stringify({ hashes: {} }), { status: 200 });
|
||||
}
|
||||
return new Response("{}", { status: 200 });
|
||||
}),
|
||||
);
|
||||
|
||||
const wrapper = mount(ContextWidget, {
|
||||
attachTo: document.body,
|
||||
props: {
|
||||
nodeId: 815,
|
||||
initialJson: JSON.stringify({
|
||||
version: 1,
|
||||
modules: [
|
||||
{ id: "bbbbbbbb", type: "wildcard", enabled: true, meta: { name: "child" }, entries: [], payload: {} },
|
||||
],
|
||||
bundles: [{
|
||||
_uid: "bu1",
|
||||
// No library_id — the unlinked shape.
|
||||
library_id: "",
|
||||
name: "Pose Library",
|
||||
start_idx: 0,
|
||||
end_idx: 0,
|
||||
enabled: true,
|
||||
// A stale baseline that would otherwise light up MOD.
|
||||
snapshot_fingerprint: "v2:deadbeef",
|
||||
}],
|
||||
}),
|
||||
upstreamVars: [],
|
||||
onChange: () => {},
|
||||
},
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(wrapper.find(".wp-mod-badge--missing").exists()).toBe(true);
|
||||
});
|
||||
// MOD is meaningless with no insert to have diverged from.
|
||||
expect(wrapper.find(".wp-mod-badge--modified").exists()).toBe(false);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it("renders 'missing' text badge when uuid is not in library", async () => {
|
||||
resetDriftStore();
|
||||
vi.stubGlobal(
|
||||
|
||||
@@ -28,6 +28,11 @@ import BundleFrame from "./bundles/BundleFrame.vue";
|
||||
import { BundleFrameCtxKey, type BundleFrameCtx } from "./bundles/bundle-frame-ctx";
|
||||
import ModuleRow from "./ModuleRow.vue";
|
||||
import { ModuleRowCtxKey, type ModuleRowCtx } from "./module-row-ctx";
|
||||
import {
|
||||
CONTEXT_POOLS_KEY,
|
||||
FOREIGN_POOL_LOOKUP_KEY,
|
||||
buildContextPools,
|
||||
} from "../../extension/context-pools";
|
||||
import { LockSeedKey } from "./lock-seed-ctx";
|
||||
import { buildBundleInsertion, type BundleLibraryEntry } from "./bundles/insert";
|
||||
import { isEnabled, type WildcardOption, type InstanceLike } from "./editors/wildcard/probability";
|
||||
@@ -53,7 +58,8 @@ import {
|
||||
MOTION_FLIP_MS,
|
||||
MOTION_CURVE_FLIP,
|
||||
} from "./bundles/flip";
|
||||
import { api } from "../../manager/api/client";
|
||||
import { ApiError, api } from "../../manager/api/client";
|
||||
import type { VarProducerLike } from "../../manager/components/RefChip.vue";
|
||||
import { emptyBundleInstance, type BundleInstance } from "../../widgets/_shared";
|
||||
import ModuleEditModal from "./ModuleEditModal.vue";
|
||||
import ModalShell from "../shared/ModalShell.vue";
|
||||
@@ -91,6 +97,7 @@ import {
|
||||
unsubscribe as unsubscribeDrift,
|
||||
} from "./drift-store";
|
||||
import { classifyOne, type CollisionState } from "../../manager/import-export/collision";
|
||||
import { applyRelink } from "../../manager/import-export/relink-apply";
|
||||
import {
|
||||
getBundleCollapsedByDefault,
|
||||
getConfirmDestructiveBundle,
|
||||
@@ -101,6 +108,16 @@ const props = withDefaults(defineProps<{
|
||||
nodeId: number;
|
||||
initialJson: string;
|
||||
upstreamVars: string[];
|
||||
/** `$var` → which module in which node writes it (last-write-wins).
|
||||
* Threaded to the edit modals so a var chip's hover card can name its
|
||||
* producer instead of only confirming the name exists. Optional for
|
||||
* headless mounts. */
|
||||
upstreamProducers?: Record<string, VarProducerLike>;
|
||||
/** uuid → labels of OTHER Context nodes that hold it as a wildcard. Lets a
|
||||
* nested-ref hover card explain WHY it fell back to the library: the pool
|
||||
* exists on the canvas, just not in this node, and a catalog never crosses
|
||||
* a node boundary. Absent in headless mounts (no graph to walk). */
|
||||
wildcardHomesReader?: (uuid: string) => string[];
|
||||
/** Resolved upstream-var snapshot — `$name → resolved string` map.
|
||||
* Drives the combine modal's live-preview pane so users see the
|
||||
* template with vars substituted (e.g. `red portrait` instead of
|
||||
@@ -467,7 +484,7 @@ function openPushToLibrary(idx: number): void {
|
||||
}
|
||||
|
||||
interface PushSaveResult {
|
||||
mode: "update" | "fork" | "reattach";
|
||||
mode: "update" | "fork" | "reattach" | "relink";
|
||||
id: string;
|
||||
payload_hash: string;
|
||||
bundles_updated: string[];
|
||||
@@ -511,6 +528,21 @@ function onPushSaved(result: PushSaveResult): void {
|
||||
};
|
||||
});
|
||||
commitModules(next);
|
||||
} else if (result.mode === "relink") {
|
||||
// Re-link: point the detached row(s) at an EXISTING content-identical
|
||||
// library uuid AND walk every module so sibling @{} refs + constraint
|
||||
// source/target follow the new uuid (applyRelink swaps id + payload_hash
|
||||
// on the matching row + remaps refs everywhere else).
|
||||
const remapped = applyRelink(
|
||||
value.value.modules as unknown as Record<string, unknown>[],
|
||||
{ oldId: result.origId, newId: result.id, newPayloadHash: result.payload_hash },
|
||||
) as unknown as ModuleEntry[];
|
||||
const next = remapped.map((m) =>
|
||||
m.id === result.id
|
||||
? { ...m, meta: { ...(m.meta ?? {}), library_name: result.name } }
|
||||
: m,
|
||||
);
|
||||
commitModules(next);
|
||||
}
|
||||
const bundlesNote =
|
||||
result.bundles_updated.length > 0
|
||||
@@ -519,6 +551,7 @@ function onPushSaved(result: PushSaveResult): void {
|
||||
let msg: string;
|
||||
if (result.mode === "fork") msg = `Saved as new library entry "${result.name}"`;
|
||||
else if (result.mode === "reattach") msg = `Re-attached "${result.name}" to library`;
|
||||
else if (result.mode === "relink") msg = `Re-linked "${result.name}" to library`;
|
||||
else msg = `Saved "${result.name}" to library${bundlesNote}`;
|
||||
pushToast(msg, { severity: "success" });
|
||||
pushOpen.value = false;
|
||||
@@ -633,7 +666,7 @@ async function pushBundleCascadeRestore(): Promise<{
|
||||
}
|
||||
|
||||
interface BundlePushSaveResult {
|
||||
mode: "update" | "fork" | "reattach";
|
||||
mode: "update" | "fork" | "reattach" | "relink";
|
||||
id: string;
|
||||
payload_hash: string;
|
||||
name: string;
|
||||
@@ -642,11 +675,12 @@ interface BundlePushSaveResult {
|
||||
}
|
||||
function onBundlePushSaved(result: BundlePushSaveResult): void {
|
||||
void forceRefreshHashes();
|
||||
if (result.mode === "update" || result.mode === "reattach") {
|
||||
if (result.mode === "update" || result.mode === "reattach" || result.mode === "relink") {
|
||||
// Update: refresh inserted_at_hash + snapshot fingerprint for every
|
||||
// BundleInstance pointing at this library entry — drift + MOD dots
|
||||
// clear instantly. Reattach: also rebind library_id from the dead
|
||||
// uuid to the freshly-created one.
|
||||
// uuid to the freshly-created one. Relink: same rebind, but onto an
|
||||
// EXISTING content-identical library bundle (no write happened).
|
||||
const nextBundles = (value.value.bundles ?? []).map((b) => {
|
||||
if (b.library_id !== result.origId) return b;
|
||||
const rebound: BundleInstance = {
|
||||
@@ -663,6 +697,7 @@ function onBundlePushSaved(result: BundlePushSaveResult): void {
|
||||
let msg: string;
|
||||
if (result.mode === "fork") msg = `Saved as new library bundle "${result.name}"`;
|
||||
else if (result.mode === "reattach") msg = `Re-attached "${result.name}" to library`;
|
||||
else if (result.mode === "relink") msg = `Re-linked "${result.name}" to library`;
|
||||
else msg = `Saved "${result.name}" to library`;
|
||||
if (result.cascade) {
|
||||
const parts: string[] = [];
|
||||
@@ -746,11 +781,51 @@ const resolvedForEditing = computed<Record<string, ResolvedValue>>(() => {
|
||||
// Combine + wildcard have no entries; without this kind-aware fallback the
|
||||
// modal's insert-var dropdown would render empty for chains where the only
|
||||
// vars come from binding-producer modules.
|
||||
const siblingNodeVars = computed<string[]>(() => {
|
||||
/**
|
||||
* Vars written by the OTHER modules in this same Context node, together with
|
||||
* who writes each one.
|
||||
*
|
||||
* `collectUpstreamProducers` walks the node chain and deliberately excludes
|
||||
* the point-of-view node, so it can only attribute vars produced further
|
||||
* upstream. In a graph where one Context node carries most of the modules —
|
||||
* which is the normal shape — that left nearly every `$var` in the
|
||||
* autocomplete with no writer at all, and the rows rendered bare while the
|
||||
* SPA's equivalent showed a full attribution line for the same names.
|
||||
*
|
||||
* Built in the same pass as the name list so the two cannot disagree about
|
||||
* which module owns a name.
|
||||
*/
|
||||
const siblingVarInfo = computed<{
|
||||
names: string[];
|
||||
producers: Record<string, VarProducerLike>;
|
||||
}>(() => {
|
||||
const names = new Set<string>();
|
||||
const producers: Record<string, VarProducerLike> = {};
|
||||
/** Last module to write each name, so repeat writes from one module (a
|
||||
* derivation's branches) do not inflate the override count. */
|
||||
const lastWriter = new Map<string, string>();
|
||||
let owner: { kind: string; moduleName: string; moduleId: string } | null = null;
|
||||
function add(name: string | undefined | null): void {
|
||||
const trimmed = (name ?? "").replace(/^\$+/, "").trim();
|
||||
if (trimmed) names.add(trimmed);
|
||||
if (!trimmed) return;
|
||||
names.add(trimmed);
|
||||
if (!owner) return;
|
||||
// Later modules win, matching the engine's last-write-wins resolution.
|
||||
// The count tracks distinct MODULES, not write statements: a derivation
|
||||
// calls this once per branch and a fixed_values once per row, but at most
|
||||
// one branch fires and the module is a single writer either way.
|
||||
const prev = producers[trimmed];
|
||||
const sameWriter = lastWriter.get(trimmed) === owner.moduleId;
|
||||
lastWriter.set(trimmed, owner.moduleId);
|
||||
producers[trimmed] = {
|
||||
kind: owner.kind,
|
||||
moduleName: owner.moduleName,
|
||||
moduleId: owner.moduleId,
|
||||
// Same node, so there is no other node to name — saying which one it is
|
||||
// would be noise when every sibling gives the same answer.
|
||||
nodeLabel: "this node",
|
||||
shadowed: prev ? (sameWriter ? prev.shadowed : prev.shadowed + 1) : 0,
|
||||
};
|
||||
}
|
||||
const editingM = editingModule.value;
|
||||
const bundleEnabled = buildBundleEnabledMap(value.value.bundles);
|
||||
@@ -761,6 +836,11 @@ const siblingNodeVars = computed<string[]>(() => {
|
||||
// Defensive: also skip if same object (shouldn't happen but Vue
|
||||
// proxies can confuse identity equals).
|
||||
void editingM;
|
||||
owner = {
|
||||
kind: m.type,
|
||||
moduleName: m.meta?.name ?? m.type,
|
||||
moduleId: m.id,
|
||||
};
|
||||
for (const e of m.entries) add(e.variable_name);
|
||||
const inst = (m.instance ?? {}) as {
|
||||
variable_binding?: string | null;
|
||||
@@ -793,7 +873,38 @@ const siblingNodeVars = computed<string[]>(() => {
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...names];
|
||||
owner = null;
|
||||
return { names: [...names], producers };
|
||||
});
|
||||
|
||||
const siblingNodeVars = computed<string[]>(() => siblingVarInfo.value.names);
|
||||
|
||||
/**
|
||||
* Every `$var` writer the editors can name: upstream nodes first, then this
|
||||
* node's own modules on top.
|
||||
*
|
||||
* Siblings override because they run later in the same chain position, which
|
||||
* is what the engine does too — so the row names the module whose value
|
||||
* actually survives.
|
||||
*
|
||||
* The override COUNT has to be carried across the seam. A plain spread
|
||||
* replaces the upstream entry outright, taking its `shadowed` with it: with
|
||||
* `$outfit` written by an upstream wildcard, rewritten by an upstream
|
||||
* derivation, then rewritten again by a module in this node, the row reported
|
||||
* "0" — no badge at all — because the sibling map only ever counted siblings
|
||||
* and started from zero. A sibling that displaces an upstream writer has
|
||||
* overridden that writer PLUS everything it had already overridden.
|
||||
*/
|
||||
const allVarProducers = computed<Record<string, VarProducerLike>>(() => {
|
||||
const upstream = props.upstreamProducers ?? {};
|
||||
const merged: Record<string, VarProducerLike> = { ...upstream };
|
||||
for (const [name, sib] of Object.entries(siblingVarInfo.value.producers)) {
|
||||
const up = upstream[name];
|
||||
merged[name] = up
|
||||
? { ...sib, shadowed: sib.shadowed + up.shadowed + 1 }
|
||||
: sib;
|
||||
}
|
||||
return merged;
|
||||
});
|
||||
|
||||
function clearDragHover() {
|
||||
@@ -1593,6 +1704,17 @@ async function duplicateBundle(uid: string): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
/** Human message for a failed bundle-snapshot fetch. A 404 means the
|
||||
* library row is gone (deleted, or re-imported under a fresh uuid), which
|
||||
* the raw API text doesn't say — and re-linking, not retrying, is the fix.
|
||||
* Anything else falls back to the raw message. */
|
||||
function bundleResetErrorMessage(e: unknown, name: string): string {
|
||||
if (e instanceof ApiError && e.status === 404) {
|
||||
return `Can't reset "${name || "bundle"}" — its library bundle no longer exists. Re-link it first.`;
|
||||
}
|
||||
return `Reset failed: ${e instanceof Error ? e.message : String(e)}`;
|
||||
}
|
||||
|
||||
/** Reset bundle to library snapshot — re-fetch the library entry
|
||||
* + replace current children with the frozen blob. Drops any user
|
||||
* edits made to bundle children since insert. Confirms first since
|
||||
@@ -1601,6 +1723,17 @@ async function resetBundleToLibrary(uid: string): Promise<void> {
|
||||
const bundles = value.value.bundles ?? [];
|
||||
const target = bundles.find((b) => b._uid === uid);
|
||||
if (!target) return;
|
||||
// Guard: a detached/unlinked instance (empty library_id — e.g. a bundle
|
||||
// whose section was never linked, or whose library row was re-imported
|
||||
// under a new uuid) has nothing to fetch. Refuse instead of fetching an
|
||||
// empty snapshot and wiping the live children. Re-link is the recovery.
|
||||
if (!target.library_id) {
|
||||
pushToast(
|
||||
`Can't reset "${target.name || "bundle"}" — it isn't linked to a library bundle. Re-link it first.`,
|
||||
{ severity: "error" },
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Delta-undo capture: keep the old child refs (their _uids will be
|
||||
// discarded by the reset since the new library snapshot stamps
|
||||
// fresh ones, but the BundleInstance _uid we re-find by below
|
||||
@@ -1624,6 +1757,17 @@ async function resetBundleToLibrary(uid: string): Promise<void> {
|
||||
// local work.
|
||||
try {
|
||||
const entry = await api.bundles.get(target.library_id);
|
||||
// Guard: never wipe the live children with an empty snapshot. A valid
|
||||
// library bundle always resolves at least one child; an empty/missing
|
||||
// `children` means the fetch resolved to the wrong shape (broken link,
|
||||
// list wrapper, stale row). Abort the destructive replace + tell the user.
|
||||
if (!Array.isArray(entry.children) || entry.children.length === 0) {
|
||||
pushToast(
|
||||
`Can't reset "${target.name || "bundle"}" — the library snapshot came back empty (its link may be broken). Re-link the bundle instead.`,
|
||||
{ severity: "error" },
|
||||
);
|
||||
return;
|
||||
}
|
||||
const libEntry: BundleLibraryEntry = {
|
||||
id: entry.id,
|
||||
name: entry.name,
|
||||
@@ -1771,8 +1915,7 @@ async function resetBundleToLibrary(uid: string): Promise<void> {
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
pushToast(`Reset failed: ${msg}`, { severity: "error" });
|
||||
pushToast(bundleResetErrorMessage(e, target.name), { severity: "error" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1791,6 +1934,18 @@ async function resetChildToBundleSnapshot(idx: number): Promise<void> {
|
||||
if (!bundle) return;
|
||||
const posInBundle = idx - bundle.start_idx;
|
||||
if (posInBundle < 0) return;
|
||||
// Guard: mirrors resetBundleToLibrary. An unlinked/detached BundleInstance
|
||||
// carries an empty `library_id`; fetching it builds `/wp/api/bundles/` whose
|
||||
// trailing slash normalizes to the collection route, so aiohttp reports
|
||||
// "No such API route: /wp/api/bundles" — a nonsense message for the user.
|
||||
// Refuse up front and name the real recovery.
|
||||
if (!bundle.library_id) {
|
||||
pushToast(
|
||||
`Can't reset "${bundle.name || "bundle"}" children — it isn't linked to a library bundle. Re-link it first.`,
|
||||
{ severity: "error" },
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Delta-undo capture: the original module ref keeps its `_uid` so
|
||||
// Undo can find it in live state regardless of position. Reset
|
||||
// only swaps payload/instance/payload_hash; the _uid stays put,
|
||||
@@ -1830,8 +1985,7 @@ async function resetChildToBundleSnapshot(idx: number): Promise<void> {
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
pushToast(`Reset failed: ${msg}`, { severity: "error" });
|
||||
pushToast(bundleResetErrorMessage(e, bundle.name), { severity: "error" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1922,21 +2076,39 @@ function openBundleContextMenu(ev: MouseEvent, uid: string): void {
|
||||
onSelect: () => toggleBundleEnabled(uid, !target.enabled),
|
||||
divider: true,
|
||||
},
|
||||
{
|
||||
label: "Reset to library snapshot",
|
||||
icon: "pi-refresh",
|
||||
subtitle: "Replace children with frozen library state",
|
||||
onSelect: () => { void resetBundleToLibrary(uid); },
|
||||
},
|
||||
// The two library actions accent themselves to match the bundle's CURRENT
|
||||
// state, so the menu points at the recovery for the badge the user just
|
||||
// saw. Only one lights up: the states are ranked, since a bundle can be
|
||||
// several at once and two competing accents would say nothing.
|
||||
// missing → Push (re-link or add) — nothing to reset FROM
|
||||
// drifted → Reset (pull the library's newer version)
|
||||
// modified → Push (save your local edits up)
|
||||
(() => {
|
||||
const drifted = !isBundleMissingFromLibrary(target)
|
||||
&& isBundleLibraryDrifted(target);
|
||||
return {
|
||||
label: "Reset to library snapshot",
|
||||
icon: "pi-refresh",
|
||||
subtitle: drifted
|
||||
? "Library changed since insert — pull the newer version"
|
||||
: "Replace children with frozen library state",
|
||||
accent: drifted,
|
||||
onSelect: () => { void resetBundleToLibrary(uid); },
|
||||
};
|
||||
})(),
|
||||
(() => {
|
||||
const bundleMissing = isBundleMissingFromLibrary(target);
|
||||
const modified = !bundleMissing
|
||||
&& !isBundleLibraryDrifted(target)
|
||||
&& bundleSnapshotModified(target, value.value.modules);
|
||||
let subtitle = "Rename, retag, overwrite library entry";
|
||||
if (bundleMissing) subtitle = "Not linked to a library entry — re-link or add";
|
||||
else if (modified) subtitle = "Local edits since insert — save them to the library";
|
||||
return {
|
||||
label: "Push to library…",
|
||||
icon: "pi-cloud-upload",
|
||||
subtitle: bundleMissing
|
||||
? "Library entry deleted — re-add to library"
|
||||
: "Rename, retag, overwrite library entry",
|
||||
accent: bundleMissing,
|
||||
subtitle,
|
||||
accent: bundleMissing || modified,
|
||||
onSelect: () => openPushBundleToLibrary(uid),
|
||||
divider: true,
|
||||
};
|
||||
@@ -2187,9 +2359,16 @@ function conflictTooltip(id: string): string {
|
||||
* lives in `classifyOne` (import-export/collision).
|
||||
*/
|
||||
function matchStateOf(m: ModuleEntry): CollisionState | null {
|
||||
if (!m.payload_hash) return null;
|
||||
if (libraryHashes.value === null) return null;
|
||||
const live = libraryHashes.value[m.id];
|
||||
if (!m.payload_hash) {
|
||||
// No local hash. Only meaningful when the uuid IS in the library — a
|
||||
// workflow copy that lost its hash (malformed import, or a builder that
|
||||
// wrote payload_hash: ""). Treat as drift so the bulk "refresh drifted"
|
||||
// button relinks it. A genuinely inline module (fresh uuid, not in the
|
||||
// library) stays verdict-less exactly as before.
|
||||
return live ? "conflict" : null;
|
||||
}
|
||||
return classifyOne(
|
||||
m.type,
|
||||
m.payload_hash,
|
||||
@@ -2389,17 +2568,32 @@ function isBundleLibraryDrifted(bundle: BundleInstance): boolean {
|
||||
return live !== bundle.inserted_at_hash;
|
||||
}
|
||||
|
||||
/** True when the bundle's library entry has been deleted upstream —
|
||||
* the polled `bundleHashes` map no longer contains its uuid. Pairs
|
||||
* with `isMissingFromLibrary` for modules. Returns false until first
|
||||
* poll lands so we don't flash MISSING before the truth is known. */
|
||||
/** True when the bundle has NO live library entry behind it. Covers both
|
||||
* shapes of that: it carries a `library_id` the polled map no longer knows,
|
||||
* OR it carries no `library_id` at all.
|
||||
*
|
||||
* The second case used to early-return false, so an unlinked bundle could
|
||||
* never show MISSING — leaving MODIFIED as its only badge, which then
|
||||
* compared its children against a snapshot baseline from a library entry that
|
||||
* isn't there. "Modified against what?" was a fair question with no answer.
|
||||
*
|
||||
* Returns false until the first poll lands so we don't flash MISSING before
|
||||
* the truth is known. */
|
||||
function isBundleMissingFromLibrary(bundle: BundleInstance): boolean {
|
||||
const map = bundleHashes.value;
|
||||
if (map === null) return false;
|
||||
if (!bundle.library_id) return false;
|
||||
if (!bundle.library_id) return true;
|
||||
return !(bundle.library_id in map);
|
||||
}
|
||||
|
||||
/** True when the bundle never had a library entry to diverge FROM — no
|
||||
* `library_id` at all. MODIFIED is meaningless in that state: there is no
|
||||
* insert to be modified since. Distinct from "the entry was deleted", where
|
||||
* the local snapshot IS a real baseline and MOD still reads correctly. */
|
||||
function isBundleUnlinked(bundle: BundleInstance): boolean {
|
||||
return bundleHashes.value !== null && !bundle.library_id;
|
||||
}
|
||||
|
||||
// Pending confirm-dialog state. Single slot — only one destructive op
|
||||
// can be in flight at a time, and the bundle ctxmenu / header buttons
|
||||
// are synchronous enough that overlapping calls don't happen in
|
||||
@@ -2894,6 +3088,19 @@ function isLocked(m: ModuleEntry): boolean {
|
||||
function isInternal(m: ModuleEntry): boolean {
|
||||
return !!m.instance?.internal;
|
||||
}
|
||||
/** Kinds whose handlers honor `seed_scope: hold` — wildcard, combine,
|
||||
* fixed_values, and derivation (which freezes its frame-0 output across a
|
||||
* loop, constrained picks + nested @{} refs included). Now equal to
|
||||
* SEED_LOCKABLE_KINDS, but kept distinct on purpose: lock-the-seed and
|
||||
* hold-the-value are different concepts that could diverge again. Gates
|
||||
* the row context-menu's quick Hold item + which RuntimeSections render
|
||||
* the toggle. */
|
||||
const HOLD_KINDS: ReadonlySet<string> = new Set([
|
||||
"wildcard", "combine", "fixed_values", "derivation",
|
||||
]);
|
||||
function isHoldable(m: ModuleEntry): boolean {
|
||||
return HOLD_KINDS.has(m.type);
|
||||
}
|
||||
function isHeld(m: ModuleEntry): boolean {
|
||||
return m.instance?.seed_scope === "hold";
|
||||
}
|
||||
@@ -3777,6 +3984,29 @@ function toggleCollapsed(idx: number) {
|
||||
commitModules(list);
|
||||
}
|
||||
|
||||
// Quick "Hold across run" toggle from the row context menu — flips base
|
||||
// `instance.seed_scope` between hold/vary without opening the editor
|
||||
// (the 4-click → 2-click ask). Base-level only: when a loop edit-frame
|
||||
// is active, hold applies to every frame, so we no-op here exactly as
|
||||
// the RuntimeSection disables its toggle. Caller gates on isHoldable;
|
||||
// re-checked here so a stray call can't stamp seed_scope on a kind
|
||||
// (constraint/derivation) whose handler ignores it.
|
||||
function toggleHold(idx: number): void {
|
||||
if (currentFrame.value != null) return;
|
||||
const target = value.value.modules[idx];
|
||||
if (!target || !isHoldable(target)) return;
|
||||
const held = target.instance?.seed_scope === "hold";
|
||||
// Annotate so the literal doesn't widen to `string` in the object
|
||||
// literal — instance.seed_scope is the "vary" | "hold" union.
|
||||
const next: "vary" | "hold" = held ? "vary" : "hold";
|
||||
const list = value.value.modules.map((m, i) =>
|
||||
i === idx
|
||||
? { ...m, instance: { ...(m.instance ?? {}), seed_scope: next } }
|
||||
: m,
|
||||
);
|
||||
commitModules(list);
|
||||
}
|
||||
|
||||
/** Bulk collapse/expand. Used by the section-header chevron — one
|
||||
* click flips every card to the same state. Idempotent if all
|
||||
* cards already match the target state (the deep watcher will
|
||||
@@ -3860,7 +4090,7 @@ function openEditModal(idx: number) {
|
||||
editingIdx.value = idx;
|
||||
}
|
||||
|
||||
function saveEditedModule(updated: ModuleEntry & { _originalId?: string }) {
|
||||
function saveEditedModule(updated: ModuleEntry & { _originalId?: string; _relinkFrom?: string }) {
|
||||
// Phase B: index-based replacement — sibling rows share `m.id`, so
|
||||
// mapping `m.id === updated.id` would clobber every sibling at once.
|
||||
// We use `editingIdx` captured at modal-open to target the specific
|
||||
@@ -3871,8 +4101,13 @@ function saveEditedModule(updated: ModuleEntry & { _originalId?: string }) {
|
||||
editingIdx.value = null;
|
||||
return;
|
||||
}
|
||||
// `_relinkFrom` (the OLD id) is set only on the re-link path — after the
|
||||
// row is committed with its new id, walk the whole list so sibling @{}
|
||||
// refs + constraint source/target follow. Captured before we strip markers.
|
||||
const relinkFrom = updated._relinkFrom;
|
||||
const cleaned: ModuleEntry = { ...updated };
|
||||
delete (cleaned as { _originalId?: string })._originalId;
|
||||
delete (cleaned as { _relinkFrom?: string })._relinkFrom;
|
||||
const list = [...value.value.modules];
|
||||
const k = currentFrame.value;
|
||||
if (k == null) {
|
||||
@@ -3891,6 +4126,17 @@ function saveEditedModule(updated: ModuleEntry & { _originalId?: string }) {
|
||||
// a stale "override #k". No-op while the base stays locked.
|
||||
list[targetIdx] = dropRedundantFrameLockNulls(list[targetIdx]);
|
||||
commitModules(list);
|
||||
if (relinkFrom && relinkFrom !== updated.id) {
|
||||
// The re-linked row already carries its new id (list[targetIdx]); walk
|
||||
// EVERY module so sibling nested @{} refs + constraint source/target that
|
||||
// pointed at the old uuid follow to the library uuid. applyRelink leaves
|
||||
// the already-swapped row's id alone (its id !== relinkFrom).
|
||||
const remapped = applyRelink(
|
||||
value.value.modules as unknown as Record<string, unknown>[],
|
||||
{ oldId: relinkFrom, newId: updated.id, newPayloadHash: updated.payload_hash ?? "" },
|
||||
) as unknown as ModuleEntry[];
|
||||
commitModules(remapped);
|
||||
}
|
||||
if (updated._originalId && updated._originalId !== updated.id) {
|
||||
nextTick(() => {
|
||||
const el = document.querySelector<HTMLElement>(
|
||||
@@ -4120,6 +4366,26 @@ function openContextMenu(ev: MouseEvent, m: ModuleEntry, idx: number) {
|
||||
const items: ContextMenuItem[] = [
|
||||
{ label: "Edit", icon: "pi-pencil", onSelect: () => openEditModal(idx) },
|
||||
];
|
||||
// Quick Hold toggle — kept at the top so it's a 2-click reach
|
||||
// (right-click → Hold) instead of opening the editor and digging into
|
||||
// Runtime. Only for kinds that honor seed_scope. Hold is base-level;
|
||||
// when a loop edit-frame is active it applies to every frame, so we
|
||||
// surface it disabled with a hint rather than silently writing it.
|
||||
if (isHoldable(m)) {
|
||||
const held = isHeld(m);
|
||||
const frameActive = currentFrame.value != null;
|
||||
items.push({
|
||||
label: held ? "Release hold" : "Hold across run",
|
||||
icon: "pi-link",
|
||||
disabled: frameActive,
|
||||
subtitle: frameActive
|
||||
? "Applies to every frame — switch to base to change"
|
||||
: held
|
||||
? undefined
|
||||
: "Freeze this value for the whole batch",
|
||||
onSelect: () => toggleHold(idx),
|
||||
});
|
||||
}
|
||||
// Refresh + Save are mutually exclusive in normal use (a module is
|
||||
// either drifted OR missing OR clean), so hiding the inactive entry
|
||||
// beats greying it — matches Save's existing conditional-push pattern
|
||||
@@ -4128,6 +4394,10 @@ function openContextMenu(ev: MouseEvent, m: ModuleEntry, idx: number) {
|
||||
items.push({
|
||||
label: "Refresh from library",
|
||||
icon: "pi-refresh",
|
||||
// Accented + explained: drift is the state where the menu HAS the fix
|
||||
// for the badge the user just saw, so it should say so.
|
||||
subtitle: "Library changed since insert — pull the newer version",
|
||||
accent: true,
|
||||
onSelect: () => { void refreshOne(idx); },
|
||||
divider: true,
|
||||
});
|
||||
@@ -4140,11 +4410,17 @@ function openContextMenu(ev: MouseEvent, m: ModuleEntry, idx: number) {
|
||||
// greys out the "Update existing" button when payload_hash is empty.
|
||||
if (!!m.payload) {
|
||||
const missing = isMissingFromLibrary(m);
|
||||
// Local overrides with no drift → pushing is what the user probably wants.
|
||||
// Ranked below `missing` so only one library action ever accents.
|
||||
const modified = !missing && !isDrifted(m) && isModified(m);
|
||||
let subtitle: string | undefined;
|
||||
if (missing) subtitle = "Not linked to a library entry — re-link or add";
|
||||
else if (modified) subtitle = "Local edits since insert — save them to the library";
|
||||
items.push({
|
||||
label: "Push to library…",
|
||||
icon: "pi-cloud-upload",
|
||||
subtitle: missing ? "Library entry deleted — re-add as new entry" : undefined,
|
||||
accent: missing,
|
||||
subtitle,
|
||||
accent: missing || modified,
|
||||
onSelect: () => openPushToLibrary(idx),
|
||||
divider: true,
|
||||
});
|
||||
@@ -4814,6 +5090,17 @@ const moduleRowCtx: ModuleRowCtx = {
|
||||
frameEnableOverride,
|
||||
};
|
||||
provide(ModuleRowCtxKey, moduleRowCtx);
|
||||
// Pools this node holds, for the nested-ref hover card. Provided rather than
|
||||
// threaded: `RefChip` sits six components below here (row → edit modal →
|
||||
// section → value chips → preview → chip) and not one layer in between has any
|
||||
// business knowing about option pools. Recomputes with the module list, so
|
||||
// picking or removing a wildcard moves the card's numbers immediately.
|
||||
provide(CONTEXT_POOLS_KEY, computed(() => buildContextPools(value.value.modules)));
|
||||
// Companion lookup for the same card: when the ref falls back to the library,
|
||||
// this names any OTHER node holding the pool, so "why isn't it using the one
|
||||
// I can see right there" has an answer on the card instead of being a puzzle.
|
||||
provide(FOREIGN_POOL_LOOKUP_KEY, (uuid: string): string[] =>
|
||||
props.wildcardHomesReader?.(uuid) ?? []);
|
||||
// Seed source for the edit-modal's Lock button — resolves the seed the module
|
||||
// actually rolled (frame #k's captured seed when a frame is active, else the
|
||||
// last-run seed) so locking pins what the user saw, not a random number.
|
||||
@@ -4831,7 +5118,10 @@ const bundleFrameCtx: BundleFrameCtx = {
|
||||
bundleLockState,
|
||||
bundleHeaderGap,
|
||||
isBundleDropTarget,
|
||||
isBundleSnapshotModified: (b: BundleInstance) => bundleSnapshotModified(b, value.value.modules),
|
||||
// Suppressed for an unlinked bundle — there is no insert for its children to
|
||||
// have diverged from, so MOD would be diffing against a ghost.
|
||||
isBundleSnapshotModified: (b: BundleInstance) =>
|
||||
!isBundleUnlinked(b) && bundleSnapshotModified(b, value.value.modules),
|
||||
recentDropUids,
|
||||
pulseDelayFor,
|
||||
toggleBundleCollapsed,
|
||||
@@ -5080,6 +5370,7 @@ provide(BundleFrameCtxKey, bundleFrameCtx);
|
||||
:visible="editingModule !== null"
|
||||
:module="editingModule"
|
||||
:upstream-vars="upstreamVars"
|
||||
:upstream-producers="allVarProducers"
|
||||
:upstream-resolved="resolvedForEditing"
|
||||
:sibling-vars="siblingNodeVars"
|
||||
:sibling-modules="value.modules"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onBeforeUnmount } from "vue";
|
||||
import { ref, computed, watch } from "vue";
|
||||
|
||||
import ModalShell from "../shared/ModalShell.vue";
|
||||
import type { ModuleEntry, ModuleEntryKind } from "../../widgets/_shared";
|
||||
@@ -18,6 +18,7 @@ import CombineInstanceModal from "./editors/combine/CombineInstanceModal.vue";
|
||||
import DerivationInstanceModal from "./editors/derivation/DerivationInstanceModal.vue";
|
||||
import ConstraintInstanceModal from "./editors/constraint/ConstraintInstanceModal.vue";
|
||||
import type { ChainModule, PairingBadge } from "../../extension/constraint-pairs";
|
||||
import type { VarProducerLike } from "../../manager/components/RefChip.vue";
|
||||
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -25,6 +26,9 @@ const props = defineProps<{
|
||||
module: ModuleEntry | null;
|
||||
/** Variable names defined upstream — used for autocomplete + validity checks. */
|
||||
upstreamVars?: string[];
|
||||
/** `$var` → its producing module + node. Forwarded to the per-kind modals so
|
||||
* var chips can name where a value comes from. */
|
||||
upstreamProducers?: Record<string, VarProducerLike>;
|
||||
/** Resolved upstream `$name → value` map. Combine modal uses this
|
||||
* to render a live preview pane with vars substituted. */
|
||||
upstreamResolved?: Record<string, ResolvedValue>;
|
||||
@@ -76,15 +80,14 @@ watch([() => props.visible, () => props.module], () => {
|
||||
// editing the draft is mutated locally; props.module identity is stable, so
|
||||
// this does not clobber in-progress edits.)
|
||||
draft.value = JSON.parse(JSON.stringify(props.module));
|
||||
window.addEventListener("keydown", onKeydown);
|
||||
} else {
|
||||
window.removeEventListener("keydown", onKeydown);
|
||||
draft.value = null;
|
||||
}
|
||||
}, { immediate: true });
|
||||
|
||||
onBeforeUnmount(() => window.removeEventListener("keydown", onKeydown));
|
||||
|
||||
// Keys arrive from ModalShell, not from window: the modal shield stops
|
||||
// inside-modal keys at the overlay so they cannot reach ComfyUI's global
|
||||
// shortcuts, which means a window listener here would never fire.
|
||||
function onKeydown(ev: KeyboardEvent) {
|
||||
if (!props.visible) return;
|
||||
if ((ev.ctrlKey || ev.metaKey) && ev.key === "Enter") {
|
||||
@@ -249,7 +252,7 @@ function onSaveToLibraryClick(): void {
|
||||
}
|
||||
|
||||
interface PushSaveResult {
|
||||
mode: "update" | "fork" | "reattach";
|
||||
mode: "update" | "fork" | "reattach" | "relink";
|
||||
id: string;
|
||||
payload_hash: string;
|
||||
bundles_updated: string[];
|
||||
@@ -263,12 +266,17 @@ function onPushToLibrarySaved(result: PushSaveResult): void {
|
||||
return;
|
||||
}
|
||||
setLibraryHash(result.id, result.payload_hash);
|
||||
if (result.mode === "fork" || result.mode === "reattach") {
|
||||
if (result.mode === "fork" || result.mode === "reattach" || result.mode === "relink") {
|
||||
// Fork: the new entry replaces the draft's identity; `_originalId`
|
||||
// lets saveEditedModule swap the row by old id during the next
|
||||
// save(). Reattach: same wiring — the dead uuid gets swapped for
|
||||
// the new one so MISSING clears.
|
||||
(draft.value as ModuleEntry & { _originalId?: string })._originalId = draft.value.id;
|
||||
// the new one so MISSING clears. Relink: point the detached row at an
|
||||
// EXISTING library uuid; `_relinkFrom` (the OLD id, captured before the
|
||||
// swap) additionally tells saveEditedModule to remap sibling @{} refs +
|
||||
// constraint source/target so cross-references follow the new uuid.
|
||||
const marked = draft.value as ModuleEntry & { _originalId?: string; _relinkFrom?: string };
|
||||
marked._originalId = draft.value.id;
|
||||
if (result.mode === "relink") marked._relinkFrom = draft.value.id;
|
||||
draft.value.id = result.id;
|
||||
draft.value.payload_hash = result.payload_hash;
|
||||
draft.value.meta = {
|
||||
@@ -279,7 +287,9 @@ function onPushToLibrarySaved(result: PushSaveResult): void {
|
||||
pushToast(
|
||||
result.mode === "reattach"
|
||||
? `Re-attached "${result.name}" to library`
|
||||
: `Saved as new library entry "${result.name}"`,
|
||||
: result.mode === "relink"
|
||||
? `Re-linked "${result.name}" to library`
|
||||
: `Saved as new library entry "${result.name}"`,
|
||||
{ severity: "success" },
|
||||
);
|
||||
save();
|
||||
@@ -391,7 +401,7 @@ function cancel() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ModalShell :visible="visible" @close="cancel">
|
||||
<ModalShell :visible="visible" @close="cancel" @keydown="onKeydown">
|
||||
<!-- Column so the frame banner stacks ABOVE the per-kind modal card
|
||||
(each per-kind modal renders a plain card; ModalShell's wrapper is
|
||||
a centered flex ROW, so a bare banner sibling would land beside the
|
||||
@@ -417,6 +427,7 @@ function cancel() {
|
||||
:module="draft"
|
||||
:is-modified="instanceModified"
|
||||
:upstream-vars="upstreamVars"
|
||||
:upstream-producers="upstreamProducers"
|
||||
:sibling-vars="siblingVars"
|
||||
:via-option-pairs="viaOptionPairs"
|
||||
:frame-active="currentFrame != null"
|
||||
@@ -448,6 +459,7 @@ function cancel() {
|
||||
:module="draft"
|
||||
:is-modified="instanceModified"
|
||||
:upstream-vars="upstreamVars"
|
||||
:upstream-producers="upstreamProducers"
|
||||
:upstream-resolved="upstreamResolved"
|
||||
:sibling-vars="siblingVars"
|
||||
:frame-active="currentFrame != null"
|
||||
@@ -470,6 +482,7 @@ function cancel() {
|
||||
:module="draft"
|
||||
:is-modified="instanceModified"
|
||||
:upstream-vars="upstreamVars"
|
||||
:upstream-producers="upstreamProducers"
|
||||
:sibling-vars="siblingVars"
|
||||
:via-option-pairs="viaOptionPairs"
|
||||
:frame-active="currentFrame != null"
|
||||
|
||||
@@ -316,7 +316,14 @@
|
||||
:data-kind="byId.get(id)?.type"
|
||||
>
|
||||
<span class="wp-picker__sel-dot"></span>
|
||||
{{ byId.get(id)?.name ?? id }}
|
||||
<!-- Wrapped in its own span so it can ellipsis-clip. As a bare
|
||||
text node it wrapped onto a second line inside a chip fixed at
|
||||
22px tall, so a long name like "Accent piece (color-neutral)"
|
||||
spilled out of its own pill. -->
|
||||
<span
|
||||
class="wp-picker__sel-name"
|
||||
:title="byId.get(id)?.name ?? id"
|
||||
>{{ byId.get(id)?.name ?? id }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="wp-picker__sel-close"
|
||||
@@ -1443,6 +1450,12 @@ onBeforeUnmount(detachCaptureListeners);
|
||||
font-weight: 500;
|
||||
max-width: 200px;
|
||||
}
|
||||
.wp-picker__sel-name {
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.wp-picker__sel-dot {
|
||||
width: 7px; height: 7px;
|
||||
border-radius: 999px;
|
||||
|
||||
@@ -433,7 +433,10 @@ const multiEntryTitle = computed<string>(() =>
|
||||
|
||||
.wp-pair-pop {
|
||||
position: fixed;
|
||||
z-index: 9999;
|
||||
/* Hover-card tier — above the popover tier (10020), since a pair badge can
|
||||
be rendered inside a popover and its card must clear it. Matches
|
||||
RefChip's hover card. */
|
||||
z-index: 10030;
|
||||
width: 280px;
|
||||
padding: 8px 10px;
|
||||
background: var(--wp-bg-1, var(--wp-bg2, #1a1d24));
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* PushBundleToLibraryModal — bundle re-link (D3a bundle side).
|
||||
*
|
||||
* A workflow BundleInstance is "detached" when its `library_id` is no longer
|
||||
* in the polled `bundleHashes` map (a re-import minted a fresh uuid). Its
|
||||
* `inserted_at_hash` IS the library bundle's payload_hash at insert time, so
|
||||
* a content-identical library bundle under a DIFFERENT uuid matches on it —
|
||||
* the same signal the module re-link uses.
|
||||
*/
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
|
||||
vi.mock("#comfyui/app", () => ({
|
||||
app: { graph: { _nodes: [], _nodes_by_id: {} } },
|
||||
}));
|
||||
|
||||
import PushBundleToLibraryModal from "./PushBundleToLibraryModal.vue";
|
||||
import { bundleHashes } from "./drift-store";
|
||||
import type { BundleInstance } from "../../widgets/_shared";
|
||||
|
||||
function makeBundle(over: Partial<BundleInstance> = {}): BundleInstance {
|
||||
return {
|
||||
_uid: "buid0001",
|
||||
library_id: "dead0001",
|
||||
name: "Environments",
|
||||
color: null,
|
||||
enabled: true,
|
||||
collapsed: false,
|
||||
parent_uid: null,
|
||||
start_idx: 0,
|
||||
end_idx: 0,
|
||||
inserted_at_hash: "HASH_A",
|
||||
...over,
|
||||
} as BundleInstance;
|
||||
}
|
||||
|
||||
function resetBody(): void {
|
||||
while (document.body.firstChild) document.body.removeChild(document.body.firstChild);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetBody();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
resetBody();
|
||||
bundleHashes.value = null;
|
||||
});
|
||||
|
||||
async function openModal(bundle: BundleInstance | null) {
|
||||
const wrap = mount(PushBundleToLibraryModal, {
|
||||
attachTo: document.body,
|
||||
props: { open: false, bundle: null, childrenForLibrary: [], childrenPreview: [] },
|
||||
});
|
||||
await wrap.setProps({ open: true, bundle, childrenForLibrary: [], childrenPreview: [] });
|
||||
await flushPromises();
|
||||
return wrap;
|
||||
}
|
||||
|
||||
describe("PushBundleToLibraryModal re-link", () => {
|
||||
it("offers re-link to a content-identical library bundle when detached", async () => {
|
||||
// A DIFFERENT uuid carries this instance's inserted_at_hash.
|
||||
bundleHashes.value = { live0001: "HASH_A" };
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo) => {
|
||||
const url = typeof input === "string" ? input : input.toString();
|
||||
if (url.includes("/wp/api/bundles")) {
|
||||
return new Response(
|
||||
JSON.stringify({ items: [{ id: "live0001", name: "Environments" }] }),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } },
|
||||
);
|
||||
}
|
||||
return new Response("{}", { status: 200 });
|
||||
}));
|
||||
|
||||
const wrap = await openModal(makeBundle());
|
||||
await flushPromises();
|
||||
|
||||
expect(document.querySelector('[data-test="pbtl-relink"]')).not.toBeNull();
|
||||
|
||||
document.querySelector<HTMLButtonElement>('[data-test="pbtl-relink-confirm"]')!.click();
|
||||
await flushPromises();
|
||||
|
||||
const saved = wrap.emitted("saved");
|
||||
expect(saved).toBeTruthy();
|
||||
const result = saved![0][0] as { mode: string; id: string; origId: string };
|
||||
expect(result.mode).toBe("relink");
|
||||
expect(result.id).toBe("live0001");
|
||||
expect(result.origId).toBe("dead0001");
|
||||
wrap.unmount();
|
||||
});
|
||||
|
||||
it("does NOT offer re-link when the bundle is still linked", async () => {
|
||||
// library_id present in the live map → not detached.
|
||||
bundleHashes.value = { dead0001: "HASH_A" };
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response("{}", { status: 200 })));
|
||||
const wrap = await openModal(makeBundle());
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-test="pbtl-relink"]')).toBeNull();
|
||||
wrap.unmount();
|
||||
});
|
||||
|
||||
it("does NOT offer re-link when no library bundle matches the content", async () => {
|
||||
bundleHashes.value = { live0009: "OTHER_HASH" };
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo) => {
|
||||
const url = typeof input === "string" ? input : input.toString();
|
||||
if (url.includes("/wp/api/bundles")) {
|
||||
return new Response(
|
||||
JSON.stringify({ items: [{ id: "live0009", name: "Unrelated" }] }),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } },
|
||||
);
|
||||
}
|
||||
return new Response("{}", { status: 200 });
|
||||
}));
|
||||
const wrap = await openModal(makeBundle({ name: "Environments" }));
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-test="pbtl-relink"]')).toBeNull();
|
||||
wrap.unmount();
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,12 @@
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { bundleHashes } from "./drift-store";
|
||||
import { api } from "../../manager/api/client";
|
||||
import {
|
||||
findRelinkCandidates,
|
||||
autoRelinkTarget,
|
||||
type RelinkCandidate,
|
||||
} from "../../manager/import-export/relink-match";
|
||||
import { bundleContentKey } from "./bundles/bundle-fingerprint";
|
||||
import type { BundleInstance } from "../../widgets/_shared";
|
||||
import WpCheck from "@/components/shared/WpCheck.vue";
|
||||
|
||||
@@ -51,10 +57,12 @@ interface SaveResult {
|
||||
* "(copy)" suffix; workflow row keeps its old library_id. `reattach`
|
||||
* — POST when source entry was missing; no copy suffix, caller
|
||||
* should rebind the workflow row's library_id to the new uuid so
|
||||
* MISSING clears. */
|
||||
mode: "update" | "fork" | "reattach";
|
||||
/** New library uuid when forking/reattaching; same as bundle.library_id
|
||||
* when updating. */
|
||||
* MISSING clears. `relink` — no write: point the detached instance at
|
||||
* an EXISTING content-identical library bundle; caller rebinds
|
||||
* library_id + inserted_at_hash. */
|
||||
mode: "update" | "fork" | "reattach" | "relink";
|
||||
/** New library uuid when forking/reattaching/re-linking; same as
|
||||
* bundle.library_id when updating. */
|
||||
id: string;
|
||||
/** payload_hash returned by the server. */
|
||||
payload_hash: string;
|
||||
@@ -122,10 +130,120 @@ const isLibraryMissing = computed(() => {
|
||||
return !(props.bundle.library_id in bundleHashes.value);
|
||||
});
|
||||
|
||||
/** Whether to OFFER the re-link picker — the bundle-side mirror of the module
|
||||
* modal's `needsRelink`. Wider than `isLibraryMissing`, which additionally
|
||||
* requires a `library_id`: a bundle that lost its link (shared workflow,
|
||||
* stale cache) still corresponds to a library entry, and matching it on child
|
||||
* content is what `bundleContentKey` is for. Costs nothing when there is no
|
||||
* match — the picker only renders once candidates come back. */
|
||||
const needsRelink = computed(() => {
|
||||
const b = props.bundle;
|
||||
if (!b || bundleHashes.value === null) return false;
|
||||
return !b.library_id || !(b.library_id in bundleHashes.value);
|
||||
});
|
||||
|
||||
const canUpdateExisting = computed(
|
||||
() => isLibraryTracked.value && !isLibraryMissing.value,
|
||||
);
|
||||
|
||||
/** uuid -> display name for every live library bundle, fetched once when the
|
||||
* instance turns out to be detached. `bundleHashes` carries the content hash
|
||||
* but not names, so the re-link picker needs this to label + weakly-match. */
|
||||
const relinkNames = ref<Map<string, { name: string; type: string }>>(new Map());
|
||||
|
||||
/** uuid → child-content key for every live library bundle. Only consulted when
|
||||
* the instance carries no `inserted_at_hash`. */
|
||||
const relinkContentKeys = ref<Map<string, string>>(new Map());
|
||||
|
||||
async function fetchBundleNames(): Promise<void> {
|
||||
try {
|
||||
const res = await fetch("/wp/api/bundles");
|
||||
if (!res.ok) return;
|
||||
const data = (await res.json()) as
|
||||
| { items?: Array<{ id?: string; name?: string; children?: unknown }> }
|
||||
| Array<{ id?: string; name?: string; children?: unknown }>;
|
||||
const items = Array.isArray(data) ? data : (data.items ?? []);
|
||||
const next = new Map<string, { name: string; type: string }>();
|
||||
const keys = new Map<string, string>();
|
||||
for (const it of items) {
|
||||
if (typeof it.id === "string" && it.id) {
|
||||
next.set(it.id, { name: it.name ?? "", type: "bundle" });
|
||||
if (Array.isArray(it.children)) {
|
||||
keys.set(it.id, bundleContentKey(
|
||||
it.children as Array<{ type?: string; payload_hash?: string }>,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
relinkNames.value = next;
|
||||
relinkContentKeys.value = keys;
|
||||
} catch {
|
||||
/* network — leave empty; no re-link offered */
|
||||
}
|
||||
}
|
||||
|
||||
/** Content-aware re-link candidates for a DETACHED bundle instance. The
|
||||
* instance's `inserted_at_hash` IS the library bundle's payload_hash at
|
||||
* insert time, so an identical-content library bundle under a different uuid
|
||||
* matches on it exactly — the same signal the module re-link uses. */
|
||||
const relinkCandidates = computed<RelinkCandidate[]>(() => {
|
||||
const b = props.bundle;
|
||||
if (!b || !needsRelink.value || bundleHashes.value === null) return [];
|
||||
const live: Record<string, { type?: string; payload_hash: string; contentKey?: string }> = {};
|
||||
for (const [uuid, h] of Object.entries(bundleHashes.value)) {
|
||||
live[uuid] = { type: "bundle", payload_hash: h, contentKey: relinkContentKeys.value.get(uuid) };
|
||||
}
|
||||
return findRelinkCandidates(
|
||||
{
|
||||
id: b.library_id,
|
||||
type: "bundle",
|
||||
payload_hash: b.inserted_at_hash,
|
||||
// Only when there's no stored hash to compare — the server hash stays
|
||||
// authoritative whenever it exists.
|
||||
contentKey: b.inserted_at_hash
|
||||
? undefined
|
||||
: bundleContentKey(
|
||||
props.childrenForLibrary as Array<{ type?: string; payload_hash?: string }>,
|
||||
),
|
||||
name: b.name ?? "",
|
||||
},
|
||||
live,
|
||||
(u) => relinkNames.value.get(u),
|
||||
);
|
||||
});
|
||||
|
||||
const relinkAuto = computed(() => autoRelinkTarget(relinkCandidates.value));
|
||||
const relinkPick = ref<RelinkCandidate | null>(null);
|
||||
const relinkQuery = ref<string>("");
|
||||
const relinkFiltered = computed<RelinkCandidate[]>(() => {
|
||||
const q = relinkQuery.value.trim().toLowerCase();
|
||||
if (!q) return relinkCandidates.value;
|
||||
return relinkCandidates.value.filter(
|
||||
(c) => c.name.toLowerCase().includes(q) || c.uuid.toLowerCase().includes(q),
|
||||
);
|
||||
});
|
||||
const relinkTarget = computed<RelinkCandidate | null>(
|
||||
() => relinkPick.value ?? relinkAuto.value,
|
||||
);
|
||||
|
||||
/** Danger tone only when nothing can be reconnected — a re-linkable bundle is
|
||||
* a routine state, and red steered users toward the duplicate-making path. */
|
||||
const relinkNoteClass = computed(() =>
|
||||
relinkCandidates.value.length > 0 ? "wp-ptl-note--info" : "wp-ptl-note--danger",
|
||||
);
|
||||
|
||||
function doRelink(): void {
|
||||
const t = relinkTarget.value;
|
||||
if (!t || !props.bundle) return;
|
||||
emit("saved", {
|
||||
mode: "relink",
|
||||
id: t.uuid,
|
||||
payload_hash: t.payloadHash,
|
||||
name: t.name,
|
||||
origId: props.bundle.library_id,
|
||||
});
|
||||
}
|
||||
|
||||
const tagsParsed = computed<string[]>(() =>
|
||||
tagsText.value
|
||||
.split(",")
|
||||
@@ -144,8 +262,17 @@ function resetForm(): void {
|
||||
// into library, so we make the safer choice the default and let the
|
||||
// user opt out.
|
||||
cascadeEnabled.value = cascadeAvailable.value;
|
||||
relinkPick.value = null;
|
||||
relinkQuery.value = "";
|
||||
}
|
||||
|
||||
// Re-link candidates only matter for a DETACHED instance — skip the extra
|
||||
// library-list fetch when the bundle is tracked + present. A drift poll can
|
||||
// flip it to detached after open, so also fetch the first time that happens.
|
||||
watch(needsRelink, (missing) => {
|
||||
if (props.open && missing && relinkNames.value.size === 0) void fetchBundleNames();
|
||||
});
|
||||
|
||||
/** Seed description + tags from the live library entry when the
|
||||
* bundle is tracked. Skips on missing — the entry is gone. Only
|
||||
* fills empty form fields so a mid-edit doesn't get clobbered. */
|
||||
@@ -170,6 +297,7 @@ watch(
|
||||
if (!isOpen) return;
|
||||
resetForm();
|
||||
void seedFromLibrary();
|
||||
if (needsRelink.value) void fetchBundleNames();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -438,10 +566,68 @@ onBeforeUnmount(() => window.removeEventListener("keydown", onKey));
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div v-if="isLibraryMissing" class="wp-ptl-note wp-ptl-note--danger" data-test="pbtl-missing">
|
||||
The library entry for this bundle has been deleted upstream.
|
||||
"Update existing" is unavailable — use "Save as new entry" to
|
||||
re-add it to the library.
|
||||
<div
|
||||
v-if="needsRelink && relinkCandidates.length"
|
||||
class="wp-ptl-relink"
|
||||
data-test="pbtl-relink"
|
||||
>
|
||||
<div class="wp-ptl-relink__title">Re-link to an existing library bundle</div>
|
||||
<p class="wp-ptl-relink__hint">
|
||||
This bundle's content matches a library entry under a different id (a re-import
|
||||
minted a new one). Re-link to reconnect drift + reset instead of adding a duplicate.
|
||||
</p>
|
||||
<input
|
||||
v-if="relinkCandidates.length > 1"
|
||||
v-model="relinkQuery"
|
||||
type="text"
|
||||
class="wp-ptl-input"
|
||||
data-test="pbtl-relink-search"
|
||||
placeholder="Search by name or id…"
|
||||
aria-label="Search library bundles to re-link"
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<ul class="wp-ptl-relink__list">
|
||||
<li
|
||||
v-for="c in relinkFiltered"
|
||||
:key="c.uuid"
|
||||
class="wp-ptl-relink__cand"
|
||||
:class="{ 'is-picked': relinkTarget != null && relinkTarget.uuid === c.uuid }"
|
||||
data-test="pbtl-relink-candidate"
|
||||
@click="relinkPick = c"
|
||||
>
|
||||
<span class="wp-ptl-relink__name">{{ c.name || "(unnamed)" }}</span>
|
||||
<code class="wp-ptl-relink__uuid">{{ c.uuid }}</code>
|
||||
<span
|
||||
class="wp-ptl-relink__tag"
|
||||
:class="c.contentIdentical ? 'is-identical' : 'is-diff'"
|
||||
>{{ c.contentIdentical ? "identical" : "content differs" }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<button
|
||||
type="button"
|
||||
class="wp-ptl-btn wp-ptl-btn--primary"
|
||||
data-test="pbtl-relink-confirm"
|
||||
:disabled="!relinkTarget || undefined"
|
||||
@click="doRelink"
|
||||
>Re-link<template v-if="relinkTarget"> to “{{ relinkTarget.name || relinkTarget.uuid }}”</template></button>
|
||||
</div>
|
||||
|
||||
<!-- States the observable fact, not a guessed cause — see the
|
||||
matching note in PushToLibraryModal. Danger tone only when
|
||||
there is genuinely nothing to reconnect to. -->
|
||||
<div v-if="needsRelink" class="wp-ptl-note" :class="relinkNoteClass" data-test="pbtl-missing">
|
||||
<template v-if="relinkCandidates.length > 0">
|
||||
This bundle isn’t linked to any library entry under its recorded id.
|
||||
{{ relinkTarget?.contentIdentical
|
||||
? "A library bundle with identical children is selected above — re-linking reconnects them."
|
||||
: "Pick a match above to re-link, or save it as a new entry." }}
|
||||
</template>
|
||||
<template v-else>
|
||||
This bundle isn’t linked to any library entry under its recorded id, and
|
||||
nothing in the library matches its children or name. “Update existing” is
|
||||
unavailable — “Save as new entry” adds it to the library.
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div v-if="errorMsg" class="wp-ptl-error" data-test="pbtl-error">
|
||||
@@ -538,7 +724,7 @@ onBeforeUnmount(() => window.removeEventListener("keydown", onKey));
|
||||
font-family: inherit;
|
||||
}
|
||||
.wp-ptl-input:focus { outline: 1px solid var(--wp-accent-500, #8b5cf6); }
|
||||
.wp-ptl-input--multi { resize: vertical; min-height: 48px; }
|
||||
.wp-ptl-input--multi { resize: vertical; overscroll-behavior: contain; min-height: 48px; }
|
||||
.wp-ptl-children {
|
||||
margin: 0;
|
||||
padding: 6px 8px;
|
||||
@@ -630,6 +816,50 @@ onBeforeUnmount(() => window.removeEventListener("keydown", onKey));
|
||||
border: 1px solid color-mix(in oklab, var(--wp-danger, #ef4444) 32%, transparent);
|
||||
color: var(--wp-danger, #ef4444);
|
||||
}
|
||||
/* Informational tone for the "pick a match" case — mirrors PushToLibraryModal. */
|
||||
.wp-ptl-note--info {
|
||||
background: color-mix(in oklab, var(--wp-accent-500, #8b5cf6) 10%, transparent);
|
||||
border: 1px solid color-mix(in oklab, var(--wp-accent-500, #8b5cf6) 30%, transparent);
|
||||
color: var(--wp-text, #e7e7ee);
|
||||
}
|
||||
.wp-ptl-relink {
|
||||
padding: 10px 12px;
|
||||
border-radius: 6px;
|
||||
background: color-mix(in oklab, var(--wp-accent-500, #8b5cf6) 8%, transparent);
|
||||
border: 1px solid color-mix(in oklab, var(--wp-accent-500, #8b5cf6) 30%, transparent);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.wp-ptl-relink__title { font-size: 12.5px; font-weight: 600; color: var(--wp-text, #e7e7ee); }
|
||||
.wp-ptl-relink__hint { margin: 0; font-size: 11.5px; color: var(--wp-text-muted, #a1a1ad); }
|
||||
.wp-ptl-relink__list {
|
||||
list-style: none; margin: 0; padding: 0;
|
||||
max-height: 160px; overflow-y: auto;
|
||||
display: flex; flex-direction: column; gap: 2px;
|
||||
}
|
||||
.wp-ptl-relink__cand {
|
||||
display: flex; align-items: baseline; gap: 8px;
|
||||
padding: 5px 8px; border-radius: 4px; cursor: pointer;
|
||||
}
|
||||
.wp-ptl-relink__cand:hover { background: color-mix(in oklab, var(--wp-accent-500, #8b5cf6) 16%, transparent); }
|
||||
.wp-ptl-relink__cand.is-picked { background: color-mix(in oklab, var(--wp-accent-500, #8b5cf6) 28%, transparent); }
|
||||
.wp-ptl-relink__name { font-size: 12px; color: var(--wp-text, #e7e7ee); }
|
||||
.wp-ptl-relink__uuid { font-family: var(--wp-font-mono, monospace); font-size: 10px; color: var(--wp-text-dim, #6e6e7c); }
|
||||
.wp-ptl-relink__tag {
|
||||
margin-left: auto; flex-shrink: 0;
|
||||
font-size: 9.5px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em;
|
||||
padding: 1px 6px; border-radius: 999px;
|
||||
}
|
||||
.wp-ptl-relink__tag.is-identical {
|
||||
color: var(--wp-green, #6ad28b);
|
||||
background: color-mix(in oklab, var(--wp-green, #6ad28b) 16%, transparent);
|
||||
}
|
||||
.wp-ptl-relink__tag.is-diff {
|
||||
color: var(--wp-warn, #facc15);
|
||||
background: color-mix(in oklab, var(--wp-warn, #facc15) 16%, transparent);
|
||||
}
|
||||
.wp-ptl-relink .wp-ptl-btn--primary { align-self: flex-start; }
|
||||
.wp-ptl-error {
|
||||
padding: 8px 10px;
|
||||
border-radius: 6px;
|
||||
|
||||
@@ -23,6 +23,7 @@ vi.mock("#comfyui/app", () => ({
|
||||
}));
|
||||
|
||||
import PushToLibraryModal from "./PushToLibraryModal.vue";
|
||||
import { hashes } from "./drift-store";
|
||||
import type { ModuleEntry } from "../../widgets/_shared";
|
||||
|
||||
const VALID_PAYLOAD = {
|
||||
@@ -86,6 +87,9 @@ beforeEach(() => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
resetBody();
|
||||
// The re-link branch reads the drift-store live hashes; null it out so a
|
||||
// set value can't leak into other tests and falsely trip isLibraryMissing.
|
||||
hashes.value = null;
|
||||
});
|
||||
|
||||
async function openModal(draft: ModuleEntry | null) {
|
||||
@@ -247,6 +251,41 @@ describe("PushToLibraryModal", () => {
|
||||
wrap.unmount();
|
||||
});
|
||||
|
||||
it("offers re-link to a content-identical library row when the draft is detached", async () => {
|
||||
// A DIFFERENT uuid carries the draft's payload_hash — the re-imported twin.
|
||||
hashes.value = { live0001: { type: "wildcard", payload_hash: "HASH_A" } };
|
||||
pushResponse({ items: [] }); // fetchBundlesContaining
|
||||
pushResponse({ description: "", tags: [] }); // seedFromLibrary
|
||||
pushResponse({ items: [{ id: "live0001", name: "test_w", type: "wildcard" }] }); // fetchLibraryNames
|
||||
const wrap = await openModal(makeDraft({ id: "dead0001", payload_hash: "HASH_A" }));
|
||||
|
||||
const relink = document.querySelector('[data-test="ptl-relink"]');
|
||||
expect(relink).not.toBeNull();
|
||||
|
||||
document.querySelector<HTMLButtonElement>('[data-test="ptl-relink-confirm"]')!.click();
|
||||
await flushPromises();
|
||||
|
||||
const saved = wrap.emitted("saved");
|
||||
expect(saved).toBeTruthy();
|
||||
const result = saved![0][0] as { mode: string; id: string; origId: string };
|
||||
expect(result.mode).toBe("relink");
|
||||
expect(result.id).toBe("live0001");
|
||||
expect(result.origId).toBe("dead0001");
|
||||
wrap.unmount();
|
||||
});
|
||||
|
||||
it("does not offer re-link when no content match exists (detached, novel content)", async () => {
|
||||
// Library has a different-content row only → no identical + no name match
|
||||
// for a differently-named draft → no re-link block (Save as new is the path).
|
||||
hashes.value = { live0009: { type: "wildcard", payload_hash: "OTHER" } };
|
||||
pushResponse({ items: [] }); // bundles
|
||||
pushResponse({ description: "", tags: [] }); // seedFromLibrary
|
||||
pushResponse({ items: [{ id: "live0009", name: "unrelated", type: "wildcard" }] }); // names
|
||||
const wrap = await openModal(makeDraft({ id: "dead0002", payload_hash: "HASH_Z" }));
|
||||
expect(document.querySelector('[data-test="ptl-relink"]')).toBeNull();
|
||||
wrap.unmount();
|
||||
});
|
||||
|
||||
it("opt-out checkbox round-trips into the PUT body", async () => {
|
||||
pushResponse({ items: [{ id: "b1", name: "framing" }] });
|
||||
pushResponse({ description: "", tags: [] }); // seedFromLibrary
|
||||
|
||||
@@ -27,6 +27,12 @@ import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { workflowSiblingCount } from "./duplicates/sibling-count";
|
||||
import { forkModule } from "./duplicates/fork";
|
||||
import { hashes as libraryHashes } from "./drift-store";
|
||||
import {
|
||||
findRelinkCandidates,
|
||||
autoRelinkTarget,
|
||||
type RelinkCandidate,
|
||||
} from "../../manager/import-export/relink-match";
|
||||
import { localPayloadFingerprint } from "../../manager/import-export/fingerprint";
|
||||
import { app } from "#comfyui/app";
|
||||
import type { ModuleEntry } from "../../widgets/_shared";
|
||||
import WpCheck from "@/components/shared/WpCheck.vue";
|
||||
@@ -41,8 +47,10 @@ interface SaveResult {
|
||||
* entry with a "(copy)" suffix; workflow row keeps its old id.
|
||||
* `reattach` — fork when the source entry was missing upstream;
|
||||
* no copy suffix, AND the caller should rebind the workflow row to
|
||||
* the new uuid so MISSING clears. */
|
||||
mode: "update" | "fork" | "reattach";
|
||||
* the new uuid so MISSING clears. `relink` — no write at all: point
|
||||
* the detached workflow row at an EXISTING content-identical library
|
||||
* uuid; the caller swaps the row id + remaps sibling refs. */
|
||||
mode: "update" | "fork" | "reattach" | "relink";
|
||||
/** New library uuid when forking; same as draft.id when updating. */
|
||||
id: string;
|
||||
/** payload_hash returned by the server after the write. */
|
||||
@@ -88,6 +96,22 @@ const isLibraryMissing = computed(() => {
|
||||
return !(props.draft.id in libraryHashes.value);
|
||||
});
|
||||
|
||||
/** Whether to OFFER the re-link picker.
|
||||
*
|
||||
* Wider than `isLibraryMissing`, which requires a payload_hash. A hash-less
|
||||
* row was treated as "never library-tracked, nothing to re-link" — true for a
|
||||
* module authored in the widget, wrong for the cases that actually bite: a
|
||||
* shared workflow, or a row whose stored hash was lost. Those still correspond
|
||||
* to a library entry, and matching them is what `contentKey` is for.
|
||||
*
|
||||
* Costs nothing when there IS no match: the picker only renders when
|
||||
* candidates come back, so a genuinely new module still sees the plain
|
||||
* save-as-new flow. */
|
||||
const needsRelink = computed(() => {
|
||||
if (!props.draft || libraryHashes.value === null) return false;
|
||||
return !(props.draft.id in libraryHashes.value);
|
||||
});
|
||||
|
||||
/** "Update existing" is enabled only when the entry exists AND is
|
||||
* library-tracked. Disabled when never library-tracked OR when the
|
||||
* upstream entry has been deleted. */
|
||||
@@ -95,6 +119,107 @@ const canUpdateExisting = computed(
|
||||
() => isLibraryTracked.value && !isLibraryMissing.value,
|
||||
);
|
||||
|
||||
/** uuid → {name, type} for every live library module, fetched once on open.
|
||||
* Backs the re-link candidate name lookup + the (type, name) fallback match.
|
||||
* drift-store hashes carry (type, payload_hash) but not names, so the picker
|
||||
* needs this to label + weakly-match candidates. */
|
||||
const relinkNames = ref<Map<string, { name: string; type: string }>>(new Map());
|
||||
|
||||
/** uuid → locally computed payload fingerprint for every live library module.
|
||||
* Only consulted for a HASH-LESS draft, where the server hash can't decide.
|
||||
* Both sides are fingerprinted by the same local function, so this needs no
|
||||
* parity with the engine's own hashing. */
|
||||
const relinkContentKeys = ref<Map<string, string>>(new Map());
|
||||
|
||||
async function fetchLibraryNames(): Promise<void> {
|
||||
try {
|
||||
const res = await fetch("/wp/api/modules");
|
||||
if (!res.ok) return;
|
||||
const data = (await res.json()) as
|
||||
| { items?: Array<{ id?: string; name?: string; type?: string; payload?: unknown }> }
|
||||
| Array<{ id?: string; name?: string; type?: string; payload?: unknown }>;
|
||||
const items = Array.isArray(data) ? data : (data.items ?? []);
|
||||
const next = new Map<string, { name: string; type: string }>();
|
||||
const keys = new Map<string, string>();
|
||||
for (const it of items) {
|
||||
if (typeof it.id === "string" && it.id) {
|
||||
next.set(it.id, { name: it.name ?? "", type: it.type ?? "" });
|
||||
if (it.payload !== undefined) {
|
||||
keys.set(it.id, localPayloadFingerprint(it.payload));
|
||||
}
|
||||
}
|
||||
}
|
||||
relinkNames.value = next;
|
||||
relinkContentKeys.value = keys;
|
||||
} catch {
|
||||
/* network — leave the maps empty; no re-link offered */
|
||||
}
|
||||
}
|
||||
|
||||
/** Content-aware re-link candidates for a DETACHED draft: existing library
|
||||
* rows whose (type, payload_hash) match the draft's content (identical) or
|
||||
* whose (type, name) match (content differs). Empty unless the draft is
|
||||
* detached (`isLibraryMissing`). */
|
||||
const relinkCandidates = computed<RelinkCandidate[]>(() => {
|
||||
if (!props.draft || !needsRelink.value || libraryHashes.value === null) return [];
|
||||
// Merge the locally computed content keys into the hash map the matcher
|
||||
// walks, so a hash-less draft can still match on payload content.
|
||||
const live: Record<string, { type?: string; payload_hash: string; contentKey?: string }> = {};
|
||||
for (const [uuid, entry] of Object.entries(libraryHashes.value)) {
|
||||
live[uuid] = { ...entry, contentKey: relinkContentKeys.value.get(uuid) };
|
||||
}
|
||||
return findRelinkCandidates(
|
||||
{
|
||||
id: props.draft.id,
|
||||
type: props.draft.type,
|
||||
payload_hash: props.draft.payload_hash,
|
||||
contentKey: props.draft.payload_hash
|
||||
? undefined
|
||||
: localPayloadFingerprint(props.draft.payload),
|
||||
name: props.draft.meta?.name ?? "",
|
||||
},
|
||||
live,
|
||||
(u) => relinkNames.value.get(u),
|
||||
);
|
||||
});
|
||||
|
||||
/** The sole content-identical candidate, if unambiguous (else null). */
|
||||
const relinkAuto = computed(() => autoRelinkTarget(relinkCandidates.value));
|
||||
const relinkPick = ref<RelinkCandidate | null>(null);
|
||||
const relinkQuery = ref<string>("");
|
||||
const relinkFiltered = computed<RelinkCandidate[]>(() => {
|
||||
const q = relinkQuery.value.trim().toLowerCase();
|
||||
if (!q) return relinkCandidates.value;
|
||||
return relinkCandidates.value.filter(
|
||||
(c) => c.name.toLowerCase().includes(q) || c.uuid.toLowerCase().includes(q),
|
||||
);
|
||||
});
|
||||
|
||||
/** The active re-link target: an explicit pick wins, else the unambiguous
|
||||
* auto-target (single identical candidate). */
|
||||
const relinkTarget = computed<RelinkCandidate | null>(
|
||||
() => relinkPick.value ?? relinkAuto.value,
|
||||
);
|
||||
|
||||
/** Danger tone only when there is genuinely nothing to reconnect to. With a
|
||||
* match on offer this is a routine "pick one" prompt, not a failure. */
|
||||
const relinkNoteClass = computed(() =>
|
||||
relinkCandidates.value.length > 0 ? "wp-ptl-note--info" : "wp-ptl-note--danger",
|
||||
);
|
||||
|
||||
function doRelink(): void {
|
||||
const t = relinkTarget.value;
|
||||
if (!t || !props.draft) return;
|
||||
emit("saved", {
|
||||
mode: "relink",
|
||||
id: t.uuid,
|
||||
payload_hash: t.payloadHash,
|
||||
bundles_updated: [],
|
||||
name: t.name,
|
||||
origId: props.draft.id,
|
||||
});
|
||||
}
|
||||
|
||||
const siblings = computed<number>(() => {
|
||||
if (!props.draft) return 0;
|
||||
try {
|
||||
@@ -133,6 +258,8 @@ function resetForm(): void {
|
||||
propagate.value = true;
|
||||
busy.value = false;
|
||||
errorMsg.value = "";
|
||||
relinkPick.value = null;
|
||||
relinkQuery.value = "";
|
||||
}
|
||||
|
||||
/** When the row is library-tracked, fetch the live library entry and
|
||||
@@ -184,9 +311,19 @@ watch(
|
||||
resetForm();
|
||||
void fetchBundlesContaining();
|
||||
void seedFromLibrary();
|
||||
// Re-link candidates only matter when the row's id ISN'T in the library —
|
||||
// skip the extra library-list fetch entirely when it's present.
|
||||
if (needsRelink.value) void fetchLibraryNames();
|
||||
},
|
||||
);
|
||||
|
||||
// A drift poll can flip the draft to unlinked AFTER open (hashes land late);
|
||||
// fetch the candidate map the first time that happens so re-link appears
|
||||
// without a reopen. One-shot: only when open, unlinked, and not yet loaded.
|
||||
watch(needsRelink, (unlinked) => {
|
||||
if (props.open && unlinked && relinkNames.value.size === 0) void fetchLibraryNames();
|
||||
});
|
||||
|
||||
function close(): void {
|
||||
if (busy.value) return;
|
||||
emit("close");
|
||||
@@ -411,10 +548,82 @@ onBeforeUnmount(() => window.removeEventListener("keydown", onKey));
|
||||
changes the library entry every instance reads from.
|
||||
</div>
|
||||
|
||||
<div v-if="isLibraryMissing" class="wp-ptl-note wp-ptl-note--danger" data-test="ptl-missing">
|
||||
The library entry for this module has been deleted upstream. "Update existing"
|
||||
is unavailable — use "Save as new entry" to re-add it to the library as a fresh
|
||||
entry.
|
||||
<div
|
||||
v-if="needsRelink && relinkCandidates.length"
|
||||
class="wp-ptl-relink"
|
||||
data-test="ptl-relink"
|
||||
>
|
||||
<div class="wp-ptl-relink__title">Re-link to an existing library entry</div>
|
||||
<p class="wp-ptl-relink__hint">
|
||||
This module's content matches a library entry under a different id (a re-import
|
||||
minted a new one). Re-link to reconnect drift + refresh instead of adding a duplicate.
|
||||
</p>
|
||||
<input
|
||||
v-if="relinkCandidates.length > 1"
|
||||
v-model="relinkQuery"
|
||||
type="text"
|
||||
class="wp-ptl-input"
|
||||
data-test="ptl-relink-search"
|
||||
placeholder="Search by name or id…"
|
||||
aria-label="Search library entries to re-link"
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<ul class="wp-ptl-relink__list">
|
||||
<li
|
||||
v-for="c in relinkFiltered"
|
||||
:key="c.uuid"
|
||||
class="wp-ptl-relink__cand"
|
||||
:class="{ 'is-picked': relinkTarget != null && relinkTarget.uuid === c.uuid }"
|
||||
data-test="ptl-relink-candidate"
|
||||
@click="relinkPick = c"
|
||||
>
|
||||
<span class="wp-ptl-relink__name">{{ c.name || "(unnamed)" }}</span>
|
||||
<code class="wp-ptl-relink__uuid">{{ c.uuid }}</code>
|
||||
<!-- "identical (content)" distinguishes a match established
|
||||
by locally fingerprinting the payload — the hash-less
|
||||
path — from one the server's own hash confirmed. Same
|
||||
confidence in practice, but the label shouldn't imply
|
||||
the authoritative hash agreed when there wasn't one. -->
|
||||
<span
|
||||
class="wp-ptl-relink__tag"
|
||||
:class="c.contentIdentical ? 'is-identical' : 'is-diff'"
|
||||
:title="c.matchedByContent
|
||||
? 'Matched by comparing payload content — this module carries no stored hash'
|
||||
: undefined"
|
||||
>{{ c.contentIdentical
|
||||
? (c.matchedByContent ? "identical (content)" : "identical")
|
||||
: "content differs" }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<button
|
||||
type="button"
|
||||
class="wp-ptl-btn wp-ptl-btn--primary"
|
||||
data-test="ptl-relink-confirm"
|
||||
:disabled="!relinkTarget || undefined"
|
||||
@click="doRelink"
|
||||
>Re-link<template v-if="relinkTarget"> to “{{ relinkTarget.name || relinkTarget.uuid }}”</template></button>
|
||||
</div>
|
||||
|
||||
<!-- States the OBSERVABLE fact and points at Re-link first when a
|
||||
match exists. The old copy asserted the entry "has been
|
||||
deleted upstream" — a cause it cannot know (a shared workflow,
|
||||
a re-import under a new id, or a lost hash all look identical
|
||||
from here) — and recommended "Save as new entry" while the
|
||||
Re-link panel sat directly above offering the better option,
|
||||
which is how duplicates got made. -->
|
||||
<div v-if="needsRelink" class="wp-ptl-note" :class="relinkNoteClass" data-test="ptl-missing">
|
||||
<template v-if="relinkCandidates.length > 0">
|
||||
This module isn’t linked to any library entry under its recorded id.
|
||||
{{ relinkTarget?.contentIdentical
|
||||
? "A library entry with identical content is selected above — re-linking reconnects them."
|
||||
: "Pick a match above to re-link, or save it as a new entry." }}
|
||||
</template>
|
||||
<template v-else>
|
||||
This module isn’t linked to any library entry under its recorded id, and
|
||||
nothing in the library matches its content or name. “Update existing” is
|
||||
unavailable — “Save as new entry” adds it to the library.
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div v-if="errorMsg" class="wp-ptl-error" data-test="ptl-error">
|
||||
@@ -511,7 +720,7 @@ onBeforeUnmount(() => window.removeEventListener("keydown", onKey));
|
||||
font-family: inherit;
|
||||
}
|
||||
.wp-ptl-input:focus { outline: 1px solid var(--wp-accent-500, #8b5cf6); }
|
||||
.wp-ptl-input--multi { resize: vertical; min-height: 48px; }
|
||||
.wp-ptl-input--multi { resize: vertical; overscroll-behavior: contain; min-height: 48px; }
|
||||
.wp-ptl-payload {
|
||||
margin: 0;
|
||||
padding: 8px 10px;
|
||||
@@ -559,6 +768,66 @@ onBeforeUnmount(() => window.removeEventListener("keydown", onKey));
|
||||
border: 1px solid color-mix(in oklab, var(--wp-danger, #ef4444) 32%, transparent);
|
||||
color: var(--wp-danger, #ef4444);
|
||||
}
|
||||
/* Informational tone for the "pick a match" case — a re-linkable module is a
|
||||
routine state, not an error, and painting it red pushed users toward the
|
||||
duplicate-creating escape hatch. */
|
||||
.wp-ptl-note--info {
|
||||
background: color-mix(in oklab, var(--wp-accent-500, #8b5cf6) 10%, transparent);
|
||||
border: 1px solid color-mix(in oklab, var(--wp-accent-500, #8b5cf6) 30%, transparent);
|
||||
color: var(--wp-text, #e7e7ee);
|
||||
}
|
||||
.wp-ptl-relink {
|
||||
padding: 10px 12px;
|
||||
border-radius: 6px;
|
||||
background: color-mix(in oklab, var(--wp-accent-500, #8b5cf6) 8%, transparent);
|
||||
border: 1px solid color-mix(in oklab, var(--wp-accent-500, #8b5cf6) 30%, transparent);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.wp-ptl-relink__title { font-size: 12.5px; font-weight: 600; color: var(--wp-text, #e7e7ee); }
|
||||
.wp-ptl-relink__hint { margin: 0; font-size: 11.5px; color: var(--wp-text-muted, #a1a1ad); }
|
||||
.wp-ptl-relink__list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
max-height: 160px;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.wp-ptl-relink__cand {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
padding: 5px 8px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.wp-ptl-relink__cand:hover { background: color-mix(in oklab, var(--wp-accent-500, #8b5cf6) 16%, transparent); }
|
||||
.wp-ptl-relink__cand.is-picked { background: color-mix(in oklab, var(--wp-accent-500, #8b5cf6) 28%, transparent); }
|
||||
.wp-ptl-relink__name { font-size: 12px; color: var(--wp-text, #e7e7ee); }
|
||||
.wp-ptl-relink__uuid { font-family: var(--wp-font-mono, monospace); font-size: 10px; color: var(--wp-text-dim, #6e6e7c); }
|
||||
.wp-ptl-relink__tag {
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
font-size: 9.5px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
padding: 1px 6px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
.wp-ptl-relink__tag.is-identical {
|
||||
color: var(--wp-green, #6ad28b);
|
||||
background: color-mix(in oklab, var(--wp-green, #6ad28b) 16%, transparent);
|
||||
}
|
||||
.wp-ptl-relink__tag.is-diff {
|
||||
color: var(--wp-warn, #facc15);
|
||||
background: color-mix(in oklab, var(--wp-warn, #facc15) 16%, transparent);
|
||||
}
|
||||
.wp-ptl-relink .wp-ptl-btn--primary { align-self: flex-start; }
|
||||
.wp-ptl-error {
|
||||
padding: 8px 10px;
|
||||
border-radius: 6px;
|
||||
|
||||
@@ -75,6 +75,14 @@ const frameColor = computed(() =>
|
||||
props.color && props.color.length ? props.color : "var(--wp-bundle-default)",
|
||||
);
|
||||
|
||||
/** Tooltip for the MISSING badge. Names the two recoveries in the order the
|
||||
* user should try them — Re-link reconnects to an existing entry, saving a
|
||||
* new one is the fallback. The old copy only offered the fallback, which is
|
||||
* what produced duplicate library entries. */
|
||||
const missingTitle =
|
||||
"No live library entry for this bundle under its recorded id. "
|
||||
+ "Right-click → Push to library: re-link it to a matching entry, or save it as a new one.";
|
||||
|
||||
const summary = computed(() => {
|
||||
const word = props.childCount === 1 ? "mod" : "mods";
|
||||
const parts = [`${props.childCount} ${word}`];
|
||||
@@ -165,16 +173,21 @@ const summary = computed(() => {
|
||||
its own dot — re-stacking them at the bundle level would be
|
||||
visual noise. -->
|
||||
<span v-if="libraryMissing || libraryDrifted || snapshotModified" class="wp-mod-dots">
|
||||
<!-- Visual hierarchy: MISSING (library deleted) is the most severe
|
||||
<!-- Visual hierarchy: MISSING (no live library entry) is the most severe
|
||||
and shows first; LIBRARY UPDATED (drift) dominates next; MOD
|
||||
sits to its right. Multiple can show simultaneously — they
|
||||
represent independent axes. -->
|
||||
represent independent axes.
|
||||
Copy states the observable fact rather than asserting the entry was
|
||||
DELETED: an id absent from the library reads identically whether it
|
||||
was deleted, re-imported under a new id, or arrived in a shared
|
||||
workflow — and Push to library now offers Re-link for the last two,
|
||||
which "deleted" steered users away from. -->
|
||||
<template v-if="libraryMissing">
|
||||
<span class="wp-mod-dot wp-mod-dot--missing"
|
||||
title="The bundle's library entry has been deleted. Right-click → Push to library to re-add as a new entry."
|
||||
:title="missingTitle"
|
||||
aria-hidden="true"></span>
|
||||
<span class="wp-mod-badge wp-mod-badge--missing"
|
||||
title="The bundle's library entry has been deleted. Right-click → Push to library to re-add as a new entry.">missing</span>
|
||||
:title="missingTitle">missing</span>
|
||||
</template>
|
||||
<template v-if="libraryDrifted">
|
||||
<span class="wp-mod-dot wp-mod-dot--drift"
|
||||
@@ -399,10 +412,19 @@ const summary = computed(() => {
|
||||
color: var(--wp-warn);
|
||||
background: color-mix(in srgb, var(--wp-warn) 7%, transparent);
|
||||
}
|
||||
/* Child-count / drift summary. Was 10px in --wp-text-dim (#666 on the dark
|
||||
* theme), which sat right at the edge of legibility against the bundle frame
|
||||
* tint — the one piece of information telling you how big a collapsed bundle
|
||||
* is. Bumped to the muted token at 11px and given a faint pill so it reads as
|
||||
* a value rather than a watermark. */
|
||||
.wp-bundle-summary {
|
||||
font: 500 10px/1.3 var(--wp-font-sans);
|
||||
color: var(--wp-text-dim, var(--wp-text3));
|
||||
font: 600 11px/1.3 var(--wp-font-sans);
|
||||
color: var(--wp-text-muted, var(--wp-text2));
|
||||
flex-shrink: 0;
|
||||
padding: 1px 6px;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in oklab, var(--wp-text-muted, var(--wp-text2)) 12%, transparent);
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* Bundle action button — base size + shape from shared
|
||||
* .wp-btn--icon-sm. Bundle-specific tweak: bg + border tinted with
|
||||
|
||||
@@ -1,4 +1,43 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { bundleContentKey } from "./bundle-fingerprint";
|
||||
|
||||
describe("bundleContentKey", () => {
|
||||
it("agrees across two copies of the same library bundle", () => {
|
||||
// This is the point: `computeBundleFingerprint` folds in per-instance
|
||||
// `_uid` / meta / instance, so a fresh insert never matches the library
|
||||
// row it came from. This key keeps only what survives an insert.
|
||||
const libraryChildren = [
|
||||
{ type: "wildcard", payload_hash: "H1", id: "aaa" },
|
||||
{ type: "constraint", payload_hash: "H2", id: "bbb" },
|
||||
];
|
||||
const workflowChildren = [
|
||||
{ type: "wildcard", payload_hash: "H1", id: "zzz", _uid: "u1", meta: { name: "renamed" } },
|
||||
{ type: "constraint", payload_hash: "H2", id: "yyy", _uid: "u2" },
|
||||
];
|
||||
expect(bundleContentKey(workflowChildren)).toBe(bundleContentKey(libraryChildren));
|
||||
});
|
||||
|
||||
it("separates different children", () => {
|
||||
expect(bundleContentKey([{ type: "wildcard", payload_hash: "H1" }]))
|
||||
.not.toBe(bundleContentKey([{ type: "wildcard", payload_hash: "H2" }]));
|
||||
});
|
||||
|
||||
it("respects child ORDER — a bundle is an ordered range", () => {
|
||||
const a = [{ type: "wildcard", payload_hash: "H1" }, { type: "combine", payload_hash: "H2" }];
|
||||
const b = [{ type: "combine", payload_hash: "H2" }, { type: "wildcard", payload_hash: "H1" }];
|
||||
expect(bundleContentKey(a)).not.toBe(bundleContentKey(b));
|
||||
});
|
||||
|
||||
it("keeps a hash-less child in the shape rather than skipping it", () => {
|
||||
const withChild = [{ type: "wildcard", payload_hash: "H1" }, { type: "combine" }];
|
||||
const without = [{ type: "wildcard", payload_hash: "H1" }];
|
||||
expect(bundleContentKey(withChild)).not.toBe(bundleContentKey(without));
|
||||
});
|
||||
|
||||
it("distinguishes an empty bundle from a one-child bundle", () => {
|
||||
expect(bundleContentKey([])).not.toBe(bundleContentKey([{ type: "wildcard" }]));
|
||||
});
|
||||
});
|
||||
import type { BundleInstance, ModuleEntry } from "../../../widgets/_shared";
|
||||
import {
|
||||
computeBundleFingerprint,
|
||||
|
||||
@@ -132,6 +132,31 @@ export function computeBundleFingerprint(
|
||||
return `${FINGERPRINT_VERSION}:${djb2(parts.join("\n"))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cross-library content key for a bundle: the ordered list of its children's
|
||||
* `(type, payload_hash)` pairs.
|
||||
*
|
||||
* Distinct from `computeBundleFingerprint`, which answers "have MY children
|
||||
* been edited since insert" and therefore folds in per-instance state — `_uid`,
|
||||
* `meta`, `instance`. That makes it useless for comparing a workflow bundle
|
||||
* against a LIBRARY bundle: a fresh insert mints new uids, so two copies of the
|
||||
* same library bundle never agree.
|
||||
*
|
||||
* This one deliberately keeps only what survives an insert, so a workflow
|
||||
* bundle and the library row it came from produce the same key. Order matters
|
||||
* (a bundle IS an ordered range) and children with no `payload_hash` contribute
|
||||
* an empty slot rather than being skipped, so a hash-less child still affects
|
||||
* the shape.
|
||||
*
|
||||
* Used by the re-link picker when a bundle carries no `inserted_at_hash`.
|
||||
*/
|
||||
export function bundleContentKey(
|
||||
children: ReadonlyArray<{ type?: string; payload_hash?: string }>,
|
||||
): string {
|
||||
const parts = children.map((c) => `${c.type ?? ""}|${c.payload_hash ?? ""}`);
|
||||
return `bk1:${djb2(parts.join("\n"))}`;
|
||||
}
|
||||
|
||||
/** True when the bundle's current children diverge from the snapshot
|
||||
* fingerprint stored on the instance. Returns FALSE when:
|
||||
* - no fingerprint stored (workflow predates MOD detection), OR
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import InstanceIdChip from "./InstanceIdChip.vue";
|
||||
|
||||
describe("InstanceIdChip", () => {
|
||||
beforeEach(() => {
|
||||
// jsdom has no clipboard by default — stub a resolving writeText.
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
value: { writeText: vi.fn(async () => undefined) },
|
||||
configurable: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("renders the library id as the visible label", () => {
|
||||
const w = mount(InstanceIdChip, { props: { id: "ab12cd34" } });
|
||||
const chip = w.get('[data-test="instance-id-chip"]');
|
||||
expect(chip.text()).toContain("ab12cd34");
|
||||
});
|
||||
|
||||
it("renders nothing when id is empty (unlinked/inline module)", () => {
|
||||
const w = mount(InstanceIdChip, { props: { id: "" } });
|
||||
expect(w.find('[data-test="instance-id-chip"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("surfaces both id and _uid in the tooltip", () => {
|
||||
const w = mount(InstanceIdChip, { props: { id: "ab12cd34", uid: "uid-9f9f9f" } });
|
||||
const title = w.get('[data-test="instance-id-chip"]').attributes("title") ?? "";
|
||||
expect(title).toContain("ab12cd34");
|
||||
expect(title).toContain("uid-9f9f9f");
|
||||
});
|
||||
|
||||
it("copies the id to the clipboard and flips to a copied state on click", async () => {
|
||||
const writeText = navigator.clipboard.writeText as ReturnType<typeof vi.fn>;
|
||||
const w = mount(InstanceIdChip, { props: { id: "ab12cd34" } });
|
||||
await w.get('[data-test="instance-id-chip"]').trigger("click");
|
||||
await flushPromises();
|
||||
expect(writeText).toHaveBeenCalledWith("ab12cd34");
|
||||
expect(w.get('[data-test="instance-id-chip"]').classes()).toContain("wp-idchip--copied");
|
||||
expect(w.get('[data-test="instance-id-chip"]').text()).toContain("copied");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Small monospace, click-to-copy chip that surfaces a module/bundle's
|
||||
* identity in the edit-modal header. Debugging aid (workstream C / issue #4):
|
||||
* the library `id` is the uuid that `@{id}` nested refs, constraint
|
||||
* source/target, and library rows all match on — so seeing it (and being
|
||||
* able to copy it) makes drift/linking bugs traceable at a glance.
|
||||
*
|
||||
* Shows the library `id` as the visible label; the instance `_uid` (what
|
||||
* constraint `pick` + `bundle_origin` key on) rides along in the tooltip so
|
||||
* both identities are one hover away without cluttering the header.
|
||||
*/
|
||||
import { ref, onBeforeUnmount } from "vue";
|
||||
|
||||
const props = defineProps<{
|
||||
/** Library uuid — the payload row id. Matches `@{id}`, constraint
|
||||
* source/target ids, and library rows. Empty for inline-only modules. */
|
||||
id: string;
|
||||
/** Instance uid — per-Context-node instance identity used by constraint
|
||||
* `pick` selectors + `bundle_origin`. Optional (absent on some surfaces). */
|
||||
uid?: string;
|
||||
}>();
|
||||
|
||||
const copied = ref(false);
|
||||
let timer: number | undefined;
|
||||
|
||||
async function copyId(): Promise<void> {
|
||||
if (!props.id) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(props.id);
|
||||
copied.value = true;
|
||||
if (timer !== undefined) window.clearTimeout(timer);
|
||||
timer = window.setTimeout(() => { copied.value = false; }, 1200);
|
||||
} catch {
|
||||
// Clipboard blocked (insecure context / denied) — the id stays visible
|
||||
// for manual selection, so a failed copy is a silent no-op.
|
||||
}
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (timer !== undefined) window.clearTimeout(timer);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
v-if="id"
|
||||
type="button"
|
||||
class="wp-idchip"
|
||||
:class="{ 'wp-idchip--copied': copied }"
|
||||
:title="`library id: ${id}${uid ? `\ninstance uid: ${uid}` : ''}\n(click to copy id)`"
|
||||
data-test="instance-id-chip"
|
||||
@click.stop="copyId"
|
||||
>
|
||||
<i
|
||||
class="pi wp-idchip__icon"
|
||||
:class="copied ? 'pi-check' : 'pi-hashtag'"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span class="wp-idchip__id">{{ copied ? "copied" : id }}</span>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.wp-idchip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 1px 6px;
|
||||
border: 1px solid var(--wp-border, #33333f);
|
||||
border-radius: var(--wp-radius-sm, 4px);
|
||||
background: var(--wp-bg2, #1b1b22);
|
||||
color: var(--wp-text-dim, #8a8a99);
|
||||
font: 500 10px/1.4 var(--wp-font-mono, ui-monospace, "JetBrains Mono", monospace);
|
||||
letter-spacing: 0.02em;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
transition: color 0.12s, border-color 0.12s, background 0.12s;
|
||||
}
|
||||
.wp-idchip:hover {
|
||||
color: var(--wp-text, #e7e7ee);
|
||||
border-color: color-mix(in oklab, var(--wp-accent, #7c6ad6) 55%, var(--wp-border, #33333f));
|
||||
}
|
||||
.wp-idchip__icon {
|
||||
font-size: 9px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
.wp-idchip__id {
|
||||
font-family: inherit;
|
||||
}
|
||||
.wp-idchip--copied {
|
||||
color: var(--wp-green, #6ad28b);
|
||||
border-color: color-mix(in oklab, var(--wp-green, #6ad28b) 55%, transparent);
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +1,7 @@
|
||||
/* Shared template-section controls — insert-var/insert-slot dropdown
|
||||
* button + reset button + dropdown panel + dropdown item. Used by:
|
||||
* - Combine's TemplateSection (`.wp-tpl__*`)
|
||||
* - InjectorBindingModal (`.ibm__*`)
|
||||
/* Shared template-section controls — insert-slot dropdown button + reset
|
||||
* button + dropdown panel + dropdown item. Used by:
|
||||
* - InjectorBindingModal (`.ibm__*`) — the insert-ref menu
|
||||
* - Combine's TemplateSection (`.wp-tpl__reset` only)
|
||||
*
|
||||
* Both modals previously declared their own copies of these rules with
|
||||
* tiny differences in padding/height — visible in the UI as a slight
|
||||
@@ -10,6 +10,10 @@
|
||||
* locked to the same dimensions (22px tall, explicit height + box-
|
||||
* sizing).
|
||||
*
|
||||
* NB: the `.wp-tpl__menu*` half of these pairs was dropped — Combine's
|
||||
* TemplateSection no longer has an insert menu, so those selectors matched
|
||||
* nothing. `.wp-tpl__reset` below IS still live.
|
||||
*
|
||||
* Imported globally from ContextWidget's unscoped `<style>` block.
|
||||
* Class names are namespaced (`.wp-tpl__*`, `.ibm__*`) so no leakage
|
||||
* concerns. */
|
||||
@@ -20,18 +24,14 @@
|
||||
* line-height. Block-level wrapper + inline-flex child can leave
|
||||
* 1-2px of descender space below the button, shifting it down vs
|
||||
* the sibling reset button (which is a direct flex child with no
|
||||
* wrapping line-box). Empirically: this is the exact gap the
|
||||
* injector modal showed but the combine modal didn't, since the
|
||||
* combine modal's `.tpl` section uses a different base line-height
|
||||
* inheritance chain. Switching the wrapper to inline-flex pins
|
||||
* cross-axis size to the button itself, killing the offset. */
|
||||
.wp-tpl__menu-wrap, .ibm__menu-wrap {
|
||||
* wrapping line-box). */
|
||||
.wp-ibm__menu-wrap {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.wp-tpl__menu-btn, .ibm__menu-btn {
|
||||
.wp-ibm__menu-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
@@ -46,11 +46,11 @@
|
||||
cursor: pointer;
|
||||
line-height: 1;
|
||||
}
|
||||
.wp-tpl__menu-btn:hover, .ibm__menu-btn:hover {
|
||||
.wp-ibm__menu-btn:hover {
|
||||
border-color: var(--wp-accent);
|
||||
color: var(--wp-text);
|
||||
}
|
||||
.wp-tpl__menu-btn .pi, .ibm__menu-btn .pi { font-size: 9px; }
|
||||
.wp-ibm__menu-btn .pi { font-size: 9px; }
|
||||
|
||||
/* Reset button — used by section-level modal headers:
|
||||
* - .wp-tpl__reset Combine TemplateSection reset
|
||||
@@ -91,10 +91,20 @@
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.wp-tpl__menu, .ibm__menu {
|
||||
position: absolute;
|
||||
top: calc(100% + 4px);
|
||||
right: 0;
|
||||
/* Teleported to <body>, so `fixed` viewport coords rather than `absolute`
|
||||
* inside the modal — as an absolutely-positioned child the menu was CLIPPED
|
||||
* by the modal's scroll container and vanished below the fold whenever its
|
||||
* trigger sat near the bottom. The owning component measures the button and
|
||||
* writes `top` / `left` inline; `--up` flips the box above the trigger when
|
||||
* there's no room below.
|
||||
*
|
||||
* z-index 10020 puts this in the POPOVER tier, above every modal overlay.
|
||||
* Modals here range from 9999 (ModalShell) to 10010 (InjectorBindingModal),
|
||||
* so the old 9999 rendered this menu BEHIND its own modal — it worked only
|
||||
* where the modal was also 9999 and DOM order broke the tie. Any popup that
|
||||
* teleports out of a modal has to clear the whole modal tier. */
|
||||
.wp-ibm__menu {
|
||||
position: fixed;
|
||||
min-width: 200px;
|
||||
max-height: 220px;
|
||||
overflow-y: auto;
|
||||
@@ -102,14 +112,16 @@
|
||||
border: 1px solid var(--wp-border);
|
||||
border-radius: 3px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
||||
z-index: 20;
|
||||
z-index: 10020;
|
||||
padding: 3px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
.wp-tpl__menu-item, .ibm__menu-item {
|
||||
.wp-ibm__menu--up { transform: translateY(-100%); }
|
||||
|
||||
.wp-ibm__menu-item {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
@@ -121,6 +133,6 @@
|
||||
cursor: pointer;
|
||||
color: var(--wp-text);
|
||||
}
|
||||
.wp-tpl__menu-item:hover, .ibm__menu-item:hover {
|
||||
.wp-ibm__menu-item:hover {
|
||||
background: color-mix(in srgb, var(--wp-accent) 18%, transparent);
|
||||
}
|
||||
|
||||
@@ -5,10 +5,15 @@
|
||||
* ModuleEditModal. Master Lock/Hide route to the live cascade
|
||||
* handlers (same ones BundleHeader buttons call). */
|
||||
import { computed } from "vue";
|
||||
import { saveChordLabel } from "../../../shared/platform-keys";
|
||||
import type { BundleInstance } from "../../../../widgets/_shared";
|
||||
import IdentitySection from "./sections/IdentitySection.vue";
|
||||
import RuntimeSection from "./sections/RuntimeSection.vue";
|
||||
import InstanceIdChip from "../InstanceIdChip.vue";
|
||||
|
||||
|
||||
/** Platform-correct save chord for the footer hint. */
|
||||
const saveChord = saveChordLabel();
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
bundle: BundleInstance;
|
||||
@@ -70,6 +75,7 @@ const headerName = computed(() => props.bundle.name || props.libraryName || "Bun
|
||||
<div class="wp-bdm__title-row">
|
||||
<span class="wp-bdm__name" data-test="bdm-name-display">{{ headerName }}</span>
|
||||
<span class="wp-bdm__chip" data-test="bdm-chip">bundle</span>
|
||||
<InstanceIdChip :id="bundle.library_id" :uid="bundle._uid" />
|
||||
<span
|
||||
v-if="libraryDrifted"
|
||||
class="wp-bdm__badge wp-bdm__badge--drift"
|
||||
@@ -135,7 +141,7 @@ const headerName = computed(() => props.bundle.name || props.libraryName || "Bun
|
||||
Reset to library
|
||||
</button>
|
||||
<span class="wp-bdm__hint">
|
||||
<kbd>Esc</kbd> cancel · <kbd>⌘↵</kbd> save
|
||||
<kbd>Esc</kbd> cancel · <kbd>{{ saveChord }}</kbd> save
|
||||
</span>
|
||||
<button
|
||||
v-if="canSaveToLibrary"
|
||||
|
||||
@@ -12,12 +12,18 @@
|
||||
* override, locked seed, hide-from-prompt.
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
import { saveChordLabel } from "../../../shared/platform-keys";
|
||||
import { type ResolvedValue } from "../../../../widgets/richTokenize";
|
||||
import type { ModuleEntry } from "../../../../widgets/_shared";
|
||||
import IdentitySection from "./sections/IdentitySection.vue";
|
||||
import TemplateSection from "./sections/TemplateSection.vue";
|
||||
import type { VarProducerLike } from "../../../../manager/components/RefChip.vue";
|
||||
import RuntimeSection from "./sections/RuntimeSection.vue";
|
||||
import InstanceIdChip from "../InstanceIdChip.vue";
|
||||
|
||||
|
||||
/** Platform-correct save chord for the footer hint. */
|
||||
const saveChord = saveChordLabel();
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
module: ModuleEntry;
|
||||
@@ -29,6 +35,10 @@ const props = withDefaults(
|
||||
* insert-var dropdown so users don't have to remember which
|
||||
* bindings they can reach from this module. */
|
||||
upstreamVars?: string[];
|
||||
/** `$var` → who writes it. Feeds the template editor's `$` autocomplete
|
||||
* so each suggestion names its producing module rather than listing a
|
||||
* bare name the user has to recognise from memory. */
|
||||
upstreamProducers?: Record<string, VarProducerLike>;
|
||||
/** Resolved upstream-var snapshot — drives the TemplateSection's
|
||||
* live preview pane with substituted values. */
|
||||
upstreamResolved?: Record<string, ResolvedValue>;
|
||||
@@ -87,6 +97,7 @@ function onSpaClick(): void {
|
||||
<div class="wp-cbm__title-row">
|
||||
<span class="wp-cbm__name" data-test="cbm-name">{{ module.meta?.name ?? module.type }}</span>
|
||||
<span class="wp-cbm__chip" data-test="cbm-chip">combine</span>
|
||||
<InstanceIdChip :id="module.id" :uid="module._uid" />
|
||||
</div>
|
||||
<div class="wp-cbm__sub">Library entry · template interpolates $vars into output binding</div>
|
||||
</div>
|
||||
@@ -107,6 +118,7 @@ function onSpaClick(): void {
|
||||
@update="onUpdate"
|
||||
/>
|
||||
<TemplateSection
|
||||
:upstream-producers="upstreamProducers"
|
||||
:module="module"
|
||||
:upstream-vars="upstreamVars"
|
||||
:upstream-resolved="upstreamResolved"
|
||||
@@ -140,7 +152,7 @@ function onSpaClick(): void {
|
||||
Reset overrides
|
||||
</button>
|
||||
<span class="wp-cbm__hint">
|
||||
<kbd>Esc</kbd> cancel · <kbd>⌘↵</kbd> save
|
||||
<kbd>Esc</kbd> cancel · <kbd>{{ saveChord }}</kbd> save
|
||||
</span>
|
||||
<button
|
||||
v-if="canSaveToLibrary"
|
||||
|
||||
@@ -20,6 +20,7 @@ import { applyVarAccessor, type ResolvedValue } from "../../../../../widgets/ric
|
||||
// Async-import the rich-text editor so the chunk is split into its own
|
||||
// asset and only pulled in when the combine instance modal opens. Bundle
|
||||
// budget is tight — eager import pushes total over.
|
||||
import type { VarProducerLike } from "../../../../../manager/components/RefChip.vue";
|
||||
const RichTextInput = defineAsyncComponent(
|
||||
() => import("../../../../../manager/components/RichTextInput.vue"),
|
||||
);
|
||||
@@ -30,6 +31,9 @@ const props = withDefaults(
|
||||
/** Vars produced upstream of this Context node — surfaced in the
|
||||
* insert-var dropdown so users don't have to remember names. */
|
||||
upstreamVars?: string[];
|
||||
/** `$var` → its producing module + node, so the `$` autocomplete can
|
||||
* attribute each name instead of listing it bare. */
|
||||
upstreamProducers?: Record<string, VarProducerLike>;
|
||||
/** Resolved upstream `$name → value` map. Drives the live-preview
|
||||
* pane below the syntax preview: when set, the template renders
|
||||
* with `$var` substitutions visible at edit time so users see the
|
||||
@@ -46,6 +50,11 @@ const emit = defineEmits<{ "update": [patch: Partial<ModuleEntry>] }>();
|
||||
/** Combined upstream + sibling vars, deduped, alpha-sorted. Drives
|
||||
* both the validity-coloring on detected pills and the
|
||||
* RichTextInput's `$`-trigger autocomplete suggestion list. */
|
||||
/** A Map because the row builder does one `get` per suggestion. */
|
||||
const varProducerMap = computed<Map<string, VarProducerLike>>(
|
||||
() => new Map(Object.entries(props.upstreamProducers ?? {})),
|
||||
);
|
||||
|
||||
const availableVars = computed<string[]>(() => {
|
||||
const set = new Set<string>();
|
||||
for (const n of props.upstreamVars) if (n) set.add(n);
|
||||
@@ -257,6 +266,8 @@ function onResetTemplate(): void {
|
||||
<RichTextInput
|
||||
:model-value="templateValue"
|
||||
:var-suggestions="availableVars"
|
||||
:var-producers="varProducerMap"
|
||||
graph-aware
|
||||
:multiline="true"
|
||||
:rows="3"
|
||||
surface="combine"
|
||||
@@ -386,7 +397,7 @@ function onResetTemplate(): void {
|
||||
font: 11px/1.5 var(--wp-font-mono);
|
||||
color: var(--wp-text);
|
||||
min-height: 56px;
|
||||
resize: vertical;
|
||||
resize: vertical; overscroll-behavior: contain;
|
||||
}
|
||||
.wp-tpl__input:focus { outline: none; border-color: var(--wp-accent); }
|
||||
.wp-tpl__input--mod {
|
||||
|
||||
@@ -17,12 +17,14 @@
|
||||
* dimmed dead UI would lie.
|
||||
*/
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { saveChordLabel } from "../../../shared/platform-keys";
|
||||
import type { ModuleEntry } from "../../../../widgets/_shared";
|
||||
import type { ChainModule, TargetSelect } from "../../../../extension/constraint-pairs";
|
||||
import IdentitySection from "./sections/IdentitySection.vue";
|
||||
import MatrixSection from "./sections/MatrixSection.vue";
|
||||
import TargetReachSection from "./sections/TargetReachSection.vue";
|
||||
import ExceptionsSection from "./sections/ExceptionsSection.vue";
|
||||
import InstanceIdChip from "../InstanceIdChip.vue";
|
||||
// Library fallback for cross-Context constraints. When the referenced
|
||||
// source/target wildcard isn't a sibling in this WP_Context (lives in
|
||||
// another node, or library-only), pull its sub_categories + option
|
||||
@@ -45,6 +47,9 @@ import { collectTransitiveDeps } from "../../../../manager/community/transitive-
|
||||
import { downloadDepsForDangling } from "../../../../manager/community/download-and-reattach";
|
||||
import { installEnvelope } from "../../../../manager/import-export/install";
|
||||
|
||||
|
||||
/** Platform-correct save chord for the footer hint. */
|
||||
const saveChord = saveChordLabel();
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
module: ModuleEntry;
|
||||
@@ -668,6 +673,7 @@ function onSpaClick(): void {
|
||||
<div class="wp-cnm__title-row">
|
||||
<span class="wp-cnm__name" data-test="cnm-name">{{ module.meta?.name ?? module.type }}</span>
|
||||
<span class="wp-cnm__chip" data-test="cnm-chip">constraint</span>
|
||||
<InstanceIdChip :id="module.id" :uid="module._uid" />
|
||||
</div>
|
||||
<div class="wp-cnm__sub">Library entry · source pick → modifies target option weights</div>
|
||||
</div>
|
||||
@@ -758,7 +764,7 @@ function onSpaClick(): void {
|
||||
Reset overrides
|
||||
</button>
|
||||
<span class="wp-cnm__hint">
|
||||
<kbd>Esc</kbd> cancel · <kbd>⌘↵</kbd> save
|
||||
<kbd>Esc</kbd> cancel · <kbd>{{ saveChord }}</kbd> save
|
||||
</span>
|
||||
<button
|
||||
v-if="canSaveToLibrary"
|
||||
|
||||
@@ -77,7 +77,9 @@ function candidates(): Candidate[] {
|
||||
const dead = new Set([props.sourceUuid, props.targetUuid]);
|
||||
for (const [uuid, name] of props.refData.uuidToName) {
|
||||
if (dead.has(uuid)) continue; // can't re-pick the dangling uuid
|
||||
if (q && !name.toLowerCase().includes(q)) continue;
|
||||
// Match name OR uuid — re-picking a source/target by its 8-hex id is the
|
||||
// reliable path when two wildcards share a display name.
|
||||
if (q && !name.toLowerCase().includes(q) && !uuid.toLowerCase().includes(q)) continue;
|
||||
out.push({
|
||||
uuid,
|
||||
name,
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import ExceptionsSection from "./ExceptionsSection.vue";
|
||||
import Select from "../../../../../manager/components/ui/Select.vue";
|
||||
import type { ModuleEntry } from "../../../../../widgets/_shared";
|
||||
|
||||
function makeModule(overrides: Partial<ModuleEntry> = {}): ModuleEntry {
|
||||
@@ -240,7 +241,7 @@ describe("constraint ExceptionsSection", () => {
|
||||
expect(patch.instance?.disabled_exception_keys).toEqual(['["red","black"]']);
|
||||
});
|
||||
|
||||
it("extra row source/target use VarAutocompleteInput", () => {
|
||||
it("extra row source/target use the Select value picker (concrete options)", () => {
|
||||
const w = mount(ExceptionsSection, {
|
||||
props: {
|
||||
module: makeModule({
|
||||
@@ -254,7 +255,12 @@ describe("constraint ExceptionsSection", () => {
|
||||
targetValues: TARGET_VALUES,
|
||||
},
|
||||
});
|
||||
expect(w.findAllComponents({ name: "VarAutocompleteInput" }).length).toBeGreaterThan(0);
|
||||
// Source + target must be picked from concrete options — a Select each
|
||||
// (its dropdown renders values as chips via the #option/#label slots),
|
||||
// never a free text box.
|
||||
expect(w.find('[data-test="ex-extra-src-0"]').exists()).toBe(true);
|
||||
expect(w.find('[data-test="ex-extra-tgt-0"]').exists()).toBe(true);
|
||||
expect(w.findAllComponents(Select).length).toBe(2);
|
||||
});
|
||||
|
||||
it("library exception with source='' renders the pi-ban chip when sourceHasNull=true", () => {
|
||||
@@ -391,9 +397,9 @@ describe("constraint ExceptionsSection — stranded read-only", () => {
|
||||
stranded: true,
|
||||
},
|
||||
});
|
||||
// The extra row still shows, but as a static snapshot.
|
||||
// The extra row still shows, but as a static snapshot — no Select picker.
|
||||
expect(w.find('[data-test="ex-extra-0"]').exists()).toBe(true);
|
||||
expect(w.findAllComponents({ name: "VarAutocompleteInput" }).length).toBe(0);
|
||||
expect(w.findAllComponents(Select).length).toBe(0);
|
||||
});
|
||||
|
||||
it("control: a healthy (non-stranded) constraint keeps the cycle button + edit controls", () => {
|
||||
|
||||
@@ -17,8 +17,8 @@ import { computed } from "vue";
|
||||
import type { ModuleEntry } from "../../../../../widgets/_shared";
|
||||
import { encodeKey } from "../../instance/keys";
|
||||
import { patchInstance } from "../../instance/patch";
|
||||
import VarAutocompleteInput from "../../../../../manager/components/VarAutocompleteInput.vue";
|
||||
import RichTextPreview from "../../../../../manager/components/RichTextPreview.vue";
|
||||
import Select, { type SelectOption } from "../../../../../manager/components/ui/Select.vue";
|
||||
|
||||
type Mode = "allow" | "exclude" | "boost" | "reduce";
|
||||
|
||||
@@ -138,6 +138,26 @@ const libraryExceptions = computed<LibraryException[]>(() => {
|
||||
|
||||
const instance = computed(() => props.module.instance ?? {});
|
||||
|
||||
/** Exception source/target must be a CONCRETE option of the source / target
|
||||
* wildcard — never free text or "any". The engine keys exceptions on real
|
||||
* option-value strings, so a picker (not a text box) is the correct control.
|
||||
* Build its options from the value lists; include the null option only when
|
||||
* the wildcard actually has one. Mirrors the SPA ConstraintEditor's
|
||||
* exceptionSrcOptions / exceptionTgtOptions. The `#option` / `#label` slots
|
||||
* render each value through RichTextPreview so `@{uuid}` refs + `{a|b}` blocks
|
||||
* chip instead of showing raw hex (issue #7). */
|
||||
const NULL_OPT_LABEL = "⌀ null";
|
||||
const exceptionSrcOptions = computed<SelectOption[]>(() => {
|
||||
const base: SelectOption[] = props.sourceValues.map((v) => ({ label: v, value: v }));
|
||||
if (props.sourceHasNull) base.unshift({ label: NULL_OPT_LABEL, value: "" });
|
||||
return base;
|
||||
});
|
||||
const exceptionTgtOptions = computed<SelectOption[]>(() => {
|
||||
const base: SelectOption[] = props.targetValues.map((v) => ({ label: v, value: v }));
|
||||
if (props.targetHasNull) base.unshift({ label: NULL_OPT_LABEL, value: "" });
|
||||
return base;
|
||||
});
|
||||
|
||||
const disabledKeys = computed<Set<string>>(
|
||||
() => new Set(instance.value.disabled_exception_keys ?? []),
|
||||
);
|
||||
@@ -480,23 +500,57 @@ function bumpExtraFactor(idx: number, dir: 1 | -1): void {
|
||||
>×{{ exc.factor }}</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<VarAutocompleteInput
|
||||
<Select
|
||||
class="ex__extra-input"
|
||||
size="sm"
|
||||
:model-value="excSrc(exc, props.sourceOptionsById)"
|
||||
:suggestions="[...sourceValues]"
|
||||
:data-test="`ex-extra-src-${i}`"
|
||||
placeholder="source"
|
||||
:options="exceptionSrcOptions"
|
||||
placeholder="Pick value"
|
||||
aria-label="Extra exception source"
|
||||
@update:model-value="(v) => onExtraFieldChange(i, 'source_value', v)"
|
||||
/>
|
||||
:data-test="`ex-extra-src-${i}`"
|
||||
@update:model-value="(v) => onExtraFieldChange(i, 'source_value', String(v ?? ''))"
|
||||
>
|
||||
<template #label="{ option }">
|
||||
<RichTextPreview
|
||||
:value="String(option.value) === '' ? option.label : String(option.value)"
|
||||
:uuid-to-name="uuidToName"
|
||||
surface="wildcard"
|
||||
/>
|
||||
</template>
|
||||
<template #option="{ option }">
|
||||
<RichTextPreview
|
||||
:value="String(option.value) === '' ? option.label : String(option.value)"
|
||||
:uuid-to-name="uuidToName"
|
||||
surface="wildcard"
|
||||
/>
|
||||
</template>
|
||||
</Select>
|
||||
<span class="ex__arrow">→</span>
|
||||
<VarAutocompleteInput
|
||||
<Select
|
||||
class="ex__extra-input"
|
||||
size="sm"
|
||||
:model-value="excTgt(exc, props.targetOptionsById)"
|
||||
:suggestions="[...targetValues]"
|
||||
:data-test="`ex-extra-tgt-${i}`"
|
||||
placeholder="target"
|
||||
:options="exceptionTgtOptions"
|
||||
placeholder="Pick value"
|
||||
aria-label="Extra exception target"
|
||||
@update:model-value="(v) => onExtraFieldChange(i, 'target_value', v)"
|
||||
/>
|
||||
:data-test="`ex-extra-tgt-${i}`"
|
||||
@update:model-value="(v) => onExtraFieldChange(i, 'target_value', String(v ?? ''))"
|
||||
>
|
||||
<template #label="{ option }">
|
||||
<RichTextPreview
|
||||
:value="String(option.value) === '' ? option.label : String(option.value)"
|
||||
:uuid-to-name="uuidToName"
|
||||
surface="wildcard"
|
||||
/>
|
||||
</template>
|
||||
<template #option="{ option }">
|
||||
<RichTextPreview
|
||||
:value="String(option.value) === '' ? option.label : String(option.value)"
|
||||
:uuid-to-name="uuidToName"
|
||||
surface="wildcard"
|
||||
/>
|
||||
</template>
|
||||
</Select>
|
||||
<button
|
||||
type="button"
|
||||
class="ex__mode-chip"
|
||||
@@ -651,6 +705,14 @@ function bumpExtraFactor(idx: number, dir: 1 | -1): void {
|
||||
}
|
||||
.ex__arrow { color: var(--wp-text-dim, var(--wp-text3)); }
|
||||
|
||||
/* Extra-exception value pickers share the row width with the mode chip +
|
||||
* factor + trash. flex:1 + min-width:0 lets the two Selects split the free
|
||||
* space instead of overflowing the row. */
|
||||
.ex__extra-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* Styled checkbox — mirror of OptionRow's `.opt__check` pattern so
|
||||
* users see one consistent on/off control across wildcard / fixed-
|
||||
* values / constraint edit modals. */
|
||||
|
||||
@@ -578,6 +578,12 @@ onBeforeUnmount(() => {
|
||||
max-width: 100%;
|
||||
max-height: 52vh;
|
||||
overflow: auto;
|
||||
/* Own stacking context: the frozen header/corner cells below use z-index up
|
||||
* to 5, which without isolation compete in the modal's root context and
|
||||
* paint OVER the sticky footer/reach dock (z-index 2) — the matrix's headers
|
||||
* + scrollbar bled onto the runtime options on a tall matrix. Isolating
|
||||
* keeps those z-indexes local so the whole grid sits under the dock. */
|
||||
isolation: isolate;
|
||||
background: var(--wp-bg-deep, #0e1015);
|
||||
border: 1px solid var(--wp-border);
|
||||
border-radius: 6px;
|
||||
|
||||
@@ -153,6 +153,30 @@ describe("TargetReachSection — pick checklist", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("clicking anywhere on a pick row toggles it, not just the 14px checkbox", async () => {
|
||||
const { w, updates } = mountSection({ mode: "pick", picks: [] });
|
||||
// Click the NAME cell — previously inert, the checkbox was the only
|
||||
// hit target.
|
||||
await w.find('[data-test="reach-pick-1#mood-a"] .rh-pick__name').trigger("click");
|
||||
expect(last(updates)).toEqual({
|
||||
mode: "pick",
|
||||
picks: [{ kind: "direct", uid: "mood-a" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("a checkbox click toggles exactly once (row handler must not double-fire)", async () => {
|
||||
// The row handler and WpCheck both see the click as it bubbles. If the
|
||||
// row didn't bail on interactive descendants the second toggle would
|
||||
// undo the first and ticking would appear to do nothing.
|
||||
const { w, updates } = mountSection({ mode: "pick", picks: [] });
|
||||
await w.find('[data-test="reach-pick-1#mood-a"] .wp-check').trigger("click");
|
||||
expect(updates).toHaveLength(1);
|
||||
expect(last(updates)).toEqual({
|
||||
mode: "pick",
|
||||
picks: [{ kind: "direct", uid: "mood-a" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("nested row labels the @TARGET ref (display name) hosted in the carrier (display name, no @)", () => {
|
||||
const { w } = mountSection({ mode: "pick", picks: [] }, { targetName: "test-target" });
|
||||
const nestedRow = w.find('[data-test="reach-pick-2#backdrop-b::opt_a"]');
|
||||
|
||||
@@ -260,6 +260,16 @@ function togglePick(entry: PickEntry): void {
|
||||
emit("update:modelValue", { mode: "pick", picks: next });
|
||||
}
|
||||
|
||||
/** Pointer clicks anywhere on a pick row toggle it. Clicks that started
|
||||
* inside the WpCheck (or any future interactive descendant) are ignored —
|
||||
* the control already emitted its own toggle, and handling it twice would
|
||||
* cancel the change out. */
|
||||
function onPickRowClick(ev: MouseEvent, entry: PickEntry): void {
|
||||
const target = ev.target as HTMLElement | null;
|
||||
if (target?.closest?.("button, input, a, label, .wp-check")) return;
|
||||
togglePick(entry);
|
||||
}
|
||||
|
||||
// ── Consequence hint ────────────────────────────────────────────
|
||||
const reachCount = computed(() => pickRows.value.length);
|
||||
const hint = computed<string>(() => {
|
||||
@@ -338,14 +348,18 @@ const hint = computed<string>(() => {
|
||||
class="rh-pick__empty"
|
||||
data-test="reach-pick-empty"
|
||||
>No reachable target instances — use first / next / all.</div>
|
||||
<!-- WpCheck is the interactive control (own role/keyboard + aria-
|
||||
label); the row is presentational so the checkbox is the single
|
||||
focus/click target — no redundant row-level handler. -->
|
||||
<!-- WpCheck remains the single FOCUS target (it owns role + keyboard
|
||||
+ aria-label), so keyboard and screen-reader users get exactly one
|
||||
stop per row. The row additionally takes POINTER clicks: hitting a
|
||||
14px checkbox for every pick was needless precision work. The two
|
||||
don't double-toggle because `onPickRowClick` bails on any click
|
||||
that originated inside an interactive descendant. -->
|
||||
<div
|
||||
v-for="row in pickRows"
|
||||
:key="row.key"
|
||||
class="rh-pick__row"
|
||||
:data-test="`reach-pick-${row.key}`"
|
||||
@click="onPickRowClick($event, row.entry)"
|
||||
>
|
||||
<WpCheck
|
||||
:model-value="isPicked(row.entry)"
|
||||
|
||||
@@ -12,10 +12,12 @@
|
||||
* Section order matches all shipped v2 modals: Header → Identity →
|
||||
* Rules (kind-specific) → Runtime → Footer.
|
||||
*/
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { computed, inject, onMounted, ref } from "vue";
|
||||
import { saveChordLabel } from "../../../shared/platform-keys";
|
||||
import type { ModuleEntry } from "../../../../widgets/_shared";
|
||||
import type { PairingBadge } from "../../../../extension/constraint-pairs";
|
||||
import type { ModuleRow } from "../../../../manager/api/types";
|
||||
import type { VarProducerLike } from "../../../../manager/components/RefChip.vue";
|
||||
import {
|
||||
buildWildcardRefData,
|
||||
collectLibraryWildcardRefs,
|
||||
@@ -23,7 +25,12 @@ import {
|
||||
import IdentitySection from "./sections/IdentitySection.vue";
|
||||
import RulesSection from "./sections/RulesSection.vue";
|
||||
import RuntimeSection from "./sections/RuntimeSection.vue";
|
||||
import InstanceIdChip from "../InstanceIdChip.vue";
|
||||
import { CONTEXT_POOLS_KEY, overlayContextPools } from "../../../../extension/context-pools";
|
||||
|
||||
|
||||
/** Platform-correct save chord for the footer hint. */
|
||||
const saveChord = saveChordLabel();
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
module: ModuleEntry;
|
||||
@@ -34,6 +41,8 @@ const props = withDefaults(
|
||||
/** Vars produced upstream of this Context node — forwarded as the
|
||||
* `$var` autocomplete list for the rule override fields. */
|
||||
upstreamVars?: string[];
|
||||
/** `$var` → its producing module + node, for the chip hover cards. */
|
||||
upstreamProducers?: Record<string, VarProducerLike>;
|
||||
/** Vars produced by other modules in the SAME Context node. */
|
||||
siblingVars?: string[];
|
||||
/** Via-nested constraint-pair badges for this derivation when it acts
|
||||
@@ -64,11 +73,25 @@ const props = withDefaults(
|
||||
// `moduleStore.catalog`. The canvas has no Pinia store, so we fetch the
|
||||
// library ONCE when the modal mounts (same `/wp/api/modules` source the
|
||||
// ModulePickerModal reads) and build the SAME maps via the shared
|
||||
// `buildWildcardRefData`. The `@{}` source is the LIBRARY (by identity),
|
||||
// NOT this Context node's chain — a chain sibling would be a `$var`.
|
||||
// `buildWildcardRefData`.
|
||||
//
|
||||
// A `@{}` addresses a wildcard BY IDENTITY, so the candidate list is the
|
||||
// library — a chain sibling would be a `$var`. What the ref then RESOLVES
|
||||
// against is a separate question, answered by the overlay below.
|
||||
const catalog = ref<ModuleRow[]>([]);
|
||||
|
||||
const refData = computed(() => buildWildcardRefData(catalog.value));
|
||||
// Library-derived picker data, then the node's OWN pools overlaid on top.
|
||||
//
|
||||
// The engine resolves a nested `@{}` ref against this node's snapshot whenever
|
||||
// the uuid is also a module here, falling back to the library otherwise. The
|
||||
// picker used to offer the library's tags unconditionally, so on a drifted
|
||||
// snapshot it listed a tag no option in the RUNNING pool carries — pick it and
|
||||
// the ref resolves to nothing, with the checkbox list itself being the thing
|
||||
// that misled you. Same precedence the hover card applies, so card, picker and
|
||||
// engine now describe one pool.
|
||||
const contextPools = inject(CONTEXT_POOLS_KEY, undefined);
|
||||
const refData = computed(() =>
|
||||
overlayContextPools(buildWildcardRefData(catalog.value), contextPools?.value));
|
||||
const uuidToName = computed(() => refData.value.uuidToName);
|
||||
// Library wildcard uuids for `@{}` autocomplete, excluding this module's own
|
||||
// id (a wildcard never nests itself) — sorted by display name to mirror the
|
||||
@@ -86,6 +109,12 @@ const varSuggestions = computed<string[]>(() => {
|
||||
return [...set].sort();
|
||||
});
|
||||
|
||||
/** Producer lookup for the chip hover cards. A Map because RefChip reads it
|
||||
* per-chip and `Map.get` beats rebuilding an object lookup on every render. */
|
||||
const varProducerMap = computed<Map<string, VarProducerLike>>(
|
||||
() => new Map(Object.entries(props.upstreamProducers ?? {})),
|
||||
);
|
||||
|
||||
onMounted(async () => {
|
||||
// Fire-and-forget: until this resolves the ref-data maps stay empty, so
|
||||
// autocomplete simply shows nothing + summary chips fall back to cached
|
||||
@@ -137,6 +166,7 @@ function onSpaClick(): void {
|
||||
<div class="wp-dvm__title-row">
|
||||
<span class="wp-dvm__name" data-test="dvm-name">{{ module.meta?.name ?? module.type }}</span>
|
||||
<span class="wp-dvm__chip" data-test="dvm-chip">derivation</span>
|
||||
<InstanceIdChip :id="module.id" :uid="module._uid" />
|
||||
</div>
|
||||
<div class="wp-dvm__sub">Library entry · conditional rule-based variable rewrites</div>
|
||||
</div>
|
||||
@@ -153,6 +183,7 @@ function onSpaClick(): void {
|
||||
<RulesSection
|
||||
:module="module"
|
||||
:var-suggestions="varSuggestions"
|
||||
:var-producers="varProducerMap"
|
||||
:ref-suggestions="refSuggestions"
|
||||
:uuid-to-name="uuidToName"
|
||||
:uuid-to-sub-categories="refData.uuidToSubCategories"
|
||||
@@ -190,7 +221,7 @@ function onSpaClick(): void {
|
||||
Reset overrides
|
||||
</button>
|
||||
<span class="wp-dvm__hint">
|
||||
<kbd>Esc</kbd> cancel · <kbd>⌘↵</kbd> save
|
||||
<kbd>Esc</kbd> cancel · <kbd>{{ saveChord }}</kbd> save
|
||||
</span>
|
||||
<button
|
||||
v-if="canSaveToLibrary"
|
||||
@@ -216,7 +247,17 @@ function onSpaClick(): void {
|
||||
max-height: 80vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
/* The MODAL does not scroll — only the RULES list inside does (it caps at
|
||||
* an absolute max-height and scrolls in place). overflow:hidden here forces
|
||||
* that: it's the only overflow path, so header + identity stay pinned at
|
||||
* the top and the dock at the bottom while the rules scroll between them.
|
||||
* (overflow-y:auto on the modal instead let the WHOLE modal scroll, sliding
|
||||
* the bottom rules under the sticky dock — the "can't see the full rules"
|
||||
* bug. An absolute inner max-height — not flex:1, which collapses because
|
||||
* the overlay parents carry only max-height:100% — is the load-bearing
|
||||
* part; RulesSection sizes it to 80vh minus this fixed chrome so nothing
|
||||
* clips.) */
|
||||
overflow: hidden;
|
||||
font-family: var(--wp-font-sans, sans-serif);
|
||||
font-size: 12px;
|
||||
color: var(--wp-text);
|
||||
@@ -228,6 +269,7 @@ function onSpaClick(): void {
|
||||
bottom: 0;
|
||||
z-index: 2;
|
||||
background: var(--wp-bg2);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.wp-dvm__foot {
|
||||
display: flex;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import RuleValueChips from "./RuleValueChips.vue";
|
||||
|
||||
// Issue #1: nested `@{uuid}` / `$var` inside an inline `{a|b}` block used to
|
||||
// render as raw hex because RuleValueChips dumped the whole dp-brace token as
|
||||
// text. It now delegates to RichTextPreview (which decomposes braces via
|
||||
// atomicEditorModel.parse and chips every ref/var via RefChip), so the inner
|
||||
// refs chip at brace depth too.
|
||||
describe("RuleValueChips — nested refs inside braces", () => {
|
||||
const names = new Map([
|
||||
["beef0001", "standing"],
|
||||
["beef0002", "sitting"],
|
||||
]);
|
||||
|
||||
it("chips each @{} ref inside a {a|b} block (not raw hex)", () => {
|
||||
const w = mount(RuleValueChips, {
|
||||
props: { value: "{@{beef0001}|@{beef0002}}", uuidToName: names },
|
||||
});
|
||||
// Two inner refs → two RefChips; raw uuid hex must not leak as text.
|
||||
expect(w.findAllComponents({ name: "RefChip" }).length).toBe(2);
|
||||
expect(w.text()).not.toContain("beef0001");
|
||||
expect(w.text()).toContain("standing");
|
||||
expect(w.text()).toContain("sitting");
|
||||
});
|
||||
|
||||
it("chips a $var reference too", () => {
|
||||
const w = mount(RuleValueChips, { props: { value: "$pose_standing" } });
|
||||
expect(w.findAllComponents({ name: "RefChip" }).length).toBe(1);
|
||||
expect(w.text()).toContain("pose_standing");
|
||||
});
|
||||
|
||||
it("renders a distinct 'empty' state (not '?') for an empty value", () => {
|
||||
// Empty replace is valid — must read as an intentional empty, not a
|
||||
// failed resolve. No RefChip, no bare '?'.
|
||||
const w = mount(RuleValueChips, { props: { value: "" } });
|
||||
const empty = w.find('[data-test="rvc-empty"]');
|
||||
expect(empty.exists()).toBe(true);
|
||||
expect(empty.text()).toContain("empty");
|
||||
expect(w.text()).not.toContain("?");
|
||||
expect(w.findAllComponents({ name: "RefChip" }).length).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,201 +1,93 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* RuleValueChips — read-only chip renderer for a derivation rule's
|
||||
* action.value / condition.value strings inside the canvas instance modal
|
||||
* summary. Tokenizes the value and renders `@{uuid}` nested-wildcard refs +
|
||||
* `$var` references as CHIPS, brace blocks / escapes as colored spans — so a
|
||||
* value like `@{ad00acd5#mood:warm}` reads as a `@mood` chip with a funnel
|
||||
* mark instead of leaking raw hex.
|
||||
* action.value / condition.value strings in the canvas instance-modal
|
||||
* summary. Thin wrapper over the shared {@link RichTextPreview}: it owns only
|
||||
* the empty-value placeholder; all token rendering (var/ref chips at EVERY
|
||||
* brace depth, brace/escape scaffolding) delegates to RichTextPreview so a
|
||||
* value like `{@{a}|@{b}}` chips its inner refs instead of leaking raw hex.
|
||||
*
|
||||
* Chip markup + CSS are copied verbatim from the wildcard editor's OptionRow
|
||||
* (`editors/wildcard/sections/OptionRow.vue`) so the canvas reads identically
|
||||
* to the option-value chips. Names resolve from the modal-supplied
|
||||
* `uuidToName` map (the live library catalog) — no preview-resolver dep on
|
||||
* this surface. A missing display value renders the placeholder text.
|
||||
* Previously this hand-rolled a `tokenizeRich` loop that emitted `dp-brace`
|
||||
* blocks as `{{ tok.raw }}` — so nested `@{}` / `$var` inside `{a|b}` never
|
||||
* chipped (issue #1). Consolidating on RichTextPreview (which decomposes
|
||||
* braces via `atomicEditorModel.parse` and renders every chip as `RefChip`)
|
||||
* fixes that AND means one hover/click surface for all chips.
|
||||
*
|
||||
* `surface="wildcard"` so refs render as ACTIVE purple chips (derivation
|
||||
* action values are `@{}` carriers — the engine resolves them), matching the
|
||||
* prior appearance; `$var` reads still render as green var chips.
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
import { splitRefFilter, tokenizeRich, type RichToken } from "../../../../../widgets/richTokenize";
|
||||
import { parse, readsAs } from "@/manager/parsing/subcatFilter";
|
||||
import RichTextPreview from "../../../../../manager/components/RichTextPreview.vue";
|
||||
import type { VarProducerLike } from "../../../../../manager/components/RefChip.vue";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
value?: string;
|
||||
/** UUID → display name, from the modal's catalog fetch. Empty until the
|
||||
* fetch resolves — chips fall back to the token's cached `#name`. */
|
||||
uuidToName?: Map<string, string>;
|
||||
/** Shown when `value` is empty (mirrors the old `|| "?"` placeholder). */
|
||||
/** UUID → display name, from the modal's catalog fetch. Forwarded to
|
||||
* RichTextPreview so ref chips show the human label. */
|
||||
uuidToName?: ReadonlyMap<string, string>;
|
||||
/** Label for the empty state. Defaults to "empty" — an empty value is a
|
||||
* VALID derivation action (replace-with-nothing), so it must read as an
|
||||
* intentional empty, NOT the `?` that looked like a failed resolve. */
|
||||
placeholder?: string;
|
||||
/** `$var` → producer, so the summary chips' hover cards can name who
|
||||
* writes the variable instead of falling back to "binds at runtime". */
|
||||
varProducers?: ReadonlyMap<string, VarProducerLike>;
|
||||
/** Canvas host — a missing producer is a real finding here. */
|
||||
graphAware?: boolean;
|
||||
}>(),
|
||||
{ value: "", uuidToName: () => new Map(), placeholder: "?" },
|
||||
{
|
||||
value: "", uuidToName: () => new Map(), placeholder: "empty",
|
||||
varProducers: () => new Map(), graphAware: false,
|
||||
},
|
||||
);
|
||||
|
||||
const tokens = computed<RichToken[]>(() => tokenizeRich(props.value ?? ""));
|
||||
const isEmpty = computed(() => (props.value ?? "").length === 0);
|
||||
|
||||
/** Human label for a ref chip — `@name` from the live map, else the cached
|
||||
* `#name` (stripping a leaked `!null`), else the raw token. Mirrors
|
||||
* OptionRow.refDisplay's fallback chain. */
|
||||
function refDisplay(tok: RichToken): string {
|
||||
const uuid = tok.meta?.uuid;
|
||||
if (!uuid) return tok.raw;
|
||||
const live = props.uuidToName.get(uuid);
|
||||
if (live && live.trim()) return `@${live.trim()}`;
|
||||
const cached = typeof tok.meta?.name === "string" ? tok.meta.name : "";
|
||||
if (cached.trim()) return `@${cached.split("!")[0].trim() || cached.trim()}`;
|
||||
return tok.raw;
|
||||
}
|
||||
|
||||
/** Ref uuid absent from the live map → broken reference. Empty map (pre-fetch)
|
||||
* is "unknown, not broken" so chips don't flash red while loading. */
|
||||
function refIsUnresolved(tok: RichToken): boolean {
|
||||
const uuid = tok.meta?.uuid;
|
||||
if (!uuid) return false;
|
||||
if (props.uuidToName.size === 0) return false;
|
||||
return !props.uuidToName.has(uuid);
|
||||
}
|
||||
|
||||
interface RefFilterInfo { hasExpr: boolean; excludeNull: boolean; isFiltered: boolean; title: string }
|
||||
const _refFilterMemo = new WeakMap<RichToken, RefFilterInfo>();
|
||||
/** Funnel (sub-cat expression) + ban (null excluded) marks + hover title.
|
||||
* Copied from OptionRow.refFilter. */
|
||||
function refFilter(tok: RichToken): RefFilterInfo {
|
||||
const cached = _refFilterMemo.get(tok);
|
||||
if (cached) return cached;
|
||||
const subs = tok.meta?.sub_categories;
|
||||
let expr = "";
|
||||
let excludeNull = false;
|
||||
if (Array.isArray(subs) && subs.length > 0) {
|
||||
({ expr, excludeNull } = splitRefFilter(subs.join(",")));
|
||||
} else {
|
||||
const name = typeof tok.meta?.name === "string" ? tok.meta.name : "";
|
||||
const bang = name.indexOf("!");
|
||||
if (bang >= 0) excludeNull = name.slice(bang + 1) === "null";
|
||||
}
|
||||
let reads = "";
|
||||
if (expr) {
|
||||
try { reads = readsAs(parse(expr)); } catch { reads = expr; }
|
||||
}
|
||||
const parts: string[] = [];
|
||||
if (reads) parts.push(reads);
|
||||
if (excludeNull) parts.push("null excluded");
|
||||
const info: RefFilterInfo = {
|
||||
hasExpr: expr.length > 0,
|
||||
excludeNull,
|
||||
isFiltered: expr.length > 0 || excludeNull,
|
||||
title: parts.join(" · "),
|
||||
};
|
||||
_refFilterMemo.set(tok, info);
|
||||
return info;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="rvc">
|
||||
<span v-if="isEmpty" class="rvc__placeholder">{{ placeholder }}</span>
|
||||
<template v-for="(tok, idx) in tokens" v-else :key="idx">
|
||||
<span
|
||||
v-if="tok.kind === 'ref'"
|
||||
class="rvc__tok rvc__tok--ref"
|
||||
:class="{
|
||||
'rvc__tok--filtered': refFilter(tok).isFiltered,
|
||||
'rvc__tok--unresolved': refIsUnresolved(tok),
|
||||
}"
|
||||
:data-uuid="tok.meta?.uuid"
|
||||
:title="refIsUnresolved(tok)
|
||||
? `Reference ${tok.meta?.uuid} not in library`
|
||||
: (refFilter(tok).title || undefined)"
|
||||
>
|
||||
<span class="rvc__tok-icon" aria-hidden="true">{{ refIsUnresolved(tok) ? '?' : '✦' }}</span>
|
||||
<span class="rvc__tok-label">{{ refDisplay(tok) }}</span>
|
||||
<span
|
||||
v-if="refFilter(tok).isFiltered"
|
||||
class="rvc__tok-filter"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<i v-if="refFilter(tok).hasExpr" class="pi pi-filter rvc__tok-funnel"></i>
|
||||
<i v-if="refFilter(tok).excludeNull" class="pi pi-ban rvc__tok-nonull"></i>
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
v-else-if="tok.kind === 'var'"
|
||||
class="rvc__tok rvc__tok--var"
|
||||
>
|
||||
<span class="rvc__tok-icon" aria-hidden="true">⌘</span>
|
||||
<span class="rvc__tok-label">{{ tok.raw }}</span>
|
||||
</span>
|
||||
<span v-else-if="tok.kind === 'dp-brace'" class="rvc__tok rvc__tok--brace">{{ tok.raw }}</span>
|
||||
<span v-else-if="tok.kind === 'dp-multi'" class="rvc__tok rvc__tok--multi">{{ tok.raw }}</span>
|
||||
<span v-else-if="tok.kind === 'escape'" class="rvc__tok rvc__tok--escape">{{ tok.raw }}</span>
|
||||
<template v-else>{{ tok.raw }}</template>
|
||||
</template>
|
||||
<!-- Empty is a first-class, VALID state (replace $var with ""). Render a
|
||||
muted ∅ pill — visually distinct from both a real value (chips) and an
|
||||
unresolved/broken ref (red) — so it never reads as "didn't resolve". -->
|
||||
<span
|
||||
v-if="isEmpty"
|
||||
class="rvc__empty"
|
||||
title="Replaced with an empty value"
|
||||
data-test="rvc-empty"
|
||||
>
|
||||
<span class="rvc__empty-glyph" aria-hidden="true">∅</span>{{ placeholder }}
|
||||
</span>
|
||||
<RichTextPreview
|
||||
v-else
|
||||
:value="value"
|
||||
:uuid-to-name="uuidToName"
|
||||
:var-producers="varProducers"
|
||||
:graph-aware="graphAware"
|
||||
surface="wildcard"
|
||||
/>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* Inline-syntax chips — palette + icon prefix copied from the wildcard
|
||||
* OptionRow (`editors/wildcard/sections/OptionRow.vue`) so an `@nestedName`
|
||||
* reads the same in the derivation summary as in an option value: purple ✦
|
||||
* for refs, green ⌘ for vars, amber funnel/ban filter marks. */
|
||||
.rvc {
|
||||
display: inline;
|
||||
}
|
||||
.rvc__placeholder {
|
||||
color: var(--wp-text);
|
||||
background: color-mix(in srgb, var(--wp-text-dim, var(--wp-text3)) 12%, transparent);
|
||||
padding: 0 4px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
.rvc__tok {
|
||||
margin: 0 1px;
|
||||
font-weight: 500;
|
||||
.rvc__empty {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
vertical-align: baseline;
|
||||
}
|
||||
.rvc__tok--ref,
|
||||
.rvc__tok--var {
|
||||
border-radius: 3px;
|
||||
padding: 0 5px;
|
||||
gap: 3px;
|
||||
border: 1px solid;
|
||||
font: 10px/1.4 var(--wp-font-mono);
|
||||
padding: 0 5px;
|
||||
border: 1px dashed color-mix(in srgb, var(--wp-text-dim, var(--wp-text3)) 45%, transparent);
|
||||
border-radius: 3px;
|
||||
color: var(--wp-text-dim, var(--wp-text3));
|
||||
font: italic 10px/1.4 var(--wp-font-mono);
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
.rvc__tok-icon { font-size: 8px; opacity: 0.75; }
|
||||
.rvc__tok-filter {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
margin-left: 2px;
|
||||
color: var(--wp-status-modified, #fbbf24);
|
||||
}
|
||||
.rvc__tok-funnel { font-size: 8px; line-height: 1; }
|
||||
.rvc__tok-nonull { font-size: 8px; line-height: 1; opacity: 0.85; }
|
||||
.rvc__tok--ref {
|
||||
background: color-mix(in srgb, var(--wp-kind-wildcard, #a855f7) 15%, transparent);
|
||||
border-color: color-mix(in srgb, var(--wp-kind-wildcard, #a855f7) 50%, transparent);
|
||||
color: var(--wp-kind-wildcard);
|
||||
}
|
||||
.rvc__tok--ref.rvc__tok--unresolved {
|
||||
background: color-mix(in srgb, var(--wp-danger, #ef4444) 15%, transparent);
|
||||
border-color: color-mix(in srgb, var(--wp-danger, #ef4444) 50%, transparent);
|
||||
color: var(--wp-danger, #ef4444);
|
||||
cursor: help;
|
||||
}
|
||||
.rvc__tok--var {
|
||||
background: color-mix(in srgb, var(--wp-success, #22c55e) 15%, transparent);
|
||||
border-color: color-mix(in srgb, var(--wp-success, #22c55e) 50%, transparent);
|
||||
color: var(--wp-success);
|
||||
}
|
||||
.rvc__tok--brace {
|
||||
color: var(--wp-warn, #fcd34d);
|
||||
font-weight: 600;
|
||||
}
|
||||
.rvc__tok--multi {
|
||||
color: var(--wp-rt-token-good, #4ad4c4);
|
||||
font-weight: 500;
|
||||
}
|
||||
.rvc__tok--escape {
|
||||
color: var(--wp-text-muted, var(--wp-text2));
|
||||
opacity: 0.7;
|
||||
.rvc__empty-glyph {
|
||||
font-size: 9px;
|
||||
font-style: normal;
|
||||
opacity: 0.8;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
import { computed, defineAsyncComponent, ref } from "vue";
|
||||
import type { ModuleEntry } from "../../../../../widgets/_shared";
|
||||
import type { PairingBadge } from "../../../../../extension/constraint-pairs";
|
||||
import type { VarProducerLike } from "../../../../../manager/components/RefChip.vue";
|
||||
import { patchInstance } from "../../instance/patch";
|
||||
import { varColorClass } from "../../../../shared/var-color";
|
||||
import RuleValueChips from "./RuleValueChips.vue";
|
||||
@@ -57,6 +58,9 @@ const props = withDefaults(
|
||||
/** `$var` autocomplete list for the override RichTextInputs —
|
||||
* upstream + sibling producer vars, forwarded by the modal. */
|
||||
varSuggestions?: string[];
|
||||
/** `$var` → producing module + node, forwarded to the override fields'
|
||||
* RichTextInputs so their var chips can name the producer on hover. */
|
||||
varProducers?: Map<string, VarProducerLike>;
|
||||
/** Library WILDCARD uuids for the `@{}` autocomplete (ACTION /
|
||||
* ELSE-action inputs only — `condition.value` is compared raw). */
|
||||
refSuggestions?: string[];
|
||||
@@ -81,6 +85,7 @@ const props = withDefaults(
|
||||
}>(),
|
||||
{
|
||||
varSuggestions: () => [],
|
||||
varProducers: () => new Map(),
|
||||
refSuggestions: () => [],
|
||||
uuidToName: () => new Map(),
|
||||
uuidToSubCategories: () => new Map(),
|
||||
@@ -363,6 +368,68 @@ function modeLabel(mode: string | undefined): string {
|
||||
function opUsesValue(op: string | undefined): boolean {
|
||||
return op !== "exists" && op !== "not_exists" && op !== "is_set" && op !== "is_unset";
|
||||
}
|
||||
|
||||
/**
|
||||
* Longest value a preview row will render before it gets cut.
|
||||
*
|
||||
* The summary wraps, which is what makes a multi-chip value readable — but a
|
||||
* paragraph-length override then ran to dozens of lines and pushed the rest of
|
||||
* the modal off screen. Capping the VALUE rather than the layout keeps every
|
||||
* normal row exactly as it was (chips, wrapping, all of it visible) and only
|
||||
* touches the outliers. `title` still carries the full text on hover.
|
||||
*/
|
||||
const SUMMARY_MAX_CHARS = 120;
|
||||
|
||||
/**
|
||||
* Cut `value` to `SUMMARY_MAX_CHARS` and append an ellipsis, never splitting a
|
||||
* `@{...}` token — half a token would render as literal text instead of a
|
||||
* chip, which looks like corruption rather than truncation. A token that would
|
||||
* straddle the limit is dropped whole.
|
||||
*/
|
||||
function clampPreviewValue(value: unknown): string {
|
||||
const s = typeof value === "string" ? value : "";
|
||||
if (s.length <= SUMMARY_MAX_CHARS) return s;
|
||||
// Capturing split keeps the `@{...}` tokens as their own segments.
|
||||
const segments = s.split(/(@\{[^}]*\})/g);
|
||||
let out = "";
|
||||
for (const seg of segments) {
|
||||
if (out.length >= SUMMARY_MAX_CHARS) break;
|
||||
if (seg.startsWith("@{")) {
|
||||
if (out.length > 0 && out.length + seg.length > SUMMARY_MAX_CHARS) break;
|
||||
out += seg;
|
||||
} else {
|
||||
out += seg.slice(0, SUMMARY_MAX_CHARS - out.length);
|
||||
}
|
||||
}
|
||||
return out.length < s.length ? `${out.trimEnd()}…` : out;
|
||||
}
|
||||
|
||||
/** Plain-text rendering of a branch, for the `title` on the preview rows —
|
||||
* the visible summary caps long values, so this is how the user reads the
|
||||
* rest. */
|
||||
function branchSummaryText(
|
||||
branch: { condition?: { var?: string; op?: string; value?: string };
|
||||
action?: { target_var?: string; mode?: string; value?: string } } | undefined,
|
||||
): string {
|
||||
if (!branch) return "";
|
||||
const parts: string[] = [];
|
||||
const c = branch.condition;
|
||||
if (c?.var) {
|
||||
parts.push(`$${c.var} ${opSymbol(c.op)}`);
|
||||
if (opUsesValue(c.op) && c.value) parts.push(c.value);
|
||||
}
|
||||
const a = branch.action;
|
||||
if (a?.target_var) parts.push(`→ $${a.target_var} ${modeLabel(a.mode)} ${a.value ?? ""}`);
|
||||
return parts.join(" ").trim();
|
||||
}
|
||||
|
||||
/** Same, for the collapsed rule head — which previews its FIRST branch. */
|
||||
function ruleSummaryText(rule: DerivationRule): string {
|
||||
const first = rule.branches?.[0];
|
||||
const head = branchSummaryText(first);
|
||||
const n = rule.branches?.length ?? 0;
|
||||
return n > 1 ? `${head} (+${n - 1} more branch${n - 1 === 1 ? "" : "es"})` : head;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -422,7 +489,11 @@ function opUsesValue(op: string | undefined): boolean {
|
||||
|
||||
<span class="rule-head__num" :title="`Rule id ${rule.id}`">Rule {{ ruleIdx + 1 }}</span>
|
||||
|
||||
<span class="rule-head__summary" :data-test="`rule-summary-${rule.id}`">
|
||||
<span
|
||||
class="rule-head__summary"
|
||||
:title="ruleSummaryText(rule)"
|
||||
:data-test="`rule-summary-${rule.id}`"
|
||||
>
|
||||
<template v-if="rule.branches && rule.branches.length > 0">
|
||||
<span
|
||||
v-if="rule.branches[0].condition?.var"
|
||||
@@ -432,14 +503,14 @@ function opUsesValue(op: string | undefined): boolean {
|
||||
<span
|
||||
v-if="opUsesValue(rule.branches[0].condition?.op)"
|
||||
class="rule-tok-val"
|
||||
><RuleValueChips :value="rule.branches[0].condition?.value" :uuid-to-name="uuidToName" /></span>
|
||||
><RuleValueChips :value="clampPreviewValue(rule.branches[0].condition?.value)" :uuid-to-name="uuidToName" :var-producers="varProducers" graph-aware /></span>
|
||||
<span class="rule-tok-arrow">→</span>
|
||||
<span
|
||||
v-if="rule.branches[0].action?.target_var"
|
||||
:class="['rule-tok-var', varColorClass(rule.branches[0].action.target_var)]"
|
||||
>${{ rule.branches[0].action.target_var }}</span>
|
||||
<span class="rule-tok-op">{{ modeLabel(rule.branches[0].action?.mode) }}</span>
|
||||
<span class="rule-tok-val"><RuleValueChips :value="rule.branches[0].action?.value" :uuid-to-name="uuidToName" /></span>
|
||||
<span class="rule-tok-val"><RuleValueChips :value="clampPreviewValue(rule.branches[0].action?.value)" :uuid-to-name="uuidToName" :var-producers="varProducers" graph-aware /></span>
|
||||
<!-- Inline ↪#N constraint-pair badge — rendered when this
|
||||
derivation is a constraint carrier through the IF branch's
|
||||
nested `@{uuid}` ref. Mirrors OptionRow's per-option badge
|
||||
@@ -518,7 +589,7 @@ function opUsesValue(op: string | undefined): boolean {
|
||||
<span class="branch-cell branch-cell--tag" :data-kind="bi === 0 ? 'if' : 'elif'">
|
||||
{{ bi === 0 ? "IF" : "ELIF" }}
|
||||
</span>
|
||||
<span class="branch-cell branch-cell--summary">
|
||||
<span class="branch-cell branch-cell--summary" :title="branchSummaryText(branch)">
|
||||
<span
|
||||
v-if="branch.condition?.var"
|
||||
:class="['rule-tok-var', varColorClass(branch.condition.var)]"
|
||||
@@ -527,14 +598,14 @@ function opUsesValue(op: string | undefined): boolean {
|
||||
<span
|
||||
v-if="opUsesValue(branch.condition?.op)"
|
||||
class="rule-tok-val"
|
||||
><RuleValueChips :value="branch.condition?.value" :uuid-to-name="uuidToName" /></span>
|
||||
><RuleValueChips :value="clampPreviewValue(branch.condition?.value)" :uuid-to-name="uuidToName" :var-producers="varProducers" graph-aware /></span>
|
||||
<span class="rule-tok-arrow">→</span>
|
||||
<span
|
||||
v-if="branch.action?.target_var"
|
||||
:class="['rule-tok-var', varColorClass(branch.action.target_var)]"
|
||||
>${{ branch.action.target_var }}</span>
|
||||
<span class="rule-tok-op">{{ modeLabel(branch.action?.mode) }}</span>
|
||||
<span class="rule-tok-val"><RuleValueChips :value="branch.action?.value" :uuid-to-name="uuidToName" /></span>
|
||||
<span class="rule-tok-val"><RuleValueChips :value="clampPreviewValue(branch.action?.value)" :uuid-to-name="uuidToName" :var-producers="varProducers" graph-aware /></span>
|
||||
<PairBadge
|
||||
v-for="p in pairBadgesFor(rule.id, bi)"
|
||||
:key="`${p.number}-${p.targetUuid}`"
|
||||
@@ -551,7 +622,8 @@ function opUsesValue(op: string | undefined): boolean {
|
||||
<RichTextInput
|
||||
v-if="opUsesValue(branch.condition?.op)"
|
||||
surface="derivation"
|
||||
:var-suggestions="varSuggestions"
|
||||
wrap
|
||||
:var-suggestions="varSuggestions" :var-producers="varProducers" graph-aware
|
||||
:uuid-to-name="uuidToName"
|
||||
:model-value="getOverride('condition_value_overrides', rule.id, String(bi))"
|
||||
:placeholder="branch.condition?.value || ''"
|
||||
@@ -570,7 +642,8 @@ function opUsesValue(op: string | undefined): boolean {
|
||||
<RichTextInput
|
||||
surface="derivation"
|
||||
allow-nested-refs
|
||||
:var-suggestions="varSuggestions"
|
||||
wrap
|
||||
:var-suggestions="varSuggestions" :var-producers="varProducers" graph-aware
|
||||
:ref-suggestions="refSuggestions"
|
||||
:uuid-to-name="uuidToName"
|
||||
:uuid-to-sub-categories="uuidToSubCategories"
|
||||
@@ -610,14 +683,17 @@ function opUsesValue(op: string | undefined): boolean {
|
||||
</span>
|
||||
</span>
|
||||
<span class="branch-cell branch-cell--tag" data-kind="else">ELSE</span>
|
||||
<span class="branch-cell branch-cell--summary">
|
||||
<span
|
||||
class="branch-cell branch-cell--summary"
|
||||
:title="branchSummaryText({ action: rule.else.action })"
|
||||
>
|
||||
<span class="rule-tok-arrow">→</span>
|
||||
<span
|
||||
v-if="rule.else.action?.target_var"
|
||||
:class="['rule-tok-var', varColorClass(rule.else.action.target_var)]"
|
||||
>${{ rule.else.action.target_var }}</span>
|
||||
<span class="rule-tok-op">{{ modeLabel(rule.else.action?.mode) }}</span>
|
||||
<span class="rule-tok-val"><RuleValueChips :value="rule.else.action?.value" :uuid-to-name="uuidToName" /></span>
|
||||
<span class="rule-tok-val"><RuleValueChips :value="clampPreviewValue(rule.else.action?.value)" :uuid-to-name="uuidToName" :var-producers="varProducers" graph-aware /></span>
|
||||
<PairBadge
|
||||
v-for="p in pairBadgesFor(rule.id, 'else')"
|
||||
:key="`${p.number}-${p.targetUuid}`"
|
||||
@@ -633,7 +709,8 @@ function opUsesValue(op: string | undefined): boolean {
|
||||
<RichTextInput
|
||||
surface="derivation"
|
||||
allow-nested-refs
|
||||
:var-suggestions="varSuggestions"
|
||||
wrap
|
||||
:var-suggestions="varSuggestions" :var-producers="varProducers" graph-aware
|
||||
:ref-suggestions="refSuggestions"
|
||||
:uuid-to-name="uuidToName"
|
||||
:uuid-to-sub-categories="uuidToSubCategories"
|
||||
@@ -693,10 +770,34 @@ function opUsesValue(op: string | undefined): boolean {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
/* Long rule lists scroll in place so identity / footer stay visible. */
|
||||
max-height: 44vh;
|
||||
/* Long rule lists scroll IN PLACE so identity / runtime / footer stay put.
|
||||
* Absolute max-height (NOT flex:1) — same load-bearing trick as the
|
||||
* wildcard's .pool__opts — because the modal's overlay parents carry only
|
||||
* max-height:100% (no definite height), so a flex-fill child collapses or
|
||||
* clips here. The cap = the modal budget (80vh, matching .dvm) MINUS the
|
||||
* fixed chrome (header + identity + rules head + runtime/footer dock,
|
||||
* measured ≈ 15rem, padded to 20rem so the dock never clips under .dvm's
|
||||
* overflow:hidden). list + chrome stays under 80vh, so the modal never
|
||||
* scrolls and THIS list owns the only scrollbar. */
|
||||
max-height: calc(80vh - 20rem);
|
||||
overflow-y: auto;
|
||||
/* Keep the scrollbar CLEARLY visible — long rule lists weren't obviously
|
||||
* scrollable before, so users thought rules were truncated. Stronger than
|
||||
* the app's subtle token default on purpose. */
|
||||
scrollbar-width: auto;
|
||||
scrollbar-color: rgba(255, 255, 255, 0.38) transparent;
|
||||
}
|
||||
.rules__list::-webkit-scrollbar { width: 12px; }
|
||||
.rules__list::-webkit-scrollbar-track {
|
||||
background: var(--wp-bg-deep, var(--wp-bg));
|
||||
border-radius: 6px;
|
||||
}
|
||||
.rules__list::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.38);
|
||||
border-radius: 6px;
|
||||
border: 2px solid var(--wp-bg-deep, var(--wp-bg));
|
||||
}
|
||||
.rules__list::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.55); }
|
||||
|
||||
/* Rule card */
|
||||
.rule-card {
|
||||
@@ -704,6 +805,13 @@ function opUsesValue(op: string | undefined): boolean {
|
||||
border: 1px solid var(--wp-border);
|
||||
border-radius: 3px;
|
||||
overflow: hidden;
|
||||
/* THE load-bearing fix for "rules clipped, no scrollbar": the cards are
|
||||
* flex children of the flex-column .rules__list, so by default they SHRINK
|
||||
* to fit its max-height and `overflow:hidden` then clips their branches —
|
||||
* the list never overflows, so it never scrolls and no scrollbar appears.
|
||||
* Pinning flex-shrink:0 keeps each card at full height; the list then truly
|
||||
* overflows its max-height and scrolls (with its scrollbar). */
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.rule-card--off { opacity: 0.55; }
|
||||
.rule-card--dragging { opacity: 0.5; }
|
||||
@@ -760,6 +868,17 @@ function opUsesValue(op: string | undefined): boolean {
|
||||
border-radius: 999px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* A rule head is a PREVIEW, kept to ONE line. Wrapping let a paragraph-length
|
||||
action value run to hundreds of lines and push the rest of the modal off
|
||||
screen. Truncating keeps the row a clean single line, and `title` (see
|
||||
`ruleSummaryText`) gives the full text on hover.
|
||||
|
||||
`display: block`, not flex: `text-overflow: ellipsis` is ignored on a flex
|
||||
container, which is why an earlier attempt reached for a gradient mask
|
||||
instead — but a mask fades EVERY pixel under it, including the ref chips,
|
||||
so the tail of the summary went unreadable rather than merely cut. As an
|
||||
inline formatting context the browser draws a real `…` at the clip point
|
||||
and leaves everything before it at full opacity. */
|
||||
.rule-head__summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -769,6 +888,7 @@ function opUsesValue(op: string | undefined): boolean {
|
||||
font: 11px var(--wp-font-mono);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.rule-card--off .rule-head__summary { text-decoration: line-through; }
|
||||
.rule-head__chip {
|
||||
font: 600 9px var(--wp-font-sans);
|
||||
@@ -824,13 +944,19 @@ function opUsesValue(op: string | undefined): boolean {
|
||||
.branch-row--off {
|
||||
opacity: 0.5;
|
||||
}
|
||||
.branch-row--off .branch-cell--summary { text-decoration: line-through; }
|
||||
.branch-row--off .branch-cell--summary {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.branch-cell {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
/* Same treatment as the rule head, for the same reason: this is a per-branch
|
||||
PREVIEW column, and one long action value stretched its row until the branch
|
||||
table stopped being a table. Single line + real ellipsis + `title` on hover;
|
||||
the override inputs beside it hold the full value and scroll. */
|
||||
.branch-cell--summary {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
@@ -36,6 +36,33 @@ describe("derivation RuntimeSection", () => {
|
||||
expect(w.find('[data-test="runtime-hide"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it("renders the Hold across run toggle, off by default", () => {
|
||||
const w = mount(RuntimeSection, { props: { module: makeModule() } });
|
||||
const hold = w.find('[data-test="runtime-hold"]');
|
||||
expect(hold.exists()).toBe(true);
|
||||
expect(hold.text()).toContain("Hold across run");
|
||||
expect(hold.classes()).not.toContain("toggle--on");
|
||||
});
|
||||
|
||||
it("Hold toggle reflects seed_scope=hold as on", () => {
|
||||
const w = mount(RuntimeSection, { props: { module: makeModule({ instance: { seed_scope: "hold" } }) } });
|
||||
expect(w.find('[data-test="runtime-hold"]').classes()).toContain("toggle--on");
|
||||
});
|
||||
|
||||
it("clicking Hold emits seed_scope = hold; clicking when held emits vary", async () => {
|
||||
const w = mount(RuntimeSection, { props: { module: makeModule() } });
|
||||
await w.find('[data-test="runtime-hold"]').trigger("click");
|
||||
expect(lastPatch(w).instance?.seed_scope).toBe("hold");
|
||||
const held = mount(RuntimeSection, { props: { module: makeModule({ instance: { seed_scope: "hold" } }) } });
|
||||
await held.find('[data-test="runtime-hold"]').trigger("click");
|
||||
expect(lastPatch(held).instance?.seed_scope).toBe("vary");
|
||||
});
|
||||
|
||||
it("Hold toggle is disabled while a loop edit-frame is active", () => {
|
||||
const w = mount(RuntimeSection, { props: { module: makeModule(), frameActive: true } });
|
||||
expect(w.find('[data-test="runtime-hold"]').attributes("disabled")).toBeDefined();
|
||||
});
|
||||
|
||||
it("seed input hidden when not locked", () => {
|
||||
const w = mount(RuntimeSection, { props: { module: makeModule() } });
|
||||
expect(w.find('[data-test="runtime-seed"]').exists()).toBe(false);
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Derivation RuntimeSection — composes the shared `<SeedLockControls />`
|
||||
* (default "Lock seed" label) plus the Hide-from-prompt toggle.
|
||||
* Mirrors combine's RuntimeSection 1:1 because the surface semantics
|
||||
* are the same: derivation's `action.value` resolves `{a|b|c}`
|
||||
* alternations, so locking the seed pins each pick across queues.
|
||||
* (default "Lock seed" label) plus the Hide-from-prompt and
|
||||
* Hold-across-run toggles. Mirrors combine's RuntimeSection 1:1 because
|
||||
* the surface semantics are the same: derivation's `action.value`
|
||||
* resolves `{a|b|c}` alternations (+ nested `@{}` refs), so locking the
|
||||
* seed pins each pick across queues and Hold freezes the resolved output
|
||||
* across a loop run.
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
import type { ModuleEntry } from "../../../../../widgets/_shared";
|
||||
@@ -19,6 +21,11 @@ const internal = computed(() => instance.value.internal === true);
|
||||
function onHideClick(): void {
|
||||
emit("update", { instance: { ...instance.value, internal: !internal.value } });
|
||||
}
|
||||
|
||||
const held = computed(() => instance.value.seed_scope === "hold");
|
||||
function onHoldClick(): void {
|
||||
emit("update", { instance: { ...instance.value, seed_scope: held.value ? "vary" : "hold" } });
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -38,11 +45,24 @@ function onHideClick(): void {
|
||||
<i class="pi pi-eye-slash" aria-hidden="true" />
|
||||
Hide from prompt
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="toggle"
|
||||
:class="{ 'toggle--on': held }"
|
||||
data-test="runtime-hold"
|
||||
role="switch"
|
||||
:aria-checked="held"
|
||||
:disabled="frameActive || undefined"
|
||||
@click="onHoldClick"
|
||||
>
|
||||
<i class="pi pi-link" aria-hidden="true" />
|
||||
Hold across run
|
||||
</button>
|
||||
<p
|
||||
v-if="frameActive"
|
||||
class="runtime__frame-hint"
|
||||
data-test="runtime-frame-hint"
|
||||
>Hide from prompt applies to every frame — switch to base to change.</p>
|
||||
>Hide from prompt and Hold across run apply to every frame — switch to base to change.</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { saveChordLabel } from "../../../shared/platform-keys";
|
||||
import type { ModuleEntry } from "../../../../widgets/_shared";
|
||||
import IdentitySection from "./sections/IdentitySection.vue";
|
||||
import ValuesSection from "./sections/ValuesSection.vue";
|
||||
import RuntimeSection from "./sections/RuntimeSection.vue";
|
||||
import InstanceIdChip from "../InstanceIdChip.vue";
|
||||
|
||||
|
||||
/** Platform-correct save chord for the footer hint. */
|
||||
const saveChord = saveChordLabel();
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
module: ModuleEntry;
|
||||
@@ -55,6 +60,7 @@ function onSpaClick(): void {
|
||||
<div class="wp-fvm__title-row">
|
||||
<span class="wp-fvm__name" data-test="fvm-name">{{ module.meta?.name ?? module.type }}</span>
|
||||
<span class="wp-fvm__chip" data-test="fvm-chip">fixed</span>
|
||||
<InstanceIdChip :id="module.id" :uid="module._uid" />
|
||||
</div>
|
||||
<div class="wp-fvm__sub">Library entry · static $var → value pairs</div>
|
||||
</div>
|
||||
@@ -97,7 +103,7 @@ function onSpaClick(): void {
|
||||
Reset overrides
|
||||
</button>
|
||||
<span class="wp-fvm__hint">
|
||||
<kbd>Esc</kbd> cancel · <kbd>⌘↵</kbd> save
|
||||
<kbd>Esc</kbd> cancel · <kbd>{{ saveChord }}</kbd> save
|
||||
</span>
|
||||
<button
|
||||
v-if="canSaveToLibrary"
|
||||
|
||||
@@ -14,6 +14,34 @@ describe("ValueRow", () => {
|
||||
expect(w.find<HTMLInputElement>('[data-test="row-value"]').element.value).toBe("85mm");
|
||||
});
|
||||
|
||||
it("value field is a growing textarea, not a single-line input", async () => {
|
||||
// Users routinely paste a whole sentence into a fixed value; a one-line
|
||||
// <input> showed a sliver with no way to see the rest.
|
||||
const w = mount(ValueRow, { props: { row: plainDraft, library: lib } });
|
||||
const el = w.find('[data-test="row-value"]');
|
||||
expect(el.element.tagName).toBe("TEXTAREA");
|
||||
});
|
||||
|
||||
it("Enter inserts a newline like any textarea", async () => {
|
||||
// Briefly swallowed for parity with the single-line <input> this replaced,
|
||||
// which was parity for its own sake: the engine stores the value verbatim,
|
||||
// multi-line round-trips fine, and the modal saves on Cmd/Ctrl+Enter.
|
||||
const w = mount(ValueRow, { props: { row: plainDraft, library: lib } });
|
||||
const el = w.find('[data-test="row-value"]');
|
||||
const ev = new KeyboardEvent("keydown", { key: "Enter", cancelable: true, bubbles: true });
|
||||
el.element.dispatchEvent(ev);
|
||||
expect(ev.defaultPrevented).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a multi-line value intact on input", async () => {
|
||||
const w = mount(ValueRow, { props: { row: plainDraft, library: lib } });
|
||||
const el = w.find<HTMLTextAreaElement>('[data-test="row-value"]');
|
||||
el.element.value = "line one\nline two";
|
||||
await el.trigger("input");
|
||||
const updates = w.emitted("update") ?? [];
|
||||
expect(updates[updates.length - 1]).toEqual(["v1", { value: "line one\nline two" }]);
|
||||
});
|
||||
|
||||
it("checkbox is checked when enabled", () => {
|
||||
const w = mount(ValueRow, { props: { row: plainDraft, library: lib } });
|
||||
expect(w.find('[data-test="row-check"]').classes()).toContain("row__check--on");
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { computed, nextTick, onMounted, ref, watch } from "vue";
|
||||
import { useGrowableField } from "../../../../shared/useGrowableField";
|
||||
import {
|
||||
rowOverrideKind,
|
||||
type DraftRow,
|
||||
@@ -62,8 +63,74 @@ function onNameInput(ev: Event): void {
|
||||
emit("update", props.row.id, { name });
|
||||
}
|
||||
function onValueInput(ev: Event): void {
|
||||
emit("update", props.row.id, { value: (ev.target as HTMLInputElement).value });
|
||||
const el = ev.target as HTMLTextAreaElement;
|
||||
emit("update", props.row.id, { value: el.value });
|
||||
autosize();
|
||||
updateOverflowHint();
|
||||
}
|
||||
|
||||
/** Grow the value field to fit its content, capped by the CSS `max-height`
|
||||
* (after which it scrolls). The field is a `<textarea>` purely to get this
|
||||
* wrapping + growth — users routinely paste an entire sentence into a fixed
|
||||
* value and a single-line `<input>` showed a sliver of it with no way to see
|
||||
* the rest. Semantics stay single-value; `onValueKeydown` blocks newlines. */
|
||||
/* Auto-grow now lives in `useGrowableField` so it can YIELD to the drag
|
||||
* handle. The old local version wrote `height = scrollHeight` on every input
|
||||
* and every external value change, which stomped whatever height the user had
|
||||
* dragged to — collapse the box, type one character, and it sprang back open.
|
||||
* That is the "the drag sticks, then starts working" report. */
|
||||
|
||||
/* Enter inserts a newline, like any other textarea.
|
||||
*
|
||||
* It was briefly swallowed to preserve the behaviour of the single-line
|
||||
* `<input>` this replaced, but that was parity for its own sake: a fixed value
|
||||
* is an arbitrary string, the engine stores and emits it verbatim, and a
|
||||
* multi-line value round-trips fine. The modal saves on Cmd/Ctrl+Enter, so
|
||||
* plain Enter is free — and users writing paragraph-length values want their
|
||||
* line breaks. */
|
||||
|
||||
const valueEl = ref<HTMLTextAreaElement | null>(null);
|
||||
|
||||
/* Shared auto-grow + overflow-hint + grip-follow. See `useGrowableField` for
|
||||
* why the three belong together — chiefly that auto-grow has to yield to the
|
||||
* drag handle, which the local copy did not. */
|
||||
const {
|
||||
hasMoreBelow,
|
||||
updateOverflowHint,
|
||||
scheduleOverflowHint,
|
||||
autosize,
|
||||
attach,
|
||||
startResize,
|
||||
} = useGrowableField(() => valueEl.value);
|
||||
|
||||
/** True when the field is capped and still hiding content below the fold.
|
||||
* Mirrors RichTextInput's hint — a capped box otherwise looks identical
|
||||
* whether it holds its whole value or a third of it. A `<textarea>` can't
|
||||
* carry a reliable `::after`, so the fade lives on `.row__value-wrap`. */
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/* Size correctly on first paint + whenever the row's value changes from
|
||||
outside (reset-to-library, undo). */
|
||||
watch(
|
||||
() => props.row.value,
|
||||
() => void nextTick(() => {
|
||||
autosize();
|
||||
scheduleOverflowHint();
|
||||
}),
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
|
||||
onMounted(() => {
|
||||
autosize();
|
||||
scheduleOverflowHint();
|
||||
attach();
|
||||
});
|
||||
|
||||
|
||||
function onReset(): void {
|
||||
emit("reset", props.row.id);
|
||||
}
|
||||
@@ -128,18 +195,35 @@ function onDelete(): void {
|
||||
>
|
||||
<span
|
||||
class="row__value-wrap"
|
||||
:class="{ 'row__value-wrap--mod': valueOverridden }"
|
||||
:class="{
|
||||
'row__value-wrap--mod': valueOverridden,
|
||||
'row__value-wrap--more': hasMoreBelow,
|
||||
}"
|
||||
data-test="row-value-wrap"
|
||||
>
|
||||
<input
|
||||
<textarea
|
||||
ref="valueEl"
|
||||
class="row__value"
|
||||
data-test="row-value"
|
||||
type="text"
|
||||
rows="1"
|
||||
spellcheck="false"
|
||||
:value="row.value"
|
||||
:disabled="!row.enabled"
|
||||
:aria-label="`Value for row ${row.id}`"
|
||||
@input="onValueInput"
|
||||
@scroll="updateOverflowHint"
|
||||
/>
|
||||
<!-- Resize grip, replacing `resize: vertical`. The native resizer
|
||||
recomputes from an origin captured at pointerdown and never clamps
|
||||
to min/max, so over-dragging banks invisible travel the user has to
|
||||
walk back — measured at 13 of 23 dead frames. Ours applies each
|
||||
move's delta to the current height. -->
|
||||
<span
|
||||
class="row__grip"
|
||||
data-test="row-grip"
|
||||
aria-hidden="true"
|
||||
@pointerdown="startResize"
|
||||
></span>
|
||||
</span>
|
||||
<span
|
||||
v-if="hasNonTextToken"
|
||||
@@ -260,6 +344,72 @@ function onDelete(): void {
|
||||
}
|
||||
.row__name:focus, .row__value:focus { outline: none; }
|
||||
|
||||
/* The value field is a <textarea> so a long value WRAPS and the box grows to
|
||||
* fit (height driven by `autosizeValue`). Capped so a pasted paragraph can't
|
||||
* push the rest of the modal off-screen; past the cap it scrolls. */
|
||||
.row__value {
|
||||
/* Manual drag handle as well as the auto-grow, matching the derivation and
|
||||
combine template inputs — auto-sizing picks a sensible height, the handle
|
||||
lets the user override it. */
|
||||
overscroll-behavior: contain;
|
||||
overflow-y: auto;
|
||||
/* Floor for the drag handle. Without it the computed `min-height` is `auto`,
|
||||
which reads as 0 — so the field could be dragged away to a sliver with no
|
||||
way to see what you were editing. One line plus its padding. */
|
||||
min-height: 28px;
|
||||
max-height: 12rem;
|
||||
line-height: 1.5;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font-family: var(--wp-font-mono);
|
||||
}
|
||||
/* The wrapper centred a single-line input; with a growing field the label
|
||||
* column should sit at the top instead of drifting down as it grows. */
|
||||
.row__value-wrap { align-items: flex-start; position: relative; }
|
||||
|
||||
/* "More below" hint, matching RichTextInput. A <textarea> can't carry a
|
||||
* dependable `::after`, so it hangs off the wrapper. Gradient runs to a
|
||||
* TRANSPARENT accent so the text underneath still reads; the 1px accent line
|
||||
* at the bottom is what catches the eye. */
|
||||
/* Sits in the corner the overflow fade deliberately leaves clear. */
|
||||
.row__grip {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
cursor: ns-resize;
|
||||
z-index: 2;
|
||||
background: repeating-linear-gradient(
|
||||
135deg,
|
||||
transparent 0 2px,
|
||||
var(--wp-text3, #8a8a9a) 2px 3px
|
||||
);
|
||||
/* Clipped to a bottom-right triangle so the hatching runs parallel to the
|
||||
hypotenuse — the shape the browser's own resizer draws, which is what
|
||||
users already read as "drag me". A filled square read as a button. */
|
||||
clip-path: polygon(100% 0, 100% 100%, 0 100%);
|
||||
opacity: 0.55;
|
||||
}
|
||||
.row__grip:hover { opacity: 0.9; }
|
||||
|
||||
.row__value-wrap--more::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
/* Right edge stops short of the resize grip. The band is as tall as the
|
||||
handle and sat straight on top of it, so a resizable field's grip was
|
||||
invisible — users aimed, missed, re-grabbed. */
|
||||
inset: auto 16px 0 0;
|
||||
height: 14px;
|
||||
pointer-events: none;
|
||||
background: linear-gradient(
|
||||
to bottom,
|
||||
transparent,
|
||||
color-mix(in srgb, var(--wp-accent, #6366f1) 26%, transparent)
|
||||
);
|
||||
box-shadow: inset 0 -1px 0 color-mix(in srgb, var(--wp-accent, #6366f1) 60%, transparent);
|
||||
}
|
||||
|
||||
.row--off { color: var(--wp-text-dim, var(--wp-text3)); }
|
||||
.row--off .row__name-wrap, .row--off .row__value-wrap { opacity: 0.5; }
|
||||
.row--off .row__name, .row--off .row__value { text-decoration: line-through; }
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import type { VarProducerLike } from "@/manager/components/RefChip.vue";
|
||||
import { saveChordLabel } from "../../../shared/platform-keys";
|
||||
import type { ModuleEntry } from "../../../../widgets/_shared";
|
||||
import type { PairingBadge } from "../../../../extension/constraint-pairs";
|
||||
import IdentitySection from "./sections/IdentitySection.vue";
|
||||
import PoolSection from "./sections/PoolSection.vue";
|
||||
import RuntimeSection from "./sections/RuntimeSection.vue";
|
||||
import InstanceIdChip from "../InstanceIdChip.vue";
|
||||
|
||||
|
||||
/** Platform-correct save chord for the footer hint. */
|
||||
const saveChord = saveChordLabel();
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
module: ModuleEntry;
|
||||
@@ -16,6 +22,9 @@ const props = withDefaults(
|
||||
/** Names produced upstream of this Context node. Drives the
|
||||
* IdentitySection collision warning. */
|
||||
upstreamVars?: string[];
|
||||
/** `$var` → who writes it upstream. Feeds the option chips' hover cards
|
||||
* so a var names its producer rather than "binds at runtime". */
|
||||
upstreamProducers?: Record<string, VarProducerLike>;
|
||||
/** Names produced by other modules in the SAME Context node. */
|
||||
siblingVars?: string[];
|
||||
/** Per-option pair badges when this wildcard is a constraint carrier
|
||||
@@ -26,7 +35,15 @@ const props = withDefaults(
|
||||
* structural controls are disabled in frame mode. */
|
||||
frameActive?: boolean;
|
||||
}>(),
|
||||
{ isDrifted: false, isModified: false, upstreamVars: () => [], siblingVars: () => [], viaOptionPairs: () => new Map() },
|
||||
{
|
||||
isDrifted: false, isModified: false, upstreamVars: () => [],
|
||||
upstreamProducers: () => ({}), siblingVars: () => [],
|
||||
viaOptionPairs: () => new Map(),
|
||||
},
|
||||
);
|
||||
|
||||
const varProducerMap = computed(
|
||||
() => new Map(Object.entries(props.upstreamProducers ?? {})),
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -79,6 +96,7 @@ function onSpaClick(): void {
|
||||
<div class="wp-wcm__title-row">
|
||||
<span class="wp-wcm__name" data-test="wcm-name">{{ module.meta?.name ?? module.type }}</span>
|
||||
<span class="wp-wcm__chip" data-test="wcm-chip">wildcard</span>
|
||||
<InstanceIdChip :id="module.id" :uid="module._uid" />
|
||||
</div>
|
||||
<div class="wp-wcm__sub" data-test="wcm-sub">
|
||||
{{ isMultiPick
|
||||
@@ -104,7 +122,12 @@ function onSpaClick(): void {
|
||||
:frame-active="frameActive"
|
||||
@update="onUpdate"
|
||||
/>
|
||||
<PoolSection :module="module" :via-option-pairs="viaOptionPairs" @update="onUpdate" />
|
||||
<PoolSection
|
||||
:module="module"
|
||||
:via-option-pairs="viaOptionPairs"
|
||||
:var-producers="varProducerMap"
|
||||
@update="onUpdate"
|
||||
/>
|
||||
<div class="wp-wcm__dock">
|
||||
<RuntimeSection :module="module" :frame-active="frameActive" @update="onUpdate" />
|
||||
|
||||
@@ -132,7 +155,7 @@ function onSpaClick(): void {
|
||||
Reset overrides
|
||||
</button>
|
||||
<span class="wp-wcm__hint">
|
||||
<kbd>Esc</kbd> cancel · <kbd>⌘↵</kbd> save
|
||||
<kbd>Esc</kbd> cancel · <kbd>{{ saveChord }}</kbd> save
|
||||
</span>
|
||||
<button
|
||||
v-if="canSaveToLibrary"
|
||||
|
||||
@@ -29,12 +29,40 @@ describe("OptionRow", () => {
|
||||
expect(w.find('[data-test="opt-cat-warm"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it("collapses a long tag run behind a +N pill", () => {
|
||||
// A well-tagged option carries 8+ sub-categories; wrapped inside the 96px
|
||||
// CATEGORY column they stacked into eight lines and made one row taller
|
||||
// than the option list was worth.
|
||||
const tags = ["red", "warm", "medium", "vivid", "hair-vivid", "eye-vivid", "fabric", "makeup-ok"];
|
||||
const opt = { id: "m", value: "crimson", weight: 1, sub_categories: tags };
|
||||
const w = mount(OptionRow, { props: { option: opt, allOptions: [opt], instance: {} } });
|
||||
expect(w.findAll(".opt__cat-chip")).toHaveLength(3);
|
||||
expect(w.find('[data-test="opt-cat-more-m"]').text()).toBe("+5");
|
||||
});
|
||||
|
||||
it("expanding the +N pill reveals every tag", async () => {
|
||||
const tags = ["red", "warm", "medium", "vivid", "hair-vivid", "eye-vivid", "fabric", "makeup-ok"];
|
||||
const opt = { id: "m", value: "crimson", weight: 1, sub_categories: tags };
|
||||
const w = mount(OptionRow, { props: { option: opt, allOptions: [opt], instance: {} } });
|
||||
await w.find('[data-test="opt-cat-more-m"]').trigger("click");
|
||||
expect(w.findAll(".opt__cat-chip")).toHaveLength(8);
|
||||
expect(w.find('[data-test="opt-cat-more-m"]').text()).toBe("−");
|
||||
await w.find('[data-test="opt-cat-more-m"]').trigger("click");
|
||||
expect(w.findAll(".opt__cat-chip")).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("does NOT show a +N pill when the tags already fit", () => {
|
||||
const opt = { id: "m", value: "lynx", weight: 1, sub_categories: ["feline", "warm"] };
|
||||
const w = mount(OptionRow, { props: { option: opt, allOptions: [opt], instance: {} } });
|
||||
expect(w.find('[data-test="opt-cat-more-m"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("decomposes a {N$$…} block into scaffolding + an inner ref chip (SP2b #6)", () => {
|
||||
_setForTests("ad00acd5", { name: "mood", varBinding: "mood" });
|
||||
const opt = { id: "b1", value: "{2$$, $$@{ad00acd5}|warm}", weight: 1, sub_categories: [] };
|
||||
const w = mount(OptionRow, { props: { option: opt, allOptions: [opt], instance: {} } });
|
||||
// The inner @{uuid} arm renders as a resolved ref chip, not raw uuid text.
|
||||
const ref = w.find(".opt__tok--ref");
|
||||
const ref = w.find(".wp-refchip--ref");
|
||||
expect(ref.exists()).toBe(true);
|
||||
expect(ref.text()).toContain("@mood");
|
||||
expect(w.find(".opt__tok--multi").exists()).toBe(true); // scaffolding coloured
|
||||
@@ -45,11 +73,11 @@ describe("OptionRow", () => {
|
||||
_setForTests("ad00acd5", { name: "mood", varBinding: "mood" });
|
||||
const opt = { id: "b3", value: "{3$$, $$@{ad00acd5#mood!null}}", weight: 1, sub_categories: [] };
|
||||
const w = mount(OptionRow, { props: { option: opt, allOptions: [opt], instance: {} } });
|
||||
const ref = w.find(".opt__tok--ref");
|
||||
const ref = w.find(".wp-refchip--ref");
|
||||
expect(ref.exists()).toBe(true);
|
||||
// The leaked `!null` is detected → ban (null-excluded) indicator shows.
|
||||
expect(ref.find(".opt__tok-filter").exists()).toBe(true);
|
||||
expect(ref.find(".opt__tok-nonull").exists()).toBe(true);
|
||||
expect(ref.find(".wp-refchip__filter").exists()).toBe(true);
|
||||
expect(ref.find(".wp-refchip__nonull").exists()).toBe(true);
|
||||
// Label is the clean name, not `@mood!null`.
|
||||
expect(ref.text()).toContain("@mood");
|
||||
expect(ref.text()).not.toContain("!null");
|
||||
@@ -59,7 +87,7 @@ describe("OptionRow", () => {
|
||||
_setForTests("ad00acd5", { name: "hair", varBinding: "hair" });
|
||||
const opt = { id: "b2", value: "{warm|@{ad00acd5}}", weight: 1, sub_categories: [] };
|
||||
const w = mount(OptionRow, { props: { option: opt, allOptions: [opt], instance: {} } });
|
||||
expect(w.find(".opt__tok--ref").exists()).toBe(true);
|
||||
expect(w.find(".wp-refchip--ref").exists()).toBe(true);
|
||||
expect(w.find(".opt__tok--brace").exists()).toBe(true);
|
||||
expect(w.find('[data-test="opt-name"]').text()).not.toContain("ad00acd5");
|
||||
});
|
||||
@@ -130,6 +158,22 @@ describe("OptionRow", () => {
|
||||
expect(w.find('[data-test="opt-prob-pct"]').text()).toBe("50%");
|
||||
});
|
||||
|
||||
it("shows sub-1% probabilities with decimals, matching the SPA", () => {
|
||||
// The canvas modal rounded to a whole number, so with 30+ options every
|
||||
// small-but-real weight read as a flat "0%".
|
||||
const many = [
|
||||
{ id: "rare", value: "rare", weight: 1, sub_categories: [] },
|
||||
...Array.from({ length: 199 }, (_, i) => ({
|
||||
id: `o${i}`, value: `o${i}`, weight: 1, sub_categories: [],
|
||||
})),
|
||||
];
|
||||
const w = mount(OptionRow, {
|
||||
props: { option: many[0], allOptions: many, instance: {} },
|
||||
});
|
||||
// 1 of 200 equal weights = 0.5%, which the old formatter collapsed to "0%".
|
||||
expect(w.find('[data-test="opt-prob-pct"]').text()).toBe("0.5%");
|
||||
});
|
||||
|
||||
it("disabled row shows 0% probability + line-through styling", () => {
|
||||
const w = mount(OptionRow, {
|
||||
props: { option: baseOption, allOptions, instance: { enabled_options: ["o2"] } },
|
||||
@@ -206,18 +250,21 @@ describe("OptionRow", () => {
|
||||
it("renders @{uuid} ref token with raw uuid form when name not yet cached", () => {
|
||||
const opt = { id: "o9", value: "city @{a361dbdc} dusk", weight: 1, sub_categories: ["warm"] };
|
||||
const w = mount(OptionRow, { props: { option: opt, allOptions: [opt], instance: {} } });
|
||||
const ref = w.find('[data-test="opt-name"] .opt__tok--ref');
|
||||
const ref = w.find('[data-test="opt-name"] .wp-refchip--ref');
|
||||
expect(ref.exists()).toBe(true);
|
||||
expect(ref.attributes("data-uuid")).toBe("a361dbdc");
|
||||
expect(ref.find(".opt__tok-label").text()).toBe("@{a361dbdc}");
|
||||
// RefChip prefixes `@` only once a ref RESOLVES; an unresolved one shows
|
||||
// the cached name or bare uuid. Same convention as every other surface,
|
||||
// which is the point of rendering the real component here.
|
||||
expect(ref.find(".wp-refchip__label").text()).toBe("{a361dbdc}");
|
||||
});
|
||||
|
||||
it("renders @{uuid} ref as @<varBinding> once resolver caches the entry", () => {
|
||||
_setForTests("a361dbdc", { name: "subject", varBinding: "subject_name" });
|
||||
const opt = { id: "o9", value: "city @{a361dbdc} dusk", weight: 1, sub_categories: ["warm"] };
|
||||
const w = mount(OptionRow, { props: { option: opt, allOptions: [opt], instance: {} } });
|
||||
const ref = w.find('[data-test="opt-name"] .opt__tok--ref');
|
||||
expect(ref.find(".opt__tok-label").text()).toBe("@subject_name");
|
||||
const ref = w.find('[data-test="opt-name"] .wp-refchip--ref');
|
||||
expect(ref.find(".wp-refchip__label").text()).toBe("@subject_name");
|
||||
});
|
||||
|
||||
it("renders a v2 boolean ref filter as funnel + ban, not inline !null text", () => {
|
||||
@@ -229,18 +276,21 @@ describe("OptionRow", () => {
|
||||
sub_categories: ["canine"],
|
||||
};
|
||||
const w = mount(OptionRow, { props: { option: opt, allOptions: [opt], instance: {} } });
|
||||
const ref = w.find('[data-test="opt-name"] .opt__tok--ref');
|
||||
const ref = w.find('[data-test="opt-name"] .wp-refchip--ref');
|
||||
expect(ref.exists()).toBe(true);
|
||||
// The raw expression + `!null` marker must NOT appear inline anymore.
|
||||
expect(ref.text()).not.toContain("!null");
|
||||
expect(ref.text()).not.toContain("warm or intense");
|
||||
// Compact indicators instead — funnel (expression) + ban (exclude-null),
|
||||
// matching the SPA RefChip grammar.
|
||||
expect(ref.find(".opt__tok-funnel").exists()).toBe(true);
|
||||
expect(ref.find(".opt__tok-nonull").exists()).toBe(true);
|
||||
// Full normalized expression lives in the hover title, `!null` peeled.
|
||||
expect(ref.attributes("title")).toContain("warm or intense");
|
||||
expect(ref.attributes("title")).not.toContain("!null");
|
||||
expect(ref.find(".wp-refchip__funnel").exists()).toBe(true);
|
||||
expect(ref.find(".wp-refchip__nonull").exists()).toBe(true);
|
||||
// The normalized expression is no longer a native `title`: RefChip
|
||||
// deliberately renders an empty one and puts the detail in its hover
|
||||
// card, so the chip carries the funnel/ban grammar and the card carries
|
||||
// the "reads as" text.
|
||||
expect(ref.attributes("title")).toBe("");
|
||||
expect(ref.classes()).toContain("wp-refchip--filtered");
|
||||
});
|
||||
|
||||
it("renders {a|b|c} brace block as a brace token (warn colour)", () => {
|
||||
@@ -259,7 +309,7 @@ describe("OptionRow", () => {
|
||||
it("renders $varname as a var token", () => {
|
||||
const opt = { id: "o9", value: "uses $style here", weight: 1, sub_categories: ["warm"] };
|
||||
const w = mount(OptionRow, { props: { option: opt, allOptions: [opt], instance: {} } });
|
||||
expect(w.find('[data-test="opt-name"] .opt__tok--var .opt__tok-label').text()).toBe("$style");
|
||||
expect(w.find('[data-test="opt-name"] .wp-refchip--var .wp-refchip__label').text()).toBe("$style");
|
||||
});
|
||||
|
||||
it("typing weight back to library default clears the override (null)", async () => {
|
||||
|
||||
@@ -1,6 +1,26 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { mount as vtuMount } from "@vue/test-utils";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import PoolSection from "../sections/PoolSection.vue";
|
||||
|
||||
/**
|
||||
* The tag-pill grid ships COLLAPSED (a well-tagged wildcard's 40-odd pills
|
||||
* pushed the option list off screen). Every test below is about the pills
|
||||
* themselves, so this local `mount` opens the pool via the component's
|
||||
* `defaultOpen` prop rather than making each case drive a click first.
|
||||
*
|
||||
* The collapse behaviour itself is covered in "PoolSection collapse", which
|
||||
* mounts through `vtuMount` to see the real default.
|
||||
*/
|
||||
const mount = ((component: unknown, options: Record<string, unknown> = {}) => {
|
||||
const opts = {
|
||||
...options,
|
||||
props: { ...((options.props as Record<string, unknown>) ?? {}), defaultOpen: true },
|
||||
};
|
||||
return (vtuMount as unknown as (c: unknown, o: unknown) => ReturnType<typeof vtuMount>)(
|
||||
component,
|
||||
opts,
|
||||
);
|
||||
}) as unknown as typeof vtuMount;
|
||||
import type { ModuleEntry } from "@/widgets/_shared";
|
||||
|
||||
const module = {
|
||||
@@ -164,6 +184,38 @@ describe("PoolSection pick-count (SP2a)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("PoolSection collapse", () => {
|
||||
it("starts COLLAPSED, and the chevron opens the pill grid", async () => {
|
||||
// A richly tagged wildcard shows 40-odd pills, pushing the option list —
|
||||
// the thing the user came to edit — most of a screen down. Uses the real
|
||||
// default, so mounts through vtuMount rather than the local helper.
|
||||
const w = vtuMount(PoolSection, { props: { module } });
|
||||
expect(w.find('[data-test="cat-chip-feline"]').exists()).toBe(false);
|
||||
await w.get('[data-test="pool-collapse"]').trigger("click");
|
||||
expect(w.find('[data-test="cat-chip-feline"]').exists()).toBe(true);
|
||||
await w.get('[data-test="pool-collapse"]').trigger("click");
|
||||
expect(w.find('[data-test="cat-chip-feline"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("accents the collapse control while shut so it reads as pressable", () => {
|
||||
const w = vtuMount(PoolSection, { props: { module } });
|
||||
expect(w.get('[data-test="pool-collapse"]').classes()).toContain("pool__collapse--nudge");
|
||||
});
|
||||
|
||||
it("drops the accent once expanded", async () => {
|
||||
const w = vtuMount(PoolSection, { props: { module } });
|
||||
await w.get('[data-test="pool-collapse"]').trigger("click");
|
||||
expect(w.get('[data-test="pool-collapse"]').classes()).not.toContain("pool__collapse--nudge");
|
||||
});
|
||||
|
||||
it("collapsed header reports how many tags are ticked", async () => {
|
||||
const w = mount(PoolSection, { props: { module } });
|
||||
await w.get('[data-test="cat-chip-feline"]').trigger("click");
|
||||
await w.get('[data-test="pool-collapse"]').trigger("click");
|
||||
expect(w.get('[data-test="pool-collapsed-count"]').text()).toContain("1 selected");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PoolSection grouped quick pills", () => {
|
||||
it("ticking family=feline + temp=warm builds 'feline and warm'", async () => {
|
||||
const w = mount(PoolSection, { props: { module } });
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { computed, ref } from "vue";
|
||||
import {
|
||||
effectiveWeight,
|
||||
isEnabled,
|
||||
@@ -11,7 +11,9 @@ import { splitRefFilter, tokenizeRich, type RichToken } from "../../../../../wid
|
||||
import { cacheVersion, ensure, lookup } from "../../../../../extension/preview-resolver";
|
||||
import type { PairingBadge } from "../../../../../extension/constraint-pairs";
|
||||
import { matches, parse, readsAs } from "@/manager/parsing/subcatFilter";
|
||||
import { formatProbability } from "@/manager/utils/percent";
|
||||
import PairBadge from "../../../PairBadge.vue";
|
||||
import RefChip, { type VarProducerLike } from "@/manager/components/RefChip.vue";
|
||||
import { axisHueAt } from "../../../../shared/axis-color";
|
||||
|
||||
interface OptionFull extends WildcardOption {
|
||||
@@ -37,8 +39,14 @@ const props = withDefaults(
|
||||
* true the null option is excluded from the pool, so its row renders
|
||||
* disabled/greyed + non-toggleable. Real option rows are unaffected. */
|
||||
multiActive?: boolean;
|
||||
/** `$var` → who writes it upstream, so a var chip's hover card names the
|
||||
* producer instead of falling back to "binds at runtime". */
|
||||
varProducers?: ReadonlyMap<string, VarProducerLike>;
|
||||
}>(),
|
||||
{ pairBadges: () => [], tagGroups: () => ({}), multiActive: false },
|
||||
{
|
||||
pairBadges: () => [], tagGroups: () => ({}), multiActive: false,
|
||||
varProducers: () => new Map(),
|
||||
},
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -109,6 +117,12 @@ const tokens = computed<RichToken[]>(() => {
|
||||
return out;
|
||||
});
|
||||
|
||||
/** RefChip renders its own `@` prefix, so hand it the bare label. */
|
||||
function refChipName(tok: RichToken): string {
|
||||
const label = refDisplay(tok.meta?.uuid, tok.meta?.name, tok.raw);
|
||||
return label.startsWith("@") ? label.slice(1) : label;
|
||||
}
|
||||
|
||||
function refDisplay(
|
||||
uuid: string | undefined,
|
||||
cachedName: string | undefined,
|
||||
@@ -152,7 +166,7 @@ function refIsUnresolved(uuid: string | undefined): boolean {
|
||||
* peeling `!null`, so rejoin + `splitRefFilter` here rather than printing
|
||||
* the glued `sub_categories` inline. Memoized per token object so the
|
||||
* several template bindings don't each re-parse. */
|
||||
interface RefFilterInfo { hasExpr: boolean; excludeNull: boolean; isFiltered: boolean; title: string }
|
||||
interface RefFilterInfo { hasExpr: boolean; excludeNull: boolean; isFiltered: boolean; title: string; expr: string }
|
||||
const _refFilterMemo = new WeakMap<RichToken, RefFilterInfo>();
|
||||
function refFilter(tok: RichToken): RefFilterInfo {
|
||||
const cached = _refFilterMemo.get(tok);
|
||||
@@ -179,6 +193,7 @@ function refFilter(tok: RichToken): RefFilterInfo {
|
||||
if (reads) parts.push(reads);
|
||||
if (excludeNull) parts.push("null excluded");
|
||||
const info: RefFilterInfo = {
|
||||
expr,
|
||||
hasExpr: expr.length > 0,
|
||||
excludeNull,
|
||||
isFiltered: expr.length > 0 || excludeNull,
|
||||
@@ -324,9 +339,34 @@ function bumpWeight(direction: 1 | -1): void {
|
||||
emitWeight(next);
|
||||
}
|
||||
|
||||
/** Percentage label, delegated to the SPA's `formatProbability` so both
|
||||
* editors agree digit-for-digit. The canvas modal used to round to a whole
|
||||
* number, so every option below 0.5% read as a flat "0%" — with 30+ options
|
||||
* that's most of the pool, and a legitimately weighted entry looked
|
||||
* impossible. `probability` is a 0–1 fraction here; the helper takes 0–100. */
|
||||
function fmtPct(p: number): string {
|
||||
return `${Math.round(p * 100)}%`;
|
||||
return formatProbability(p * 100);
|
||||
}
|
||||
|
||||
// ---------- CATEGORY chips ----------
|
||||
//
|
||||
// A well-tagged option carries 8+ sub-categories (hue + temperature + tone +
|
||||
// saturation + several suitability flags). Wrapped inside the 96px column
|
||||
// that stacked into eight lines and made ONE option row taller than the
|
||||
// modal's whole option list is worth — the pool became unreadable.
|
||||
//
|
||||
// Show the first few and collapse the rest behind a `+N` pill the user can
|
||||
// expand per row. The tags stay fully reachable; they just stop dominating.
|
||||
const CAT_CHIP_LIMIT = 3;
|
||||
const catExpanded = ref(false);
|
||||
|
||||
const allTags = computed<string[]>(() =>
|
||||
props.option.is_null ? [] : (props.option.sub_categories ?? []),
|
||||
);
|
||||
const visibleTags = computed<string[]>(() =>
|
||||
catExpanded.value ? allTags.value : allTags.value.slice(0, CAT_CHIP_LIMIT),
|
||||
);
|
||||
const hiddenTagCount = computed(() => allTags.value.length - visibleTags.value.length);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -367,7 +407,7 @@ function fmtPct(p: number): string {
|
||||
</svg>
|
||||
</span>
|
||||
<span class="opt__name" data-test="opt-name" :class="{ 'opt__name--null': option.is_null }">
|
||||
<span class="opt__name-main">
|
||||
<span class="opt__name-main" :title="option.value || undefined">
|
||||
<span
|
||||
v-if="option.is_null"
|
||||
class="opt__null-chip"
|
||||
@@ -377,39 +417,32 @@ function fmtPct(p: number): string {
|
||||
<span>null</span>
|
||||
</span>
|
||||
<template v-for="(tok, idx) in tokens" v-else :key="idx">
|
||||
<span
|
||||
<!-- The real RefChip, not a look-alike. These chips used to be
|
||||
hand-rolled spans that only MIRRORED RefChip's styling, so they
|
||||
were the one place in the editor with no hover card — you could
|
||||
not see which library entry a ref pointed at, or who writes a
|
||||
`$var`. Using the component gets the same card as everywhere
|
||||
else, for free. -->
|
||||
<RefChip
|
||||
v-if="tok.kind === 'ref'"
|
||||
class="opt__tok opt__tok--ref"
|
||||
:class="{
|
||||
'opt__tok--filtered': refFilter(tok).isFiltered,
|
||||
'opt__tok--unresolved': refIsUnresolved(tok.meta?.uuid),
|
||||
}"
|
||||
:kind="'ref'"
|
||||
:name="refChipName(tok)"
|
||||
:uuid="tok.meta?.uuid ?? ''"
|
||||
:resolved="!refIsUnresolved(tok.meta?.uuid)"
|
||||
:expr="refFilter(tok).expr"
|
||||
:exclude-null="refFilter(tok).excludeNull"
|
||||
:data-uuid="tok.meta?.uuid"
|
||||
:title="refIsUnresolved(tok.meta?.uuid)
|
||||
? `Reference ${tok.meta?.uuid} not in library`
|
||||
: (refFilter(tok).title || undefined)"
|
||||
>
|
||||
<span class="opt__tok-icon" aria-hidden="true">{{ refIsUnresolved(tok.meta?.uuid) ? '?' : '✦' }}</span>
|
||||
<span class="opt__tok-label">{{ refDisplay(tok.meta?.uuid, tok.meta?.name, tok.raw) }}</span>
|
||||
<!-- Compact filter mark, matching SPA RefChip: funnel = expression
|
||||
set (full expr in hover title), ban = null option excluded.
|
||||
The expression is never printed inline (it can be long). -->
|
||||
<span
|
||||
v-if="refFilter(tok).isFiltered"
|
||||
class="opt__tok-filter"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<i v-if="refFilter(tok).hasExpr" class="pi pi-filter opt__tok-funnel"></i>
|
||||
<i v-if="refFilter(tok).excludeNull" class="pi pi-ban opt__tok-nonull"></i>
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
class="opt__tok opt__tok--chip"
|
||||
/>
|
||||
<RefChip
|
||||
v-else-if="tok.kind === 'var'"
|
||||
class="opt__tok opt__tok--var"
|
||||
>
|
||||
<span class="opt__tok-icon" aria-hidden="true">⌘</span>
|
||||
<span class="opt__tok-label">{{ tok.raw }}</span>
|
||||
</span>
|
||||
:kind="'var'"
|
||||
:name="tok.raw.replace(/^\$/, '')"
|
||||
:resolved="true"
|
||||
:producer="varProducers?.get(tok.raw.replace(/^\$/, ''))"
|
||||
graph-aware
|
||||
class="opt__tok opt__tok--chip"
|
||||
/>
|
||||
<span
|
||||
v-else-if="tok.kind === 'dp-brace'"
|
||||
class="opt__tok opt__tok--brace"
|
||||
@@ -481,12 +514,23 @@ function fmtPct(p: number): string {
|
||||
</span>
|
||||
<span class="opt__cat">
|
||||
<span
|
||||
v-for="tag in (option.is_null ? [] : (option.sub_categories ?? []))"
|
||||
v-for="tag in visibleTags"
|
||||
:key="tag"
|
||||
class="opt__cat-chip"
|
||||
:data-test="`opt-cat-${tag}`"
|
||||
:style="chipStyle(tag)"
|
||||
>{{ tag }}</span>
|
||||
<button
|
||||
v-if="hiddenTagCount > 0 || catExpanded"
|
||||
type="button"
|
||||
class="opt__cat-more"
|
||||
:data-test="`opt-cat-more-${option.id}`"
|
||||
:aria-expanded="catExpanded"
|
||||
:aria-label="catExpanded
|
||||
? `Collapse tags for ${option.value}`
|
||||
: `Show ${hiddenTagCount} more tags for ${option.value}`"
|
||||
@click.stop="catExpanded = !catExpanded"
|
||||
>{{ catExpanded ? "−" : `+${hiddenTagCount}` }}</button>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
@@ -553,10 +597,21 @@ function fmtPct(p: number): string {
|
||||
color: var(--wp-text);
|
||||
line-height: 1.55;
|
||||
}
|
||||
/* An option's value is a PREVIEW here, not the editor for it — the row is a
|
||||
list entry with a checkbox, a weight and a probability beside it. Left
|
||||
unbounded, one paragraph-long option grew taller than the rest of the pool
|
||||
put together and pushed every other option off the panel.
|
||||
`-webkit-line-clamp` needs `overflow: hidden` to do anything at all, so the
|
||||
two must stay together; `title` carries the full value on hover. */
|
||||
.opt__name-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
word-break: break-word;
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 3;
|
||||
line-clamp: 3;
|
||||
overflow: hidden;
|
||||
}
|
||||
.opt__pair-badges {
|
||||
flex: 0 0 auto;
|
||||
@@ -811,4 +866,23 @@ function fmtPct(p: number): string {
|
||||
.opt--off .opt__cat-chip {
|
||||
opacity: 0.5;
|
||||
}
|
||||
/* `+N` / `−` disclosure for the hidden tags. Styled as a neutral chip so it
|
||||
* reads as part of the tag run rather than as a row action. */
|
||||
.opt__cat-more {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 1px 5px;
|
||||
border-radius: 999px;
|
||||
font: 8px var(--wp-font-sans);
|
||||
letter-spacing: 0.06em;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
color: var(--wp-text-dim, var(--wp-text3));
|
||||
border: 1px dashed color-mix(in srgb, var(--wp-text3) 45%, transparent);
|
||||
background: transparent;
|
||||
}
|
||||
.opt__cat-more:hover {
|
||||
color: var(--wp-text);
|
||||
border-color: var(--wp-accent);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from "vue";
|
||||
import type { VarProducerLike } from "@/manager/components/RefChip.vue";
|
||||
import type { ModuleEntry } from "../../../../../widgets/_shared";
|
||||
import type { PairingBadge } from "../../../../../extension/constraint-pairs";
|
||||
import { patchInstance, patchInstanceMapEntry } from "../../instance/patch";
|
||||
@@ -25,8 +26,14 @@ const props = withDefaults(
|
||||
/** Per-option pair badges for via-nested constraint carriers.
|
||||
* Keyed by option id. Empty when this wildcard is not a carrier. */
|
||||
viaOptionPairs?: Map<string, PairingBadge[]>;
|
||||
/** Initial state of the tag-pill grid. Defaults to COLLAPSED — see
|
||||
* `poolOpen`. Exposed so tests (and any host that wants the pool open on
|
||||
* arrival) don't have to drive a click first. */
|
||||
defaultOpen?: boolean;
|
||||
/** `$var` → producer, forwarded to each OptionRow's chips. */
|
||||
varProducers?: ReadonlyMap<string, VarProducerLike>;
|
||||
}>(),
|
||||
{ viaOptionPairs: () => new Map() },
|
||||
{ viaOptionPairs: () => new Map(), defaultOpen: false, varProducers: () => new Map() },
|
||||
);
|
||||
const emit = defineEmits<{ "update": [patch: Partial<ModuleEntry>] }>();
|
||||
|
||||
@@ -156,6 +163,15 @@ function categoryOptionCount(cat: string): number {
|
||||
* while-invalid contract — so `category_filter` is never persisted broken. */
|
||||
|
||||
const advanced = ref(false);
|
||||
|
||||
/** Whether the tag-pill grid is showing. A richly tagged wildcard (hue +
|
||||
* temperature + tone + saturation + suitability, 40-odd pills) pushed the
|
||||
* option list — the thing the user actually came to edit — most of a screen
|
||||
* down, so this starts COLLAPSED. The header keeps reporting how many tags are
|
||||
* ticked, and the chevron is accented while shut so it still reads as
|
||||
* something to press. */
|
||||
const poolOpen = ref(props.defaultOpen);
|
||||
const tickedCount = computed(() => ticked.value.size);
|
||||
const draft = ref(filterExpr.value);
|
||||
|
||||
// Re-seed the draft when the upstream filter changes (e.g. pills edited it
|
||||
@@ -341,7 +357,19 @@ const skewedTowards = computed(() => {
|
||||
<template>
|
||||
<section class="pool">
|
||||
<div class="pool__head">
|
||||
<button
|
||||
type="button"
|
||||
class="pool__collapse"
|
||||
:class="{ 'pool__collapse--nudge': !poolOpen }"
|
||||
:aria-expanded="poolOpen"
|
||||
data-test="pool-collapse"
|
||||
:aria-label="poolOpen ? 'Collapse tag pool' : 'Expand tag pool'"
|
||||
@click="poolOpen = !poolOpen"
|
||||
>{{ poolOpen ? "▾" : "▸" }}</button>
|
||||
<div class="pool__label">Pool · what RNG can pick from</div>
|
||||
<span v-if="!poolOpen && tickedCount > 0" class="pool__collapsed-count" data-test="pool-collapsed-count">
|
||||
{{ tickedCount }} selected
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="pool__adv-toggle"
|
||||
@@ -353,7 +381,7 @@ const skewedTowards = computed(() => {
|
||||
</div>
|
||||
|
||||
<!-- Quick mode — grouped pills. OR within an axis, AND across axes. -->
|
||||
<div v-if="!advanced" class="pool__groups">
|
||||
<div v-if="!advanced && poolOpen" class="pool__groups">
|
||||
<div
|
||||
v-for="group in pillGroups"
|
||||
:key="group.axis"
|
||||
@@ -387,7 +415,7 @@ const skewedTowards = computed(() => {
|
||||
</div>
|
||||
|
||||
<!-- Advanced mode — boolean expression editor (§4.1 grammar). -->
|
||||
<div v-else class="pool__advanced">
|
||||
<div v-else-if="advanced" class="pool__advanced">
|
||||
<input
|
||||
ref="exprInput"
|
||||
v-model="draft"
|
||||
@@ -557,6 +585,7 @@ const skewedTowards = computed(() => {
|
||||
<span class="pool__opt-head-cell pool__opt-head-cell--right">Category</span>
|
||||
</div>
|
||||
<OptionRow
|
||||
:var-producers="varProducers"
|
||||
v-for="option in allOptions"
|
||||
:key="option.id"
|
||||
:option="option"
|
||||
@@ -595,9 +624,48 @@ const skewedTowards = computed(() => {
|
||||
.pool__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 6px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
/* Pushes the Advanced toggle to the right now that the head has a leading
|
||||
* chevron + an optional collapsed-count. */
|
||||
.pool__adv-toggle { margin-left: auto; }
|
||||
/* Deliberately larger than a bare glyph: at 9px with no hit area this read as
|
||||
* decoration and nobody knew it was pressable. */
|
||||
.pool__collapse {
|
||||
background: none;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 3px;
|
||||
padding: 0;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
cursor: pointer;
|
||||
color: var(--wp-text-muted, var(--wp-text2));
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
}
|
||||
.pool__collapse:hover {
|
||||
color: var(--wp-text);
|
||||
border-color: var(--wp-border);
|
||||
background: color-mix(in srgb, var(--wp-text) 6%, transparent);
|
||||
}
|
||||
/* Accented while collapsed so a first-time user reads it as "there is more
|
||||
here" rather than as dim decoration. Static tint, not an animation — this
|
||||
sits on screen for the whole editing session. */
|
||||
.pool__collapse--nudge {
|
||||
color: var(--wp-accent-text, var(--wp-accent, #c4b5fd));
|
||||
border-color: color-mix(in srgb, var(--wp-accent, #6366f1) 55%, transparent);
|
||||
background: color-mix(in srgb, var(--wp-accent, #6366f1) 16%, transparent);
|
||||
}
|
||||
.pool__collapsed-count {
|
||||
font: 600 9px var(--wp-font-sans);
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--wp-accent, #c4b5fd);
|
||||
}
|
||||
.pool__label {
|
||||
font: 600 9px var(--wp-font-sans);
|
||||
text-transform: uppercase;
|
||||
|
||||
@@ -180,6 +180,14 @@ interface WarningEntry {
|
||||
* finalisation warnings (`constraint_never_applied` /
|
||||
* `constraint_partial_reach`). */
|
||||
const WARNING_LABELS: Record<string, string> = {
|
||||
// Nested-ref diagnostics. Both were emitted all along but had no label, so
|
||||
// the panel showed the raw slug and the user was left to guess — which is
|
||||
// how "my filtered nested ref is always empty" became a hunt rather than a
|
||||
// read. The engine now packs the pool it searched, that pool's size and its
|
||||
// available tags into `detail`, so the row explains itself.
|
||||
ref_subcategory_empty_pool: "Filter matched no options",
|
||||
unknown_ref: "Nested reference not found",
|
||||
ref_out_of_surface: "Nested reference not allowed here",
|
||||
constraint_never_applied: "Constraint never applied",
|
||||
constraint_partial_reach: "Constraint partial reach",
|
||||
constraint_source_missing: "Constraint source missing",
|
||||
|
||||
@@ -1,8 +1,38 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { afterEach, describe, it, expect } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { nextTick } from "vue";
|
||||
import InjectorBindingModal from "./InjectorBindingModal.vue";
|
||||
import type { InjectorRow } from "../../widgets/_shared";
|
||||
|
||||
// The insert menu is `<Teleport to="body">` — it escapes the modal's scroll
|
||||
// container so it can't be clipped, which means it is NOT inside the test
|
||||
// wrapper's subtree. Query the document for it instead.
|
||||
function menuItem(name: string): HTMLElement | null {
|
||||
return document.body.querySelector<HTMLElement>(`[data-test="ibm-slot-item-${name}"]`);
|
||||
}
|
||||
|
||||
async function clickMenuItem(name: string): Promise<void> {
|
||||
const el = menuItem(name);
|
||||
if (!el) throw new Error(`no insert-menu item for "${name}"`);
|
||||
el.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
// Teleported nodes outlive an un-unmounted wrapper, so a menu left open by
|
||||
// one test would still answer `menuItem()` in the next. Unmount rather than
|
||||
// clearing document.body — ripping the body out from under a live component
|
||||
// detaches Vue's teleport anchor and the next patch throws on a null parent.
|
||||
const mounted: { unmount: () => void }[] = [];
|
||||
type MountArgs = Parameters<typeof mount<typeof InjectorBindingModal>>;
|
||||
function mountModal(...args: MountArgs): ReturnType<typeof mount<typeof InjectorBindingModal>> {
|
||||
const w = mount(...args);
|
||||
mounted.push(w);
|
||||
return w;
|
||||
}
|
||||
afterEach(() => {
|
||||
for (const w of mounted.splice(0)) w.unmount();
|
||||
});
|
||||
|
||||
function makeRow(over: Partial<InjectorRow> = {}): InjectorRow {
|
||||
return {
|
||||
_uid: "uid_self",
|
||||
@@ -16,7 +46,7 @@ function makeRow(over: Partial<InjectorRow> = {}): InjectorRow {
|
||||
|
||||
describe("InjectorBindingModal — identity section", () => {
|
||||
it("renders the row's slot_name in the header + current binding in the input", () => {
|
||||
const w = mount(InjectorBindingModal, {
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: makeRow({ slot_name: "input_2", binding: "seed" }) },
|
||||
});
|
||||
expect(w.find('[data-test="ibm-name"]').text()).toBe("input_2");
|
||||
@@ -25,14 +55,14 @@ describe("InjectorBindingModal — identity section", () => {
|
||||
});
|
||||
|
||||
it("does NOT emit update while typing — draft buffer holds edits until Save", async () => {
|
||||
const w = mount(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
const w = mountModal(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
const input = w.find<HTMLInputElement>('[data-test="ibm-binding"]');
|
||||
await input.setValue("renamed");
|
||||
expect(w.emitted("update")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Save emits update with the draft binding + closes", async () => {
|
||||
const w = mount(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
const w = mountModal(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
await w.find<HTMLInputElement>('[data-test="ibm-binding"]').setValue("renamed");
|
||||
await w.find('[data-test="ibm-save"]').trigger("click");
|
||||
const updates = w.emitted("update")!;
|
||||
@@ -44,7 +74,7 @@ describe("InjectorBindingModal — identity section", () => {
|
||||
|
||||
describe("InjectorBindingModal — template section", () => {
|
||||
it("template textarea bound to row.template at open", () => {
|
||||
const w = mount(InjectorBindingModal, {
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: makeRow({ template: "i love $input_1" }) },
|
||||
});
|
||||
const ta = w.find<HTMLTextAreaElement>('[data-test="ibm-template"]');
|
||||
@@ -52,7 +82,7 @@ describe("InjectorBindingModal — template section", () => {
|
||||
});
|
||||
|
||||
it("Save emits a non-empty template string verbatim (no null collapse)", async () => {
|
||||
const w = mount(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
const w = mountModal(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
await w.find<HTMLTextAreaElement>('[data-test="ibm-template"]').setValue("i love $input_2");
|
||||
await w.find('[data-test="ibm-save"]').trigger("click");
|
||||
const updates = w.emitted("update")!;
|
||||
@@ -62,7 +92,7 @@ describe("InjectorBindingModal — template section", () => {
|
||||
});
|
||||
|
||||
it("Save collapses whitespace-only template to null", async () => {
|
||||
const w = mount(InjectorBindingModal, {
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: makeRow({ template: "hello" }) },
|
||||
});
|
||||
await w.find<HTMLTextAreaElement>('[data-test="ibm-template"]').setValue(" ");
|
||||
@@ -78,21 +108,21 @@ describe("InjectorBindingModal — template section", () => {
|
||||
makeRow({ _uid: "uid_b", slot_name: "input_1", binding: "b" }),
|
||||
makeRow({ _uid: "uid_c", slot_name: "input_2", binding: "c" }),
|
||||
];
|
||||
const w = mount(InjectorBindingModal, {
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: siblings[0], siblingRows: siblings },
|
||||
});
|
||||
await w.find('[data-test="ibm-insert-slot"]').trigger("click");
|
||||
expect(w.find('[data-test="ibm-slot-item-input_0"]').exists()).toBe(true);
|
||||
expect(w.find('[data-test="ibm-slot-item-input_1"]').exists()).toBe(false);
|
||||
expect(w.find('[data-test="ibm-slot-item-input_2"]').exists()).toBe(false);
|
||||
expect(menuItem("input_0")).not.toBeNull();
|
||||
expect(menuItem("input_1")).toBeNull();
|
||||
expect(menuItem("input_2")).toBeNull();
|
||||
});
|
||||
|
||||
it("clicking the row's own slot appends $slot_name to the draft, Save persists it", async () => {
|
||||
const w = mount(InjectorBindingModal, {
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: makeRow({ slot_name: "input_0", template: "prefix " }) },
|
||||
});
|
||||
await w.find('[data-test="ibm-insert-slot"]').trigger("click");
|
||||
await w.find('[data-test="ibm-slot-item-input_0"]').trigger("click");
|
||||
await clickMenuItem("input_0");
|
||||
await w.find('[data-test="ibm-save"]').trigger("click");
|
||||
const updates = w.emitted("update")!;
|
||||
const last = updates[updates.length - 1][0] as Partial<InjectorRow>;
|
||||
@@ -100,7 +130,7 @@ describe("InjectorBindingModal — template section", () => {
|
||||
});
|
||||
|
||||
it("preview pane highlights known $slot refs (own slot) + flags unknown", () => {
|
||||
const w = mount(InjectorBindingModal, {
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: makeRow({ slot_name: "input_0", template: "love $input_0 and $missing" }) },
|
||||
});
|
||||
expect(w.findAll(".ibm-tok--ref")).toHaveLength(1);
|
||||
@@ -108,7 +138,7 @@ describe("InjectorBindingModal — template section", () => {
|
||||
});
|
||||
|
||||
it("reset button clears the draft template", async () => {
|
||||
const w = mount(InjectorBindingModal, {
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: makeRow({ template: "hi" }) },
|
||||
});
|
||||
await w.find('[data-test="ibm-template-reset"]').trigger("click");
|
||||
@@ -117,7 +147,7 @@ describe("InjectorBindingModal — template section", () => {
|
||||
});
|
||||
|
||||
it("typing a bare $ does NOT crash the tokenizer (regression)", () => {
|
||||
const w = mount(InjectorBindingModal, {
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: makeRow({ template: "hello $" }) },
|
||||
});
|
||||
expect(w.find('[data-test="ibm-preview"]').exists()).toBe(true);
|
||||
@@ -126,7 +156,7 @@ describe("InjectorBindingModal — template section", () => {
|
||||
|
||||
describe("InjectorBindingModal — Save / Cancel / keybinds", () => {
|
||||
it("Cancel closes without emitting update", async () => {
|
||||
const w = mount(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
const w = mountModal(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
await w.find<HTMLInputElement>('[data-test="ibm-binding"]').setValue("dropped");
|
||||
await w.find('[data-test="ibm-cancel"]').trigger("click");
|
||||
expect(w.emitted("update")).toBeUndefined();
|
||||
@@ -134,7 +164,7 @@ describe("InjectorBindingModal — Save / Cancel / keybinds", () => {
|
||||
});
|
||||
|
||||
it("clicking overlay cancels (no update emit)", async () => {
|
||||
const w = mount(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
const w = mountModal(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
await w.find<HTMLInputElement>('[data-test="ibm-binding"]').setValue("dropped");
|
||||
await w.find('[data-test="ibm-overlay"]').trigger("click");
|
||||
expect(w.emitted("update")).toBeUndefined();
|
||||
@@ -142,7 +172,7 @@ describe("InjectorBindingModal — Save / Cancel / keybinds", () => {
|
||||
});
|
||||
|
||||
it("Esc cancels", async () => {
|
||||
const w = mount(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
const w = mountModal(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
await w.find<HTMLInputElement>('[data-test="ibm-binding"]').setValue("dropped");
|
||||
await w.find('[data-test="ibm-overlay"]').trigger("keydown", { key: "Escape" });
|
||||
expect(w.emitted("update")).toBeUndefined();
|
||||
@@ -150,7 +180,7 @@ describe("InjectorBindingModal — Save / Cancel / keybinds", () => {
|
||||
});
|
||||
|
||||
it("Cmd+Enter saves", async () => {
|
||||
const w = mount(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
const w = mountModal(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
await w.find<HTMLInputElement>('[data-test="ibm-binding"]').setValue("kept");
|
||||
await w.find('[data-test="ibm-overlay"]').trigger("keydown", { key: "Enter", metaKey: true });
|
||||
const updates = w.emitted("update")!;
|
||||
@@ -161,20 +191,20 @@ describe("InjectorBindingModal — Save / Cancel / keybinds", () => {
|
||||
});
|
||||
|
||||
it("Ctrl+Enter also saves (non-mac users)", async () => {
|
||||
const w = mount(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
const w = mountModal(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
await w.find<HTMLInputElement>('[data-test="ibm-binding"]').setValue("kept2");
|
||||
await w.find('[data-test="ibm-overlay"]').trigger("keydown", { key: "Enter", ctrlKey: true });
|
||||
expect(w.emitted("update")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("Save button is disabled when no changes were made", () => {
|
||||
const w = mount(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
const w = mountModal(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
const btn = w.find<HTMLButtonElement>('[data-test="ibm-save"]');
|
||||
expect(btn.element.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("Save button becomes enabled after editing the binding", async () => {
|
||||
const w = mount(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
const w = mountModal(InjectorBindingModal, { props: { row: makeRow() } });
|
||||
await w.find<HTMLInputElement>('[data-test="ibm-binding"]').setValue("changed");
|
||||
const btn = w.find<HTMLButtonElement>('[data-test="ibm-save"]');
|
||||
expect(btn.element.disabled).toBe(false);
|
||||
@@ -187,23 +217,23 @@ describe("InjectorBindingModal — general (template) row", () => {
|
||||
}
|
||||
|
||||
it("header reads as a Template row, not a socket", () => {
|
||||
const w = mount(InjectorBindingModal, { props: { row: generalRow() } });
|
||||
const w = mountModal(InjectorBindingModal, { props: { row: generalRow() } });
|
||||
expect(w.find('[data-test="ibm-name"]').text()).toBe("template row");
|
||||
expect(w.find('[data-test="ibm-chip"]').text()).toBe("Template");
|
||||
});
|
||||
|
||||
it("insert menu lists every reference (sockets + socket-row bindings)", async () => {
|
||||
const w = mount(InjectorBindingModal, {
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: generalRow(), references: ["input_0", "input_1", "test"] },
|
||||
});
|
||||
await w.find('[data-test="ibm-insert-slot"]').trigger("click");
|
||||
expect(w.find('[data-test="ibm-slot-item-input_0"]').exists()).toBe(true);
|
||||
expect(w.find('[data-test="ibm-slot-item-input_1"]').exists()).toBe(true);
|
||||
expect(w.find('[data-test="ibm-slot-item-test"]').exists()).toBe(true);
|
||||
expect(menuItem("input_0")).not.toBeNull();
|
||||
expect(menuItem("input_1")).not.toBeNull();
|
||||
expect(menuItem("test")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("preview treats references as known refs (no unknown flags)", () => {
|
||||
const w = mount(InjectorBindingModal, {
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: generalRow({ template: "$input_0 by $test" }), references: ["input_0", "test"] },
|
||||
});
|
||||
expect(w.findAll(".ibm-tok--ref")).toHaveLength(2);
|
||||
@@ -211,7 +241,7 @@ describe("InjectorBindingModal — general (template) row", () => {
|
||||
});
|
||||
|
||||
it("flags a ref that isn't in the references list as unknown", () => {
|
||||
const w = mount(InjectorBindingModal, {
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: generalRow({ template: "$input_0 and $missing" }), references: ["input_0"] },
|
||||
});
|
||||
expect(w.findAll(".ibm-tok--ref")).toHaveLength(1);
|
||||
@@ -219,7 +249,7 @@ describe("InjectorBindingModal — general (template) row", () => {
|
||||
});
|
||||
|
||||
it("Save emits binding + template for a general row", async () => {
|
||||
const w = mount(InjectorBindingModal, {
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: generalRow({ binding: "combo", template: "$input_0" }), references: ["input_0", "test"] },
|
||||
});
|
||||
await w.find<HTMLTextAreaElement>('[data-test="ibm-template"]').setValue("$input_0 by $test");
|
||||
@@ -231,14 +261,42 @@ describe("InjectorBindingModal — general (template) row", () => {
|
||||
});
|
||||
|
||||
it("inserting a socket-row binding ref appends $name to the draft", async () => {
|
||||
const w = mount(InjectorBindingModal, {
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: generalRow({ template: "prefix " }), references: ["input_0", "test"] },
|
||||
});
|
||||
await w.find('[data-test="ibm-insert-slot"]').trigger("click");
|
||||
await w.find('[data-test="ibm-slot-item-test"]').trigger("click");
|
||||
await clickMenuItem("test");
|
||||
await w.find('[data-test="ibm-save"]').trigger("click");
|
||||
const updates = w.emitted("update")!;
|
||||
const last = updates[updates.length - 1][0] as Partial<InjectorRow>;
|
||||
expect(last.template).toBe("prefix $test");
|
||||
});
|
||||
|
||||
it("a click outside the insert menu closes it", async () => {
|
||||
// The menu had no outside-click dismissal at all — once open, the only
|
||||
// way out was picking an item or closing the whole modal.
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: generalRow(), references: ["input_0"] },
|
||||
});
|
||||
await w.find('[data-test="ibm-insert-slot"]').trigger("click");
|
||||
await nextTick();
|
||||
expect(menuItem("input_0")).not.toBeNull();
|
||||
document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
|
||||
await nextTick();
|
||||
expect(menuItem("input_0")).toBeNull();
|
||||
});
|
||||
|
||||
it("Escape closes the insert menu without discarding the draft", async () => {
|
||||
// Escape cancels the modal (dropping the draft). With a dropdown open it
|
||||
// must dismiss the dropdown first, not throw away the user's edits.
|
||||
const w = mountModal(InjectorBindingModal, {
|
||||
props: { row: generalRow({ template: "prefix " }), references: ["input_0"] },
|
||||
});
|
||||
await w.find('[data-test="ibm-insert-slot"]').trigger("click");
|
||||
await nextTick();
|
||||
expect(menuItem("input_0")).not.toBeNull();
|
||||
await w.find('[data-test="ibm-overlay"]').trigger("keydown", { key: "Escape" });
|
||||
expect(menuItem("input_0")).toBeNull();
|
||||
expect(w.emitted("cancel")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
* there is no draft buffer, mirroring the lightweight per-row UX of
|
||||
* the inline row controls. Save = close.
|
||||
*/
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
|
||||
import type { InjectorRow } from "../../widgets/_shared";
|
||||
|
||||
const props = withDefaults(
|
||||
@@ -200,7 +200,7 @@ function insertSlotRef(slotName: string): void {
|
||||
} else {
|
||||
next = current + insertion;
|
||||
}
|
||||
showInsertMenu.value = false;
|
||||
closeInsertMenu();
|
||||
draftTemplate.value = next;
|
||||
}
|
||||
|
||||
@@ -270,8 +270,87 @@ const previewTokens = computed<PreviewToken[]>(() => {
|
||||
const refCount = computed(() => previewTokens.value.filter((t) => t.kind === "ref").length);
|
||||
const unknownRefCount = computed(() => previewTokens.value.filter((t) => t.kind === "ref-unknown").length);
|
||||
|
||||
// --- Insert menu placement + dismissal ---------------------------------
|
||||
//
|
||||
// The menu used to be `position: absolute` inside the modal, so it was
|
||||
// CLIPPED by the modal's scroll container — a menu opened near the bottom
|
||||
// simply disappeared below the fold. It's now teleported to <body> with
|
||||
// `position: fixed` viewport coords (the same strategy RichTextInput's
|
||||
// autocomplete popover uses) and flips above the button when there's no
|
||||
// room below.
|
||||
const menuBtnEl = ref<HTMLButtonElement | null>(null);
|
||||
const menuEl = ref<HTMLDivElement | null>(null);
|
||||
const menuPos = ref<{ top: number; left: number; flipped: boolean }>({
|
||||
top: 0, left: 0, flipped: false,
|
||||
});
|
||||
const MENU_MAX_H = 220; // keep in sync with `max-height` in _modal-template-ctrls.css
|
||||
const MENU_MIN_W = 200;
|
||||
|
||||
function positionInsertMenu(): void {
|
||||
const btn = menuBtnEl.value;
|
||||
if (!btn) return;
|
||||
const rect = btn.getBoundingClientRect();
|
||||
const margin = 8;
|
||||
const spaceBelow = window.innerHeight - rect.bottom - margin;
|
||||
const flipped = spaceBelow < MENU_MAX_H && rect.top > spaceBelow;
|
||||
// Right-align to the button (the menu is wider than it), then clamp so a
|
||||
// button near the left edge can't push the menu off-screen.
|
||||
const left = Math.max(margin, Math.min(rect.right - MENU_MIN_W, window.innerWidth - MENU_MIN_W - margin));
|
||||
menuPos.value = {
|
||||
top: flipped ? rect.top - 4 : rect.bottom + 4,
|
||||
left,
|
||||
flipped,
|
||||
};
|
||||
}
|
||||
|
||||
/** Close when the click lands outside BOTH the menu and its trigger button.
|
||||
* Bound on `mousedown` (not `click`) so it fires before the menu item's own
|
||||
* click handler can be lost to a re-render, and excludes the button so the
|
||||
* toggle doesn't immediately re-open what it just closed. */
|
||||
function onDocMouseDown(ev: MouseEvent): void {
|
||||
const target = ev.target as Node | null;
|
||||
if (!target) return;
|
||||
if (menuEl.value?.contains(target)) return;
|
||||
if (menuBtnEl.value?.contains(target)) return;
|
||||
closeInsertMenu();
|
||||
}
|
||||
|
||||
function openInsertMenu(): void {
|
||||
showInsertMenu.value = true;
|
||||
void nextTick(() => {
|
||||
positionInsertMenu();
|
||||
document.addEventListener("mousedown", onDocMouseDown, true);
|
||||
window.addEventListener("scroll", positionInsertMenu, true);
|
||||
window.addEventListener("resize", positionInsertMenu);
|
||||
});
|
||||
}
|
||||
|
||||
function closeInsertMenu(): void {
|
||||
if (!showInsertMenu.value) return;
|
||||
showInsertMenu.value = false;
|
||||
document.removeEventListener("mousedown", onDocMouseDown, true);
|
||||
window.removeEventListener("scroll", positionInsertMenu, true);
|
||||
window.removeEventListener("resize", positionInsertMenu);
|
||||
}
|
||||
|
||||
function toggleInsertMenu(): void {
|
||||
showInsertMenu.value = !showInsertMenu.value;
|
||||
if (showInsertMenu.value) closeInsertMenu();
|
||||
else openInsertMenu();
|
||||
}
|
||||
|
||||
onBeforeUnmount(closeInsertMenu);
|
||||
|
||||
/** Mirror the host's resolved theme onto the body-teleported menu. The
|
||||
* `--wp-*` light/dark variants hang off `.wp-theme-light` / `.wp-theme-dark`,
|
||||
* which the teleported node escapes — without this the menu paints with the
|
||||
* default dark palette inside a light-themed canvas. Same helper shape as
|
||||
* RichTextInput's `teleportThemeClass`. */
|
||||
function menuThemeClass(): string {
|
||||
const el = menuBtnEl.value;
|
||||
if (!el || typeof el.closest !== "function") return "";
|
||||
const themed = el.closest(".wp-theme-light, .wp-theme-dark");
|
||||
if (!themed) return "";
|
||||
return themed.classList.contains("wp-theme-light") ? "wp-theme-light" : "wp-theme-dark";
|
||||
}
|
||||
|
||||
// Esc cancels (drops draft), Cmd/Ctrl+Enter saves. Mirrors the
|
||||
@@ -281,6 +360,12 @@ function toggleInsertMenu(): void {
|
||||
function onKeydown(ev: KeyboardEvent): void {
|
||||
if (ev.key === "Escape") {
|
||||
ev.preventDefault();
|
||||
// Escape dismisses the insert menu first — losing the whole draft
|
||||
// because a dropdown happened to be open is a nasty surprise.
|
||||
if (showInsertMenu.value) {
|
||||
closeInsertMenu();
|
||||
return;
|
||||
}
|
||||
onCancel();
|
||||
return;
|
||||
}
|
||||
@@ -342,38 +427,44 @@ function onKeydown(ev: KeyboardEvent): void {
|
||||
<span class="ibm__section-label">Template</span>
|
||||
<span class="ibm__section-hint">{{ isGeneral ? "$ref names · $$ for literal $ · composed after socket rows" : "$slot_name refs · $$ for literal $ · empty = pass-through" }}</span>
|
||||
<div class="ibm__head-actions">
|
||||
<div class="ibm__menu-wrap">
|
||||
<div class="wp-ibm__menu-wrap">
|
||||
<button
|
||||
v-if="insertOptions.length > 0"
|
||||
ref="menuBtnEl"
|
||||
type="button"
|
||||
class="ibm__menu-btn"
|
||||
class="wp-ibm__menu-btn"
|
||||
data-test="ibm-insert-slot"
|
||||
:title="`Insert a reference (${insertOptions.length} available)`"
|
||||
aria-label="Insert reference"
|
||||
:aria-expanded="showInsertMenu"
|
||||
@click="toggleInsertMenu"
|
||||
><i class="pi pi-plus" aria-hidden="true" /> {{ isGeneral ? "$ref" : "$slot" }}</button>
|
||||
<div
|
||||
v-if="showInsertMenu"
|
||||
class="ibm__menu"
|
||||
data-test="ibm-slot-menu"
|
||||
role="listbox"
|
||||
>
|
||||
<button
|
||||
v-for="opt in insertOptions"
|
||||
:key="opt.slotName"
|
||||
type="button"
|
||||
class="ibm__menu-item"
|
||||
:data-test="`ibm-slot-item-${opt.slotName}`"
|
||||
role="option"
|
||||
:aria-selected="false"
|
||||
@click="insertSlotRef(opt.slotName)"
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="showInsertMenu"
|
||||
ref="menuEl"
|
||||
class="wp-ibm__menu"
|
||||
:class="[menuThemeClass(), { 'wp-ibm__menu--up': menuPos.flipped }]"
|
||||
:style="{ top: menuPos.top + 'px', left: menuPos.left + 'px' }"
|
||||
data-test="ibm-slot-menu"
|
||||
role="listbox"
|
||||
>
|
||||
<span class="ibm__menu-name">${{ opt.slotName }}</span>
|
||||
<span v-if="opt.label !== opt.slotName" class="ibm__menu-label">{{ opt.label }}</span>
|
||||
<span v-if="opt.typeKey" class="ibm__menu-type">{{ opt.typeKey }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-for="opt in insertOptions"
|
||||
:key="opt.slotName"
|
||||
type="button"
|
||||
class="wp-ibm__menu-item"
|
||||
:data-test="`ibm-slot-item-${opt.slotName}`"
|
||||
role="option"
|
||||
:aria-selected="false"
|
||||
@click="insertSlotRef(opt.slotName)"
|
||||
>
|
||||
<span class="ibm__menu-name">${{ opt.slotName }}</span>
|
||||
<span v-if="opt.label !== opt.slotName" class="ibm__menu-label">{{ opt.label }}</span>
|
||||
<span v-if="opt.typeKey" class="ibm__menu-type">{{ opt.typeKey }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</Teleport>
|
||||
</div>
|
||||
<button
|
||||
v-if="templateValue"
|
||||
@@ -622,7 +713,13 @@ function onKeydown(ev: KeyboardEvent): void {
|
||||
background: color-mix(in srgb, var(--wp-text3) 18%, transparent);
|
||||
color: var(--wp-text2);
|
||||
flex-shrink: 0;
|
||||
/* Right-align the type pill even on rows WITHOUT a label (the label
|
||||
* carries the `margin-left:auto` for labelled rows). When a label IS
|
||||
* present it precedes the type, so reset the auto there and let the
|
||||
* flex gap space them — keeping label + type grouped at the right. */
|
||||
margin-left: auto;
|
||||
}
|
||||
.ibm__menu-label + .ibm__menu-type { margin-left: 0; }
|
||||
|
||||
/* Reset button styling shared via _modal-template-ctrls.css. */
|
||||
|
||||
@@ -636,7 +733,7 @@ function onKeydown(ev: KeyboardEvent): void {
|
||||
font: 11px/1.5 var(--wp-font-mono);
|
||||
color: var(--wp-text);
|
||||
min-height: 56px;
|
||||
resize: vertical;
|
||||
resize: vertical; overscroll-behavior: contain;
|
||||
}
|
||||
.ibm__template:focus { outline: none; border-color: var(--wp-accent); }
|
||||
.ibm__template--set {
|
||||
|
||||
@@ -619,6 +619,14 @@ function onDragEnd(): void {
|
||||
.wp-inj-summary__template {
|
||||
color: var(--wp-accent);
|
||||
font-family: var(--wp-font-mono, monospace);
|
||||
/* A collapsed row summary. One line is the whole contract — a long template
|
||||
otherwise stretched the row and broke the list rhythm. */
|
||||
display: inline-block;
|
||||
max-width: 100%;
|
||||
vertical-align: bottom;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Template-active badge — small pill at the trailing edge of the
|
||||
|
||||
@@ -54,6 +54,41 @@ describe("InjectorWidget — lifecycle", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("InjectorWidget — durable custom slot labels", () => {
|
||||
const labelledRow = (over: Record<string, unknown> = {}): string => JSON.stringify({
|
||||
version: 1,
|
||||
rows: [{ _uid: "uid_a", slot_name: "input_0", binding: "phrase", enabled: true, internal: false, ...over }],
|
||||
});
|
||||
|
||||
it("renders the durable row.slot_label as the pin tag, even with an empty slotLabels prop", () => {
|
||||
const w = mount(InjectorWidget, {
|
||||
props: { nodeId: 7, initialJson: labelledRow({ slot_label: "test_label_1" }), connectedSlots: ["input_0"], slotLabels: {} },
|
||||
});
|
||||
expect(w.find('[data-test="inj-row-slot"]').text()).toBe("test_label_1");
|
||||
});
|
||||
|
||||
it("durable slot_label wins over a live slotLabels entry", () => {
|
||||
const w = mount(InjectorWidget, {
|
||||
props: { nodeId: 7, initialJson: labelledRow({ slot_label: "durable" }), connectedSlots: ["input_0"], slotLabels: { input_0: "live" } },
|
||||
});
|
||||
expect(w.find('[data-test="inj-row-slot"]').text()).toBe("durable");
|
||||
});
|
||||
|
||||
it("falls back to the live slotLabels entry when no durable slot_label", () => {
|
||||
const w = mount(InjectorWidget, {
|
||||
props: { nodeId: 7, initialJson: labelledRow(), connectedSlots: ["input_0"], slotLabels: { input_0: "live_label" } },
|
||||
});
|
||||
expect(w.find('[data-test="inj-row-slot"]').text()).toBe("live_label");
|
||||
});
|
||||
|
||||
it("falls back to slot_name when neither durable nor live label is set", () => {
|
||||
const w = mount(InjectorWidget, {
|
||||
props: { nodeId: 7, initialJson: labelledRow(), connectedSlots: ["input_0"], slotLabels: {} },
|
||||
});
|
||||
expect(w.find('[data-test="inj-row-slot"]').text()).toBe("input_0");
|
||||
});
|
||||
});
|
||||
|
||||
describe("InjectorWidget — template persistence (Phase 6)", () => {
|
||||
const ONE_ROW = JSON.stringify({
|
||||
version: 1,
|
||||
|
||||
@@ -812,7 +812,7 @@ function openRowContextMenu(ev: MouseEvent, idx: number): void {
|
||||
? `$${row.binding}`
|
||||
: isGeneral
|
||||
? "template row"
|
||||
: (props.slotLabels[row.slot_name] ?? row.slot_name);
|
||||
: (row.slot_label ?? props.slotLabels[row.slot_name] ?? row.slot_name);
|
||||
ctxMenu.value = {
|
||||
visible: true,
|
||||
x: Math.max(8, x),
|
||||
@@ -880,7 +880,7 @@ defineExpose({ addRow, addGeneralRow, removeRow });
|
||||
:reorderable="row.kind === 'general' ? generalRowCount > 1 : socketRowCount > 1"
|
||||
:is-connected="row.kind === 'general' ? true : isConnected(row.slot_name)"
|
||||
:value-type="row.kind === 'general' ? undefined : slotTypes[row.slot_name]"
|
||||
:display-label="row.kind === 'general' ? undefined : slotLabels[row.slot_name]"
|
||||
:display-label="row.kind === 'general' ? undefined : (row.slot_label ?? slotLabels[row.slot_name])"
|
||||
:conflict-severity="conflictByUid[row._uid]?.severity"
|
||||
:conflict-label="conflictByUid[row._uid]?.label"
|
||||
:drop-indicator="dropIndicatorFor(row._uid)"
|
||||
|
||||
@@ -3,6 +3,8 @@ import { mount } from "@vue/test-utils";
|
||||
import SeedListWidget from "./SeedListWidget.vue";
|
||||
import SeedListModal from "../shared/SeedListModal.vue";
|
||||
import { emptySeedListConfig } from "./types";
|
||||
import type { SeedListConfig } from "./types";
|
||||
import { deriveLoopSeeds } from "../shared/seed-derive";
|
||||
|
||||
describe("SeedListWidget", () => {
|
||||
it("renders defaults — hash chip active, all three override switches off", () => {
|
||||
@@ -186,3 +188,94 @@ describe("SeedListWidget seeds button", () => {
|
||||
expect(off.findComponent(SeedListModal).props("overrideHint")).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("SeedListWidget bypass mirror (#13)", () => {
|
||||
it("shows an N-bypassed badge from the loop's bypassedFrames", () => {
|
||||
const w = mount(SeedListWidget, {
|
||||
props: { modelValue: emptySeedListConfig(), bypassedFrames: [1, 3] },
|
||||
});
|
||||
expect(w.find('[data-test="seedlist-seeds-bypass-badge"]').text()).toMatch(/2 bypassed/i);
|
||||
});
|
||||
it("no bypass badge when the loop bypasses nothing", () => {
|
||||
const w = mount(SeedListWidget, {
|
||||
props: { modelValue: emptySeedListConfig(), bypassedFrames: [] },
|
||||
});
|
||||
expect(w.find('[data-test="seedlist-seeds-bypass-badge"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Frame chips on the Seed List. Unlike the Loop's, these take a PLAIN click:
|
||||
* this node has no edit cursor, so there is nothing else a chip could do and
|
||||
* requiring a modifier for the only available action would be ceremony.
|
||||
*/
|
||||
describe("SeedListWidget frame chips", () => {
|
||||
function fw(cfgPatch: Partial<SeedListConfig> = {}, extra: Record<string, unknown> = {}) {
|
||||
return mount(SeedListWidget, {
|
||||
props: { modelValue: { ...emptySeedListConfig(), ...cfgPatch }, baseSeed: 42, count: 4, ...extra },
|
||||
});
|
||||
}
|
||||
const lastEmit = (w: ReturnType<typeof fw>) => {
|
||||
const calls = w.emitted("update:modelValue");
|
||||
return calls?.[calls.length - 1]?.[0] as SeedListConfig;
|
||||
};
|
||||
|
||||
it("renders one chip per frame and NO base chip — there is nothing to inherit", () => {
|
||||
const w = fw();
|
||||
expect(w.findAll('[data-test^="seedlist-frame-"]')).toHaveLength(4);
|
||||
expect(w.find('[data-test="seedlist-frame-base"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("a plain click locks the frame to the seed it would have used", async () => {
|
||||
const w = fw();
|
||||
await w.find('[data-test="seedlist-frame-3"]').trigger("click");
|
||||
const locks = lastEmit(w).seed_locks!;
|
||||
expect(Object.keys(locks)).toEqual(["2"]);
|
||||
expect(locks["2"]).toBe(deriveLoopSeeds(42, 4, "hash_index")[2]);
|
||||
});
|
||||
|
||||
it("a plain click on a locked frame unlocks it", async () => {
|
||||
const w = fw({ seed_locks: { "2": 999 } });
|
||||
await w.find('[data-test="seedlist-frame-3"]').trigger("click");
|
||||
expect(lastEmit(w).seed_locks).toEqual({});
|
||||
});
|
||||
|
||||
it("locks against the EFFECTIVE strategy when the loop overrides it", async () => {
|
||||
const w = fw({}, { previewStrategy: "sequential" });
|
||||
await w.find('[data-test="seedlist-frame-2"]').trigger("click");
|
||||
expect(lastEmit(w).seed_locks!["1"]).toBe(deriveLoopSeeds(42, 4, "sequential")[1]);
|
||||
});
|
||||
|
||||
it("marks locked chips", () => {
|
||||
const w = fw({ seed_locks: { "1": 5 } });
|
||||
expect(w.find('[data-test="seedlist-frame-2"]').classes()).toContain("wp-fchips__chip--locked");
|
||||
expect(w.find('[data-test="seedlist-frame-1"]').classes()).not.toContain("wp-fchips__chip--locked");
|
||||
});
|
||||
|
||||
it("shows frames the wired loop bypasses", () => {
|
||||
const w = fw({}, { bypassedFrames: [1, 3] });
|
||||
expect(w.find('[data-test="seedlist-frame-2"]').classes()).toContain("wp-fchips__chip--bypassed");
|
||||
expect(w.find('[data-test="seedlist-frame-4"]').classes()).toContain("wp-fchips__chip--bypassed");
|
||||
expect(w.find('[data-test="seedlist-frame-1"]').classes()).not.toContain("wp-fchips__chip--bypassed");
|
||||
});
|
||||
|
||||
// Bypass belongs to the wired Context Loop. Editing it from here would mean
|
||||
// writing to a different node.
|
||||
it("refuses to change bypass — it is owned by the loop", async () => {
|
||||
const w = fw({}, { bypassedFrames: [1] });
|
||||
await w.find('[data-test="seedlist-frame-2"]').trigger("click", { altKey: true });
|
||||
expect(w.emitted("update:modelValue")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("says where bypass is owned rather than looking broken", () => {
|
||||
const w = fw({}, { bypassedFrames: [1] });
|
||||
expect(w.find('[data-test="seedlist-frame-2"]').attributes("title")).toMatch(/Context Loop/i);
|
||||
});
|
||||
|
||||
it("a locked frame can also be bypassed by the loop", () => {
|
||||
const w = fw({ seed_locks: { "1": 5 } }, { bypassedFrames: [1] });
|
||||
const chip = w.find('[data-test="seedlist-frame-2"]');
|
||||
expect(chip.classes()).toContain("wp-fchips__chip--locked");
|
||||
expect(chip.classes()).toContain("wp-fchips__chip--bypassed");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
import { computed, ref } from "vue";
|
||||
import type { SeedListConfig, SeedListStrategy } from "./types";
|
||||
import SeedListModal from "../shared/SeedListModal.vue";
|
||||
import FrameChips from "../shared/FrameChips.vue";
|
||||
import { deriveLoopSeeds } from "../shared/seed-derive";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
@@ -37,12 +39,21 @@ const props = withDefaults(
|
||||
* executed `loop_seeds` UI payload by the host glue. Drives the seed
|
||||
* modal's per-frame "lock previous" button. Null until a run lands. */
|
||||
previousSeeds?: number[] | null;
|
||||
/** 0-based frames the wired loop bypasses (resolved by the host glue —
|
||||
* only when Override count from loop is on). Shown READ-ONLY in the
|
||||
* modal (dimmed rows + "N bypassed" badge); bypass is owned by the loop.
|
||||
* Empty when no loop is wired or none are bypassed. */
|
||||
bypassedFrames?: number[];
|
||||
}>(),
|
||||
{ nodeMode: 0, baseSeed: 0, count: 1, previewStrategy: undefined, previousSeeds: null },
|
||||
{ nodeMode: 0, baseSeed: 0, count: 1, previewStrategy: undefined, previousSeeds: null, bypassedFrames: () => [] },
|
||||
);
|
||||
|
||||
const emit = defineEmits<{ "update:modelValue": [next: SeedListConfig] }>();
|
||||
|
||||
/** Frame-grid collapse. Owned by the widget glue so it can persist to
|
||||
* `node.properties` and survive a workflow save. */
|
||||
const chipsCollapsed = defineModel<boolean>("chipsCollapsed", { default: false });
|
||||
|
||||
const STRATEGIES: { id: SeedListStrategy; label: string; hint: string }[] = [
|
||||
{ id: "hash_index", label: "hash", hint: "Independent per-iteration; recommended for varied results." },
|
||||
{ id: "sequential", label: "sequential", hint: "base, base+1, base+2, … Predictable diffs." },
|
||||
@@ -73,11 +84,54 @@ const isBypassed = computed<boolean>(() => props.nodeMode === 4);
|
||||
|
||||
const seedsOpen = ref(false);
|
||||
const lockedCount = computed(() => Object.keys(props.modelValue.seed_locks ?? {}).length);
|
||||
const bypassedCount = computed(() => props.bypassedFrames.length);
|
||||
|
||||
function onSeedLocks(next: Record<string, number>): void {
|
||||
emit("update:modelValue", { ...props.modelValue, seed_locks: next });
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* Frame chips — lock a seed without opening the modal.
|
||||
*
|
||||
* Unlike the Loop's chips these take a PLAIN click, because this node has no
|
||||
* edit cursor: there is nothing else a chip could do, and making people hold
|
||||
* Shift for the only available action would be ceremony.
|
||||
*
|
||||
* Bypass is shown but not editable. It belongs to the WP Context Loop wired
|
||||
* into `loop_config` (and only surfaces when "Override count from loop" is
|
||||
* on) — changing it here would mean writing to a different node.
|
||||
* ------------------------------------------------------------------------ */
|
||||
|
||||
const BYPASS_READONLY_HINT = "Bypassed by the wired Context Loop — change it there.";
|
||||
|
||||
/** 0-based locked frame indices. Config keys are strings; a non-numeric key
|
||||
* is ignored rather than becoming `NaN` in the set. */
|
||||
const lockSet = computed(() => {
|
||||
const out = new Set<number>();
|
||||
for (const k of Object.keys(props.modelValue.seed_locks ?? {})) {
|
||||
const n = Number(k);
|
||||
if (Number.isInteger(n)) out.add(n);
|
||||
}
|
||||
return out;
|
||||
});
|
||||
|
||||
/** The seed series this node WOULD produce, using the same effective values
|
||||
* the modal previews with — so a chip-lock and a modal-lock agree. */
|
||||
const derivedSeeds = computed(() =>
|
||||
deriveLoopSeeds(
|
||||
props.baseSeed,
|
||||
Math.max(1, props.count ?? 1),
|
||||
props.previewStrategy ?? props.modelValue.strategy,
|
||||
),
|
||||
);
|
||||
|
||||
function toggleFrameLock(i: number): void {
|
||||
const next = { ...(props.modelValue.seed_locks ?? {}) };
|
||||
if (lockSet.value.has(i)) delete next[String(i)];
|
||||
else next[String(i)] = derivedSeeds.value[i] ?? props.baseSeed;
|
||||
emit("update:modelValue", { ...props.modelValue, seed_locks: next });
|
||||
}
|
||||
|
||||
/** True while strategy comes from the upstream loop_config wire.
|
||||
* Mirrors what `setStockWidgetDisabled("count", ...)` does for the count
|
||||
* stock widget in the host glue — chips can't live as a stock widget so
|
||||
@@ -153,9 +207,24 @@ function toggleOverrideStrategy(): void {
|
||||
Per-iteration seeds
|
||||
<span class="wp-seedlist__seedbtn-fill" />
|
||||
<span v-if="lockedCount" class="wp-seedlist__seedbtn-badge" data-test="seedlist-seeds-badge">{{ lockedCount }} locked</span>
|
||||
<span v-if="bypassedCount" class="wp-seedlist__seedbtn-badge" data-test="seedlist-seeds-bypass-badge">{{ bypassedCount }} bypassed</span>
|
||||
<svg class="wp-seedlist__seedbtn-chev" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M9 6l6 6-6 6" /></svg>
|
||||
</button>
|
||||
|
||||
<!-- Directly under the seeds button it belongs to: the chips are the
|
||||
inline view of what that modal lists, so they read as its expansion
|
||||
rather than as another unrelated section. -->
|
||||
<FrameChips
|
||||
label="seeds"
|
||||
test-id="seedlist-frame"
|
||||
v-model:collapsed="chipsCollapsed"
|
||||
:count="Math.max(1, count ?? 1)"
|
||||
:locked="[...lockSet]"
|
||||
:bypassed="bypassedFrames"
|
||||
:bypass-readonly-hint="BYPASS_READONLY_HINT"
|
||||
@toggle-lock="toggleFrameLock"
|
||||
/>
|
||||
|
||||
<div class="wp-seedlist__row" :title="OVERRIDE_SEED_TOOLTIP">
|
||||
<span class="wp-seedlist__row-label">Override base seed from loop</span>
|
||||
<button
|
||||
@@ -206,6 +275,7 @@ function toggleOverrideStrategy(): void {
|
||||
<SeedListModal v-if="seedsOpen" :node-name="'WP Seed List'" :base-seed="baseSeed"
|
||||
:count="count" :strategy="previewStrategy ?? modelValue.strategy" :seed-locks="modelValue.seed_locks ?? {}"
|
||||
:previous-seeds="previousSeeds"
|
||||
:bypass-frames="bypassedFrames.length ? bypassedFrames : undefined" :bypass-readonly="true"
|
||||
:override-hint="modelValue.override_seed ? 'Base seed comes from the wired loop while Override base seed from loop is on.' : ''"
|
||||
@update:seed-locks="onSeedLocks" @close="seedsOpen = false" />
|
||||
</div>
|
||||
|
||||
@@ -472,13 +472,24 @@ onBeforeUnmount(() => {
|
||||
background: var(--wp-brand-gradient);
|
||||
position: relative;
|
||||
}
|
||||
/* Scrim that knocks the brand gradient back so the title stays readable on
|
||||
* top of it. It was hardcoded to a near-black rgba, so under the light theme
|
||||
* the banner stayed dark while `--wp-text` flipped to a DARK ink — dark text
|
||||
* on a dark band. The scrim now follows the theme: near-black under dark,
|
||||
* near-white under light, each keeping the same 0.85 knock-back. */
|
||||
.wp-pg__head::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(35, 35, 35, 0.85);
|
||||
background: var(--wp-pg-head-scrim, rgba(35, 35, 35, 0.85));
|
||||
pointer-events: none;
|
||||
}
|
||||
.wp-theme-light .wp-pg__head {
|
||||
--wp-pg-head-scrim: rgba(248, 248, 250, 0.85);
|
||||
}
|
||||
.wp-theme-dark .wp-pg__head {
|
||||
--wp-pg-head-scrim: rgba(35, 35, 35, 0.85);
|
||||
}
|
||||
.wp-pg__head > * { position: relative; z-index: 1; }
|
||||
.wp-pg__head-inner { display: flex; gap: 10px; align-items: flex-start; }
|
||||
.wp-pg__head-icon {
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import FrameChips from "./FrameChips.vue";
|
||||
|
||||
/**
|
||||
* The grid shared by WP_ContextLoop and WP_SeedList. The two nodes disagree
|
||||
* about what a click means, so most of what matters here is that `selectable`
|
||||
* and `bypassInteractive` actually gate the right emissions.
|
||||
*/
|
||||
describe("FrameChips", () => {
|
||||
const at = (w: ReturnType<typeof mount>, n: number | "base") =>
|
||||
w.find(`[data-test="loop-frame-${n}"]`);
|
||||
|
||||
it("renders one chip per frame, and base only when asked", () => {
|
||||
const a = mount(FrameChips, { props: { count: 5 } });
|
||||
expect(a.findAll('[data-test^="loop-frame-"]')).toHaveLength(5);
|
||||
expect(a.find('[data-test="loop-frame-base"]').exists()).toBe(false);
|
||||
|
||||
const b = mount(FrameChips, { props: { count: 5, showBase: true } });
|
||||
expect(b.find('[data-test="loop-frame-base"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it("always renders at least one chip, even at count 0", () => {
|
||||
const w = mount(FrameChips, { props: { count: 0 } });
|
||||
expect(w.findAll('[data-test^="loop-frame-"]')).toHaveLength(1);
|
||||
});
|
||||
|
||||
describe("selectable (Context Loop)", () => {
|
||||
const sel = (extra = {}) =>
|
||||
mount(FrameChips, { props: { count: 4, selectable: true, showBase: true, bypassInteractive: true, ...extra } });
|
||||
|
||||
it("plain click selects, shift locks, alt bypasses", async () => {
|
||||
const w = sel();
|
||||
await at(w, 2).trigger("click");
|
||||
expect(w.emitted("select")?.[0]).toEqual([1]);
|
||||
await at(w, 3).trigger("click", { shiftKey: true });
|
||||
expect(w.emitted("toggleLock")?.[0]).toEqual([2]);
|
||||
await at(w, 4).trigger("click", { altKey: true });
|
||||
expect(w.emitted("toggleBypass")?.[0]).toEqual([3]);
|
||||
});
|
||||
|
||||
it("a modifier click never also selects", async () => {
|
||||
const w = sel();
|
||||
await at(w, 2).trigger("click", { shiftKey: true });
|
||||
await at(w, 3).trigger("click", { altKey: true });
|
||||
expect(w.emitted("select")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("base selects null and takes no modifiers", async () => {
|
||||
const w = sel();
|
||||
await at(w, "base").trigger("click");
|
||||
expect(w.emitted("select")?.[0]).toEqual([null]);
|
||||
expect(w.emitted("toggleLock")).toBeUndefined();
|
||||
expect(w.emitted("toggleBypass")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("non-selectable (Seed List)", () => {
|
||||
const plain = (extra = {}) => mount(FrameChips, { props: { count: 4, ...extra } });
|
||||
|
||||
// No edit cursor here, so demanding a modifier for the only available
|
||||
// action would be ceremony.
|
||||
it("a plain click IS the lock toggle", async () => {
|
||||
const w = plain();
|
||||
await at(w, 2).trigger("click");
|
||||
expect(w.emitted("toggleLock")?.[0]).toEqual([1]);
|
||||
expect(w.emitted("select")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("alt does nothing when bypass belongs to another node", async () => {
|
||||
const w = plain({ bypassed: [1] });
|
||||
await at(w, 2).trigger("click", { altKey: true });
|
||||
expect(w.emitted("toggleBypass")).toBeUndefined();
|
||||
expect(w.emitted("toggleLock")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("still SHOWS bypass it cannot change", () => {
|
||||
const w = plain({ bypassed: [1] });
|
||||
expect(at(w, 2).classes()).toContain("wp-fchips__chip--bypassed");
|
||||
});
|
||||
|
||||
it("explains who owns the bypass instead of looking broken", () => {
|
||||
const w = plain({ bypassed: [1], bypassReadonlyHint: "Owned by the loop." });
|
||||
expect(at(w, 2).attributes("title")).toContain("Owned by the loop.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("collapse", () => {
|
||||
it("starts open and hides the grid when toggled", async () => {
|
||||
const w = mount(FrameChips, { props: { count: 4 } });
|
||||
expect(w.find('[data-test="loop-frames-grid"]').exists()).toBe(true);
|
||||
await w.find('[data-test="loop-frames-toggle"]').trigger("click");
|
||||
expect(w.find('[data-test="loop-frames-grid"]').exists()).toBe(false);
|
||||
await w.find('[data-test="loop-frames-toggle"]').trigger("click");
|
||||
expect(w.find('[data-test="loop-frames-grid"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
// Hiding the grid must not also hide the fact that frames are set — a
|
||||
// forgotten lock is a confusing run.
|
||||
it("keeps reporting locked/bypassed counts while collapsed", async () => {
|
||||
const w = mount(FrameChips, { props: { count: 6, locked: [0, 2], bypassed: [4] } });
|
||||
await w.find('[data-test="loop-frames-toggle"]').trigger("click");
|
||||
const summary = w.find('[data-test="loop-frames-summary"]');
|
||||
expect(summary.text()).toMatch(/2 locked/);
|
||||
expect(summary.text()).toMatch(/1 bypassed/);
|
||||
});
|
||||
|
||||
it("is controllable by the host, which persists it to node.properties", async () => {
|
||||
const w = mount(FrameChips, { props: { count: 4, collapsed: true } });
|
||||
// Starts collapsed because the host said so — a saved workflow reopens
|
||||
// the way it was left.
|
||||
expect(w.find('[data-test="loop-frames-grid"]').exists()).toBe(false);
|
||||
await w.find('[data-test="loop-frames-toggle"]').trigger("click");
|
||||
expect(w.emitted("update:collapsed")?.[0]).toEqual([false]);
|
||||
});
|
||||
|
||||
it("shows no summary when nothing is set", () => {
|
||||
const w = mount(FrameChips, { props: { count: 6 } });
|
||||
expect(w.find('[data-test="loop-frames-summary"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
// Out-of-range locks survive a count change and re-apply if it grows back,
|
||||
// but they have no chip here — claiming them would name a frame that is
|
||||
// not on screen. The modal owns that story.
|
||||
it("counts only in-range locks", () => {
|
||||
const w = mount(FrameChips, { props: { count: 3, locked: [0, 9] } });
|
||||
expect(w.find('[data-test="loop-frames-summary"]').text()).toMatch(/1 locked/);
|
||||
});
|
||||
});
|
||||
|
||||
it("namespaces every test id so two widgets can coexist", () => {
|
||||
const w = mount(FrameChips, { props: { count: 2, testId: "seedlist-frame" } });
|
||||
expect(w.find('[data-test="seedlist-frame-1"]').exists()).toBe(true);
|
||||
expect(w.find('[data-test="seedlist-frames-grid"]').exists()).toBe(true);
|
||||
expect(w.find('[data-test="loop-frame-1"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("prints the combos that apply to this mode", () => {
|
||||
const loop = mount(FrameChips, { props: { count: 2, selectable: true } });
|
||||
expect(loop.find('[data-test="loop-frames-hint"]').text()).toMatch(/shift/i);
|
||||
const list = mount(FrameChips, { props: { count: 2 } });
|
||||
expect(list.find('[data-test="loop-frames-hint"]').text()).toMatch(/click a frame to lock/i);
|
||||
expect(list.find('[data-test="loop-frames-hint"]').text()).not.toMatch(/shift/i);
|
||||
});
|
||||
|
||||
it("bounds its height and scrolls rather than growing the node", () => {
|
||||
const w = mount(FrameChips, { props: { count: 200 } });
|
||||
const grid = w.find('[data-test="loop-frames-grid"]');
|
||||
expect(w.findAll('[data-test^="loop-frame-"]')).toHaveLength(200);
|
||||
// jsdom does not lay out, so assert the contract the CSS declares.
|
||||
expect(grid.classes()).toContain("wp-fchips__grid");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,353 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* FrameChips — the per-frame chip grid shared by WP_ContextLoop and
|
||||
* WP_SeedList.
|
||||
*
|
||||
* One grid, two jobs, because the two nodes disagree about what a click
|
||||
* MEANS. The Loop has an edit cursor, so a plain click selects the frame to
|
||||
* edit and the state toggles need modifiers. The Seed List has no cursor and
|
||||
* nothing else to do with a chip, so a plain click toggles the lock directly
|
||||
* — making people hold Shift for the only available action would be
|
||||
* ceremony. `selectable` picks between the two.
|
||||
*
|
||||
* Bypass is likewise asymmetric. The Loop OWNS its bypass set, so Alt-click
|
||||
* toggles it. The Seed List only MIRRORS the bypass of the loop wired into
|
||||
* its `loop_config`, so its chips show the state and refuse to change it —
|
||||
* editing it here would have to write to a different node.
|
||||
*
|
||||
* Both states already had a home in the per-iteration seeds modal. Keeping
|
||||
* that as the only way to flip one frame meant a round trip through a dialog
|
||||
* that covers the node you are reading; the modal stays for what it is
|
||||
* actually good at (lock all, paste a series, out-of-range locks).
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/** Number of frames. Chips are 0-based internally, labelled from 1. */
|
||||
count: number;
|
||||
/** 0-based locked frame indices. */
|
||||
locked?: number[];
|
||||
/** 0-based bypassed frame indices. */
|
||||
bypassed?: number[];
|
||||
/** Selected frame for the edit cursor; `null` is the `base` chip.
|
||||
* Ignored unless `selectable`. */
|
||||
current?: number | null;
|
||||
/** Plain click selects (Loop) vs toggles the lock (Seed List). */
|
||||
selectable?: boolean;
|
||||
/** Render the `base` chip. Only the Loop has values every frame inherits. */
|
||||
showBase?: boolean;
|
||||
/** Alt-click may toggle bypass. False where bypass belongs to another node. */
|
||||
bypassInteractive?: boolean;
|
||||
/** Section heading. */
|
||||
label?: string;
|
||||
/** Why bypass cannot be edited here, shown on bypassed chips when
|
||||
* `bypassInteractive` is false. */
|
||||
bypassReadonlyHint?: string;
|
||||
/** `data-test` namespace, so the two host widgets address their own
|
||||
* chips: `<testId>-base`, `<testId>-1`, `<testId>-2`, … */
|
||||
testId?: string;
|
||||
}>(),
|
||||
{
|
||||
locked: () => [],
|
||||
bypassed: () => [],
|
||||
current: null,
|
||||
selectable: false,
|
||||
showBase: false,
|
||||
bypassInteractive: false,
|
||||
label: "frames",
|
||||
bypassReadonlyHint: "",
|
||||
testId: "loop-frame",
|
||||
},
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
select: [index: number | null];
|
||||
toggleLock: [index: number];
|
||||
toggleBypass: [index: number];
|
||||
}>();
|
||||
|
||||
/**
|
||||
* Collapse state, persisted by the host.
|
||||
*
|
||||
* `defineModel` so this works both ways: bound, the widget glue owns the value
|
||||
* and writes it to `node.properties` (the workflow-JSON serialization root, and
|
||||
* the only place per-node UI state survives a save); unbound, it falls back to
|
||||
* a local ref, which is what keeps the component usable standalone.
|
||||
*
|
||||
* The risk a persisted collapse carries is someone forgetting a frame is
|
||||
* locked behind a grid that stays hidden across sessions. That is why the
|
||||
* header keeps reporting counts while collapsed — see `summary`.
|
||||
*/
|
||||
const collapsed = defineModel<boolean>("collapsed", { default: false });
|
||||
|
||||
const frames = computed(() =>
|
||||
Array.from({ length: Math.max(1, props.count) }, (_, i) => i),
|
||||
);
|
||||
const lockedSet = computed(() => new Set(props.locked));
|
||||
const bypassedSet = computed(() => new Set(props.bypassed));
|
||||
|
||||
/** In-range counts only — an out-of-range lock is the modal's business, and
|
||||
* claiming it here would name a frame that has no chip. */
|
||||
const lockedInRange = computed(() => frames.value.filter((i) => lockedSet.value.has(i)).length);
|
||||
const bypassedInRange = computed(() => frames.value.filter((i) => bypassedSet.value.has(i)).length);
|
||||
|
||||
/** Collapsed summary — the whole point of collapsing is to hide the grid, so
|
||||
* the header has to keep saying whether anything is set. */
|
||||
const summary = computed(() => {
|
||||
const bits: string[] = [];
|
||||
if (lockedInRange.value) bits.push(`${lockedInRange.value} locked`);
|
||||
if (bypassedInRange.value) bits.push(`${bypassedInRange.value} bypassed`);
|
||||
return bits.join(" · ");
|
||||
});
|
||||
|
||||
/** Option on a Mac keyboard, Alt everywhere else. `altKey` covers both; only
|
||||
* the printed label differs. */
|
||||
const ALT_LABEL =
|
||||
typeof navigator !== "undefined" && /Mac|iP(hone|ad|od)/i.test(navigator.userAgent)
|
||||
? "⌥"
|
||||
: "Alt";
|
||||
|
||||
function onChipClick(i: number, ev: MouseEvent): void {
|
||||
if (ev.altKey) {
|
||||
if (props.bypassInteractive) emit("toggleBypass", i);
|
||||
return;
|
||||
}
|
||||
if (!props.selectable) {
|
||||
// No cursor to move: the plain click IS the lock toggle.
|
||||
emit("toggleLock", i);
|
||||
return;
|
||||
}
|
||||
if (ev.shiftKey) { emit("toggleLock", i); return; }
|
||||
emit("select", i);
|
||||
}
|
||||
|
||||
function chipTitle(i: number): string {
|
||||
const state = [
|
||||
lockedSet.value.has(i) ? "seed locked" : null,
|
||||
bypassedSet.value.has(i) ? "bypassed" : null,
|
||||
].filter(Boolean).join(", ");
|
||||
const lines = [`Frame ${i + 1}${state ? ` — ${state}` : ""}`];
|
||||
const lockVerb = lockedSet.value.has(i) ? "Unlock" : "Lock";
|
||||
if (props.selectable) {
|
||||
lines.push("Click to edit this frame", `Shift-click to ${lockVerb.toLowerCase()} its seed`);
|
||||
} else {
|
||||
lines.push(`Click to ${lockVerb.toLowerCase()} its seed`);
|
||||
}
|
||||
if (props.bypassInteractive) {
|
||||
lines.push(`${ALT_LABEL}-click to ${bypassedSet.value.has(i) ? "re-enable" : "bypass"} it`);
|
||||
} else if (bypassedSet.value.has(i) && props.bypassReadonlyHint) {
|
||||
lines.push(props.bypassReadonlyHint);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* `data-test` root for the chrome (toggle / summary / grid / hint).
|
||||
*
|
||||
* Pluralised so it does NOT collide with the chips' own `${testId}-` prefix —
|
||||
* suites count chips with `[data-test^="loop-frame-"]`, and a sibling named
|
||||
* `loop-frame-hint` silently inflates that count.
|
||||
*/
|
||||
const uiId = computed(() => `${props.testId}s`);
|
||||
|
||||
/** The combos, printed. An undiscoverable shortcut is the same as no
|
||||
* shortcut, and this row is where the reader is already looking. */
|
||||
const hint = computed(() => {
|
||||
if (!props.selectable) return "Click a frame to lock its seed";
|
||||
return `Shift-click locks a seed · ${ALT_LABEL}-click bypasses`;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="wp-fchips">
|
||||
<button
|
||||
type="button"
|
||||
class="wp-fchips__head"
|
||||
:aria-expanded="!collapsed"
|
||||
:data-test="`${uiId}-toggle`"
|
||||
:title="collapsed ? 'Show frames' : 'Hide frames'"
|
||||
@click="collapsed = !collapsed"
|
||||
>
|
||||
<svg
|
||||
class="wp-fchips__caret"
|
||||
:class="{ 'wp-fchips__caret--collapsed': collapsed }"
|
||||
width="9" height="9" viewBox="0 0 24 24"
|
||||
fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"
|
||||
aria-hidden="true"
|
||||
><path d="M6 9l6 6 6-6" /></svg>
|
||||
<span class="wp-fchips__label">{{ label }}</span>
|
||||
<span
|
||||
v-if="summary"
|
||||
class="wp-fchips__summary"
|
||||
:data-test="`${uiId}-summary`"
|
||||
>{{ summary }}</span>
|
||||
</button>
|
||||
|
||||
<template v-if="!collapsed">
|
||||
<!-- `overflow-y: auto` + a bounded height is what makes a 100-frame loop
|
||||
survivable. The wheel shield installed on every widget host lets the
|
||||
wheel scroll this instead of zooming the canvas under Nodes 2.0. -->
|
||||
<div
|
||||
class="wp-fchips__grid"
|
||||
:role="selectable ? 'radiogroup' : 'group'"
|
||||
:aria-label="label"
|
||||
:data-test="`${uiId}-grid`"
|
||||
>
|
||||
<button
|
||||
v-if="showBase"
|
||||
type="button"
|
||||
class="wp-fchips__chip"
|
||||
:class="{ 'wp-fchips__chip--active': current === null }"
|
||||
:data-test="`${testId}-base`"
|
||||
role="radio"
|
||||
:aria-checked="current === null"
|
||||
title="Edit the values every frame inherits"
|
||||
@click="emit('select', null)"
|
||||
>base</button>
|
||||
|
||||
<button
|
||||
v-for="i in frames"
|
||||
:key="i"
|
||||
type="button"
|
||||
class="wp-fchips__chip"
|
||||
:class="{
|
||||
'wp-fchips__chip--active': selectable && current === i,
|
||||
'wp-fchips__chip--locked': lockedSet.has(i),
|
||||
'wp-fchips__chip--bypassed': bypassedSet.has(i),
|
||||
}"
|
||||
:data-test="`${testId}-${i + 1}`"
|
||||
:role="selectable ? 'radio' : undefined"
|
||||
:aria-checked="selectable ? current === i : undefined"
|
||||
:aria-pressed="selectable ? undefined : lockedSet.has(i)"
|
||||
:data-locked="lockedSet.has(i) ? 'true' : undefined"
|
||||
:data-bypassed="bypassedSet.has(i) ? 'true' : undefined"
|
||||
:title="chipTitle(i)"
|
||||
@click="onChipClick(i, $event)"
|
||||
>#{{ i + 1 }}</button>
|
||||
</div>
|
||||
<p class="wp-fchips__hint" :data-test="`${uiId}-hint`">{{ hint }}</p>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* No `@import "./theme.css"` here on purpose.
|
||||
*
|
||||
* theme.css declares its tokens on `:root`, so one copy anywhere in the
|
||||
* document serves everything — and this component only ever renders inside
|
||||
* ContextLoopWidget or SeedListWidget, both of which already import it.
|
||||
* Importing it again inlines the whole 521-line sheet into this shared chunk:
|
||||
* a third copy of the same tokens, and 10.7 KB gzipped for a grid of buttons.
|
||||
*
|
||||
* Every declaration below carries a literal fallback anyway, so the component
|
||||
* still renders standalone if it is ever used somewhere unthemed. */
|
||||
|
||||
.wp-fchips { display: flex; flex-direction: column; gap: 4px; }
|
||||
|
||||
.wp-fchips__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
background: none;
|
||||
border: 0;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
color: var(--wp-text-dim, var(--wp-text-muted, #8a8d99));
|
||||
}
|
||||
.wp-fchips__head:hover { color: var(--wp-text-muted, #aeb1bb); }
|
||||
.wp-fchips__caret { flex: none; transition: transform var(--wp-motion-hover, 120ms) ease; }
|
||||
.wp-fchips__caret--collapsed { transform: rotate(-90deg); }
|
||||
.wp-fchips__label {
|
||||
font: 600 9px var(--wp-font-sans, sans-serif);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
}
|
||||
/* Kept visible while collapsed — hiding the grid must not also hide the fact
|
||||
* that frames are locked or bypassed. */
|
||||
.wp-fchips__summary {
|
||||
margin-left: auto;
|
||||
font: 600 8px var(--wp-font-sans, sans-serif);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
padding: 2px 6px;
|
||||
border-radius: 3px;
|
||||
color: var(--wp-accent-text, var(--wp-text, #e6e7ea));
|
||||
background: rgba(99, 102, 241, 0.14);
|
||||
border: 1px solid color-mix(in srgb, var(--wp-accent, #c4b5fd) 40%, transparent);
|
||||
}
|
||||
|
||||
/* auto-fill keeps a uniform cell width so 15+ chips WRAP instead of
|
||||
* overflowing the node; the bounded height then caps how much of the node
|
||||
* a long series can claim. ~4 rows before it scrolls. */
|
||||
.wp-fchips__grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(38px, 1fr));
|
||||
gap: 4px;
|
||||
max-height: var(--wp-fchips-max-h, 112px);
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--wp-scrollbar-thumb, rgba(255, 255, 255, 0.28)) transparent;
|
||||
/* Room for the scrollbar so the last column is never sat on. */
|
||||
padding-right: 2px;
|
||||
}
|
||||
.wp-fchips__grid::-webkit-scrollbar { width: 8px; }
|
||||
.wp-fchips__grid::-webkit-scrollbar-track { background: transparent; }
|
||||
.wp-fchips__grid::-webkit-scrollbar-thumb {
|
||||
background: var(--wp-scrollbar-thumb, rgba(255, 255, 255, 0.28));
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.wp-fchips__chip {
|
||||
/* Not `flex: 1` — the grid owns the track sizing, and a flex hint here
|
||||
* fights it. */
|
||||
position: relative;
|
||||
padding: 4px 6px;
|
||||
text-align: center;
|
||||
background: var(--wp-bg-deep, var(--wp-bg, #0e1015));
|
||||
border: 1px solid var(--wp-border, #353841);
|
||||
border-radius: 3px;
|
||||
color: var(--wp-text-muted, #aeb1bb);
|
||||
font: 600 10px var(--wp-font-sans, sans-serif);
|
||||
cursor: pointer;
|
||||
}
|
||||
.wp-fchips__chip:hover { color: var(--wp-text, #e6e7ea); border-color: var(--wp-border-strong, #4a4d55); }
|
||||
.wp-fchips__chip--active {
|
||||
background: color-mix(in srgb, var(--wp-accent, #c4b5fd) 18%, transparent);
|
||||
border-color: var(--wp-accent, #c4b5fd);
|
||||
color: var(--wp-accent, #c4b5fd);
|
||||
}
|
||||
/* Bypassed — interrupted (dashed) border + dimmed, so it reads at a glance.
|
||||
* Composes with --active (dashed overrides the solid). */
|
||||
.wp-fchips__chip--bypassed {
|
||||
border-style: dashed;
|
||||
border-color: var(--wp-border-strong, #4a4d55);
|
||||
opacity: 0.5;
|
||||
}
|
||||
.wp-fchips__chip--bypassed:hover { opacity: 0.8; }
|
||||
/* Locked — a corner dot. At ~20px tall a padlock glyph would be mud; the dot
|
||||
* only has to say "something is pinned here" and the tooltip carries the
|
||||
* value. Every chip is position:relative, so toggling never reflows the grid. */
|
||||
.wp-fchips__chip--locked::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 2px;
|
||||
width: 4px;
|
||||
height: 4px;
|
||||
border-radius: 50%;
|
||||
background: var(--wp-accent, #c4b5fd);
|
||||
}
|
||||
/* A bypassed frame keeps its lock, and the dot must survive the dim — else
|
||||
* unlocking it later looks like it did nothing. */
|
||||
.wp-fchips__chip--bypassed.wp-fchips__chip--locked::after { opacity: 0.9; }
|
||||
|
||||
.wp-fchips__hint {
|
||||
margin: 1px 0 0;
|
||||
font: 400 9px var(--wp-font-sans, sans-serif);
|
||||
color: var(--wp-text-dim, var(--wp-text-muted, #8a8d99));
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<Transition name="wp-modal" appear>
|
||||
<div v-if="visible" class="wp-modal-overlay" @click="$emit('close')">
|
||||
<div v-if="visible" ref="overlayEl" class="wp-modal-overlay" @click="$emit('close')">
|
||||
<div class="wp-modal-wrapper" role="dialog" aria-modal="true" @click.stop>
|
||||
<slot></slot>
|
||||
</div>
|
||||
@@ -11,16 +11,40 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { watch, onBeforeUnmount } from "vue";
|
||||
import { ref, watch, onBeforeUnmount } from "vue";
|
||||
import { useModalKeyShield } from "./useModalKeyShield";
|
||||
|
||||
const props = defineProps<{ visible: boolean }>();
|
||||
const emit = defineEmits<{ (e: "close"): void }>();
|
||||
const emit = defineEmits<{
|
||||
(e: "close"): void;
|
||||
/** Every keydown inside the modal. Consumers MUST use this instead of a
|
||||
* window listener: the shield stops inside-modal keys at the overlay, so a
|
||||
* window listener would never see them. */
|
||||
(e: "keydown", ev: KeyboardEvent): void;
|
||||
}>();
|
||||
|
||||
const overlayEl = ref<HTMLElement | null>(null);
|
||||
|
||||
function closeOnEscape(event: KeyboardEvent): void {
|
||||
if (!props.visible || event.key !== "Escape") return;
|
||||
event.preventDefault();
|
||||
emit("close");
|
||||
}
|
||||
|
||||
// Keys pressed INSIDE the modal are handled here and stop at the overlay, so
|
||||
// they never reach ComfyUI's global shortcuts (see useModalKeyShield).
|
||||
useModalKeyShield(overlayEl, {
|
||||
onKey: (ev) => {
|
||||
emit("keydown", ev);
|
||||
closeOnEscape(ev);
|
||||
},
|
||||
});
|
||||
|
||||
// The window listener still covers the case where focus is OUTSIDE the modal
|
||||
// — clicking the canvas leaves the modal open but unfocused, and Escape should
|
||||
// still close it. Events from inside never get here; the shield stops them.
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (props.visible && event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
emit("close");
|
||||
}
|
||||
closeOnEscape(event);
|
||||
}
|
||||
|
||||
watch(
|
||||
|
||||
@@ -21,8 +21,19 @@ const props = defineProps<{
|
||||
* short → that frame's button greys out. Distinct from the computed
|
||||
* `derived` series, which is the UPCOMING seeds from the current base. */
|
||||
previousSeeds?: number[] | null;
|
||||
/** 0-based bypassed frame indices. When PASSED, bypassed rows dim + strike.
|
||||
* Absent → no bypass display at all. */
|
||||
bypassFrames?: number[];
|
||||
/** Read-only bypass (Seed List mirroring a loop): show bypassed rows dimmed
|
||||
* but WITHOUT an interactive toggle — bypass is owned by the loop node.
|
||||
* Default false (Context Loop = interactive toggles). */
|
||||
bypassReadonly?: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
"update:seedLocks": [next: Record<string, number>];
|
||||
"update:bypassFrames": [next: number[]];
|
||||
close: [];
|
||||
}>();
|
||||
const emit = defineEmits<{ "update:seedLocks": [next: Record<string, number>]; close: [] }>();
|
||||
|
||||
const derived = computed(() => deriveLoopSeeds(props.baseSeed, Math.max(1, props.count), props.strategy));
|
||||
const lockedCount = computed(() => Object.keys(props.seedLocks).length);
|
||||
@@ -41,6 +52,41 @@ const inactiveLocks = computed(() => {
|
||||
.sort((a, b) => a - b);
|
||||
});
|
||||
|
||||
const bypassEnabled = computed(() => props.bypassFrames !== undefined);
|
||||
/** Interactive toggle only when bypass is enabled AND not read-only. In
|
||||
* read-only mode rows still show the bypassed (dim + strike) state — that's
|
||||
* the `:bypassed` prop, independent of `:bypassable`. */
|
||||
const bypassInteractive = computed(() => bypassEnabled.value && !props.bypassReadonly);
|
||||
const bypassSet = computed(() => new Set(props.bypassFrames ?? []));
|
||||
const bypassCount = computed(() => (props.bypassFrames ?? []).length);
|
||||
/** Number of in-range frames NOT bypassed. */
|
||||
const activeFrameCount = computed(() => {
|
||||
let n = 0;
|
||||
for (let i = 0; i < derived.value.length; i++) if (!bypassSet.value.has(i)) n++;
|
||||
return n;
|
||||
});
|
||||
/** Bypass toggle is disabled for an ACTIVE frame when it's the last one left. */
|
||||
function bypassDisabledFor(i: number): boolean {
|
||||
return !bypassSet.value.has(i) && activeFrameCount.value <= 1;
|
||||
}
|
||||
/** Bypassed indices beyond the current count — dimmed, re-apply if count grows. */
|
||||
const inactiveBypass = computed(() =>
|
||||
[...bypassSet.value].filter((i) => i >= derived.value.length).sort((a, b) => a - b),
|
||||
);
|
||||
/** Real derived seed for any index (out-of-range inactive rows compute it on
|
||||
* the fly since `derived` only spans the active count). PRECONDITION: `i >= 1`
|
||||
* — only ever called for inactive rows where `i >= derived.length >= 1`. At
|
||||
* `i === 0` deriveLoopSeeds hits its `count <= 1` branch and returns the base
|
||||
* seed, NOT the series' derived[0], so do not reuse this for in-range index 0. */
|
||||
function seedAt(i: number): number {
|
||||
return deriveLoopSeeds(props.baseSeed, i + 1, props.strategy)[i] ?? 0;
|
||||
}
|
||||
function onBypass(p: { index: number; bypassed: boolean }): void {
|
||||
const next = new Set(bypassSet.value);
|
||||
if (p.bypassed) next.add(p.index);
|
||||
else next.delete(p.index);
|
||||
emit("update:bypassFrames", [...next].sort((a, b) => a - b));
|
||||
}
|
||||
function onRow(p: { index: number; seed: number | null }): void {
|
||||
const next = { ...props.seedLocks };
|
||||
if (p.seed == null) delete next[String(p.index)];
|
||||
@@ -115,6 +161,7 @@ onBeforeUnmount(() => {
|
||||
<span class="sm__count">{{ Math.max(1, count) }} iterations</span>
|
||||
<span class="sm__strat">{{ strategy }}</span>
|
||||
<span v-if="lockedCount" class="sm__lockcount" data-test="mx-seed-lockcount">{{ lockedCount }} locked</span>
|
||||
<span v-if="bypassEnabled && bypassCount" class="sm__lockcount" data-test="mx-bypass-count">{{ bypassCount }} bypassed</span>
|
||||
<span class="sm__bar-spacer" />
|
||||
<button class="ghost" data-test="mx-seed-lockall" @click="lockAll">Lock all</button>
|
||||
<button class="ghost" data-test="mx-seed-unlockall" @click="unlockAll">Unlock all</button>
|
||||
@@ -133,7 +180,21 @@ onBeforeUnmount(() => {
|
||||
<div class="sm__list">
|
||||
<SeedLockRow v-for="(s, i) in derived" :key="i" :index="i" :derived="s"
|
||||
:locked="Object.prototype.hasOwnProperty.call(seedLocks, String(i))"
|
||||
:seed="seedLocks[String(i)] ?? null" :previous="previousSeeds?.[i] ?? null" @update="onRow" />
|
||||
:seed="seedLocks[String(i)] ?? null" :previous="previousSeeds?.[i] ?? null"
|
||||
:bypassable="bypassInteractive" :bypassed="bypassSet.has(i)"
|
||||
:bypass-disabled="bypassDisabledFor(i)"
|
||||
@update="onRow" @bypass="onBypass" />
|
||||
<template v-if="inactiveBypass.length">
|
||||
<div class="sm__inactive-label" data-test="mx-bypass-inactive">
|
||||
Bypassed · won't apply at count {{ derived.length }}
|
||||
</div>
|
||||
<SeedLockRow v-for="i in inactiveBypass" :key="`inbypass-${i}`" :index="i"
|
||||
:derived="seedAt(i)"
|
||||
:locked="Object.prototype.hasOwnProperty.call(seedLocks, String(i))"
|
||||
:seed="seedLocks[String(i)] ?? null" :previous="previousSeeds?.[i] ?? null"
|
||||
:inactive="true" :bypassable="bypassInteractive" :bypassed="true"
|
||||
@update="onRow" @bypass="onBypass" />
|
||||
</template>
|
||||
<template v-if="inactiveLocks.length">
|
||||
<div class="sm__inactive-label" data-test="mx-seed-inactive">
|
||||
Inactive · won't apply at count {{ derived.length }}
|
||||
@@ -163,7 +224,11 @@ onBeforeUnmount(() => {
|
||||
<style scoped>
|
||||
@import "./theme.css";
|
||||
.sm-overlay { position: fixed; inset: 0; z-index: 9999; display: flex; align-items: center; justify-content: center; padding: 20px; background: rgba(0,0,0,.62); font-family: var(--wp-font-sans, sans-serif); }
|
||||
.sm { width: 486px; max-width: 100%; max-height: 86vh; display: flex; flex-direction: column; background: var(--wp-bg2); border: 1px solid var(--wp-border); border-radius: 6px; overflow: hidden; color: var(--wp-text); font-size: 12px; box-shadow: 0 18px 50px rgba(0,0,0,.55); }
|
||||
/* 560px, up from 486px: the toolbar (iterations · strategy · N locked · N
|
||||
* bypassed · Lock all · Unlock all · Copy) and each row's three toggles were
|
||||
* being squeezed into near-square boxes to fit. Widening is the cheaper fix
|
||||
* than re-organising the toolbar. */
|
||||
.sm { width: 560px; max-width: 100%; max-height: 86vh; display: flex; flex-direction: column; background: var(--wp-bg2); border: 1px solid var(--wp-border); border-radius: 6px; overflow: hidden; color: var(--wp-text); font-size: 12px; box-shadow: 0 18px 50px rgba(0,0,0,.55); }
|
||||
.sm__head { display: flex; align-items: center; gap: 10px; padding: 12px 14px; flex-shrink: 0; border-bottom: 1px solid var(--wp-border); background: linear-gradient(180deg, color-mix(in srgb, var(--wp-accent) 18%, var(--wp-bg2)) 0%, var(--wp-bg2) 100%); }
|
||||
.sm__head-icon { color: var(--wp-accent); width: 24px; display: flex; justify-content: center; }
|
||||
.sm__title-block { flex: 1; min-width: 0; }
|
||||
|
||||
@@ -15,8 +15,17 @@ const props = defineProps<{
|
||||
* frame — the "lock previous" button greys out. Distinct from `derived`,
|
||||
* which is the UPCOMING seed computed from the current base. */
|
||||
previous?: number | null;
|
||||
/** When true, render a per-frame bypass toggle (Context Loop only). */
|
||||
bypassable?: boolean;
|
||||
/** Whether this frame is currently bypassed. */
|
||||
bypassed?: boolean;
|
||||
/** Disable the bypass toggle (e.g. it's the last active frame). */
|
||||
bypassDisabled?: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
update: [payload: { index: number; seed: number | null }];
|
||||
bypass: [payload: { index: number; bypassed: boolean }];
|
||||
}>();
|
||||
const emit = defineEmits<{ update: [payload: { index: number; seed: number | null }] }>();
|
||||
|
||||
const SEED_MAX = (2 ** 50) - 1; // MAX_SAFE_SEED (matches engine)
|
||||
function randomSeed(): number {
|
||||
@@ -40,8 +49,16 @@ function bump(d: 1 | -1) {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="srow" :class="{ 'srow--locked': locked, 'srow--inactive': inactive }">
|
||||
<div class="srow" :class="{ 'srow--locked': locked, 'srow--inactive': inactive, 'srow--bypassed': bypassed }">
|
||||
<span class="srow__idx" data-test="seedrow-idx">#{{ index + 1 }}</span>
|
||||
<button v-if="bypassable" type="button" class="toggle toggle--bypass"
|
||||
:class="{ 'toggle--on': bypassed }" :disabled="bypassDisabled || undefined"
|
||||
data-test="seedrow-bypass" role="switch" :aria-checked="bypassed"
|
||||
:title="bypassed ? 'Frame bypassed — click to re-enable' : 'Bypass this frame (skip its generation)'"
|
||||
@click="emit('bypass', { index, bypassed: !bypassed })">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9" /><path d="M5.6 5.6l12.8 12.8" stroke-linecap="round" /></svg>
|
||||
{{ bypassed ? "Bypassed" : "Bypass" }}
|
||||
</button>
|
||||
<button type="button" class="toggle" :class="{ 'toggle--on': locked }"
|
||||
data-test="seedrow-lock" role="switch" :aria-checked="locked" @click="onLock">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
@@ -90,6 +107,23 @@ function bump(d: 1 | -1) {
|
||||
/* out-of-range lock: dimmed ("deemed down") but still interactive — hover lifts it. */
|
||||
.srow--inactive { opacity: .5; }
|
||||
.srow--inactive:hover { opacity: .85; }
|
||||
/* Bypassed row — purple-dimmed wash + a dashed left accent bar so it reads
|
||||
* clearly even when the struck-through seed alone is too faint. The dashed
|
||||
* bar echoes the loop node's dashed bypass chips. */
|
||||
.srow--bypassed {
|
||||
background:
|
||||
repeating-linear-gradient(
|
||||
to bottom,
|
||||
var(--wp-accent, #c4b5fd) 0 4px,
|
||||
transparent 4px 8px
|
||||
) left / 3px 100% no-repeat,
|
||||
color-mix(in srgb, var(--wp-accent, #c4b5fd) 11%, transparent);
|
||||
border-radius: 5px;
|
||||
}
|
||||
.srow--bypassed .derived__val { text-decoration: line-through; opacity: .65; }
|
||||
.srow--bypassed .srow__idx { color: var(--wp-accent-text, #c4b5fd); opacity: .75; }
|
||||
.toggle--bypass { color: var(--wp-text-dim, var(--wp-text3)); }
|
||||
.toggle--bypass.toggle--on { border-color: var(--wp-accent); color: var(--wp-accent-text, var(--wp-text)); background: rgba(99,102,241,.10); }
|
||||
.srow__idx { flex-shrink: 0; width: 30px; text-align: right; font: 600 11px var(--wp-font-mono, monospace); color: var(--wp-text-dim, #7a7d88); }
|
||||
.srow--locked .srow__idx { color: var(--wp-accent-text, #c4b5fd); }
|
||||
.srow__fill { flex: 1; }
|
||||
@@ -103,11 +137,20 @@ function bump(d: 1 | -1) {
|
||||
.toggle--prev { color: var(--wp-text-dim, var(--wp-text3)); }
|
||||
.toggle:disabled { opacity: .4; cursor: not-allowed; }
|
||||
.toggle:disabled:hover { border-color: var(--wp-border); color: var(--wp-text-dim, var(--wp-text3)); }
|
||||
.derived { display: inline-flex; align-items: center; gap: 8px; }
|
||||
.derived__val { font: 11px var(--wp-font-mono, monospace); color: var(--wp-text4, #888); }
|
||||
/* Same shrink rule as the locked column, so a 15-digit derived seed clips
|
||||
* instead of shoving the DERIVED tag past the panel edge. */
|
||||
.derived { display: inline-flex; align-items: center; gap: 8px; min-width: 0; }
|
||||
.derived__val { font: 11px var(--wp-font-mono, monospace); color: var(--wp-text4, #888); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.derived__tag { flex-shrink: 0; }
|
||||
.derived__tag { font: 600 8px var(--wp-font-sans); text-transform: uppercase; letter-spacing: .07em; color: var(--wp-text-dim, var(--wp-text3)); border: 1px solid var(--wp-border); border-radius: 3px; padding: 1px 5px; }
|
||||
.seed-controls { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.seed-input-wrap { display: inline-flex; align-items: stretch; background: var(--wp-bg-deep, var(--wp-bg)); border: 1px solid var(--wp-border); border-radius: 3px; height: 24px; width: 178px; overflow: hidden; }
|
||||
/* The value column has to SHRINK. A locked row carries three fixed-width
|
||||
* toggles plus a 178px input and a roll button; on the 486px modal that
|
||||
* overran the panel, clipping the input at the right edge and pushing the
|
||||
* roll button out of view entirely. `min-width: 0` lets the flex item shrink
|
||||
* below its content, and the input wrap now treats 178px as a max rather than
|
||||
* a fixed size. */
|
||||
.seed-controls { display: inline-flex; align-items: center; gap: 6px; min-width: 0; flex: 0 1 auto; }
|
||||
.seed-input-wrap { display: inline-flex; align-items: stretch; background: var(--wp-bg-deep, var(--wp-bg)); border: 1px solid var(--wp-border); border-radius: 3px; height: 24px; flex: 1 1 auto; min-width: 88px; max-width: 178px; overflow: hidden; }
|
||||
.seed-input-wrap:focus-within { border-color: var(--wp-accent); }
|
||||
.seed-input { flex: 1; background: transparent; border: 0; padding: 0 7px; font: 11px var(--wp-font-mono, monospace); color: var(--wp-text); text-align: right; min-width: 0; -moz-appearance: textfield; }
|
||||
.seed-input::-webkit-outer-spin-button, .seed-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
|
||||
@@ -116,6 +159,6 @@ function bump(d: 1 | -1) {
|
||||
.seed-spin-btn { flex: 1; display: flex; align-items: center; justify-content: center; background: transparent; border: 0; padding: 0; color: var(--wp-text-dim, var(--wp-text3)); cursor: pointer; line-height: 0; }
|
||||
.seed-spin-btn + .seed-spin-btn { border-top: 1px solid var(--wp-border); }
|
||||
.seed-spin-btn:hover { color: var(--wp-accent-text, var(--wp-text)); background: rgba(99,102,241,.12); }
|
||||
.seed-roll { background: transparent; border: 0; color: var(--wp-text-dim, var(--wp-text3)); cursor: pointer; padding: 2px 4px; display: flex; }
|
||||
.seed-roll { background: transparent; border: 0; color: var(--wp-text-dim, var(--wp-text3)); cursor: pointer; padding: 2px 4px; display: flex; flex-shrink: 0; }
|
||||
.seed-roll:hover { color: var(--wp-accent-text, var(--wp-text)); }
|
||||
</style>
|
||||
|
||||
@@ -123,3 +123,38 @@ describe("SeedListModal", () => {
|
||||
expect(writes[writes.length - 1]).toBe("#2: 999");
|
||||
});
|
||||
});
|
||||
|
||||
describe("SeedListModal bypass column (#13)", () => {
|
||||
it("shows no bypass toggles when bypassFrames prop is absent (Seed List parity)", () => {
|
||||
const w = modal({ seedLocks: {} });
|
||||
expect(w.findAll('[data-test="seedrow-bypass"]').length).toBe(0);
|
||||
});
|
||||
it("renders a bypass toggle per active row when bypassFrames is passed", () => {
|
||||
const w = modal({ seedLocks: {}, bypassFrames: [] });
|
||||
expect(w.findAll('[data-test="seedrow-bypass"]').length).toBe(4);
|
||||
});
|
||||
it("emits update:bypassFrames when a row is bypassed", async () => {
|
||||
const w = modal({ seedLocks: {}, bypassFrames: [] });
|
||||
await w.findAll('[data-test="seedrow-bypass"]')[1].trigger("click");
|
||||
expect(w.emitted("update:bypassFrames")![0]).toEqual([[1]]);
|
||||
});
|
||||
it("disables the last active frame's bypass toggle", () => {
|
||||
const w = modal({ seedLocks: {}, bypassFrames: [0, 1, 2] });
|
||||
const toggles = w.findAll('[data-test="seedrow-bypass"]');
|
||||
expect(toggles[3].attributes("disabled")).toBeDefined();
|
||||
expect(toggles[0].attributes("disabled")).toBeUndefined();
|
||||
});
|
||||
it("renders out-of-range bypassed frames as inactive rows", () => {
|
||||
const w = modal({ seedLocks: {}, bypassFrames: [9] });
|
||||
expect(w.find('[data-test="mx-bypass-inactive"]').exists()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("SeedListModal read-only bypass (#13 seed-list mirror)", () => {
|
||||
it("dims bypassed rows without an interactive toggle + shows the badge", () => {
|
||||
const w = modal({ seedLocks: {}, bypassFrames: [1], bypassReadonly: true });
|
||||
expect(w.findAll('[data-test="seedrow-bypass"]').length).toBe(0); // no toggles
|
||||
expect(w.findAll(".srow")[1].classes()).toContain("srow--bypassed");
|
||||
expect(w.find('[data-test="mx-bypass-count"]').text()).toMatch(/1 bypassed/i);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -49,3 +49,21 @@ describe("SeedLockRow", () => {
|
||||
expect(row().find('[data-test="seedrow-lockprev"]').attributes("disabled")).toBeDefined(); // absent → disabled
|
||||
});
|
||||
});
|
||||
|
||||
describe("SeedLockRow bypass (#13)", () => {
|
||||
it("hides the bypass toggle unless bypassable", () => {
|
||||
expect(row().find('[data-test="seedrow-bypass"]').exists()).toBe(false);
|
||||
expect(row({ bypassable: true }).find('[data-test="seedrow-bypass"]').exists()).toBe(true);
|
||||
});
|
||||
it("emits bypass with the toggled state", async () => {
|
||||
const w = row({ bypassable: true, bypassed: false });
|
||||
await w.get('[data-test="seedrow-bypass"]').trigger("click");
|
||||
expect(w.emitted("bypass")![0]).toEqual([{ index: 0, bypassed: true }]);
|
||||
});
|
||||
it("marks the row bypassed + respects bypassDisabled", () => {
|
||||
const on = row({ bypassable: true, bypassed: true });
|
||||
expect(on.get(".srow").classes()).toContain("srow--bypassed");
|
||||
const dis = row({ bypassable: true, bypassed: false, bypassDisabled: true });
|
||||
expect(dis.get('[data-test="seedrow-bypass"]').attributes("disabled")).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import { defineComponent, h, ref } from "vue";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { useGrowableField } from "../useGrowableField";
|
||||
|
||||
/**
|
||||
* jsdom has no ResizeObserver and no layout, so these exercise the parts that
|
||||
* are pure logic: when auto-grow yields, and — the one that actually bit —
|
||||
* that the observer callback itself does no work.
|
||||
*/
|
||||
|
||||
let observerCallback: (() => void) | null = null;
|
||||
let observedEl: Element | null = null;
|
||||
let disconnected = false;
|
||||
|
||||
class FakeResizeObserver {
|
||||
constructor(cb: () => void) { observerCallback = cb; }
|
||||
observe(el: Element) { observedEl = el; }
|
||||
disconnect() { disconnected = true; }
|
||||
unobserve() { /* unused */ }
|
||||
}
|
||||
|
||||
/** Host that wires the composable to a real element, like the real callers. */
|
||||
function mountField(height = 100) {
|
||||
const el = ref<HTMLElement | null>(null);
|
||||
let api!: ReturnType<typeof useGrowableField>;
|
||||
const Comp = defineComponent({
|
||||
setup() {
|
||||
api = useGrowableField(() => el.value);
|
||||
return () => h("div", {
|
||||
ref: (r) => { el.value = r as HTMLElement | null; },
|
||||
});
|
||||
},
|
||||
});
|
||||
const wrap = mount(Comp, { attachTo: document.body });
|
||||
const node = wrap.element as HTMLElement;
|
||||
// jsdom reports 0 for everything; stub the geometry these read.
|
||||
node.getBoundingClientRect = () => ({
|
||||
height, bottom: height, top: 0, left: 0, right: 0, width: 100, x: 0, y: 0,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect;
|
||||
// Real callers wire the observer from their own `onMounted`.
|
||||
api.attach();
|
||||
return { wrap, api, node };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
observerCallback = null;
|
||||
observedEl = null;
|
||||
disconnected = false;
|
||||
vi.stubGlobal("ResizeObserver", FakeResizeObserver);
|
||||
// Run rAF synchronously so the deferred flush is observable.
|
||||
vi.stubGlobal("requestAnimationFrame", (fn: FrameRequestCallback) => {
|
||||
fn(0); return 0;
|
||||
});
|
||||
});
|
||||
afterEach(() => { vi.unstubAllGlobals(); });
|
||||
|
||||
describe("useGrowableField — auto-grow yields to the drag", () => {
|
||||
it("auto-sizes while the user has not touched the handle", () => {
|
||||
const { api, node, wrap } = mountField();
|
||||
Object.defineProperty(node, "scrollHeight", { value: 240, configurable: true });
|
||||
api.autosize();
|
||||
expect(node.style.height).toBe("240px");
|
||||
wrap.unmount();
|
||||
});
|
||||
|
||||
it("STOPS auto-sizing once the user has resized — the collapse-springs-back bug", () => {
|
||||
const { api, node, wrap } = mountField();
|
||||
Object.defineProperty(node, "scrollHeight", { value: 240, configurable: true });
|
||||
api.userResized.value = true;
|
||||
node.style.height = "60px";
|
||||
api.autosize();
|
||||
// Would have been stomped back to 240px before.
|
||||
expect(node.style.height).toBe("60px");
|
||||
wrap.unmount();
|
||||
});
|
||||
|
||||
it("respects a minimum height", () => {
|
||||
const el = ref<HTMLElement | null>(null);
|
||||
let api!: ReturnType<typeof useGrowableField>;
|
||||
const Comp = defineComponent({
|
||||
setup() {
|
||||
api = useGrowableField(() => el.value, { minHeight: 80 });
|
||||
return () => h("div", { ref: (r) => { el.value = r as HTMLElement | null; } });
|
||||
},
|
||||
});
|
||||
const wrap = mount(Comp, { attachTo: document.body });
|
||||
const node = wrap.element as HTMLElement;
|
||||
api.attach();
|
||||
Object.defineProperty(node, "scrollHeight", { value: 20, configurable: true });
|
||||
api.autosize();
|
||||
expect(node.style.height).toBe("80px");
|
||||
wrap.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("useGrowableField — the observer callback stays cheap", () => {
|
||||
it("does NOT read layout synchronously inside the ResizeObserver callback", () => {
|
||||
// The bug: measuring and writing reactive state inside the callback dirties
|
||||
// layout in the very callback the browser uses to report it. Chrome
|
||||
// throttles that and drops a frame, which feels like the drag seizing up.
|
||||
// The callback must only schedule.
|
||||
const { wrap, node } = mountField();
|
||||
let reads = 0;
|
||||
Object.defineProperty(node, "scrollHeight", {
|
||||
get() { reads++; return 300; },
|
||||
configurable: true,
|
||||
});
|
||||
// Take rAF away so a deferred flush cannot run — anything measured now
|
||||
// would have to have come from the callback itself.
|
||||
vi.stubGlobal("requestAnimationFrame", () => 0);
|
||||
expect(observerCallback).toBeTypeOf("function");
|
||||
observerCallback?.();
|
||||
expect(reads).toBe(0);
|
||||
wrap.unmount();
|
||||
});
|
||||
|
||||
it("observes the element and disconnects on unmount", () => {
|
||||
const { wrap, node } = mountField();
|
||||
expect(observedEl).toBe(node);
|
||||
wrap.unmount();
|
||||
expect(disconnected).toBe(true);
|
||||
});
|
||||
|
||||
it("flags a user resize once a height change it did not author lands", () => {
|
||||
const { wrap, api, node } = mountField(100);
|
||||
Object.defineProperty(node, "scrollHeight", { value: 100, configurable: true });
|
||||
expect(api.userResized.value).toBe(false);
|
||||
node.getBoundingClientRect = () => ({
|
||||
height: 60, bottom: 60, top: 0, left: 0, right: 0, width: 100, x: 0, y: 0,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect;
|
||||
observerCallback?.();
|
||||
expect(api.userResized.value).toBe(true);
|
||||
wrap.unmount();
|
||||
});
|
||||
|
||||
it("does not mistake its OWN autosize write for a user drag", () => {
|
||||
const { wrap, api, node } = mountField(100);
|
||||
Object.defineProperty(node, "scrollHeight", { value: 300, configurable: true });
|
||||
api.autosize();
|
||||
node.getBoundingClientRect = () => ({
|
||||
height: 300, bottom: 300, top: 0, left: 0, right: 0, width: 100, x: 0, y: 0,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect;
|
||||
observerCallback?.();
|
||||
expect(api.userResized.value).toBe(false);
|
||||
wrap.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("useGrowableField — the drag itself", () => {
|
||||
/** A pointerdown as the grip element would deliver it. */
|
||||
function gripDown(clientY: number): PointerEvent {
|
||||
// `currentTarget` is getter-only on a real Event, so build a plain object
|
||||
// carrying just what `startResize` reads.
|
||||
return {
|
||||
clientY,
|
||||
pointerId: 1,
|
||||
currentTarget: null,
|
||||
preventDefault: () => {},
|
||||
} as unknown as PointerEvent;
|
||||
}
|
||||
|
||||
it("releases max-height on grab, pinning the current height first", () => {
|
||||
// `max-height` bounds AUTO-grow; a deliberate drag overrides it. Pinning
|
||||
// first stops an `auto`-height box leaping to full content height the
|
||||
// instant the handle is touched.
|
||||
const { wrap, api, node } = mountField(192);
|
||||
node.style.maxHeight = "12rem";
|
||||
api.startResize(gripDown(500));
|
||||
expect(node.style.maxHeight).toBe("none");
|
||||
expect(node.style.height).toBe("192px");
|
||||
wrap.unmount();
|
||||
});
|
||||
|
||||
it("marks the field user-resized on grab, so auto-grow stops fighting it", () => {
|
||||
const { wrap, api, node } = mountField(192);
|
||||
expect(api.userResized.value).toBe(false);
|
||||
api.startResize(gripDown(500));
|
||||
expect(node.style.maxHeight).toBe("none");
|
||||
expect(api.userResized.value).toBe(true);
|
||||
wrap.unmount();
|
||||
});
|
||||
|
||||
it("applies each move's DELTA rather than a captured origin", () => {
|
||||
// The whole reason the native resizer had to go. It computes
|
||||
// `startHeight + (pointerY - startY)`, so dragging past a limit banks
|
||||
// invisible travel the user must walk all the way back — 13 of 23 dead
|
||||
// frames, measured. An incremental delta keeps no history: the first pixel
|
||||
// back off a limit moves the box.
|
||||
let h = 100;
|
||||
const { wrap, api, node } = mountField(100);
|
||||
node.getBoundingClientRect = () => ({
|
||||
height: h, bottom: h, top: 0, left: 0, right: 0, width: 100, x: 0, y: 0,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect;
|
||||
api.startResize(gripDown(500));
|
||||
const move = (y: number) => window.dispatchEvent(
|
||||
Object.assign(new MouseEvent("pointermove", { clientY: y }), { pointerId: 1 }),
|
||||
);
|
||||
move(520);
|
||||
expect(node.style.height).toBe("120px");
|
||||
h = 120;
|
||||
move(510); // back up 10 — must respond immediately
|
||||
expect(node.style.height).toBe("110px");
|
||||
wrap.unmount();
|
||||
});
|
||||
|
||||
it("falls back to a hard floor when CSS declares none", () => {
|
||||
// `min-height: auto` is the default and parses to NaN. Treating that as 0
|
||||
// let a field be dragged away to a sliver — which is exactly what the
|
||||
// canvas fixed-values rows did, since they never declared one.
|
||||
const h = 40;
|
||||
const { wrap, api, node } = mountField(40);
|
||||
node.getBoundingClientRect = () => ({
|
||||
height: h, bottom: h, top: 0, left: 0, right: 0, width: 100, x: 0, y: 0,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect;
|
||||
api.startResize(gripDown(500));
|
||||
window.dispatchEvent(
|
||||
Object.assign(new MouseEvent("pointermove", { clientY: 100 }), { pointerId: 1 }),
|
||||
);
|
||||
expect(Number.parseFloat(node.style.height)).toBeGreaterThanOrEqual(28);
|
||||
wrap.unmount();
|
||||
});
|
||||
|
||||
it("never shrinks past the CSS floor", () => {
|
||||
const h = 40;
|
||||
const { wrap, api, node } = mountField(40);
|
||||
node.style.minHeight = "34px";
|
||||
node.getBoundingClientRect = () => ({
|
||||
height: h, bottom: h, top: 0, left: 0, right: 0, width: 100, x: 0, y: 0,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect;
|
||||
api.startResize(gripDown(500));
|
||||
window.dispatchEvent(
|
||||
Object.assign(new MouseEvent("pointermove", { clientY: 400 }), { pointerId: 1 }),
|
||||
);
|
||||
expect(node.style.height).toBe("34px");
|
||||
wrap.unmount();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,17 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { kindIcon, KIND_ICON_MAP } from "./kind-icons";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
/** Glyph names the installed PrimeIcons actually ships. The stylesheet is the
|
||||
* authority; a hard-coded list would go stale on the next upgrade. */
|
||||
function installedGlyphs(): Set<string> {
|
||||
const css = readFileSync(require.resolve("primeicons/primeicons.css"), "utf8");
|
||||
return new Set([...css.matchAll(/\.pi-([a-z0-9-]+):before/g)].map((m) => m[1]));
|
||||
}
|
||||
|
||||
describe("kind-icons", () => {
|
||||
it("returns the canonical PrimeIcons class for each module kind", () => {
|
||||
expect(kindIcon("wildcard")).toBe("pi pi-sparkles");
|
||||
@@ -9,6 +20,27 @@ describe("kind-icons", () => {
|
||||
expect(kindIcon("derivation")).toBe("pi pi-arrow-right-arrow-left");
|
||||
expect(kindIcon("constraint")).toBe("pi pi-filter");
|
||||
expect(kindIcon("loop")).toBe("pi pi-replay");
|
||||
expect(kindIcon("injector")).toBe("pi pi-sign-in");
|
||||
});
|
||||
|
||||
it("names only glyphs that exist — a typo renders an empty ring, not an error", () => {
|
||||
// How `brush` shipped broken in the icon picker. A kind whose glyph does
|
||||
// not exist falls back to nothing visible, which reads as "this kind has
|
||||
// no icon" rather than as a mistake, so nobody reports it.
|
||||
const have = installedGlyphs();
|
||||
expect(have.size).toBeGreaterThan(200);
|
||||
const missing = Object.entries(KIND_ICON_MAP)
|
||||
.map(([kind, cls]) => [kind, cls.replace(/^pi pi-/, "")] as const)
|
||||
.filter(([, glyph]) => !have.has(glyph));
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
|
||||
it("covers every kind a canvas producer can report", () => {
|
||||
// `collectUpstreamProducers` emits these three alongside the module kinds;
|
||||
// `injector` was absent and every injected $var rendered as a bare circle.
|
||||
for (const kind of ["injector", "loop", "wildcard"]) {
|
||||
expect(kindIcon(kind)).not.toBe("pi pi-circle");
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to a neutral circle icon for unknown kinds", () => {
|
||||
|
||||
@@ -20,6 +20,18 @@ export const KIND_ICON_MAP = {
|
||||
// Templates are reusable assembler strings (a `template_string` plus
|
||||
// metadata). `pi-file-edit` reads as "editable text document".
|
||||
template: "pi pi-file-edit",
|
||||
// Not a module kind either — categories are library metadata — but the
|
||||
// import/export pickers render them as a bucket alongside the real kinds,
|
||||
// and without a row here they fell through to the generic `pi-circle`.
|
||||
// `pi-bookmark` matches the Categories page's own empty-state glyph.
|
||||
category: "pi pi-bookmark",
|
||||
// WP_ContextInjector rows. Not a library module kind — the injector writes
|
||||
// `$var`s straight into the context without a module behind them — but its
|
||||
// producers flow through the same kind→icon path, and without a row here
|
||||
// every injected var fell through to the generic `pi-circle` and rendered
|
||||
// as an empty ring. `pi-sign-in` is the arrow-into-a-door mark, matching
|
||||
// "inject a value into the context".
|
||||
injector: "pi pi-sign-in",
|
||||
// WP_ContextLoop iteration vars (`$iteration` / `$<name>_total`).
|
||||
// Not a library module kind — synthesised by the loop head — but it
|
||||
// flows through the same kind→icon path so the assembler chip reads
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Platform-correct labels for the modifier we actually listen for.
|
||||
*
|
||||
* The save shortcut in our modals is `(ev.ctrlKey || ev.metaKey) && Enter`, so
|
||||
* it has always worked on both platforms — but the hint rendered a hardcoded
|
||||
* `⌘`, which reads as a Mac-only binding to the ~90% of ComfyUI users on
|
||||
* Windows and Linux.
|
||||
*/
|
||||
|
||||
/** True on macOS/iPadOS, where the command key is the accelerator. */
|
||||
export function isApplePlatform(): boolean {
|
||||
if (typeof navigator === "undefined") return false;
|
||||
const nav = navigator as Navigator & { userAgentData?: { platform?: string } };
|
||||
// `navigator.platform` is deprecated; prefer the UA-CH hint and fall back to
|
||||
// the user-agent string, which still carries "Macintosh" / "iPhone".
|
||||
const hint = nav.userAgentData?.platform ?? "";
|
||||
if (hint) return /mac/i.test(hint);
|
||||
return /mac|iphone|ipad|ipod/i.test(nav.userAgent ?? "");
|
||||
}
|
||||
|
||||
/** The accelerator key's symbol: `⌘` on Apple platforms, `Ctrl` elsewhere. */
|
||||
export function accelLabel(): string {
|
||||
return isApplePlatform() ? "⌘" : "Ctrl";
|
||||
}
|
||||
|
||||
/** The full "save" chord as shown in modal footers — `⌘↵` or `Ctrl+↵`. */
|
||||
export function saveChordLabel(): string {
|
||||
return isApplePlatform() ? "⌘↵" : "Ctrl+↵";
|
||||
}
|
||||
@@ -113,6 +113,34 @@
|
||||
* without clashing with any module kind. */
|
||||
--wp-kind-injector: #60a5fa;
|
||||
|
||||
/* Type + spacing scale, mirrored from the SPA's tokens.css.
|
||||
*
|
||||
* These were the LAST gap in the alias block: colors, borders, radius and
|
||||
* shadow all had graph-side equivalents, but a component written against
|
||||
* `var(--wp-text-sm)` or `var(--wp-space-3)` resolved to NOTHING here —
|
||||
* font-size fell back to inherited, padding collapsed to 0. That is the
|
||||
* same failure mode `Select.vue` hit when its styles lived only in the SPA
|
||||
* bundle, and it is invisible in the SPA where the tokens exist.
|
||||
*
|
||||
* Values are the SPA's `--wp-density: 1` resolution, flattened: the graph
|
||||
* side has no density control, so there is nothing to multiply by.
|
||||
* Anything shared between the two targets can now use one set of names. */
|
||||
--wp-space-0: 0;
|
||||
--wp-space-1: 2px;
|
||||
--wp-space-2: 4px;
|
||||
--wp-space-3: 6px;
|
||||
--wp-space-4: 8px;
|
||||
--wp-space-5: 12px;
|
||||
--wp-space-6: 16px;
|
||||
--wp-space-7: 24px;
|
||||
--wp-space-8: 32px;
|
||||
|
||||
--wp-text-xs: 11px; --wp-line-xs: 16px;
|
||||
--wp-text-sm: 12px; --wp-line-sm: 16px;
|
||||
--wp-text-base: 13px; --wp-line-base: 20px;
|
||||
--wp-text-md: 14px; --wp-line-md: 20px;
|
||||
--wp-text-lg: 16px; --wp-line-lg: 22px;
|
||||
|
||||
/* Bundle frame default color — used when a bundle library entry
|
||||
* has no user-picked color set. Indigo-500 chosen for visibility:
|
||||
* distinct from accent purple and injector blue, high enough chroma
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
/**
|
||||
* The behaviour every capped, user-resizable text field in this project needs.
|
||||
*
|
||||
* Three components had grown their own copy of it — `RichTextInput`'s two
|
||||
* hosts, the fixed-values `ValueRow`, the combine template — and the copies had
|
||||
* already diverged: only one clears the resize grip, only one follows the grip
|
||||
* off-screen, and the auto-grow in `ValueRow` silently fought the drag handle.
|
||||
* One implementation, three fixes, no third copy.
|
||||
*
|
||||
* What it provides:
|
||||
*
|
||||
* 1. **Auto-grow that yields to the user.** The field sizes itself to its
|
||||
* content until the user drags the handle; from then on their height is
|
||||
* authoritative. Previously `height = scrollHeight` ran on every input and
|
||||
* external value change, so a manually collapsed box snapped straight back
|
||||
* open — which reads as "the drag sticks, then starts working".
|
||||
*
|
||||
* 2. **A "more below" flag.** A capped box looks identical whether it holds
|
||||
* its whole value or a third of it.
|
||||
*
|
||||
* 3. **Grip-follow.** Dragging a field taller than the space beneath it moves
|
||||
* the box, not the pointer, so the handle being held slides off-screen and
|
||||
* the drag goes blind. Scrolling by exactly the overshoot pins the bottom
|
||||
* edge to the viewport, keeping the grip under the cursor.
|
||||
*
|
||||
* DOM-only and framework-light: takes an element getter, returns plain
|
||||
* functions plus one ref. Callers own their own `onMounted` / `watch`.
|
||||
*/
|
||||
import { onBeforeUnmount, ref, type Ref } from "vue";
|
||||
|
||||
export interface GrowableField {
|
||||
/** True while content extends past the visible bottom edge. */
|
||||
hasMoreBelow: Ref<boolean>;
|
||||
/** Re-measure the overflow flag. Cheap; call on scroll and input. */
|
||||
updateOverflowHint: () => void;
|
||||
/** Same, deferred a frame — use at mount, before layout has settled. */
|
||||
scheduleOverflowHint: () => void;
|
||||
/** Resize to fit content, UNLESS the user has taken manual control. */
|
||||
autosize: () => void;
|
||||
/** Begin observing: wires the resize observer for the hint + grip-follow. */
|
||||
attach: () => void;
|
||||
/** True once the user has dragged the handle. */
|
||||
userResized: Ref<boolean>;
|
||||
/** Bind to a grip element's `pointerdown`. Replaces `resize: vertical`,
|
||||
* which cannot be clamped from outside — see `startResize`. */
|
||||
startResize: (ev: PointerEvent) => void;
|
||||
}
|
||||
|
||||
/** Nearest ancestor that actually scrolls, or null when only the page does.
|
||||
* Walks computed `overflow-y` rather than trusting a class name — these
|
||||
* fields live in modals, pages and canvas widgets, each of which puts its
|
||||
* scroller somewhere different. */
|
||||
function scrollableAncestor(el: HTMLElement): HTMLElement | null {
|
||||
let node = el.parentElement;
|
||||
while (node && node !== document.body) {
|
||||
const oy = getComputedStyle(node).overflowY;
|
||||
if (oy === "auto" || oy === "scroll") return node;
|
||||
node = node.parentElement;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Backstop floor for a field whose CSS declares no `min-height`. Enough to
|
||||
* keep one line and its padding visible, so a drag can always be undone. */
|
||||
const ABSOLUTE_MIN = 28;
|
||||
|
||||
export function useGrowableField(
|
||||
getEl: () => HTMLElement | null,
|
||||
opts: { minHeight?: number } = {},
|
||||
): GrowableField {
|
||||
const hasMoreBelow = ref(false);
|
||||
const userResized = ref(false);
|
||||
|
||||
function updateOverflowHint(): void {
|
||||
const el = getEl();
|
||||
if (!el) return;
|
||||
// 2px slack absorbs sub-pixel rounding at the exact bottom.
|
||||
hasMoreBelow.value = el.scrollHeight - el.scrollTop - el.clientHeight > 2;
|
||||
}
|
||||
|
||||
function scheduleOverflowHint(): void {
|
||||
if (typeof requestAnimationFrame === "function") requestAnimationFrame(updateOverflowHint);
|
||||
else updateOverflowHint();
|
||||
}
|
||||
|
||||
function autosize(): void {
|
||||
const el = getEl();
|
||||
// The user's drag wins from the moment it happens. Re-running the fit
|
||||
// after that is what made a collapsed box spring open again.
|
||||
if (!el || userResized.value) return;
|
||||
autoDriven = true;
|
||||
el.style.height = "auto";
|
||||
const next = Math.max(opts.minHeight ?? 0, el.scrollHeight);
|
||||
el.style.height = `${next}px`;
|
||||
lastHeight = next;
|
||||
// Release on the next frame: the observer fires asynchronously, and
|
||||
// clearing synchronously would let our own write look like a user drag.
|
||||
if (typeof requestAnimationFrame === "function") {
|
||||
requestAnimationFrame(() => { autoDriven = false; });
|
||||
} else {
|
||||
autoDriven = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep the grip under the cursor while the box grows past the fold.
|
||||
* Only ever scrolls DOWN, and only while the bottom is genuinely
|
||||
* off-screen — shrinking must not yank the view around.
|
||||
*
|
||||
* Deliberately not `scrollIntoView`, which this project bans for scrolling
|
||||
* every ancestor rather than the one the user is working in. */
|
||||
function followGrip(): void {
|
||||
const el = getEl();
|
||||
if (!el) return;
|
||||
const margin = 8;
|
||||
const rect = el.getBoundingClientRect();
|
||||
const container = scrollableAncestor(el);
|
||||
if (container) {
|
||||
const cRect = container.getBoundingClientRect();
|
||||
const overshoot = rect.bottom - (cRect.bottom - margin);
|
||||
if (overshoot > 0) container.scrollTop += overshoot;
|
||||
return;
|
||||
}
|
||||
const overshoot = rect.bottom - (window.innerHeight - margin);
|
||||
if (overshoot > 0) window.scrollBy(0, overshoot);
|
||||
}
|
||||
|
||||
let obs: ResizeObserver | null = null;
|
||||
let lastHeight = 0;
|
||||
/** Set while `autosize` is writing, so its own change is not mistaken for a
|
||||
* drag. Without it the first auto-fit would lock the field immediately. */
|
||||
let autoDriven = false;
|
||||
/** True between pointerdown on the field and the matching pointerup —
|
||||
* i.e. while the user may be holding the resize handle. */
|
||||
let dragging = false;
|
||||
let pending = false;
|
||||
/** Set once the height cap has been dropped for a manual drag. */
|
||||
let capLifted = false;
|
||||
/** Pointer Y at the previous move — the drag is incremental, so only the
|
||||
* step between moves matters, never a captured origin. */
|
||||
let lastPointerY = 0;
|
||||
/** Floor read from CSS at drag start; CSS stays the source of truth. */
|
||||
let minPx = 0;
|
||||
|
||||
/**
|
||||
* Everything the observer wants to do, moved OUT of the observer.
|
||||
*
|
||||
* A ResizeObserver callback that reads layout and writes reactive state runs
|
||||
* before paint, so doing it synchronously on every frame of a resize drag
|
||||
* dirties layout inside the very callback the browser is using to report
|
||||
* layout. Chrome throttles that (the "ResizeObserver loop" case) and stops
|
||||
* delivering for a frame, which the user feels as the drag seizing up until
|
||||
* they release and re-grab. Deferring to rAF leaves the callback trivial.
|
||||
*/
|
||||
function flush(): void {
|
||||
pending = false;
|
||||
const el = getEl();
|
||||
if (!el) return;
|
||||
const h = el.getBoundingClientRect().height;
|
||||
updateOverflowHint();
|
||||
// A height change we did not author is the user on the drag handle.
|
||||
if (!autoDriven && Math.abs(h - lastHeight) > 1) userResized.value = true;
|
||||
// Follows LIVE, including mid-drag. Scrolling by the overshoot moves the
|
||||
// element up by exactly that much, landing its bottom edge at the viewport
|
||||
// edge — which is where the pointer already is, so the grip stays under the
|
||||
// cursor. Deferring this to pointerup (an earlier attempt at the stall,
|
||||
// which turned out to be the height cap) just made the field vanish off
|
||||
// the bottom for the whole drag.
|
||||
if (h > lastHeight) followGrip();
|
||||
lastHeight = h;
|
||||
}
|
||||
|
||||
function schedule(): void {
|
||||
if (pending) return;
|
||||
pending = true;
|
||||
if (typeof requestAnimationFrame === "function") requestAnimationFrame(flush);
|
||||
else flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Our own resize drag, replacing the native `resize: vertical`.
|
||||
*
|
||||
* The native resizer computes `startHeight + (pointerY - startY)` from an
|
||||
* origin it captured at pointerdown, and it does NOT clamp to the element's
|
||||
* own min/max. Drag past a limit and that sum keeps running while the
|
||||
* rendered box stays pinned, so dragging back moves nothing until the
|
||||
* invisible total walks all the way home. Measured: collapsing past a 34px
|
||||
* floor then expanding cost 13 of 23 frames of completely dead travel. That
|
||||
* is the "gets stuck, then starts working" report, and it bites exactly when
|
||||
* the box reaches one line — which is also when the overflow fade returns,
|
||||
* which is why the fade kept looking guilty.
|
||||
*
|
||||
* Nothing outside can fix it: rewriting `style.height` mid-drag is ignored,
|
||||
* because the browser recomputes from its own captured origin every move.
|
||||
* Clamping the RESULT does not help either — the accumulated input is the
|
||||
* problem, so a clamped absolute drag measured the same 13 / 23.
|
||||
*
|
||||
* Applying each move's DELTA to the current height instead keeps no history
|
||||
* to accumulate: the first pixel back off a limit moves the box. Same
|
||||
* harness, same over-drag: 0 / 23.
|
||||
*/
|
||||
function startResize(ev: PointerEvent): void {
|
||||
const el = getEl();
|
||||
if (!el) return;
|
||||
ev.preventDefault();
|
||||
dragging = true;
|
||||
userResized.value = true;
|
||||
lastPointerY = ev.clientY;
|
||||
|
||||
const cs = getComputedStyle(el);
|
||||
// CSS stays the source of truth for the floor; the ceiling is deliberately
|
||||
// released, because a deliberate drag is the user overriding a cap that
|
||||
// exists only to bound AUTO-grow.
|
||||
// `min-height: auto` (the default) parses to NaN, so a field that never
|
||||
// declared one would get a floor of 0 and could be dragged away to a
|
||||
// sliver. CSS stays authoritative when it says anything; ABSOLUTE_MIN is
|
||||
// only the backstop for when it does not.
|
||||
const declared = Number.parseFloat(cs.minHeight);
|
||||
minPx = Number.isFinite(declared) && declared > 0 ? declared : ABSOLUTE_MIN;
|
||||
if (!capLifted) {
|
||||
el.style.height = `${el.getBoundingClientRect().height}px`;
|
||||
el.style.maxHeight = "none";
|
||||
capLifted = true;
|
||||
}
|
||||
(ev.currentTarget as HTMLElement | null)?.setPointerCapture?.(ev.pointerId);
|
||||
window.addEventListener("pointermove", onResizeMove);
|
||||
window.addEventListener("pointerup", onPointerUp);
|
||||
window.addEventListener("pointercancel", onPointerUp);
|
||||
}
|
||||
|
||||
function onResizeMove(ev: PointerEvent): void {
|
||||
const el = getEl();
|
||||
if (!el || !dragging) return;
|
||||
const dy = ev.clientY - lastPointerY;
|
||||
lastPointerY = ev.clientY;
|
||||
const cur = el.getBoundingClientRect().height;
|
||||
el.style.height = `${Math.max(minPx, cur + dy)}px`;
|
||||
}
|
||||
|
||||
function onPointerUp(): void {
|
||||
if (!dragging) return;
|
||||
dragging = false;
|
||||
window.removeEventListener("pointermove", onResizeMove);
|
||||
window.removeEventListener("pointerup", onPointerUp);
|
||||
window.removeEventListener("pointercancel", onPointerUp);
|
||||
}
|
||||
|
||||
/** Idempotent: callers re-attach when the element they own is REPLACED
|
||||
* rather than mutated (RichTextInput swaps its contenteditable host to
|
||||
* repair a browser-mangled DOM). Without the disconnect the old observer
|
||||
* would keep watching a detached node and leak, and the hint would go
|
||||
* permanently stale on the live one. */
|
||||
function attach(): void {
|
||||
obs?.disconnect();
|
||||
obs = null;
|
||||
const el = getEl();
|
||||
if (!el) return;
|
||||
lastHeight = el.getBoundingClientRect().height;
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
obs = new ResizeObserver(schedule);
|
||||
obs.observe(el);
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
obs?.disconnect();
|
||||
obs = null;
|
||||
onPointerUp();
|
||||
});
|
||||
|
||||
return {
|
||||
hasMoreBelow,
|
||||
updateOverflowHint,
|
||||
scheduleOverflowHint,
|
||||
autosize,
|
||||
attach,
|
||||
userResized,
|
||||
startResize,
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user