fix(board): persist batch item actions

This commit is contained in:
Thomas Camlong committed 2026-08-21 02:31:13 +02:00
1 parent 3a7cad9e2f
commit 8b69688640
12 files changed
+256 -205

No files matched your search

@@ -1,5 +1,7 @@
"use client";
import { useEffect, useRef } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Group, Menu } from "@mantine/core";
import { IconBox, IconChevronDown, IconLayoutGridAdd, IconPlug, IconPlus, IconResize } from "@tabler/icons-react";
@@ -28,6 +30,21 @@ const AddMenu = () => {
const { addContainer } = useContainerActions();
const { createItem } = useItemActions();
const t = useI18n();
const pathname = usePathname();
const router = useRouter();
const searchParams = useSearchParams();
const handledInitialAdd = useRef(false);
useEffect(() => {
if (handledInitialAdd.current || searchParams.get("add") !== "true") return;
handledInitialAdd.current = true;
openItemSelectModal({ boardId: board.id });
const nextSearchParams = new URLSearchParams(searchParams.toString());
nextSearchParams.delete("add");
const query = nextSearchParams.toString();
router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false });
}, [board.id, openItemSelectModal, pathname, router, searchParams]);
const handleSelectItem = () => {
openItemSelectModal({ boardId: board.id });
@@ -54,7 +71,7 @@ const AddMenu = () => {
};
const handleAddIntegration = () => {
openIntegrationSelectModal({});
openIntegrationSelectModal({ completionBoardId: board.id });
};
return (
@@ -7,17 +7,18 @@ let audioContext: AudioContext | null = null;
const getAudioContext = (): AudioContext | null => {
if (typeof window === "undefined") return null;
if (!audioContext) {
const AudioContextClass =
window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
if (AudioContextClass) {
audioContext = new AudioContextClass();
try {
if (!audioContext) {
const AudioContextClass =
window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
if (AudioContextClass) audioContext = new AudioContextClass();
}
if (audioContext?.state === "suspended") void audioContext.resume().catch(() => undefined);
return audioContext;
} catch {
return null;
}
if (audioContext && audioContext.state === "suspended") {
void audioContext.resume();
}
return audioContext;
};
/**
@@ -41,50 +42,54 @@ export const playTrashSound = (volume = 0.35) => {
const ctx = getAudioContext();
if (!ctx) return;
const now = ctx.currentTime;
// Master Gain
const masterGain = ctx.createGain();
masterGain.gain.setValueAtTime(volume, now);
masterGain.connect(ctx.destination);
// 1. Downward sweep sub-oscillator (physical thud)
const osc = ctx.createOscillator();
const oscGain = ctx.createGain();
osc.type = "triangle";
osc.frequency.setValueAtTime(260, now);
osc.frequency.exponentialRampToValueAtTime(35, now + 0.18);
oscGain.gain.setValueAtTime(0.7, now);
oscGain.gain.exponentialRampToValueAtTime(0.001, now + 0.18);
osc.connect(oscGain);
oscGain.connect(masterGain);
osc.start(now);
osc.stop(now + 0.2);
// 2. High-crunch noise burst (crush / crumple texture)
try {
const noiseBuffer = createNoiseBuffer(ctx, 0.22);
const noiseSource = ctx.createBufferSource();
noiseSource.buffer = noiseBuffer;
const now = ctx.currentTime;
const noiseFilter = ctx.createBiquadFilter();
noiseFilter.type = "bandpass";
noiseFilter.frequency.setValueAtTime(1400, now);
noiseFilter.frequency.exponentialRampToValueAtTime(320, now + 0.2);
noiseFilter.Q.setValueAtTime(2.2, now);
// Master Gain
const masterGain = ctx.createGain();
masterGain.gain.setValueAtTime(volume, now);
masterGain.connect(ctx.destination);
const noiseGain = ctx.createGain();
noiseGain.gain.setValueAtTime(0.9, now);
noiseGain.gain.exponentialRampToValueAtTime(0.001, now + 0.2);
// 1. Downward sweep sub-oscillator (physical thud)
const osc = ctx.createOscillator();
const oscGain = ctx.createGain();
osc.type = "triangle";
osc.frequency.setValueAtTime(260, now);
osc.frequency.exponentialRampToValueAtTime(35, now + 0.18);
oscGain.gain.setValueAtTime(0.7, now);
oscGain.gain.exponentialRampToValueAtTime(0.001, now + 0.18);
osc.connect(oscGain);
oscGain.connect(masterGain);
osc.start(now);
osc.stop(now + 0.2);
noiseSource.connect(noiseFilter);
noiseFilter.connect(noiseGain);
noiseGain.connect(masterGain);
// 2. High-crunch noise burst (crush / crumple texture)
try {
const noiseBuffer = createNoiseBuffer(ctx, 0.22);
const noiseSource = ctx.createBufferSource();
noiseSource.buffer = noiseBuffer;
noiseSource.start(now);
noiseSource.stop(now + 0.22);
const noiseFilter = ctx.createBiquadFilter();
noiseFilter.type = "bandpass";
noiseFilter.frequency.setValueAtTime(1400, now);
noiseFilter.frequency.exponentialRampToValueAtTime(320, now + 0.2);
noiseFilter.Q.setValueAtTime(2.2, now);
const noiseGain = ctx.createGain();
noiseGain.gain.setValueAtTime(0.9, now);
noiseGain.gain.exponentialRampToValueAtTime(0.001, now + 0.2);
noiseSource.connect(noiseFilter);
noiseFilter.connect(noiseGain);
noiseGain.connect(masterGain);
noiseSource.start(now);
noiseSource.stop(now + 0.22);
} catch {
// The noise layer is optional; retain the oscillator when buffers are constrained.
}
} catch {
// Ignore if audio buffer creation is constrained
// Sound feedback must never interrupt deleting board items.
}
};
@@ -95,20 +100,24 @@ export const playPopSound = (volume = 0.25) => {
const ctx = getAudioContext();
if (!ctx) return;
const now = ctx.currentTime;
const osc = ctx.createOscillator();
const gain = ctx.createGain();
try {
const now = ctx.currentTime;
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.type = "sine";
osc.frequency.setValueAtTime(460, now);
osc.frequency.exponentialRampToValueAtTime(780, now + 0.05);
osc.type = "sine";
osc.frequency.setValueAtTime(460, now);
osc.frequency.exponentialRampToValueAtTime(780, now + 0.05);
gain.gain.setValueAtTime(volume, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.06);
gain.gain.setValueAtTime(volume, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.06);
osc.connect(gain);
gain.connect(ctx.destination);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start(now);
osc.stop(now + 0.07);
osc.start(now);
osc.stop(now + 0.07);
} catch {
// Sound feedback must never interrupt selecting board items.
}
};
@@ -96,7 +96,7 @@ describe("Advanced Add App - Modal Subcomponents", () => {
),
);
expect(host.textContent?.trim()).toBe("");
expect(host.querySelector("[class*='Badge-root']")).toBeNull();
});
});
@@ -180,7 +180,7 @@ describe("Advanced Add App - Modal Subcomponents", () => {
expect(onSelect).toHaveBeenCalledOnce();
});
it("marks card as selected when isSelected is true", async () => {
it("does not mark widget cards as selected", async () => {
const item = {
kind: "clock" as WidgetKind,
name: "Clock",
@@ -204,7 +204,7 @@ describe("Advanced Add App - Modal Subcomponents", () => {
);
const button = host.querySelector("button");
expect(button?.getAttribute("data-selected")).toBe("true");
expect(button?.hasAttribute("data-selected")).toBe(false);
});
});
});
@@ -484,7 +484,7 @@ const ItemSelectModalContent = ({
description={def.description ?? ""}
footerLeft={
<Text size="xs" c="dimmed">
Custom Widget
{t("item.create.customWidget")}
</Text>
}
/>
@@ -569,10 +569,12 @@ export const ConnectionStatusBadge = ({ status }: { status: WidgetConnectionStat
};
export const SupportedIntegrations = ({ integrations }: { integrations: IntegrationKind[] }) => {
const t = useI18n();
if (integrations.length === 0) {
return (
<Text size="xs" c="dimmed" fs="italic">
Standalone
{t("item.create.standalone")}
</Text>
);
}
@@ -7,10 +7,10 @@ import { notifications } from "@mantine/notifications";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
import { useUpdateBoard } from "@homarr/boards/updater";
import { usePersistBoard } from "@homarr/boards/updater";
import { getBoardLaneColumnCount, getRootSectionLane } from "@homarr/definitions";
import { showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import type { ContainerSection, ItemLayout } from "~/app/[locale]/boards/_types";
import { getFirstEmptyPosition } from "~/components/board/items/actions/empty-position";
@@ -32,8 +32,23 @@ export const BoardSelectionProvider = ({ children }: PropsWithChildren) => {
const [isEditMode] = useEditMode();
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const { updateBoard } = useUpdateBoard();
const { updateAndPersistBoard } = usePersistBoard(board);
const t = useI18n();
const tSelection = useScopedI18n("item.selection");
const persistBoard = useCallback(
(updater: (previous: typeof board) => typeof board) => {
updateAndPersistBoard(updater, {
onError: () => {
showErrorNotification({
title: tSelection("saveErrorTitle"),
message: tSelection("saveErrorMessage"),
});
},
});
},
[tSelection, updateAndPersistBoard],
);
// Clear selection if leaving edit mode
useEffect(() => {
@@ -85,7 +100,7 @@ export const BoardSelectionProvider = ({ children }: PropsWithChildren) => {
playTrashSound();
clearSelection();
updateBoard((previous) => ({
persistBoard((previous) => ({
...previous,
items: previous.items.filter((item) => !idsToRemove.includes(item.id)),
}));
@@ -96,12 +111,12 @@ export const BoardSelectionProvider = ({ children }: PropsWithChildren) => {
title: t("common.success"),
message: (
<Group justify="space-between" wrap="nowrap">
<Text size="sm">{count === 1 ? "1 item removed" : `${count} items removed`}</Text>
<Text size="sm">{tSelection("removed", { count })}</Text>
<Button
variant="subtle"
size="compact-xs"
onClick={() => {
updateBoard((previous) => ({
persistBoard((previous) => ({
...previous,
items: [...previous.items, ...removedItems],
}));
@@ -114,73 +129,40 @@ export const BoardSelectionProvider = ({ children }: PropsWithChildren) => {
),
autoClose: 10_000,
});
}, [board.items, clearSelection, selectedItemIds, t, updateBoard]);
}, [board.items, clearSelection, persistBoard, selectedItemIds, t, tSelection]);
const moveSelectedItemsToSection = useCallback(
(targetSectionId: string) => {
if (selectedItemIds.size === 0) return;
const idsToMove = Array.from(selectedItemIds);
const idsToMove = new Set(selectedItemIds);
updateBoard((previous) => {
persistBoard((previous) => {
const targetSection = previous.sections.find((section) => section.id === targetSectionId);
if (!targetSection) return previous;
const boardLayout = previous.layouts.find((layout) => layout.id === currentLayoutId);
if (!targetSection || !boardLayout) return previous;
const itemsToMove = previous.items.filter((item) => idsToMove.includes(item.id));
const untouchedItems = previous.items.filter((item) => !idsToMove.includes(item.id));
const containerLayout =
targetSection.kind === "container"
? targetSection.layouts.find((layout) => layout.layoutId === currentLayoutId)
: undefined;
const columnCount =
targetSection.kind === "container"
? (containerLayout?.width ?? 0)
: getBoardLaneColumnCount(boardLayout, getRootSectionLane(targetSection.xOffset));
const rowCount = containerLayout?.height ?? 9999;
if (columnCount === 0 || rowCount === 0) return previous;
// Map of itemId -> layoutId -> new ItemLayout
const updatedItemLayoutsMap = new Map<string, Map<string, ItemLayout>>();
for (const item of itemsToMove) {
updatedItemLayoutsMap.set(item.id, new Map());
}
const acceptedItemIds = new Set<string>();
const layoutsToProcess = previous.layouts.toSorted(
(left, right) => Number(right.id === currentLayoutId) - Number(left.id === currentLayoutId),
);
for (const boardLayout of layoutsToProcess) {
const containerLayout =
targetSection.kind === "container"
? targetSection.layouts.find((layout) => layout.layoutId === boardLayout.id)
: undefined;
const columnCount =
targetSection.kind === "container"
? (containerLayout?.width ?? 0)
: getBoardLaneColumnCount(boardLayout, getRootSectionLane(targetSection.xOffset));
const rowCount = containerLayout?.height ?? 9999;
if (columnCount === 0 || rowCount === 0) continue;
// Collect existing elements in targetSection for this layout (excluding items to move)
const existingContainers = previous.sections
.filter((section): section is ContainerSection => section.kind === "container")
.flatMap((section) => {
const layout = section.layouts.find(
(l) => l.layoutId === boardLayout.id && l.parentSectionId === targetSection.id,
);
return layout
? [
{
id: section.id,
xOffset: layout.xOffset,
yOffset: layout.yOffset,
width: layout.width,
height: layout.height,
},
]
: [];
});
const existingItems = previous.items.flatMap((item) => {
const layout = item.layouts.find((layout) => {
return layout.layoutId === boardLayout.id && layout.sectionId === targetSection.id;
});
const existingContainers = previous.sections
.filter((section): section is ContainerSection => section.kind === "container")
.flatMap((section) => {
const layout = section.layouts.find(
(candidate) => candidate.layoutId === currentLayoutId && candidate.parentSectionId === targetSection.id,
);
return layout
? [
{
id: item.id,
id: section.id,
xOffset: layout.xOffset,
yOffset: layout.yOffset,
width: layout.width,
@@ -189,74 +171,70 @@ export const BoardSelectionProvider = ({ children }: PropsWithChildren) => {
]
: [];
});
const existingItems = previous.items.flatMap((item) => {
const layout = item.layouts.find(
(candidate) => candidate.layoutId === currentLayoutId && candidate.sectionId === targetSection.id,
);
return layout
? [
{
id: item.id,
xOffset: layout.xOffset,
yOffset: layout.yOffset,
width: layout.width,
height: layout.height,
},
]
: [];
});
const occupiedPositions = [...existingContainers, ...existingItems];
const movedLayouts = new Map<string, ItemLayout>();
const occupiedPositions = [...existingContainers, ...existingItems];
for (const item of previous.items.filter((candidate) => idsToMove.has(candidate.id))) {
const currentItemLayout = item.layouts.find((layout) => layout.layoutId === currentLayoutId);
if (!currentItemLayout) continue;
// Place each item being moved into the first available space. The current
// layout decides which selected items can participate in the move; items
// that do not fit there remain untouched in every layout.
for (const item of itemsToMove) {
if (boardLayout.id !== currentLayoutId && !acceptedItemIds.has(item.id)) continue;
const previousPositionIndex = occupiedPositions.findIndex((position) => position.id === item.id);
const previousPosition =
previousPositionIndex >= 0 ? occupiedPositions.splice(previousPositionIndex, 1).at(0) : undefined;
const { width, height } = currentItemLayout;
const emptyPosition =
width <= columnCount && height <= rowCount
? getFirstEmptyPosition(occupiedPositions, columnCount, rowCount, { width, height })
: undefined;
const currentItemLayout = item.layouts.find((layout) => layout.layoutId === boardLayout.id);
if (!currentItemLayout) continue;
const previousPositionIndex = occupiedPositions.findIndex((position) => position.id === item.id);
const previousPosition =
previousPositionIndex >= 0 ? occupiedPositions.splice(previousPositionIndex, 1).at(0) : undefined;
const { width, height } = currentItemLayout;
if (width > columnCount || height > rowCount) {
if (previousPosition) occupiedPositions.push(previousPosition);
continue;
}
const emptyPosition = getFirstEmptyPosition(occupiedPositions, columnCount, rowCount, { width, height });
if (!emptyPosition) {
if (previousPosition) occupiedPositions.push(previousPosition);
continue;
}
if (boardLayout.id === currentLayoutId) acceptedItemIds.add(item.id);
const newLayout: ItemLayout = {
layoutId: boardLayout.id,
sectionId: targetSectionId,
xOffset: emptyPosition.xOffset,
yOffset: emptyPosition.yOffset,
width,
height,
};
occupiedPositions.push({
id: item.id,
xOffset: emptyPosition.xOffset,
yOffset: emptyPosition.yOffset,
width,
height,
});
updatedItemLayoutsMap.get(item.id)?.set(boardLayout.id, newLayout);
if (!emptyPosition) {
if (previousPosition) occupiedPositions.push(previousPosition);
continue;
}
const nextLayout: ItemLayout = {
...currentItemLayout,
sectionId: targetSectionId,
xOffset: emptyPosition.xOffset,
yOffset: emptyPosition.yOffset,
};
movedLayouts.set(item.id, nextLayout);
occupiedPositions.push({ id: item.id, ...emptyPosition, width, height });
}
const updatedMovedItems = itemsToMove.map((item) => {
const itemLayoutsMap = updatedItemLayoutsMap.get(item.id);
const newLayouts = item.layouts.map((layout) => itemLayoutsMap?.get(layout.layoutId) ?? layout);
return {
...item,
layouts: newLayouts,
};
});
if (movedLayouts.size === 0) return previous;
return {
...previous,
items: [...untouchedItems, ...updatedMovedItems],
items: previous.items.map((item) => {
const movedLayout = movedLayouts.get(item.id);
if (!movedLayout) return item;
return {
...item,
layouts: item.layouts.map((layout) => (layout.layoutId === currentLayoutId ? movedLayout : layout)),
};
}),
};
});
clearSelection();
},
[clearSelection, currentLayoutId, selectedItemIds, updateBoard],
[clearSelection, currentLayoutId, persistBoard, selectedItemIds],
);
const value = useMemo(
@@ -3,7 +3,6 @@
import {
ActionIcon,
Avatar,
Box,
Button,
Divider,
Group,
@@ -14,6 +13,7 @@ import {
Stack,
Text,
Tooltip,
UnstyledButton,
} from "@mantine/core";
import { IconCheck, IconFolderShare, IconTrash, IconX } from "@tabler/icons-react";
@@ -21,7 +21,7 @@ import { clientApi } from "@homarr/api/client";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
import { getBoardLaneColumnCount, getRootSectionLane } from "@homarr/definitions";
import { useI18n } from "@homarr/translation/client";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { widgetCatalogIcons } from "@homarr/widgets/catalog";
import type { EmptySection } from "~/app/[locale]/boards/_types";
@@ -36,6 +36,7 @@ export const BoardSelectionToolbar = () => {
const currentLayoutId = useCurrentLayout();
const currentLayout = board.layouts.find((layout) => layout.id === currentLayoutId);
const t = useI18n();
const tSelection = useScopedI18n("item.selection");
const selectedItems = board.items.filter((item) => selectedItemIds.has(item.id));
const hasAppWidgets = selectedItems.some((item) => item.kind === "app");
@@ -121,7 +122,8 @@ export const BoardSelectionToolbar = () => {
left: "50%",
transform: "translateX(-50%)",
zIndex: 1000,
maxWidth: "min(92vw, 760px)",
width: "max-content",
maxWidth: "calc(100vw - 1rem)",
boxShadow: "0 12px 40px rgba(0, 0, 0, 0.28)",
backdropFilter: "blur(14px)",
border: "1px solid var(--mantine-color-default-border)",
@@ -132,7 +134,11 @@ export const BoardSelectionToolbar = () => {
{/* Avatar Group with HoverCard Popover showing all items */}
<HoverCard position="top" withArrow shadow="xl" radius="md" openDelay={100} closeDelay={200} withinPortal>
<HoverCard.Target>
<Box style={{ cursor: "pointer", display: "inline-flex", alignItems: "center" }}>
<UnstyledButton
display="inline-flex"
aria-label={tSelection("summary", { count: sortedSelectedItems.length })}
style={{ alignItems: "center", borderRadius: "var(--mantine-radius-xl)" }}
>
<Avatar.Group>
{visibleItems.map((item) => {
const { displayName, iconUrl, IconComponent } = getItemDetails(item);
@@ -157,13 +163,13 @@ export const BoardSelectionToolbar = () => {
</Avatar>
)}
</Avatar.Group>
</Box>
</UnstyledButton>
</HoverCard.Target>
<HoverCard.Dropdown p={6} style={{ width: 220 }}>
<Stack gap={4}>
<Text size="10px" fw={700} c="dimmed" tt="uppercase" px={4}>
{sortedSelectedItems.length} selected
{tSelection("selected", { count: sortedSelectedItems.length })}
</Text>
<ScrollArea.Autosize mah={176} type="auto">
@@ -203,11 +209,11 @@ export const BoardSelectionToolbar = () => {
<Menu position="top" withArrow shadow="md">
<Menu.Target>
<Button size="xs" variant="light" color="primaryColor" leftSection={<IconFolderShare size={15} />}>
Move
{tSelection("move")}
</Button>
</Menu.Target>
<Menu.Dropdown>
<Menu.Label>Move selected to section</Menu.Label>
<Menu.Label>{tSelection("moveTo")}</Menu.Label>
{placementOptions.map((opt) => (
<Menu.Item key={opt.value} onClick={() => moveSelectedItemsToSection(opt.value)}>
{opt.label}
@@ -224,11 +230,17 @@ export const BoardSelectionToolbar = () => {
leftSection={<IconTrash size={15} />}
onClick={removeSelectedItems}
>
Delete
{tSelection("delete")}
</Button>
<Tooltip label="Deselect (Escape)" withArrow>
<ActionIcon size="sm" variant="subtle" color="gray" onClick={clearSelection} aria-label="Clear selection">
<Tooltip label={tSelection("clearShortcut")} withArrow>
<ActionIcon
size="sm"
variant="subtle"
color="gray"
onClick={clearSelection}
aria-label={tSelection("clear")}
>
<IconX size={14} />
</ActionIcon>
</Tooltip>
@@ -37,7 +37,7 @@ export const useSetupAnalytics = () => {
onError() {
showErrorNotification({
title: t("common.error"),
message: t("common.error"),
message: t("common.analyticsError"),
});
},
});