"use client"; import { Button } from "@suphark/ui/components/shared/button/button"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { Input } from "@suphark/ui/components/ui/input"; import { focusAfterRemove } from "@suphark/ui/lib/focus-after-remove"; import { cn } from "@suphark/ui/lib/utils"; import { ArrowDownIcon, ArrowUpIcon, EyeIcon, EyeOffIcon, PlusIcon, XIcon } from "lucide-react"; import { type ClipboardEvent, useMemo, useRef, useState } from "react"; export interface KeyValuePair { key: string; value: string; } interface Row extends KeyValuePair { id: number; } /** แยกข้อความแบบไฟล์ .env เป็นคู่ key/value — ข้ามบรรทัดว่าง/ความเห็น, ตัด `export `, ถอดเครื่องหมายคำพูดครอบ */ export function parseKeyValueText(text: string): KeyValuePair[] { const out: KeyValuePair[] = []; for (const raw of text.split(/\r?\n/)) { const line = raw.trim(); if (!line || line.startsWith("#")) continue; const eq = line.indexOf("="); if (eq <= 0) continue; const key = line .slice(0, eq) .replace(/^export\s+/, "") .trim(); let value = line.slice(eq + 1).trim(); if ( value.length >= 2 && ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) ) { value = value.slice(1, -1); } if (key) out.push({ key, value }); } return out; } const DEFAULT_SECRET = /KEY|SECRET|TOKEN|PASSWORD|PASS|PRIVATE/i; export interface KeyValueEditorProps { value?: ReadonlyArray; defaultValue?: ReadonlyArray; onValueChange?: (pairs: KeyValuePair[]) => void; /** ส่งไปกับฟอร์มเป็น input ซ่อน: JSON `{ key: value }` (เฉพาะแถวที่มีชื่อ) */ name?: string; /** ชื่อที่ถือว่าเป็นค่าลับ (ซ่อนค่า มีปุ่มตา) — ค่าเริ่มต้น KEY/SECRET/TOKEN/PASSWORD · false = ไม่ซ่อนเลย */ secretKeys?: RegExp | false; /** ตรวจชื่อเพิ่มเติม คืนข้อความผิดพลาดหรือ null (ชื่อซ้ำตรวจให้เองอยู่แล้ว) */ validateKey?: (key: string) => string | null; /** ปุ่มเลื่อนขึ้น/ลงต่อแถว */ reorderable?: boolean; keyPlaceholder?: string; valuePlaceholder?: string; disabled?: boolean; className?: string; } /** * แก้คู่ชื่อ/ค่าหลายแถว (env vars, headers, tags, metadata) — เพิ่ม/ลบ/เรียงแถว, ตรวจชื่อซ้ำ, ซ่อนค่าลับ, * วางข้อความแบบ .env (หลายบรรทัด) ลงช่องชื่อแล้วแตกเป็นหลายแถว (ชื่อซ้ำถามก่อนว่าทับหรือข้าม) * จอแคบแต่ละแถวเป็นการ์ด ชื่ออยู่บน ค่าอยู่ล่าง · ช่อง/ปุ่ม 44px บนจอสัมผัส * * */ export function KeyValueEditor({ value, defaultValue = [], onValueChange, name, secretKeys = DEFAULT_SECRET, validateKey, reorderable = false, keyPlaceholder, valuePlaceholder, disabled = false, className, }: KeyValueEditorProps) { const text = useUiText().keyValue; const nextId = useRef(0); const withIds = (pairs: ReadonlyArray): Row[] => pairs.map((p) => ({ ...p, id: nextId.current++ })); const [innerRows, setInnerRows] = useState(() => withIds(defaultValue.length ? defaultValue : [{ key: "", value: "" }]), ); // controlled: เก็บ id ตามตำแหน่งไว้ (ไม่สร้างใหม่ทุก render = โฟกัสไม่หลุด) const controlledIds = useRef([]); const rows: Row[] = useMemo(() => { if (!value) return innerRows; return value.map((p, i) => { if (controlledIds.current[i] === undefined) controlledIds.current[i] = nextId.current++; return { ...p, id: controlledIds.current[i] as number }; }); }, [value, innerRows]); const [revealed, setRevealed] = useState>(new Set()); const [pendingPaste, setPendingPaste] = useState<{ at: number; pairs: KeyValuePair[] } | null>( null, ); const commit = (next: Row[]) => { if (!value) setInnerRows(next); else controlledIds.current = next.map((r) => r.id); onValueChange?.(next.map(({ key, value: v }) => ({ key, value: v }))); }; const update = (id: number, patch: Partial) => commit(rows.map((r) => (r.id === id ? { ...r, ...patch } : r))); const remove = (id: number) => { const next = rows.filter((r) => r.id !== id); commit(next.length ? next : [{ id: nextId.current++, key: "", value: "" }]); }; const move = (index: number, delta: number) => { const target = index + delta; if (target < 0 || target >= rows.length) return; const next = [...rows]; [next[index], next[target]] = [next[target] as Row, next[index] as Row]; commit(next); }; const errors = useMemo(() => { const firstAt = new Map(); return rows.map((r, i) => { const k = r.key.trim(); if (!k) return r.value ? (text?.keyRequired ?? "ใส่ชื่อ") : null; const custom = validateKey?.(k); if (custom) return custom; const seen = firstAt.get(k); if (seen !== undefined) { return (text?.duplicate ?? "ชื่อซ้ำกับแถวที่ {row}").replace("{row}", String(seen + 1)); } firstAt.set(k, i); return null; }); }, [rows, text, validateKey]); const applyPaste = (at: number, pairs: KeyValuePair[], overwrite: boolean) => { const next = [...rows]; const indexOf = new Map(next.map((r, i) => [r.key.trim(), i] as const)); const fresh: Row[] = []; for (const p of pairs) { const existing = indexOf.get(p.key); if (existing !== undefined && existing !== at) { if (overwrite) next[existing] = { ...(next[existing] as Row), value: p.value }; continue; } fresh.push({ ...p, id: nextId.current++ }); } // แถวที่วางอยู่ว่าง = แทนที่ด้วยแถวแรกที่วาง const target = next[at]; if (target && !target.key && !target.value && fresh.length) { next.splice(at, 1, ...fresh); } else { next.splice(at + 1, 0, ...fresh); } commit(next); setPendingPaste(null); }; const onPasteKey = (index: number, event: ClipboardEvent) => { const pasted = event.clipboardData.getData("text"); if (!pasted.includes("\n") && !pasted.includes("=")) return; const pairs = parseKeyValueText(pasted); if (pairs.length === 0) return; event.preventDefault(); const existing = new Set(rows.filter((_, i) => i !== index).map((r) => r.key.trim())); if (pairs.some((p) => existing.has(p.key))) setPendingPaste({ at: index, pairs }); else applyPaste(index, pairs, false); }; const isSecret = (key: string) => secretKeys !== false && secretKeys.test(key); const json = name ? JSON.stringify( Object.fromEntries(rows.filter((r) => r.key.trim()).map((r) => [r.key.trim(), r.value])), ) : null; const iconButton = "size-8 shrink-0 pointer-coarse:size-11"; return (
    {rows.map((row, index) => { const error = errors[index]; const secret = isSecret(row.key); const shown = !secret || revealed.has(row.id); return (
  • update(row.id, { key: e.target.value })} onPaste={(e) => onPasteKey(index, e)} /> {error &&

    {error}

    }
    update(row.id, { value: e.target.value })} />
    {secret && ( )} {reorderable && ( <> )}
  • ); })}
{pendingPaste && (
{(text?.pasteDuplicates ?? "มีชื่อที่ซ้ำกับแถวเดิม {count} รายการ").replace( "{count}", String( pendingPaste.pairs.filter((p) => rows.some((r, i) => i !== pendingPaste.at && r.key.trim() === p.key), ).length, ), )}
)} {json !== null && }
); }