Files
Termix/src/ui/features/homepage/HomepageCanvas.tsx
T
Luke Gustafson 9de904dd4c release-2.5.0 (#994)
* feat(sshid) - sshid.io equivalent for termix (#919)

* feat(ssh-id): database schema, migrations and field encryption

Adds ssh_identities, ssh_identity_keys and ssh_identity_ca tables (public keys
stored plaintext for the unauthenticated resolver; CA private key registered
for per-user field encryption), with UNIQUE(user_id), an index on
ssh_identity_keys(identity_id), and idempotent CREATE TABLE migrations.

* feat(ssh-id): backend API — resolver, key management, CA and certificates

Mounts /sshid (nginx route added). Public text/plain authorized_keys resolver
(+ exact /:algo filter, HTML viewer) and CA public-key endpoint; no-store +
noindex headers on every resolver response including early 404s. Authenticated
management: claim/rename/delete handle, add/import/generate/enable/delete keys,
and a per-user CA (create/rotate/delete) with pure-Node OpenSSH certificate
issuance. Audit logging on all mutations; UNIQUE races map to a precise 409.
Unit tests for key parsing and certificate signing (ssh-keygen-validated).

* feat(ssh-id): frontend panel, API client and i18n

SSH ID panel wired into the app rail and AppShell: claim handle, resolver URL +
curl one-liner, key list, generate, paste/import, CA enable/rotate/remove with
server trust command, and per-key certificate issuance. API client re-exported
through main-axios.ts; all strings i18n'd.

* style(ssh-id): align panel and resolver page with Termix theme

- Rebuild the SSH ID sidebar panel with the theme's square components
  (SectionCard / SettingRow / FakeSwitch) instead of rounded ad-hoc cards;
  use accent-brand and destructive tokens rather than raw red/green.
- Fix panel scrolling: move overflow to a block scroll container so the
  cards keep their natural height instead of being clipped.
- Restyle the public resolver HTML page (/sshid/u/:handle) to the Termix
  dark theme: square corners, #18181b/#303032 palette, #f59145 accent,
  uppercase section labels.
- Tidy copy: 'Save To Credentials' label, drop the redundant generate intro,
  and correct the generate tooltip (the key is stored when saving to vault).

* feat: rename to Termix ID, improve UI, backend inconsistencies, and general bug fixes

---------

Co-authored-by: LukeGus <bugattiguy527@gmail.com>

* ci(deps): bump actions/checkout from 6 to 7 in the github-actions group (#922)

Bumps the github-actions group with 1 update: [actions/checkout](https://github.com/actions/checkout).


Updates `actions/checkout` from 6 to 7
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump the dev-patch-updates group with 11 updates (#923)

Bumps the dev-patch-updates group with 11 updates:

| Package | From | To |
| --- | --- | --- |
| [@codemirror/search](https://github.com/codemirror/search) | `6.7.0` | `6.7.1` |
| [@codemirror/view](https://github.com/codemirror/view) | `6.43.0` | `6.43.1` |
| [@tailwindcss/vite](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/@tailwindcss-vite) | `4.3.0` | `4.3.1` |
| [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) | `4.1.8` | `4.1.9` |
| [@vitest/ui](https://github.com/vitest-dev/vitest/tree/HEAD/packages/ui) | `4.1.8` | `4.1.9` |
| [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) | `0.5.2` | `0.5.3` |
| [lint-staged](https://github.com/lint-staged/lint-staged) | `17.0.7` | `17.0.8` |
| [prettier](https://github.com/prettier/prettier) | `3.8.3` | `3.8.4` |
| [sharp](https://github.com/lovell/sharp) | `0.35.1` | `0.35.2` |
| [tailwindcss](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/tailwindcss) | `4.3.0` | `4.3.1` |
| [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `4.1.8` | `4.1.9` |


Updates `@codemirror/search` from 6.7.0 to 6.7.1
- [Changelog](https://github.com/codemirror/search/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/search/commits)

Updates `@codemirror/view` from 6.43.0 to 6.43.1
- [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/view/commits)

Updates `@tailwindcss/vite` from 4.3.0 to 4.3.1
- [Release notes](https://github.com/tailwindlabs/tailwindcss/releases)
- [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.1/packages/@tailwindcss-vite)

Updates `@vitest/coverage-v8` from 4.1.8 to 4.1.9
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.9/packages/coverage-v8)

Updates `@vitest/ui` from 4.1.8 to 4.1.9
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.9/packages/ui)

Updates `eslint-plugin-react-refresh` from 0.5.2 to 0.5.3
- [Release notes](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/releases)
- [Changelog](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/compare/v0.5.2...v0.5.3)

Updates `lint-staged` from 17.0.7 to 17.0.8
- [Release notes](https://github.com/lint-staged/lint-staged/releases)
- [Changelog](https://github.com/lint-staged/lint-staged/blob/main/CHANGELOG.md)
- [Commits](https://github.com/lint-staged/lint-staged/compare/v17.0.7...v17.0.8)

Updates `prettier` from 3.8.3 to 3.8.4
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.8.3...3.8.4)

Updates `sharp` from 0.35.1 to 0.35.2
- [Release notes](https://github.com/lovell/sharp/releases)
- [Commits](https://github.com/lovell/sharp/compare/v0.35.1...v0.35.2)

Updates `tailwindcss` from 4.3.0 to 4.3.1
- [Release notes](https://github.com/tailwindlabs/tailwindcss/releases)
- [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.1/packages/tailwindcss)

Updates `vitest` from 4.1.8 to 4.1.9
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.9/packages/vitest)

---
updated-dependencies:
- dependency-name: "@codemirror/search"
  dependency-version: 6.7.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@codemirror/view"
  dependency-version: 6.43.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@tailwindcss/vite"
  dependency-version: 4.3.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@vitest/coverage-v8"
  dependency-version: 4.1.9
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@vitest/ui"
  dependency-version: 4.1.9
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: eslint-plugin-react-refresh
  dependency-version: 0.5.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: lint-staged
  dependency-version: 17.0.8
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: prettier
  dependency-version: 3.8.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: sharp
  dependency-version: 0.35.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: tailwindcss
  dependency-version: 4.3.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: vitest
  dependency-version: 4.1.9
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump nanoid in the prod-patch-updates group (#925)

Bumps the prod-patch-updates group with 1 update: [nanoid](https://github.com/ai/nanoid).


Updates `nanoid` from 5.1.11 to 5.1.15
- [Release notes](https://github.com/ai/nanoid/releases)
- [Changelog](https://github.com/ai/nanoid/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ai/nanoid/compare/5.1.11...5.1.15)

---
updated-dependencies:
- dependency-name: nanoid
  dependency-version: 5.1.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump the major-updates group with 5 updates (#926)

Bumps the major-updates group with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [js-yaml](https://github.com/nodeca/js-yaml) | `4.2.0` | `5.0.0` |
| [@eslint/js](https://github.com/eslint/eslint/tree/HEAD/packages/js) | `9.39.4` | `10.0.1` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `25.9.2` | `26.0.0` |
| [concurrently](https://github.com/open-cli-tools/concurrently) | `9.2.1` | `10.0.3` |
| [eslint](https://github.com/eslint/eslint) | `9.39.4` | `10.5.0` |


Updates `js-yaml` from 4.2.0 to 5.0.0
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.2.0...5.0.0)

Updates `@eslint/js` from 9.39.4 to 10.0.1
- [Release notes](https://github.com/eslint/eslint/releases)
- [Commits](https://github.com/eslint/eslint/commits/v10.0.1/packages/js)

Updates `@types/node` from 25.9.2 to 26.0.0
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `concurrently` from 9.2.1 to 10.0.3
- [Release notes](https://github.com/open-cli-tools/concurrently/releases)
- [Commits](https://github.com/open-cli-tools/concurrently/compare/v9.2.1...v10.0.3)

Updates `eslint` from 9.39.4 to 10.5.0
- [Release notes](https://github.com/eslint/eslint/releases)
- [Commits](https://github.com/eslint/eslint/compare/v9.39.4...v10.5.0)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 5.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: major-updates
- dependency-name: "@eslint/js"
  dependency-version: 10.0.1
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: major-updates
- dependency-name: "@types/node"
  dependency-version: 26.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: major-updates
- dependency-name: concurrently
  dependency-version: 10.0.3
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: major-updates
- dependency-name: eslint
  dependency-version: 10.5.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: major-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* feat(ssh): add HashiCorp Vault SSH signer authentication

* fix: small fixes to vault feature to align with Termix codebase

* chore: add view docs links for vault/termix id

* fix: file upload fails with 400 and missing schema migrations on upgrade (#929)

Two bugs introduced in v2.4.1:

1. uploadFileStream uses fileManagerApi.post() which triggers axios's
   transformRequest to JSON-serialize the FormData because the instance
   default Content-Type is application/json. Change to postForm() which
   sets Content-Type: multipart/form-data so the browser XHR sends the
   correct multipart body with boundary.

2. Two schema items added to schema.ts were not included in migrateSchema()
   in db/index.ts, causing 500 errors on existing installations upgrading
   from v2.4.0:
   - user_preferences.status_color_scheme (no such column)
   - dashboard_service_links table (no such table)

Fixes #928

Co-authored-by: sash <sash@fominykh.io>

* fix: support PuTTY PPK ssh keys (#930)

* fix: chunk large file manager uploads (#932)

* fix: route dashboard hosts by protocol (#934)

* fix: resolve tunnel endpoints reliably (#935)

* Fix Electron OIDC browser auth failures (#936)

* Allow RDP connections without stored credentials (#937)

* Sync role credential shares for OIDC users (#938)

* Fix terminal link dialog layering (#940)

* Confirm large files before opening editor (#942)

* Confirm closing active host connections (#943)

* Preserve file path case in file manager UI (#941)

* fix: preserve unicode guacamole tokens (#933)

* Persist VNC authentication settings (#944)

* Fix Guacamole websocket base path (#946)

* Promote file manager terminals to tabs (#939)

* Guard Guacamole disconnect during startup (#945)

* chore: increment ver

* feat: bitwarden ssh agent integration

* feat: serial connections support

* fix: various small bug fixes

* feat: open all sessions in a folder and terminal custom theme color support

* feat: cross host file manager clipboard and several small bug fixes

* feat: tailscale/wireguard support and added a new status state for when backend is checking status

* feat: grafana like server stats history, new alert system, ntfy/webhook support

* feat: new grid and widget based homepage function

* feat: new donate button in dashboard

* fix: alert ui incorrectly using termix css and fixed issue with alert system not loading

* chore: fix ci checks (#966)

* Fix dashboard service link creation (#950)

* Fix jump host SOCKS5 proxy selection (#951)

* Fix jump host SOCKS5 proxy selection

* fix: type jump host socks proxy config

* Fix tmux detection path handling (#949)

* Support GUACD_URL environment config (#952)

* Retry autostart tunnel host fetches (#953)

* Retry autostart tunnel host fetches

* chore: format tunnel route

* Fix PUID html ownership in Docker entrypoint (#954)

* feat: allow custom tunnel endpoints (#977)

* fix: skip metrics start for non-ssh hosts (#976)

* Fix Proxmox import auth fallback (#956)

* Fix Proxmox import auth fallback

* chore: format proxmox import auth

* Fix SSH heading syntax highlighting (#955)

* Fix SSH heading syntax highlighting

* chore: format terminal highlighter

* Initialize auth before fullscreen terminal routes (#957)

* Add WebAuthn passkey authentication (#959)

* chore: add Biome tooling (#965)

* chore: add biome tooling

* chore: support tailwind syntax in biome

* Fix VNC required argument handshake (#968)

* Prioritize host results in command palette search (#969)

* Prevent sidebar host hover layout shift (#970)

* Add terminal font zoom with mouse wheel (#971)

* Add host temperature metrics card (#972)

* Make file downloads reliable in desktop app (#973)

* Add app rail hover expansion setting (#974)

* fix: use correct translation key for nav.close (#964)

* fix(tunnel): skip endpoint credential validation for direct tunnels (#963)

* fix: SSH port connection bug (#975)

* fix: chunked upload for files >=1.5GB to bypass browser ArrayBuffer limit (#948)

* feat: support SSH agent auth across SSH features (#960)

* feat: add Podman container runtime support (#958)

* chore: update readme and release notes

* fix: stabilize Windows app icon (#978)

* Add safe host sharing export (#979)

* Add external editor support for file manager (#985)

* Rework SSH credential password handling (#984)

* Support password fallback for SSH key credentials

* Complete SSH credential password fallback

* Fix runtime base path for auth callbacks (#982)

* Fix TUI terminal output highlighting (#983)

Co-authored-by: LukeGus <bugattiguy527@gmail.com>

* Add app fullscreen mode (#993)

* Fix host metrics startup polling (#986)

* chore: update release notes

* fix: line chart text overlap

* chore: update RELEASE_NOTES.md

* chore: add donation goal to readme

* chore: update readme

* fix: hide full-screen button in electron app

* fix: failed unit tests

* chore: lint, format, and bump version to 2.5.0

* chore: remove timeout from crowdin translate

* chore: sync Crowdin translations for 2.5.0

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: DivByZero <mr.oplus@yahoo.fr>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: devdanetra <46488477+devdanetra@users.noreply.github.com>
Co-authored-by: Aleksandr Fominykh <neoformalex@users.noreply.github.com>
Co-authored-by: sash <sash@fominykh.io>
Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com>
2026-06-29 13:28:26 -05:00

572 lines
17 KiB
TypeScript

import { useState, useEffect, useCallback, useRef } from "react";
import { useTranslation } from "react-i18next";
import { LayoutGrid } from "lucide-react";
import type {
CanvasWidget,
ContextMenuState,
WidgetTypeId,
} from "@/types/homepage-types";
import { GRID_SIZE, MIN_ZOOM, MAX_ZOOM } from "@/types/homepage-types";
import {
getHomepageItems,
getHomepageLayout,
createHomepageItem,
updateHomepageItem,
deleteHomepageItem,
saveHomepageLayout,
} from "@/api/homepage-api";
import { snapToGrid } from "./canvas/snapToGrid";
import { screenToCanvas } from "./canvas/canvasGeometry";
import { useCanvasInput } from "./canvas/useCanvasInput";
import { useBoxDrag } from "./canvas/useBoxDrag";
import { useBoxResize } from "./canvas/useBoxResize";
import { CanvasDotBackground } from "./canvas/CanvasDotBackground";
import { WidgetShell } from "./widgets/WidgetShell";
import { AddWidgetMenu } from "./dialogs/AddWidgetMenu";
import { WidgetEditDialog } from "./dialogs/WidgetEditDialog";
import { HomepageToolbar } from "./toolbar/HomepageToolbar";
import { getWidgetType } from "./widgets/WidgetRegistry";
// Side-effect imports so widgets register themselves
import "./widgets/ServiceLinkWidget";
import "./widgets/ClockWidget";
import "./widgets/NotesWidget";
import "./widgets/BookmarkListWidget";
import "./widgets/HostStatusWidget";
import "./widgets/FolderWidget";
import "./widgets/WeatherWidget";
import "./widgets/IframeWidget";
import "./widgets/RssFeedWidget";
import "./widgets/MetricsChartWidget";
import "./widgets/HostGridWidget";
import "./widgets/AlertFeedWidget";
import "./widgets/PingStatusWidget";
import "./widgets/RecentActivityWidget";
import "./widgets/TermixUptimeWidget";
import "./widgets/SystemOverviewWidget";
import "./widgets/SshTerminalWidget";
import "./widgets/QuickConnectWidget";
import "./widgets/FileManagerWidget";
import "./widgets/DockerWidget";
import "./widgets/TunnelWidget";
import "./widgets/CalendarWidget";
import "./widgets/CountdownWidget";
import "./widgets/SearchBarWidget";
import "./widgets/TextBannerWidget";
import "./widgets/ImageWidget";
import "./widgets/MarkdownNotesWidget";
import "./widgets/CustomApiWidget";
import "./widgets/ServiceGridWidget";
import "./widgets/DashboardLinksWidget";
import "./widgets/SearchLinksWidget";
import "./widgets/LinkTreeWidget";
const CANVAS_SIZE = 100_000;
const DEFAULT_PAN = { x: CANVAS_SIZE / 2 - 600, y: CANVAS_SIZE / 2 - 400 };
const DEFAULT_ZOOM = 1.0;
interface HomepageCanvasProps {
isReadOnly?: boolean;
fitOnLoad?: boolean;
onOpenFullscreen?: () => void;
}
function nextZOrder(widgets: CanvasWidget[]): number {
const nonFolders = widgets.filter((w) => w.typeId !== "folder");
return nonFolders.length === 0
? 1
: Math.max(...nonFolders.map((w) => w.zOrder)) + 1;
}
export function HomepageCanvas({
isReadOnly,
fitOnLoad,
onOpenFullscreen,
}: HomepageCanvasProps) {
const { t } = useTranslation();
const containerRef = useRef<HTMLDivElement>(null);
const [widgets, setWidgets] = useState<CanvasWidget[]>([]);
const [pan, setPan] = useState(DEFAULT_PAN);
const [zoom, setZoom] = useState(DEFAULT_ZOOM);
const [isLocked, setIsLocked] = useState(
() => localStorage.getItem("homepage.locked") === "true",
);
const [draggingId, setDraggingId] = useState<number | null>(null);
const [resizingId, setResizingId] = useState<number | null>(null);
const [editingWidget, setEditingWidget] = useState<CanvasWidget | null>(null);
const [dialogKey, setDialogKey] = useState(0);
const [contextMenu, setContextMenu] = useState<ContextMenuState>({
visible: false,
screenX: 0,
screenY: 0,
canvasX: 0,
canvasY: 0,
});
const [containerSize, setContainerSize] = useState({ w: 800, h: 600 });
const [loading, setLoading] = useState(true);
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const panRef = useRef(pan);
const zoomRef = useRef(zoom);
const widgetsRef = useRef(widgets);
panRef.current = pan;
zoomRef.current = zoom;
widgetsRef.current = widgets;
const hasFitRef = useRef(false);
useEffect(() => {
const el = containerRef.current;
if (!el) return;
const ro = new ResizeObserver(() => {
setContainerSize({ w: el.offsetWidth, h: el.offsetHeight });
});
ro.observe(el);
return () => ro.disconnect();
}, []);
useEffect(() => {
let cancelled = false;
Promise.all([getHomepageItems(), getHomepageLayout()])
.then(([items, layoutRow]) => {
if (cancelled) return;
const layoutEntries = layoutRow?.layout?.entries ?? [];
const merged: CanvasWidget[] = items.map((item) => {
const entry = layoutEntries.find((e) => e.itemId === item.id);
const typeDef = getWidgetType(item.typeId as WidgetTypeId);
return {
id: item.id,
typeId: item.typeId as WidgetTypeId,
title: item.title,
config: JSON.parse(item.config || "{}"),
x: entry?.x ?? snapToGrid(Math.random() * 600 + 100),
y: entry?.y ?? snapToGrid(Math.random() * 400 + 100),
w: entry?.w ?? typeDef?.defaultSize.w ?? GRID_SIZE * 8,
h: entry?.h ?? typeDef?.defaultSize.h ?? GRID_SIZE * 6,
zOrder: entry?.zOrder ?? 0,
};
});
setWidgets(merged);
if (layoutRow?.layout?.pan) setPan(layoutRow.layout.pan);
if (layoutRow?.layout?.zoom) setZoom(layoutRow.layout.zoom);
})
.catch(() => {})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, []);
const scheduleSave = useCallback(
(newWidgets?: CanvasWidget[], newPan?: typeof pan, newZoom?: number) => {
if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
saveTimerRef.current = setTimeout(() => {
const ws = newWidgets ?? widgetsRef.current;
const p = newPan ?? panRef.current;
const z = newZoom ?? zoomRef.current;
saveHomepageLayout({
entries: ws.map((w) => ({
itemId: w.id,
x: w.x,
y: w.y,
w: w.w,
h: w.h,
zOrder: w.zOrder,
})),
pan: p,
zoom: z,
}).catch(() => {});
}, 500);
},
[],
);
useEffect(() => {
if (!fitOnLoad || loading || widgets.length === 0 || hasFitRef.current)
return;
const el = containerRef.current;
if (!el || el.offsetWidth === 0 || el.offsetHeight === 0) return;
hasFitRef.current = true;
const vw = el.offsetWidth;
const vh = el.offsetHeight;
const minX = Math.min(...widgets.map((w) => w.x));
const minY = Math.min(...widgets.map((w) => w.y));
const maxX = Math.max(...widgets.map((w) => w.x + w.w));
const maxY = Math.max(...widgets.map((w) => w.y + w.h));
const contentW = maxX - minX;
const contentH = maxY - minY;
const PADDING = 48;
const fz = Math.min(
MAX_ZOOM,
Math.max(
MIN_ZOOM,
Math.min((vw - PADDING * 2) / contentW, (vh - PADDING * 2) / contentH),
),
);
setPan({
x: (vw - contentW * fz) / 2 - minX * fz,
y: (vh - contentH * fz) / 2 - minY * fz,
});
setZoom(fz);
}, [fitOnLoad, loading, widgets, containerSize]);
const handlePanChange = useCallback(
(newPan: typeof pan) => {
setPan(newPan);
scheduleSave(undefined, newPan, undefined);
},
[scheduleSave],
);
const handleZoomChange = useCallback(
(newZoom: number, newPan: typeof pan) => {
setZoom(newZoom);
setPan(newPan);
scheduleSave(undefined, newPan, newZoom);
},
[scheduleSave],
);
const canvasInput = useCanvasInput({
isDraggingWidget: draggingId !== null,
isResizing: resizingId !== null,
isContextMenuVisible: contextMenu.visible,
onPanChange: handlePanChange,
onZoomChange: handleZoomChange,
getPan: () => panRef.current,
getZoom: () => zoomRef.current,
containerRef,
});
const handleWidgetMove = useCallback(
(id: number, x: number, y: number) => {
setWidgets((prev) => {
const next = prev.map((w) => (w.id === id ? { ...w, x, y } : w));
scheduleSave(next);
return next;
});
},
[scheduleSave],
);
const handleWidgetResize = useCallback(
(id: number, w: number, h: number) => {
setWidgets((prev) => {
const next = prev.map((widget) =>
widget.id === id ? { ...widget, w, h } : widget,
);
scheduleSave(next);
return next;
});
},
[scheduleSave],
);
const handleDragStart = useCallback(
(id: number) => {
setDraggingId(id);
setWidgets((prev) => {
const widget = prev.find((w) => w.id === id);
if (!widget || widget.typeId === "folder") return prev;
const top = nextZOrder(prev);
const next = prev.map((w) => (w.id === id ? { ...w, zOrder: top } : w));
scheduleSave(next);
return next;
});
},
[scheduleSave],
);
const { startDrag } = useBoxDrag({
widgets,
zoom,
getZoom: () => zoomRef.current,
onWidgetMove: handleWidgetMove,
onDragStart: handleDragStart,
onDragEnd: () => setDraggingId(null),
});
const { startResize } = useBoxResize({
widgets,
getZoom: () => zoomRef.current,
onWidgetResize: handleWidgetResize,
onResizeStart: setResizingId,
onResizeEnd: () => setResizingId(null),
});
const handleContextMenu = useCallback(
(e: React.MouseEvent) => {
if (isLocked || isReadOnly) return;
if ((e.target as HTMLElement).closest("[data-widget]")) return;
e.preventDefault();
const rect = containerRef.current!.getBoundingClientRect();
const sx = e.clientX - rect.left;
const sy = e.clientY - rect.top;
const { x, y } = screenToCanvas(sx, sy, panRef.current, zoomRef.current);
setContextMenu({
visible: true,
screenX: e.clientX,
screenY: e.clientY,
canvasX: snapToGrid(x),
canvasY: snapToGrid(y),
});
},
[isLocked, isReadOnly],
);
const handleAddWidget = useCallback(
async (typeId: WidgetTypeId, canvasX: number, canvasY: number) => {
const typeDef = getWidgetType(typeId);
if (!typeDef) return;
try {
const item = await createHomepageItem({
typeId,
config: typeDef.defaultConfig as Record<string, unknown>,
});
setWidgets((prev) => {
const zOrder = typeId === "folder" ? 0 : nextZOrder(prev);
const newWidget: CanvasWidget = {
id: item.id,
typeId,
title: item.title,
config: typeDef.defaultConfig as Record<string, unknown>,
x: canvasX,
y: canvasY,
w: typeDef.defaultSize.w,
h: typeDef.defaultSize.h,
zOrder,
};
const next = [...prev, newWidget];
scheduleSave(next);
return next;
});
} catch {}
},
[scheduleSave],
);
const handleOpenAddMenu = useCallback(
(anchorRect: {
top: number;
bottom: number;
left: number;
right: number;
width: number;
height: number;
}) => {
const w = containerSize.w;
const h = containerSize.h;
const { x, y } = screenToCanvas(
w / 2,
h / 2,
panRef.current,
zoomRef.current,
);
setContextMenu({
visible: true,
screenX: anchorRect.left,
screenY: anchorRect.top,
canvasX: snapToGrid(x),
canvasY: snapToGrid(y),
anchorRect,
});
},
[containerSize],
);
const handleDelete = useCallback(
async (id: number) => {
try {
await deleteHomepageItem(id);
setWidgets((prev) => {
const next = prev.filter((w) => w.id !== id);
scheduleSave(next);
return next;
});
} catch {}
},
[scheduleSave],
);
const handleEdit = useCallback(
(id: number) => {
const w = widgets.find((x) => x.id === id);
if (w) {
setEditingWidget(w);
setDialogKey((k) => k + 1);
}
},
[widgets],
);
const handleSaveEdit = useCallback(
async (
id: number,
title: string | null,
config: Record<string, unknown>,
) => {
try {
await updateHomepageItem(id, { title, config });
setWidgets((prev) =>
prev.map((w) => (w.id === id ? { ...w, title, config } : w)),
);
} catch {}
},
[],
);
const resetView = useCallback(() => {
const ws = widgetsRef.current;
const el = containerRef.current;
const vw = el?.offsetWidth ?? 800;
const vh = el?.offsetHeight ?? 600;
if (ws.length === 0) {
setPan(DEFAULT_PAN);
setZoom(DEFAULT_ZOOM);
return;
}
const minX = Math.min(...ws.map((w) => w.x));
const minY = Math.min(...ws.map((w) => w.y));
const maxX = Math.max(...ws.map((w) => w.x + w.w));
const maxY = Math.max(...ws.map((w) => w.y + w.h));
const contentW = maxX - minX;
const contentH = maxY - minY;
const PADDING = 48;
const fitZoom = Math.min(
MAX_ZOOM,
Math.max(
MIN_ZOOM,
Math.min((vw - PADDING * 2) / contentW, (vh - PADDING * 2) / contentH),
),
);
// Place the content bbox center at the viewport center
const newPan = {
x: (vw - contentW * fitZoom) / 2 - minX * fitZoom,
y: (vh - contentH * fitZoom) / 2 - minY * fitZoom,
};
setZoom(fitZoom);
setPan(newPan);
scheduleSave(undefined, newPan, fitZoom);
}, [scheduleSave]);
// Folders always render first (lowest z), non-folders sorted by zOrder ascending
const sortedWidgets = [...widgets].sort((a, b) => {
const aFolder = a.typeId === "folder";
const bFolder = b.typeId === "folder";
if (aFolder && !bFolder) return -1;
if (!aFolder && bFolder) return 1;
return a.zOrder - b.zOrder;
});
if (loading) {
return (
<div className="flex items-center justify-center w-full h-full text-muted-foreground text-sm">
{t("homepage.loading")}
</div>
);
}
return (
<div
ref={containerRef}
className="relative w-full h-full overflow-hidden bg-background"
onMouseDown={editingWidget ? undefined : canvasInput.handleMouseDown}
onMouseMove={canvasInput.handleMouseMove}
onMouseUp={canvasInput.handleMouseUp}
onMouseLeave={canvasInput.handleMouseUp}
onWheel={canvasInput.handleWheel}
onContextMenu={handleContextMenu}
style={{ cursor: draggingId ? "grabbing" : "default" }}
>
<CanvasDotBackground pan={pan} zoom={zoom} />
<div
className="absolute origin-top-left"
style={{
width: CANVAS_SIZE,
height: CANVAS_SIZE,
transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
willChange: "transform",
}}
>
{sortedWidgets.map((widget) => (
<WidgetShell
key={widget.id}
widget={widget}
isLocked={isLocked}
isReadOnly={isReadOnly}
isDragging={draggingId === widget.id}
isResizing={resizingId === widget.id}
onStartDrag={startDrag}
onStartResize={startResize}
onDelete={handleDelete}
onEdit={handleEdit}
onConfigUpdate={(config) =>
handleSaveEdit(widget.id, widget.title, config)
}
/>
))}
</div>
{widgets.length === 0 && !isReadOnly && (
<div className="absolute inset-0 flex items-center justify-center pointer-events-none select-none">
<div className="flex items-center gap-2 bg-card border border-border px-3 py-2 shadow-sm">
<LayoutGrid className="size-3.5 text-muted-foreground/50 shrink-0" />
<span className="text-xs text-muted-foreground/70">
{t("homepage.noWidgets")}
</span>
</div>
</div>
)}
{isReadOnly && onOpenFullscreen && (
<button
className="absolute top-2 right-2 z-20 text-xs text-muted-foreground hover:text-foreground bg-card/80 border border-border px-2 py-1"
onClick={onOpenFullscreen}
>
{t("homepage.openFullView")}
</button>
)}
{!isReadOnly && (
<HomepageToolbar
zoom={zoom}
isLocked={isLocked}
pan={pan}
containerSize={containerSize}
onZoomChange={handleZoomChange}
onLockToggle={() =>
setIsLocked((v) => {
const next = !v;
localStorage.setItem("homepage.locked", String(next));
return next;
})
}
onResetView={resetView}
onAddWidget={handleOpenAddMenu}
/>
)}
<AddWidgetMenu
state={contextMenu}
onAdd={handleAddWidget}
onClose={() => setContextMenu((s) => ({ ...s, visible: false }))}
/>
<WidgetEditDialog
key={dialogKey}
widget={editingWidget}
onSave={handleSaveEdit}
onClose={() => setEditingWidget(null)}
/>
</div>
);
}