Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: stacks not saving on edit
Kyle Mendellba13d7bbda14
diff --git a/package-lock.json b/package-lock.jsonindex a4d789907..7a76a65c0 100644--- a/package-lock.json+++ b/package-lock.json@@ -20,7 +20,8 @@"prettier-plugin-svelte": "^3.3.3","proper-lockfile": "^4.1.2","redis": "^4.7.0",- "svelte-codemirror-editor": "^1.4.1"+ "svelte-codemirror-editor": "^1.4.1",+ "thememirror": "^2.0.1"},"devDependencies": {"@eslint/compat": "^1.2.5",@@ -5734,6 +5735,17 @@"node": ">=6"}},+ "node_modules/thememirror": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/thememirror/-/thememirror-2.0.1.tgz",+ "integrity": "sha512-d5i6FVvWWPkwrm4cHLI3t9AT1OrkAt7Ig8dtdYSofgF7C/eiyNuq6zQzSTusWTde3jpW9WLvA9J/fzNKMUsd0w==",+ "license": "MIT",+ "peerDependencies": {+ "@codemirror/language": "^6.0.0",+ "@codemirror/state": "^6.0.0",+ "@codemirror/view": "^6.0.0"+ }+ },"node_modules/tiny-case": {"version": "1.0.3","resolved": "https://registry.npmjs.org/tiny-case/-/tiny-case-1.0.3.tgz",diff --git a/package.json b/package.jsonindex 8ec2a4e1b..2f84fa553 100644--- a/package.json+++ b/package.json@@ -47,7 +47,6 @@},"dependencies": {"@codemirror/lang-yaml": "^6.1.2",- "@codemirror/theme-one-dark": "^6.1.2","@tanstack/table-core": "^8.21.3","codemirror": "^6.0.1","dockerode": "^4.0.6",@@ -58,6 +57,7 @@"prettier-plugin-svelte": "^3.3.3","proper-lockfile": "^4.1.2","redis": "^4.7.0",- "svelte-codemirror-editor": "^1.4.1"+ "svelte-codemirror-editor": "^1.4.1",+ "thememirror": "^2.0.1"}}diff --git a/src/lib/components/yaml-editor.svelte b/src/lib/components/yaml-editor.svelteindex 443f7cfa9..5d4793441 100644--- a/src/lib/components/yaml-editor.svelte+++ b/src/lib/components/yaml-editor.svelte@@ -4,21 +4,14 @@import { linter, lintGutter } from '@codemirror/lint';import { browser } from '$app/environment';import jsyaml from 'js-yaml';- import { createEventDispatcher } from 'svelte';- import { oneDark } from '@codemirror/theme-one-dark';+ import { coolGlow } from 'thememirror';+ import type { EditorView } from 'codemirror';- const dispatch = createEventDispatcher();+ // Make value bindable+ let { value = $bindable(''), height = '400px', placeholder = 'Enter YAML content', readOnly = false } = $props();- let { value = $bindable(''), height = '400px', placeholder = 'Enter YAML content', forceDarkTheme = true, readOnly = false } = $props();-- let darkMode = $state(forceDarkTheme || false);-- // Check for dark mode preference- $effect(() => {- if (browser) {- darkMode = forceDarkTheme || window.matchMedia('(prefers-color-scheme: dark)').matches || document.documentElement.classList.contains('dark');- }- });+ // Reference to the CodeMirror instance (for debugging if needed)+ let editorView: EditorView;// YAML linting functionfunction yamlLinter(view: { state: { doc: { toString(): string } } }) {@@ -28,7 +21,7 @@} catch (e: unknown) {const err = e as { mark?: { position: number }; message: string };const start = err.mark?.position || 0;- const end = err.mark?.position !== undefined ? err.mark.position + 1 : 1;+ const end = err.mark?.position !== undefined ? Math.max(start + 1, err.mark.position + 1) : start + 1;diagnostics.push({from: start,to: end,@@ -39,23 +32,18 @@return diagnostics;}- const extensions = $derived([yaml(), lintGutter(), linter(yamlLinter), darkMode ? oneDark : []]);-- function handleChange(e: Event) {- // No need to dispatch if readOnly- if (readOnly) return;- const target = e.target as HTMLInputElement;- value = target.value;- dispatch('change', { value });- }+ // Combined extensions array+ const lintExtension = linter(yamlLinter);</script>{#if browser}<div class="border rounded-md overflow-hidden"><CodeMirrorbind:value- on:change={handleChange}- {extensions}+ on:ready={(e) => (editorView = e.detail)}+ lang={yaml()}+ theme={coolGlow}+ extensions={[lintGutter(), lintExtension]}styles={{'&': {height,@@ -63,7 +51,6 @@fontFamily: 'JetBrains Mono, Menlo, Monaco, Consolas, monospace'},'&.cm-editor[contenteditable=false]': {- backgroundColor: '#f8f8f8',cursor: 'not-allowed'},'.cm-content[contenteditable=false]': {@@ -72,6 +59,7 @@}}{placeholder}readonly={readOnly}+ nodebounce={true}/></div>{/if}diff --git a/src/lib/types/errors.ts b/src/lib/types/errors.tsnew file mode 100644index 000000000..a1ccf08f7--- /dev/null+++ b/src/lib/types/errors.ts@@ -0,0 +1,19 @@+/* The `ServiceError` class in TypeScript extends the built-in `Error` class and sets its name to+'ServiceError'. */+export class ServiceError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ServiceError';+ // Ensure the prototype chain is correct+ Object.setPrototypeOf(this, ServiceError.prototype);+ }+}++/* The NotFoundError class is a subclass of ServiceError that represents a resource not found error. */+export class NotFoundError extends ServiceError {+ constructor(message: string = 'Resource not found') {+ super(message);+ this.name = 'NotFoundError';+ Object.setPrototypeOf(this, NotFoundError.prototype);+ }+}diff --git a/src/routes/api/stacks/[stackId]/+server.ts b/src/routes/api/stacks/[stackId]/+server.tsnew file mode 100644index 000000000..d39955092--- /dev/null+++ b/src/routes/api/stacks/[stackId]/+server.ts@@ -0,0 +1,45 @@+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';+import { updateStack } from '$lib/services/docker/stack-service';+import { NotFoundError, ServiceError } from '$lib/types/errors';++export const PATCH: RequestHandler = async ({ params, request }) => {+ const stackId = params.stackId;++ try {+ const body = await request.json();+ const { name, composeContent } = body;++ // Basic validation+ if (!stackId) {+ return json({ error: 'Stack ID is required' }, { status: 400 });+ }+ if (typeof name !== 'string' || name.trim() === '') {+ return json({ error: 'Stack name is required' }, { status: 400 });+ }+ // Allow empty compose content? Assuming yes for now.+ if (typeof composeContent !== 'string') {+ return json({ error: 'Invalid composeContent format' }, { status: 400 });+ }++ const updatedStack = await updateStack(stackId, { name: name.trim(), composeContent });++ return json({ message: 'Stack updated successfully', stack: updatedStack }, { status: 200 });+ } catch (error: any) {+ console.error(`Error updating stack ${stackId}:`, error);++ if (error instanceof SyntaxError) {+ // Handle invalid JSON+ return json({ error: 'Invalid request body' }, { status: 400 });+ }+ if (error instanceof NotFoundError) {+ return json({ error: error.message }, { status: 404 });+ }+ if (error instanceof ServiceError) {+ // Handle errors from stack-service+ return json({ error: error.message }, { status: 500 });+ }++ return json({ error: 'Failed to update stack' }, { status: 500 });+ }+};diff --git a/src/routes/stacks/[stackId]/+page.server.ts b/src/routes/stacks/[stackId]/+page.server.tsindex 0cd5405d4..60530e707 100644--- a/src/routes/stacks/[stackId]/+page.server.ts+++ b/src/routes/stacks/[stackId]/+page.server.ts@@ -7,10 +7,32 @@ export async function load({ params }) {try {const stack = await getStack(stackId);- return { stack };++ // Pre-populate the editor state values for SSR+ return {+ stack,+ error: null,+ // These will be available directly in the svelte component's data prop+ editorState: {+ name: stack.name || '',+ composeContent: stack.composeContent || '',+ originalName: stack.name || '',+ originalComposeContent: stack.composeContent || ''+ }+ };} catch (err) {+ console.error(`Error loading stack ${stackId}:`, err);const errorMessage = err instanceof Error ? err.message : String(err);- throw error(404, `Stack not found: ${errorMessage}`);+ return {+ stack: null,+ error: `Stack not found or failed to load: ${errorMessage}`,+ editorState: {+ name: '',+ composeContent: '',+ originalName: '',+ originalComposeContent: ''+ }+ };}}@@ -31,6 +53,14 @@ export const actions = {};} catch (err) {console.error('Error updating stack:', err);+ // Consider using fail() for form action errors+ // import { fail } from '@sveltejs/kit';+ // return fail(422, { // Example: Unprocessable Entity+ // name, // Return submitted values for repopulation+ // composeContent,+ // error: err instanceof Error ? err.message : 'Failed to update stack'+ // });+ // Or keep the simple return for now:return {success: false,error: err instanceof Error ? err.message : 'Failed to update stack'@@ -81,7 +111,9 @@ export const actions = {try {const success = await removeStack(params.stackId);if (success) {- return { success: true, redirectTo: '/stacks' };+ // Redirect can be handled differently, maybe client-side after success+ // Or use SvelteKit's redirect helper if needed server-side+ return { success: true, message: 'Stack removal initiated' };}return { success: false, error: 'Failed to remove stack' };} catch (err) {diff --git a/src/routes/stacks/[stackId]/+page.svelte b/src/routes/stacks/[stackId]/+page.svelteindex d7f96e624..0d4f41f35 100644--- a/src/routes/stacks/[stackId]/+page.svelte+++ b/src/routes/stacks/[stackId]/+page.svelte@@ -4,19 +4,24 @@import { Button } from '$lib/components/ui/button/index.js';import { ArrowLeft, Loader2, AlertCircle, Save, FileStack, Layers, ArrowRight } from '@lucide/svelte';import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';- import { enhance } from '$app/forms';import * as Alert from '$lib/components/ui/alert/index.js';import { Input } from '$lib/components/ui/input/index.js';import { Label } from '$lib/components/ui/label/index.js';- import YamlEditor from '$lib/components/yaml-editor.svelte';- import { onMount } from 'svelte';+ import CodeMirror from 'svelte-codemirror-editor';+ import { yaml } from '@codemirror/lang-yaml';+ import { linter, lintGutter } from '@codemirror/lint';+ import { coolGlow } from 'thememirror';+ import jsyaml from 'js-yaml';import ActionButtons from '$lib/components/action-buttons.svelte';import StatusBadge from '$lib/components/badges/status-badge.svelte';import { statusVariantMap } from '$lib/types/statuses';import { capitalizeFirstLetter } from '$lib/utils';+ import { invalidateAll } from '$app/navigation';+ import { toast } from 'svelte-sonner';+ import { enhance } from '$app/forms';let { data, form }: { data: PageData; form: ActionData } = $props();- let { stack } = $derived(data);+ let { stack, editorState } = $derived(data);let depoloying = $state(false);let stopping = $state(false);@@ -24,21 +29,12 @@let removing = $state(false);let saving = $state(false);- let name = $state('');- let composeContent = $state('');- let editorReady = $state(false);+ let name = $derived(editorState.name);+ let composeContent = $derived(editorState.composeContent);+ let originalName = $derived(editorState.originalName);+ let originalComposeContent = $derived(editorState.originalComposeContent);- $effect(() => {- if (stack) {- name = stack.name || '';- composeContent = stack.composeContent || '';-- console.log('Stack data loaded:', {- name,- composeLength: composeContent.length- });- }- });+ let hasChanges = $derived(name !== originalName || composeContent !== originalComposeContent);$effect(() => {depoloying = false;@@ -48,15 +44,64 @@saving = false;});- onMount(() => {- setTimeout(() => {- editorReady = true;- }, 100);- });+ async function handleSaveChanges() {+ if (!stack || !hasChanges) return;++ saving = true;+ console.log('Saving stack via API...');++ try {+ const response = await fetch(`/api/stacks/${stack.id}`, {+ method: 'PATCH',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({ name, composeContent })+ });++ const result = await response.json();++ if (!response.ok) {+ throw new Error(result.error || `HTTP error! status: ${response.status}`);+ }++ console.log('Stack save successful:', result);+ toast.success('Stack updated successfully!');++ originalName = name;+ originalComposeContent = composeContent;++ await invalidateAll();+ } catch (error: any) {+ console.error('Error saving stack:', error);+ toast.error(`Failed to update stack: ${error.message}`);+ } finally {+ saving = false;+ }+ }++ function yamlLinter(view: { state: { doc: { toString(): string } } }) {+ const diagnostics = [];+ try {+ jsyaml.load(view.state.doc.toString());+ } catch (e: unknown) {+ const err = e as { mark?: { position: number }; message: string };+ const start = err.mark?.position || 0;+ const end = err.mark?.position !== undefined ? Math.max(start + 1, err.mark.position + 1) : start + 1;+ diagnostics.push({+ from: start,+ to: end,+ severity: 'error' as const,+ message: err.message+ });+ }+ return diagnostics;+ }++ const lintExtension = linter(yamlLinter);</script><div class="space-y-6 pb-8">- <!-- Breadcrumb Navigation --><div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4"><div><Breadcrumb.Root>@@ -113,17 +158,15 @@{/if}</div>- <!-- Error Alert -->- {#if form?.error}+ {#if data.error}<Alert.Root variant="destructive">- <AlertCircle class="h-4 w-4 mr-2" />- <Alert.Title>Action Failed</Alert.Title>- <Alert.Description>{form.error}</Alert.Description>+ <AlertCircle class="h-4 w-4" />+ <Alert.Title>Error Loading Stack</Alert.Title>+ <Alert.Description>{data.error}</Alert.Description></Alert.Root>{/if}{#if stack}- <!-- Stack Details Section --><div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6"><Card.Root><Card.Content class="p-4 flex items-center justify-between">@@ -164,19 +207,7 @@</Card.Root></div>- <!-- Stack Editor -->- <form- method="POST"- action="?/update"- class="space-y-6"- use:enhance={() => {- saving = true;- return async ({ update }) => {- saving = false;- await update({ reset: false });- };- }}- >+ <div class="space-y-6"><Card.Root class="border shadow-sm"><Card.Header><Card.Title>Stack Configuration</Card.Title>@@ -186,15 +217,34 @@<div class="space-y-4"><div class="grid w-full max-w-sm items-center gap-1.5"><Label for="name">Stack Name</Label>- <Input type="text" id="name" name="name" bind:value={name} required />+ <Input type="text" id="name" name="name" bind:value={name} required disabled={saving} /></div><div class="grid w-full items-center gap-1.5"><Label for="compose-editor">Docker Compose File</Label>- <input type="hidden" name="composeContent" value={composeContent} />- {#key editorReady || composeContent}- <YamlEditor value={composeContent} on:change={(e) => (composeContent = e.detail.value)} height="400px" placeholder="Enter your compose.yaml content" forceDarkTheme={true} />- {/key}+ <div class="border rounded-md overflow-hidden">+ <CodeMirror+ bind:value={composeContent}+ lang={yaml()}+ theme={coolGlow}+ extensions={[lintGutter(), lintExtension]}+ styles={{+ '&': {+ height: '550px',+ fontSize: '14px',+ fontFamily: 'JetBrains Mono, Menlo, Monaco, Consolas, monospace'+ },+ '&.cm-editor[contenteditable=false]': {+ cursor: 'not-allowed'+ },+ '.cm-content[contenteditable=false]': {+ cursor: 'not-allowed'+ }+ }}+ placeholder="Enter your compose.yaml content"+ readonly={saving || depoloying || stopping || restarting || removing}+ />+ </div><p class="text-xs text-muted-foreground">Edit your <span class="font-bold">compose.yaml</span> file directly. Syntax errors will be highlighted.</p>@@ -202,23 +252,21 @@</div></Card.Content><Card.Footer class="flex justify-between">- <Button variant="outline" type="button" onclick={() => window.history.back()}>+ <Button variant="outline" type="button" onclick={() => window.history.back()} disabled={saving}><ArrowLeft class="w-4 h-4 mr-2" />Back</Button>- <Button type="submit" variant="default" disabled={saving}>+ <Button type="button" variant="default" onclick={handleSaveChanges} disabled={saving || !hasChanges}>{#if saving}- <Loader2 class="w-4 h-4 mr-2 animate-spin" />+ <Loader2 class="w-4 h-4 mr-2 animate-spin" /> Saving...{:else}- <Save class="w-4 h-4 mr-2" />+ <Save class="w-4 h-4 mr-2" /> Save Changes{/if}- Save Changes</Button></Card.Footer></Card.Root>- </form>+ </div>- <!-- Service List --><Card.Root class="border shadow-sm"><Card.Header><Card.Title>Services</Card.Title>@@ -261,7 +309,7 @@</div></Card.Content></Card.Root>- {:else}+ {:else if !data.error}<div class="flex flex-col items-center justify-center py-12 border rounded-lg shadow-sm bg-card"><div class="rounded-full bg-muted/50 p-4 mb-4"><AlertCircle class="h-8 w-8 text-muted-foreground" />