feat: modernize widget experience

This commit is contained in:
Thomas Camlong committed 2026-08-03 17:18:22 +02:00
1 parent 65ff0ecb34
commit 61a2f8cb6c
198 files changed
+4209 -2295

No files matched your search

@@ -3,6 +3,10 @@
animation: focus-backdrop-in 180ms cubic-bezier(0.16, 1, 0.3, 1);
}
.manualBackdrop {
pointer-events: auto;
}
.surface {
position: fixed;
z-index: 1;
@@ -15,6 +19,25 @@
transform-origin: top left;
}
.manualSurface {
position: fixed;
max-width: none;
max-height: none;
overflow: visible;
background: transparent;
box-shadow: none;
overscroll-behavior: contain;
animation: focus-surface-in 180ms cubic-bezier(0.16, 1, 0.3, 1);
transform-origin: top left;
}
.manualSurface > div {
width: 100%;
height: 100%;
max-height: none !important;
overflow: visible;
}
.backdropClosing {
animation: focus-backdrop-out 180ms ease-in forwards;
}
@@ -32,6 +55,18 @@
height: 100%;
}
.surfacePortalTarget,
.manualSurfaceMount {
width: 100%;
height: 100%;
min-height: 0;
}
.manualSurfaceMount {
overflow: hidden;
border-radius: inherit;
}
.surfaceHostAdvanced {
position: fixed;
inset: 0;
@@ -49,7 +84,7 @@
}
.closeButton {
position: fixed;
position: absolute;
z-index: 2;
pointer-events: auto;
}
@@ -99,7 +134,8 @@
@media (prefers-reduced-motion: reduce) {
.backdrop,
.surface {
.surface,
.manualSurface {
animation: none;
}
}
@@ -16,6 +16,7 @@ interface ActiveFocus {
sourceRect: FocusRect;
activation: "preview" | "manual";
autofocusClose: boolean;
restorePreviewFocus: boolean;
phase: "visible" | "closing";
}
@@ -79,6 +80,7 @@ export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
sourceRect: { left: rect.left, top: rect.top, width: rect.width, height: rect.height },
activation: options.activation ?? "manual",
autofocusClose: options.autofocusClose ?? false,
restorePreviewFocus: options.activation === "preview" && document.activeElement === source,
phase: "visible",
});
},
@@ -118,12 +120,46 @@ export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
if (current?.activation === "preview" && current.itemId !== itemId) {
cancelCloseTimer();
updateActive(null);
if (current.restorePreviewFocus && current.source.isConnected) current.source.focus({ preventScroll: true });
}
startHoverTimer();
},
[cancelCloseTimer, startHoverTimer, updateActive],
);
useEffect(() => {
const handlePointerMove = (event: PointerEvent) => {
const current = activeRef.current;
if (!shiftHeldRef.current || current?.activation !== "preview") return;
const underlyingSource = document
.elementsFromPoint(event.clientX, event.clientY)
.map((element) =>
element instanceof HTMLElement
? element.matches(".grid-stack-item-content")
? element
: element.closest<HTMLElement>(".grid-stack-item-content")
: null,
)
.find((source) => source !== null && source !== current.source);
const itemId = underlyingSource?.closest<HTMLElement>(".grid-stack-item[data-id]")?.dataset.id;
if (!underlyingSource || !itemId) return;
if (underlyingSource.hasAttribute("aria-keyshortcuts")) {
hover(itemId, underlyingSource);
return;
}
hoveredRef.current = null;
cancelHoverTimer();
cancelCloseTimer();
updateActive(null);
};
window.addEventListener("pointermove", handlePointerMove, { capture: true });
return () => window.removeEventListener("pointermove", handlePointerMove, { capture: true });
}, [cancelCloseTimer, cancelHoverTimer, hover, updateActive]);
const leave = useCallback(
(itemId: string) => {
if (hoveredRef.current?.itemId === itemId) hoveredRef.current = null;
@@ -145,7 +181,7 @@ export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape" && activeRef.current) {
const advancedSurface = document.querySelector(`.${classes.surface}`);
const advancedSurface = document.querySelector("[data-advanced-focus-surface]");
if (event.defaultPrevented || event.isComposing || isEscapeOwnedByNestedOverlay(event.target, advancedSurface))
return;
event.preventDefault();
@@ -170,11 +206,11 @@ export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
if (activeRef.current?.activation === "preview") close(false);
};
window.addEventListener("keydown", handleKeyDown);
window.addEventListener("keydown", handleKeyDown, { capture: true });
window.addEventListener("keyup", handleKeyUp);
window.addEventListener("blur", handleBlur);
return () => {
window.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("keydown", handleKeyDown, { capture: true });
window.removeEventListener("keyup", handleKeyUp);
window.removeEventListener("blur", handleBlur);
cancelHoverTimer();
@@ -194,7 +230,7 @@ export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
return (
<AdvancedFocusContext.Provider value={value}>
{children}
{active && (
{active?.activation === "preview" && (
<Portal>
<Overlay
fixed
@@ -5,7 +5,7 @@ import { isEscapeOwnedByNestedOverlay } from "./escape";
describe("isEscapeOwnedByNestedOverlay", () => {
test("allows Escape from the advanced surface itself", () => {
const surface = document.createElement("section");
surface.setAttribute("role", "region");
surface.setAttribute("role", "dialog");
const button = document.createElement("button");
surface.append(button);
@@ -44,6 +44,24 @@ describe("isEscapeOwnedByNestedOverlay", () => {
expect(isEscapeOwnedByNestedOverlay(target, surface)).toBe(true);
});
test("leaves Escape to a visible portalled menu when focus stays in the advanced surface", () => {
const surface = document.createElement("section");
surface.setAttribute("role", "dialog");
const target = document.createElement("button");
surface.append(target);
document.body.append(surface);
const menu = document.createElement("div");
menu.setAttribute("role", "menu");
menu.getClientRects = () => [{ width: 100, height: 100 }] as unknown as DOMRectList;
document.body.append(menu);
expect(isEscapeOwnedByNestedOverlay(target, surface)).toBe(true);
menu.remove();
surface.remove();
});
test("does not mistake the compact widget source for a nested overlay", () => {
const surface = document.createElement("section");
surface.setAttribute("role", "region");
@@ -6,8 +6,14 @@ const escapeOwnerSelector = [
].join(", ");
export const isEscapeOwnedByNestedOverlay = (target: EventTarget | null, advancedSurface: Element | null) => {
if (!(target instanceof Element)) return false;
const escapeOwner = target instanceof Element ? target.closest(escapeOwnerSelector) : null;
if (escapeOwner !== null && escapeOwner !== advancedSurface) return true;
const escapeOwner = target.closest(escapeOwnerSelector);
return escapeOwner !== null && escapeOwner !== advancedSurface;
return Array.from(document.querySelectorAll(escapeOwnerSelector)).some(
(owner) =>
owner !== advancedSurface &&
owner.getAttribute("aria-hidden") !== "true" &&
owner.closest('[aria-hidden="true"]') === null &&
owner.getClientRects().length > 0,
);
};
@@ -0,0 +1,107 @@
// @vitest-environment jsdom
import { act, createElement, Fragment, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import { MantineProvider } from "@mantine/core";
import { afterEach, describe, expect, test, vi } from "vitest";
import { AdvancedFocusManualSurface } from "./manual-surface";
const sourceRect = { left: 100, top: 120, width: 240, height: 160 };
const rect = { left: 40, top: 80, width: 640, height: 480 };
const closePosition = { left: 688, top: 80 };
describe("AdvancedFocusManualSurface", () => {
let host: HTMLDivElement | undefined;
let root: ReturnType<typeof createRoot> | undefined;
afterEach(async () => {
if (root) await act(async () => root?.unmount());
host?.remove();
document.querySelectorAll("[data-portal]").forEach((portal) => portal.remove());
vi.unstubAllGlobals();
});
test("portals dialog semantics, traps focus, closes from the backdrop, and restores focus", async () => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal(
"matchMedia",
vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
);
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
const Harness = () => {
const [opened, setOpened] = useState(false);
const contentRef = useRef<HTMLDivElement>(null);
return createElement(
Fragment,
null,
createElement("button", { type: "button", onClick: () => setOpened(true) }, "Open advanced view"),
createElement(
AdvancedFocusManualSurface,
{
opened,
phase: "visible",
id: "advanced-focus-test",
label: "Test widget advanced view",
closeLabel: "Close advanced view",
rect,
closePosition,
sourceRect,
radius: "md",
contentRef,
onClose: () => setOpened(false),
},
createElement("button", { type: "button" }, "First widget action"),
createElement("button", { type: "button" }, "Last widget action"),
),
);
};
await act(async () => root?.render(createElement(MantineProvider, null, createElement(Harness))));
const trigger = document.querySelector<HTMLButtonElement>("button");
expect(trigger).not.toBeNull();
trigger?.focus();
await act(async () => trigger?.click());
await act(async () => await new Promise((resolve) => setTimeout(resolve, 20)));
const dialog = document.querySelector<HTMLElement>("[role='dialog']");
const closeButton = dialog?.querySelector<HTMLButtonElement>("[aria-label='Close advanced view']");
const actions = dialog?.querySelectorAll<HTMLButtonElement>("button");
expect(dialog?.id).toBe("advanced-focus-test");
expect(dialog?.getAttribute("aria-modal")).toBe("true");
expect(dialog?.closest("[data-portal]")).not.toBeNull();
expect(dialog?.closest(".grid-stack-item")).toBeNull();
expect(document.getElementById(dialog?.getAttribute("aria-labelledby") ?? "")?.textContent).toBe(
"Test widget advanced view",
);
expect(document.activeElement).toBe(closeButton);
const lastAction = actions?.item((actions?.length ?? 1) - 1);
lastAction?.focus();
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true }));
expect(document.activeElement).toBe(closeButton);
closeButton?.focus();
document.dispatchEvent(
new KeyboardEvent("keydown", { key: "Tab", shiftKey: true, bubbles: true, cancelable: true }),
);
expect(document.activeElement).toBe(lastAction);
const backdrop = document.querySelector<HTMLElement>("[data-advanced-focus-overlay]");
await act(async () => backdrop?.click());
await act(async () => await new Promise((resolve) => setTimeout(resolve, 20)));
expect(document.activeElement).toBe(trigger);
});
});
@@ -0,0 +1,101 @@
"use client";
import type { CSSProperties, PropsWithChildren, Ref } from "react";
import { Modal, VisuallyHidden } from "@mantine/core";
import { useReducedMotion } from "@mantine/hooks";
import classes from "./advanced-focus.module.css";
import type { FocusClosePosition, FocusRect } from "./geometry";
interface AdvancedFocusManualSurfaceProps extends PropsWithChildren {
opened: boolean;
phase: "visible" | "closing";
id: string;
label: string;
closeLabel: string;
rect: FocusRect;
closePosition: FocusClosePosition;
sourceRect: FocusRect;
radius: string | number;
contentRef: Ref<HTMLDivElement>;
onClose: () => void;
}
export const AdvancedFocusManualSurface = ({
opened,
phase,
id,
label,
closeLabel,
rect,
closePosition,
sourceRect,
radius,
contentRef,
onClose,
children,
}: AdvancedFocusManualSurfaceProps) => {
const reduceMotion = useReducedMotion();
const transitionDuration = reduceMotion ? 0 : 180;
const geometryStyle = {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
"--focus-translate-x": `${sourceRect.left - rect.left}px`,
"--focus-translate-y": `${sourceRect.top - rect.top}px`,
"--focus-scale-x": rect.width > 0 ? sourceRect.width / rect.width : 1,
"--focus-scale-y": rect.height > 0 ? sourceRect.height / rect.height : 1,
} as CSSProperties;
const relativeClosePosition = {
left: closePosition.left - rect.left,
top: closePosition.top - rect.top,
};
return (
<Modal.Root
opened={opened}
onClose={onClose}
radius={radius}
padding={0}
shadow="none"
zIndex="calc(var(--mantine-z-index-modal) - 1)"
closeOnEscape={false}
closeOnClickOutside
lockScroll
trapFocus
returnFocus
removeScrollProps={{ allowPinchZoom: true }}
transitionProps={{ duration: transitionDuration, transition: "fade" }}
>
<Modal.Overlay
data-advanced-focus-overlay
backgroundOpacity={0.38}
blur={0}
className={`${classes.backdrop} ${classes.manualBackdrop} ${
phase === "closing" ? classes.backdropClosing : ""
}`}
/>
<Modal.Content
ref={contentRef}
id={id}
data-advanced-focus-surface
className={`${classes.manualSurface} ${phase === "closing" ? classes.surfaceClosing : ""}`}
style={geometryStyle}
>
<Modal.Title>
<VisuallyHidden>{label}</VisuallyHidden>
</Modal.Title>
<Modal.CloseButton
className={classes.closeButton}
variant="default"
size={44}
aria-label={closeLabel}
aria-controls={id}
style={relativeClosePosition}
/>
{children}
</Modal.Content>
</Modal.Root>
);
};
@@ -13,10 +13,8 @@ export const redirectShiftWheel = (root: HTMLElement, target: EventTarget | null
if (delta === 0) return false;
let current = target instanceof Element ? target : null;
let startedInScrollContainer = false;
while (current && root.contains(current)) {
const isCurrentScrollContainer = isVerticalScrollContainer(current);
startedInScrollContainer ||= isCurrentScrollContainer;
if (isCurrentScrollContainer && canScrollVertically(current, delta)) {
current.scrollTop += delta;
return true;
@@ -24,8 +22,9 @@ export const redirectShiftWheel = (root: HTMLElement, target: EventTarget | null
if (current === root) break;
current = current.parentElement;
}
if (startedInScrollContainer) return false;
// A nested control can reach its edge before the widget's main Mantine viewport.
// Hand the gesture to that viewport instead of making Shift+wheel feel stuck.
const viewport = [...root.querySelectorAll<HTMLElement>("[data-scrollbars='y'], [data-scrollbars='xy']")].find(
(element) => isVerticalScrollContainer(element) && canScrollVertically(element, delta),
);
@@ -1,8 +1,9 @@
import type { CSSProperties, KeyboardEvent, MutableRefObject } from "react";
import { useEffect, useRef } from "react";
import { ActionIcon, Badge, Box, Card } from "@mantine/core";
import { useElementSize, useViewportSize } from "@mantine/hooks";
import { IconMaximize, IconX } from "@tabler/icons-react";
import type { CSSProperties, KeyboardEvent } from "react";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { ActionIcon, Badge, Box, Card, Portal } from "@mantine/core";
import { useElementSize, useIsomorphicEffect, useViewportSize } from "@mantine/hooks";
import { IconMaximize } from "@tabler/icons-react";
import { QueryErrorResetBoundary, useQueryClient } from "@tanstack/react-query";
import combineClasses from "clsx";
import { NoIntegrationSelectedError } from "@homarr/widgets/errors/classes";
@@ -12,8 +13,9 @@ import { useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
import { useSettings } from "@homarr/settings";
import { useI18n } from "@homarr/translation/client";
import type { WidgetDefinition } from "@homarr/widgets";
import type { WidgetRuntimeRef } from "@homarr/widgets";
import {
createWidgetRuntimeState,
loadWidgetDynamic,
reduceWidgetOptionsWithDefaultValues,
supportsAdvancedFocus as definitionSupportsAdvancedFocus,
@@ -25,6 +27,7 @@ import type { SectionItem } from "~/app/[locale]/boards/_types";
import advancedFocusClasses from "../advanced-focus/advanced-focus.module.css";
import { useAdvancedFocus } from "../advanced-focus/context";
import { getAdvancedFocusClosePosition, getAdvancedFocusRect } from "../advanced-focus/geometry";
import { AdvancedFocusManualSurface } from "../advanced-focus/manual-surface";
import { redirectShiftWheel } from "../advanced-focus/wheel";
import classes from "../sections/item.module.css";
import { useItemActions } from "./item-actions";
@@ -52,13 +55,12 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
const widgetName = t(`widget.${item.kind}.name`);
const advancedViewLabel = t("item.advancedFocus.label", { widget: widgetName });
const [isEditMode] = useEditMode();
const widgetStateRef = useRef<Record<string, unknown> | null>(null);
const closeButtonRef = useRef<HTMLButtonElement>(null);
const surfaceRef = useRef<HTMLDivElement>(null);
const widgetRuntimeRef = useRef(createWidgetRuntimeState());
const cardRef = useRef<HTMLDivElement>(null);
const [manualSurface, setManualSurface] = useState<HTMLDivElement | null>(null);
const [surfacePortalTarget, setSurfacePortalTarget] = useState<HTMLDivElement | null>(null);
const { active, open, close, dismiss, hover, leave } = useAdvancedFocus();
const supportsAdvancedFocus = definitionSupportsAdvancedFocus(
widgetImports[item.kind].definition as WidgetDefinition,
);
const supportsAdvancedFocus = definitionSupportsAdvancedFocus(widgetImports[item.kind].definition);
const advancedViewId = `advanced-focus-${item.id}`;
const activeFocus = supportsAdvancedFocus && active?.itemId === item.id ? active : null;
const isAdvanced = activeFocus !== null;
@@ -66,16 +68,21 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
? getAdvancedFocusRect(activeFocus.sourceRect, { width: viewportWidth, height: viewportHeight })
: null;
const closePosition = advancedRect ? getAdvancedFocusClosePosition(advancedRect, viewportWidth) : null;
const isPreview = activeFocus?.activation === "preview";
const isManual = activeFocus?.activation === "manual";
// Keep one widget subtree mounted while moving its stable portal target between the grid and viewport layers.
// This preserves iframe/editor state and escapes Gridstack's transformed containing block.
useIsomorphicEffect(() => {
const target = document.createElement("div");
target.className = advancedFocusClasses.surfacePortalTarget ?? "";
setSurfacePortalTarget(target);
return () => target.remove();
}, []);
// Responsive layout changes remount grid items. Never leave their focus backdrop orphaned.
useEffect(() => () => dismiss(item.id), [dismiss, item.id]);
useEffect(() => {
if (!activeFocus?.autofocusClose || activeFocus.phase !== "visible") return;
const frame = requestAnimationFrame(() => closeButtonRef.current?.focus());
return () => cancelAnimationFrame(frame);
}, [activeFocus?.autofocusClose, activeFocus?.phase]);
const openAdvanced = (autofocusClose = false) => {
if (sourceRef.current) open(item.id, sourceRef.current, { activation: "manual", autofocusClose });
};
@@ -92,7 +99,7 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
openAdvanced(true);
};
useEffect(() => {
const surface = surfaceRef.current;
const surface = isManual ? manualSurface : cardRef.current;
if (!isAdvanced || !surface) return;
const handleWheel = (event: WheelEvent) => {
@@ -106,11 +113,87 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
surface.addEventListener("wheel", handleWheel, { capture: true, passive: false });
return () => surface.removeEventListener("wheel", handleWheel, { capture: true });
}, [isAdvanced]);
}, [isAdvanced, isManual, manualSurface]);
const mountPortalTarget = (node: HTMLDivElement | null, activation: "compact" | "preview" | "manual") => {
if (!node || !surfacePortalTarget) return;
const shouldMount =
(activation === "compact" && !isAdvanced) ||
(activation === "preview" && isPreview) ||
(activation === "manual" && isManual);
if (shouldMount) node.append(surfacePortalTarget);
};
const previewStyle =
isPreview && advancedRect
? ({
left: advancedRect.left,
top: advancedRect.top,
width: advancedRect.width,
height: advancedRect.height,
"--focus-translate-x": `${activeFocus.sourceRect.left - advancedRect.left}px`,
"--focus-translate-y": `${activeFocus.sourceRect.top - advancedRect.top}px`,
"--focus-scale-x": advancedRect.width > 0 ? activeFocus.sourceRect.width / advancedRect.width : 1,
"--focus-scale-y": advancedRect.height > 0 ? activeFocus.sourceRect.height / advancedRect.height : 1,
} as CSSProperties)
: undefined;
const widgetCard = (
<Card
ref={cardRef}
id={isPreview ? advancedViewId : undefined}
role={isPreview ? "region" : undefined}
aria-label={isPreview ? advancedViewLabel : undefined}
data-advanced-focus-surface={isPreview || undefined}
radius={board.itemRadius}
p={isAdvanced ? undefined : 0}
h={isManual ? "100%" : isAdvanced ? undefined : "100%"}
w={isManual ? "100%" : isAdvanced ? undefined : "100%"}
className={combineClasses(
classes.itemCard,
`${item.kind}-wrapper`,
isPreview && advancedFocusClasses.surface,
activeFocus?.phase === "closing" && isPreview && advancedFocusClasses.surfaceClosing,
item.advancedOptions.customCssClasses.join(" "),
)}
styles={{
root: {
"--opacity": isAdvanced ? 0.98 : board.opacity / 100,
containerType: "size",
overflow: getOverflowFromKind(item.kind),
"--border-color": item.advancedOptions.borderColor !== "" ? item.advancedOptions.borderColor : undefined,
},
}}
style={previewStyle}
>
<div className={advancedFocusClasses.surfaceControls}>
{!isEditMode && supportsAdvancedFocus && !isAdvanced && (
<ActionIcon
className={advancedFocusClasses.touchButton}
variant="default"
size={44}
aria-label={t("item.advancedFocus.open")}
onClick={() => openAdvanced()}
>
<IconMaximize size={18} />
</ActionIcon>
)}
</div>
<Box ref={contentRef} w="100%" h="100%" mih={0}>
<InnerContent
item={item}
width={width}
height={height}
widgetRuntimeRef={widgetRuntimeRef}
displayMode={isAdvanced ? "advanced" : "compact"}
/>
</Box>
</Card>
);
return (
<>
<WidgetContextMenu item={item} widgetStateRef={widgetStateRef} sourceRef={sourceRef}>
<WidgetContextMenu item={item} widgetRuntimeRef={widgetRuntimeRef} sourceRef={sourceRef}>
<Box
ref={sourceRef}
tabIndex={!isEditMode && supportsAdvancedFocus ? 0 : undefined}
@@ -130,99 +213,44 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
}}
className={combineClasses("grid-stack-item-content", isAdvanced && advancedFocusClasses.sourcePlaceholder)}
>
<div
className={combineClasses(
advancedFocusClasses.surfaceHost,
isAdvanced && advancedFocusClasses.surfaceHostAdvanced,
)}
>
{activeFocus?.activation === "manual" && closePosition && (
<ActionIcon
ref={closeButtonRef}
className={advancedFocusClasses.closeButton}
variant="default"
size={44}
aria-label={t("item.advancedFocus.close")}
aria-controls={advancedViewId}
style={closePosition}
onClick={() => close()}
>
<IconX size={18} />
</ActionIcon>
)}
<Card
ref={surfaceRef}
id={isAdvanced ? advancedViewId : undefined}
role={isAdvanced ? "region" : undefined}
aria-label={isAdvanced ? advancedViewLabel : undefined}
data-advanced-focus-surface={isAdvanced || undefined}
radius={board.itemRadius}
p={isAdvanced ? undefined : 0}
h={isAdvanced ? undefined : "100%"}
w={isAdvanced ? undefined : "100%"}
className={combineClasses(
classes.itemCard,
`${item.kind}-wrapper`,
isAdvanced && advancedFocusClasses.surface,
activeFocus?.phase === "closing" && advancedFocusClasses.surfaceClosing,
item.advancedOptions.customCssClasses.join(" "),
)}
styles={{
root: {
"--opacity": isAdvanced ? 0.98 : board.opacity / 100,
containerType: "size",
overflow: getOverflowFromKind(item.kind),
"--border-color":
item.advancedOptions.borderColor !== "" ? item.advancedOptions.borderColor : undefined,
},
}}
style={
activeFocus && advancedRect
? ({
left: advancedRect.left,
top: advancedRect.top,
width: advancedRect.width,
height: advancedRect.height,
"--focus-translate-x": `${activeFocus.sourceRect.left - advancedRect.left}px`,
"--focus-translate-y": `${activeFocus.sourceRect.top - advancedRect.top}px`,
"--focus-scale-x": advancedRect.width > 0 ? activeFocus.sourceRect.width / advancedRect.width : 1,
"--focus-scale-y":
advancedRect.height > 0 ? activeFocus.sourceRect.height / advancedRect.height : 1,
} as CSSProperties)
: undefined
}
>
<div className={advancedFocusClasses.surfaceControls}>
{!isEditMode && supportsAdvancedFocus && !isAdvanced && (
<ActionIcon
className={advancedFocusClasses.touchButton}
variant="default"
size={44}
aria-label={t("item.advancedFocus.open")}
onClick={() => openAdvanced()}
>
<IconMaximize size={18} />
</ActionIcon>
)}
</div>
<Box ref={contentRef} w="100%" h="100%" mih={0}>
<InnerContent
item={item}
width={width}
height={height}
widgetStateRef={widgetStateRef}
displayMode={isAdvanced ? "advanced" : "compact"}
/>
</Box>
</Card>
<div ref={(node) => mountPortalTarget(node, "compact")} className={advancedFocusClasses.surfaceHost}>
{!surfacePortalTarget && widgetCard}
</div>
{surfacePortalTarget && createPortal(widgetCard, surfacePortalTarget)}
{isPreview && (
<Portal reuseTargetNode={false}>
<div
ref={(node) => mountPortalTarget(node, "preview")}
className={advancedFocusClasses.surfaceHostAdvanced}
/>
</Portal>
)}
{isManual && advancedRect && closePosition && (
<AdvancedFocusManualSurface
opened={activeFocus.phase === "visible"}
phase={activeFocus.phase}
id={advancedViewId}
label={advancedViewLabel}
closeLabel={t("item.advancedFocus.close")}
rect={advancedRect}
closePosition={closePosition}
sourceRect={activeFocus.sourceRect}
radius={board.itemRadius}
contentRef={setManualSurface}
onClose={() => close()}
>
<div
ref={(node) => mountPortalTarget(node, "manual")}
className={advancedFocusClasses.manualSurfaceMount}
/>
</AdvancedFocusManualSurface>
)}
</Box>
</WidgetContextMenu>
{!isAdvanced && item.advancedOptions.title?.trim() && (
<Badge
pos="absolute"
// It's 4 because of the mantine-react-table that has z-index 3
style={{ zIndex: 4 }}
style={{ zIndex: "var(--mantine-z-index-app)" }}
top={2}
left={16}
size="xs"
@@ -247,7 +275,7 @@ interface InnerContentProps {
item: SectionItem;
width: number;
height: number;
widgetStateRef: MutableRefObject<Record<string, unknown> | null>;
widgetRuntimeRef: WidgetRuntimeRef;
displayMode: "compact" | "advanced";
}
@@ -115,7 +115,7 @@ const BoardItemMenuInner = ({ offset, item, resetErrorBoundary }: BoardItemMenuP
pos="absolute"
top={offset}
right={offset}
style={{ zIndex: 10 }}
style={{ zIndex: "var(--mantine-z-index-popover)" }}
aria-label={tItem("menu.label.settings")}
>
<IconDotsVertical size={"1rem"} />
@@ -33,7 +33,7 @@ export const ItemSelectModal = createModal<ItemSelectModalProps>(({ actions, inn
const { createItem } = useItemActions();
const { openModal: openEditModal } = useModalAction(WidgetEditModal);
const { data: integrationData } = clientApi.integration.all.useQuery();
const { data: customWidgetDefs } = clientApi.customWidget.all.useQuery();
const { data: customWidgetDefs } = clientApi.customWidget.available.useQuery({ boardId: innerProps.board.id });
const settings = useSettings();
const { updateAndPersistBoard } = usePersistBoard(innerProps.board);
@@ -208,7 +208,7 @@ export const ItemSelectModal = createModal<ItemSelectModalProps>(({ actions, inn
</Text>
</Group>
<Text lh={1.2} style={{ whiteSpace: "normal" }} size="xs" c="dimmed" lineClamp={1}>
{def.description ?? def.url}
{def.description}
</Text>
</Stack>
<Box
@@ -1,6 +1,6 @@
"use client";
import type { MutableRefObject, ReactNode, RefObject } from "react";
import type { ReactNode, RefObject } from "react";
import { useCallback, useMemo, useState } from "react";
import { Group, Loader, Menu, Text, Tooltip } from "@mantine/core";
import {
@@ -28,7 +28,7 @@ import { useSettings } from "@homarr/settings";
import { translateIfNecessary } from "@homarr/translation";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import type { TranslationFunction } from "@homarr/translation";
import type { WidgetContextMenuAction, WidgetDefinition } from "@homarr/widgets";
import type { WidgetDefinition, WidgetRuntimeRef } from "@homarr/widgets";
import {
getWidgetQueryKeys,
getWidgetRuntimeQueries,
@@ -48,12 +48,12 @@ import { matchesWidgetItemQuery } from "./widget-query-scope";
interface WidgetContextMenuProps {
item: SectionItem;
widgetStateRef: MutableRefObject<Record<string, unknown> | null>;
widgetRuntimeRef: WidgetRuntimeRef;
sourceRef: RefObject<HTMLElement | null>;
children: ReactNode;
}
export const WidgetContextMenu = ({ item, widgetStateRef, sourceRef, children }: WidgetContextMenuProps) => {
export const WidgetContextMenu = ({ item, widgetRuntimeRef, sourceRef, children }: WidgetContextMenuProps) => {
const { data: session } = useSession();
const [isEditMode] = useEditMode();
const board = useRequiredBoard();
@@ -70,8 +70,11 @@ export const WidgetContextMenu = ({ item, widgetStateRef, sourceRef, children }:
const { updateItemOptions, updateItemAdvancedOptions, updateItemIntegrations, duplicateItem, removeItem } =
useItemActions();
const { data: integrationData, isPending } = clientApi.integration.all.useQuery();
const currentDefinition = useMemo(() => widgetImports[item.kind].definition, [item.kind]);
const canOpenAdvancedFocus = supportsAdvancedFocus(currentDefinition as WidgetDefinition);
const currentDefinition = useMemo(
() => widgetImports[item.kind].definition as WidgetDefinition & { kind: string },
[item.kind],
);
const canOpenAdvancedFocus = supportsAdvancedFocus(currentDefinition);
const { gridstack } = useSectionContext().refs;
const queryClient = useQueryClient();
const { open: openAdvancedFocus } = useAdvancedFocus();
@@ -93,15 +96,12 @@ export const WidgetContextMenu = ({ item, widgetStateRef, sourceRef, children }:
);
const options = useMemo(
() => reduceWidgetOptionsWithDefaultValues(item.kind, settings, item.options) as Record<string, unknown>,
() => reduceWidgetOptionsWithDefaultValues(item.kind, settings, item.options),
[item.kind, settings, item.options],
);
const widgetQueryKeys = useMemo(
() => getWidgetQueryKeys(currentDefinition as Parameters<typeof getWidgetQueryKeys>[0]),
[currentDefinition],
);
const widgetQueryMatcher = (currentDefinition as WidgetDefinition).queryMatcher;
const widgetQueryKeys = useMemo(() => getWidgetQueryKeys(currentDefinition), [currentDefinition]);
const widgetQueryMatcher = "queryMatcher" in currentDefinition ? currentDefinition.queryMatcher : undefined;
const matchesWidgetQuery = useCallback(
(queryKey: QueryKey) =>
matchesWidgetItemQuery(
@@ -112,11 +112,11 @@ export const WidgetContextMenu = ({ item, widgetStateRef, sourceRef, children }:
boardId: board.id,
integrationIds: item.integrationIds,
options,
runtimeQueries: getWidgetRuntimeQueries(widgetStateRef),
runtimeQueries: getWidgetRuntimeQueries(widgetRuntimeRef),
},
widgetQueryMatcher,
),
[board.id, item.id, item.integrationIds, options, widgetQueryKeys, widgetQueryMatcher, widgetStateRef],
[board.id, item.id, item.integrationIds, options, widgetQueryKeys, widgetQueryMatcher, widgetRuntimeRef],
);
const isWidgetFetching =
useIsFetching({
@@ -156,11 +156,8 @@ export const WidgetContextMenu = ({ item, widgetStateRef, sourceRef, children }:
return Object.entries(rawOptions).filter(([, def]) => def.type === "switch" && !def.skipContextMenu);
}, [currentDefinition, hasChangeAccess, settings]);
const widgetContextActions = (() => {
const def = currentDefinition as Record<string, unknown>;
if (typeof def.contextActions !== "function") return [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const actions = (def.contextActions as any)({
const widgetContextActions =
currentDefinition.contextActions?.({
options,
setOptions: setItemOptions,
integrationIds: item.integrationIds,
@@ -170,10 +167,8 @@ export const WidgetContextMenu = ({ item, widgetStateRef, sourceRef, children }:
itemId: item.id,
canInteractWithSelectedIntegrations,
},
widgetStateRef,
});
return (Array.isArray(actions) ? actions : []) as WidgetContextMenuAction[];
})();
widgetRuntimeRef,
}) ?? [];
const openEditModal = useCallback(() => {
openModal(
@@ -294,7 +289,7 @@ export const WidgetContextMenu = ({ item, widgetStateRef, sourceRef, children }:
disabled={action.disabled}
color={action.color}
>
{String(translateIfNecessary(t, action.label))}
{t(action.label as never)}
</Menu.Item>
);
})}
@@ -416,14 +411,8 @@ const WidgetQueryStatus = ({ queryClient, matchesQuery, isFetching, t }: WidgetQ
const hasError = queries.some((q) => q.state.status === "error");
if (hasError) {
const errorQuery = queries.find((q) => q.state.status === "error");
const errorMessage =
errorQuery?.state.error instanceof Error
? errorQuery.state.error.message
: String(errorQuery?.state.error ?? "Unknown error");
return (
<Tooltip label={errorMessage} multiline position="left" w={250}>
<Tooltip label={t("item.menu.status.error")} position="left">
<Group gap={4} wrap="nowrap">
<IconAlertTriangle size={12} color="var(--mantine-color-red-6)" />
<Text size="xs" c="red.6">
@@ -4,7 +4,7 @@
right: 10px;
bottom: calc(100% - 10px);
margin-bottom: 1px;
z-index: 200;
z-index: var(--mantine-z-index-app);
pointer-events: none;
opacity: 0;
transform: translateY(6px);
@@ -101,6 +101,15 @@
overflow: hidden;
}
@media (forced-colors: active) {
.panel {
border-color: CanvasText;
background: Canvas;
box-shadow: none;
backdrop-filter: none;
}
}
.metadataLabel {
color: var(--mantine-color-dimmed);
flex-shrink: 0;
@@ -2,7 +2,7 @@ import { useCallback } from "react";
import { fetchApi } from "@homarr/api/client";
import { getCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { createId } from "@homarr/common";
import { createId, getSafeApplicationUrl } from "@homarr/common";
import { useConfirmModal, useModalAction } from "@homarr/modals";
import { useSettings } from "@homarr/settings";
import { useI18n } from "@homarr/translation/client";
@@ -116,10 +116,13 @@ export const useCategoryMenuActions = (category: CategorySection) => {
});
const apps = await fetchApi.app.byIds.query(appIds);
const appsWithUrls = apps.filter((app) => app.href && app.href.length > 0);
const safeUrls = apps.flatMap((app) => {
const href = getSafeApplicationUrl(app.href);
return href ? [href] : [];
});
for (const app of appsWithUrls) {
const openedWindow = window.open(app.href ?? undefined);
for (const href of safeUrls) {
const openedWindow = window.open(href, "_blank", "noopener,noreferrer");
if (openedWindow) {
continue;
}
@@ -51,7 +51,7 @@ export const BoardDynamicSectionMenu = ({ section }: { section: DynamicSectionIt
pos="absolute"
top={4}
right={4}
style={{ zIndex: 10 }}
style={{ zIndex: "var(--mantine-z-index-popover)" }}
aria-label={tItem("menu.label.settings")}
>
<IconDotsVertical size={"1rem"} />