import { useState, type ReactNode } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api } from '../api' import { useCaps } from '../lib/capabilities' import { overwriteWarning, readOnlyNotice, saveLabel } from '../lib/platformCopy' import { Icon } from '../lib/icons' import { askConfirm } from '../lib/confirm' interface Props { onError: (msg: string) => void /** Rendered to the right of the save button (the settings gear). */ trailing?: ReactNode /** After a discard, so the owner can refresh what it holds outside queries. */ onDiscarded?: () => void } // Bottom-of-sidebar save control. Shows unsaved-changes state and writes to the // NML; every save is recorded in the collection's version history. export function SaveBar({ onError, trailing, onDiscarded }: Props) { const qc = useQueryClient() const [justSaved, setJustSaved] = useState(null) const { data: state } = useQuery({ queryKey: ['state'], queryFn: api.state }) const save = useMutation({ mutationFn: api.save, onSuccess: (res) => { qc.invalidateQueries({ queryKey: ['state'] }) qc.invalidateQueries({ queryKey: ['history'] }) if (res.saved && res.commit) { setJustSaved(`Saved · version ${res.commit.slice(0, 8)}`) setTimeout(() => setJustSaved(null), 6000) } }, onError: (e: Error) => onError(e.message), }) // The way back that did not exist: every edit since the last save goes, and // the library re-reads itself from disk. Everything cached is refetched. const discard = useMutation({ mutationFn: api.discard, onSuccess: () => { qc.invalidateQueries() onDiscarded?.() }, onError: (e: Error) => onError(e.message), }) const confirmDiscard = async () => { const ok = await askConfirm({ title: 'Discard unsaved changes?', body: 'Every change since the last save is thrown away and the library is re-read from disk. This cannot be undone.', confirmLabel: 'Discard changes', }) if (ok) discard.mutate() } const caps = useCaps() const warning = overwriteWarning(caps.save) const dirty = state?.dirty ?? false const readOnly = readOnlyNotice(caps) // A read-only library has no save to offer, and saying so plainly is the whole // point: a greyed-out button with no explanation reads as a bug. if (readOnly) { return (
Read-only
{readOnly}
{trailing}
) } return (
{dirty && warning && (
{warning}
)}
{trailing}
{dirty && !save.isPending && (
)} {justSaved && (
{justSaved}
)}
) }