import { useState, useEffect, useCallback, useMemo } from 'react'; import InfoTip from '@/components/InfoTip'; import { ArrowLeft, Boxes, Plus, Trash2 } from 'lucide-react'; import api from '../../services/api'; import { useToast } from '../../contexts/useToast.js'; import { Button } from '@/components/ui/button'; import PagePrimaryButton from '@/components/PagePrimaryButton'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Checkbox } from '@/components/ui/checkbox'; import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select'; import Modal from '@/components/Modal'; import ResourceListPage from '../layouts/ResourceListPage'; import { useTopbarActions } from '@/hooks/useTopbarActions'; import { SearchField, Pill, ServiceTile } from '@/components/ds'; import { useConfirm } from '@/hooks/useConfirm'; import { useTranslation } from 'react-i18next'; import { toastError } from '@/utils/errorMessage'; const RESOURCE_TYPES = ['application', 'database', 'service', 'wordpress', 'server']; // Preset views. "Unattached" is the one that earns its place: a group nothing // is attached to is a group whose variables reach nothing, which is almost // always a mistake rather than a choice. const GROUP_VIEWS = [ { name: 'All groups', state: { search: '', sorts: [], hiddenKeys: [], columnFilters: null } }, { name: 'Unattached', state: { search: '', sorts: [], hiddenKeys: [], columnFilters: { match: 'all', rules: [{ id: 'sg1', field: 'attachments', op: 'eq', value: 0 }] }, }, }, ]; /** * Manage shared variable groups for a given scope: create groups, add/remove * variables (secrets masked), and attach/detach a group to resources. * * Two depths on the same surface, matching every other list page: a table of * groups, and — once you pick one — a table of that group's variables. It used * to be a fixed sidebar of groups beside a detail pane, which meant the group * list alone could not be searched, sorted, filtered or saved as a view the way * every other list in the panel can. * * Props: * scopeType 'workspace' | 'project' | 'environment' (default 'workspace') * scopeId the scope identifier (string) (default 'default') */ const SharedVariableGroups = ({ scopeType = 'workspace', scopeId = 'default' }) => { const { t } = useTranslation(); const toast = useToast(); const { confirm } = useConfirm(); const [groups, setGroups] = useState([]); const [loading, setLoading] = useState(true); const [selectedId, setSelectedId] = useState(null); const [detail, setDetail] = useState(null); // create-group form const [creating, setCreating] = useState(false); const [newName, setNewName] = useState(''); const [newDescription, setNewDescription] = useState(''); const [search, setSearch] = useState(''); // add-variable form const [varKey, setVarKey] = useState(''); const [varValue, setVarValue] = useState(''); const [varSecret, setVarSecret] = useState(false); const [varTarget, setVarTarget] = useState(''); // attach form const [attachType, setAttachType] = useState(RESOURCE_TYPES[0]); const [attachId, setAttachId] = useState(''); const [loadError, setLoadError] = useState(null); const loadGroups = useCallback(async () => { try { setLoading(true); const data = await api.listVariableGroups(scopeType, scopeId); setGroups(data.groups || []); setLoadError(null); } catch (err) { setLoadError(err); } finally { setLoading(false); } }, [scopeType, scopeId]); const loadDetail = useCallback(async (groupId) => { if (!groupId) { setDetail(null); return; } try { const data = await api.getVariableGroup(groupId); setDetail(data); } catch (err) { toastError(toast, t('app.sharedVariableGroups.failedToLoadGroup', "Couldn't load the group."), err); } }, [t, toast]); useEffect(() => { loadGroups(); }, [loadGroups]); useEffect(() => { loadDetail(selectedId); }, [selectedId, loadDetail]); async function handleCreateGroup(e) { e.preventDefault(); if (!newName.trim()) return; try { const group = await api.createVariableGroup({ scopeType, scopeId, name: newName.trim(), description: newDescription.trim() || null, }); toast.success(t('app.sharedVariableGroups.groupCreated', 'Group created')); setNewName(''); setNewDescription(''); setCreating(false); await loadGroups(); setSelectedId(group.id); } catch (err) { toastError(toast, t('app.sharedVariableGroups.failedToCreateGroup', "Couldn't create the group."), err); } } async function handleDeleteGroup(groupId) { if (!await confirm({ title: t('app.sharedVariableGroups.deleteVariableGroup', 'Delete variable group'), message: t('app.sharedVariableGroups.deleteThisVariableGroupItsAttachments', 'Delete this variable group? Its attachments will be removed.'), confirmText: t('app.sharedVariableGroups.deleteGroup', 'Delete group'), })) return; try { await api.deleteVariableGroup(groupId); toast.success(t('app.sharedVariableGroups.groupDeleted', 'Group deleted')); if (selectedId === groupId) setSelectedId(null); loadGroups(); } catch (err) { toastError(toast, t('app.sharedVariableGroups.failedToDeleteGroup', "Couldn't delete the group."), err); } } async function handleAddVariable(e) { e.preventDefault(); if (!varKey.trim() || !selectedId) return; try { await api.addGroupVariable(selectedId, { key: varKey.trim(), value: varValue, isSecret: varSecret, targetService: varTarget.trim() || null, }); setVarKey(''); setVarValue(''); setVarSecret(false); setVarTarget(''); loadDetail(selectedId); loadGroups(); } catch (err) { toastError(toast, t('app.sharedVariableGroups.failedToAddVariable', "Couldn't add the variable."), err); } } async function handleDeleteVariable(variableId) { try { await api.deleteGroupVariable(selectedId, variableId); loadDetail(selectedId); loadGroups(); } catch (err) { toastError(toast, t('app.sharedVariableGroups.failedToDeleteVariable', "Couldn't delete the variable."), err); } } async function handleAttach(e) { e.preventDefault(); if (!attachId.trim() || !selectedId) return; try { await api.attachVariableGroup(selectedId, attachType, attachId.trim()); toast.success(t('app.sharedVariableGroups.groupAttached', 'Group attached')); setAttachId(''); loadDetail(selectedId); loadGroups(); } catch (err) { toastError(toast, t('app.sharedVariableGroups.failedToAttachGroup', "Couldn't attach the group."), err); } } async function handleDetach(att) { try { await api.detachVariableGroup(selectedId, att.resource_type, att.resource_id); loadDetail(selectedId); loadGroups(); } catch (err) { toastError(toast, t('app.sharedVariableGroups.failedToDetach', "Couldn't detach the group."), err); } } // The top bar follows the depth, like Vaults: create groups at the list, // go back and manage one inside it. useTopbarActions(() => (detail ? ( <> setSelectedId(null)}> {t('app.sharedVariableGroups.allGroups', 'All groups')} > ) : ( <> setCreating(true)} /> > )), [detail, search]); // A term that matched a group name is not a variable key; clear on depth change. useEffect(() => { setSearch(''); }, [selectedId]); const groupRows = useMemo(() => { const q = search.trim().toLowerCase(); if (!q) return groups; return groups.filter((g) => ( g.name?.toLowerCase().includes(q) || g.description?.toLowerCase().includes(q) )); }, [groups, search]); const variableRows = useMemo(() => { const all = detail?.variables || []; const q = search.trim().toLowerCase(); if (!q) return all; return all.filter((v) => ( v.key?.toLowerCase().includes(q) || v.target_service?.toLowerCase().includes(q) )); }, [detail, search]); const groupColumns = useMemo(() => [ { key: 'name', headerKey: 'app.sharedVariableGroups.group', header: 'Group', sortable: true, hideable: false, value: (g) => g.name, render: (g) => ( {g.name} ), }, { key: 'description', headerKey: 'common.labels.description', header: 'Description', sortable: true, value: (g) => g.description || '', render: (g) => g.description || —, }, // `value` sorts and filters; `render` is what the cell shows — // DataTable falls back to row[key], and these counts have no such key. { key: 'variables', headerKey: 'app.sharedVariableGroups.variables', header: 'Variables', type: 'number', sortable: true, width: 110, cellClassName: 'sk-cell-dim', value: (g) => g.variable_count ?? 0, render: (g) => g.variable_count ?? 0, }, { key: 'attachments', headerKey: 'app.sharedVariableGroups.attached', header: 'Attached', type: 'number', sortable: true, width: 110, cellClassName: 'sk-cell-dim', value: (g) => g.attachment_count ?? 0, render: (g) => g.attachment_count ?? 0, }, { key: '__actions', header: '', sortable: false, hideable: false, width: 56, className: 'text-right', render: (g) => ( { e.stopPropagation(); handleDeleteGroup(g.id); }} > ), }, // eslint-disable-next-line react-hooks/exhaustive-deps ], [selectedId, loadGroups]); const variableColumns = useMemo(() => [ { key: 'key', headerKey: 'common.labels.key', header: 'Key', sortable: true, hideable: false, value: (v) => v.key, cellClassName: 'sk-cell-mono', render: (v) => ( {v.key} {v.is_secret && secret} ), }, { key: 'value', headerKey: 'common.labels.value', header: 'Value', sortable: false, filterable: false, cellClassName: 'sk-cell-mono', render: (v) => {v.value}, }, { key: 'target', headerKey: 'app.sharedVariableGroups.targetService', header: 'Target service', sortable: true, // A blank target is not missing data — it means every service in the // stack, which is a different statement from "unknown". value: (v) => v.target_service || '', render: (v) => (v.target_service ? ( → {v.target_service} ) : ( {t('app.sharedVariableGroups.allServices', 'all services')} )), }, { key: '__actions', header: '', sortable: false, hideable: false, width: 56, className: 'text-right', render: (v) => ( { e.stopPropagation(); handleDeleteVariable(v.id); }} > ), }, // eslint-disable-next-line react-hooks/exhaustive-deps ], [selectedId, loadDetail, loadGroups]); if (!detail) { return ( <> setSelectedId(g.id)} emptyIcon={Boxes} emptyTitle="No variable groups yet" emptyDescription={<>{t('app.sharedVariableGroups.emptyShort', 'Reusable variables for many resources.')} {t('app.sharedVariableGroups.emptyFull', 'A group is a set of variables you attach to services, databases or servers at once, instead of copying the same values into each.')}>} emptyAction={ setCreating(true)}> {t('app.sharedVariableGroups.createYourFirstGroup', 'Create your first group')}} filteredEmptyIcon={Boxes} filteredEmptyTitle="No groups found" filteredEmptyDescription="Try adjusting your search or filters." /> setCreating(false)} title={t('app.sharedVariableGroups.newVariableGroup', 'New variable group')}> {t('app.sharedVariableGroups.variablesInThisGroupApplyTo', 'Variables in this group apply to every resource you attach it to.')} {t('common.labels.name', 'Name')} setNewName(e.target.value)} placeholder={t('app.sharedVariableGroups.eGSharedDatabase', 'e.g. shared-database')} required /> {t('app.sharedVariableGroups.descriptionOptional', 'Description (optional)')} setNewDescription(e.target.value)} placeholder={t('app.sharedVariableGroups.whatThisGroupIsFor', 'What this group is for…')} /> setCreating(false)}>{t('common.actions.cancel', 'Cancel')} {t('app.sharedVariableGroups.createGroup', 'Create group')} > ); } return ( {detail.name} {detail.description && ( {detail.description} )} handleDeleteGroup(detail.id)} > {t('app.sharedVariableGroups.deleteGroup', 'Delete group')} setVarKey(e.target.value)} placeholder="KEY" className="shared-groups__var-key" /> setVarValue(e.target.value)} placeholder="value" className="shared-groups__var-value" /> setVarTarget(e.target.value)} placeholder={t('app.sharedVariableGroups.allServices', 'all services')} className="shared-groups__var-target" title={t('app.sharedVariableGroups.targetComposeServiceLeaveBlankTo', 'Target compose service (leave blank to apply to all services)')} /> {t('app.sharedVariableGroups.secret', 'Secret')} {t('common.actions.add', 'Add')} {/* Attachments */} {t('app.sharedVariableGroups.attachedResources', 'Attached resources')} {(detail.attachments || []).length === 0 ? ( {t('app.sharedVariableGroups.notAttachedToAnyResourceYet', 'Not attached to any resource yet.')} ) : ( {detail.attachments.map((a) => ( {a.resource_type}:{a.resource_id} handleDetach(a)} title={t('app.sharedVariableGroups.detach', 'Detach')} aria-label={t('app.sharedVariableGroups.detachGroup', 'Detach group')} > × ))} )} {RESOURCE_TYPES.map((type) => ( {type} ))} setAttachId(e.target.value)} placeholder={t('app.sharedVariableGroups.resourceId', 'resource ID')} className="shared-groups__attach-id" /> {t('app.sharedVariableGroups.attach', 'Attach')} ); }; export default SharedVariableGroups;
{t('app.sharedVariableGroups.variablesInThisGroupApplyTo', 'Variables in this group apply to every resource you attach it to.')}
{detail.description}
{t('app.sharedVariableGroups.notAttachedToAnyResourceYet', 'Not attached to any resource yet.')}