This commit is contained in:
jarek committed 2026-04-26 08:01:32 +02:00
1 parent ccfda4c054
commit 7e3797cbfe
38 files changed
+1115 -274

No files matched your search

+9 -7
View File
@@ -22,6 +22,7 @@
import { getLabelColor, getLabelBgColor } from '$lib/utils/label-colors';
import { Input } from '$lib/components/ui/input';
import MultiSelectFilter from '$lib/components/MultiSelectFilter.svelte';
import { appSettings } from '$lib/stores/settings';
const LABEL_FILTER_STORAGE_KEY = 'dockhand-dashboard-label-filter';
@@ -210,10 +211,10 @@
if (filterLabels.length === 0) {
return tiles;
}
return tiles.filter(t => {
const tileLabels = t.stats?.labels || [];
return tileLabels.some(label => filterLabels.includes(label));
});
const matchFn = $appSettings.labelFilterMode === 'all'
? (tileLabels: string[]) => filterLabels.every(label => tileLabels.includes(label))
: (tileLabels: string[]) => filterLabels.some(label => tileLabels.includes(label));
return tiles.filter(t => matchFn(t.stats?.labels || []));
});
// Filter grid items based on selected labels
@@ -221,11 +222,12 @@
if (filterLabels.length === 0) {
return gridItems;
}
// Filter to only show tiles whose environments have at least one matching label
const matchFn = $appSettings.labelFilterMode === 'all'
? (tileLabels: string[]) => filterLabels.every(label => tileLabels.includes(label))
: (tileLabels: string[]) => filterLabels.some(label => tileLabels.includes(label));
return gridItems.filter(item => {
const tile = tiles.find(t => t.id === item.id);
const tileLabels = tile?.stats?.labels || [];
return tileLabels.some(label => filterLabels.includes(label));
return matchFn(tile?.stats?.labels || []);
});
});
const orderedGridItems = $derived.by(() => {
+4 -1
View File
@@ -3,6 +3,7 @@ import { listContainers, createContainer, pullImage, EnvironmentNotFoundError, D
import { authorize } from '$lib/server/authorize';
import { auditContainer } from '$lib/server/audit';
import { hasEnvironments } from '$lib/server/db';
import { isHiddenByLabel } from '$lib/server/container-labels';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ url, cookies }) => {
@@ -34,7 +35,9 @@ export const GET: RequestHandler = async ({ url, cookies }) => {
try {
const containers = await listContainers(all, envIdNum);
return json(containers);
// Filter out containers with dockhand.hidden=true label
const visible = containers.filter(c => !isHiddenByLabel(c.labels));
return json(visible);
} catch (error: any) {
// Return 404 for missing environment so frontend can clear stale localStorage
if (error instanceof EnvironmentNotFoundError) {
+6 -3
View File
@@ -4,7 +4,8 @@ import {
removeContainer,
getContainerLogs
} from '$lib/server/docker';
import { deleteAutoUpdateSchedule, getAutoUpdateSetting, getSecretKeyNames, removePendingContainerUpdate } from '$lib/server/db';
import { deleteAutoUpdateSchedule, getAutoUpdateSetting, getSecretKeysToMask, removePendingContainerUpdate } from '$lib/server/db';
import { getStackComposeFile } from '$lib/server/stacks';
import { authorize } from '$lib/server/authorize';
import { auditContainer } from '$lib/server/audit';
import { unregisterSchedule } from '$lib/server/scheduler';
@@ -34,10 +35,12 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
const details = await inspectContainer(params.id, envIdNum);
// Mask secret env vars for containers belonging to a Compose stack
// Mask secret env vars for containers belonging to a Compose stack.
// Uses compose file parsing to detect interpolation (e.g., MYSQL_PASSWORD=${db_secret}).
const stackName = details.Config?.Labels?.['com.docker.compose.project'];
if (stackName && Array.isArray(details.Config?.Env)) {
const secretKeys = await getSecretKeyNames(stackName, envIdNum);
const composeResult = await getStackComposeFile(stackName, envIdNum).catch(() => null);
const secretKeys = await getSecretKeysToMask(stackName, envIdNum, composeResult?.content);
if (secretKeys.size > 0) {
details.Config.Env = details.Config.Env.map((entry: string) => {
const eqIdx = entry.indexOf('=');
@@ -1,7 +1,8 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { inspectContainer } from '$lib/server/docker';
import { getSecretKeyNames } from '$lib/server/db';
import { getSecretKeysToMask } from '$lib/server/db';
import { getStackComposeFile } from '$lib/server/stacks';
import { authorize } from '$lib/server/authorize';
import { validateDockerIdParam } from '$lib/server/docker-validation';
@@ -22,10 +23,12 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
try {
const containerData = await inspectContainer(params.id, envIdNum);
// Mask secret env vars for containers belonging to a Compose stack
// Mask secret env vars for containers belonging to a Compose stack.
// Uses compose file parsing to detect interpolation (e.g., MYSQL_PASSWORD=${db_secret}).
const stackName = containerData.Config?.Labels?.['com.docker.compose.project'];
if (stackName && Array.isArray(containerData.Config?.Env)) {
const secretKeys = await getSecretKeyNames(stackName, envIdNum);
const composeResult = await getStackComposeFile(stackName, envIdNum).catch(() => null);
const secretKeys = await getSecretKeysToMask(stackName, envIdNum, composeResult?.content);
if (secretKeys.size > 0) {
containerData.Config.Env = containerData.Config.Env.map((entry: string) => {
const eqIdx = entry.indexOf('=');
@@ -15,6 +15,7 @@ import { auditContainer } from '$lib/server/audit';
import { getScannerSettings, scanImage } from '$lib/server/scanner';
import { saveVulnerabilityScan, removePendingContainerUpdate, type VulnerabilityCriteria } from '$lib/server/db';
import { parseImageNameAndTag, shouldBlockUpdate, combineScanSummaries, isSystemContainer } from '$lib/server/scheduler/tasks/update-utils';
import { isUpdateDisabledByLabel } from '$lib/server/container-labels';
import { recreateContainer } from '$lib/server/scheduler/tasks/container-update';
import { createJob, appendLine, completeJob, failJob } from '$lib/server/jobs';
@@ -173,6 +174,22 @@ export const POST: RequestHandler = async (event) => {
continue;
}
// Skip containers with dockhand.update=false label
if (isUpdateDisabledByLabel(config.Labels)) {
sendData({
type: 'progress',
containerId,
containerName,
step: 'skipped',
current: i + 1,
total: containerIds.length,
success: true,
message: `Skipping ${containerName} - dockhand.update=false label`
});
skippedCount++;
continue;
}
// Skip digest-pinned images - they are explicitly locked to a specific version
if (isDigestBasedImage(imageName)) {
sendData({
@@ -4,6 +4,7 @@ import { authorize } from '$lib/server/authorize';
import { listContainers, pullImage, inspectContainer } from '$lib/server/docker';
import { auditContainer } from '$lib/server/audit';
import { recreateContainer } from '$lib/server/scheduler/tasks/container-update';
import { isUpdateDisabledByLabel } from '$lib/server/container-labels';
export interface BatchUpdateResult {
containerId: string;
@@ -62,6 +63,17 @@ export const POST: RequestHandler = async (event) => {
const imageName = config.Image;
const containerName = container.name;
// Skip containers with dockhand.update=false label
if (isUpdateDisabledByLabel(config.Labels)) {
results.push({
containerId,
containerName,
success: true,
error: 'Skipped - dockhand.update=false label'
});
continue;
}
// Pull latest image first
try {
await pullImage(imageName, undefined, envIdNum);
@@ -4,6 +4,7 @@ import { authorize } from '$lib/server/authorize';
import { listContainers, inspectContainer, checkImageUpdateAvailable } from '$lib/server/docker';
import { clearPendingContainerUpdates, addPendingContainerUpdate } from '$lib/server/db';
import { isSystemContainer } from '$lib/server/scheduler/tasks/update-utils';
import { isUpdateDisabledByLabel } from '$lib/server/container-labels';
import { createJobResponse } from '$lib/server/sse';
export interface UpdateCheckResult {
@@ -16,6 +17,7 @@ export interface UpdateCheckResult {
error?: string;
isLocalImage?: boolean;
systemContainer?: 'dockhand' | 'hawser' | null;
updateDisabled?: boolean;
}
/**
@@ -64,6 +66,7 @@ export const POST: RequestHandler = async ({ url, cookies, request }) => {
}
const result = await checkImageUpdateAvailable(imageName, currentImageId, envIdNum);
const updateDisabled = isUpdateDisabledByLabel(inspectData.Config?.Labels);
return {
containerId: container.id,
@@ -74,7 +77,8 @@ export const POST: RequestHandler = async ({ url, cookies, request }) => {
newDigest: result.registryDigest,
error: result.error,
isLocalImage: result.isLocalImage,
systemContainer: isSystemContainer(imageName) || null
systemContainer: isSystemContainer(imageName) || null,
updateDisabled
};
} catch (error: any) {
return {
@@ -102,12 +106,12 @@ export const POST: RequestHandler = async ({ url, cookies, request }) => {
}
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, containers.length) }, () => runNext()));
const updatesFound = results.filter(r => r.hasUpdate && !r.systemContainer).length;
const updatesFound = results.filter(r => r.hasUpdate && !r.systemContainer && !r.updateDisabled).length;
// Save containers with updates to the database for persistence
if (envIdNum) {
for (const result of results) {
if (result.hasUpdate && !result.systemContainer) {
if (result.hasUpdate && !result.systemContainer && !result.updateDisabled) {
await addPendingContainerUpdate(
envIdNum,
result.containerId,
@@ -115,6 +115,7 @@ export const DELETE: RequestHandler = async (event) => {
// Delete git stack clone directories before cascade deletes the DB rows
const stacks = await getGitStacksByRepositoryId(id);
console.log(`[GitStack] Repository "${repository.name}" (id=${id}) deletion affects ${stacks.length} stacks: ${stacks.map(s => s.stackName).join(', ')}`);
for (const stack of stacks) {
await deleteGitStackFiles(stack.id, stack.stackName, stack.environmentId);
}
+49 -8
View File
@@ -77,6 +77,10 @@ export interface GeneralSettings {
// Scanner images
defaultGrypeImage: string;
defaultTrivyImage: string;
// Compose template
defaultComposeTemplate: string;
// Label filter mode
labelFilterMode: 'any' | 'all';
}
const DEFAULT_SETTINGS: Omit<GeneralSettings, 'scheduleRetentionDays' | 'eventRetentionDays' | 'scheduleCleanupCron' | 'eventCleanupCron' | 'scheduleCleanupEnabled' | 'eventCleanupEnabled'> = {
@@ -105,7 +109,26 @@ const DEFAULT_SETTINGS: Omit<GeneralSettings, 'scheduleRetentionDays' | 'eventRe
externalStackPaths: [],
primaryStackLocation: null,
defaultGrypeImage: DEFAULT_GRYPE_IMAGE,
defaultTrivyImage: DEFAULT_TRIVY_IMAGE
defaultTrivyImage: DEFAULT_TRIVY_IMAGE,
labelFilterMode: 'any' as const,
defaultComposeTemplate: `version: "3.8"
services:
app:
image: nginx:alpine
ports:
- "8080:80"
environment:
- APP_ENV=\${APP_ENV:-production}
volumes:
- ./html:/usr/share/nginx/html:ro
restart: unless-stopped
# Add more services as needed
# networks:
# default:
# driver: bridge
`
};
const VALID_LIGHT_THEMES = ['default', 'catppuccin', 'rose-pine', 'nord', 'solarized', 'gruvbox', 'alucard', 'github', 'material', 'atom-one'];
@@ -159,7 +182,9 @@ export const GET: RequestHandler = async ({ cookies }) => {
externalStackPaths,
primaryStackLocation,
defaultGrypeImage,
defaultTrivyImage
defaultTrivyImage,
defaultComposeTemplate,
labelFilterMode
] = await Promise.all([
getSetting('confirm_destructive'),
getSetting('show_stopped_containers'),
@@ -192,7 +217,9 @@ export const GET: RequestHandler = async ({ cookies }) => {
getExternalStackPaths(),
getPrimaryStackLocation(),
getSetting('default_grype_image'),
getSetting('default_trivy_image')
getSetting('default_trivy_image'),
getSetting('default_compose_template'),
getSetting('label_filter_mode')
]);
const settings: GeneralSettings = {
@@ -227,7 +254,9 @@ export const GET: RequestHandler = async ({ cookies }) => {
externalStackPaths,
primaryStackLocation,
defaultGrypeImage: defaultGrypeImage ?? DEFAULT_GRYPE_IMAGE,
defaultTrivyImage: defaultTrivyImage ?? DEFAULT_TRIVY_IMAGE
defaultTrivyImage: defaultTrivyImage ?? DEFAULT_TRIVY_IMAGE,
defaultComposeTemplate: defaultComposeTemplate ?? DEFAULT_SETTINGS.defaultComposeTemplate,
labelFilterMode: labelFilterMode ?? DEFAULT_SETTINGS.labelFilterMode
};
return json(settings);
@@ -245,7 +274,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
try {
const body = await request.json();
const { confirmDestructive, showStoppedContainers, highlightUpdates, timeFormat, dateFormat, downloadFormat, defaultGrypeArgs, defaultTrivyArgs, scheduleRetentionDays, eventRetentionDays, scheduleCleanupCron, eventCleanupCron, scheduleCleanupEnabled, eventCleanupEnabled, logBufferSizeKb, defaultTimezone, eventCollectionMode, eventPollInterval, metricsCollectionInterval, lightTheme, darkTheme, font, fontSize, gridFontSize, terminalFont, editorFont, compactPorts, formatLogTimestamps, externalStackPaths, primaryStackLocation, defaultGrypeImage, defaultTrivyImage } = body;
const { confirmDestructive, showStoppedContainers, highlightUpdates, timeFormat, dateFormat, downloadFormat, defaultGrypeArgs, defaultTrivyArgs, scheduleRetentionDays, eventRetentionDays, scheduleCleanupCron, eventCleanupCron, scheduleCleanupEnabled, eventCleanupEnabled, logBufferSizeKb, defaultTimezone, eventCollectionMode, eventPollInterval, metricsCollectionInterval, lightTheme, darkTheme, font, fontSize, gridFontSize, terminalFont, editorFont, compactPorts, formatLogTimestamps, externalStackPaths, primaryStackLocation, defaultGrypeImage, defaultTrivyImage, defaultComposeTemplate, labelFilterMode } = body;
if (confirmDestructive !== undefined) {
await setSetting('confirm_destructive', confirmDestructive);
@@ -364,6 +393,12 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
if (defaultTrivyImage !== undefined && typeof defaultTrivyImage === 'string') {
await setSetting('default_trivy_image', defaultTrivyImage);
}
if (defaultComposeTemplate !== undefined && typeof defaultComposeTemplate === 'string') {
await setSetting('default_compose_template', defaultComposeTemplate);
}
if (labelFilterMode !== undefined && (labelFilterMode === 'any' || labelFilterMode === 'all')) {
await setSetting('label_filter_mode', labelFilterMode);
}
// Fetch all settings in parallel for the response
const [
@@ -398,7 +433,9 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
externalStackPathsVal,
primaryStackLocationVal,
defaultGrypeImageVal,
defaultTrivyImageVal
defaultTrivyImageVal,
defaultComposeTemplateVal,
labelFilterModeVal
] = await Promise.all([
getSetting('confirm_destructive'),
getSetting('show_stopped_containers'),
@@ -431,7 +468,9 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
getExternalStackPaths(),
getPrimaryStackLocation(),
getSetting('default_grype_image'),
getSetting('default_trivy_image')
getSetting('default_trivy_image'),
getSetting('default_compose_template'),
getSetting('label_filter_mode')
]);
const settings: GeneralSettings = {
@@ -466,7 +505,9 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
externalStackPaths: externalStackPathsVal,
primaryStackLocation: primaryStackLocationVal,
defaultGrypeImage: defaultGrypeImageVal ?? DEFAULT_GRYPE_IMAGE,
defaultTrivyImage: defaultTrivyImageVal ?? DEFAULT_TRIVY_IMAGE
defaultTrivyImage: defaultTrivyImageVal ?? DEFAULT_TRIVY_IMAGE,
defaultComposeTemplate: defaultComposeTemplateVal ?? DEFAULT_SETTINGS.defaultComposeTemplate,
labelFilterMode: labelFilterModeVal ?? DEFAULT_SETTINGS.labelFilterMode
};
return json(settings);
+2 -3
View File
@@ -12,6 +12,7 @@
import * as Select from '$lib/components/ui/select';
import * as Tooltip from '$lib/components/ui/tooltip';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import { formatPorts, type PortMapping } from '$lib/utils/port-format';
import MultiSelectFilter from '$lib/components/MultiSelectFilter.svelte';
import PageHeader from '$lib/components/PageHeader.svelte';
import { Badge } from '$lib/components/ui/badge';
@@ -1149,8 +1150,6 @@
}
}
import { formatPorts, type PortMapping } from '$lib/utils/port-format';
function extractHostFromUrl(urlString: string): string | null {
if (!urlString) return null;
@@ -1861,7 +1860,7 @@
{@const remainingCount = ports.length - 1}
<div class="flex {compactPorts ? 'flex-nowrap' : 'flex-wrap'} gap-1">
{#each displayPorts as port}
{@const url = !port.isRange && currentEnvDetails ? getPortUrl(port.publicPort) : null}
{@const url = currentEnvDetails ? getPortUrl(port.publicPort) : null}
{#if url}
<a
href={url}
+63 -5
View File
@@ -6,6 +6,7 @@
import { CircleArrowUp, Loader2, AlertCircle, CheckCircle2, XCircle, ChevronDown, ChevronRight, ExternalLink } from 'lucide-svelte';
import { appendEnvParam } from '$lib/stores/environment';
import { untrack } from 'svelte';
import type { VulnerabilityCriteria } from '$lib/server/db';
import type { StepType } from '$lib/utils/update-steps';
import { getStepLabel, getStepIcon, getStepColor } from '$lib/utils/update-steps';
@@ -78,11 +79,33 @@
let progress = $state<ContainerProgress[]>([]);
let progressListEl = $state<HTMLDivElement | null>(null);
let scrollTick = $state(0);
let userScrolledUp = $state(false);
let currentIndex = $state(0);
let totalCount = $state(0);
let summary = $state<{ total: number; success: number; failed: number; blocked: number } | null>(null);
let errorMessage = $state('');
let forceUpdating = $state<Set<string>>(new Set()); // Track containers being force-updated
let filterMode = $state<'updated' | 'failed'>('updated');
let filteredProgress = $derived(
!summary
? progress
: filterMode === 'failed'
? progress.filter(p => p.step === 'failed' || p.step === 'blocked')
: progress.filter(p => p.step === 'done' || p.success)
);
$effect(() => {
// Only track filterMode, not progress — avoid re-running on every SSE update
const mode = filterMode;
if (mode === 'updated') {
untrack(() => {
for (const item of progress) {
item.showLogs = false;
}
});
}
});
function formatPullLog(entry: PullLogEntry): string {
// Clarify potentially confusing Docker messages
@@ -241,6 +264,9 @@
} else if (data.type === 'complete') {
status = 'complete';
summary = data.summary;
for (const item of progress) {
item.showLogs = false;
}
onComplete({ success: successIds, failed: failedIds, blocked: blockedIds });
} else if (data.type === 'error') {
status = 'error';
@@ -266,6 +292,7 @@
currentIndex = 0;
summary = null;
errorMessage = '';
filterMode = 'updated';
}
function handleOpenChange(isOpen: boolean) {
@@ -384,10 +411,18 @@ const severityOrder: Record<string, number> = { critical: 0, high: 1, medium: 2,
}
});
// Auto-scroll progress list to bottom on SSE data (not UI toggles)
// Track whether user has scrolled up to read earlier output
function handleProgressScroll() {
if (!progressListEl) return;
const { scrollTop, scrollHeight, clientHeight } = progressListEl;
// Consider "at bottom" if within 50px of the end
userScrolledUp = scrollHeight - scrollTop - clientHeight > 50;
}
// Auto-scroll progress list to bottom on SSE data, but only if user hasn't scrolled up
$effect(() => {
scrollTick;
if (progressListEl) {
if (progressListEl && !userScrolledUp) {
requestAnimationFrame(() => {
progressListEl?.scrollTo({ top: progressListEl.scrollHeight, behavior: 'smooth' });
});
@@ -438,10 +473,33 @@ const severityOrder: Record<string, number> = { critical: 0, high: 1, medium: 2,
<Progress value={progressPercentage} class="h-2" />
</div>
<!-- Container list with status - scrollable area -->
<!-- Filter toggle + Container list with status - scrollable area -->
{#if progress.length > 0}
<div bind:this={progressListEl} class="border rounded-lg divide-y flex-1 min-h-0 overflow-auto">
{#each progress as item (item.containerId)}
{#if summary && (summary.failed > 0 || summary.blocked > 0) && summary.success > 0}
<div class="flex items-center gap-1 shrink-0">
<Button
variant={filterMode === 'updated' ? 'default' : 'outline'}
size="sm"
class="h-7 text-xs"
onclick={() => filterMode = 'updated'}
>
<CheckCircle2 class="w-3 h-3 mr-1" />
Updated ({summary.success})
</Button>
<Button
variant={filterMode === 'failed' ? 'destructive' : 'outline'}
size="sm"
class="h-7 text-xs"
onclick={() => filterMode = 'failed'}
>
<XCircle class="w-3 h-3 mr-1" />
Failed ({summary.failed + summary.blocked})
</Button>
</div>
{/if}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div bind:this={progressListEl} onscroll={handleProgressScroll} class="border rounded-lg divide-y flex-1 min-h-0 overflow-auto">
{#each filteredProgress as item (item.containerId)}
{@const StepIcon = getStepIcon(item.step)}
{@const isActive = item.step !== 'done' && item.step !== 'failed' && item.step !== 'blocked'}
{@const hasLogs = item.pullLogs.length > 0 || item.scanLogs.length > 0 || (item.vulnerabilities && item.vulnerabilities.length > 0)}
+26 -9
View File
@@ -162,20 +162,37 @@
// Push colliding items down (returns new array)
function pushCollidingItems(movedItem: GridItemLayout, sourceItems: GridItemLayout[]): GridItemLayout[] {
const newItems = sourceItems.map(item => ({ ...item }));
// Step 1: Push items that directly collide with the moved item
for (const item of newItems) {
if (item.id === movedItem.id) continue;
const overlaps = !(item.x + item.w <= movedItem.x || item.x >= movedItem.x + movedItem.w ||
item.y + item.h <= movedItem.y || item.y >= movedItem.y + movedItem.h);
if (overlaps) {
item.y = movedItem.y + movedItem.h;
}
}
// Step 2: Resolve cascading collisions by sorting top-to-bottom and pushing down
let changed = true;
let iterations = 0;
const maxIterations = 100; // Prevent infinite loops
while (changed && iterations < maxIterations) {
while (changed && iterations < 100) {
changed = false;
iterations++;
for (const item of newItems) {
if (item.id === movedItem.id) continue;
const sorted = newItems
.filter(i => i.id !== movedItem.id)
.sort((a, b) => a.y - b.y || a.x - b.x);
if (hasCollision(item, movedItem)) {
// Push this item down
item.y = movedItem.y + movedItem.h;
changed = true;
for (let i = 0; i < sorted.length; i++) {
for (let j = i + 1; j < sorted.length; j++) {
const upper = sorted[i];
const lower = sorted[j];
const overlaps = !(upper.x + upper.w <= lower.x || upper.x >= lower.x + lower.w ||
upper.y + upper.h <= lower.y || upper.y >= lower.y + lower.h);
if (overlaps) {
lower.y = upper.y + upper.h;
changed = true;
}
}
}
}
+209 -31
View File
@@ -10,13 +10,15 @@
import * as Select from '$lib/components/ui/select';
import { Checkbox } from '$lib/components/ui/checkbox';
import { ToggleGroup } from '$lib/components/ui/toggle-pill';
import { RefreshCw, Search, ChevronDown, ChevronUp, Unplug, Copy, Download, WrapText, ArrowDownToLine, X, Sun, Moon, LayoutList, Square, Box, Wifi, WifiOff, Pause, Play, ScrollText, Star, GripVertical, Layers, Check, FolderHeart, Save, Trash2, MoreHorizontal, Eraser } from 'lucide-svelte';
import { RefreshCw, Search, ChevronDown, ChevronUp, Unplug, Copy, Download, WrapText, ArrowDownToLine, X, Sun, Moon, LayoutList, Square, Box, Wifi, WifiOff, Pause, Play, ScrollText, Star, GripVertical, Layers, Check, FolderHeart, Save, Trash2, MoreHorizontal, Eraser, Filter, GripHorizontal, Terminal, ArrowDown, ArrowRight } from 'lucide-svelte';
import { copyToClipboard } from '$lib/utils/clipboard';
import PageHeader from '$lib/components/PageHeader.svelte';
import TerminalPanel from '../terminal/TerminalPanel.svelte';
import { detectShells, getBestShell, getSavedUser } from '$lib/utils/shell-detection';
import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
import type { ContainerInfo } from '$lib/types';
import { currentEnvironment, environments, appendEnvParam } from '$lib/stores/environment';
import { appSettings } from '$lib/stores/settings';
import { appSettings, formatLogTimestamps } from '$lib/stores/settings';
import { NoEnvironment } from '$lib/components/ui/empty-state';
import { AnsiUp } from 'ansi_up';
const ansiUp = new AnsiUp();
@@ -306,12 +308,94 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
// Log search state
let logSearchActive = $state(false);
let logSearchQuery = $state('');
let logSearchFilterMode = $state(false);
let currentMatchIndex = $state(0);
let matchCount = $state(0);
let logSearchInputRef: HTMLInputElement | undefined;
const fontSizeOptions = [10, 12, 14, 16];
// Terminal state
let terminalOpen = $state(false);
let terminalContainerId = $state<string | null>(null);
let terminalContainerName = $state('');
let terminalShell = $state('/bin/bash');
let terminalUser = $state('root');
let terminalLayout = $state<'below' | 'right'>('below');
let terminalSplitRatio = $state(0.5); // 0-1, ratio of logs panel
let isResizingTerminal = $state(false);
let terminalSplitRef: HTMLDivElement | undefined;
const TERMINAL_LAYOUT_KEY = 'dockhand-logs-terminal-layout';
const TERMINAL_SPLIT_KEY = 'dockhand-logs-terminal-split';
function loadTerminalSettings() {
if (typeof window === 'undefined') return;
const savedLayout = localStorage.getItem(TERMINAL_LAYOUT_KEY);
if (savedLayout === 'below' || savedLayout === 'right') terminalLayout = savedLayout;
const savedSplit = localStorage.getItem(TERMINAL_SPLIT_KEY);
if (savedSplit) {
const r = parseFloat(savedSplit);
if (!isNaN(r) && r >= 0.2 && r <= 0.8) terminalSplitRatio = r;
}
}
function saveTerminalSettings() {
if (typeof window === 'undefined') return;
localStorage.setItem(TERMINAL_LAYOUT_KEY, terminalLayout);
localStorage.setItem(TERMINAL_SPLIT_KEY, String(terminalSplitRatio));
}
async function openTerminal(containerId: string, containerName: string, layout?: 'below' | 'right') {
if (terminalOpen && terminalContainerId === containerId && (!layout || layout === terminalLayout)) {
closeTerminal();
return;
}
if (layout) {
terminalLayout = layout;
saveTerminalSettings();
}
terminalContainerId = containerId;
terminalContainerName = containerName;
const savedUser = getSavedUser(containerId);
if (savedUser) terminalUser = savedUser;
const result = await detectShells(containerId, envId);
const best = getBestShell(result, terminalShell);
if (best) terminalShell = best;
terminalOpen = true;
}
function closeTerminal() {
terminalOpen = false;
terminalContainerId = null;
}
function startTerminalResize(e: MouseEvent) {
e.preventDefault();
isResizingTerminal = true;
document.addEventListener('mousemove', handleTerminalResize);
document.addEventListener('mouseup', stopTerminalResize);
}
function handleTerminalResize(e: MouseEvent) {
if (!isResizingTerminal || !terminalSplitRef) return;
const rect = terminalSplitRef.getBoundingClientRect();
let ratio: number;
if (terminalLayout === 'below') {
ratio = (e.clientY - rect.top) / rect.height;
} else {
ratio = (e.clientX - rect.left) / rect.width;
}
terminalSplitRatio = Math.max(0.2, Math.min(0.8, ratio));
}
function stopTerminalResize() {
isResizingTerminal = false;
document.removeEventListener('mousemove', handleTerminalResize);
document.removeEventListener('mouseup', stopTerminalResize);
saveTerminalSettings();
}
// Subscribe to environment changes - restore state and fetch data
const unsubscribeEnv = currentEnvironment.subscribe(async (env) => {
envId = env?.id ?? null;
@@ -769,6 +853,10 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
return `[${data.containerName}] ${line}`;
}).join('\n');
}
// Format timestamps if enabled
if ($appSettings.formatLogTimestamps) {
text = formatLogTimestamps(text);
}
// Buffer text and schedule flush
pendingText += text;
if (!flushTimer) {
@@ -953,12 +1041,13 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
if (data.text) {
// Use consistent color based on position in all selected containers
const color = getContainerColor(data.containerId);
const logText = $appSettings.formatLogTimestamps ? formatLogTimestamps(data.text) : data.text;
// Add to pending batch instead of updating state immediately
pendingLogs.push({
containerId: data.containerId,
containerName: data.containerName,
color,
text: data.text,
text: logText,
timestamp: data.timestamp,
stream: data.stream
});
@@ -1134,6 +1223,11 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
// Stop any existing stream
stopStreaming();
// Close terminal when switching containers
if (terminalOpen && terminalContainerId !== container.id) {
closeTerminal();
}
selectedContainer = container;
searchQuery = '';
dropdownOpen = false;
@@ -1314,10 +1408,15 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
function closeLogSearch() {
logSearchActive = false;
logSearchQuery = '';
logSearchFilterMode = false;
currentMatchIndex = 0;
matchCount = 0;
}
function toggleSearchFilterMode() {
logSearchFilterMode = !logSearchFilterMode;
}
function navigateMatch(direction: 'prev' | 'next') {
if (!logsRef || matchCount === 0) return;
@@ -1368,38 +1467,54 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
// Highlighted logs with search matches and ANSI color support (single container mode)
let highlightedLogs = $derived(() => {
// First convert ANSI codes to HTML
const withAnsi = ansiToHtml(logs || '');
if (!logSearchQuery.trim()) return withAnsi;
let text = logs || '';
const query = logSearchQuery.trim();
// For search, we need to highlight matches while preserving HTML tags
// We'll only highlight text outside of HTML tags
const query = logSearchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const escapedQuery = escapeHtml(query);
// Filter lines before ANSI conversion (plain text matching)
if (logSearchFilterMode && query) {
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const filterRegex = new RegExp(escapedForRegex, 'i');
text = text.split('\n').filter(line => filterRegex.test(line)).join('\n');
}
const withAnsi = ansiToHtml(text);
if (!query) return withAnsi;
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const escapedQuery = escapeHtml(escapedForRegex);
// Split by HTML tags and only process text parts
const parts = withAnsi.split(/(<[^>]*>)/);
const highlighted = parts.map(part => {
// Skip HTML tags
return parts.map(part => {
if (part.startsWith('<')) return part;
// Highlight matches in text
const regex = new RegExp(`(${escapedQuery})`, 'gi');
return part.replace(regex, '<mark class="search-match">$1</mark>');
}).join('');
return highlighted;
});
// Format merged logs HTML — uses pre-built mergedHtml string, only applies search highlighting when needed
let formattedMergedHtml = $derived(() => {
if (!mergedHtml) return '';
if (!logSearchQuery.trim()) return mergedHtml;
const query = logSearchQuery.trim();
// Apply search highlighting (same approach as single mode's highlightedLogs)
const query = logSearchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const escapedQuery = escapeHtml(query);
// Filter mode: remove non-matching lines from HTML
let html = mergedHtml;
if (logSearchFilterMode && query) {
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const filterRegex = new RegExp(escapedForRegex, 'i');
// Split by <br/> or newlines, filter lines (strip HTML for matching, keep original for display)
const lines = html.split(/\n/);
html = lines.filter(line => {
const plainText = line.replace(/<[^>]*>/g, '');
return filterRegex.test(plainText);
}).join('\n');
}
if (!query) return html;
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const escapedQuery = escapeHtml(escapedForRegex);
const searchRegex = new RegExp(`(${escapedQuery})`, 'gi');
const parts = mergedHtml.split(/(<[^>]*>)/);
const parts = html.split(/(<[^>]*>)/);
return parts.map(part => {
if (part.startsWith('<')) return part;
return part.replace(searchRegex, '<mark class="search-match">$1</mark>');
@@ -1430,6 +1545,7 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
onMount(() => {
loadTerminalSettings();
// All initialization is handled in currentEnvironment.subscribe
// This just sets up the refresh interval
containerInterval = setInterval(fetchContainers, 10000);
@@ -1437,6 +1553,8 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
});
onDestroy(() => {
document.removeEventListener('mousemove', handleTerminalResize);
document.removeEventListener('mouseup', stopTerminalResize);
unsubscribeEnv();
if (containerInterval) {
clearInterval(containerInterval);
@@ -1831,8 +1949,9 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
</div>
{/if}
<!-- Logs panel -->
<div class="flex-1 min-h-0 border rounded-lg overflow-hidden flex flex-col transition-colors {darkMode ? 'bg-zinc-950 border-zinc-800' : 'bg-gray-50 border-gray-300'}">
<!-- Logs + Terminal split -->
<div bind:this={terminalSplitRef} class="flex-1 min-h-0 min-w-0 overflow-hidden flex {terminalOpen ? (terminalLayout === 'below' ? 'flex-col' : 'flex-row') : ''} gap-0">
<div class="{terminalOpen ? 'min-h-0 min-w-0' : 'flex-1'} border rounded-lg overflow-hidden flex flex-col transition-colors {darkMode ? 'bg-zinc-950 border-zinc-800' : 'bg-gray-50 border-gray-300'}" style="{terminalOpen ? (terminalLayout === 'below' ? `height: ${terminalSplitRatio * 100}%` : `width: ${terminalSplitRatio * 100}%`) : ''}">
{#if layoutMode === 'grouped'}
{#if selectedContainerIds.size === 0}
<div class="flex items-center justify-center h-full text-muted-foreground">
@@ -1840,8 +1959,8 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
</div>
{:else}
<!-- Header bar for grouped mode -->
<div class="flex items-center justify-between px-3 py-1.5 border-b shrink-0 transition-colors {darkMode ? 'border-zinc-800 bg-zinc-900/50' : 'border-gray-300 bg-gray-100'}">
<div class="flex items-center gap-2 min-w-[100px]">
<div class="flex items-center flex-wrap gap-y-1 px-3 py-1.5 border-b shrink-0 transition-colors {darkMode ? 'border-zinc-800 bg-zinc-900/50' : 'border-gray-300 bg-gray-100'}">
<div class="flex items-center gap-2 shrink-0">
{#if streamingEnabled}
{#if isConnected}
<div class="flex items-center gap-1.5" title="Connected - Live streaming">
@@ -1885,7 +2004,7 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
{/if}
</div>
</div>
<div class="flex items-center gap-3">
<div class="flex items-center gap-2 flex-wrap ml-auto">
<button
onclick={toggleStreaming}
class="flex items-center gap-1.5 px-2 py-1 rounded text-xs transition-colors {streamingEnabled ? (darkMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50 text-amber-400' : 'bg-amber-500/30 ring-1 ring-amber-600/50 text-amber-700') : darkMode ? 'text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-200'}"
@@ -1943,6 +2062,13 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
onkeydown={handleLogSearchKeydown}
class="bg-transparent border-none outline-none text-xs w-28 {darkMode ? 'text-zinc-200 placeholder:text-zinc-500' : 'text-gray-800 placeholder:text-gray-400'}"
/>
<button
onclick={toggleSearchFilterMode}
class="p-0.5 rounded transition-colors {logSearchFilterMode ? (darkMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : 'bg-amber-500/30 ring-1 ring-amber-600/50') : darkMode ? 'hover:bg-zinc-700' : 'hover:bg-gray-300'}"
title={logSearchFilterMode ? 'Show all lines (filter mode active)' : 'Hide non-matching lines'}
>
<Filter class="w-3 h-3 transition-colors {logSearchFilterMode ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-400' : 'text-gray-500'}" />
</button>
{#if matchCount > 0}
<span class="text-xs {darkMode ? 'text-zinc-400' : 'text-gray-500'}">{currentMatchIndex + 1}/{matchCount}</span>
{:else if logSearchQuery}
@@ -1993,8 +2119,8 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
</div>
{:else}
<!-- Header bar inside black area -->
<div class="flex items-center justify-between px-3 py-1.5 border-b shrink-0 transition-colors {darkMode ? 'border-zinc-800 bg-zinc-900/50' : 'border-gray-300 bg-gray-100'}">
<div class="flex items-center gap-2 min-w-[100px]">
<div class="flex items-center flex-wrap gap-y-1 px-3 py-1.5 border-b shrink-0 transition-colors {darkMode ? 'border-zinc-800 bg-zinc-900/50' : 'border-gray-300 bg-gray-100'}">
<div class="flex items-center gap-2 shrink-0">
<!-- Connection status indicator -->
{#if streamingEnabled}
{#if isConnected}
@@ -2028,14 +2154,34 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
<span class="text-xs {darkMode ? 'text-zinc-500' : 'text-gray-400'}">Paused</span>
</div>
{/if}
<!-- Container name -->
<!-- Container name + terminal toggles -->
{#if selectedContainer}
<div class="flex items-center gap-1 ml-2">
<div class="flex items-center gap-1.5 ml-2">
<span class="text-xs font-medium {darkMode ? 'text-zinc-300' : 'text-gray-700'}">{selectedContainer.name}</span>
<button
onclick={() => openTerminal(selectedContainer!.id, selectedContainer!.name, 'below')}
class="p-0.5 rounded transition-colors {terminalOpen && terminalLayout === 'below' && terminalContainerId === selectedContainer.id ? (darkMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : 'bg-amber-500/30 ring-1 ring-amber-600/50') : darkMode ? 'hover:bg-zinc-800' : 'hover:bg-gray-200'}"
title="Terminal below"
>
<span class="inline-flex items-center gap-px">
<Terminal class="w-3.5 h-3.5 {terminalOpen && terminalLayout === 'below' && terminalContainerId === selectedContainer.id ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-500 hover:text-zinc-300' : 'text-gray-500 hover:text-gray-700'}" />
<ArrowDown class="w-2.5 h-2.5 {terminalOpen && terminalLayout === 'below' && terminalContainerId === selectedContainer.id ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-600' : 'text-gray-400'}" strokeWidth={2.5} />
</span>
</button>
<button
onclick={() => openTerminal(selectedContainer!.id, selectedContainer!.name, 'right')}
class="p-0.5 rounded transition-colors {terminalOpen && terminalLayout === 'right' && terminalContainerId === selectedContainer.id ? (darkMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : 'bg-amber-500/30 ring-1 ring-amber-600/50') : darkMode ? 'hover:bg-zinc-800' : 'hover:bg-gray-200'}"
title="Terminal on side"
>
<span class="inline-flex items-center gap-px">
<Terminal class="w-3.5 h-3.5 {terminalOpen && terminalLayout === 'right' && terminalContainerId === selectedContainer.id ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-500 hover:text-zinc-300' : 'text-gray-500 hover:text-gray-700'}" />
<ArrowRight class="w-2.5 h-2.5 {terminalOpen && terminalLayout === 'right' && terminalContainerId === selectedContainer.id ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-600' : 'text-gray-400'}" strokeWidth={2.5} />
</span>
</button>
</div>
{/if}
</div>
<div class="flex items-center gap-3">
<div class="flex items-center gap-2 flex-wrap ml-auto">
<!-- Streaming toggle -->
<button
onclick={toggleStreaming}
@@ -2099,6 +2245,13 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
onkeydown={handleLogSearchKeydown}
class="bg-transparent border-none outline-none text-xs w-28 {darkMode ? 'text-zinc-200 placeholder:text-zinc-500' : 'text-gray-800 placeholder:text-gray-400'}"
/>
<button
onclick={toggleSearchFilterMode}
class="p-0.5 rounded transition-colors {logSearchFilterMode ? (darkMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : 'bg-amber-500/30 ring-1 ring-amber-600/50') : darkMode ? 'hover:bg-zinc-700' : 'hover:bg-gray-300'}"
title={logSearchFilterMode ? 'Show all lines (filter mode active)' : 'Hide non-matching lines'}
>
<Filter class="w-3 h-3 transition-colors {logSearchFilterMode ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-400' : 'text-gray-500'}" />
</button>
{#if matchCount > 0}
<span class="text-xs {darkMode ? 'text-zinc-400' : 'text-gray-500'}">{currentMatchIndex + 1}/{matchCount}</span>
{:else if logSearchQuery}
@@ -2177,6 +2330,31 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
{/if}
{/if}
</div>
<!-- Terminal panel with resize handle -->
{#if terminalOpen && terminalContainerId}
<!-- Resize handle -->
<div
role="separator"
class="{terminalLayout === 'below' ? 'h-2 cursor-ns-resize w-full' : 'w-2 cursor-ew-resize h-full'} flex items-center justify-center hover:bg-muted/50 transition-colors {isResizingTerminal ? 'bg-muted/50' : ''}"
onmousedown={startTerminalResize}
>
<GripHorizontal class="{terminalLayout === 'below' ? 'w-8 h-4' : 'w-4 h-8 rotate-90'} text-zinc-600" />
</div>
<!-- Terminal -->
<div class="min-h-0 min-w-0 border rounded-lg overflow-hidden" style="{terminalLayout === 'below' ? `height: ${(1 - terminalSplitRatio) * 100}%` : `width: ${(1 - terminalSplitRatio) * 100}%`}">
<TerminalPanel
containerId={terminalContainerId}
containerName={terminalContainerName}
shell={terminalShell}
user={terminalUser}
visible={true}
envId={envId}
fillHeight={true}
onClose={closeTerminal}
/>
</div>
{/if}
</div>
</div>
</div>
{/if}
+30 -5
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { RefreshCw, Copy, Download, WrapText, ArrowDownToLine, Search, ChevronUp, ChevronDown, X, Type, Eraser } from 'lucide-svelte';
import { RefreshCw, Copy, Download, WrapText, ArrowDownToLine, Search, ChevronUp, ChevronDown, X, Type, Eraser, Filter } from 'lucide-svelte';
import { copyToClipboard } from '$lib/utils/clipboard';
import * as Select from '$lib/components/ui/select';
import { appSettings, formatLogTimestamps } from '$lib/stores/settings';
@@ -45,6 +45,7 @@
// Search state
let logSearchActive = $state(false);
let logSearchQuery = $state('');
let logSearchFilterMode = $state(typeof window !== 'undefined' && localStorage.getItem('dockhand-log-filter-mode') === 'true');
let currentMatchIndex = $state(0);
let matchCount = $state(0);
let logSearchInputRef: HTMLInputElement;
@@ -107,10 +108,16 @@
function closeLogSearch() {
logSearchActive = false;
logSearchQuery = '';
logSearchFilterMode = false;
currentMatchIndex = 0;
matchCount = 0;
}
function toggleSearchFilterMode() {
logSearchFilterMode = !logSearchFilterMode;
localStorage.setItem('dockhand-log-filter-mode', String(logSearchFilterMode));
}
function navigateMatch(direction: 'prev' | 'next') {
if (!logsRef || matchCount === 0) return;
@@ -151,11 +158,22 @@
if ($appSettings.formatLogTimestamps) {
text = formatLogTimestamps(text);
}
const withAnsi = ansiUp.ansi_to_html(text);
if (!logSearchQuery.trim()) return withAnsi;
const query = logSearchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const escapedQuery = query.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const query = logSearchQuery.trim();
// Filter lines before ANSI conversion (plain text matching)
if (logSearchFilterMode && query) {
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const filterRegex = new RegExp(escapedForRegex, 'i');
const lines = text.split('\n');
text = lines.filter(line => filterRegex.test(line)).join('\n');
}
const withAnsi = ansiUp.ansi_to_html(text);
if (!query) return withAnsi;
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const escapedQuery = escapedForRegex.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// Split by HTML tags and only process text parts
const parts = withAnsi.split(/(<[^>]*>)/);
@@ -246,6 +264,13 @@
onkeydown={handleLogSearchKeydown}
class="bg-transparent border-none outline-none text-xs text-zinc-200 w-20 placeholder:text-zinc-500"
/>
<button
onclick={toggleSearchFilterMode}
class="p-0.5 rounded transition-colors {logSearchFilterMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : 'hover:bg-zinc-700'}"
title={logSearchFilterMode ? 'Show all lines (filter mode active)' : 'Hide non-matching lines'}
>
<Filter class="w-3 h-3 transition-colors {logSearchFilterMode ? 'text-amber-400' : 'text-zinc-400'}" />
</button>
{#if matchCount > 0}
<span class="text-xs text-zinc-400">{currentMatchIndex + 1}/{matchCount}</span>
{:else if logSearchQuery}
+33 -6
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import { onMount, onDestroy, tick } from 'svelte';
import { X, GripHorizontal, RefreshCw, Copy, Download, WrapText, ArrowDownToLine, Search, ChevronUp, ChevronDown, Sun, Moon, Wifi, WifiOff, Pause, Play, Eraser } from 'lucide-svelte';
import { X, GripHorizontal, RefreshCw, Copy, Download, WrapText, ArrowDownToLine, Search, ChevronUp, ChevronDown, Sun, Moon, Wifi, WifiOff, Pause, Play, Eraser, Filter } from 'lucide-svelte';
import { copyToClipboard } from '$lib/utils/clipboard';
import * as Select from '$lib/components/ui/select';
import { appSettings, formatLogTimestamps } from '$lib/stores/settings';
@@ -53,6 +53,7 @@
// Search state
let logSearchActive = $state(false);
let logSearchQuery = $state('');
let logSearchFilterMode = $state(false);
let currentMatchIndex = $state(0);
let matchCount = $state(0);
let logSearchInputRef: HTMLInputElement | undefined;
@@ -97,6 +98,7 @@
if (settings.fontSize !== undefined) fontSize = settings.fontSize;
if (settings.autoScroll !== undefined) autoScroll = settings.autoScroll;
if (settings.streamingEnabled !== undefined) streamingEnabled = settings.streamingEnabled;
if (settings.logSearchFilterMode !== undefined) logSearchFilterMode = settings.logSearchFilterMode;
} catch {
// Ignore parse errors
}
@@ -112,7 +114,8 @@
wordWrap,
fontSize,
autoScroll,
streamingEnabled
streamingEnabled,
logSearchFilterMode
}));
}
}
@@ -490,10 +493,16 @@
function closeLogSearch() {
logSearchActive = false;
logSearchQuery = '';
logSearchFilterMode = false;
currentMatchIndex = 0;
matchCount = 0;
}
function toggleSearchFilterMode() {
logSearchFilterMode = !logSearchFilterMode;
saveSettings();
}
function navigateMatch(direction: 'prev' | 'next') {
if (!logsRef || matchCount === 0) return;
@@ -534,11 +543,22 @@
if ($appSettings.formatLogTimestamps) {
text = formatLogTimestamps(text);
}
const withAnsi = ansiUp.ansi_to_html(text);
if (!logSearchQuery.trim()) return withAnsi;
const query = logSearchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const escapedQuery = query.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const query = logSearchQuery.trim();
// Filter lines before ANSI conversion (plain text matching)
if (logSearchFilterMode && query) {
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const filterRegex = new RegExp(escapedForRegex, 'i');
const lines = text.split('\n');
text = lines.filter(line => filterRegex.test(line)).join('\n');
}
const withAnsi = ansiUp.ansi_to_html(text);
if (!query) return withAnsi;
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const escapedQuery = escapedForRegex.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// Split by HTML tags and only process text parts
const parts = withAnsi.split(/(<[^>]*>)/);
@@ -734,6 +754,13 @@
onkeydown={handleLogSearchKeydown}
class="bg-transparent border-none outline-none text-xs w-20 {darkMode ? 'text-zinc-200 placeholder:text-zinc-500' : 'text-gray-800 placeholder:text-gray-400'}"
/>
<button
onclick={toggleSearchFilterMode}
class="p-0.5 rounded transition-colors {logSearchFilterMode ? (darkMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : 'bg-amber-500/30 ring-1 ring-amber-600/50') : darkMode ? 'hover:bg-zinc-700' : 'hover:bg-gray-300'}"
title={logSearchFilterMode ? 'Show all lines (filter mode active)' : 'Hide non-matching lines'}
>
<Filter class="w-3 h-3 transition-colors {logSearchFilterMode ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-400' : 'text-gray-500'}" />
</button>
{#if matchCount > 0}
<span class="text-xs {darkMode ? 'text-zinc-400' : 'text-gray-500'}">{currentMatchIndex + 1}/{matchCount}</span>
{:else if logSearchQuery}
+2 -2
View File
@@ -560,12 +560,12 @@
<RefreshCw class="w-3.5 h-3.5" />
Refresh
</Button>
<Button size="sm" variant="secondary" onclick={openGraphModal}>
<Button size="sm" variant="outline" onclick={openGraphModal}>
<GitGraph class="w-3.5 h-3.5" />
View Graph
</Button>
{#if $canAccess('networks', 'create')}
<Button size="sm" variant="secondary" onclick={() => showCreateModal = true}>
<Button size="sm" variant="outline" onclick={() => showCreateModal = true}>
<Plus class="w-3.5 h-3.5" />
Create
</Button>
+113 -2
View File
@@ -8,8 +8,9 @@
import { TogglePill, ToggleSwitch } from '$lib/components/ui/toggle-pill';
import CronEditor from '$lib/components/cron-editor.svelte';
import TimezoneSelector from '$lib/components/TimezoneSelector.svelte';
import { Eye, Bell, Database, Calendar, ShieldCheck, FileText, AlertTriangle, HelpCircle, Globe, Activity, Clock, Info } from 'lucide-svelte';
import { appSettings, type DateFormat, type DownloadFormat, type EventCollectionMode } from '$lib/stores/settings';
import { Eye, Bell, Database, Calendar, ShieldCheck, FileText, AlertTriangle, HelpCircle, Globe, Activity, Clock, Info, Save, RotateCcw, LayoutDashboard, Tags } from 'lucide-svelte';
import CodeEditor from '$lib/components/CodeEditor.svelte';
import { appSettings, type DateFormat, type DownloadFormat, type EventCollectionMode, type LabelFilterMode } from '$lib/stores/settings';
import { canAccess, authStore } from '$lib/stores/auth';
import { toast } from 'svelte-sonner';
import ThemeSelector from '$lib/components/ThemeSelector.svelte';
@@ -27,6 +28,46 @@
let defaultTrivyArgs = $derived($appSettings.defaultTrivyArgs);
let defaultGrypeImage = $derived($appSettings.defaultGrypeImage);
let defaultTrivyImage = $derived($appSettings.defaultTrivyImage);
let defaultComposeTemplate = $derived($appSettings.defaultComposeTemplate);
let labelFilterMode = $derived($appSettings.labelFilterMode);
let composeTemplateWIP = $state('');
let composeTemplateInitialized = false;
$effect(() => {
if (!composeTemplateInitialized && defaultComposeTemplate !== undefined) {
composeTemplateWIP = defaultComposeTemplate;
composeTemplateInitialized = true;
}
});
const builtinComposeTemplate = `version: "3.8"
services:
app:
image: nginx:alpine
ports:
- "8080:80"
environment:
- APP_ENV=\${APP_ENV:-production}
volumes:
- ./html:/usr/share/nginx/html:ro
restart: unless-stopped
# Add more services as needed
# networks:
# default:
# driver: bridge
`;
function saveComposeTemplate() {
appSettings.setDefaultComposeTemplate(composeTemplateWIP);
toast.success('Compose template updated');
}
function revertComposeTemplate() {
composeTemplateWIP = builtinComposeTemplate;
toast.info('Template reverted to default');
}
let scheduleRetentionDays = $derived($appSettings.scheduleRetentionDays);
let eventRetentionDays = $derived($appSettings.eventRetentionDays);
let scheduleCleanupCron = $derived($appSettings.scheduleCleanupCron);
@@ -425,6 +466,39 @@
</Card.Content>
</Card.Root>
<Card.Root>
<Card.Header>
<Card.Title class="text-sm font-medium flex items-center gap-2">
<FileText class="w-4 h-4" />
Compose template
</Card.Title>
<p class="text-xs text-muted-foreground">Default YAML content when creating a new stack.</p>
</Card.Header>
<Card.Content class="space-y-3">
<div class="h-64">
<CodeEditor
value={composeTemplateWIP}
onchange={(v) => { composeTemplateWIP = v; }}
language="yaml"
readonly={!$canAccess('settings', 'edit')}
class="h-full rounded-md overflow-hidden border border-zinc-200 dark:border-zinc-700"
/>
</div>
{#if $canAccess('settings', 'edit')}
<div class="flex gap-2">
<Button size="sm" variant="outline" onclick={saveComposeTemplate}>
<Save class="w-3.5 h-3.5" />
Save template
</Button>
<Button size="sm" variant="ghost" onclick={revertComposeTemplate}>
<RotateCcw class="w-3.5 h-3.5" />
Revert to default
</Button>
</div>
{/if}
</Card.Content>
</Card.Root>
</div>
<!-- Right column -->
@@ -686,6 +760,43 @@
</div>
</Card.Content>
</Card.Root>
<Card.Root>
<Card.Header>
<Card.Title class="text-sm font-medium flex items-center gap-2">
<LayoutDashboard class="w-4 h-4" />
Dashboard
</Card.Title>
</Card.Header>
<Card.Content class="space-y-4">
<div class="space-y-3">
<div class="space-y-1">
<div class="flex items-center gap-3">
<Label>Label filter matching</Label>
<Tooltip.Root>
<Tooltip.Trigger>
<HelpCircle class="w-3.5 h-3.5 text-muted-foreground" />
</Tooltip.Trigger>
<Tooltip.Content class="w-80">
<p class="text-xs">
Controls how multiple selected labels filter environments on the dashboard.
<strong>"Any"</strong>: shows environments that have at least one of the selected labels.
<strong>"All"</strong>: shows only environments that have every selected label.
</p>
</Tooltip.Content>
</Tooltip.Root>
<ToggleSwitch
value={labelFilterMode}
leftValue="any"
rightValue="all"
onchange={(mode) => appSettings.setLabelFilterMode(mode as LabelFilterMode)}
disabled={!$canAccess('settings', 'edit')}
/>
</div>
</div>
</div>
</Card.Content>
</Card.Root>
</div>
</div>
</div>
+1 -1
View File
@@ -2019,7 +2019,7 @@
{#if container.ports.length > 0}
{@const mappedPorts = formatPorts(container.ports)}
{#each mappedPorts as port}
{@const url = !port.isRange ? getPortUrl(port.publicPort) : null}
{@const url = getPortUrl(port.publicPort)}
{#if url}
<a
href={url}
+1 -18
View File
@@ -564,24 +564,7 @@
// Debounce timer for validation
let validateTimer: ReturnType<typeof setTimeout> | null = null;
const defaultCompose = `version: "3.8"
services:
app:
image: nginx:alpine
ports:
- "8080:80"
environment:
- APP_ENV=\${APP_ENV:-production}
volumes:
- ./html:/usr/share/nginx/html:ro
restart: unless-stopped
# Add more services as needed
# networks:
# default:
# driver: bridge
`;
const defaultCompose = $appSettings.defaultComposeTemplate;
// Count of defined environment variables (with non-empty keys)
const envVarCount = $derived(envVars.filter(v => v.key.trim()).length);