mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
fix: refresh host-control tokens on late skin CSS, resolve modern colours and refuse skin fonts
- bindHostControlTheme re-applies when <head> stylesheets or root attributes change, so a stored skin id themes the floating recovery capsule, skin-load banner and authorization dialog once its CSS actually arrives; the recovery root pass stands down while a slot binding owns the capsule tokens. - The shadow-root probe converts oklch()/color-mix() results to sRGB via a 1x1 canvas instead of silently dropping them to the default palette. - Host-owned controls ignore font tokens naming a document @font-face, which could ship blank glyphs and erase the recovery/consent labels. - Authorization body text uses the full sanitized foreground (the 76% mix could fall under the 4.5 contrast floor); theme refreshes before showModal. - Browser fixture covers late CSS, oklch and font refusal; docs updated.
This commit is contained in:
1 parent
c1187d12d2
commit
a353c32892
8 files changed
+232
-31
No files matched your search
@@ -501,7 +501,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
| `--skin-recovery-foreground` | 文字色。与背景的对比度必须 ≥ 4.5。 |
|
||||
| `--skin-recovery-border` | 胶囊和普通按钮的边框色。与背景的对比度必须 ≥ 3,否则使用宿主默认边框;不影响固定浅色底的「使用内置皮肤」按钮。 |
|
||||
| `--skin-recovery-radius` | 圆角,只接受 px 长度并限制在 0–999;其他值使用宿主默认 999px。 |
|
||||
| `--skin-recovery-font` | 字体族列表,只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;其他值使用宿主默认字体。 |
|
||||
| `--skin-recovery-font` | 字体族列表,只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;列表中只要出现皮肤用 `@font-face` 注册的字体就整项忽略(只认系统已安装字体和通用族名);其他值使用宿主默认字体。 |
|
||||
| `--skin-recovery-size` | `small`(默认)、`medium` 或 `large`。宿主映射为固定指标:按钮最小命中高度 28 / 32 / 36 px,最小字号 11 / 12 / 13 px;皮肤不能把这些值降到宿主下限以下。 |
|
||||
|
||||
颜色建议使用 `#rgb`、`#rrggbb`、`rgb()` 或 `rgba()`;宿主通过影子根内的探针元素让浏览器解析颜色,再按 WCAG 相对亮度检查对比度。无效、缺失或无法解析的值使用宿主默认颜色(强调色 `#b45309`、背景 `#ffffff`、文字 `#31524f`)。
|
||||
@@ -561,13 +561,13 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
}
|
||||
```
|
||||
|
||||
宿主从计算样式读取这些变量,通过影子根内的探针解析颜色,再写入控件自己的 `--ws-control-*` 变量;皮肤不能写入 Shadow DOM 内部,也不能替换结构令牌。安全底线与其他受保护控件一致:
|
||||
宿主从计算样式读取这些变量,通过影子根内的探针解析颜色(`oklch()`、`color-mix()` 等现代写法会先换算成 sRGB 再检查对比度),再写入控件自己的 `--ws-control-*` 变量;皮肤样式晚于皮肤 ID 加载、运行时插件追加样式时,宿主会自动重新读取,不需要刷新页面。皮肤不能写入 Shadow DOM 内部,也不能替换结构令牌。安全底线与其他受保护控件一致:
|
||||
|
||||
- 背景强制不透明(alpha 视为 1)。
|
||||
- 文字与背景对比度必须 ≥ 4.5,强调色与背景 ≥ 3;任一不达标时整组颜色回退到宿主默认,而不是只改一项。
|
||||
- 边框与背景对比度 ≥ 3,否则使用宿主默认边框。
|
||||
- 圆角只接受 px 并限制上限(恢复胶囊 999px,横幅和授权对话框 64px)。
|
||||
- 字体族只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符。
|
||||
- 字体族只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;只认系统已安装字体和通用族名(`sans-serif` 等)。列表里只要有一个族名来自文档里的 `@font-face`(也就是皮肤自带字体),整项令牌就被忽略,因为自带字体可以把字形做成空白,让宿主控件的文字消失。应用 DOM 内的受保护控件不受此限制,照常可以在 `skin.css` 里用皮肤字体。
|
||||
- `size` 只接受 `small`、`medium`、`large`,并且只能把命中区域/字号调大;恢复胶囊为 28/32/36px 命中区域、11/12/13px 字号,横幅和授权对话框以自身更大的内置尺寸为下限。
|
||||
- 授权对话框的主按钮文字色由宿主根据强调色自动选择黑/白,保证可读。
|
||||
- 恢复胶囊停靠后如果锚点消失、被遮挡或压到其他受保护控件,仍会回退到默认位置;横幅固定在顶部,授权对话框始终是顶层模态框,二者不参与停靠,因此不会因为皮肤布局而找不到。
|
||||
|
||||
@@ -178,11 +178,13 @@ const showRecovery = computed(() => shouldShowRecovery({
|
||||
const shortcutOpen = ref(false);
|
||||
const recoveryPopover = ref<HTMLElement | null>(null);
|
||||
|
||||
let slotBinding: HostSlotBinding | undefined;
|
||||
|
||||
/**
|
||||
* Theme the capsule even when the skin does not declare a slot. `bindHostSlot`
|
||||
* still reads the anchor first when a slot exists; this root-level pass covers
|
||||
* the floating capsule and is overwritten by the anchor values on the next
|
||||
* revalidation.
|
||||
* Theme the capsule even when the skin does not declare a slot. While a slot
|
||||
* binding exists it reads the anchor first and owns the tokens; this
|
||||
* root-level pass covers the slot-less capsule and refreshes itself when the
|
||||
* skin stylesheet arrives after the stored skin id.
|
||||
*/
|
||||
const recoveryTheme = layer ? bindHostControlTheme({
|
||||
layer,
|
||||
@@ -190,6 +192,8 @@ const recoveryTheme = layer ? bindHostControlTheme({
|
||||
part: "host.recovery",
|
||||
defaults: RECOVERY_CONTROL_DEFAULTS,
|
||||
source: () => findSkinRoot(hostChromeActiveSkinId.value),
|
||||
// While a slot binding exists it owns the capsule tokens (anchor first).
|
||||
active: () => !slotBinding,
|
||||
}) : null;
|
||||
|
||||
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
|
||||
@@ -254,7 +258,6 @@ function onRecoveryFocusOut(event: FocusEvent) {
|
||||
compactPinned.value = false;
|
||||
}
|
||||
|
||||
let slotBinding: HostSlotBinding | undefined;
|
||||
function syncSlotBinding() {
|
||||
slotBinding?.dispose();
|
||||
slotBinding = undefined;
|
||||
|
||||
@@ -36,7 +36,7 @@ const AUTHORIZATION_LAYER_CSS = `
|
||||
:host { font: 14px/1.75 system-ui, -apple-system, "Segoe UI", sans-serif; }
|
||||
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid var(--ws-control-border,#dbe3f1);border-radius:var(--ws-control-radius,20px);background:var(--ws-control-background,#fff);color:var(--ws-control-foreground,#25324b);font-family:var(--ws-control-font,system-ui,-apple-system,"Segoe UI",sans-serif);font-size:var(--ws-control-font-size,14px);line-height:1.75;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto;pointer-events:auto}
|
||||
.ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
|
||||
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:var(--ws-control-foreground,#202e49)}.ws-instance-authorization p{margin:12px 0;color:color-mix(in srgb,var(--ws-control-foreground,#25324b) 76%,transparent)}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:color-mix(in srgb,var(--ws-control-accent,#5265df) 14%,var(--ws-control-background,#fff));color:var(--ws-control-accent,#5265df);font-size:28px}
|
||||
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:var(--ws-control-foreground,#202e49)}.ws-instance-authorization p{margin:12px 0;color:var(--ws-control-foreground,#526079)}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:color-mix(in srgb,var(--ws-control-accent,#5265df) 14%,var(--ws-control-background,#fff));color:var(--ws-control-accent,#5265df);font-size:28px}
|
||||
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:color-mix(in srgb,var(--ws-control-foreground,#25324b) 6%,var(--ws-control-background,#fff));border:1px solid var(--ws-control-border,#dce3f3);border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:var(--ws-control-accent,#5265df)}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:var(--ws-control-hit,42px);padding:9px 16px;border:1px solid var(--ws-control-border,#d9e1ef);border-radius:var(--ws-control-radius,10px);background:color-mix(in srgb,var(--ws-control-foreground,#25324b) 6%,var(--ws-control-background,#fff));color:var(--ws-control-foreground,#43516d);font:600 var(--ws-control-font-size,14px)/1.5 var(--ws-control-font,system-ui);cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:var(--ws-control-accent,#5265df);color:var(--ws-control-on-accent,#fff);border-color:var(--ws-control-accent,#5265df)}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid var(--ws-control-accent,#5265df);outline-offset:3px}
|
||||
@media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
|
||||
`;
|
||||
@@ -59,6 +59,7 @@ watch([dialog, hostChromeActiveSkinId], () => { theme?.apply(); }, { flush: 'pos
|
||||
watch(() => props.language, value => { authorizationLanguage.value = value; }, { immediate: true });
|
||||
watch([dialog, authorizationRequested, authorizationDecision], () => {
|
||||
if (!dialog.value || dialog.value.open || (authorizationDecision.value !== null && !authorizationRequested.value)) return;
|
||||
theme?.apply();
|
||||
firstVisit.value = authorizationDecision.value === null;
|
||||
checked.value = authorizationDecision.value === true;
|
||||
dialog.value.showModal();
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
|
||||
applyHostControlTokens,
|
||||
contrastRatio,
|
||||
fontFamilyNames,
|
||||
hasHostControlTokens,
|
||||
hostControlTokenKey,
|
||||
hostControlTokenProperty,
|
||||
@@ -248,3 +249,19 @@ test("WCAG contrast follows the relative-luminance formula", () => {
|
||||
assert.equal(contrastRatio({ r: 12, g: 34, b: 56 }, { r: 12, g: 34, b: 56 }), 1);
|
||||
assert.ok(HOST_CONTROL_MIN_FOREGROUND_CONTRAST > HOST_CONTROL_MIN_ACCENT_CONTRAST);
|
||||
});
|
||||
|
||||
test("host controls ignore fonts registered by a skin @font-face", () => {
|
||||
assert.deepEqual(fontFamilyNames(`"Wave Font", 'Other' , sans-serif`), ["wave font", "other", "sans-serif"]);
|
||||
const webFonts = new Set(["blank glyphs"]);
|
||||
const isWebFont = (family: string) => webFonts.has(family);
|
||||
const resolve = (font: string) => resolveHostControlTokens(
|
||||
style({ "--skin-host-font": font }),
|
||||
"app.skin-load-recovery",
|
||||
raw => raw,
|
||||
SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
|
||||
isWebFont,
|
||||
).font;
|
||||
assert.equal(resolve('"Blank Glyphs", sans-serif'), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
|
||||
assert.equal(resolve("Tahoma, 'blank glyphs'"), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
|
||||
assert.equal(resolve('Tahoma, "Segoe UI", sans-serif'), 'Tahoma, "Segoe UI", sans-serif');
|
||||
});
|
||||
@@ -268,12 +268,20 @@ function sanitizeRadius(value: string | undefined, fallback: number, maxRadius:
|
||||
return Number.isFinite(radius) ? Math.min(maxRadius, Math.max(0, radius)) : fallback;
|
||||
}
|
||||
|
||||
function sanitizeFont(value: string | undefined, fallback: string): string {
|
||||
/** Lower-cased family names from a `font-family` list, quotes removed. */
|
||||
export function fontFamilyNames(value: string): string[] {
|
||||
return value.split(",").map((name) => name.trim().replace(/^["']|["']$/g, "").trim().toLowerCase()).filter(Boolean);
|
||||
}
|
||||
|
||||
function sanitizeFont(value: string | undefined, fallback: string, isWebFont: WebFontCheck): string {
|
||||
if (!value) return fallback;
|
||||
const font = value.trim().replace(/\s+/g, " ");
|
||||
if (!font || font.length > MAX_FONT_LENGTH || !FONT_FAMILY_PATTERN.test(font) || !/[A-Za-z0-9]/.test(font)) {
|
||||
return fallback;
|
||||
}
|
||||
// A skin-supplied @font-face can ship glyph-less outlines and blank the
|
||||
// control's label, so host-owned controls only accept installed/generic fonts.
|
||||
if (fontFamilyNames(font).some(isWebFont)) return fallback;
|
||||
return font;
|
||||
}
|
||||
|
||||
@@ -308,6 +316,9 @@ function mergeRawTokens(...layers: readonly HostControlRawTokens[]): HostControl
|
||||
}
|
||||
|
||||
type ColorProbe = (raw: string | undefined) => string | undefined;
|
||||
/** True when a (lower-cased, unquoted) family is provided by a document @font-face. */
|
||||
type WebFontCheck = (family: string) => boolean;
|
||||
const NO_WEB_FONTS: WebFontCheck = () => false;
|
||||
|
||||
function resolvePalette(
|
||||
raw: HostControlRawTokens,
|
||||
@@ -362,12 +373,14 @@ export function hasHostControlTokens(
|
||||
* unreadable, the resolver retries the global layer and finally the built-in
|
||||
* palette, so a skin can never make a protected control unreadable. The
|
||||
* border is optional and must stay visible against the resolved background.
|
||||
* Fonts registered by the document (skin `@font-face`) are ignored.
|
||||
*/
|
||||
export function resolveHostControlTokens(
|
||||
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
|
||||
part: string,
|
||||
probeColor: ColorProbe,
|
||||
defaults: HostControlDefaults,
|
||||
isWebFont: WebFontCheck = NO_WEB_FONTS,
|
||||
): HostControlTokens {
|
||||
const partTokens = readTokenSet(style, (token) => hostControlTokenProperty(part, token));
|
||||
const globalTokens = readTokenSet(style, (token) => HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES[token]);
|
||||
@@ -399,7 +412,7 @@ export function resolveHostControlTokens(
|
||||
foreground: formatRgb(palette.foreground),
|
||||
border: formatRgb(border),
|
||||
radius: sanitizeRadius(merged.radius, defaults.radius, defaults.maxRadius),
|
||||
font: sanitizeFont(merged.font, defaults.font),
|
||||
font: sanitizeFont(merged.font, defaults.font, isWebFont),
|
||||
size,
|
||||
hitTarget,
|
||||
fontSize,
|
||||
@@ -432,6 +445,11 @@ export interface HostControlThemeBindingOptions {
|
||||
defaults: HostControlDefaults;
|
||||
/** The active skin root (or a slot anchor) to read token values from. */
|
||||
source: () => Element | null;
|
||||
/**
|
||||
* When this returns false another owner (the recovery slot binding) is
|
||||
* writing the control's tokens, so `apply()` leaves them untouched.
|
||||
*/
|
||||
active?: () => boolean;
|
||||
}
|
||||
|
||||
export interface HostControlThemeBinding {
|
||||
@@ -441,13 +459,29 @@ export interface HostControlThemeBinding {
|
||||
|
||||
/**
|
||||
* Bind one host-owned control to the active skin's token set. The returned
|
||||
* binding owns the hidden colour probe and never stores a token value on the
|
||||
* skin side; callers re-apply it when the active skin or the control changes.
|
||||
* binding owns the hidden probe and never stores a token value on the skin
|
||||
* side. Callers re-apply it when the active skin or the control changes; the
|
||||
* binding also re-applies itself when stylesheets in `<head>` or the document
|
||||
* root attributes change, because a stored skin id is known before its CSS
|
||||
* (and therefore its tokens) has been injected.
|
||||
*/
|
||||
export function bindHostControlTheme(options: HostControlThemeBindingOptions): HostControlThemeBinding {
|
||||
let probe: HostControlColorProbe | null = null;
|
||||
return {
|
||||
let probe: HostControlProbe | null = null;
|
||||
let observer: MutationObserver | null = null;
|
||||
const doc = options.layer.shadow.ownerDocument;
|
||||
const win = doc.defaultView;
|
||||
|
||||
// MutationObserver already batches a burst of changes into one callback.
|
||||
// Frames are avoided on purpose: they do not run in background tabs.
|
||||
if (win && typeof win.MutationObserver === "function") {
|
||||
observer = new win.MutationObserver(() => binding.apply());
|
||||
observer.observe(doc.head, { childList: true, subtree: true, characterData: true });
|
||||
observer.observe(doc.documentElement, { attributes: true });
|
||||
}
|
||||
|
||||
const binding: HostControlThemeBinding = {
|
||||
apply() {
|
||||
if (options.active && !options.active()) return;
|
||||
const control = options.control();
|
||||
if (!control) return;
|
||||
const source = options.source();
|
||||
@@ -462,14 +496,20 @@ export function bindHostControlTheme(options: HostControlThemeBindingOptions): H
|
||||
applyHostControlTokens(control, null);
|
||||
return;
|
||||
}
|
||||
probe ??= createHostControlColorProbe(options.layer.shadow);
|
||||
applyHostControlTokens(control, resolveHostControlTokens(style, options.part, probe.probeColor, options.defaults));
|
||||
probe ??= createHostControlProbe(options.layer.shadow);
|
||||
applyHostControlTokens(
|
||||
control,
|
||||
resolveHostControlTokens(style, options.part, probe.probeColor, options.defaults, probe.isWebFont),
|
||||
);
|
||||
},
|
||||
dispose() {
|
||||
observer?.disconnect();
|
||||
observer = null;
|
||||
probe?.dispose();
|
||||
probe = null;
|
||||
},
|
||||
};
|
||||
return binding;
|
||||
}
|
||||
|
||||
/** The active skin root; the token source for controls without a slot anchor. */
|
||||
@@ -480,19 +520,23 @@ export function findSkinRoot(skinId: string | undefined, doc: Document = documen
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface HostControlColorProbe {
|
||||
export interface HostControlProbe {
|
||||
/** Resolve a CSS colour through the browser, inside the closed shadow root. */
|
||||
probeColor(raw: string | undefined): string | undefined;
|
||||
/** True when `family` (lower-cased, unquoted) comes from a document `@font-face`. */
|
||||
isWebFont(family: string): boolean;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A hidden probe element for resolving arbitrary CSS colour syntax (for
|
||||
* example `color-mix()` or `oklch()`) to a concrete `rgb()` value.
|
||||
* A hidden probe for resolving arbitrary CSS colour syntax (for example
|
||||
* `color-mix()` or `oklch()`) to a concrete `rgb()` value, and for spotting
|
||||
* fonts that a skin registered itself.
|
||||
*/
|
||||
export function createHostControlColorProbe(shadow: ShadowRoot): HostControlColorProbe {
|
||||
export function createHostControlProbe(shadow: ShadowRoot): HostControlProbe {
|
||||
const doc = shadow.ownerDocument;
|
||||
const win = doc.defaultView;
|
||||
let canvas: CanvasRenderingContext2D | null | undefined;
|
||||
const element = doc.createElement("span");
|
||||
element.setAttribute("aria-hidden", "true");
|
||||
element.style.cssText = "position:absolute;left:-9999px;top:0;width:0;height:0;visibility:hidden;pointer-events:none;";
|
||||
@@ -507,13 +551,42 @@ export function createHostControlColorProbe(shadow: ShadowRoot): HostControlColo
|
||||
return win.getComputedStyle(element).color;
|
||||
};
|
||||
|
||||
/**
|
||||
* Browsers serialise `oklch()`, `lab()` and most `color-mix()` results in
|
||||
* their own colour space instead of `rgb()`. Paint those into a 1×1 canvas
|
||||
* to get sRGB channels the contrast check understands.
|
||||
*/
|
||||
const toRgb = (computed: string): string | undefined => {
|
||||
if (parseCssColor(computed)) return computed;
|
||||
if (canvas === undefined) {
|
||||
canvas = doc.createElement("canvas").getContext("2d", { willReadFrequently: true });
|
||||
if (canvas) canvas.canvas.width = canvas.canvas.height = 1;
|
||||
}
|
||||
if (!canvas) return undefined;
|
||||
canvas.clearRect(0, 0, 1, 1);
|
||||
canvas.fillStyle = "#000";
|
||||
canvas.fillStyle = computed;
|
||||
canvas.fillRect(0, 0, 1, 1);
|
||||
const [r, g, b] = canvas.getImageData(0, 0, 1, 1).data;
|
||||
return formatRgb({ r, g, b });
|
||||
};
|
||||
|
||||
return {
|
||||
probeColor(raw) {
|
||||
if (!raw) return undefined;
|
||||
const first = resolveWith(raw, "rgb(1, 2, 3)");
|
||||
if (first !== "rgb(1, 2, 3)") return first;
|
||||
if (first !== "rgb(1, 2, 3)") return first === undefined ? undefined : toRgb(first);
|
||||
const second = resolveWith(raw, "rgb(4, 5, 6)");
|
||||
return second === "rgb(4, 5, 6)" ? undefined : second;
|
||||
return second === undefined || second === "rgb(4, 5, 6)" ? undefined : toRgb(second);
|
||||
},
|
||||
isWebFont(family) {
|
||||
const fonts = doc.fonts;
|
||||
if (!fonts) return false;
|
||||
let found = false;
|
||||
fonts.forEach((face) => {
|
||||
if (!found && fontFamilyNames(face.family).includes(family)) found = true;
|
||||
});
|
||||
return found;
|
||||
},
|
||||
dispose() {
|
||||
element.remove();
|
||||
|
||||
@@ -20,11 +20,11 @@ import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
|
||||
import {
|
||||
RECOVERY_CONTROL_DEFAULTS,
|
||||
applyHostControlTokens,
|
||||
createHostControlColorProbe,
|
||||
createHostControlProbe,
|
||||
findSkinRoot,
|
||||
resolveHostControlTokens,
|
||||
type HostControlTokens,
|
||||
type HostControlColorProbe,
|
||||
type HostControlProbe,
|
||||
} from "./host-control-tokens.js";
|
||||
|
||||
export interface SlotViewport {
|
||||
@@ -338,7 +338,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
|
||||
let lastReason: SlotFailureReason | undefined;
|
||||
let currentAnchor: HTMLElement | null = null;
|
||||
let observer: ResizeObserver | null = null;
|
||||
const colorProbe: HostControlColorProbe = createHostControlColorProbe(layer.shadow);
|
||||
const probe: HostControlProbe = createHostControlProbe(layer.shadow);
|
||||
let frame: number | undefined;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let disposed = false;
|
||||
@@ -349,12 +349,12 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
|
||||
const cancelFrame = (handle: number): void => win.cancelAnimationFrame(handle);
|
||||
|
||||
function readTokens(source: Element | null): HostControlTokens {
|
||||
if (!source) return resolveHostControlTokens(null, "host.recovery", colorProbe.probeColor, RECOVERY_CONTROL_DEFAULTS);
|
||||
return resolveHostControlTokens(
|
||||
win.getComputedStyle(source),
|
||||
source ? win.getComputedStyle(source) : null,
|
||||
"host.recovery",
|
||||
colorProbe.probeColor,
|
||||
probe.probeColor,
|
||||
RECOVERY_CONTROL_DEFAULTS,
|
||||
probe.isWebFont,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -531,7 +531,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
|
||||
win.removeEventListener("scroll", schedule, { capture: true });
|
||||
clearPlacement();
|
||||
applyHostControlTokens(control, null);
|
||||
colorProbe.dispose();
|
||||
probe.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Host control theme fixture</title>
|
||||
<style>
|
||||
html, body { margin: 0; font: 12px/1.5 system-ui, sans-serif; }
|
||||
/* A skin-registered font: host-owned controls must refuse it. */
|
||||
@font-face { font-family: "Blank Glyphs"; src: url(data:font/woff2;base64,AAAA); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="ws-skin-root" data-ws-skin="community.theme-fixture" data-ws-part="app"></div>
|
||||
<pre id="result">pending</pre>
|
||||
<script type="module">
|
||||
import { createHostOwnedLayer } from "/src/services/host-owned-layer.ts";
|
||||
import { SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS, bindHostControlTheme, findSkinRoot } from "/src/services/host-control-tokens.ts";
|
||||
|
||||
const output = document.getElementById("result");
|
||||
const frames = () => new Promise((resolve) => setTimeout(resolve, 120));
|
||||
const addSkinStyle = (css) => {
|
||||
const style = document.createElement("style");
|
||||
style.textContent = css;
|
||||
document.head.append(style);
|
||||
return style;
|
||||
};
|
||||
|
||||
(async () => {
|
||||
const layer = createHostOwnedLayer("theme-fixture", `.banner { background: var(--ws-control-background, #fffbeb); color: var(--ws-control-foreground, #78350f); font-family: var(--ws-control-font, serif); }`);
|
||||
const control = document.createElement("section");
|
||||
control.className = "banner";
|
||||
control.textContent = "Use built-in skin";
|
||||
layer.container.append(control);
|
||||
const theme = bindHostControlTheme({
|
||||
layer,
|
||||
control: () => control,
|
||||
part: "app.skin-load-recovery",
|
||||
defaults: SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
|
||||
source: () => findSkinRoot("community.theme-fixture"),
|
||||
});
|
||||
const snap = (name) => ({
|
||||
name,
|
||||
inlineBackground: control.style.getPropertyValue("--ws-control-background"),
|
||||
inlineFont: control.style.getPropertyValue("--ws-control-font"),
|
||||
background: getComputedStyle(control).backgroundColor,
|
||||
});
|
||||
const results = [];
|
||||
|
||||
// The stored skin id is known before its stylesheet arrives.
|
||||
theme.apply();
|
||||
results.push(snap("before-skin-css"));
|
||||
|
||||
// Late skin CSS: oklch() background must resolve to sRGB and theme the banner
|
||||
// without any caller re-applying the binding.
|
||||
addSkinStyle(`.ws-skin-root { --skin-host-background: oklch(0.25 0.05 250); --skin-host-foreground: #ffffff; --skin-host-accent: #47dcc4; --skin-host-font: "Blank Glyphs", sans-serif; }`);
|
||||
await frames();
|
||||
results.push(snap("late-skin-css"));
|
||||
|
||||
addSkinStyle(`.ws-skin-root { --skin-host-font: Tahoma, "Segoe UI", sans-serif; }`);
|
||||
await frames();
|
||||
results.push(snap("system-font"));
|
||||
|
||||
theme.dispose();
|
||||
addSkinStyle(`.ws-skin-root { --skin-host-background: #ffffff; --skin-host-foreground: #111111; }`);
|
||||
await frames();
|
||||
results.push(snap("after-dispose"));
|
||||
|
||||
output.textContent = JSON.stringify({ results });
|
||||
})().catch((error) => {
|
||||
output.textContent = JSON.stringify({ error: String(error && error.stack || error) });
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -169,7 +169,7 @@ test("the public-skin composable opts in only through chrome.json#visibleParts",
|
||||
assert.doesNotMatch(usePublicSkin, /\.test\(skin\.css\)/);
|
||||
});
|
||||
|
||||
async function dumpDom(url) {
|
||||
async function dumpDom(url, extraArgs = []) {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(CHROME, [
|
||||
"--headless=new",
|
||||
@@ -177,6 +177,7 @@ async function dumpDom(url) {
|
||||
"--disable-gpu",
|
||||
"--disable-dev-shm-usage",
|
||||
"--hide-scrollbars",
|
||||
...extraArgs,
|
||||
"--dump-dom",
|
||||
url,
|
||||
], { stdio: ["ignore", "pipe", "pipe"] });
|
||||
@@ -301,3 +302,34 @@ test("a declared slot docks the capsule and falls back at runtime", { skip: !CHR
|
||||
assert.equal(byName.disposed.atDefaultCorner, true);
|
||||
assert.equal(byName.disposed.leftoverAccent, "");
|
||||
});
|
||||
|
||||
test("host control tokens follow late skin CSS, resolve modern colours and refuse skin fonts", { skip: !CHROME && "google-chrome is not installed" }, async (t) => {
|
||||
const server = await createServer({
|
||||
root: webRoot,
|
||||
configFile: path.join(webRoot, "vite.config.ts"),
|
||||
logLevel: "silent",
|
||||
server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false, ws: false },
|
||||
});
|
||||
t.after(() => server.close());
|
||||
await server.listen();
|
||||
const address = server.httpServer?.address();
|
||||
const port = address && typeof address === "object" ? address.port : 0;
|
||||
assert.ok(port, "Vite did not expose a listening port");
|
||||
|
||||
// The fixture awaits animation frames, so give headless Chrome virtual time.
|
||||
const dom = await dumpDom(`http://127.0.0.1:${port}/test/fixtures/host-control-theme.html`, ["--virtual-time-budget=10000"]);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, "the fixture did not emit a result block");
|
||||
const payload = JSON.parse(match[1].replace(/"/g, '"').replace(/&/g, "&"));
|
||||
assert.equal(payload.error, undefined, payload.error);
|
||||
const byName = Object.fromEntries(payload.results.map((result) => [result.name, result]));
|
||||
|
||||
assert.equal(byName["before-skin-css"].inlineBackground, "", "tokens were applied before the skin declared any");
|
||||
const late = byName["late-skin-css"];
|
||||
assert.match(late.inlineBackground, /^rgb\(\d+, \d+, \d+\)$/, "late skin CSS did not re-theme the control");
|
||||
assert.notEqual(late.inlineBackground, "rgb(255, 251, 235)", "the oklch() background fell back to the default palette");
|
||||
assert.equal(late.background, late.inlineBackground);
|
||||
assert.equal(late.inlineFont, "ui-sans-serif, system-ui, sans-serif", "a skin @font-face reached a host-owned control");
|
||||
assert.equal(byName["system-font"].inlineFont, 'Tahoma, "Segoe UI", sans-serif');
|
||||
assert.equal(byName["after-dispose"].inlineBackground, late.inlineBackground, "a disposed binding kept observing the document");
|
||||
});
|
||||
Reference in new issue
Block a user