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:
OddTurtleHead committed 2026-11-15 20:59:48 +08:00
1 parent 0df25e4892
commit e46d7a0eb7
9 files changed
+629 -7

No files matched your search

+56 -5
View File
@@ -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);
+21 -1
View File
@@ -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");
});
+322
View File
@@ -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);
},
};
}
+5
View File
@@ -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}