fix: address release v2 review findings

This commit is contained in:
ajnart committed 2026-08-26 14:51:16 +02:00
1 parent f0eddda573
commit 16e437decc
35 files changed
+587 -258

No files matched your search

+12 -7
View File
@@ -320,8 +320,12 @@ jobs:
publish-preview: publish-preview:
name: Publish multi-platform preview image name: Publish multi-platform preview image
needs: [preview-amd64, preview-arm64] needs: [container, preview-amd64, preview-arm64]
if: | if: |
!cancelled() &&
needs.container.result == 'success' &&
needs.preview-amd64.result == 'success' &&
needs.preview-arm64.result == 'success' &&
( (
(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) ||
(github.event_name == 'push' && github.ref == 'refs/heads/release/v2') || (github.event_name == 'push' && github.ref == 'refs/heads/release/v2') ||
@@ -375,9 +379,6 @@ jobs:
ARM64_DIGEST: ${{ needs.preview-arm64.outputs.digest }} ARM64_DIGEST: ${{ needs.preview-arm64.outputs.digest }}
run: | run: |
tags=(-t "${PREVIEW_IMAGE}:${PREVIEW_TAG}") tags=(-t "${PREVIEW_IMAGE}:${PREVIEW_TAG}")
if [[ "${GITHUB_EVENT_NAME}" == "push" && "${GITHUB_REF}" == "refs/heads/release/v2" ]]; then
tags+=(-t "${PREVIEW_IMAGE}:pr-6545")
fi
docker buildx imagetools create "${tags[@]}" \ docker buildx imagetools create "${tags[@]}" \
"${PREVIEW_IMAGE}@${AMD64_DIGEST}" \ "${PREVIEW_IMAGE}@${AMD64_DIGEST}" \
"${PREVIEW_IMAGE}@${ARM64_DIGEST}" "${PREVIEW_IMAGE}@${ARM64_DIGEST}"
@@ -386,9 +387,6 @@ jobs:
if: "!env.ACT" if: "!env.ACT"
run: | run: |
tags=("${PREVIEW_TAG}") tags=("${PREVIEW_TAG}")
if [[ "${GITHUB_EVENT_NAME}" == "push" && "${GITHUB_REF}" == "refs/heads/release/v2" ]]; then
tags+=("pr-6545")
fi
for tag in "${tags[@]}"; do for tag in "${tags[@]}"; do
image="${PREVIEW_IMAGE}:${tag}" image="${PREVIEW_IMAGE}:${tag}"
manifest="$(docker buildx imagetools inspect "$image" --raw)" manifest="$(docker buildx imagetools inspect "$image" --raw)"
@@ -435,6 +433,13 @@ jobs:
core.info(`No package version found with tag "${tag}"`); core.info(`No package version found with tag "${tag}"`);
return; return;
} }
const targetTags = target.metadata?.container?.tags ?? [];
if (targetTags.includes("v2")) {
core.setFailed(
`Package version ${target.id} also carries protected tag "v2"; refusing cleanup.`,
);
return;
}
await github.rest.packages.deletePackageVersionForOrg({ await github.rest.packages.deletePackageVersionForOrg({
package_type: "container", package_type: "container",
package_name: packageName, package_name: packageName,
@@ -36,7 +36,7 @@ pnpm cli harness setup feature-board
The command builds `homarr:feature-board`, starts a container with a persistent data volume, enables demo mode, and keeps demo mutations writable (`DEMO_READ_ONLY=false`). Docker assigns a free host port by default; use the URL printed by the command or query it later: The command builds `homarr:feature-board`, starts a container with a persistent data volume, enables demo mode, and keeps demo mutations writable (`DEMO_READ_ONLY=false`). Docker assigns a free host port by default; use the URL printed by the command or query it later:
The demo board includes every widget kind. Integration-backed widgets use the bundled mock integration; media widgets use public stock assets. The demo board includes every widget kind. Integration-backed widgets use the bundled mock integration; media widgets use bundled same-origin demo assets.
```sh ```sh
pnpm cli harness port feature-board pnpm cli harness port feature-board
@@ -128,6 +128,26 @@ You can decide if app status is disabled on all boards.
You can set the default color scheme for users without their own color scheme. You can set the default color scheme for users without their own color scheme.
## Branding
Branding settings let administrators adapt Homarr to the identity and visual style of their installation. Changes apply across the application and authentication pages after you save the settings.
### Identity
- **Application name** replaces the default Homarr name in page titles and branded surfaces.
- **Logo** is used in the header and other application branding.
- **Favicon** controls the browser tab icon. When it is empty, Homarr falls back to the configured logo.
### Colors and corners
Choose the primary and secondary colors used by the theme. **Lock primary color** prevents users from overriding the configured primary color. **Default corner style** controls the global radius used by cards, controls, and other interface elements.
### Sign-in page
You can set a greeting and a background image for authentication pages. The overlay slider adjusts the contrast between the background and the sign-in content. The visibility controls independently show or hide the application name, logo, and greeting.
Use an image URL that every user can load before signing in. A URL that requires an authenticated Homarr session will not work on the sign-in page.
## Culture ## Culture
### Default language ### Default language
@@ -9,6 +9,7 @@ import {
getQueryPersistenceStorageKey, getQueryPersistenceStorageKey,
queryPersistenceBuster, queryPersistenceBuster,
queryPersistenceMaxDataBytes, queryPersistenceMaxDataBytes,
queryPersistenceThrottleMs,
shouldPersistDashboardQuery, shouldPersistDashboardQuery,
} from "./query-persistence"; } from "./query-persistence";
@@ -54,6 +55,15 @@ describe("widget query persistence", () => {
queryKey: [["widget", "calendar", "findAllEvents"], { type: "query" }], queryKey: [["widget", "calendar", "findAllEvents"], { type: "query" }],
queryFn: () => Promise.resolve([]), queryFn: () => Promise.resolve([]),
}); });
const forbidden = createSuccessfulQuery(
[["widget", "calendar", "findAllEvents"], { type: "query" }],
[{ title: "revoked" }],
);
forbidden.query.setState({
...forbidden.query.state,
error: Object.assign(new Error("access denied"), { data: { code: "FORBIDDEN" } }),
status: "error",
});
expect(shouldPersistDashboardQuery(widget.query)).toBe(true); expect(shouldPersistDashboardQuery(widget.query)).toBe(true);
expect(shouldPersistDashboardQuery(supporting.query)).toBe(true); expect(shouldPersistDashboardQuery(supporting.query)).toBe(true);
@@ -61,6 +71,7 @@ describe("widget query persistence", () => {
expect(shouldPersistDashboardQuery(ping.query)).toBe(false); expect(shouldPersistDashboardQuery(ping.query)).toBe(false);
expect(shouldPersistDashboardQuery(oversized.query)).toBe(false); expect(shouldPersistDashboardQuery(oversized.query)).toBe(false);
expect(shouldPersistDashboardQuery(pending)).toBe(false); expect(shouldPersistDashboardQuery(pending)).toBe(false);
expect(shouldPersistDashboardQuery(forbidden.query)).toBe(false);
}); });
test("uses stable, isolated storage keys for anonymous and authenticated scopes", () => { test("uses stable, isolated storage keys for anonymous and authenticated scopes", () => {
@@ -170,6 +181,19 @@ describe("widget query persistence", () => {
expect(restored?.clientState.queries[0]?.state.isInvalidated).toBe(true); expect(restored?.clientState.queries[0]?.state.isInvalidated).toBe(true);
expect(window.sessionStorage.getItem(key)).not.toContain("private refresh error"); expect(window.sessionStorage.getItem(key)).not.toContain("private refresh error");
query.setState({
...query.state,
error: Object.assign(new Error("access denied"), { data: { code: "FORBIDDEN" } }),
status: "error",
});
persister.persistClient({
timestamp: Date.now(),
buster: queryPersistenceBuster,
clientState: dehydrate(queryClient),
});
persister.flush();
expect(window.sessionStorage.getItem(key)).toBeNull();
window.sessionStorage.setItem(key, "not-valid-superjson"); window.sessionStorage.setItem(key, "not-valid-superjson");
expect(persister.restoreClient()).toBeUndefined(); expect(persister.restoreClient()).toBeUndefined();
expect(window.sessionStorage.getItem(key)).toBeNull(); expect(window.sessionStorage.getItem(key)).toBeNull();
@@ -280,6 +304,10 @@ describe("widget query persistence", () => {
const restored = await persister.restoreClient(); const restored = await persister.restoreClient();
expect(restored?.clientState.queries).toHaveLength(1); expect(restored?.clientState.queries).toHaveLength(1);
expect(restored?.clientState.queries[0]?.queryKey).toEqual([["widget", "recent"], { type: "query" }]); expect(restored?.clientState.queries[0]?.queryKey).toEqual([["widget", "recent"], { type: "query" }]);
persister.persistClient(persistedClient);
persister.flush();
expect(setItemSpy).toHaveBeenCalledTimes(3);
}); });
test("coalesces pending writes and can synchronously flush the latest cache before reload", async () => { test("coalesces pending writes and can synchronously flush the latest cache before reload", async () => {
@@ -302,10 +330,12 @@ describe("widget query persistence", () => {
clientState: dehydrate(latest.queryClient), clientState: dehydrate(latest.queryClient),
}); });
expect(setItem).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(queryPersistenceThrottleMs - 1);
expect(setItem).not.toHaveBeenCalled(); expect(setItem).not.toHaveBeenCalled();
persister.flush(); persister.flush();
expect(setItem).toHaveBeenCalledOnce(); expect(setItem).toHaveBeenCalledOnce();
await vi.advanceTimersByTimeAsync(0); await vi.advanceTimersByTimeAsync(queryPersistenceThrottleMs);
expect(setItem).toHaveBeenCalledOnce(); expect(setItem).toHaveBeenCalledOnce();
const restored = await persister.restoreClient(); const restored = await persister.restoreClient();
@@ -1,12 +1,14 @@
import type { QueryKey } from "@tanstack/react-query"; import type { QueryKey } from "@tanstack/react-query";
import type { PersistedClient, Persister } from "@tanstack/react-query-persist-client"; import type { PersistedClient, Persister } from "@tanstack/react-query-persist-client";
import { removeOldestQuery } from "@tanstack/react-query-persist-client";
import { parse, stringify } from "superjson"; import { parse, stringify } from "superjson";
import { isWidgetDataQueryKey, queryCacheDefaultGcTimeMs } from "@homarr/api/query-cache"; import { isWidgetDataQueryKey, queryCacheDefaultGcTimeMs } from "@homarr/api/query-cache";
export const queryPersistenceMaxAgeMs = queryCacheDefaultGcTimeMs; export const queryPersistenceMaxAgeMs = queryCacheDefaultGcTimeMs;
export const queryPersistenceMaxDataBytes = 256 * 1024; export const queryPersistenceMaxDataBytes = 256 * 1024;
export const queryPersistenceMaxCacheBytes = 2 * 1024 * 1024;
export const queryPersistenceThrottleMs = 1_000;
export const queryPersistenceIdleTimeoutMs = 1_000;
export const queryPersistenceBuster = "v2-session-superjson"; export const queryPersistenceBuster = "v2-session-superjson";
const queryPersistenceStoragePrefix = "homarr:widget-query-cache"; const queryPersistenceStoragePrefix = "homarr:widget-query-cache";
@@ -19,6 +21,7 @@ interface PersistableQuery {
state: { state: {
data: unknown; data: unknown;
dataUpdatedAt: number; dataUpdatedAt: number;
error?: unknown;
}; };
} }
@@ -27,6 +30,28 @@ export type SessionQueryPersister = Persister & { flush: () => void; stop: () =>
const textEncoder = new TextEncoder(); const textEncoder = new TextEncoder();
const budgetVerdictCache = new WeakMap<object, boolean>(); const budgetVerdictCache = new WeakMap<object, boolean>();
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
interface ForbiddenTrpcError {
data: { code: "FORBIDDEN" };
}
const isTrpcForbiddenError = (error: unknown): error is ForbiddenTrpcError => {
if (!isRecord(error) || !isRecord(error.data)) return false;
return error.data.code === "FORBIDDEN";
};
const isQuotaExceededError = (error: unknown): boolean => {
if (!isRecord(error)) return false;
return (
error.name === "QuotaExceededError" ||
error.name === "NS_ERROR_DOM_QUOTA_REACHED" ||
error.code === 22 ||
error.code === 1014
);
};
const measureFitsBudget = (data: unknown) => { const measureFitsBudget = (data: unknown) => {
try { try {
return textEncoder.encode(stringify(data)).byteLength <= queryPersistenceMaxDataBytes; return textEncoder.encode(stringify(data)).byteLength <= queryPersistenceMaxDataBytes;
@@ -35,6 +60,8 @@ const measureFitsBudget = (data: unknown) => {
} }
}; };
const measureSerializedBytes = (data: unknown) => textEncoder.encode(stringify(data)).byteLength;
const fitsStorageBudget = (data: unknown) => { const fitsStorageBudget = (data: unknown) => {
if (typeof data !== "object" || data === null) return measureFitsBudget(data); if (typeof data !== "object" || data === null) return measureFitsBudget(data);
@@ -53,10 +80,25 @@ const holdsDashboardData = (query: PersistableQuery) =>
isWidgetDataQueryKey(query.queryKey); isWidgetDataQueryKey(query.queryKey);
export const shouldPersistDashboardQuery = (query: PersistableQuery) => export const shouldPersistDashboardQuery = (query: PersistableQuery) =>
holdsDashboardData(query) && fitsStorageBudget(query.state.data); holdsDashboardData(query) && !isTrpcForbiddenError(query.state.error) && fitsStorageBudget(query.state.data);
type DehydratedQuery = PersistedClient["clientState"]["queries"][number]; type DehydratedQuery = PersistedClient["clientState"]["queries"][number];
const keepNewestQueries = (client: PersistedClient, maximumQueries: number): PersistedClient | undefined => {
if (maximumQueries <= 0) return undefined;
if (client.clientState.queries.length <= maximumQueries) return client;
return {
...client,
clientState: {
...client.clientState,
queries: client.clientState.queries
.toSorted((left, right) => right.state.dataUpdatedAt - left.state.dataUpdatedAt)
.slice(0, maximumQueries),
},
};
};
const sanitizePersistedQuery = (query: DehydratedQuery): DehydratedQuery => ({ const sanitizePersistedQuery = (query: DehydratedQuery): DehydratedQuery => ({
...query, ...query,
state: { state: {
@@ -76,13 +118,12 @@ const sanitizePersistedClient = (client: PersistedClient): PersistedClient => ({
...client, ...client,
clientState: { clientState: {
mutations: [], mutations: [],
queries: client.clientState.queries.map(sanitizePersistedQuery), queries: client.clientState.queries
.filter((query) => !isTrpcForbiddenError(query.state.error))
.map(sanitizePersistedQuery),
}, },
}); });
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const isRestorableQuery = (value: unknown): value is DehydratedQuery => { const isRestorableQuery = (value: unknown): value is DehydratedQuery => {
if (!isRecord(value) || typeof value.queryHash !== "string" || !Array.isArray(value.queryKey)) return false; if (!isRecord(value) || typeof value.queryHash !== "string" || !Array.isArray(value.queryKey)) return false;
if (!isRecord(value.state) || typeof value.state.status !== "string") return false; if (!isRecord(value.state) || typeof value.state.status !== "string") return false;
@@ -146,15 +187,53 @@ export const createSessionQueryPersister = (
const key = getQueryPersistenceStorageKey(scope); const key = getQueryPersistenceStorageKey(scope);
removeForeignScopes(storage, key); removeForeignScopes(storage, key);
let pendingClient: PersistedClient | undefined; let pendingClient: PersistedClient | undefined;
let persistTimer: ReturnType<typeof setTimeout> | undefined; let persistDelayTimer: ReturnType<typeof setTimeout> | undefined;
let persistIdleCallback: number | undefined;
let persistedQueryLimit = Number.POSITIVE_INFINITY;
let persistenceDisabled = false;
let stopped = false; let stopped = false;
const persistNow = (client: PersistedClient) => { const trimToQueryLimit = (client: PersistedClient): PersistedClient | undefined => {
if (!storage) return; const limitedClient = keepNewestQueries(client, persistedQueryLimit);
let candidate: PersistedClient | undefined = sanitizePersistedClient(client); if (!limitedClient || measureSerializedBytes(limitedClient) <= queryPersistenceMaxCacheBytes) return limitedClient;
let errorCount = 0;
if (candidate.clientState.queries.length === 0) { const emptyClient: PersistedClient = {
...limitedClient,
clientState: { ...limitedClient.clientState, queries: [] },
};
let remainingBytes = queryPersistenceMaxCacheBytes - measureSerializedBytes(emptyClient);
const selectedQueries: DehydratedQuery[] = [];
const newestQueries = limitedClient.clientState.queries.toSorted(
(left, right) => right.state.dataUpdatedAt - left.state.dataUpdatedAt,
);
for (const query of newestQueries) {
const queryBytes = measureSerializedBytes(query) + 1;
if (queryBytes > remainingBytes) continue;
selectedQueries.push(query);
remainingBytes -= queryBytes;
}
return {
...limitedClient,
clientState: { ...limitedClient.clientState, queries: selectedQueries },
};
};
const persistNow = (client: PersistedClient) => {
if (!storage || persistenceDisabled) return;
let candidate: PersistedClient | undefined;
let sanitizedQueryCount = 0;
try {
const sanitizedClient = sanitizePersistedClient(client);
sanitizedQueryCount = sanitizedClient.clientState.queries.length;
candidate = trimToQueryLimit(sanitizedClient);
} catch {
persistenceDisabled = true;
removeStorageItem(storage, key);
return;
}
if (!candidate || candidate.clientState.queries.length === 0) {
removeStorageItem(storage, key); removeStorageItem(storage, key);
return; return;
} }
@@ -162,37 +241,56 @@ export const createSessionQueryPersister = (
while (candidate) { while (candidate) {
try { try {
storage.setItem(key, stringify(candidate)); storage.setItem(key, stringify(candidate));
if (candidate.clientState.queries.length < sanitizedQueryCount) {
persistedQueryLimit = Math.min(persistedQueryLimit, candidate.clientState.queries.length);
}
return; return;
} catch (error) { } catch (error) {
errorCount += 1; removeStorageItem(storage, key);
candidate = removeOldestQuery({ if (!isQuotaExceededError(error)) {
persistedClient: candidate, persistenceDisabled = true;
error: error instanceof Error ? error : new Error("Failed to persist the widget query cache"), return;
errorCount, }
}); candidate = keepNewestQueries(candidate, Math.floor(candidate.clientState.queries.length / 2));
} }
} }
persistenceDisabled = true;
};
const clearScheduledPersist = () => {
if (persistDelayTimer !== undefined) {
clearTimeout(persistDelayTimer);
persistDelayTimer = undefined;
}
if (persistIdleCallback !== undefined && typeof window !== "undefined") {
window.cancelIdleCallback?.(persistIdleCallback);
persistIdleCallback = undefined;
}
}; };
const clearPersistTimer = () => {
if (persistTimer === undefined) return;
clearTimeout(persistTimer);
persistTimer = undefined;
};
const flush = () => { const flush = () => {
clearPersistTimer(); clearScheduledPersist();
const client = pendingClient; const client = pendingClient;
pendingClient = undefined; pendingClient = undefined;
if (client) persistNow(client); if (client) persistNow(client);
}; };
const scheduleIdlePersist = () => {
persistDelayTimer = undefined;
if (typeof window !== "undefined" && window.requestIdleCallback) {
persistIdleCallback = window.requestIdleCallback(flush, { timeout: queryPersistenceIdleTimeoutMs });
return;
}
flush();
};
return { return {
persistClient(client) { persistClient(client) {
if (!storage || stopped) return; if (!storage || stopped || persistenceDisabled) return;
pendingClient = client; pendingClient = client;
if (persistTimer !== undefined) return; if (persistDelayTimer !== undefined || persistIdleCallback !== undefined) return;
persistTimer = setTimeout(flush, 0); persistDelayTimer = setTimeout(scheduleIdlePersist, queryPersistenceThrottleMs);
}, },
restoreClient() { restoreClient() {
try { try {
@@ -212,14 +310,14 @@ export const createSessionQueryPersister = (
} }
}, },
removeClient() { removeClient() {
clearPersistTimer(); clearScheduledPersist();
pendingClient = undefined; pendingClient = undefined;
removeStorageItem(storage, key); removeStorageItem(storage, key);
}, },
flush, flush,
stop() { stop() {
stopped = true; stopped = true;
clearPersistTimer(); clearScheduledPersist();
pendingClient = undefined; pendingClient = undefined;
}, },
}; };
@@ -10,24 +10,17 @@ import { useI18n } from "@homarr/translation/client";
import { useOptionalHomarrAssistant } from "~/components/assistant/assistant-context"; import { useOptionalHomarrAssistant } from "~/components/assistant/assistant-context";
interface CopyAiPromptButtonBaseProps { interface CopyAiPromptButtonProps {
rawResponse?: string | null; rawResponse?: string | null;
request?: string | null; request?: string | null;
documentationUrl?: string | null; documentationUrl?: string | null;
getDraft: () => CustomWidgetAiDraft;
getDiagnostics: () => readonly CustomWidgetAiDiagnostic[];
} }
type CopyAiPromptButtonProps = CopyAiPromptButtonBaseProps &
({ draft: CustomWidgetAiDraft; getDraft?: never } | { draft?: never; getDraft(): CustomWidgetAiDraft }) &
(
| { diagnostics: readonly CustomWidgetAiDiagnostic[]; getDiagnostics?: never }
| { diagnostics?: never; getDiagnostics(): readonly CustomWidgetAiDiagnostic[] }
);
export const CopyAiPromptButton = ({ export const CopyAiPromptButton = ({
rawResponse, rawResponse,
draft,
getDraft, getDraft,
diagnostics,
getDiagnostics, getDiagnostics,
request, request,
documentationUrl, documentationUrl,
@@ -35,23 +28,14 @@ export const CopyAiPromptButton = ({
const t = useI18n("customWidget"); const t = useI18n("customWidget");
const assistant = useOptionalHomarrAssistant(); const assistant = useOptionalHomarrAssistant();
const readDraft = () => {
if (getDraft) return getDraft();
return draft;
};
const readDiagnostics = () => {
if (getDiagnostics) return getDiagnostics();
return diagnostics;
};
const handleAssistant = () => { const handleAssistant = () => {
const prompt = buildCustomWidgetAssistantPrompt( const prompt = buildCustomWidgetAssistantPrompt(
undefined, undefined,
rawResponse, rawResponse,
readDraft(), getDraft(),
request, request,
documentationUrl, documentationUrl,
readDiagnostics(), getDiagnostics(),
); );
if (!assistant?.enabled || !assistant.sendPrompt(prompt)) return; if (!assistant?.enabled || !assistant.sendPrompt(prompt)) return;
showSuccessNotification({ title: t("action.aiPrompt"), message: t("notification.aiPromptSent") }); showSuccessNotification({ title: t("action.aiPrompt"), message: t("notification.aiPromptSent") });
@@ -62,10 +46,10 @@ export const CopyAiPromptButton = ({
const value = buildCustomWidgetAiPrompt( const value = buildCustomWidgetAiPrompt(
undefined, undefined,
rawResponse, rawResponse,
readDraft(), getDraft(),
request, request,
documentationUrl, documentationUrl,
readDiagnostics(), getDiagnostics(),
); );
await navigator.clipboard.writeText(value); await navigator.clipboard.writeText(value);
showSuccessNotification({ showSuccessNotification({
@@ -13,6 +13,8 @@ import type { ScopedTranslationFunction } from "@homarr/translation";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import { useTranslatedMantineReactTable } from "@homarr/ui/hooks"; import { useTranslatedMantineReactTable } from "@homarr/ui/hooks";
import { createKubernetesResourceQueryOptions } from "../kubernetes-query-options";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
interface ConfigMapsTableComponentProps { interface ConfigMapsTableComponentProps {
@@ -47,13 +49,7 @@ export function ConfigmapsTable({ contextId, initialConfigMaps }: ConfigMapsTabl
const { data } = clientApi.kubernetes.configMaps.getConfigMaps.useQuery( const { data } = clientApi.kubernetes.configMaps.getConfigMaps.useQuery(
{ contextId }, { contextId },
{ createKubernetesResourceQueryOptions(initialConfigMaps),
initialData: initialConfigMaps,
refetchOnMount: "always",
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchInterval: (query) => (query.state.status === "error" ? 30_000 : false),
},
); );
const table = useTranslatedMantineReactTable({ const table = useTranslatedMantineReactTable({
@@ -17,6 +17,7 @@ import { useI18n } from "@homarr/translation/client";
import { useTranslatedMantineReactTable } from "@homarr/ui/hooks"; import { useTranslatedMantineReactTable } from "@homarr/ui/hooks";
import KubernetesErrorPage from "../cluster-dashboard/error"; import KubernetesErrorPage from "../cluster-dashboard/error";
import { createKubernetesResourceQueryOptions } from "../kubernetes-query-options";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
@@ -84,13 +85,7 @@ export function IngressesTable({ contextId, initialIngresses }: IngressesTableCo
const { data, isError } = clientApi.kubernetes.ingresses.getIngresses.useQuery( const { data, isError } = clientApi.kubernetes.ingresses.getIngresses.useQuery(
{ contextId }, { contextId },
{ createKubernetesResourceQueryOptions(initialIngresses),
initialData: initialIngresses,
refetchOnMount: "always",
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchInterval: (query) => (query.state.status === "error" ? 30_000 : false),
},
); );
const table = useTranslatedMantineReactTable({ const table = useTranslatedMantineReactTable({
@@ -0,0 +1,18 @@
interface QueryWithStatus {
state: {
status: string;
};
}
const getErrorRefetchInterval = (query: QueryWithStatus) => {
if (query.state.status === "error") return 30_000;
return false;
};
export const createKubernetesResourceQueryOptions = <TData>(initialData: TData) => ({
initialData,
refetchOnMount: "always" as const,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchInterval: getErrorRefetchInterval,
});
@@ -15,6 +15,8 @@ import type { ScopedTranslationFunction } from "@homarr/translation";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import { useTranslatedMantineReactTable } from "@homarr/ui/hooks"; import { useTranslatedMantineReactTable } from "@homarr/ui/hooks";
import { createKubernetesResourceQueryOptions } from "../kubernetes-query-options";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
interface NamespacesTableComponentProps { interface NamespacesTableComponentProps {
@@ -66,13 +68,7 @@ export function NamespacesTable({ contextId, initialNamespaces }: NamespacesTabl
const { data } = clientApi.kubernetes.namespaces.getNamespaces.useQuery( const { data } = clientApi.kubernetes.namespaces.getNamespaces.useQuery(
{ contextId }, { contextId },
{ createKubernetesResourceQueryOptions(initialNamespaces),
initialData: initialNamespaces,
refetchOnMount: "always",
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchInterval: (query) => (query.state.status === "error" ? 30_000 : false),
},
); );
const table = useTranslatedMantineReactTable({ const table = useTranslatedMantineReactTable({
@@ -17,6 +17,7 @@ import { useI18n } from "@homarr/translation/client";
import { useTranslatedMantineReactTable } from "@homarr/ui/hooks"; import { useTranslatedMantineReactTable } from "@homarr/ui/hooks";
import KubernetesErrorPage from "../cluster-dashboard/error"; import KubernetesErrorPage from "../cluster-dashboard/error";
import { createKubernetesResourceQueryOptions } from "../kubernetes-query-options";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
@@ -97,13 +98,7 @@ export function NodesTable({ contextId, initialNodes }: NodesListComponentProps)
const { data, isError } = clientApi.kubernetes.nodes.getNodes.useQuery( const { data, isError } = clientApi.kubernetes.nodes.getNodes.useQuery(
{ contextId }, { contextId },
{ createKubernetesResourceQueryOptions(initialNodes),
initialData: initialNodes,
refetchOnMount: "always",
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchInterval: (query) => (query.state.status === "error" ? 30_000 : false),
},
); );
const table = useTranslatedMantineReactTable({ const table = useTranslatedMantineReactTable({
@@ -13,6 +13,8 @@ import type { ScopedTranslationFunction } from "@homarr/translation";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import { useTranslatedMantineReactTable } from "@homarr/ui/hooks"; import { useTranslatedMantineReactTable } from "@homarr/ui/hooks";
import { createKubernetesResourceQueryOptions } from "../kubernetes-query-options";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
interface PodsTableComponentProps { interface PodsTableComponentProps {
@@ -57,13 +59,7 @@ export function PodsTable({ contextId, initialPods }: PodsTableComponentProps) {
const { data } = clientApi.kubernetes.pods.getPods.useQuery( const { data } = clientApi.kubernetes.pods.getPods.useQuery(
{ contextId }, { contextId },
{ createKubernetesResourceQueryOptions(initialPods),
initialData: initialPods,
refetchOnMount: "always",
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchInterval: (query) => (query.state.status === "error" ? 30_000 : false),
},
); );
const table = useTranslatedMantineReactTable({ const table = useTranslatedMantineReactTable({
@@ -13,6 +13,8 @@ import type { ScopedTranslationFunction } from "@homarr/translation";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import { useTranslatedMantineReactTable } from "@homarr/ui/hooks"; import { useTranslatedMantineReactTable } from "@homarr/ui/hooks";
import { createKubernetesResourceQueryOptions } from "../kubernetes-query-options";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
interface SecretsTableComponentProps { interface SecretsTableComponentProps {
@@ -52,13 +54,7 @@ export function SecretsTable({ contextId, initialSecrets }: SecretsTableComponen
const { data } = clientApi.kubernetes.secrets.getSecrets.useQuery( const { data } = clientApi.kubernetes.secrets.getSecrets.useQuery(
{ contextId }, { contextId },
{ createKubernetesResourceQueryOptions(initialSecrets),
initialData: initialSecrets,
refetchOnMount: "always",
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchInterval: (query) => (query.state.status === "error" ? 30_000 : false),
},
); );
const table = useTranslatedMantineReactTable({ const table = useTranslatedMantineReactTable({
@@ -14,6 +14,8 @@ import type { ScopedTranslationFunction } from "@homarr/translation";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import { useTranslatedMantineReactTable } from "@homarr/ui/hooks"; import { useTranslatedMantineReactTable } from "@homarr/ui/hooks";
import { createKubernetesResourceQueryOptions } from "../kubernetes-query-options";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
interface ServicesTableComponentProps { interface ServicesTableComponentProps {
@@ -71,13 +73,7 @@ export function ServicesTable({ contextId, initialServices }: ServicesTableCompo
const { data } = clientApi.kubernetes.services.getServices.useQuery( const { data } = clientApi.kubernetes.services.getServices.useQuery(
{ contextId }, { contextId },
{ createKubernetesResourceQueryOptions(initialServices),
initialData: initialServices,
refetchOnMount: "always",
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchInterval: (query) => (query.state.status === "error" ? 30_000 : false),
},
); );
const table = useTranslatedMantineReactTable({ const table = useTranslatedMantineReactTable({
@@ -13,6 +13,8 @@ import type { ScopedTranslationFunction } from "@homarr/translation";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import { useTranslatedMantineReactTable } from "@homarr/ui/hooks"; import { useTranslatedMantineReactTable } from "@homarr/ui/hooks";
import { createKubernetesResourceQueryOptions } from "../kubernetes-query-options";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
interface VolumesTableComponentProps { interface VolumesTableComponentProps {
@@ -76,13 +78,7 @@ export function VolumesTable({ contextId, initialVolumes }: VolumesTableComponen
const { data } = clientApi.kubernetes.volumes.getVolumes.useQuery( const { data } = clientApi.kubernetes.volumes.getVolumes.useQuery(
{ contextId }, { contextId },
{ createKubernetesResourceQueryOptions(initialVolumes),
initialData: initialVolumes,
refetchOnMount: "always",
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchInterval: (query) => (query.state.status === "error" ? 30_000 : false),
},
); );
const table = useTranslatedMantineReactTable({ const table = useTranslatedMantineReactTable({
@@ -0,0 +1,56 @@
const overview = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
display: grid;
place-items: center;
overflow: hidden;
color: #f8f9fa;
font-family: Inter, ui-sans-serif, system-ui, sans-serif;
background:
radial-gradient(circle at 18% 15%, rgba(116, 143, 252, .32), transparent 36%),
radial-gradient(circle at 82% 80%, rgba(59, 201, 219, .22), transparent 42%),
#15121f;
}
main { width: min(86%, 34rem); text-align: center; }
.mark {
width: 4rem;
height: 4rem;
margin: 0 auto 1rem;
display: grid;
place-items: center;
border-radius: 1.25rem;
font-size: 1.75rem;
font-weight: 900;
background: linear-gradient(135deg, #748ffc, #3bc9db);
box-shadow: 0 1rem 3rem rgba(116, 143, 252, .34);
}
h1 { margin: 0; font-size: clamp(1.5rem, 8vw, 2.5rem); letter-spacing: -.04em; }
p { margin: .65rem auto 0; max-width: 28rem; color: #c1c2c5; line-height: 1.55; }
.signals { display: flex; justify-content: center; gap: .55rem; margin-top: 1.25rem; flex-wrap: wrap; }
span { padding: .38rem .7rem; border: 1px solid rgba(255,255,255,.13); border-radius: 999px; background: rgba(255,255,255,.06); font-size: .75rem; }
</style>
</head>
<body>
<main>
<div class="mark">H</div>
<h1>Your home, at a glance.</h1>
<p>Bring services, media, infrastructure, notes and everyday tools together on one practical dashboard.</p>
<div class="signals"><span>59 widgets</span><span>Mock data included</span><span>Built for self-hosters</span></div>
</main>
</body>
</html>`;
export const GET = () =>
new Response(overview, {
headers: {
"Cache-Control": "public, max-age=31536000, immutable",
"Content-Type": "text/html; charset=utf-8",
},
});
@@ -0,0 +1 @@
export { GET } from "../route";
@@ -0,0 +1,10 @@
const videoBase64 =
"AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAWDbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAAC7gAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAABK10cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAC7gAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAoAAAAFoAAAAAAAkZWR0cwAAABxl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ugNPVjfmzvc8PDVHO7tzXHhQ/lGxzo7V+cMH1BXb9R4D23HGSyCGTN86uTESdWXBp1M45EwwHlwk47eXhp0zIsZRXDNI++aumypyQNgJfyf6cM9/yZshiiy4Om1E7vAmSv2/W7pe0tw9szIQk9e8kzwQ+zzY2XBCzbyKsTjygEJq3/qPZHbaK1NByTYJZoURb0vBq29z/+YOMQ7Dc04aF/tlozRN99kqMqDNHZbXTsmdWV656KUBqip2Tth/X+C2zLdkFfRDoDXuE+HwI2ZZG8A2WL1riAVH8l3a/vFOYyvXYqu1SE7kfK0Z9TjDJ96IwqcHEv3do8M9phRlTgdmWAS9dpDB695k5i9 Line truncated
export const GET = () =>
new Response(Buffer.from(videoBase64, "base64"), {
headers: {
"Cache-Control": "public, max-age=31536000, immutable",
"Content-Type": "video/mp4",
},
});
@@ -11,16 +11,17 @@ import classes from "./board-layout-thumbnail.module.css";
interface BoardLayoutThumbnailProps { interface BoardLayoutThumbnailProps {
preview: BoardPreviewData | null; preview: BoardPreviewData | null;
label: string; label: string;
fitFullLayout?: boolean; previewRowLimit?: number;
className?: string; className?: string;
} }
const maxThumbnailRows = 12; const compactBoardLayoutThumbnailRows = 12;
export const maxBoardLayoutThumbnailRows = 48;
export const BoardLayoutThumbnail = ({ export const BoardLayoutThumbnail = ({
preview, preview,
label, label,
fitFullLayout = false, previewRowLimit = compactBoardLayoutThumbnailRows,
className, className,
}: BoardLayoutThumbnailProps) => { }: BoardLayoutThumbnailProps) => {
const canvasClassName = [classes.canvas, className].filter(Boolean).join(" "); const canvasClassName = [classes.canvas, className].filter(Boolean).join(" ");
@@ -34,7 +35,7 @@ export const BoardLayoutThumbnail = ({
} }
const elements = projectBoardLayout(preview, layout, layout); const elements = projectBoardLayout(preview, layout, layout);
const thumbnailRowLimit = fitFullLayout ? Number.POSITIVE_INFINITY : maxThumbnailRows; const thumbnailRowLimit = Math.max(1, Math.min(Math.floor(previewRowLimit), maxBoardLayoutThumbnailRows));
const roots = preview.sections const roots = preview.sections
.filter((section) => section.kind === "empty") .filter((section) => section.kind === "empty")
.toSorted((first, second) => (first.xOffset ?? 0) - (second.xOffset ?? 0) || first.id.localeCompare(second.id)); .toSorted((first, second) => (first.xOffset ?? 0) - (second.xOffset ?? 0) || first.id.localeCompare(second.id));
@@ -94,9 +95,21 @@ export const BoardLayoutThumbnail = ({
}} }}
> >
{laneElements.map((element) => { {laneElements.map((element) => {
const renderedWidth = Math.min(element.width, columnCount - element.xOffset);
const renderedHeight = Math.min(element.height, rowCount - element.yOffset);
const nestedItems = const nestedItems =
element.type === "section" element.type === "section"
? elements.filter((candidate) => candidate.type === "item" && candidate.sectionId === element.id) ? elements.filter(
(candidate) =>
candidate.type === "item" &&
candidate.sectionId === element.id &&
candidate.xOffset >= 0 &&
candidate.xOffset < renderedWidth &&
candidate.yOffset >= 0 &&
candidate.yOffset < renderedHeight &&
candidate.width > 0 &&
candidate.height > 0,
)
: []; : [];
return ( return (
<span <span
@@ -104,16 +117,16 @@ export const BoardLayoutThumbnail = ({
aria-hidden aria-hidden
className={`${classes.tile} ${element.type === "section" ? classes.container : ""}`} className={`${classes.tile} ${element.type === "section" ? classes.container : ""}`}
style={{ style={{
gridColumn: `${element.xOffset + 1} / span ${Math.min(element.width, columnCount - element.xOffset)}`, gridColumn: `${element.xOffset + 1} / span ${renderedWidth}`,
gridRow: `${element.yOffset + 1} / span ${Math.min(element.height, rowCount - element.yOffset)}`, gridRow: `${element.yOffset + 1} / span ${renderedHeight}`,
}} }}
> >
{element.type === "section" ? ( {element.type === "section" ? (
<span <span
className={classes.containerContents} className={classes.containerContents}
style={{ style={{
gridTemplateColumns: `repeat(${element.width}, minmax(0, 1fr))`, gridTemplateColumns: `repeat(${renderedWidth}, minmax(0, 1fr))`,
gridTemplateRows: `repeat(${element.height}, minmax(0, 1fr))`, gridTemplateRows: `repeat(${renderedHeight}, minmax(0, 1fr))`,
}} }}
> >
{nestedItems.map((nestedItem) => ( {nestedItems.map((nestedItem) => (
@@ -123,11 +136,11 @@ export const BoardLayoutThumbnail = ({
style={{ style={{
gridColumn: `${nestedItem.xOffset + 1} / span ${Math.min( gridColumn: `${nestedItem.xOffset + 1} / span ${Math.min(
nestedItem.width, nestedItem.width,
element.width - nestedItem.xOffset, renderedWidth - nestedItem.xOffset,
)}`, )}`,
gridRow: `${nestedItem.yOffset + 1} / span ${Math.min( gridRow: `${nestedItem.yOffset + 1} / span ${Math.min(
nestedItem.height, nestedItem.height,
element.height - nestedItem.yOffset, renderedHeight - nestedItem.yOffset,
)}`, )}`,
}} }}
> >
@@ -30,11 +30,12 @@ import { useRegisterSpotlightContextActions } from "@homarr/spotlight";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import { Link, UserAvatar } from "@homarr/ui"; import { Link, UserAvatar } from "@homarr/ui";
import { BoardLayoutThumbnail } from "~/components/board/board-layout-thumbnail"; import { BoardLayoutThumbnail, maxBoardLayoutThumbnailRows } from "~/components/board/board-layout-thumbnail";
import classes from "./board-switcher.module.css"; import classes from "./board-switcher.module.css";
export const boardSwitcherHotkey = "shift+c"; export const boardSwitcherHotkey = "shift+c";
const boardSwitcherPreview = { previewRowLimit: maxBoardLayoutThumbnailRows } as const;
export interface BoardSwitcherControls { export interface BoardSwitcherControls {
open: () => void; open: () => void;
@@ -61,18 +62,12 @@ export const BoardSwitcher = ({ children }: BoardSwitcherProps) => {
data: boards = [], data: boards = [],
isPending, isPending,
isError, isError,
} = clientApi.board.getManageOverview.useQuery( } = clientApi.board.getManageOverview.useQuery(boardSwitcherPreview, {
{ fullPreview: true }, enabled: isOpen,
{ });
enabled: isOpen,
},
);
const switcherBoards = useMemo( const switcherBoards = useMemo(
() => [ () => boards.filter((board) => board.id !== currentBoard?.id),
...boards.filter((board) => board.id !== currentBoard?.id),
...boards.filter((board) => board.id === currentBoard?.id),
],
[boards, currentBoard?.id], [boards, currentBoard?.id],
); );
const filteredBoards = useMemo(() => { const filteredBoards = useMemo(() => {
@@ -91,7 +86,7 @@ export const BoardSwitcher = ({ children }: BoardSwitcherProps) => {
setSearch(""); setSearch("");
setActiveIndex(0); setActiveIndex(0);
}, []); }, []);
const preloadBoards = () => void utils.board.getManageOverview.prefetch({ fullPreview: true }); const preloadBoards = () => void utils.board.getManageOverview.prefetch(boardSwitcherPreview);
const spotlightAction = useMemo( const spotlightAction = useMemo(
() => ({ () => ({
@@ -335,7 +330,7 @@ const getBoardSwitcherResults = ({
<BoardLayoutThumbnail <BoardLayoutThumbnail
preview={board.preview} preview={board.preview}
label={t("preview", { name: board.name, count: String(board.preview?.items.length ?? 0) })} label={t("preview", { name: board.name, count: String(board.preview?.items.length ?? 0) })}
fitFullLayout previewRowLimit={boardSwitcherPreview.previewRowLimit}
/> />
</Card.Section> </Card.Section>
<Card.Section withBorder px="sm" py={6}> <Card.Section withBorder px="sm" py={6}>
@@ -9,6 +9,7 @@ import { useModalAction } from "@homarr/modals";
import { useSettings } from "@homarr/settings"; import { useSettings } from "@homarr/settings";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import type { WidgetDefinition } from "@homarr/widgets/definition"; import type { WidgetDefinition } from "@homarr/widgets/definition";
import type { WidgetPreviewDimensions } from "@homarr/widgets/modals";
import type { SectionItem } from "~/app/[locale]/boards/_types"; import type { SectionItem } from "~/app/[locale]/boards/_types";
import { BoardRemoveConfirmationMenuItem } from "../remove-confirmation-menu-item"; import { BoardRemoveConfirmationMenuItem } from "../remove-confirmation-menu-item";
@@ -21,7 +22,7 @@ import { LazyWidgetEditModal, preloadWidgetEditModal } from "./lazy-widget-edit-
interface BoardItemMenuProps { interface BoardItemMenuProps {
item: SectionItem; item: SectionItem;
definition: WidgetDefinition; definition: WidgetDefinition;
previewDimensions: { width: number; height: number; scale?: number }; previewDimensions: WidgetPreviewDimensions;
resetErrorBoundary?: () => void; resetErrorBoundary?: () => void;
} }
@@ -24,6 +24,7 @@ import type { WidgetDefinition, WidgetRuntimeRef } from "@homarr/widgets/definit
import { getWidgetQueryKeys, getWidgetRuntimeQueries, supportsAdvancedFocus } from "@homarr/widgets/definition"; import { getWidgetQueryKeys, getWidgetRuntimeQueries, supportsAdvancedFocus } from "@homarr/widgets/definition";
import { reduceWidgetOptionsWithDefinition } from "@homarr/widgets/manifest"; import { reduceWidgetOptionsWithDefinition } from "@homarr/widgets/manifest";
import { getWidgetOptionTranslationNamespace } from "@homarr/widgets/option-translation"; import { getWidgetOptionTranslationNamespace } from "@homarr/widgets/option-translation";
import type { WidgetPreviewDimensions } from "@homarr/widgets/modals";
import type { SectionItem } from "~/app/[locale]/boards/_types"; import type { SectionItem } from "~/app/[locale]/boards/_types";
import { useAdvancedFocus } from "../advanced-focus/context"; import { useAdvancedFocus } from "../advanced-focus/context";
@@ -35,7 +36,7 @@ import { matchesWidgetItemQuery } from "./widget-query-scope";
interface WidgetContextMenuProps { interface WidgetContextMenuProps {
item: SectionItem; item: SectionItem;
definition: WidgetDefinition; definition: WidgetDefinition;
previewDimensions: { width: number; height: number; scale?: number }; previewDimensions: WidgetPreviewDimensions;
widgetStateRef: MutableRefObject<Record<string, unknown> | null>; widgetStateRef: MutableRefObject<Record<string, unknown> | null>;
widgetRuntimeRef: WidgetRuntimeRef; widgetRuntimeRef: WidgetRuntimeRef;
sourceRef: RefObject<HTMLElement | null>; sourceRef: RefObject<HTMLElement | null>;
@@ -54,11 +54,13 @@ export const LazySpotlight = () => {
}; };
}, []); }, []);
return isMounted || isPreloaded ? ( if (!isMounted && !isPreloaded) return null;
return (
<> <>
{isPreloaded && <span hidden data-homarr-dev-benchmark-spotlight-preloaded />} {isPreloaded && <span hidden data-homarr-dev-benchmark-spotlight-preloaded />}
{isMounted && <span hidden data-homarr-dev-benchmark-spotlight-mounted />} {isMounted && <span hidden data-homarr-dev-benchmark-spotlight-mounted />}
<Spotlight /> {isMounted && <Spotlight />}
</> </>
) : null; );
}; };
+12 -5
View File
@@ -86,9 +86,14 @@ interface BoardItemPlacementRectangle {
} }
const boardItemPlacementTails = new Map<string, Promise<void>>(); const boardItemPlacementTails = new Map<string, Promise<void>>();
const maxManageOverviewPreviewRows = 12; const defaultManageOverviewPreviewRows = 12;
const maxManageOverviewPreviewRows = 48;
const manageOverviewInputSchema = z const manageOverviewInputSchema = z
.object({ fullPreview: z.boolean().default(false), userId: z.string().optional() }) .object({
fullPreview: z.boolean().default(false),
previewRowLimit: z.number().int().min(1).max(maxManageOverviewPreviewRows).optional(),
userId: z.string().optional(),
})
.optional(); .optional();
const serializeBoardItemPlacementAsync = async <T>(boardId: string, operation: () => Promise<T>) => { const serializeBoardItemPlacementAsync = async <T>(boardId: string, operation: () => Promise<T>) => {
@@ -311,6 +316,8 @@ export const boardRouter = createTRPCRouter({
const { boardIds, currentUser, groupMemberships } = await getBoardAccessContextAsync(ctx.db, userId); const { boardIds, currentUser, groupMemberships } = await getBoardAccessContextAsync(ctx.db, userId);
const groupPermissionWhere = getBoardGroupPermissionWhere(groupMemberships); const groupPermissionWhere = getBoardGroupPermissionWhere(groupMemberships);
const canViewAllBoards = getCanViewAllBoards(groupMemberships); const canViewAllBoards = getCanViewAllBoards(groupMemberships);
let previewRowLimit = input?.previewRowLimit ?? defaultManageOverviewPreviewRows;
if (input?.fullPreview) previewRowLimit = maxManageOverviewPreviewRows;
const dbBoards = await ctx.db.query.boards.findMany({ const dbBoards = await ctx.db.query.boards.findMany({
columns: { columns: {
@@ -388,7 +395,7 @@ export const boardRouter = createTRPCRouter({
inArray(itemLayouts.sectionId, rootSectionIds), inArray(itemLayouts.sectionId, rootSectionIds),
gte(itemLayouts.xOffset, 0), gte(itemLayouts.xOffset, 0),
gte(itemLayouts.yOffset, 0), gte(itemLayouts.yOffset, 0),
input?.fullPreview ? undefined : lt(itemLayouts.yOffset, maxManageOverviewPreviewRows), lt(itemLayouts.yOffset, previewRowLimit),
gt(itemLayouts.width, 0), gt(itemLayouts.width, 0),
gt(itemLayouts.height, 0), gt(itemLayouts.height, 0),
), ),
@@ -413,7 +420,7 @@ export const boardRouter = createTRPCRouter({
inArray(sectionLayouts.parentSectionId, rootSectionIds), inArray(sectionLayouts.parentSectionId, rootSectionIds),
gte(sectionLayouts.xOffset, 0), gte(sectionLayouts.xOffset, 0),
gte(sectionLayouts.yOffset, 0), gte(sectionLayouts.yOffset, 0),
input?.fullPreview ? undefined : lt(sectionLayouts.yOffset, maxManageOverviewPreviewRows), lt(sectionLayouts.yOffset, previewRowLimit),
gt(sectionLayouts.width, 0), gt(sectionLayouts.width, 0),
gt(sectionLayouts.height, 0), gt(sectionLayouts.height, 0),
), ),
@@ -448,7 +455,7 @@ export const boardRouter = createTRPCRouter({
inArray(itemLayouts.sectionId, previewContainerSectionIds), inArray(itemLayouts.sectionId, previewContainerSectionIds),
gte(itemLayouts.xOffset, 0), gte(itemLayouts.xOffset, 0),
gte(itemLayouts.yOffset, 0), gte(itemLayouts.yOffset, 0),
input?.fullPreview ? undefined : lt(itemLayouts.yOffset, maxManageOverviewPreviewRows), lt(itemLayouts.yOffset, previewRowLimit),
gt(itemLayouts.width, 0), gt(itemLayouts.width, 0),
gt(itemLayouts.height, 0), gt(itemLayouts.height, 0),
), ),
@@ -84,15 +84,13 @@ export const getDockerReconciliationAsync = async (db: Database) => {
const appAmbiguous = const appAmbiguous =
!linkedApp && (exactAppMatches.length > 1 || (exactAppMatches.length === 0 && nameAppMatches.length > 1)); !linkedApp && (exactAppMatches.length > 1 || (exactAppMatches.length === 0 && nameAppMatches.length > 1));
const ambiguous = integrationAmbiguous || appAmbiguous; const ambiguous = integrationAmbiguous || appAmbiguous;
const state: DockerReconciliationState = integrationMoved const state = getReconciliationState({
? "moved" integrationMoved,
: linked linked,
? "linked" represented: Boolean(integration || app),
: integration || app recognized: Boolean(match),
? "represented" });
: match const nextAction = getCandidateNextAction(state, integrationAmbiguous, appAmbiguous);
? "newRecognized"
: "newApp";
return { return {
candidateKey: container.resourceId, candidateKey: container.resourceId,
@@ -103,11 +101,7 @@ export const getDockerReconciliationAsync = async (db: Database) => {
match, match,
urlCandidates, urlCandidates,
state, state,
nextAction: integrationAmbiguous nextAction,
? ("reviewIntegration" as const)
: appAmbiguous
? ("viewRepresentation" as const)
: nextActionForState(state),
representation: { representation: {
integration: integration integration: integration
? { ? {
@@ -147,87 +141,100 @@ export const getDockerServiceHealthAsync = async (db: Database) => {
status: endpoint.status, status: endpoint.status,
nextAction: endpoint.status === "unavailable" ? ("checkEndpoint" as const) : ("none" as const), nextAction: endpoint.status === "unavailable" ? ("checkEndpoint" as const) : ("none" as const),
})), })),
services: reconciliation.candidates.map((candidate) => ({ services: reconciliation.candidates.map((candidate) => {
key: candidate.candidateKey, const integration = candidate.representation.integration;
identity: { const app = candidate.representation.app;
endpointId: candidate.endpointId, const itemCount = integration?.itemCount;
nativeId: candidate.nativeId,
name: candidate.container.name, return {
integration: candidate.representation.integration, key: candidate.candidateKey,
app: candidate.representation.app, identity: {
}, endpointId: candidate.endpointId,
layers: [ nativeId: candidate.nativeId,
{ layer: "docker" as const, status: "available" as const, nextAction: "none" as const }, name: candidate.container.name,
{ integration,
layer: "integrationConfiguration" as const, app,
status: integrationHealthStatus(
candidate.state,
candidate.match?.kind,
Boolean(candidate.representation.integration),
),
nextAction:
candidate.nextAction === "reviewIntegration"
? ("reviewIntegration" as const)
: candidate.state === "newRecognized"
? ("setupIntegration" as const)
: ("none" as const),
}, },
{ layers: [
layer: "authentication" as const, { layer: "docker" as const, status: "available" as const, nextAction: "none" as const },
status: "notObserved" as const, {
nextAction: candidate.representation.integration layer: "integrationConfiguration" as const,
? ("testConnection" as const) status: integrationHealthStatus(candidate.state, candidate.match?.kind, Boolean(integration)),
: candidate.nextAction === "reviewIntegration" nextAction: getIntegrationConfigurationNextAction(candidate.state, candidate.nextAction),
? ("reviewIntegration" as const) },
: candidate.match {
? ("setupIntegration" as const) layer: "authentication" as const,
: ("none" as const), status: "notObserved" as const,
}, nextAction: getAuthenticationNextAction(
{ Boolean(integration),
layer: "apiRequest" as const, Boolean(candidate.match),
status: "notObserved" as const, candidate.nextAction,
nextAction: candidate.representation.integration ),
? ("openIntegrationDiagnostics" as const) },
: ("none" as const), {
}, layer: "apiRequest" as const,
{ status: "notObserved" as const,
layer: "appRepresentation" as const, nextAction: integration ? ("openIntegrationDiagnostics" as const) : ("none" as const),
status: candidate.representation.app ? ("linked" as const) : ("missing" as const), },
nextAction: candidate.representation.app {
? ("none" as const) layer: "appRepresentation" as const,
: candidate.representation.signals.ambiguous && candidate.nextAction === "viewRepresentation" status: app ? ("linked" as const) : ("missing" as const),
? ("viewRepresentation" as const) nextAction: getAppRepresentationNextAction(
: ("createApp" as const), Boolean(app),
}, candidate.representation.signals.ambiguous,
{ candidate.nextAction,
layer: "widgetConfiguration" as const, ),
status: candidate.representation.integration },
? candidate.representation.integration.itemCount > 0 {
? ("linked" as const) layer: "widgetConfiguration" as const,
: ("unused" as const) status: getWidgetConfigurationStatus(itemCount),
: ("notApplicable" as const), nextAction: itemCount === 0 ? ("addWidget" as const) : ("none" as const),
nextAction: },
candidate.representation.integration && candidate.representation.integration.itemCount === 0 {
? ("addWidget" as const) layer: "widgetQuery" as const,
: ("none" as const), status: "notObserved" as const,
}, nextAction: itemCount !== undefined && itemCount > 0 ? ("openBoard" as const) : ("none" as const),
{ },
layer: "widgetQuery" as const, ],
status: "notObserved" as const, status: candidate.state,
nextAction: nextAction: candidate.nextAction,
candidate.representation.integration && candidate.representation.integration.itemCount > 0 };
? ("openBoard" as const) }),
: ("none" as const),
},
],
status: candidate.state,
nextAction: candidate.nextAction,
})),
}; };
}; };
const normalizeName = (value: string) => value.trim().toLowerCase(); const normalizeName = (value: string) => value.trim().toLowerCase();
interface ReconciliationStateInput {
integrationMoved: boolean;
linked: boolean;
represented: boolean;
recognized: boolean;
}
const getReconciliationState = ({
integrationMoved,
linked,
represented,
recognized,
}: ReconciliationStateInput): DockerReconciliationState => {
if (integrationMoved) return "moved";
if (linked) return "linked";
if (represented) return "represented";
if (recognized) return "newRecognized";
return "newApp";
};
const getCandidateNextAction = (
state: DockerReconciliationState,
integrationAmbiguous: boolean,
appAmbiguous: boolean,
) => {
if (integrationAmbiguous) return "reviewIntegration" as const;
if (appAmbiguous) return "viewRepresentation" as const;
return nextActionForState(state);
};
const nextActionForState = (state: DockerReconciliationState): DockerReconciliationNextAction => { const nextActionForState = (state: DockerReconciliationState): DockerReconciliationNextAction => {
if (state === "newRecognized") return "setupIntegration"; if (state === "newRecognized") return "setupIntegration";
if (state === "newApp") return "createApp"; if (state === "newApp") return "createApp";
@@ -235,6 +242,42 @@ const nextActionForState = (state: DockerReconciliationState): DockerReconciliat
return "viewRepresentation"; return "viewRepresentation";
}; };
const getIntegrationConfigurationNextAction = (
state: DockerReconciliationState,
nextAction: DockerReconciliationNextAction,
) => {
if (nextAction === "reviewIntegration") return "reviewIntegration" as const;
if (state === "newRecognized") return "setupIntegration" as const;
return "none" as const;
};
const getAuthenticationNextAction = (
hasIntegration: boolean,
hasMatch: boolean,
nextAction: DockerReconciliationNextAction,
) => {
if (hasIntegration) return "testConnection" as const;
if (nextAction === "reviewIntegration") return "reviewIntegration" as const;
if (hasMatch) return "setupIntegration" as const;
return "none" as const;
};
const getAppRepresentationNextAction = (
hasApp: boolean,
ambiguous: boolean,
nextAction: DockerReconciliationNextAction,
) => {
if (hasApp) return "none" as const;
if (ambiguous && nextAction === "viewRepresentation") return "viewRepresentation" as const;
return "createApp" as const;
};
const getWidgetConfigurationStatus = (itemCount: number | undefined) => {
if (itemCount === undefined) return "notApplicable" as const;
if (itemCount > 0) return "linked" as const;
return "unused" as const;
};
const integrationHealthStatus = ( const integrationHealthStatus = (
state: DockerReconciliationState, state: DockerReconciliationState,
kind: IntegrationKind | undefined, kind: IntegrationKind | undefined,
@@ -242,5 +285,6 @@ const integrationHealthStatus = (
) => { ) => {
if (!kind) return "notApplicable" as const; if (!kind) return "notApplicable" as const;
if (state === "moved") return "changed" as const; if (state === "moved") return "changed" as const;
return hasIntegration ? ("configured" as const) : ("missing" as const); if (hasIntegration) return "configured" as const;
return "missing" as const;
}; };
@@ -4,6 +4,7 @@ import { z } from "zod/v4";
import type { ContainerState, DockerContainerTarget, Port } from "@homarr/docker"; import type { ContainerState, DockerContainerTarget, Port } from "@homarr/docker";
import { DockerSingleton } from "@homarr/docker"; import { DockerSingleton } from "@homarr/docker";
import { createSubPubChannel } from "@homarr/redis";
import { import {
dockerContainersRequestHandler, dockerContainersRequestHandler,
findDockerContainerAsync, findDockerContainerAsync,
@@ -23,6 +24,29 @@ const dockerContainerTargetSchema = z.object({
}); });
const dockerContainerTargetsSchema = z.array(dockerContainerTargetSchema).min(1).max(100); const dockerContainerTargetsSchema = z.array(dockerContainerTargetSchema).min(1).max(100);
const resetDockerInventory = () => {
DockerSingleton.reset();
dockerContainersRequestHandler.invalidateCache();
};
const dockerInventoryRefreshChannel = createSubPubChannel<{ requestedAt: number }>("docker-inventory-refresh", {
persist: false,
});
const isRedisDisabled = () => Boolean(process.env.CI) || Boolean(process.env.DISABLE_REDIS_LOGS);
try {
dockerInventoryRefreshChannel.subscribe(resetDockerInventory);
} catch (error) {
if (!isRedisDisabled()) throw error;
}
const publishDockerInventoryRefreshAsync = async () => {
try {
await dockerInventoryRefreshChannel.publishAsync({ requestedAt: Date.now() });
} catch (error) {
if (!isRedisDisabled()) throw error;
}
};
const normalizeGetContainersInput = (input: { endpointIds?: string[] } | undefined) => { const normalizeGetContainersInput = (input: { endpointIds?: string[] } | undefined) => {
if (!input?.endpointIds || input.endpointIds.length === 0) return {}; if (!input?.endpointIds || input.endpointIds.length === 0) return {};
return input; return input;
@@ -61,9 +85,9 @@ export const dockerRouter = createTRPCRouter({
}, },
}) })
.concat(dockerMiddleware()) .concat(dockerMiddleware())
.mutation(() => { .mutation(async () => {
DockerSingleton.reset(); resetDockerInventory();
dockerContainersRequestHandler.invalidateCache(); await publishDockerInventoryRefreshAsync();
}), }),
getContainers: permissionRequiredProcedure getContainers: permissionRequiredProcedure
.requiresPermission("admin") .requiresPermission("admin")
@@ -14,6 +14,18 @@ import { dockerRouter } from "../../docker/docker-router";
const findDockerContainerAsyncMock = vi.hoisted(() => vi.fn()); const findDockerContainerAsyncMock = vi.hoisted(() => vi.fn());
const hasDockerEndpointCapabilityMock = vi.hoisted(() => vi.fn(() => true)); const hasDockerEndpointCapabilityMock = vi.hoisted(() => vi.fn(() => true));
const invalidateDockerCacheMock = vi.hoisted(() => vi.fn()); const invalidateDockerCacheMock = vi.hoisted(() => vi.fn());
const resetDockerSingletonMock = vi.hoisted(() => vi.fn());
const dockerInventoryRefreshChannelMock = vi.hoisted(() => {
let subscriber: (() => void) | undefined;
return {
publishAsync: vi.fn(async () => undefined),
subscribe: vi.fn((callback: () => void) => {
subscriber = callback;
return () => undefined;
}),
trigger: () => subscriber?.(),
};
});
const getDockerDataAsyncMock = vi.hoisted(() => const getDockerDataAsyncMock = vi.hoisted(() =>
vi.fn< vi.fn<
() => Promise<{ () => Promise<{
@@ -62,9 +74,12 @@ vi.mock("@homarr/docker", () => ({
}, },
}, },
], ],
reset: () => undefined, reset: resetDockerSingletonMock,
}, },
})); }));
vi.mock("@homarr/redis", () => ({
createSubPubChannel: () => dockerInventoryRefreshChannelMock,
}));
vi.mock("@homarr/request-handler/docker", () => ({ vi.mock("@homarr/request-handler/docker", () => ({
findDockerContainerAsync: findDockerContainerAsyncMock, findDockerContainerAsync: findDockerContainerAsyncMock,
hasDockerEndpointCapability: hasDockerEndpointCapabilityMock, hasDockerEndpointCapability: hasDockerEndpointCapabilityMock,
@@ -501,6 +516,13 @@ test("invalidates the shared Docker inventory on explicit refresh", async () =>
await createAdminCaller().refreshInventory(); await createAdminCaller().refreshInventory();
expect(invalidateDockerCacheMock).toHaveBeenCalledOnce(); expect(invalidateDockerCacheMock).toHaveBeenCalledOnce();
expect(resetDockerSingletonMock).toHaveBeenCalledOnce();
expect(dockerInventoryRefreshChannelMock.publishAsync).toHaveBeenCalledOnce();
dockerInventoryRefreshChannelMock.trigger();
expect(invalidateDockerCacheMock).toHaveBeenCalledTimes(2);
expect(resetDockerSingletonMock).toHaveBeenCalledTimes(2);
}); });
test("projects persisted service layers without inventing runtime health", async () => { test("projects persisted service layers without inventing runtime health", async () => {
+4 -1
View File
@@ -50,7 +50,10 @@ export const immichRouter = createTRPCRouter({
) )
.concat(createImmichIntegrationMiddleware("query")) .concat(createImmichIntegrationMiddleware("query"))
.query(async ({ ctx, input }) => { .query(async ({ ctx, input }) => {
if (ctx.integration.kind === "mock") return mockWidgetData.immichAlbums.slice(0, input.limit); if (ctx.integration.kind === "mock") {
if (input.limit === undefined) return mockWidgetData.immichAlbums;
return mockWidgetData.immichAlbums.slice(0, input.limit);
}
const innerHandler = immichAlbumsRequestHandler.handler( const innerHandler = immichAlbumsRequestHandler.handler(
{ ...ctx.integration, kind: "immich" }, { ...ctx.integration, kind: "immich" },
{ {
+2 -1
View File
@@ -6,7 +6,8 @@ import { harnessRoot, normalizeHarnessEnvironmentArgs } from "./commands/harness
const harnessCommandNames = new Set(["harness", "local-harness"]); const harnessCommandNames = new Set(["harness", "local-harness"]);
function isHarnessInvocation(argv: string[]): boolean { function isHarnessInvocation(argv: string[]): boolean {
return argv.slice(2).some((argument) => harnessCommandNames.has(argument)); const command = argv[2];
return command !== undefined && harnessCommandNames.has(command);
} }
async function main(): Promise<void> { async function main(): Promise<void> {
+2 -5
View File
@@ -805,10 +805,7 @@ const buildDemoWidgets = (appIds: string[], customWidgetDefinitionId: string): D
width: 4, width: 4,
height: 3, height: 3,
needsIntegration: false, needsIntegration: false,
options: { options: { embedUrl: "/api/demo-assets/overview", allowScrolling: true },
embedUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/svg/homarr.svg",
allowScrolling: false,
},
}, },
{ {
kind: "video", kind: "video",
@@ -818,7 +815,7 @@ const buildDemoWidgets = (appIds: string[], customWidgetDefinitionId: string): D
height: 3, height: 3,
needsIntegration: false, needsIntegration: false,
options: { options: {
feedUrl: "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4", feedUrl: "/api/demo-assets/video/file.mp4",
hasAutoPlay: false, hasAutoPlay: false,
isMuted: true, isMuted: true,
hasControls: true, hasControls: true,
@@ -12,6 +12,11 @@ describe("getUsableWidgetQueryData", () => {
expect(getUsableWidgetQueryData({ data, error: new Error("offline") })).toBe(data); expect(getUsableWidgetQueryData({ data, error: new Error("offline") })).toBe(data);
}); });
test("throws access-denied refetches instead of rendering stale cached data", () => {
const error = { data: { code: "FORBIDDEN" } };
expect(() => getUsableWidgetQueryData({ data: [{ id: "revoked" }], error })).toThrow(error);
});
test("throws a terminal failure when no usable data exists", () => { test("throws a terminal failure when no usable data exists", () => {
const error = new Error("offline"); const error = new Error("offline");
expect(() => getUsableWidgetQueryData({ data: undefined, error })).toThrow(error); expect(() => getUsableWidgetQueryData({ data: undefined, error })).toThrow(error);
@@ -7,8 +7,20 @@ interface PendingWidgetQueryState extends WidgetQueryState {
isPending: boolean; isPending: boolean;
} }
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null;
interface ForbiddenTrpcError {
data: { code: "FORBIDDEN" };
}
export const isTrpcForbiddenError = (error: unknown): error is ForbiddenTrpcError => {
if (!isRecord(error) || !isRecord(error.data)) return false;
return error.data.code === "FORBIDDEN";
};
/** Throws terminal query failures while preserving successful empty values and stale cached data. */ /** Throws terminal query failures while preserving successful empty values and stale cached data. */
export const getUsableWidgetQueryData = <TQuery extends WidgetQueryState>(query: TQuery): TQuery["data"] => { export const getUsableWidgetQueryData = <TQuery extends WidgetQueryState>(query: TQuery): TQuery["data"] => {
if (isTrpcForbiddenError(query.error)) throw query.error;
if (query.error && query.data === undefined) throw query.error; if (query.error && query.data === undefined) throw query.error;
return query.data; return query.data;
}; };
@@ -63,10 +63,14 @@ export interface WidgetEditModalSize {
height: number; height: number;
} }
export interface WidgetPreviewDimensions extends WidgetEditModalSize {
scale?: number;
}
interface WidgetEditPreviewResizeOptions { interface WidgetEditPreviewResizeOptions {
initialSize: WidgetEditModalSize; initialSize: WidgetEditModalSize;
maximumSize: WidgetEditModalSize; maximumSize: WidgetEditModalSize;
getDimensions?: (size: WidgetEditModalSize) => { width: number; height: number; scale?: number }; getDimensions?: (size: WidgetEditModalSize) => WidgetPreviewDimensions;
} }
export interface EmbeddedIntegrationEditFormHandle { export interface EmbeddedIntegrationEditFormHandle {
@@ -94,7 +98,7 @@ export interface WidgetEditModalProps<TSort extends WidgetKind> {
onIntegrationSaved?: () => void; onIntegrationSaved?: () => void;
onOpenNewIntegration?: (onCreated?: (id: string) => void) => void; onOpenNewIntegration?: (onCreated?: (id: string) => void) => void;
previewComponent?: ComponentType<WidgetComponentProps<TSort>>; previewComponent?: ComponentType<WidgetComponentProps<TSort>>;
previewDimensions?: { width: number; height: number; scale?: number }; previewDimensions?: WidgetPreviewDimensions;
previewResize?: WidgetEditPreviewResizeOptions; previewResize?: WidgetEditPreviewResizeOptions;
previewWrapper?: ComponentType<PropsWithChildren>; previewWrapper?: ComponentType<PropsWithChildren>;
} }
@@ -106,7 +110,7 @@ interface WidgetEditPreviewProps {
state: WidgetEditModalState; state: WidgetEditModalState;
itemId?: string; itemId?: string;
boardId?: string; boardId?: string;
dimensions?: { width: number; height: number; scale?: number }; dimensions?: WidgetPreviewDimensions;
integrationData: IntegrationSelectOption[]; integrationData: IntegrationSelectOption[];
onChangeOptions: (newOptions: Record<string, unknown>) => void; onChangeOptions: (newOptions: Record<string, unknown>) => void;
resize?: { resize?: {
@@ -174,7 +178,9 @@ const WidgetEditPreview = ({
}, },
})); }));
let componentItemId = itemId; let componentItemId = itemId;
if (kind === "assistant") componentItemId = `widget-preview-${generatedPreviewId}`; if (kind === "assistant" || kind === "timer") {
componentItemId = `widget-preview-${generatedPreviewId}`;
}
const isPendingCustomWidget = kind === "customApi" && !itemId; const isPendingCustomWidget = kind === "customApi" && !itemId;
const previewOpacity = (board?.opacity ?? 100) / 100; const previewOpacity = (board?.opacity ?? 100) / 100;
const handleResizeValue = (dimension: keyof WidgetEditModalSize, value: string | number) => { const handleResizeValue = (dimension: keyof WidgetEditModalSize, value: string | number) => {
+5 -1
View File
@@ -76,7 +76,7 @@ func (m Model) instanceTarget(row instanceRow) target {
result := target{ result := target{
label: row.container.Name, label: row.container.Name,
container: row.container.Name, container: row.container.Name,
volume: row.container.Name + "_data", volume: row.volume,
running: row.container.Running(), running: row.container.Running(),
port: row.container.HostPort(), port: row.container.HostPort(),
} }
@@ -315,6 +315,10 @@ func (m Model) deleteImage(reference string) (Model, tea.Cmd) {
// away either way, and failing halfway would leave the user to work out why. // away either way, and failing halfway would leave the user to work out why.
func (m Model) deleteData(subject target) (Model, tea.Cmd) { func (m Model) deleteData(subject target) (Model, tea.Cmd) {
container, volume := subject.container, subject.volume container, volume := subject.container, subject.volume
if volume == "" {
m.status, m.statusLevel = subject.label+" has no data volume to delete", levelWarn
return m, nil
}
m.tasks.Action("delete data "+volume, volume, func(ctx context.Context) error { m.tasks.Action("delete data "+volume, volume, func(ctx context.Context) error {
_ = docker.RemoveContext(ctx, container) _ = docker.RemoveContext(ctx, container)
return docker.RemoveVolume(ctx, volume) return docker.RemoveVolume(ctx, volume)
+4
View File
@@ -65,6 +65,10 @@ func (m Model) handleManageKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
return m.arm(actionDeleteImage, subject) return m.arm(actionDeleteImage, subject)
case key.Matches(msg, m.keys.ManageData): case key.Matches(msg, m.keys.ManageData):
if subject.volume == "" {
m.status, m.statusLevel = subject.label+" has no data volume to delete", levelWarn
return m, nil
}
return m.arm(actionDeleteData, subject) return m.arm(actionDeleteData, subject)
case key.Matches(msg, m.keys.ManageStop): case key.Matches(msg, m.keys.ManageStop):