mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-02 19:42:51 +08:00
fix: move floating host controls off skin controls at runtime
The recovery capsule and the fallback application-library launcher float in fixed viewport corners. In v0.3.2 that already covered the microphone in the Persona/host-chrome skins, the whole Harbor audio dock, the Cancel/Create buttons of mobile bottom sheets and a Send button behind the launcher. Add host-floating-placement: every 400 ms (and shortly after each click) the host samples the skin's visible, topmost interactive controls and moves the floating control to the least-covering corner/edge position, weighting protected parts and open dialogs higher, avoiding the other host floating control, and folding the capsule to its mark when every position collides. It never moves under the pointer or focus and leaves a docked (slotted) capsule to the slot binding. Runtime only: no new skin.css restriction.
This commit is contained in:
1 parent
0df25e4892
commit
e46d7a0eb7
9 files changed
+629
-7
No files matched your search
@@ -492,6 +492,8 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
|
||||
**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊位于顶层,会挡住它下面的一切,因此宿主还会检查胶囊的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
|
||||
|
||||
**浮动位置的运行时避让。** 没有停靠(未声明 `slots`,或锚点回退)时,恢复胶囊默认在左下角;宿主约每 400 ms(以及每次点击后约 150 ms)检查一次它是否盖住了皮肤里可见、处于最上层的可交互控件(按钮、链接、输入框等;禁用的“发送”按钮也算,受保护部件和打开的对话框/底部弹层里的控件权重更高)。盖住时,胶囊会换到左下、右下、左上、右上、左中、右中、底部居中、顶部居中里遮挡最少的位置;处处都会遮挡时,收成只显示 ◈ 的紧凑形态(悬停、聚焦或点按展开)。鼠标悬停或焦点在胶囊内时不会移动。宿主自带的应用库悬浮按钮(皮肤没有提供 `voice.plugin-launcher` 挂载点时出现在右下角)使用同一套避让,两者也互相避开。这同样只是运行时行为,不新增任何 `skin.css` 编译期限制;皮肤作者无需为它做任何事,但如果希望胶囊固定在设计好的位置,仍建议用 `slots` 停靠。
|
||||
|
||||
**样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。
|
||||
|
||||
| 令牌 | 规则 |
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/test/host-chrome-recovery.test.mjs",
|
||||
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs",
|
||||
"verify": "npm test && npm run build && npm run web:build",
|
||||
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
|
||||
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
@focusout="onRecoveryFocusOut"
|
||||
class="ws-host-recovery"
|
||||
:class="{ 'ws-host-recovery-compact': compact }"
|
||||
:data-ws-float="slotMode === 'slotted' ? undefined : floatPosition"
|
||||
:tabindex="compact || compactPinned ? 0 : undefined"
|
||||
data-ws-host-recovery
|
||||
role="region"
|
||||
@@ -83,6 +84,11 @@ import {
|
||||
type HostOwnedLayer,
|
||||
} from "../services/host-owned-layer.js";
|
||||
import { bindHostSlot, type HostSlotBinding } from "../services/host-slot-placement.js";
|
||||
import {
|
||||
bindFloatingAvoidance,
|
||||
type FloatingAvoidance,
|
||||
type FloatingPosition,
|
||||
} from "../services/host-floating-placement.js";
|
||||
import { shouldShowRecovery } from "../services/host-chrome-visibility.js";
|
||||
import { thirdPartyAllowed } from "../services/instance-authorization.js";
|
||||
import {
|
||||
@@ -117,6 +123,13 @@ const RECOVERY_LAYER_CSS = `
|
||||
pointer-events: auto;
|
||||
}
|
||||
.ws-host-recovery:popover-open { display: flex; }
|
||||
/* Runtime collision avoidance (host-floating-placement.ts): when the default
|
||||
corner would cover a skin control, the floating capsule moves. A docked
|
||||
(slotted) capsule carries no data-ws-float and uses inline placement. */
|
||||
.ws-host-recovery[data-ws-float$="right"] { left: auto; right: max(12px, env(safe-area-inset-right)); }
|
||||
.ws-host-recovery[data-ws-float^="top"] { bottom: auto; top: max(12px, env(safe-area-inset-top)); }
|
||||
.ws-host-recovery[data-ws-float^="middle"] { bottom: auto; top: 50%; translate: 0 -50%; }
|
||||
.ws-host-recovery[data-ws-float$="center"] { left: 50%; translate: -50% 0; }
|
||||
.ws-host-recovery-mark {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -231,11 +244,19 @@ const shortcutExpanded = ref(false);
|
||||
/** A tap/click on the compact mark keeps it expanded (no hover on touch). */
|
||||
const compactPinned = ref(false);
|
||||
|
||||
const compact = computed(() => Boolean(slotConfig.value?.compact)
|
||||
&& slotMode.value === "slotted"
|
||||
&& !compactHold.value
|
||||
&& !shortcutExpanded.value
|
||||
&& !compactPinned.value);
|
||||
/**
|
||||
* Floating (not docked) capsule: corner chosen at runtime so it does not cover
|
||||
* skin controls, and folded to its mark when every corner collides.
|
||||
*/
|
||||
const floatPosition = ref<FloatingPosition>("bottom-left");
|
||||
const floatCompact = ref(false);
|
||||
let floatingAvoidance: FloatingAvoidance | undefined;
|
||||
|
||||
const compact = computed(() => !shortcutExpanded.value
|
||||
&& !compactPinned.value
|
||||
&& (slotMode.value === "slotted"
|
||||
? Boolean(slotConfig.value?.compact) && !compactHold.value
|
||||
: floatCompact.value));
|
||||
|
||||
function onRecoveryEscape() {
|
||||
shortcutOpen.value = false;
|
||||
@@ -279,6 +300,33 @@ function syncSlotBinding() {
|
||||
});
|
||||
}
|
||||
|
||||
function bindFloating() {
|
||||
floatingAvoidance?.dispose();
|
||||
floatingAvoidance = undefined;
|
||||
const control = recoveryPopover.value;
|
||||
if (!control || !layer) return;
|
||||
const host = layer.host;
|
||||
floatingAvoidance = bindFloatingAvoidance({
|
||||
element: control,
|
||||
isSelf: node => node === host || host.contains(node),
|
||||
margins: { top: 12, right: 12, bottom: 38, left: 12 },
|
||||
defaultPosition: "bottom-left",
|
||||
apply: next => { floatPosition.value = next; },
|
||||
compactSize: () => {
|
||||
const hit = Number.parseFloat(getComputedStyle(control).getPropertyValue("--ws-control-hit")) || 28;
|
||||
return { width: hit + 10, height: hit + 10 };
|
||||
},
|
||||
onCompactChange: next => { floatCompact.value = next; },
|
||||
// Never move the capsule under the user's pointer or focus, and leave a
|
||||
// docked capsule to the slot binding.
|
||||
paused: () => slotMode.value === "slotted"
|
||||
|| shortcutExpanded.value
|
||||
|| compactPinned.value
|
||||
|| control.matches(":hover")
|
||||
|| Boolean(layer.shadow.activeElement),
|
||||
});
|
||||
}
|
||||
|
||||
function syncPopover() {
|
||||
syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
|
||||
}
|
||||
@@ -318,6 +366,7 @@ watch([recoveryVisible, recoveryPopover], () => {
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
slotBinding?.revalidate();
|
||||
floatingAvoidance?.revalidate();
|
||||
});
|
||||
}, { flush: "post" });
|
||||
watch([recoveryPopover, hostChromeActiveSkinId], () => {
|
||||
@@ -340,12 +389,14 @@ onMounted(() => {
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
syncSlotBinding();
|
||||
bindFloating();
|
||||
});
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
if (reachabilityTimer) clearInterval(reachabilityTimer);
|
||||
if (compactHoldTimer) clearTimeout(compactHoldTimer);
|
||||
slotBinding?.dispose();
|
||||
floatingAvoidance?.dispose();
|
||||
recoveryTheme?.dispose();
|
||||
window.removeEventListener("resize", refreshLauncherReachability);
|
||||
window.removeEventListener("keydown", onKeydown, true);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<Teleport :to="toolbarTarget ?? 'body'">
|
||||
<div v-if="thirdPartyAllowed && connected && sessionToken" ref="toolbar" class="ws-plugin-toolbar" :class="{ 'ws-plugin-toolbar-fallback': !toolbarTarget }" data-ws-part="voice.plugin-launcher" :data-presentation="presentation" :data-theme="theme" @keydown.esc="dismissDrawer">
|
||||
<div v-if="thirdPartyAllowed && connected && sessionToken" ref="toolbar" class="ws-plugin-toolbar" :class="{ 'ws-plugin-toolbar-fallback': !toolbarTarget }" :data-ws-float="toolbarTarget ? undefined : fallbackPosition" data-ws-part="voice.plugin-launcher" :data-presentation="presentation" :data-theme="theme" @keydown.esc="dismissDrawer">
|
||||
<button v-if="!isHostPartHidden('host.plugins.launcher')" ref="launcher" class="header-action ws-plugin-toolbar-trigger" data-ws-part="host.plugins.launcher" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="presentation === 'dialog' ? visible : drawerOpen" :aria-controls="drawerOpen ? drawerId : undefined" @click="toggle">
|
||||
<svg viewBox="0 0 24 24" data-ws-icon-slot="host.plugins.launcher" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
|
||||
<span v-if="presentation === 'drawer-side'">{{ tr('title') }}</span>
|
||||
@@ -70,12 +70,17 @@ import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
import { thirdPartyAllowed } from '../services/instance-authorization.js';
|
||||
import { isHostPartHidden, isHostPartVisuallyReachable, pluginLibraryRequests } from '../services/host-chrome.js';
|
||||
import type { SkinPluginWidgetOptions } from '../../../src/shared/skin-plugin.js';
|
||||
import { bindFloatingAvoidance, type FloatingAvoidance, type FloatingPosition } from '../services/host-floating-placement.js';
|
||||
const props = defineProps<{ sessionToken: string; gatewayUrl: string; connected: boolean; language: SiteLanguage; toolbarTarget: HTMLElement | null; presentation: NonNullable<SkinPluginWidgetOptions['pluginPresentation']> }>();
|
||||
const tr = (key: PluginTextKey) => pluginTranslations[props.language][key];
|
||||
const ui = computed(() => pluginWindowTranslations[props.language]);
|
||||
const windowElement = ref<HTMLElement | null>(null), launcher = ref<HTMLButtonElement | null>(null), frame = ref<HTMLIFrameElement | null>(null);
|
||||
const available = shallowRef<AvailablePluginApp[]>([]), current = shallowRef<PluginAppLaunch | null>(null);
|
||||
const toolbar = ref<HTMLElement | null>(null);
|
||||
// The fallback toolbar floats in a viewport corner the skin knows nothing
|
||||
// about; move it off any skin control it would cover (runtime only).
|
||||
const fallbackPosition = ref<FloatingPosition>('bottom-right');
|
||||
let fallbackAvoidance: FloatingAvoidance | undefined;
|
||||
const drawerOpen = ref(false);
|
||||
const drawer = ref<HTMLElement | null>(null);
|
||||
const drawerSearch = ref<HTMLInputElement | null>(null);
|
||||
@@ -227,6 +232,21 @@ watch(pluginLibraryRequests, () => {
|
||||
if (props.presentation !== 'dialog' && isHostPartVisuallyReachable('host.plugins.launcher')) openDrawer();
|
||||
else openLibraryDialog();
|
||||
});
|
||||
watch([toolbar, () => props.toolbarTarget], ([element, target]) => {
|
||||
fallbackAvoidance?.dispose();
|
||||
fallbackAvoidance = undefined;
|
||||
fallbackPosition.value = 'bottom-right';
|
||||
if (!element || target) return;
|
||||
fallbackAvoidance = bindFloatingAvoidance({
|
||||
element,
|
||||
isSelf: node => element.contains(node),
|
||||
margins: { top: 16, right: 16, bottom: 16, left: 16 },
|
||||
defaultPosition: 'bottom-right',
|
||||
apply: next => { fallbackPosition.value = next; },
|
||||
paused: () => drawerOpen.value || element.matches(':hover') || element.contains(document.activeElement),
|
||||
});
|
||||
}, { flush: 'post' });
|
||||
onBeforeUnmount(() => { fallbackAvoidance?.dispose(); fallbackAvoidance = undefined; });
|
||||
onMounted(() => {
|
||||
document.addEventListener('pointerdown', closeDrawerOutside, true);
|
||||
window.addEventListener('resize', fitDrawer);
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
FLOATING_WEIGHT_CONTROL,
|
||||
FLOATING_WEIGHT_DIALOG,
|
||||
FLOATING_WEIGHT_PROTECTED,
|
||||
chooseFloatingPosition,
|
||||
floatingRect,
|
||||
floatingScore,
|
||||
type FloatingObstacle,
|
||||
} from "./host-floating-placement.js";
|
||||
import type { HostPartRect } from "./host-chrome-visibility.js";
|
||||
|
||||
const rect = (left: number, top: number, width: number, height: number): HostPartRect => ({
|
||||
left, top, width, height, right: left + width, bottom: top + height,
|
||||
});
|
||||
const viewport = { width: 1280, height: 800 };
|
||||
const margins = { top: 12, right: 12, bottom: 38, left: 12 };
|
||||
const capsule = { width: 200, height: 38 };
|
||||
|
||||
test("floating rects follow the corner margins and stay inside the viewport", () => {
|
||||
assert.deepEqual(floatingRect("bottom-left", capsule, viewport, margins), rect(12, 724, 200, 38));
|
||||
assert.deepEqual(floatingRect("bottom-right", capsule, viewport, margins), rect(1068, 724, 200, 38));
|
||||
assert.deepEqual(floatingRect("top-left", capsule, viewport, margins), rect(12, 12, 200, 38));
|
||||
assert.deepEqual(floatingRect("middle-right", capsule, viewport, margins), rect(1068, 381, 200, 38));
|
||||
assert.deepEqual(floatingRect("bottom-center", capsule, viewport, margins), rect(540, 724, 200, 38));
|
||||
// A control wider than a phone viewport is clamped to x = 0, never off-screen.
|
||||
const narrow = floatingRect("bottom-right", { width: 500, height: 38 }, { width: 390, height: 844 }, margins);
|
||||
assert.equal(narrow.left, 0);
|
||||
assert.ok(narrow.bottom <= 844);
|
||||
});
|
||||
|
||||
test("score is zero without overlap, ignores 1px brushes and weights protected/dialog controls", () => {
|
||||
const footprint = rect(12, 724, 200, 38);
|
||||
assert.equal(floatingScore(footprint, [{ rect: rect(400, 400, 40, 40), weight: 1 }]), 0);
|
||||
assert.equal(floatingScore(footprint, [{ rect: rect(211, 724, 40, 38), weight: 1 }]), 0);
|
||||
const control = floatingScore(footprint, [{ rect: rect(150, 730, 34, 34), weight: FLOATING_WEIGHT_CONTROL }]);
|
||||
const protectedPart = floatingScore(footprint, [{ rect: rect(150, 730, 34, 34), weight: FLOATING_WEIGHT_PROTECTED }]);
|
||||
const dialog = floatingScore(footprint, [{ rect: rect(150, 730, 34, 34), weight: FLOATING_WEIGHT_DIALOG }]);
|
||||
assert.ok(control > 0 && protectedPart > control && dialog > protectedPart);
|
||||
});
|
||||
|
||||
test("the default corner is kept while it is free", () => {
|
||||
const choice = chooseFloatingPosition({ current: "bottom-left", size: capsule, viewport, margins, obstacles: [] });
|
||||
assert.deepEqual(choice, { position: "bottom-left", score: 0 });
|
||||
});
|
||||
|
||||
test("a capsule over the microphone moves to the first free corner", () => {
|
||||
// Persona-style dock: microphone at x≈226 under the default capsule.
|
||||
const obstacles: FloatingObstacle[] = [
|
||||
{ rect: rect(209, 738, 34, 34), weight: FLOATING_WEIGHT_PROTECTED },
|
||||
// Something in the bottom-right corner too (chat composer send button).
|
||||
{ rect: rect(1200, 730, 40, 40), weight: FLOATING_WEIGHT_CONTROL },
|
||||
];
|
||||
const choice = chooseFloatingPosition({ current: "bottom-left", size: capsule, viewport, margins, obstacles });
|
||||
assert.equal(choice.position, "top-left");
|
||||
assert.equal(choice.score, 0);
|
||||
});
|
||||
|
||||
test("when every position collides, the least harmful one wins and dialogs dominate", () => {
|
||||
const mobile = { width: 390, height: 844 };
|
||||
const wide = { width: 250, height: 38 };
|
||||
// Bottom sheet: Cancel (left) and Enter (right) inside a dialog; header
|
||||
// controls at the top are ordinary controls.
|
||||
const obstacles: FloatingObstacle[] = [
|
||||
{ rect: rect(20, 780, 190, 44), weight: FLOATING_WEIGHT_DIALOG },
|
||||
{ rect: rect(228, 780, 140, 44), weight: FLOATING_WEIGHT_DIALOG },
|
||||
{ rect: rect(0, 0, 390, 70), weight: FLOATING_WEIGHT_CONTROL },
|
||||
{ rect: rect(0, 380, 390, 90), weight: FLOATING_WEIGHT_CONTROL },
|
||||
];
|
||||
const choice = chooseFloatingPosition({ current: "bottom-left", size: wide, viewport: mobile, margins, obstacles });
|
||||
assert.ok(!choice.position.startsWith("bottom"), choice.position);
|
||||
assert.ok(choice.score > 0 && choice.score < FLOATING_WEIGHT_DIALOG);
|
||||
});
|
||||
|
||||
test("ties keep the current position (no flapping between equal corners)", () => {
|
||||
const obstacles: FloatingObstacle[] = [{ rect: rect(0, 0, 1280, 800), weight: 1 }];
|
||||
const choice = chooseFloatingPosition({ current: "top-right", size: capsule, viewport, margins, obstacles });
|
||||
assert.equal(choice.position, "top-right");
|
||||
});
|
||||
@@ -0,0 +1,322 @@
|
||||
/**
|
||||
* Runtime collision avoidance for host-owned floating controls.
|
||||
*
|
||||
* The recovery capsule (closed-shadow top layer) and the fallback application
|
||||
* library launcher float in a fixed viewport corner. Neither knows the active
|
||||
* skin's layout, so a skin that puts its own audio dock, chat composer or a
|
||||
* dialog's buttons in that corner used to lose those controls under the host
|
||||
* control: v0.3.2 already covered the microphone in the Persona skins, the
|
||||
* whole Harbor audio dock and the "Cancel" button of the mobile channel
|
||||
* password sheet.
|
||||
*
|
||||
* This module never restricts what a skin may do. It samples the skin's
|
||||
* visible interactive controls at runtime and moves the host control to the
|
||||
* candidate position that covers the fewest of them (protected parts and
|
||||
* controls inside an open dialog count more). When every position collides,
|
||||
* the caller may fall back to a compact footprint. The host control stays in
|
||||
* the viewport and stays clickable in every position; only its corner changes.
|
||||
*/
|
||||
|
||||
import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
|
||||
import type { HostPartRect } from "./host-chrome-visibility.js";
|
||||
|
||||
export const FLOATING_POSITIONS = [
|
||||
"bottom-left",
|
||||
"bottom-right",
|
||||
"top-left",
|
||||
"top-right",
|
||||
"middle-left",
|
||||
"middle-right",
|
||||
"bottom-center",
|
||||
"top-center",
|
||||
] as const;
|
||||
|
||||
export type FloatingPosition = typeof FLOATING_POSITIONS[number];
|
||||
|
||||
export interface FloatingMargins {
|
||||
top: number;
|
||||
right: number;
|
||||
bottom: number;
|
||||
left: number;
|
||||
}
|
||||
|
||||
export interface FloatingObstacle {
|
||||
rect: HostPartRect;
|
||||
/** Higher weight = worse to cover (protected part, open dialog, other host control). */
|
||||
weight: number;
|
||||
}
|
||||
|
||||
export interface FloatingSize {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface FloatingViewport {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Interval of the runtime re-check while the control is shown. */
|
||||
export const HOST_FLOATING_INTERVAL_MS = 400;
|
||||
/** Extra re-check shortly after a click, which is what usually opens a dialog or sheet. */
|
||||
export const HOST_FLOATING_AFTER_CLICK_MS = 150;
|
||||
/** Obstacle weights. */
|
||||
export const FLOATING_WEIGHT_CONTROL = 1;
|
||||
export const FLOATING_WEIGHT_PROTECTED = 4;
|
||||
export const FLOATING_WEIGHT_DIALOG = 8;
|
||||
export const FLOATING_WEIGHT_HOST = 8;
|
||||
|
||||
/** Rect a control of `size` would occupy at `position`. */
|
||||
export function floatingRect(
|
||||
position: FloatingPosition,
|
||||
size: FloatingSize,
|
||||
viewport: FloatingViewport,
|
||||
margins: FloatingMargins,
|
||||
): HostPartRect {
|
||||
const width = Math.max(0, size.width);
|
||||
const height = Math.max(0, size.height);
|
||||
let left: number;
|
||||
if (position.endsWith("left")) left = margins.left;
|
||||
else if (position.endsWith("right")) left = viewport.width - margins.right - width;
|
||||
else left = (viewport.width - width) / 2;
|
||||
let top: number;
|
||||
if (position.startsWith("top")) top = margins.top;
|
||||
else if (position.startsWith("bottom")) top = viewport.height - margins.bottom - height;
|
||||
else top = (viewport.height - height) / 2;
|
||||
// Never leave the viewport, even on a viewport narrower than the control.
|
||||
left = Math.max(0, Math.min(left, viewport.width - width));
|
||||
top = Math.max(0, Math.min(top, viewport.height - height));
|
||||
return { left, top, width, height, right: left + width, bottom: top + height };
|
||||
}
|
||||
|
||||
function overlapArea(first: HostPartRect, second: HostPartRect): number {
|
||||
const width = Math.min(first.right, second.right) - Math.max(first.left, second.left);
|
||||
const height = Math.min(first.bottom, second.bottom) - Math.max(first.top, second.top);
|
||||
// A one-pixel brush (shadow, border) is not a collision.
|
||||
return width > 1 && height > 1 ? width * height : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collision score of a footprint: for every obstacle, the covered fraction of
|
||||
* that obstacle times its weight. Zero means nothing interactive is covered.
|
||||
*/
|
||||
export function floatingScore(footprint: HostPartRect, obstacles: readonly FloatingObstacle[]): number {
|
||||
let score = 0;
|
||||
for (const obstacle of obstacles) {
|
||||
const area = obstacle.rect.width * obstacle.rect.height;
|
||||
if (!(area > 0)) continue;
|
||||
const covered = overlapArea(footprint, obstacle.rect);
|
||||
if (covered > 0) score += obstacle.weight * Math.min(1, covered / area + 0.25);
|
||||
}
|
||||
return score;
|
||||
}
|
||||
|
||||
export interface FloatingChoice {
|
||||
position: FloatingPosition;
|
||||
score: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep `current` while it is collision-free; otherwise take the position with
|
||||
* the lowest score (ties keep `current`, then follow `FLOATING_POSITIONS`
|
||||
* order so the default corner wins whenever it is as good as any other).
|
||||
*/
|
||||
export function chooseFloatingPosition(input: {
|
||||
current: FloatingPosition;
|
||||
size: FloatingSize;
|
||||
viewport: FloatingViewport;
|
||||
margins: FloatingMargins;
|
||||
obstacles: readonly FloatingObstacle[];
|
||||
positions?: readonly FloatingPosition[];
|
||||
}): FloatingChoice {
|
||||
const positions = input.positions ?? FLOATING_POSITIONS;
|
||||
const scoreAt = (position: FloatingPosition) => floatingScore(
|
||||
floatingRect(position, input.size, input.viewport, input.margins),
|
||||
input.obstacles,
|
||||
);
|
||||
const currentScore = scoreAt(input.current);
|
||||
if (currentScore === 0) return { position: input.current, score: 0 };
|
||||
let best: FloatingChoice = { position: input.current, score: currentScore };
|
||||
for (const position of positions) {
|
||||
if (position === input.current) continue;
|
||||
const score = scoreAt(position);
|
||||
if (score < best.score - 1e-6) best = { position, score };
|
||||
if (best.score === 0) break;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* DOM binding
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
const INTERACTIVE_SELECTOR = "a[href],button,input:not([type='hidden']),select,textarea,summary,[role='button'],[role='tab'],[role='menuitem'],[role='link'],[contenteditable='true']";
|
||||
const DIALOG_SELECTOR = "dialog[open],[role='dialog'],[role='alertdialog'],[aria-modal='true']";
|
||||
|
||||
/** Live host floating controls, so they also avoid each other. */
|
||||
const registry = new Set<{ owner: Element; rect: () => HostPartRect | null }>();
|
||||
|
||||
function toRect(rect: DOMRect | HostPartRect): HostPartRect {
|
||||
return { left: rect.left, top: rect.top, width: rect.width, height: rect.height, right: rect.right, bottom: rect.bottom };
|
||||
}
|
||||
|
||||
/**
|
||||
* Visible, topmost interactive controls of the page (outside `self`). A control
|
||||
* hidden under the host control itself still counts: that is the collision we
|
||||
* want to resolve. A control hidden under a modal backdrop does not.
|
||||
*/
|
||||
export function collectFloatingObstacles(options: {
|
||||
doc: Document;
|
||||
/** Elements that belong to the floating control (light DOM wrapper or layer host). */
|
||||
isSelf: (element: Element) => boolean;
|
||||
owner: Element;
|
||||
}): FloatingObstacle[] {
|
||||
const { doc, isSelf, owner } = options;
|
||||
const view = doc.defaultView;
|
||||
if (!view) return [];
|
||||
const obstacles: FloatingObstacle[] = [];
|
||||
const viewportWidth = view.innerWidth;
|
||||
const viewportHeight = view.innerHeight;
|
||||
for (const element of doc.querySelectorAll<HTMLElement>(INTERACTIVE_SELECTOR)) {
|
||||
if (isSelf(element)) continue;
|
||||
const rect = element.getBoundingClientRect();
|
||||
if (rect.width < 2 || rect.height < 2) continue;
|
||||
if (rect.right <= 0 || rect.bottom <= 0 || rect.left >= viewportWidth || rect.top >= viewportHeight) continue;
|
||||
const style = view.getComputedStyle(element);
|
||||
if (style.visibility === "hidden" || style.visibility === "collapse" || style.pointerEvents === "none") continue;
|
||||
// Disabled controls still count: a "Send" button is disabled only until the
|
||||
// user types, and the host control must not sit on it either way.
|
||||
const x = Math.min(Math.max(rect.left + rect.width / 2, 0), viewportWidth - 1);
|
||||
const y = Math.min(Math.max(rect.top + rect.height / 2, 0), viewportHeight - 1);
|
||||
const hit = doc.elementFromPoint(x, y);
|
||||
if (!hit || !(hit === element || element.contains(hit) || isSelf(hit))) continue;
|
||||
const part = element.closest("[data-ws-part]")?.getAttribute("data-ws-part") ?? "";
|
||||
const weight = element.closest(DIALOG_SELECTOR)
|
||||
? FLOATING_WEIGHT_DIALOG
|
||||
: PROTECTED_PART_IDS.has(part) ? FLOATING_WEIGHT_PROTECTED : FLOATING_WEIGHT_CONTROL;
|
||||
obstacles.push({ rect: toRect(rect), weight });
|
||||
}
|
||||
for (const entry of registry) {
|
||||
if (entry.owner === owner) continue;
|
||||
const rect = entry.rect();
|
||||
if (rect && rect.width > 0 && rect.height > 0) obstacles.push({ rect, weight: FLOATING_WEIGHT_HOST });
|
||||
}
|
||||
return obstacles;
|
||||
}
|
||||
|
||||
export interface FloatingAvoidanceOptions {
|
||||
/** The floating element whose box is measured. */
|
||||
element: HTMLElement;
|
||||
/** Element that identifies "self" for hit tests (layer host or the element). */
|
||||
isSelf: (element: Element) => boolean;
|
||||
margins: FloatingMargins;
|
||||
defaultPosition?: FloatingPosition;
|
||||
/** Apply a position (attribute/class on the element; never inline skin styles). */
|
||||
apply: (position: FloatingPosition) => void;
|
||||
/** Optional smaller footprint used when every full-size position collides. */
|
||||
compactSize?: () => FloatingSize | null;
|
||||
onCompactChange?: (compact: boolean) => void;
|
||||
/** Skip re-evaluation (hovered, focused, slotted, drawer open…). */
|
||||
paused?: () => boolean;
|
||||
}
|
||||
|
||||
export interface FloatingAvoidance {
|
||||
revalidate(): void;
|
||||
readonly position: FloatingPosition;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): FloatingAvoidance {
|
||||
const { element, isSelf, margins, apply, onCompactChange } = options;
|
||||
const doc = element.ownerDocument;
|
||||
const view = doc.defaultView;
|
||||
const defaultPosition = options.defaultPosition ?? "bottom-left";
|
||||
let position: FloatingPosition = defaultPosition;
|
||||
let compact = false;
|
||||
let fullSize: FloatingSize = { width: 0, height: 0 };
|
||||
let disposed = false;
|
||||
let timer: ReturnType<typeof setInterval> | undefined;
|
||||
const entry = {
|
||||
owner: element as Element,
|
||||
rect: () => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
return rect.width > 0 && rect.height > 0 ? toRect(rect) : null;
|
||||
},
|
||||
};
|
||||
registry.add(entry);
|
||||
apply(position);
|
||||
|
||||
function setCompact(next: boolean) {
|
||||
if (compact === next) return;
|
||||
compact = next;
|
||||
onCompactChange?.(next);
|
||||
}
|
||||
|
||||
function evaluate() {
|
||||
if (disposed || !view) return;
|
||||
if (options.paused?.()) return;
|
||||
const box = element.getBoundingClientRect();
|
||||
if (!(box.width > 0) || !(box.height > 0)) return;
|
||||
// The expanded footprint is what the user sees on hover/focus, so score
|
||||
// with the largest full size observed (never the compact size).
|
||||
if (!compact) fullSize = { width: Math.max(fullSize.width, box.width), height: Math.max(fullSize.height, box.height) };
|
||||
const size = fullSize.width > 0 ? fullSize : { width: box.width, height: box.height };
|
||||
const viewport = { width: view.innerWidth, height: view.innerHeight };
|
||||
const obstacles = collectFloatingObstacles({ doc, isSelf, owner: element });
|
||||
const full = chooseFloatingPosition({ current: position, size, viewport, margins, obstacles });
|
||||
let next = full;
|
||||
let nextCompact = false;
|
||||
const small = full.score > 0 ? options.compactSize?.() : null;
|
||||
if (small && small.width > 0 && small.height > 0) {
|
||||
const reduced = chooseFloatingPosition({ current: full.position, size: small, viewport, margins, obstacles });
|
||||
if (reduced.score < full.score - 1e-6) {
|
||||
next = reduced;
|
||||
nextCompact = true;
|
||||
}
|
||||
}
|
||||
if (next.position !== position) {
|
||||
position = next.position;
|
||||
apply(position);
|
||||
}
|
||||
setCompact(nextCompact);
|
||||
}
|
||||
|
||||
function safeEvaluate() {
|
||||
try {
|
||||
evaluate();
|
||||
} catch {
|
||||
// A failed sample must never strand the control; return to the default.
|
||||
if (position !== defaultPosition) {
|
||||
position = defaultPosition;
|
||||
apply(position);
|
||||
}
|
||||
setCompact(false);
|
||||
}
|
||||
}
|
||||
|
||||
let clickTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const afterClick = () => {
|
||||
if (clickTimer) clearTimeout(clickTimer);
|
||||
clickTimer = setTimeout(safeEvaluate, HOST_FLOATING_AFTER_CLICK_MS);
|
||||
};
|
||||
if (view) {
|
||||
timer = setInterval(safeEvaluate, HOST_FLOATING_INTERVAL_MS);
|
||||
view.addEventListener("resize", safeEvaluate, { passive: true });
|
||||
doc.addEventListener("click", afterClick, { capture: true, passive: true });
|
||||
}
|
||||
safeEvaluate();
|
||||
|
||||
return {
|
||||
revalidate: safeEvaluate,
|
||||
get position() { return position; },
|
||||
dispose() {
|
||||
disposed = true;
|
||||
registry.delete(entry);
|
||||
if (timer) clearInterval(timer);
|
||||
if (clickTimer) clearTimeout(clickTimer);
|
||||
view?.removeEventListener("resize", safeEvaluate);
|
||||
doc.removeEventListener("click", afterClick, { capture: true });
|
||||
setCompact(false);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -53,6 +53,11 @@
|
||||
|
||||
.ws-plugin-toolbar{position:relative;display:flex;align-items:center;min-width:0}
|
||||
.ws-plugin-toolbar-fallback{position:fixed;z-index:1001;right:16px;bottom:calc(16px + env(safe-area-inset-bottom));padding:4px;border-radius:12px;background:var(--ws-panel,#fff);box-shadow:0 4px 20px #0003;color:#233049}
|
||||
/* Runtime collision avoidance (host-floating-placement.ts) moves the fallback toolbar off skin controls. */
|
||||
.ws-plugin-toolbar-fallback[data-ws-float$="left"]{right:auto;left:16px}
|
||||
.ws-plugin-toolbar-fallback[data-ws-float^="top"]{bottom:auto;top:calc(16px + env(safe-area-inset-top))}
|
||||
.ws-plugin-toolbar-fallback[data-ws-float^="middle"]{bottom:auto;top:50%;translate:0 -50%}
|
||||
.ws-plugin-toolbar-fallback[data-ws-float$="center"]{right:auto;left:50%;translate:-50% 0}
|
||||
.ws-plugin-toolbar[data-presentation="drawer-side"]{display:grid;width:100%;gap:4px;color:inherit}
|
||||
.ws-plugin-toolbar[data-presentation="drawer-side"] .ws-plugin-toolbar-trigger{justify-content:flex-start;width:100%;gap:8px;padding:7px 10px;color:inherit;background:transparent;border:1px solid transparent;font:inherit}
|
||||
.ws-plugin-drawer{position:absolute;top:calc(100% + 8px);right:0;z-index:60;width:min(280px,calc(100vw - 32px));max-height:min(380px,60dvh);overflow:auto;overscroll-behavior:contain;padding:8px;color:var(--plugin-drawer-text,#233049);background:var(--plugin-drawer-bg,#fff);border:1px solid var(--plugin-drawer-border,#dae1ef);border-radius:12px;box-shadow:0 12px 32px #17223430;text-align:left;font:13px/1.4 system-ui,sans-serif}
|
||||
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Host floating placement fixture</title>
|
||||
<style>
|
||||
html, body { margin: 0; width: 100%; height: 100%; font: 12px/1.5 system-ui, sans-serif; }
|
||||
/* Skin audio dock in the bottom-left corner, where the capsule floats by default. */
|
||||
#mic { position: fixed; left: 20px; bottom: 40px; width: 120px; height: 34px; }
|
||||
/* Skin "Send" button (disabled until the user types) in the bottom-right corner. */
|
||||
#send { position: fixed; right: 20px; bottom: 20px; width: 60px; height: 34px; }
|
||||
/* A right-hand side sheet whose buttons sit where the capsule moved to. */
|
||||
#sheet { position: fixed; inset: 0 0 0 auto; width: 320px; background: #eee; }
|
||||
#sheet button { position: absolute; right: 8px; width: 280px; height: 40px; }
|
||||
#cancel { top: 8px; } #enter { bottom: 30px; }
|
||||
#backdrop { position: fixed; inset: 0; background: #0006; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="ws-skin-root" data-ws-skin="community.float-fixture" data-ws-part="app">
|
||||
<div data-ws-part="voice.audio-dock.microphone"><button type="button" id="mic">Mic</button></div>
|
||||
<button type="button" id="send" disabled>Send</button>
|
||||
<button type="button" id="top-left" style="position:fixed;left:8px;top:8px;width:220px;height:44px">Server strip</button>
|
||||
</div>
|
||||
<pre id="result">pending</pre>
|
||||
<script type="module">
|
||||
import { createHostOwnedLayer } from "/src/services/host-owned-layer.ts";
|
||||
import { bindFloatingAvoidance } from "/src/services/host-floating-placement.ts";
|
||||
|
||||
const output = document.getElementById("result");
|
||||
const CSS = `
|
||||
.cap { position: fixed; inset: auto auto 38px 12px; margin: 0; display: flex; gap: 4px; padding: 4px; border: 0; width: 200px; height: 30px; pointer-events: auto; }
|
||||
.cap[data-ws-float$="right"] { left: auto; right: 12px; }
|
||||
.cap[data-ws-float^="top"] { bottom: auto; top: 12px; }
|
||||
.cap[data-ws-float^="middle"] { bottom: auto; top: 50%; translate: 0 -50%; }
|
||||
.cap[data-ws-float$="center"] { left: 50%; translate: -50% 0; }
|
||||
.cap.compact { width: 30px; }
|
||||
`;
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
try {
|
||||
const layer = createHostOwnedLayer("recovery", CSS);
|
||||
const control = document.createElement("div");
|
||||
control.className = "cap";
|
||||
control.setAttribute("popover", "manual");
|
||||
control.innerHTML = '<button type="button">Use built-in skin</button>';
|
||||
layer.container.append(control);
|
||||
control.showPopover();
|
||||
const host = layer.host;
|
||||
let compact = false;
|
||||
const binding = bindFloatingAvoidance({
|
||||
element: control,
|
||||
isSelf: (node) => node === host || host.contains(node),
|
||||
margins: { top: 12, right: 12, bottom: 38, left: 12 },
|
||||
apply: (position) => control.setAttribute("data-ws-float", position),
|
||||
compactSize: () => ({ width: 30, height: 38 }),
|
||||
onCompactChange: (next) => { compact = next; control.classList.toggle("compact", next); },
|
||||
});
|
||||
const covered = () => ["mic", "send", "top-left", "cancel", "enter"].filter((id) => {
|
||||
const element = document.getElementById(id);
|
||||
if (!element) return false;
|
||||
const r = element.getBoundingClientRect();
|
||||
if (!(r.width > 0)) return false;
|
||||
return document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2) === host;
|
||||
});
|
||||
const snap = (name) => ({ name, position: binding.position, compact, covered: covered(), capsuleHit: (() => {
|
||||
const r = control.getBoundingClientRect();
|
||||
return document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2) === host;
|
||||
})() });
|
||||
const results = [];
|
||||
binding.revalidate();
|
||||
results.push(snap("dock-and-send"));
|
||||
|
||||
// A bottom sheet opens behind a backdrop: only its buttons count now.
|
||||
document.body.insertAdjacentHTML("beforeend", '<div id="backdrop"></div><div id="sheet" role="dialog" aria-modal="true"><button type="button" id="cancel">Cancel</button><button type="button" id="enter">Enter channel</button></div>');
|
||||
document.getElementById("cancel").click();
|
||||
await sleep(400);
|
||||
results.push({ ...snap("after-click-sheet"), before: results[0].position });
|
||||
|
||||
// Everything is covered: the capsule folds to its mark at the least harmful spot.
|
||||
document.getElementById("sheet").remove();
|
||||
document.getElementById("backdrop").remove();
|
||||
document.body.insertAdjacentHTML("beforeend", '<div id="wall" style="position:fixed;inset:0;display:grid;grid-template-columns:repeat(20,1fr)">' + '<button type="button"></button>'.repeat(400) + "</div>");
|
||||
binding.revalidate();
|
||||
results.push(snap("wall"));
|
||||
|
||||
document.getElementById("wall").remove();
|
||||
binding.revalidate();
|
||||
results.push(snap("wall-removed"));
|
||||
|
||||
binding.dispose();
|
||||
results.push({ ...snap("disposed") });
|
||||
output.textContent = JSON.stringify({ results });
|
||||
} catch (error) {
|
||||
output.textContent = JSON.stringify({ error: String(error && error.stack || error) });
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -303,6 +303,49 @@ test("a declared slot docks the capsule and falls back at runtime", { skip: !CHR
|
||||
assert.equal(byName.disposed.leftoverAccent, "");
|
||||
});
|
||||
|
||||
test("floating host controls move off skin controls at runtime", { 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");
|
||||
|
||||
const dom = await dumpDom(`http://127.0.0.1:${port}/test/fixtures/host-floating-placement.html`, ["--virtual-time-budget=10000", "--window-size=1280,800"]);
|
||||
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]));
|
||||
|
||||
// Default corner covers the microphone, bottom-right covers the (disabled)
|
||||
// Send button and top-left a server strip: the capsule takes a free spot.
|
||||
const first = byName["dock-and-send"];
|
||||
assert.deepEqual(first.covered, [], JSON.stringify(payload));
|
||||
assert.notEqual(first.position, "bottom-left");
|
||||
assert.notEqual(first.position, "bottom-right");
|
||||
assert.equal(first.capsuleHit, true, "the moved capsule is not clickable");
|
||||
assert.equal(first.compact, false);
|
||||
|
||||
// A modal sheet opened by a click: its buttons are freed within one re-check.
|
||||
// Controls under the modal backdrop are not reachable anyway and do not count.
|
||||
assert.deepEqual(byName["after-click-sheet"].covered.filter((id) => id === "cancel" || id === "enter"), [], JSON.stringify(byName["after-click-sheet"]));
|
||||
assert.equal(byName["after-click-sheet"].capsuleHit, true);
|
||||
assert.notEqual(byName["after-click-sheet"].position, byName["after-click-sheet"].before, "the capsule did not move off the sheet");
|
||||
|
||||
// Nowhere is free: the capsule folds to its mark but stays clickable.
|
||||
assert.equal(byName.wall.compact, true, JSON.stringify(byName.wall));
|
||||
assert.equal(byName.wall.capsuleHit, true);
|
||||
|
||||
assert.equal(byName["wall-removed"].compact, false);
|
||||
assert.equal(byName.disposed.compact, false);
|
||||
});
|
||||
|
||||
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,
|
||||
|
||||
Reference in new issue
Block a user