Implemented Discard changes button

This commit is contained in:
patben8 committed 2026-09-30 17:07:26 +02:00
1 parent 4e875958a7
commit e4e98eda3f
17 files changed
+564 -43

No files matched your search

+84 -6
View File
@@ -5,21 +5,94 @@
// it to actually accept connections, then create the app window with an
// initialization script that hands the frontend its API base
// (`window.__KONDUKTOR_API__`). The sidecar is killed when the app exits.
//
// Quitting ASKS FIRST. Closing the window or Cmd/Ctrl+Q is prevented and
// becomes a `konduktor://quit-requested` event; the frontend (QuitGuard.tsx)
// acknowledges it, checks for unsaved changes and either quits (`quit_now`) or
// asks Save / Discard / Cancel. The sidecar must outlive that question — a
// Save or Discard runs in it — so it is killed only once the app really exits.
// If the webview does not acknowledge within ~2 s (hung, or not loaded yet),
// the app quits anyway: a broken page must never make the app unquittable.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use std::time::Duration;
use tauri::{Manager, WebviewUrl, WebviewWindowBuilder};
use tauri::{AppHandle, Emitter, Manager, RunEvent, WebviewUrl, WebviewWindowBuilder, WindowEvent};
use tauri_plugin_shell::process::{CommandChild, CommandEvent};
use tauri_plugin_shell::ShellExt;
/// Holds the running sidecar child so we can terminate it on exit.
struct Sidecar(Mutex<Option<CommandChild>>);
/// Quit handshake state: `allowed` once the frontend (or the timeout) has said
/// quit; `acked` once the frontend has seen the current request.
struct Quit {
allowed: AtomicBool,
acked: AtomicBool,
}
fn kill_sidecar(app: &AppHandle) {
if let Some(child) = app.state::<Sidecar>().0.lock().unwrap().take() {
let _ = child.kill();
}
}
fn exit_now(app: &AppHandle) {
app.state::<Quit>().allowed.store(true, Ordering::SeqCst);
kill_sidecar(app);
app.exit(0);
}
/// Hand the quit decision to the frontend, with a deadline for it to answer.
fn request_quit(app: &AppHandle) {
app.state::<Quit>().acked.store(false, Ordering::SeqCst);
if app.emit("konduktor://quit-requested", ()).is_err() {
exit_now(app);
return;
}
let handle = app.clone();
tauri::async_runtime::spawn(async move {
tokio::time::sleep(Duration::from_secs(2)).await;
if !handle.state::<Quit>().acked.load(Ordering::SeqCst) {
exit_now(&handle);
}
});
}
/// The frontend has seen the quit request (it may now take as long as it likes).
#[tauri::command]
fn quit_ack(app: AppHandle) {
app.state::<Quit>().acked.store(true, Ordering::SeqCst);
}
/// The user chose Cancel: forget the request.
#[tauri::command]
fn quit_cancel(app: AppHandle) {
app.state::<Quit>().acked.store(false, Ordering::SeqCst);
}
/// Quit for real (nothing unsaved, or Save / Discard has finished).
#[tauri::command]
fn quit_now(app: AppHandle) {
exit_now(&app);
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.manage(Sidecar(Mutex::new(None)))
.manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) })
.invoke_handler(tauri::generate_handler![quit_ack, quit_cancel, quit_now])
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
let app = window.app_handle();
if !app.state::<Quit>().allowed.load(Ordering::SeqCst) {
api.prevent_close();
request_quit(app);
}
}
})
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
@@ -99,12 +172,17 @@ pub fn run() {
})
.build(tauri::generate_context!())
.expect("error while building the Tauri application")
.run(|app_handle, event| {
// Terminate the sidecar when the app is quitting.
if let tauri::RunEvent::ExitRequested { .. } = event {
if let Some(child) = app_handle.state::<Sidecar>().0.lock().unwrap().take() {
let _ = child.kill();
.run(|app_handle, event| match event {
// Cmd/Ctrl+Q, the app menu's Quit, the last window closing: ask
// first, unless the answer is already in.
RunEvent::ExitRequested { api, .. } => {
if !app_handle.state::<Quit>().allowed.load(Ordering::SeqCst) {
api.prevent_exit();
request_quit(app_handle);
}
}
// Really exiting: only now may the backend go.
RunEvent::Exit => kill_sidecar(app_handle),
_ => {}
});
}
+7 -1
View File
@@ -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>
+2
View File
@@ -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'),
+150
View File
@@ -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,
)
}
+34 -1
View File
@@ -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>
)}
+12 -15
View File
@@ -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>
)
}
+24
View File
@@ -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',
})
}
+3
View File
@@ -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>,
)