Env editorNew
A structured .env and secrets editor with multi-line .env bulk paste, automatic 8×8 Bayer secret veiling, copy-while-veiled, duplicate key checks and Prod/Prev/Dev scopes.
Used forCloud and deployment dashboardsAI agent and MCP tool credentialsWebhook and integration settingsInternal admin configuration
Install with the shadcn CLI
$ npxnpx shadcn@latest add https://hairlineui.com/r/env-editor.jsonRegistered the namespace? Then it’s shadcn add @hairline/env-editor. Set it up
Templates
Need the whole page?
63 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.
Where it’s used
Cloud and deployment dashboards
Let developers paste an entire .env file straight from their editor, assign Production/Preview/Development scopes and export cleanly.
AI agent and MCP tool credentials
Auto-veil API keys and tokens in Bayer grain while letting users copy values during screen shares without revealing them.
Webhook and integration settings
Catch duplicate variable names live and normalise stray spaces or lowercase keys to uppercase snake_case on blur.
Internal admin configuration
Reuse parseEnvText() and serializeEnvText() across forms, imports and clipboard exports.
What it handles for you
Real deployment editors have to handle messy multi-line pastes, keep credentials safe during screen shares and prevent silent duplicate keys.
- 01
Multi-line .env bulk paste
Pasting KEY=VALUE blocks into any key input strips # comments, export prefixes and quotes, preserves = inside URLs and imports all rows in one action.
- 02
Automatic Bayer secret veiling
Keys matching SECRET, KEY, TOKEN, PASSWORD or DATABASE_URL (excluding NEXT_PUBLIC_ and PUBLIC_) automatically veil behind a full-slot 1.5px 8×8 Bayer pane.
- 03
Copy while veiled with emerald sweep
Pressing Copy lifts a secret directly to the clipboard without exposing it on screen, confirming with an emerald Bayer wavefront across the veiled cell.
- 04
Key normalisation and duplicate guard
Converts spaces and hyphens to uppercase snake_case on blur and flags colliding variable names live with an amber Duplicate pill.
- 05
Optional Prod / Prev / Dev scopes
Enable showScopes to attach per-variable environment target pills (Production, Preview, Development).
- 06
Exported parser and serialiser
Exports parseEnvText(), serializeEnvText(), normalizeEnvKey() and isLikelySecretKey() alongside EnvEditor.
Overview
Entering environment variables one input at a time is tedious, and showing raw credentials or plain password dots on a deployment screen feels brittle. EnvEditor brings cloud-dashboard ergonomics into one hairline component: paste a whole multi-line .env file into any key input and it strips comments, export prefixes and surrounding quotes, keeps equals signs inside connection URLs, spawns every row cleanly and automatically classifies secret-looking keys (SECRET, KEY, TOKEN, PASSWORD, DATABASE_URL) while keeping PUBLIC_ keys readable. Veiled secrets sit behind a full-slot 1.5px 8×8 Bayer optical pane that copies straight to the clipboard even while concealed with an emerald Bayer sweep. Auto-uppercase key normalisation, live duplicate-key warnings, optional Prod/Prev/Dev scope toggles and exported parseEnvText() and serializeEnvText() helpers are built in.
States
- veiled secret
- Sensitive values sit behind a full-slot multi-tonal 1.5px 8×8 Bayer pane that reveals on click or Eye button while concealing token length.
- copy while veiled
- Copying a veiled secret writes straight to the clipboard and sweeps an emerald Bayer pulse across that cell while swapping Copy to a Check.
- bulk paste import
- Pasting multi-line .env text splits into rows, auto-veils credential keys, sweeps new cells emerald and shows an inline import summary chip.
- duplicate key
- Colliding keys highlight in amber with an inline Duplicate badge so deployment overrides are caught before save.
- reduced motion
- Bayer flash sweeps skip animation and static veiled grain stays crisp at 0% CPU.
Usage
import { EnvEditor, type EnvVar } from "@/components/env-editor";<EnvEditor value={vars} onChange={setVars} showScopes/>Depends on lucide-react, installed for you by the CLI along with the keyframes it needs.
Works with
Installs with it
- Text morphText that changes the way it should: shared letters slide over, new ones rise out of a blur, the width eases.
- Number rollNumbers that change like an odometer: every digit rolls in the direction the number moved.
- Status buttonSave, Saving, Saved: the spinner opens in, the check draws itself, errors shake, and the label morphs between them.
Project environment settings wired to bulk save and .env export
Store EnvEditor state in React and guard your Save button whenever duplicate keys exist.
"use client";import { useState } from "react";import { EnvEditor, type EnvVar } from "@/components/env-editor";export function ProjectEnvSettings({ initial, onSave }: { initial: EnvVar[]; onSave: (vars: EnvVar[]) => Promise<void> }) { const [vars, setVars] = useState<EnvVar[]>(initial); const keys = vars.map((v) => v.key.trim().toUpperCase()).filter(Boolean); const hasDuplicates = new Set(keys).size !== keys.length; return ( <div className="space-y-3"> <EnvEditor value={vars} onChange={setVars} showScopes /> <button type="button" disabled={hasDuplicates} onClick={() => void onSave(vars)} className="h-9 rounded-xl bg-primary px-4 text-xs font-medium text-primary-foreground disabled:opacity-40" > Save environment variables </button> </div> );}Props
| Prop | Type | Description |
|---|---|---|
| value / defaultValue / onChange | EnvVar[] / EnvVar[] / (v: EnvVar[]) => void | Controlled or uncontrolled array of { id, key, value, secret?, scopes? }. |
| normalizeKeys / autoDetectSecrets | boolean / boolean= true / true | Auto-uppercase keys to snake_case on blur and automatically veil secret-like keys. |
| showScopes / allowExport | boolean / boolean= false / true | Toggle per-row Prod/Prev/Dev scope pills and the header Copy .env export action. |
| label / sound | string / boolean= "Environment variables" / false | Accessible region label and opt-in Web Audio feedback cues. |
| parseEnvText / serializeEnvText / isLikelySecretKey | exported utility functions | Parse raw .env files, serialise back to .env syntax and classify secret keys outside the editor. |
- value / defaultValue / onChange
- EnvVar[] / EnvVar[] / (v: EnvVar[]) => void
- Controlled or uncontrolled array of { id, key, value, secret?, scopes? }.
- normalizeKeys / autoDetectSecrets= true / true
- boolean / boolean
- Auto-uppercase keys to snake_case on blur and automatically veil secret-like keys.
- showScopes / allowExport= false / true
- boolean / boolean
- Toggle per-row Prod/Prev/Dev scope pills and the header Copy .env export action.
- label / sound= "Environment variables" / false
- string / boolean
- Accessible region label and opt-in Web Audio feedback cues.
- parseEnvText / serializeEnvText / isLikelySecretKey
- exported utility functions
- Parse raw .env files, serialise back to .env syntax and classify secret keys outside the editor.
Accessibility and motion
- Veiled secret panes render a static 1.5px 8×8 Bayer canvas at rest (0 rAF loops / 0% CPU) and wake briefly for ~0.56s only during an import or copy-while-veiled emerald sweep.
- Keys prefixed with NEXT_PUBLIC_, VITE_, PUBLIC_, REACT_APP_ or EXPO_PUBLIC_ are never auto-classified as secrets.
- Copy .env serialises values containing spaces or # inside escaped double quotes automatically.
- Under prefers-reduced-motion: reduce, flash waves stay still while all paste parsing, veiling and copy controls work unchanged.
Requirements
React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.
The CLI also installs Text morph, Number roll, Status button.
Source
"use client";import * as React from "react";import { Check, Copy, Eye, EyeOff, Lock, Plus, Trash2, Unlock } from "lucide-react";import { EASE_OUT, INTERACTION_FOCUS, INTERACTION_PRESS, interactionIcon, useInteractionActivity, useInteractionReducedMotion,} from "./ui-interaction-motion";import { ConfirmAction } from "./confirm-action";import { NumberRoll } from "./number-roll";import { TextMorph } from "./text-morph";import { useRowMotion } from "./use-row-motion";import { playSound } from "./ui-sounds";/* ───────────────────────────────────────────────────────── * ENV EDITOR: structured .env & secrets key-value editor * * paste pasting a multi-line .env file into any key input * parses every KEY=VALUE pair (ignoring # comments, * stripping export prefixes and quotes, keeping "=" * inside URLs), spawns all rows cleanly and sweeps an * emerald 8×8 Bayer confirmation pulse across new rows * * secrets keys matching SECRET / KEY / TOKEN / PASSWORD / DSN * (and not PUBLIC_) automatically veil their values * behind a full-slot 1.5px 8×8 Bayer optical pane; * Copy lifts the value straight to clipboard even * while veiled with an emerald Bayer flash * * infra auto-uppercases keys on blur, flags duplicate keys * live, supports optional Prod/Prev/Dev scope pills * and exports parseEnvText() / serializeEnvText() * ───────────────────────────────────────────────────────── */export type EnvScope = "production" | "preview" | "development";export interface EnvVar { id: string; key: string; value: string; /** Conceal value behind the optical Bayer pane until revealed. */ secret?: boolean; /** Optional target environments (used when `showScopes` is true). */ scopes?: EnvScope[];}export interface EnvEditorProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "defaultValue" | "onChange"> { /** Controlled environment variables array. */ value?: EnvVar[]; /** Initial uncontrolled environment variables. */ defaultValue?: EnvVar[]; /** Called on every edit, bulk .env paste, add or removal. */ onChange?: (vars: EnvVar[]) => void; /** Auto-uppercase and replace spaces/hyphens with underscores on key blur (default true). */ normalizeKeys?: boolean; /** Automatically mark secret-looking keys (SECRET, KEY, TOKEN, PASSWORD, DATABASE_URL) as veiled on paste (default true). */ autoDetectSecrets?: boolean; /** Show compact environment scope toggles (Prod / Prev / Dev) per row (default false). */ showScopes?: boolean; /** Allow copying the full serialised .env file from the header (default true). */ allowExport?: boolean; /** Accessible name for the editor region (default "Environment variables"). */ label?: string; /** Opt-in quiet Web Audio cues on paste import, copy and delete (from ui-sounds.ts). */ sound?: boolean;}const ALL_SCOPES: { id: EnvScope; short: string; label: string }[] = [ { id: "production", short: "Prod", label: "Production" }, { id: "preview", short: "Prev", label: "Preview" }, { id: "development", short: "Dev", label: "Development" },];const SECRET_KEY_RE = /(SECRET|KEY|TOKEN|PASSWORD|PASSWD|PASS|PRIVATE|AUTH|SIGNING|CREDENTIAL|WEBHOOK|DATABASE_URL|DB_URL|DSN|CERT)/i;const PUBLIC_PREFIX_RE = /^(NEXT_PUBLIC_|VITE_|PUBLIC_|REACT_APP_|EXPO_PUBLIC_)/i;/** Heuristic classifying whether an env key likely holds sensitive credentials. */export function isLikelySecretKey(key: string): boolean { const k = key.trim(); if (!k || PUBLIC_PREFIX_RE.test(k)) return false; return SECRET_KEY_RE.test(k);}/** Normalise a variable name to standard POSIX uppercase snake_case (e.g. "stripe key" -> "STRIPE_KEY"). */export function normalizeEnvKey(raw: string): string { return raw .trim() .replace(/[\s-]+/g, "_") .replace(/[^A-Za-z0-9_]/g, "") .toUpperCase();}/** Parse multi-line .env text (ignoring # comments, stripping optional `export ` and outer quotes). */export function parseEnvText(raw: string, autoDetectSecrets = true): Omit<EnvVar, "id">[] { const lines = raw.replace(/\r\n/g, "\n").split("\n"); const parsed: Omit<EnvVar, "id">[] = []; for (const rawLine of lines) { const line = rawLine.trim(); if (!line || line.startsWith("#")) continue; const stripped = line.startsWith("export ") ? line.slice(7).trim() : line; const eqIdx = stripped.indexOf("="); if (eqIdx <= 0) continue; const key = normalizeEnvKey(stripped.slice(0, eqIdx)); if (!key) continue; let val = stripped.slice(eqIdx + 1).trim(); if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) { val = val.slice(1, -1); } parsed.push({ key, value: val, secret: autoDetectSecrets ? isLikelySecretKey(key) : false, scopes: ["production", "preview", "development"], }); } return parsed;}/** Serialise EnvVar entries back to clean .env syntax (quoting values containing spaces or #). */export function serializeEnvText(vars: EnvVar[]): string { return vars .filter((v) => v.key.trim().length > 0) .map((v) => { const needsQuotes = /[\s#"']/.test(v.value); const val = needsQuotes ? `"${v.value.replace(/"/g, '\\"')}"` : v.value; return `${v.key.trim()}=${val}`; }) .join("\n");}/* ── Compact 1.5px 8×8 Bayer optical veil cell for veiled secret values ── */const BAYER8: Float32Array = (() => { const m = [ [0, 32, 8, 40, 2, 34, 10, 42], [48, 16, 56, 24, 50, 18, 58, 26], [12, 44, 4, 36, 14, 46, 6, 38], [60, 28, 52, 20, 62, 30, 54, 22], [3, 35, 11, 43, 1, 33, 9, 41], [51, 19, 59, 27, 49, 17, 57, 25], [15, 47, 7, 39, 13, 45, 5, 37], [63, 31, 55, 23, 61, 29, 53, 21], ]; const out = new Float32Array(64); for (let y = 0; y < 8; y++) { for (let x = 0; x < 8; x++) { out[(y << 3) | x] = (m[y][x] + 0.5) / 64; } } return out;})();const IS_LE = (() => { const b = new ArrayBuffer(4); new Uint32Array(b)[0] = 0x0a0b0c0d; return new Uint8Array(b)[0] === 0x0d;})();function packRgba(r: number, g: number, b: number, a: number): number { const ri = r < 0 ? 0 : r > 255 ? 255 : r | 0; const gi = g < 0 ? 0 : g > 255 ? 255 : g | 0; const bi = b < 0 ? 0 : b > 255 ? 255 : b | 0; const ai = a < 0 ? 0 : a > 255 ? 255 : a | 0; return IS_LE ? ((ai << 24) | (bi << 16) | (gi << 8) | ri) >>> 0 : ((ri << 24) | (gi << 16) | (bi << 8) | ai) >>> 0;}const clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);const clamp01 = (v: number) => (Number.isFinite(v) ? clamp(v, 0, 1) : 0);const lerp = (a: number, b: number, t: number) => a + (b - a) * t;function isLightDocument(): boolean { if (typeof document === "undefined") return false; return !document.documentElement.classList.contains("dark");}function BayerSecretPane({ flashToken, active, reduced, onClick, ariaLabel,}: { flashToken: number; active: boolean; reduced: boolean; onClick: () => void; ariaLabel: string;}) { const canvasRef = React.useRef<HTMLCanvasElement>(null); const flashAgeRef = React.useRef<number>(-1); const lastFlashTokenRef = React.useRef<number>(flashToken); React.useEffect(() => { if (flashToken !== lastFlashTokenRef.current) { lastFlashTokenRef.current = flashToken; if (!reduced) flashAgeRef.current = 0; } }, [flashToken, reduced]); React.useEffect(() => { const canvas = canvasRef.current; const ctx = canvas?.getContext("2d"); if (!canvas || !ctx) return; const gridCanvas = document.createElement("canvas"); const gridCtx = gridCanvas.getContext("2d"); if (!gridCtx) return; let raf = 0; let last = 0; let gCols = 0; let gRows = 0; let gridImg: ImageData | null = null; let gridU32: Uint32Array | null = null; let w = 0; let h = 0; let dpr = 1; const draw = (dt: number): boolean => { if (w <= 0 || h <= 0) return false; const pitch = 1.5; const cols = Math.max(1, Math.ceil(w / pitch)); const rows = Math.max(1, Math.ceil(h / pitch)); if (cols !== gCols || rows !== gRows || !gridImg || !gridU32) { gCols = cols; gRows = rows; gridCanvas.width = cols; gridCanvas.height = rows; gridImg = gridCtx.createImageData(cols, rows); gridU32 = new Uint32Array(gridImg.data.buffer); } const flashing = flashAgeRef.current >= 0 && !reduced; if (flashing && dt > 0) { flashAgeRef.current += dt; if (flashAgeRef.current >= 0.56) flashAgeRef.current = -1; } const isFlash = flashAgeRef.current >= 0; const fk = isFlash ? flashAgeRef.current / 0.56 : 0; const flashFront = (1 - Math.pow(1 - fk, 2.2)) * 1.18 - 0.06; const flashFade = Math.sin(Math.PI * Math.pow(fk, 0.72)); const light = isLightDocument(); const ink: [number, number, number] = light ? [76, 84, 98] : [164, 170, 182]; const em: [number, number, number] = light ? [5, 150, 105] : [52, 211, 153]; const paneTint = light ? 10 : 11; const u32 = gridU32; u32.fill(0); for (let r = 0; r < rows; r++) { const v = (r + 0.5) / rows; const vFade = Math.min(1, Math.min(v, 1 - v) * 8); const bRow = (r & 7) << 3; const rowOff = r * cols; for (let c = 0; c < cols; c++) { const u = (c + 0.5) / cols; const uFade = Math.min(1, Math.min(u, 1 - u) * 24); const w1 = Math.sin(u * 5.2 - v * 2.1 + 0.9); const w2 = Math.cos(u * 11.4 + v * 4.2 - 0.5); let density = clamp01((0.42 + 0.18 * w1 + 0.1 * w2) * (0.7 + 0.3 * uFade * vFade)); let fBoost = 0; if (isFlash) { const df = u - flashFront; const lead = Math.exp(-(df * df) / 0.02); const tail = df < 0 ? Math.exp(df / 0.22) * 0.5 : 0; fBoost = (lead + tail) * flashFade; if (fBoost * 0.78 > density) density = fBoost * 0.78; } const bayer = BAYER8[bRow | (c & 7)]; const hit = clamp01((density - bayer + 0.055) / 0.12); if (hit <= 0.02) { u32[rowOff + c] = packRgba(ink[0], ink[1], ink[2], paneTint); continue; } const fm = clamp01(fBoost * 1.15); const cr = lerp(ink[0], em[0], fm); const cg = lerp(ink[1], em[1], fm); const cb = lerp(ink[2], em[2], fm); const alpha = hit * clamp01((light ? 0.62 : 0.7) + fm * 0.24); u32[rowOff + c] = packRgba(cr, cg, cb, alpha * 255); } } gridCtx.putImageData(gridImg, 0, 0); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, w, h); ctx.imageSmoothingEnabled = false; ctx.drawImage(gridCanvas, 0, 0, cols * pitch, rows * pitch); return flashAgeRef.current >= 0 && active && !reduced; }; const tick = (now: number) => { const dt = last ? Math.min(1 / 24, (now - last) / 1000) : 1 / 60; last = now; if (draw(dt)) raf = requestAnimationFrame(tick); else raf = 0; }; const resize = () => { const rect = canvas.getBoundingClientRect(); w = Math.round(rect.width); h = Math.round(rect.height); if (w <= 0 || h <= 0) return; dpr = Math.min(2, window.devicePixelRatio || 1); canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr); if (draw(0) && !raf) { last = 0; raf = requestAnimationFrame(tick); } }; resize(); const ro = new ResizeObserver(resize); ro.observe(canvas); const mo = new MutationObserver(() => { draw(0); }); mo.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style", "data-theme"] }); return () => { cancelAnimationFrame(raf); ro.disconnect(); mo.disconnect(); }; }, [flashToken, active, reduced]); return ( <button type="button" aria-label={ariaLabel} onClick={onClick} className={`relative block h-8 w-full cursor-pointer overflow-hidden rounded-[8px] border border-border/70 bg-background/60 transition-colors hover:border-foreground/25 ${INTERACTION_FOCUS}`} > <canvas ref={canvasRef} aria-hidden="true" className="pointer-events-none block h-full w-full" /> </button> );}let uidSeq = 1;const nextUid = () => `env-${Date.now().toString(36)}-${uidSeq++}`;export function EnvEditor({ value: controlledValue, defaultValue, onChange, normalizeKeys = true, autoDetectSecrets = true, showScopes = false, allowExport = true, label = "Environment variables", sound = false, className = "", ...props}: EnvEditorProps) { const reduced = useInteractionReducedMotion(); const { ref: rootRef, active: onScreen } = useInteractionActivity<HTMLDivElement>(); const [ownVars, setOwnVars] = React.useState<EnvVar[]>(() => defaultValue?.length ? defaultValue : [{ id: "env-initial-1", key: "", value: "", secret: false, scopes: ["production", "preview", "development"] }], ); const vars = controlledValue ?? ownVars; const [revealedIds, setRevealedIds] = React.useState<Record<string, boolean>>({}); const [flashCounts, setFlashCounts] = React.useState<Record<string, number>>({}); const [copiedId, setCopiedId] = React.useState<string | null>(null); const [copiedAll, setCopiedAll] = React.useState(false); const [importBanner, setImportBanner] = React.useState<string | null>(null); const [lastBanner, setLastBanner] = React.useState(""); const [liveStatus, setLiveStatus] = React.useState(""); if (importBanner && importBanner !== lastBanner) { setLastBanner(importBanner); } const listRef = React.useRef<HTMLDivElement | null>(null); const ghostsRef = React.useRef<HTMLDivElement | null>(null); const copyTimerRef = React.useRef(0); const allTimerRef = React.useRef(0); const bannerTimerRef = React.useRef(0); const rowRanks = React.useMemo(() => new Map(vars.map((v, i) => [v.id, i])), [vars]); useRowMotion(listRef, { reduced, ranks: rowRanks, ghosts: ghostsRef }); React.useEffect( () => () => { window.clearTimeout(copyTimerRef.current); window.clearTimeout(allTimerRef.current); window.clearTimeout(bannerTimerRef.current); }, [], ); const commitVars = React.useCallback( (next: EnvVar[]) => { if (controlledValue === undefined) setOwnVars(next); onChange?.(next); }, [controlledValue, onChange], ); const pulseRow = React.useCallback((ids: string[]) => { setFlashCounts((prev) => { const next = { ...prev }; for (const id of ids) next[id] = (next[id] ?? 0) + 1; return next; }); }, []); // Compute duplicate key map live const duplicateKeys = React.useMemo(() => { const counts = new Map<string, number>(); for (const v of vars) { const k = v.key.trim().toUpperCase(); if (k) counts.set(k, (counts.get(k) ?? 0) + 1); } const dups = new Set<string>(); counts.forEach((n, k) => { if (n > 1) dups.add(k); }); return dups; }, [vars]); const secretVars = vars.filter((v) => v.secret && v.value.length > 0); const allSecretsRevealed = secretVars.length > 0 && secretVars.every((v) => revealedIds[v.id]); // Bulk .env paste handler (the Vercel-grade signature moment!) const handleKeyPaste = (rowId: string, e: React.ClipboardEvent<HTMLInputElement>) => { const text = e.clipboardData.getData("text"); if (!text || (!text.includes("=") && !text.includes("\n"))) return; const parsed = parseEnvText(text, autoDetectSecrets); if (parsed.length === 0) return; e.preventDefault(); const targetIdx = vars.findIndex((v) => v.id === rowId); const targetRow = vars[targetIdx]; const replaceCurrent = targetRow && !targetRow.key.trim() && !targetRow.value.trim(); const newRows: EnvVar[] = parsed.map((item) => ({ ...item, id: nextUid() })); const nextList = [...vars]; if (replaceCurrent && targetIdx >= 0) { nextList.splice(targetIdx, 1, ...newRows); } else if (targetIdx >= 0) { nextList.splice(targetIdx + 1, 0, ...newRows); } else { nextList.push(...newRows); } commitVars(nextList); const newIds = newRows.map((r) => r.id); window.requestAnimationFrame(() => pulseRow(newIds)); const veiledCount = newRows.filter((r) => r.secret).length; const summary = veiledCount > 0 ? `Imported ${newRows.length} variable${newRows.length === 1 ? "" : "s"} · ${veiledCount} veiled` : `Imported ${newRows.length} variable${newRows.length === 1 ? "" : "s"}`; setImportBanner(summary); setLiveStatus(summary); if (sound) playSound("success", 0.36); window.clearTimeout(bannerTimerRef.current); bannerTimerRef.current = window.setTimeout(() => setImportBanner(null), 3200); }; const updateRow = (id: string, patch: Partial<EnvVar>) => { commitVars(vars.map((v) => (v.id === id ? { ...v, ...patch } : v))); }; const removeRow = (id: string) => { const remaining = vars.filter((v) => v.id !== id); commitVars( remaining.length > 0 ? remaining : [{ id: nextUid(), key: "", value: "", secret: false, scopes: ["production", "preview", "development"] }], ); if (sound) playSound("fold", 0.28); }; const confirmRemoveRow = async (id: string) => { if (!reduced) { await new Promise((r) => window.setTimeout(r, 220)); } removeRow(id); }; const addRow = () => { const added: EnvVar = { id: nextUid(), key: "", value: "", secret: false, scopes: ["production", "preview", "development"], }; commitVars([...vars, added]); if (sound) playSound("tick", 0.28); }; const copyRowValue = async (row: EnvVar) => { if (!row.value) return; try { await navigator.clipboard?.writeText(row.value); } catch {} setCopiedId(row.id); pulseRow([row.id]); if (sound) playSound("success", 0.34); setLiveStatus(`Copied ${row.key || "value"}`); window.clearTimeout(copyTimerRef.current); copyTimerRef.current = window.setTimeout(() => setCopiedId(null), 1600); }; const copyFullEnv = async () => { const text = serializeEnvText(vars); if (!text) return; try { await navigator.clipboard?.writeText(text); } catch {} setCopiedAll(true); if (sound) playSound("success", 0.34); setLiveStatus("Copied .env to clipboard"); window.clearTimeout(allTimerRef.current); allTimerRef.current = window.setTimeout(() => setCopiedAll(false), 1800); }; const toggleAllSecrets = () => { if (allSecretsRevealed) { setRevealedIds({}); if (sound) playSound("fold", 0.3); } else { const next: Record<string, boolean> = {}; for (const v of secretVars) next[v.id] = true; setRevealedIds(next); if (sound) playSound("unfold", 0.3); } }; const toggleScope = (row: EnvVar, scope: EnvScope) => { const cur = row.scopes ?? ["production", "preview", "development"]; const has = cur.includes(scope); const next = has ? (cur.length > 1 ? cur.filter((s) => s !== scope) : cur) : [...cur, scope]; updateRow(row.id, { scopes: next }); }; const filledCount = vars.filter((v) => v.key.trim().length > 0).length; return ( <div ref={rootRef} role="region" aria-label={label} className={`@container flex w-full flex-col overflow-hidden rounded-[16px] border border-border bg-card text-card-foreground shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)] ${className}`} {...props} > {/* Hairline header bar */} <div className="flex flex-wrap items-center justify-between gap-2 border-b border-border bg-muted/20 px-3.5 py-2.5"> <div className="flex flex-wrap items-center gap-2 text-[12px]"> <span className="inline-flex items-center gap-1 font-medium text-foreground"> <NumberRoll value={filledCount} /> <TextMorph>{filledCount === 1 ? "variable" : "variables"}</TextMorph> </span> <span aria-hidden={secretVars.length === 0 || undefined} className="grid" style={{ gridTemplateColumns: secretVars.length > 0 ? "1fr" : "0fr", opacity: secretVars.length > 0 ? 1 : 0, transition: reduced ? "none" : `grid-template-columns 340ms ${EASE_OUT}, opacity 240ms ${EASE_OUT}`, }} > <span className="min-w-0 overflow-hidden"> <span className="inline-flex w-max items-center gap-1 whitespace-nowrap text-muted-foreground"> <span>·</span> <NumberRoll value={secretVars.length} /> <TextMorph>{secretVars.length === 1 ? "secret" : "secrets"}</TextMorph> </span> </span> </span> <span aria-hidden={!importBanner || undefined} className="grid" style={{ gridTemplateColumns: importBanner ? "1fr" : "0fr", opacity: importBanner ? 1 : 0, transition: reduced ? "none" : `grid-template-columns 360ms ${EASE_OUT}, opacity 220ms ${EASE_OUT}`, }} > <span className="min-w-0 overflow-hidden"> <span className="inline-flex w-max items-center whitespace-nowrap rounded-full border border-emerald-500/30 bg-emerald-500/10 px-2 py-0.5 text-[11px] font-medium text-emerald-700 dark:text-emerald-300"> <TextMorph>{importBanner ?? lastBanner}</TextMorph> </span> </span> </span> </div> <div className="flex items-center gap-1"> {secretVars.length > 0 && ( <button type="button" onClick={toggleAllSecrets} className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] border border-border bg-background px-2 text-[11.5px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <span className="relative flex size-3.5 shrink-0 items-center justify-center"> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(!allSecretsRevealed, reduced)}> <Eye className="size-3.5" strokeWidth={1.9} /> </span> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(allSecretsRevealed, reduced)}> <EyeOff className="size-3.5" strokeWidth={1.9} /> </span> </span> <TextMorph>{allSecretsRevealed ? "Hide secrets" : "Reveal all"}</TextMorph> </button> )} {allowExport && filledCount > 0 && ( <button type="button" onClick={() => void copyFullEnv()} className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] border border-border bg-background px-2 text-[11.5px] font-medium hover:bg-accent ${ copiedAll ? "text-emerald-600 dark:text-emerald-400" : "text-muted-foreground hover:text-foreground" } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <span className="relative flex size-3.5 shrink-0 items-center justify-center"> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(!copiedAll, reduced)}> <Copy className="size-3.5" strokeWidth={1.9} /> </span> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(copiedAll, reduced)}> <Check className="size-3.5" strokeWidth={2.3} /> </span> </span> <TextMorph>{copiedAll ? "Copied .env" : "Copy .env"}</TextMorph> </button> )} </div> </div> {/* Structured key / value rows with additive FLIP glides and detached ghost fade exits */} <div className="relative"> <div ref={ghostsRef} aria-hidden="true" className="pointer-events-none absolute inset-0 overflow-hidden" /> <div ref={listRef} className="divide-y divide-border/80"> {vars.map((row) => { const isDup = row.key.trim().length > 0 && duplicateKeys.has(row.key.trim().toUpperCase()); const isVeiled = Boolean(row.secret && row.value.length > 0 && !revealedIds[row.id]); const isCopied = copiedId === row.id; const hasContent = Boolean(row.key.trim() || row.value.trim()); const activeScopes = row.scopes ?? ["production", "preview", "development"]; return ( <div key={row.id} data-row-id={row.id} data-env-row={row.key || row.id} data-veiled={isVeiled ? "true" : "false"} className="flex flex-col gap-2 bg-card px-3 py-2.5" > <div className="flex flex-col gap-2 @[480px]:flex-row @[480px]:items-center"> {/* KEY input (supports bulk multi-line .env paste!) */} <div className="relative flex min-w-0 @[480px]:w-[40%] @[480px]:shrink-0"> <input type="text" spellCheck={false} autoComplete="off" aria-label="Variable key" aria-invalid={isDup || undefined} placeholder="STRIPE_SECRET_KEY" value={row.key} onPaste={(e) => handleKeyPaste(row.id, e)} onChange={(e) => updateRow(row.id, { key: e.currentTarget.value })} onBlur={() => { if (!normalizeKeys) return; const clean = normalizeEnvKey(row.key); const autoSecret = autoDetectSecrets && clean && !row.secret && isLikelySecretKey(clean); if (clean !== row.key || autoSecret) { updateRow(row.id, { key: clean, ...(autoSecret ? { secret: true } : {}) }); } }} className={`h-8 w-full rounded-[8px] border bg-background px-2.5 font-mono text-[12.5px] tracking-[-0.01em] placeholder:text-muted-foreground/45 focus:border-foreground/30 focus:outline-none ${ isDup ? "border-amber-500/50 text-amber-700 dark:text-amber-300" : "border-border/80 text-foreground" }`} /> {isDup && ( <span className="pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 rounded-[5px] bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-300"> Duplicate </span> )} </div> {/* VALUE slot: full-width 1.5px 8×8 Bayer optical pane when veiled, crisp input when open */} <div className="relative min-w-0 flex-1"> {isVeiled ? ( <BayerSecretPane flashToken={flashCounts[row.id] ?? 0} active={onScreen} reduced={reduced} ariaLabel={`Reveal ${row.key || "secret"} value`} onClick={() => { setRevealedIds((prev) => ({ ...prev, [row.id]: true })); if (sound) playSound("unfold", 0.28); }} /> ) : ( <> <input type="text" spellCheck={false} autoComplete="off" aria-label={`Value for ${row.key || "variable"}`} placeholder="Value" value={row.value} onChange={(e) => updateRow(row.id, { value: e.currentTarget.value })} className={`h-8 w-full rounded-[8px] border border-border/80 bg-background pl-2.5 font-mono text-[12.5px] tracking-[-0.01em] text-foreground placeholder:text-muted-foreground/45 focus:border-foreground/30 focus:outline-none ${ row.secret ? "pr-8" : "pr-2.5" }`} /> {row.secret && ( <button type="button" aria-label={`Make ${row.key || "variable"} plain text`} title="Convert to plain variable" onClick={() => updateRow(row.id, { secret: false })} className={`absolute right-1 top-1/2 flex size-6 -translate-y-1/2 cursor-pointer items-center justify-center rounded-[6px] text-muted-foreground/65 hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <Lock className="size-3" strokeWidth={2} /> </button> )} </> )} </div> {/* Compact row actions: fixed 3-button rail so value columns never shift width */} <div className="flex shrink-0 items-center justify-end gap-0.5"> {row.secret ? ( <button type="button" aria-label={isVeiled ? `Reveal ${row.key || "secret"}` : `Hide ${row.key || "secret"}`} title={isVeiled ? "Reveal value" : "Hide value"} onClick={() => { setRevealedIds((prev) => ({ ...prev, [row.id]: !prev[row.id] })); if (sound) playSound(isVeiled ? "unfold" : "fold", 0.28); }} className={`relative flex size-7 cursor-pointer items-center justify-center rounded-[8px] text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(isVeiled, reduced)}> <Eye className="size-3.5" strokeWidth={1.9} /> </span> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(!isVeiled, reduced)}> <EyeOff className="size-3.5" strokeWidth={1.9} /> </span> </button> ) : ( <button type="button" aria-label={`Mark ${row.key || "variable"} as secret`} title="Veil as secret" onClick={() => { updateRow(row.id, { secret: true }); setRevealedIds((prev) => ({ ...prev, [row.id]: false })); }} className={`flex size-7 cursor-pointer items-center justify-center rounded-[8px] text-muted-foreground/75 hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <Unlock className="size-3.5" strokeWidth={1.9} /> </button> )} <button type="button" disabled={!row.value} aria-label={isCopied ? `Copied ${row.key || "value"}` : `Copy ${row.key || "value"}`} title="Copy value" onClick={() => void copyRowValue(row)} className={`relative flex size-7 cursor-pointer items-center justify-center rounded-[8px] hover:bg-accent disabled:cursor-default disabled:opacity-35 ${ isCopied ? "text-emerald-600 dark:text-emerald-400" : "text-muted-foreground hover:text-foreground" } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(!isCopied, reduced)}> <Copy className="size-3.5" strokeWidth={1.9} /> </span> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(isCopied, reduced)}> <Check className="size-3.5" strokeWidth={2.3} /> </span> </button> {hasContent ? ( <ConfirmAction icon={<Trash2 className="size-3.5" strokeWidth={1.9} />} label={`Remove ${row.key || "variable"}`} labels={{ idle: "Remove", pending: "Removing", success: "Removed" }} tone="danger" onConfirm={() => confirmRemoveRow(row.id)} /> ) : ( <button type="button" aria-label="Remove empty variable" title="Remove variable" onClick={() => removeRow(row.id)} className={`flex size-7 cursor-pointer items-center justify-center rounded-full text-muted-foreground hover:bg-accent hover:text-red-600 dark:hover:text-red-400 ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <Trash2 className="size-3.5" strokeWidth={1.9} /> </button> )} </div> </div> {/* Optional Prod / Prev / Dev environment scope chips */} {showScopes && ( <div className="flex items-center gap-1 pl-0.5"> {ALL_SCOPES.map((s) => { const on = activeScopes.includes(s.id); return ( <button key={s.id} type="button" aria-pressed={on} aria-label={`${s.label} scope for ${row.key || "variable"}`} onClick={() => toggleScope(row, s.id)} className={`inline-flex h-5 cursor-pointer items-center rounded-[6px] border px-1.5 text-[10.5px] font-medium transition-colors duration-100 ${ on ? "border-foreground/20 bg-accent text-foreground" : "border-border/70 bg-transparent text-muted-foreground/60 hover:text-foreground" } ${INTERACTION_FOCUS}`} > {s.short} </button> ); })} </div> )} </div> ); })} </div> </div> {/* Hairline footer bar */} <div className="flex flex-wrap items-center justify-between gap-2 border-t border-border bg-muted/15 px-3 py-2"> <button type="button" onClick={addRow} className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] px-2 text-[12px] font-medium text-foreground hover:bg-accent ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <Plus className="size-3.5 text-muted-foreground" strokeWidth={2.2} /> Add variable </button> <span className="text-[11.5px] text-muted-foreground">Paste a full .env block into any key</span> </div> <span className="sr-only" role="status" aria-live="polite"> {liveStatus} </span> </div> );}export default EnvEditor;Registry item: /r/env-editor.json


