mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented Discard changes button
This commit is contained in:
1 parent
681add852a
commit
28b705173e
17 files changed
+564
-43
No files matched your search
@@ -5,6 +5,7 @@ import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
|
||||
import { writeHint } from './lib/platformCopy'
|
||||
import { invalidateTrackLists } from './lib/trackQueries'
|
||||
import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type Track, type TrackOrigin } from './api'
|
||||
import { confirmDiscardUnsaved } from './lib/unsaved'
|
||||
import {
|
||||
COLUMN_MENU,
|
||||
DEFAULT_COLUMN_ORDER,
|
||||
@@ -1034,6 +1035,7 @@ export default function App() {
|
||||
onSwitchLibrary={() => setForcePicker(true)}
|
||||
onDone={(msg) => notify('success', msg)}
|
||||
onOpenPathMapping={() => setShowPaths(true)}
|
||||
onDiscarded={() => afterBulk(prepTrack ? [prepTrack.id] : [], true)}
|
||||
/>
|
||||
|
||||
<CapabilitiesContext.Provider value={viewCaps}>
|
||||
@@ -1353,7 +1355,11 @@ export default function App() {
|
||||
}
|
||||
loading={loading}
|
||||
collectionName={capabilities.data ? libraryName : null}
|
||||
onChangeCollection={() => setForcePicker(true)}
|
||||
onChangeCollection={() => {
|
||||
// The same question the sidebar header asks: this button used to
|
||||
// switch library without it, silently dropping unsaved edits.
|
||||
void confirmDiscardUnsaved().then((ok) => ok && setForcePicker(true))
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</CapabilitiesContext.Provider>
|
||||
|
||||
@@ -758,6 +758,8 @@ export const api = {
|
||||
patchPrefs: (patch: Record<string, unknown>) =>
|
||||
send<Record<string, unknown>>('PATCH', '/api/prefs', patch),
|
||||
save: () => send<SaveResult>('POST', '/api/save'),
|
||||
/** Drop every unsaved edit; the library re-reads itself from disk. */
|
||||
discard: () => send<EditState>('POST', '/api/discard'),
|
||||
|
||||
// ---- version history ----
|
||||
history: () => getJSON<HistoryEntry[]>('/api/history'),
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
|
||||
/**
|
||||
* Ask before quitting with unsaved changes: Save · Discard · Cancel.
|
||||
*
|
||||
* The desktop shell (src-tauri/src/lib.rs) no longer quits on its own. Closing
|
||||
* the window or Cmd/Ctrl+Q is PREVENTED there and becomes a
|
||||
* `konduktor://quit-requested` event; this answers it. It acknowledges at once
|
||||
* (`quit_ack`) — the shell quits anyway after ~2 s without one, so a webview
|
||||
* that has hung can never trap the user — then either quits (`quit_now`) or
|
||||
* asks. Discard goes through the backend rather than just letting the process
|
||||
* die, because unsaved state may include files to put back (a stem
|
||||
* conversion's parked originals).
|
||||
*
|
||||
* In a plain browser (dev) there is no shell to prevent anything, so the most
|
||||
* that can be done is the browser's own `beforeunload` warning.
|
||||
*
|
||||
* Mounted once in main.tsx, beside App, so it works on the picker screen too.
|
||||
*/
|
||||
export function QuitGuard() {
|
||||
const [asking, setAsking] = useState(false)
|
||||
const [busy, setBusy] = useState<null | 'save' | 'discard'>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const askingRef = useRef(false)
|
||||
const state = useQuery({ queryKey: ['state'], queryFn: api.state, retry: false })
|
||||
const dirty = state.data?.dirty ?? false
|
||||
|
||||
// Tauri: answer the shell's quit request.
|
||||
useEffect(() => {
|
||||
if (!('__TAURI_INTERNALS__' in window)) return
|
||||
let unlisten: (() => void) | undefined
|
||||
let cancelled = false
|
||||
void (async () => {
|
||||
const [{ listen }, { invoke }] = await Promise.all([
|
||||
import('@tauri-apps/api/event'),
|
||||
import('@tauri-apps/api/core'),
|
||||
])
|
||||
const off = await listen('konduktor://quit-requested', async () => {
|
||||
await invoke('quit_ack')
|
||||
if (askingRef.current) return // already asking: a second Cmd+Q changes nothing
|
||||
const unsaved = await api
|
||||
.state()
|
||||
.then((s) => s.dirty)
|
||||
.catch(() => false) // no library loaded: nothing to lose
|
||||
if (!unsaved) {
|
||||
await invoke('quit_now')
|
||||
return
|
||||
}
|
||||
askingRef.current = true
|
||||
setError(null)
|
||||
setAsking(true)
|
||||
})
|
||||
if (cancelled) off()
|
||||
else unlisten = off
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
unlisten?.()
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Browser dev: the browser's own warning is all there is.
|
||||
useEffect(() => {
|
||||
if ('__TAURI_INTERNALS__' in window || !dirty) return
|
||||
const warn = (e: BeforeUnloadEvent) => {
|
||||
e.preventDefault()
|
||||
}
|
||||
window.addEventListener('beforeunload', warn)
|
||||
return () => window.removeEventListener('beforeunload', warn)
|
||||
}, [dirty])
|
||||
|
||||
const quit = async () => {
|
||||
const { invoke } = await import('@tauri-apps/api/core')
|
||||
await invoke('quit_now')
|
||||
}
|
||||
const cancel = async () => {
|
||||
askingRef.current = false
|
||||
setAsking(false)
|
||||
const { invoke } = await import('@tauri-apps/api/core')
|
||||
await invoke('quit_cancel')
|
||||
}
|
||||
const act = async (kind: 'save' | 'discard') => {
|
||||
setBusy(kind)
|
||||
setError(null)
|
||||
try {
|
||||
if (kind === 'save') await api.save()
|
||||
else await api.discard()
|
||||
await quit()
|
||||
} catch (e) {
|
||||
// Stay open: a failed save must never turn into a silent loss.
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
setBusy(null)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!asking) return
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && !busy) void cancel()
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
})
|
||||
|
||||
if (!asking) return null
|
||||
return createPortal(
|
||||
<div
|
||||
aria-modal="true"
|
||||
className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
|
||||
>
|
||||
<div className="w-full max-w-sm overflow-hidden glass-overlay">
|
||||
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
|
||||
Save changes before quitting?
|
||||
</div>
|
||||
<div className="space-y-2 px-5 py-4 text-sm text-muted">
|
||||
<p>You have unsaved changes. If you quit without saving, they are lost.</p>
|
||||
{error && <p className="text-pink">{error}</p>}
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
|
||||
<button
|
||||
onClick={() => void cancel()}
|
||||
disabled={!!busy}
|
||||
className="btn-glass rounded-full px-4 py-1.5 text-sm text-muted hover:text-text disabled:opacity-40"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={() => void act('discard')}
|
||||
disabled={!!busy}
|
||||
className="rounded-full bg-pink/15 px-4 py-1.5 text-sm font-semibold text-[#ffd0da] shadow-[inset_0_1px_0_rgb(255_255_255/0.12),inset_0_0_0_1px_rgb(255_122_154/0.55)] hover:bg-pink/25 disabled:opacity-50"
|
||||
>
|
||||
{busy === 'discard' ? 'Discarding…' : 'Discard'}
|
||||
</button>
|
||||
<button
|
||||
autoFocus
|
||||
onClick={() => void act('save')}
|
||||
disabled={!!busy}
|
||||
className="btn-primary rounded-full px-4 py-1.5 text-sm font-semibold disabled:opacity-50"
|
||||
>
|
||||
{busy === 'save' ? 'Saving…' : 'Save and quit'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
@@ -4,16 +4,19 @@ 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 }: Props) {
|
||||
export function SaveBar({ onError, trailing, onDiscarded }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const [justSaved, setJustSaved] = useState<string | null>(null)
|
||||
const { data: state } = useQuery({ queryKey: ['state'], queryFn: api.state })
|
||||
@@ -31,6 +34,25 @@ export function SaveBar({ onError, trailing }: Props) {
|
||||
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
|
||||
@@ -79,6 +101,17 @@ export function SaveBar({ onError, trailing }: Props) {
|
||||
</button>
|
||||
{trailing}
|
||||
</div>
|
||||
{dirty && !save.isPending && (
|
||||
<div className="mt-1.5 text-center">
|
||||
<button
|
||||
onClick={() => void confirmDiscard()}
|
||||
disabled={discard.isPending}
|
||||
className="text-[11px] text-faint hover:text-pink disabled:opacity-50"
|
||||
>
|
||||
{discard.isPending ? 'Discarding…' : 'Discard changes…'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{justSaved && (
|
||||
<div className="mt-2 text-center text-[11px] text-mint">{justSaved}</div>
|
||||
)}
|
||||
|
||||
@@ -3,11 +3,11 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type PlaylistKind, type PlaylistNode } from '../api'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { SaveBar } from './SaveBar'
|
||||
import { confirmDiscardUnsaved } from '../lib/unsaved'
|
||||
import { SettingsMenu } from './SettingsMenu'
|
||||
import { DevicesSection } from './DevicesSection'
|
||||
import { ExportsSection } from './ExportsSection'
|
||||
import { ConfirmDialog, type ConfirmRequest } from './ConfirmDialog'
|
||||
import { askConfirm } from '../lib/confirm'
|
||||
import { ContextMenu, type MenuItem } from './ContextMenu'
|
||||
import { Icon, type IconName } from '../lib/icons'
|
||||
import { PlatformIcon } from '../lib/platformIcons'
|
||||
@@ -49,6 +49,8 @@ interface Props {
|
||||
onSwitchLibrary: () => void
|
||||
onDone: (msg: string) => void
|
||||
onOpenPathMapping: () => void
|
||||
/** After unsaved edits were discarded (SaveBar). */
|
||||
onDiscarded?: () => void
|
||||
}
|
||||
|
||||
// Kind picks the icon; every behavioural question is answered by the node's own
|
||||
@@ -319,27 +321,18 @@ export function Sidebar({
|
||||
onSwitchLibrary,
|
||||
onDone,
|
||||
onOpenPathMapping,
|
||||
onDiscarded,
|
||||
}: Props) {
|
||||
const qc = useQueryClient()
|
||||
// Both share a cache entry with App and SaveBar, so the header never
|
||||
// disagrees with what is loaded or with whether it has been saved.
|
||||
// Shares a cache entry with App, so the header never disagrees with what is
|
||||
// loaded.
|
||||
const library = useQuery({ queryKey: ['collection'], queryFn: api.collection }).data?.library
|
||||
const dirty = useQuery({ queryKey: ['state'], queryFn: api.state }).data?.dirty ?? false
|
||||
|
||||
// Switching library throws away every unsaved edit — the adapter holds them in
|
||||
// its native model, and opening another library replaces it. Worth a confirm:
|
||||
// until now there was no way to switch at all, so this hazard is new.
|
||||
const switchLibrary = async () => {
|
||||
if (
|
||||
dirty &&
|
||||
!(await askConfirm({
|
||||
title: 'Discard unsaved changes?',
|
||||
body: 'You have unsaved changes. Opening a different library will discard them.',
|
||||
confirmLabel: 'Discard and switch',
|
||||
}))
|
||||
)
|
||||
return
|
||||
onSwitchLibrary()
|
||||
if (await confirmDiscardUnsaved()) onSwitchLibrary()
|
||||
}
|
||||
// There is no per-node flag for "you may create a NEW playlist" — the node
|
||||
// flags describe existing nodes — so this is the library-level gate.
|
||||
@@ -609,7 +602,11 @@ export function Sidebar({
|
||||
Collection Version History
|
||||
</button>
|
||||
|
||||
<SaveBar onError={onError} trailing={<SettingsMenu up onOpenPathMapping={onOpenPathMapping} />} />
|
||||
<SaveBar
|
||||
onError={onError}
|
||||
onDiscarded={onDiscarded}
|
||||
trailing={<SettingsMenu up onOpenPathMapping={onOpenPathMapping} />}
|
||||
/>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { api } from '../api'
|
||||
import { askConfirm } from './confirm'
|
||||
|
||||
/**
|
||||
* Ask before an action that throws away unsaved edits — opening a different
|
||||
* library replaces the adapter that holds them. Resolves true when there is
|
||||
* nothing to lose or the user agreed.
|
||||
*
|
||||
* Reads the state fresh rather than from a cached query: the two places that
|
||||
* switch library (the sidebar header and the status bar) must not disagree, and
|
||||
* the status bar's button used to skip the question entirely.
|
||||
*/
|
||||
export async function confirmDiscardUnsaved(): Promise<boolean> {
|
||||
const dirty = await api
|
||||
.state()
|
||||
.then((s) => s.dirty)
|
||||
.catch(() => false) // no library loaded: nothing to lose
|
||||
if (!dirty) return true
|
||||
return askConfirm({
|
||||
title: 'Discard unsaved changes?',
|
||||
body: 'You have unsaved changes. Opening a different library will discard them.',
|
||||
confirmLabel: 'Discard and switch',
|
||||
})
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import App from './App.tsx'
|
||||
import { UpdateCheck } from './components/UpdateDialog.tsx'
|
||||
import { AmbientBackdrop } from './components/AmbientBackdrop.tsx'
|
||||
import { ConfirmHost } from './lib/confirm.tsx'
|
||||
import { QuitGuard } from './components/QuitGuard.tsx'
|
||||
import { preventHistoryNavigation } from './lib/noNavigation.ts'
|
||||
|
||||
preventHistoryNavigation()
|
||||
@@ -31,6 +32,8 @@ createRoot(document.getElementById('root')!).render(
|
||||
<UpdateCheck />
|
||||
{/* askConfirm()'s dialogs — the app's replacement for window.confirm. */}
|
||||
<ConfirmHost />
|
||||
{/* Save · Discard · Cancel when quitting with unsaved changes. */}
|
||||
<QuitGuard />
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
Reference in new issue
Block a user