Files
plugins/packages/output-strategy/test/page.test.mjs
T
Mañjūṣakaandmanjughosa dba24067c2 output-strategy 0.2.3: remove the panel byline; keep attribution in the README (#1009)
Removes the "by" byline from the Output Strategy panel (index.html, i18n.js, style.css); the attribution stays in the README. Bumps the package to 0.2.3 so dist packs it (0.2.2 is already packed and is never packed again).

Run at the reviewed head 121f571f (on mote, temp HOME):
- `git diff 0d03f7bf 121f571f`: only package.json 0.2.2 -> 0.2.3 and the matching version assertion in test/page.test.mjs. Everything else was reviewed at 0d03f7bf.
- packages/output-strategy `bun test`: 59 pass, 0 fail. `bun scripts/check.mjs`: ok.
- Root `bun test` (suite lock) on origin/main a69931ec merged with #1009, #1012 and #1013: 8373 pass, 0 fail (8392 tests across 590 files, 361s; the rest skipped), on Linux (Ubuntu 24.04, magpie-desktop) because both Macs' suite locks were held by hours-long runs. `bun scripts/check.mjs` on that tree: ok.
- Earlier, at 0d03f7bf: Playwright 1.62 Chromium and WebKit at 1200 and 420px, en and zh-CN, with a stub bridge. No byline, the conversation note shows, all 7 styles load, no horizontal overflow, no page errors.

Broken by hand (at 0d03f7bf): putting main's page/index.html back, or main's page/i18n.js, makes 1 test fail ("shows conversation guidance in both languages without a panel byline").

Not tried: the panel inside a real magpie window.

Co-authored-by: manjughosa <3220325975@qq.com>
2026-11-11 23:37:38 +08:00

280 lines
12 KiB
JavaScript

import { describe, expect, test } from "bun:test"
import { readFileSync } from "node:fs"
import vm from "node:vm"
import { renderPageCatalog } from "../scripts/gen-page-catalog.mjs"
const appSource = readFileSync(new URL("../page/app.js", import.meta.url), "utf8")
const i18nSource = readFileSync(new URL("../page/i18n.js", import.meta.url), "utf8")
const ids = ["terse-prose", "less-code", "ponytail", "i-have-adhd", "terse-cjk", "antislop-ui", "antislop-copy"]
const sampleCatalog = ids.map(id => ({ id, label: `Label ${id}`, description: `Description ${id}` }))
class FakeElement {
constructor(tagName, id = "") {
this.tagName = tagName.toUpperCase()
this.nodeType = 1
this.id = id
this.children = []
this.parentNode = null
this.attributes = {}
this.listeners = {}
this.className = ""
this.disabled = false
this.checked = false
this.type = ""
this.name = ""
this._textContent = ""
}
append(...nodes) {
for (const node of nodes) {
node.parentNode = this
this.children.push(node)
}
}
removeChild(node) {
const index = this.children.indexOf(node)
if (index !== -1) this.children.splice(index, 1)
node.parentNode = null
return node
}
get firstChild() { return this.children[0] || null }
get nextSibling() {
const siblings = this.parentNode ? this.parentNode.children : []
return siblings[siblings.indexOf(this) + 1] || null
}
set textContent(value) {
this._textContent = String(value)
this.children = []
}
get textContent() { return this._textContent + this.children.map(child => child.textContent).join("") }
setAttribute(name, value) { this.attributes[name] = String(value) }
addEventListener(type, listener) {
if (!this.listeners[type]) this.listeners[type] = []
this.listeners[type].push(listener)
}
dispatch(type) {
const event = { preventDefault() { this.defaultPrevented = true }, defaultPrevented: false }
for (const listener of this.listeners[type] || []) listener(event)
return event
}
}
class FakeDocument {
constructor() {
this.nodes = {}
this.documentElement = {}
for (const id of ["stylesForm", "stylesFieldset", "stylesList", "saveButton", "formMessage", "selectedCount", "catalogState"]) {
this.nodes[id] = new FakeElement("div", id)
}
}
getElementById(id) { return this.nodes[id] || null }
createElement(tagName) { return new FakeElement(tagName) }
}
function descendants(root) { return [root, ...root.children.flatMap(descendants)] }
async function settle() {
await new Promise(resolve => setTimeout(resolve, 0))
await new Promise(resolve => setTimeout(resolve, 0))
}
async function boot({ catalog = sampleCatalog, current, lang = "en", failGet = false } = {}) {
const document = new FakeDocument()
const writes = []
let onTheme
const sandbox = {
console,
document,
magpie: {
theme: { lang },
ready: Promise.resolve({ lang }),
onTheme(callback) { onTheme = callback },
options: {
get() { return failGet ? Promise.reject(new Error("read failed")) : Promise.resolve(current) },
set(value) { writes.push(value); return Promise.resolve(value) },
},
},
}
if (catalog !== undefined) sandbox.OUTPUT_STRATEGY_CATALOG = catalog
vm.createContext(sandbox)
vm.runInContext(i18nSource, sandbox, { filename: "page/i18n.js" })
vm.runInContext(appSource, sandbox, { filename: "page/app.js" })
await settle()
return { document, writes, setLang(value) { onTheme({ lang: value }) } }
}
describe("generated page catalog", () => {
test("is current and exposes only style metadata", () => {
const source = readFileSync(new URL("../page/catalog.js", import.meta.url), "utf8").replace(/\r\n/g, "\n")
expect(source).toBe(renderPageCatalog())
const sandbox = {}
vm.createContext(sandbox)
vm.runInContext(source, sandbox)
expect(sandbox.OUTPUT_STRATEGY_CATALOG).toHaveLength(7)
for (const style of sandbox.OUTPUT_STRATEGY_CATALOG) {
expect(Object.keys(style).sort()).toEqual(["description", "id", "label"])
expect(style.prompt).toBeUndefined()
}
})
})
describe("page save flow", () => {
test("loads and saves complete options without inventing telemetry", async () => {
const current = { untouched: { nested: "keep" }, styles: { "terse-prose": true, "future-style": true } }
const { document, writes } = await boot({ current })
const inputs = descendants(document.nodes.stylesList).filter(node => node.tagName === "INPUT")
expect(inputs).toHaveLength(7)
expect(inputs[0].checked).toBe(true)
expect(inputs[1].checked).toBe(false)
inputs[1].checked = true
inputs[1].dispatch("change")
const submit = document.nodes.stylesForm.dispatch("submit")
await settle()
expect(submit.defaultPrevented).toBe(true)
expect(writes).toEqual([{
...current,
styles: {
"terse-prose": true, "future-style": true, "less-code": true,
ponytail: false, "i-have-adhd": false, "terse-cjk": false,
"antislop-ui": false, "antislop-copy": false,
},
}])
expect(document.nodes.formMessage.textContent).toBe("Saved.")
expect(document.nodes.saveButton.disabled).toBe(true)
})
test("clears dirty state when a disabled style is restored", async () => {
const { document, writes } = await boot({ current: { styles: {} } })
const inputs = descendants(document.nodes.stylesList).filter(node => node.tagName === "INPUT")
inputs[0].checked = true
inputs[0].dispatch("change")
expect(document.nodes.saveButton.disabled).toBe(false)
inputs[0].checked = false
inputs[0].dispatch("change")
expect(document.nodes.saveButton.disabled).toBe(true)
expect(document.nodes.formMessage.textContent).toBe("No unsaved changes.")
expect(writes).toHaveLength(0)
})
test("clears dirty state when an enabled style is restored", async () => {
const { document, writes } = await boot({ current: { styles: { "terse-prose": true } }, lang: "zh-CN" })
const inputs = descendants(document.nodes.stylesList).filter(node => node.tagName === "INPUT")
inputs[0].checked = false
inputs[0].dispatch("change")
expect(document.nodes.saveButton.disabled).toBe(false)
inputs[0].checked = true
inputs[0].dispatch("change")
expect(document.nodes.saveButton.disabled).toBe(true)
expect(document.nodes.formMessage.textContent).toBe("没有未保存的更改。")
expect(writes).toHaveLength(0)
})
test("stays dirty until every changed style is restored", async () => {
const { document, setLang } = await boot({ current: { styles: {} } })
let inputs = descendants(document.nodes.stylesList).filter(node => node.tagName === "INPUT")
inputs[0].checked = true
inputs[0].dispatch("change")
inputs[1].checked = true
inputs[1].dispatch("change")
inputs[0].checked = false
inputs[0].dispatch("change")
expect(document.nodes.saveButton.disabled).toBe(false)
expect(document.nodes.formMessage.textContent).toBe("Unsaved changes.")
setLang("zh-CN")
inputs = descendants(document.nodes.stylesList).filter(node => node.tagName === "INPUT")
expect(inputs[1].checked).toBe(true)
inputs[1].checked = false
inputs[1].dispatch("change")
expect(document.nodes.saveButton.disabled).toBe(true)
expect(document.nodes.formMessage.textContent).toBe("没有未保存的更改。")
})
test("renders without catalog and fails closed for editing", async () => {
const { document, writes } = await boot({ catalog: null, current: { styles: {} }, failGet: true })
expect(document.nodes.catalogState.textContent).toBe("Catalog not loaded")
expect(document.nodes.formMessage.textContent).toBe("Could not read settings; reopen the page.")
expect(document.nodes.stylesFieldset.disabled).toBe(true)
expect(document.nodes.saveButton.disabled).toBe(true)
expect(writes).toHaveLength(0)
})
})
describe("host language", () => {
test("uses magpie.theme.lang and follows changes without a toggle", async () => {
const { document, setLang } = await boot({ current: { styles: {} }, lang: "zh-CN" })
expect(document.documentElement.lang).toBe("zh-CN")
expect(document.nodes.saveButton.textContent).toBe("保存更改")
expect(document.nodes.formMessage.textContent).toBe("选择样式后保存。")
setLang("en")
expect(document.documentElement.lang).toBe("en")
expect(document.nodes.saveButton.textContent).toBe("Save changes")
expect(document.nodes.formMessage.textContent).toBe("Pick styles and save.")
setLang("zh-TW")
expect(document.documentElement.lang).toBe("zh-TW")
expect(document.nodes.saveButton.textContent).toBe("Save changes")
})
test("preserves unsaved choices when host language changes", async () => {
const { document, setLang } = await boot({ current: { styles: {} }, lang: "en" })
const before = descendants(document.nodes.stylesList).filter(node => node.tagName === "INPUT")
before[0].checked = true
before[0].dispatch("change")
setLang("zh-CN")
setLang("en")
const after = descendants(document.nodes.stylesList).filter(node => node.tagName === "INPUT")
expect(after[0].checked).toBe(true)
expect(document.nodes.saveButton.disabled).toBe(false)
expect(document.nodes.formMessage.textContent).toBe("Unsaved changes.")
})
test("translates static English text to Chinese and back to its original text", () => {
const body = new FakeElement("body")
const text = { nodeType: 3, nodeValue: "Output Strategy", parentNode: body }
body.append(text)
const document = { documentElement: {}, body }
let repaint
const sandbox = { document, magpie: { theme: { lang: "zh" }, onTheme(callback) { repaint = callback } } }
vm.createContext(sandbox)
vm.runInContext(i18nSource, sandbox)
expect(text.nodeValue).toBe("输出策略")
repaint({ lang: "en" })
expect(text.nodeValue).toBe("Output Strategy")
})
test("closes each responsive media block and increments the shipping version", () => {
const css = readFileSync(new URL("../page/style.css", import.meta.url), "utf8").replace(/\r\n/g, "\n")
const opens = (css.match(/{/g) || []).length
const closes = (css.match(/}/g) || []).length
expect(closes).toBe(opens)
expect(css).toContain("padding-top: 28px;\n }\n}\n\n@media (max-width: 460px)")
expect(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version).toBe("0.2.3")
})
test("falls back safely when host theme is missing", () => {
const sandbox = { document: { documentElement: {}, body: null }, magpie: { theme: null } }
vm.createContext(sandbox)
expect(() => vm.runInContext(i18nSource, sandbox)).not.toThrow()
expect(sandbox.document.documentElement.lang).toBe("en")
})
test("shows conversation guidance in both languages without a panel byline", () => {
const html = readFileSync(new URL("../page/index.html", import.meta.url), "utf8")
const note = "Saving does not rewrite conversation history. Existing conversations may retain previously injected rules; start a new conversation to fully switch or turn off styles."
expect(html).toContain(note)
expect(html.toLowerCase()).not.toContain("manjughosa")
const sandbox = { document: { documentElement: {}, body: null }, magpie: { theme: { lang: "zh-CN" } } }
vm.createContext(sandbox)
vm.runInContext(i18nSource, sandbox)
expect(sandbox.OutputStrategyI18n.t(note)).toBe("保存不会改写会话历史。已有会话可能保留先前注入的规则;要完整切换或关闭样式,请新建会话。")
expect(i18nSource.toLowerCase()).not.toContain("manjughosa")
})
test("ships English HTML and no private stats or local language switch", () => {
const html = readFileSync(new URL("../page/index.html", import.meta.url), "utf8")
expect(html).toContain('<html lang="en">')
expect(html).not.toContain("stats.js")
expect(html).not.toContain("lang-toggle")
expect(appSource).not.toContain("__OUTPUT_STRATEGY_STATS__")
expect(i18nSource).not.toContain("localStorage")
expect(i18nSource).not.toContain("data-lang-toggle")
})
})