310 lines
13 KiB
JavaScript
310 lines
13 KiB
JavaScript
import test from 'node:test'
|
||
import assert from 'node:assert/strict'
|
||
import fs from 'node:fs'
|
||
import path from 'node:path'
|
||
import { fileURLToPath } from 'node:url'
|
||
import { loadTestModule } from './load-test-module.mjs'
|
||
|
||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||
const rootDir = path.resolve(__dirname, '..')
|
||
const srcDir = path.join(rootDir, 'src')
|
||
const localesDir = path.resolve(rootDir, '..', 'locales', 'en-US')
|
||
|
||
function walkFiles(dir, exts) {
|
||
const out = []
|
||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||
const full = path.join(dir, entry.name)
|
||
if (entry.isDirectory()) out.push(...walkFiles(full, exts))
|
||
else if (exts.some((ext) => entry.name.endsWith(ext))) out.push(full)
|
||
}
|
||
return out
|
||
}
|
||
|
||
test('lazy i18n domain keys are always backed by domain .gen imports', () => {
|
||
const lazyDomains = ['wizard', 'settings', 'plugins']
|
||
const keyToDomain = new Map()
|
||
for (const dom of ['core', 'vm', ...lazyDomains]) {
|
||
const raw = JSON.parse(fs.readFileSync(path.join(localesDir, `${dom}.json`), 'utf8'))
|
||
for (const k of Object.keys(raw)) {
|
||
if (!k.startsWith('$')) keyToDomain.set(k, dom)
|
||
}
|
||
}
|
||
|
||
// Known lazy-loaded chunk entry trees (loaded via React.lazy or dynamic import in App.tsx)
|
||
const lazyEntryBasenames = new Set([
|
||
'CreateWizard.tsx',
|
||
'SettingsModal.tsx',
|
||
'AffinityDialog.tsx',
|
||
'Setup.tsx',
|
||
'RuntimeOnline.tsx',
|
||
'HostView.tsx',
|
||
'ImagesPage.tsx',
|
||
'InstallersPage.tsx',
|
||
'PluginsPage.tsx',
|
||
'PluginMarket.tsx',
|
||
'PluginParts.tsx',
|
||
'AppSettingsPage.tsx',
|
||
'AboutPage.tsx',
|
||
'PluginPanelFrame.tsx',
|
||
'SchemaForm.tsx',
|
||
'optimizations.ts',
|
||
])
|
||
|
||
for (const file of walkFiles(srcDir, ['.ts', '.tsx'])) {
|
||
const rel = path.relative(srcDir, file).replace(/\\/g, '/')
|
||
if (rel.startsWith('i18n/')) continue
|
||
const base = path.basename(file)
|
||
const src = fs.readFileSync(file, 'utf8')
|
||
|
||
// Match string literals passed to t(..., 'key'), tr('key'), labelKey: 'key', detailKey: 'key', titleKey: 'key', descKey: 'key'
|
||
const referencedLazyDomains = new Set()
|
||
const callMatches = [
|
||
...src.matchAll(/\b(?:tr|t)\(\s*(?:[a-zA-Z0-9_$.]+\s*,\s*)?'([a-zA-Z0-9_.]+)'/g),
|
||
...src.matchAll(/\b(?:labelKey|detailKey|titleKey|descKey)\s*:\s*'([a-zA-Z0-9_.]+)'/g),
|
||
]
|
||
for (const m of callMatches) {
|
||
const dom = keyToDomain.get(m[1])
|
||
if (dom && lazyDomains.includes(dom)) {
|
||
referencedLazyDomains.add(`${dom}:${m[1]}`)
|
||
}
|
||
}
|
||
|
||
if (referencedLazyDomains.size === 0) continue
|
||
|
||
assert.ok(
|
||
lazyEntryBasenames.has(base),
|
||
`Eager module ${rel} references lazy domain keys (${[...referencedLazyDomains].join(', ')})! Either move keys to core/vm or lazy-load the module.`,
|
||
)
|
||
|
||
for (const item of referencedLazyDomains) {
|
||
const [dom, key] = item.split(':')
|
||
// Sub-dialogs rendered exclusively inside lazy parent chunks inherit their parent's domain registration
|
||
if (base === 'AffinityDialog.tsx' && dom === 'settings') continue
|
||
if (base === 'RuntimeOnline.tsx' && (dom === 'wizard' || dom === 'settings')) continue
|
||
assert.match(
|
||
src,
|
||
new RegExp(`i18n/domains/${dom}\\.gen`),
|
||
`Module ${rel} uses ${dom} key "${key}" without importing i18n/domains/${dom}.gen`,
|
||
)
|
||
}
|
||
}
|
||
})
|
||
|
||
test('every stack-*, notice-*, error-boundary*, and toast-* class in TSX exists in CSS', () => {
|
||
const css =
|
||
fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8') +
|
||
'\n' +
|
||
fs.readFileSync(path.join(srcDir, 'styles', 'tokens.css'), 'utf8')
|
||
|
||
const prefixes = ['stack-', 'notice-', 'error-boundary', 'toast-']
|
||
const used = new Set()
|
||
for (const file of walkFiles(srcDir, ['.tsx'])) {
|
||
const src = fs.readFileSync(file, 'utf8')
|
||
for (const m of src.matchAll(/className\s*=\s*(?:"([^"]+)"|'([^']+)'|\{`([^`]+)`\})/g)) {
|
||
const raw = (m[1] || m[2] || m[3] || '').replace(/\$\{[^}]+\}/g, ' ')
|
||
for (const tok of raw.split(/\s+/)) {
|
||
if (prefixes.some((p) => tok.startsWith(p))) used.add(tok)
|
||
}
|
||
}
|
||
}
|
||
|
||
for (const cls of used) {
|
||
const escaped = cls.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||
assert.match(css, new RegExp(`\\.${escaped}(?![a-zA-Z0-9_-])`), `Missing CSS rule for .${cls}`)
|
||
}
|
||
})
|
||
|
||
test('Radix Presence .menu/.tooltip animations never replay on close', () => {
|
||
const rawCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8')
|
||
const css = rawCss.replace(/\/\*[\s\S]*?\*\//g, '')
|
||
const titleMenus = fs.readFileSync(path.join(srcDir, 'components', 'TitleMenus.tsx'), 'utf8')
|
||
|
||
// Unconditional `.menu` / `.tooltip` animation (including animation-name inside
|
||
// comma-separated selector lists or reduced-motion media queries) causes Radix
|
||
// Presence to detect an animationName change on close and flash for 160ms.
|
||
for (const m of css.matchAll(/([^{}@]+)\{([^{}]+)\}/g)) {
|
||
const selectors = m[1].split(',').map((s) => s.trim()).filter(Boolean)
|
||
const decls = m[2]
|
||
if (!/\banimation(?:-name)?\s*:(?!\s*none\b)/.test(decls)) continue
|
||
for (const sel of selectors) {
|
||
assert.doesNotMatch(
|
||
sel,
|
||
/\.menu(?![a-zA-Z0-9_-])(?!\[data-state="open"\])/,
|
||
`Non-open .menu selector "${sel}" must not apply an active animation`,
|
||
)
|
||
assert.doesNotMatch(
|
||
sel,
|
||
/\.tooltip(?![a-zA-Z0-9_-])(?!\[data-state="delayed-open"\])/,
|
||
`Non-delayed-open .tooltip selector "${sel}" must not apply an active animation`,
|
||
)
|
||
}
|
||
}
|
||
assert.match(
|
||
css,
|
||
/\.menu\[data-state="open"\]\s*\{[^}]*animation\s*:/,
|
||
'.menu[data-state="open"] must define the menu enter animation',
|
||
)
|
||
assert.match(
|
||
css,
|
||
/\.menu\[data-state="open"\]\[data-menubar-switch="true"\][^\{]*\{[^}]*animation\s*:\s*none/,
|
||
'.menu[data-state="open"][data-menubar-switch="true"] must disable enter animation',
|
||
)
|
||
assert.match(
|
||
css,
|
||
/\.menu\[data-state="closed"\][^\{]*\{[^}]*animation\s*:\s*none/,
|
||
'.menu[data-state="closed"] must explicitly disable animation so Radix Presence unmounts immediately',
|
||
)
|
||
assert.match(
|
||
css,
|
||
/\.tooltip\[data-state="closed"\][^\{]*\{[^}]*animation\s*:\s*none/,
|
||
'.tooltip[data-state="closed"] must explicitly disable animation',
|
||
)
|
||
assert.match(
|
||
css,
|
||
/@media\s*\(\s*prefers-reduced-motion\s*:\s*reduce\s*\)\s*\{[\s\S]*?\.toast\[data-state="closed"\][^{]*\{[^}]*animation-name\s*:\s*fade-out/,
|
||
'Reduced-motion .toast[data-state="closed"] must use fade-out',
|
||
)
|
||
assert.doesNotMatch(
|
||
titleMenus,
|
||
/data-menubar-switch=\{\s*menuState\.id\s*===\s*id\s*&&\s*menuState\.switched/,
|
||
'TitleMenus must not strip data-menubar-switch from the outgoing sibling menu on switch',
|
||
)
|
||
})
|
||
|
||
test('software-composited UI avoids backdrop-filter and slow pre shaping', () => {
|
||
const rawCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8')
|
||
const css = rawCss.replace(/\/\*[\s\S]*?\*\//g, '')
|
||
|
||
// main.go sets WebviewGpuIsDisabled: true (software compositing), where
|
||
// backdrop-filter blurs stall CPU rasterization on animations and scrolling.
|
||
assert.doesNotMatch(
|
||
css,
|
||
/(?:-webkit-)?backdrop-filter\s*:/i,
|
||
'app.css must not apply backdrop-filter under software compositing',
|
||
)
|
||
assert.match(
|
||
css,
|
||
/\.license-pre\s*\{[^}]*contain\s*:\s*content/,
|
||
'.license-pre should isolate scroll/layout repaints with contain: content',
|
||
)
|
||
assert.match(
|
||
css,
|
||
/\.license-pre\s*\{[^}]*text-rendering\s*:\s*auto/,
|
||
'.license-pre should opt out of global optimizeLegibility for long monospace texts',
|
||
)
|
||
})
|
||
|
||
const mod = await loadTestModule(`
|
||
import './i18n/domains/wizard.gen'
|
||
import './i18n/domains/settings.gen'
|
||
import './i18n/domains/plugins.gen'
|
||
export * from './i18n'
|
||
export * from './lib/format'
|
||
export * from './lib/themeEngine'
|
||
`)
|
||
|
||
test('memory sizes use the active locale’s decimal separator', () => {
|
||
assert.equal(mod.formatMemory('16G', 'en-US'), '16 GB')
|
||
assert.equal(mod.formatMemory('1536M', 'de-DE'), '1,5 GB')
|
||
})
|
||
|
||
test('plugin translations can be used without adding a host UI locale', (t) => {
|
||
t.after(() => mod.setPluginLocales([]))
|
||
mod.setPluginLocales([
|
||
{
|
||
locale: 'de-DE',
|
||
label: 'Deutsch',
|
||
fallback: 'en-US',
|
||
has_ui_messages: false,
|
||
messages: {},
|
||
plugin_messages: {
|
||
'acme.de': { 'btn.run': 'Ausführen ({n})' },
|
||
},
|
||
},
|
||
{
|
||
locale: 'ja-JP',
|
||
label: '日本語',
|
||
fallback: 'en-US',
|
||
has_ui_messages: true,
|
||
messages: { sidebarSettings: '設定' },
|
||
plugin_messages: {
|
||
'acme.de': { 'btn.run': '実行 ({n})' },
|
||
},
|
||
},
|
||
])
|
||
|
||
const opts = mod.getLocaleOptions().map((o) => o.value)
|
||
assert.ok(opts.includes('ja-JP'), 'ja-JP language pack should appear in UI options')
|
||
assert.ok(!opts.includes('de-DE'), 'de-DE functional plugin L10n must NOT appear as ghost UI locale')
|
||
assert.equal(mod.resolveActiveLocale('de-DE'), 'en-US')
|
||
assert.equal(mod.resolveActiveLocale('ja-JP'), 'ja-JP')
|
||
assert.equal(mod.t('ja-JP', 'sidebarSettings'), '設定')
|
||
assert.equal(mod.tPlugin('acme.de', 'de-DE', 'btn.run', { n: 3 }), 'Ausführen (3)')
|
||
assert.equal(mod.getPluginMessageBundle('acme.de', 'ja-JP')['btn.run'], '実行 ({n})')
|
||
})
|
||
|
||
test('the pseudo-locale marks host and plugin strings and preserves placeholders', () => {
|
||
const pseudoHost = mod.t('en-XA', 'cores', { n: 8 })
|
||
assert.ok(pseudoHost.startsWith('⟦') && pseudoHost.endsWith('⟧') && pseudoHost.includes('8'), `bad pseudoHost: ${pseudoHost}`)
|
||
const pseudoPlugin = mod.tPlugin('acme.de', 'en-XA', 'btn.run', { n: 5 }, 'Run ({n})')
|
||
assert.ok(pseudoPlugin.startsWith('⟦') && pseudoPlugin.includes('5'), `bad pseudoPlugin: ${pseudoPlugin}`)
|
||
})
|
||
|
||
test('bridge errors preserve their code, summary and diagnostic detail', () => {
|
||
const codedSuffix = mod.parseAppError('First summary line\nSecond summary line [E_VM_BUSY]\n[detail] raw trace line 1\nline 2')
|
||
assert.equal(codedSuffix.code, 'E_VM_BUSY')
|
||
assert.equal(codedSuffix.summary, 'First summary line\nSecond summary line')
|
||
assert.equal(codedSuffix.rawDetail, 'raw trace line 1\nline 2')
|
||
|
||
const codedPrefix = mod.parseAppError('[E_VM_BUSY] First summary line\nSecond summary line\n[detail] raw trace line 1\nline 2')
|
||
assert.equal(codedPrefix.code, 'E_VM_BUSY')
|
||
assert.equal(codedPrefix.summary, 'First summary line\nSecond summary line')
|
||
assert.equal(codedPrefix.rawDetail, 'raw trace line 1\nline 2')
|
||
|
||
const codelessDetail = mod.parseAppError('Human summary without code\n[detail] exit status 1')
|
||
assert.equal(codelessDetail.code, undefined)
|
||
assert.equal(codelessDetail.summary, 'Human summary without code')
|
||
assert.equal(codelessDetail.rawDetail, 'exit status 1')
|
||
|
||
const objErr = mod.parseAppError({ message: 'Timeout [E_NET]' })
|
||
assert.equal(objErr.code, 'E_NET')
|
||
assert.equal(objErr.summary, 'Timeout')
|
||
})
|
||
|
||
test('text direction and guest language presets resolve from locale identifiers', () => {
|
||
for (const rtl of ['ar-SA', 'he-IL', 'iw-IL', 'fa-IR', 'ur-PK', 'ps-AF', 'dv-MV', 'yi']) {
|
||
assert.equal(mod.isRTLLocale(rtl), true, `expected RTL for ${rtl}`)
|
||
}
|
||
assert.equal(mod.isRTLLocale('en-US'), false)
|
||
assert.equal(mod.isRTLLocale('zh-TW'), false)
|
||
|
||
const zhGuest = mod.resolveGuestLang('zh-CN', 'zh-Hans:0')
|
||
assert.ok(zhGuest.label.length > 0 && zhGuest.detail && zhGuest.detail.length > 0)
|
||
})
|
||
|
||
test('theme accents retain WCAG AA contrast on light and dark surfaces', () => {
|
||
const hslContrast = (hslStr, surfaceLum) => {
|
||
const m = hslStr.match(/hsl\(\s*(\d+)\s+(\d+)%\s+(\d+)%\s*\)/)
|
||
assert.ok(m, `unexpected hsl string: ${hslStr}`)
|
||
const h = Number(m[1]), s = Number(m[2]) / 100, l = Number(m[3]) / 100
|
||
const c = (1 - Math.abs(2 * l - 1)) * s
|
||
const hp = (h % 360) / 60
|
||
const x = c * (1 - Math.abs((hp % 2) - 1))
|
||
const [r1, g1, b1] = hp < 1 ? [c, x, 0] : hp < 2 ? [x, c, 0] : hp < 3 ? [0, c, x] : hp < 4 ? [0, x, c] : hp < 5 ? [x, 0, c] : [c, 0, x]
|
||
const mv = l - c / 2
|
||
const lin = (v) => (v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4))
|
||
const lum = 0.2126 * lin(r1 + mv) + 0.7152 * lin(g1 + mv) + 0.0722 * lin(b1 + mv)
|
||
return (Math.max(lum, surfaceLum) + 0.05) / (Math.min(lum, surfaceLum) + 0.05)
|
||
}
|
||
const brightYellow = mod.deriveTokensFromSeeds({ accent: '#ffd60a' }, undefined, 'light')
|
||
assert.equal(brightYellow['--accent-text'], '#1d1d1f')
|
||
assert.ok(hslContrast(brightYellow['--accent-soft-text'], 0.92) >= 4.5, `yellow light contrast too low: ${brightYellow['--accent-soft-text']}`)
|
||
|
||
const pureBlueDark = mod.deriveTokensFromSeeds({ accent: '#0000ff' }, undefined, 'dark')
|
||
assert.ok(hslContrast(pureBlueDark['--accent-soft-text'], 0.015) >= 4.5, `blue dark contrast too low: ${pureBlueDark['--accent-soft-text']}`)
|
||
|
||
const appleBlue = mod.deriveTokensFromSeeds({ accent: '#0071e3' }, undefined, 'dark')
|
||
assert.equal(appleBlue['--accent-text'], '#ffffff')
|
||
assert.ok(hslContrast(appleBlue['--accent-soft-text'], 0.015) >= 4.5, `appleBlue dark contrast too low: ${appleBlue['--accent-soft-text']}`)
|
||
})
|