Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: .env configuration support (#128)
Kyle Mendell20e12df66afc
diff --git a/docs/docs/features/stacks/overview.md b/docs/docs/features/stacks/overview.mdindex 1c1130521..d1f58b658 100644--- a/docs/docs/features/stacks/overview.md+++ b/docs/docs/features/stacks/overview.md@@ -15,9 +15,10 @@ A **Stack** is a collection of services defined in a `compose.yaml` file. For ex- **View Stacks:** See all your managed stacks and any external stacks detected on your Docker host.- **Create Stacks:** Add a new stack by giving it a name and pasting your `compose.yaml` content.+- **Edit Environment Variables:** Use the built-in `.env` editor to manage environment variables for your stack.- **Start/Stop Stacks:** Easily start or stop all services in a stack with one click.- **Restart or Redeploy:** Restart a stack or redeploy it to pull the latest images for your services.-- **Update Stacks:** Change the stack’s name or update its compose file.+- **Update Stacks:** Change the stack’s name, update its compose file, or modify its environment variables.- **Remove Stacks:** Delete a stack and its definition from Arcane.- **Import External Stacks:** Bring existing stacks (not yet managed by Arcane) under Arcane’s control.@@ -35,7 +36,21 @@ A **Stack** is a collection of services defined in a `compose.yaml` file. For ex1. Click the **Create Stack** button.2. Enter a name for your stack.3. Paste or write your `compose.yaml` content.-4. Click **Create**. Arcane will save your stack and try to start it.+4. (Optional) Use the **Environment Configuration (.env)** editor to define environment variables for your stack.+ These variables will be saved in a `.env` file alongside your compose file.+5. Click **Create**. Arcane will save your stack and try to start it.++> **Note:**+> To use environment variables from your `.env` file in your services, you must still reference the file in your `compose.yaml` using the `env_file` property.+> Example:+>+> ```yaml+> services:+> web:+> image: nginx+> env_file:+> - .env+> ```### Controlling a Stack@@ -46,7 +61,7 @@ A **Stack** is a collection of services defined in a `compose.yaml` file. For ex### Updating or Removing a Stack-- To update, open the stack and click **Edit**. Change the name or compose file, then save.+- To update, open the stack and click **Edit**. Change the name, compose file, or environment variables, then save.- To remove, click the **Remove** button. Confirm the action to delete the stack from Arcane.### Importing External Stacks@@ -57,5 +72,5 @@ If Arcane detects a stack running on your Docker host that it doesn’t manage y## Where Are My Stacks Stored?-Arcane saves your stack definitions (compose files and metadata) in its data directory (by default `/app/data/stacks`).+Arcane saves your stack definitions (compose files, `.env` files, and metadata) in its data directory (by default `/app/data/stacks`).**Tip:** To keep your stacks safe, make sure to mount this directory as a Docker volume if you’re running Arcane in a container.diff --git a/package-lock.json b/package-lock.jsonindex 0383f56ce..54b6b525b 100644--- a/package-lock.json+++ b/package-lock.json@@ -9,6 +9,7 @@"version": "0.5.0","dependencies": {"@codemirror/lang-yaml": "^6.1.2",+ "@codemirror/legacy-modes": "^6.5.1","@tanstack/table-core": "^8.21.3","axios": "^1.9.0","bcryptjs": "^3.0.2",@@ -161,6 +162,15 @@"style-mod": "^4.0.0"}},+ "node_modules/@codemirror/legacy-modes": {+ "version": "6.5.1",+ "resolved": "https://registry.npmjs.org/@codemirror/legacy-modes/-/legacy-modes-6.5.1.tgz",+ "integrity": "sha512-DJYQQ00N1/KdESpZV7jg9hafof/iBNp9h7TYo1SLMk86TWl9uDsVdho2dzd81K+v4retmK6mdC7WpuOQDytQqw==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/language": "^6.0.0"+ }+ },"node_modules/@codemirror/lint": {"version": "6.8.5","resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.8.5.tgz",diff --git a/package.json b/package.jsonindex c9177b7ff..7960427f5 100644--- a/package.json+++ b/package.json@@ -54,6 +54,7 @@},"dependencies": {"@codemirror/lang-yaml": "^6.1.2",+ "@codemirror/legacy-modes": "^6.5.1","@tanstack/table-core": "^8.21.3","axios": "^1.9.0","bcryptjs": "^3.0.2",diff --git a/src/lib/components/badges/name-cell.svelte b/src/lib/components/badges/name-cell.sveltedeleted file mode 100644index 26aeda6e9..000000000--- a/src/lib/components/badges/name-cell.svelte+++ /dev/null@@ -1,20 +0,0 @@-<script lang="ts">- interface Props {- name: string;- link?: string;- }-- let { name, link }: Props = $props();-</script>--<div class="flex items-center gap-2">- {#if link}- <span class="truncate">- <a class="font-medium hover:underline" href={link}>- {name}- </a>- </span>- {:else}- <span class="truncate">{name}</span>- {/if}-</div>diff --git a/src/lib/components/badges/unused-text-badge.svelte b/src/lib/components/badges/unused-text-badge.svelteindex 049f70670..7c414ff67 100644--- a/src/lib/components/badges/unused-text-badge.svelte+++ b/src/lib/components/badges/unused-text-badge.svelte@@ -1,6 +1,5 @@<script lang="ts">import StatusBadge from './status-badge.svelte';- import NameCell from './name-cell.svelte';interface Props {name: string;@@ -12,7 +11,15 @@</script><div class="flex items-center gap-2">- <NameCell {name} {link} />+ {#if link}+ <span class="truncate">+ <a class="font-medium hover:underline" href={link}>+ {name}+ </a>+ </span>+ {:else}+ <span class="truncate">{name}</span>+ {/if}{#if !inUse}<StatusBadge text="Unused" variant="amber" />{/if}diff --git a/src/lib/components/env-editor.svelte b/src/lib/components/env-editor.sveltenew file mode 100644index 000000000..8e33c45de--- /dev/null+++ b/src/lib/components/env-editor.svelte@@ -0,0 +1,38 @@+<script lang="ts">+ import CodeMirror from 'svelte-codemirror-editor';+ import { browser } from '$app/environment';+ import { coolGlow } from 'thememirror';+ import { StreamLanguage } from '@codemirror/language';+ import { properties } from '@codemirror/legacy-modes/mode/properties';++ let { value = $bindable(''), placeholder = '# Add environment variables here', readOnly = false } = $props();+</script>++{#if browser}+ <div class="border rounded-md overflow-hidden">+ <CodeMirror+ bind:value+ theme={coolGlow}+ extensions={[StreamLanguage.define(properties)]}+ 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'+ },+ '.cm-line': {+ padding: '2px 4px'+ }+ }}+ {placeholder}+ readonly={readOnly}+ nodebounce={true}+ />+ </div>+{/if}diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex 9daa38fc4..2ecb03de1 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -5,3 +5,34 @@ export const isDev = dev;// For test environment, we can use a safer approachexport const isTest = false; // Default for browser++export const defaultEnvTemplate = `# Environment Variables+# These variables will be available to your stack services+# Format: VARIABLE_NAME=value++NGINX_HOST=localhost+NGINX_PORT=80++# Example Database Configuration+# DB_USER=myuser+# DB_PASSWORD=mypassword+# DB_NAME=mydatabase+`;++export const defaultComposeTemplate = `+services:+ nginx:+ image: nginx:alpine+ container_name: nginx_service+ env_file:+ - .env+ ports:+ - "8080:80"+ volumes:+ - nginx_data:/usr/share/nginx/html+ restart: unless-stopped++volumes:+ nginx_data:+ driver: local+`;diff --git a/src/lib/services/api/stack-api-service.ts b/src/lib/services/api/stack-api-service.tsindex e773032b8..6481624c5 100644--- a/src/lib/services/api/stack-api-service.ts+++ b/src/lib/services/api/stack-api-service.ts@@ -39,19 +39,21 @@ export default class StackAPIService extends BaseAPIService {return res.data;}- async save(stackId: string, name: string, composeContent: string, autoUpdate: boolean) {- const res = await this.api.put(`/stacks/${stackId}`, {+ async save(id: string, name: string, content: string, autoUpdate: boolean, envContent?: string) {+ const res = await this.api.put(`/stacks/${id}`, {name,- composeContent,- autoUpdate+ composeContent: content,+ autoUpdate,+ envContent});return res.data;}- async create(name: string, content: string) {+ async create(name: string, content: string, envContent?: string) {const res = await this.api.post('/stacks/create', {name,- composeContent: content+ composeContent: content,+ envContent: envContent || ''});return res.data;}diff --git a/src/lib/services/docker/stack-service.ts b/src/lib/services/docker/stack-service.tsindex 8d77aa4dd..101db60c1 100644--- a/src/lib/services/docker/stack-service.ts+++ b/src/lib/services/docker/stack-service.ts@@ -109,6 +109,49 @@ async function getStackMetaPath(stackId: string): Promise<string> {return join(stackDir, 'meta.json');}+/**+ * Gets the path to the .env file for a specific stack+ */+async function getEnvFilePath(stackId: string): Promise<string> {+ const stackDir = await getStackDir(stackId);+ return join(stackDir, '.env');+}++/**+ * Saves environment variables to a .env file in the stack directory+ * Handles empty content gracefully+ */+async function saveEnvFile(stackId: string, content?: string): Promise<void> {+ const envPath = await getEnvFilePath(stackId);++ // Create a new local variable instead of reassigning the parameter+ const fileContent = content === undefined || content === null ? '' : content;++ await fs.writeFile(envPath, fileContent, 'utf8');+ console.log(`Saved .env file for stack ${stackId}`);+}++/**+ * Loads environment variables from a .env file in the stack directory+ * Returns empty string if the file doesn't exist+ */+async function loadEnvFile(stackId: string): Promise<string> {+ const envPath = await getEnvFilePath(stackId);++ try {+ return await fs.readFile(envPath, 'utf8');+ } catch (err) {+ const nodeErr = err as NodeJS.ErrnoException;+ // Return empty string if file doesn't exist+ if (nodeErr.code === 'ENOENT') {+ console.log(`No .env file found for stack ${stackId}`);+ return '';+ }+ console.error(`Error reading .env file for stack ${stackId}:`, err);+ throw new Error(`Failed to read .env file: ${nodeErr.message}`, { cause: err });+ }+}+/*** The function `getComposeInstance` returns a new instance of `DockerodeCompose` using a Docker* client, compose file path, and stack ID.@@ -318,73 +361,9 @@ export async function loadComposeStacks(): Promise<Stack[]> {}/**- * This TypeScript function retrieves information about a stack, including its services and status,- * based on the provided stack ID.- * @param {string} stackId - The `stackId` parameter is a string that represents the unique identifier- * of a stack. It is used to retrieve information about a specific stack, such as its metadata,- * services, status, and content.- * @returns The `getStack` function returns a Promise that resolves to an object of type `Stack`. The- * `Stack` object contains properties such as `id`, `name`, `services`, `serviceCount`, `runningCount`,- * `status`, `createdAt`, `updatedAt`, and `composeContent`. These properties hold information about a- * specific stack identified by `stackId`.- */-export async function getStack(stackId: string): Promise<Stack> {- try {- const metaPath = await getStackMetaPath(stackId);- const composePath = await getComposeFilePath(stackId);-- const [metaContent, composeContent] = await Promise.all([fs.readFile(metaPath, 'utf8'), fs.readFile(composePath, 'utf8')]);-- const meta = JSON.parse(metaContent) as StackMeta;-- const services = await getStackServices(stackId, composeContent);-- const serviceCount = services.length;- const runningCount = services.filter((s) => s.state?.Running).length;-- let status: Stack['status'] = 'stopped';- if (runningCount === serviceCount && serviceCount > 0) {- status = 'running';- } else if (runningCount > 0) {- status = 'partially running';- }-- return {- id: stackId,- name: meta.name,- services,- serviceCount,- runningCount,- status,- createdAt: meta.createdAt,- updatedAt: meta.updatedAt,- composeContent,- meta- };- } catch (err) {- console.error(`Error getting stack ${stackId}:`, err);- throw new Error(`Stack not found or cannot be accessed`);- }-}--/**- * The function `createStack` creates a new stack with a unique ID, saves the stack's metadata and- * Docker Compose file to disk, and returns information about the created stack.- * @param {string} name - The `name` parameter is a string that represents the name of the stack being- * created. It is used to identify the stack and is included in the metadata of the stack.- * @param {string} composeContent - The `composeContent` parameter in the `createStack` function is a- * string that represents the content of a Docker Compose file. This file defines the services,- * networks, and volumes for a Docker application. It is used to configure and run multiple Docker- * containers as a single application.- * @returns The `createStack` function returns a Promise that resolves to a `Stack` object with the- * following properties:- * - `id`: The unique identifier of the stack- * - `name`: The name of the stack- * - `serviceCount`: The number of services defined in the Docker Compose file- * - `runningCount`: The number of services currently running- * - `status`: The status of the+ * Creates a new stack with a compose file and optional .env file*/-export async function createStack(name: string, composeContent: string): Promise<Stack> {+export async function createStack(name: string, composeContent: string, envContent?: string): Promise<Stack> {const stackId = nanoid();const stackDir = await getStackDir(stackId);const composePath = join(stackDir, 'docker-compose.yml');@@ -398,7 +377,9 @@ export async function createStack(name: string, composeContent: string): Promisetry {await fs.mkdir(stackDir, { recursive: true });- await Promise.all([fs.writeFile(composePath, composeContent, 'utf8'), fs.writeFile(metaPath, JSON.stringify(meta, null, 2), 'utf8')]);++ // Write all files in parallel+ await Promise.all([fs.writeFile(composePath, composeContent, 'utf8'), fs.writeFile(metaPath, JSON.stringify(meta, null, 2), 'utf8'), saveEnvFile(stackId, envContent)]);let serviceCount = 0;try {@@ -418,7 +399,8 @@ export async function createStack(name: string, composeContent: string): Promisestatus: 'stopped',createdAt: meta.createdAt,updatedAt: meta.updatedAt,- composeContent: composeContent+ composeContent: composeContent,+ envContent: envContent || ''};} catch (err) {console.error('Error creating stack:', err);@@ -432,19 +414,49 @@ export async function createStack(name: string, composeContent: string): Promise}/**- * The function `updateStack` updates a stack's metadata and compose file, calculates the status of the- * stack based on its services, and returns the updated stack information.- * @param {string} stackId - The `stackId` parameter is a string that represents the unique identifier- * of the stack that you want to update.- * @param {StackUpdate} updates - The `updates` parameter in the `updateStack` function is an object- * that contains the changes you want to apply to the stack. It can have the following properties:- * @returns The `updateStack` function returns a Promise that resolves to a `Stack` object with the- * following properties:- * - `id`: The ID of the stack- * - `name`: The updated name of the stack- * - `serviceCount`: The total number of services in the stack- * - `runningCount`: The number of services currently running in the stack- * - `status`: The status of the+ * Gets information about a specific stack including its .env file+ */+export async function getStack(stackId: string): Promise<Stack> {+ try {+ const metaPath = await getStackMetaPath(stackId);+ const composePath = await getComposeFilePath(stackId);++ const [metaContent, composeContent, envContent] = await Promise.all([fs.readFile(metaPath, 'utf8'), fs.readFile(composePath, 'utf8'), loadEnvFile(stackId)]);++ const meta = JSON.parse(metaContent) as StackMeta;+ const services = await getStackServices(stackId, composeContent);++ const serviceCount = services.length;+ const runningCount = services.filter((s) => s.state?.Running).length;++ let status: Stack['status'] = 'stopped';+ if (runningCount === serviceCount && serviceCount > 0) {+ status = 'running';+ } else if (runningCount > 0) {+ status = 'partially running';+ }++ return {+ id: stackId,+ name: meta.name,+ services,+ serviceCount,+ runningCount,+ status,+ createdAt: meta.createdAt,+ updatedAt: meta.updatedAt,+ composeContent,+ envContent,+ meta+ };+ } catch (err) {+ console.error(`Error getting stack ${stackId}:`, err);+ throw new Error(`Stack not found or cannot be accessed`);+ }+}++/**+ * Updates a stack with new configuration and/or .env file*/export async function updateStack(stackId: string, updates: StackUpdate): Promise<Stack> {const metaPath = await getStackMetaPath(stackId);@@ -458,7 +470,6 @@ export async function updateStack(stackId: string, updates: StackUpdate): Promis...meta,name: updates.name || meta.name,updatedAt: new Date().toISOString(),- // Add auto-update flag if provided...(updates.autoUpdate !== undefined ? { autoUpdate: updates.autoUpdate } : {})};@@ -468,9 +479,15 @@ export async function updateStack(stackId: string, updates: StackUpdate): Promispromises.push(fs.writeFile(composePath, updates.composeContent, 'utf8'));}+ if (updates.envContent !== undefined) {+ promises.push(saveEnvFile(stackId, updates.envContent));+ }+await Promise.all(promises);const composeContent = updates.composeContent || (await fs.readFile(composePath, 'utf8'));+ const envContent = updates.envContent !== undefined ? updates.envContent : await loadEnvFile(stackId);+const services = await getStackServices(stackId, composeContent);const serviceCount = services.length;@@ -490,7 +507,9 @@ export async function updateStack(stackId: string, updates: StackUpdate): PromisrunningCount,status,createdAt: updatedMeta.createdAt,- updatedAt: updatedMeta.updatedAt+ updatedAt: updatedMeta.updatedAt,+ composeContent,+ envContent};} catch (err) {console.error(`Error updating stack ${stackId}:`, err);diff --git a/src/lib/types/docker/stack.type.ts b/src/lib/types/docker/stack.type.tsindex 69f58c065..e54d24e5c 100644--- a/src/lib/types/docker/stack.type.ts+++ b/src/lib/types/docker/stack.type.ts@@ -26,6 +26,7 @@ export interface Stack {createdAt: string;updatedAt: string;composeContent?: string;+ envContent?: string;isExternal?: boolean;compose?: any;meta?: StackMeta;@@ -34,5 +35,6 @@ export interface Stack {export interface StackUpdate {name?: string;composeContent?: string;+ envContent?: string;autoUpdate?: boolean;}diff --git a/src/routes/api/stacks/[stackId]/+server.ts b/src/routes/api/stacks/[stackId]/+server.tsindex be3d34f71..465de0819 100644--- a/src/routes/api/stacks/[stackId]/+server.ts+++ b/src/routes/api/stacks/[stackId]/+server.ts@@ -4,11 +4,11 @@ import { updateStack } from '$lib/services/docker/stack-service';export const PUT: RequestHandler = async ({ params, request }) => {const { stackId } = params;- const { name, composeContent, autoUpdate } = await request.json();+ const { name, composeContent, autoUpdate, envContent } = await request.json();try {// From your API endpoint- await updateStack(stackId, { name, composeContent, autoUpdate });+ await updateStack(stackId, { name, composeContent, autoUpdate, envContent });return json({ success: true, message: 'Stack updated successfully' });} catch (error: any) {console.error('Error updating stack:', error);diff --git a/src/routes/api/stacks/create/+server.ts b/src/routes/api/stacks/create/+server.tsindex 23fe2946e..ed8b20463 100644--- a/src/routes/api/stacks/create/+server.ts+++ b/src/routes/api/stacks/create/+server.ts@@ -7,6 +7,7 @@ export const POST: RequestHandler = async ({ request }) => {const body = await request.json();const name = body.name?.toString();const composeContent = body.composeContent?.toString();+ const envContent = body.envContent?.toString();if (!name) {throw error(502, 'Stack name is required');@@ -16,7 +17,7 @@ export const POST: RequestHandler = async ({ request }) => {throw error(503, 'Compose file content is required');}- const newStack = await createStack(name, composeContent);+ const newStack = await createStack(name, composeContent, envContent);return json({success: true,diff --git a/src/routes/stacks/+page.svelte b/src/routes/stacks/+page.svelteindex e9de1527d..ef90a78aa 100644--- a/src/routes/stacks/+page.svelte+++ b/src/routes/stacks/+page.svelte@@ -21,7 +21,6 @@let { data }: { data: PageData } = $props();let stacks = $state(data.stacks);let selectedIds = $state([]);- let isRefreshing = $state(false);let isLoading = $state({start: false,stop: false,diff --git a/src/routes/stacks/ImportExternalStack.svelte b/src/routes/stacks/ImportExternalStack.sveltedeleted file mode 100644index 394e32766..000000000--- a/src/routes/stacks/ImportExternalStack.svelte+++ /dev/null@@ -1,35 +0,0 @@-<script lang="ts">- import { Button } from '$lib/components/ui/button/index.js';- import { enhance } from '$app/forms';- import { Import, Loader2 } from '@lucide/svelte';- import { invalidateAll } from '$app/navigation';-- const { id, name, isExternal } = $props<{ id: string; name: string; isExternal: boolean }>();- let stack = $derived({ id, name, isExternal });-- let importing = $state(false);-</script>--{#if stack.isExternal}- <form- method="POST"- action="/stacks/import"- use:enhance={() => {- importing = true;- return async () => {- await invalidateAll();- importing = false;- };- }}- >- <input type="hidden" name="stackId" value={stack.id} />- <Button size="sm" variant="outline" title="Import to Arcane" disabled={importing} type="submit">- {#if importing}- <Loader2 class="h-4 w-4 mr-2 animate-spin" />- {:else}- <Import class="h-4 w-4 mr-2" />- {/if}- Import- </Button>- </form>-{/if}diff --git a/src/routes/stacks/[stackId]/+page.server.ts b/src/routes/stacks/[stackId]/+page.server.tsindex b78ddfd47..3fd08e1a9 100644--- a/src/routes/stacks/[stackId]/+page.server.ts+++ b/src/routes/stacks/[stackId]/+page.server.ts@@ -7,16 +7,20 @@ export const load: PageServerLoad = async ({ params }) => {try {const stack = await getStack(stackId);+ // Create editor state with all current values+ const editorState = {+ name: stack.name,+ composeContent: stack.composeContent || '',+ envContent: stack.envContent || '', // Include env content+ autoUpdate: stack.meta?.autoUpdate || false,+ originalName: stack.name,+ originalComposeContent: stack.composeContent || '',+ originalEnvContent: stack.envContent || '' // Include original env content+ };+return {stack,- error: null,- editorState: {- name: stack.name || '',- composeContent: stack.composeContent || '',- originalName: stack.name || '',- originalComposeContent: stack.composeContent || '',- autoUpdate: stack.meta?.autoUpdate || false- }+ editorState};} catch (err: unknown) {console.error(`Error loading stack ${stackId}:`, err);@@ -27,8 +31,10 @@ export const load: PageServerLoad = async ({ params }) => {editorState: {name: '',composeContent: '',+ envContent: '', // Include env contentoriginalName: '',originalComposeContent: '',+ originalEnvContent: '', // Include original env contentautoUpdate: false}};diff --git a/src/routes/stacks/[stackId]/+page.svelte b/src/routes/stacks/[stackId]/+page.svelteindex 1ce1aa835..c979e809b 100644--- a/src/routes/stacks/[stackId]/+page.svelte+++ b/src/routes/stacks/[stackId]/+page.svelte@@ -14,6 +14,7 @@import { invalidateAll } from '$app/navigation';import { toast } from 'svelte-sonner';import YamlEditor from '$lib/components/yaml-editor.svelte';+ import EnvEditor from '$lib/components/env-editor.svelte';import { Switch } from '$lib/components/ui/switch/index.js';import { tryCatch } from '$lib/utils/try-catch';import StackAPIService from '$lib/services/api/stack-api-service';@@ -24,39 +25,48 @@let { data }: { data: PageData } = $props();let { stack, editorState } = $derived(data);- let deploying = $state(false);- let stopping = $state(false);- let restarting = $state(false);- let removing = $state(false);- let saving = $state(false);+ let isLoading = $state({+ deploying: false,+ stopping: false,+ restarting: false,+ removing: false,+ importing: false,+ redeploying: false,+ destroying: false,+ pulling: false,+ saving: false+ });let name = $derived(editorState.name);let composeContent = $derived(editorState.composeContent);+ let envContent = $derived(editorState.envContent || '');let autoUpdate = $derived(editorState.autoUpdate);let originalName = $derived(editorState.originalName);let originalComposeContent = $derived(editorState.originalComposeContent);+ let originalEnvContent = $derived(editorState.originalEnvContent || '');let originalAutoUpdate = $derived(editorState.autoUpdate);- let hasChanges = $derived(name !== originalName || composeContent !== originalComposeContent || autoUpdate !== originalAutoUpdate);+ let hasChanges = $derived(name !== originalName || composeContent !== originalComposeContent || envContent !== originalEnvContent || autoUpdate !== originalAutoUpdate);$effect(() => {- deploying = false;- stopping = false;- restarting = false;- removing = false;- saving = false;+ isLoading.deploying = false;+ isLoading.stopping = false;+ isLoading.restarting = false;+ isLoading.removing = false;+ isLoading.saving = false;});async function handleSaveChanges() {if (!stack || !hasChanges) return;handleApiReponse(- await tryCatch(stackApi.save(stack.id, name, composeContent, autoUpdate)),+ await tryCatch(stackApi.save(stack.id, name, composeContent, autoUpdate, envContent)),'Failed to Save Stack',- (value) => (saving = value),+ (value) => (isLoading.saving = value),async (data) => {originalName = name;originalComposeContent = composeContent;+ originalEnvContent = envContent;originalAutoUpdate = autoUpdate;console.log('Stack save successful:', data);@@ -102,10 +112,10 @@type="stack"itemState={stack.status}loading={{- start: deploying,- stop: stopping,- restart: restarting,- remove: removing+ start: isLoading.deploying,+ stop: isLoading.stopping,+ restart: isLoading.restarting,+ remove: isLoading.removing}}/></div>@@ -165,23 +175,34 @@<Card.Root class="border shadow-sm"><Card.Header><Card.Title>Stack Configuration</Card.Title>- <Card.Description>Edit stack settings and compose file</Card.Description>+ <Card.Description>Edit stack settings, compose file, and environment variables</Card.Description></Card.Header><Card.Content><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 disabled={saving} />+ <Input type="text" id="name" name="name" bind:value={name} required disabled={isLoading.saving} /></div>- <div class="grid w-full items-center gap-1.5">- <Label for="compose-editor">Docker Compose File</Label>- <div class="border rounded-md overflow-hidden">- <YamlEditor bind:value={composeContent} readOnly={saving || deploying || stopping || restarting || removing} />+ <div class="grid grid-cols-1 md:grid-cols-3 gap-4">+ <div class="md:col-span-2 space-y-2">+ <Label for="compose-editor" class="mb-2">Docker Compose File</Label>+ <div class="border rounded-md overflow-hidden h-[550px] mt-2">+ <YamlEditor bind:value={composeContent} readOnly={isLoading.saving || isLoading.deploying || isLoading.stopping || isLoading.restarting || isLoading.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>+ </div>++ <div class="space-y-2">+ <Label for="env-editor" class="mb-2">Environment Configuration (.env)</Label>++ <div class="border rounded-md overflow-hidden h-[550px] mt-2">+ <EnvEditor bind:value={envContent} readOnly={isLoading.saving || isLoading.deploying || isLoading.stopping || isLoading.restarting || isLoading.removing} />+ </div>+ <p class="text-xs text-muted-foreground">Define environment variables in KEY=value format. These will be saved as a .env file in the stack directory.</p></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></div><div class="flex items-center space-x-2 mt-4">@@ -194,12 +215,12 @@</div></Card.Content><Card.Footer class="flex justify-between">- <Button variant="outline" type="button" onclick={() => window.history.back()} disabled={saving}>+ <Button variant="outline" type="button" onclick={() => window.history.back()} disabled={isLoading.saving}><ArrowLeft class="w-4 h-4 mr-2" />Back</Button>- <Button type="button" variant="default" onclick={handleSaveChanges} disabled={saving || !hasChanges}>- {#if saving}+ <Button type="button" variant="default" onclick={handleSaveChanges} disabled={isLoading.saving || !hasChanges}>+ {#if isLoading.saving}<Loader2 class="w-4 h-4 mr-2 animate-spin" /> Saving...{:else}<Save class="w-4 h-4 mr-2" /> Save Changesdiff --git a/src/routes/stacks/new/+page.svelte b/src/routes/stacks/new/+page.svelteindex 0c746659e..b252517c7 100644--- a/src/routes/stacks/new/+page.svelte+++ b/src/routes/stacks/new/+page.svelte@@ -12,37 +12,25 @@import { preventDefault } from '$lib/utils/form.utils';import { tryCatch } from '$lib/utils/try-catch';import { handleApiReponse } from '$lib/utils/api.util';+ import EnvEditor from '$lib/components/env-editor.svelte';+ import { defaultEnvTemplate, defaultComposeTemplate } from '$lib/constants';const stackApi = new StackAPIService();let saving = $state(false);- const defaultComposeTemplate = `services:- nginx:- image: nginx:alpine- container_name: nginx_service- ports:- - "8080:80"- volumes:- - nginx_data:/usr/share/nginx/html- restart: unless-stopped--volumes:- nginx_data:- driver: local-`;-let name = $state('');let composeContent = $state(defaultComposeTemplate);+ let envContent = $state(defaultEnvTemplate);async function handleSubmit() {saving = true;handleApiReponse(- await tryCatch(stackApi.create(name, composeContent)),+ await tryCatch(stackApi.create(name, composeContent, envContent)),'Failed to Create Stack',(value) => (saving = value),async (data) => {- toast.success(`Stack "${data.stack.name}" created.`);+ toast.success(`Stack "${data.stack.name}" created with environment file.`);await invalidateAll();goto(`/stacks/${data.stack.id}`);}@@ -82,7 +70,7 @@ volumes:</div><div><Card.Title>Stack Configuration</Card.Title>- <Card.Description>Create a new Docker Compose stack</Card.Description>+ <Card.Description>Create a new Docker Compose stack with environment variables</Card.Description></div></div></Card.Header>@@ -93,12 +81,23 @@ volumes:<Input type="text" id="name" name="name" bind:value={name} required placeholder="e.g., my-web-app" disabled={saving} /></div>- <div class="grid w-full items-center gap-1.5">- <Label for="compose-editor">Docker Compose File</Label>+ <div class="grid grid-cols-1 md:grid-cols-3 gap-4">+ <div class="md:col-span-2 space-y-2">+ <Label for="compose-editor" class="mb-2">Docker Compose File</Label>+ <div class="border rounded-md overflow-hidden h-[550px] mt-2">+ <YamlEditor bind:value={composeContent} readOnly={saving} />+ </div>+ <p class="text-xs text-muted-foreground">Enter a valid compose.yaml file.</p>+ </div>- <YamlEditor bind:value={composeContent} readOnly={saving} />+ <div class="space-y-2">+ <Label for="env-editor" class="mb-2">Environment Configuration (.env)</Label>- <p class="text-xs text-muted-foreground">Enter a valid compose.yaml file.</p>+ <div class="border rounded-md overflow-hidden h-[550px] mt-2">+ <EnvEditor bind:value={envContent} readOnly={saving} />+ </div>+ <p class="text-xs text-muted-foreground">Define environment variables in KEY=value format. These will be saved as a .env file in the stack directory.</p>+ </div></div></div></Card.Content>