diff --git a/src/lib/Dialog.svelte b/src/lib/Dialog.svelte index 4473400..2719007 100644 --- a/src/lib/Dialog.svelte +++ b/src/lib/Dialog.svelte @@ -41,24 +41,29 @@ title: (title: string) => void; } + type DialogControlButton = { + label?: string; + class?: ClassValue; + action?: (dialog: DialogAPI) => void; + }; + /** * Configures the default dialog controls. */ - export type DialogControlOpts = { - cancel?: { - label?: string; - class?: ClassValue; - action?: (dialog: DialogAPI) => void; - }; - ok?: { - label?: string; - class?: ClassValue; - action?: (dialog: DialogAPI) => void; - }; - close?: { - class?: ClassValue; - action?: (dialog: DialogAPI) => void; - }; + export type DialogControls = { + cancel?: DialogControlButton | null; + ok?: DialogControlButton | null; + close?: Omit | null; + }; + + const defaultDialogControls: DialogControls = { + cancel: { + label: 'Cancel' + }, + ok: { + label: 'OK' + }, + close: {} }; @@ -72,6 +77,7 @@ import { X } from 'phosphor-svelte'; import { ErrorMessage, type RawError } from './error'; import ErrorBox from './ErrorBox.svelte'; + import { mergeOverrideObject } from './util'; interface Props { open?: boolean; @@ -80,7 +86,7 @@ size?: 'sm' | 'md' | 'lg' | 'max'; class?: ClassValue; children?: Snippet; - controls?: Snippet | DialogControlOpts; + controls?: Snippet | DialogControls; onopen?: (dialog: DialogAPI) => void; onclose?: (dialog: DialogAPI) => void; loading?: boolean; @@ -95,7 +101,7 @@ size = 'sm', class: classValue, children, - controls, + controls: rawControls = defaultDialogControls, onopen, onclose, loading = $bindable(false), @@ -103,6 +109,12 @@ disabled = $bindable(false) }: Props = $props(); + let controls = $derived( + typeof rawControls === 'function' + ? rawControls + : mergeOverrideObject(defaultDialogControls, rawControls) + ); + let dialogContainer = $state(null); let error = $state(null); @@ -192,49 +204,62 @@ {#if children}{@render children()}{:else}Dialog is empty{/if} +
{#if controls && typeof controls === 'function'}{@render controls()}{:else} - - + {#if controls.cancel !== null} + + {/if} + {#if controls.ok !== null} + + {/if} {/if}
- + onclick={() => { + if (typeof controls !== 'function' && controls?.close?.action) { + controls?.close?.action?.(dialogAPI); + } else if (!frozen) { + open = false; + } + }} + disabled={frozen} + > + + + {/if} {/snippet} diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 9d94e41..053f3d0 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -523,7 +523,8 @@ dialog.close(); alert('Dialog submitted!'); } - } + }, + cancel: null }} onopen={(dialog) => { dialog.error('Example error message!');