Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,8 @@ Grant date/time fields use the calendar and time wheels on touch devices too, wi
**Alerts and toasts.** `InlineAlert` for what persists or needs action: load errors, dialog submit errors, partial
saves. It defaults to `tone="danger"` and `role="alert"`, so pass another tone for notices that aren't errors. Toasts
(`appToast.success/info/warning/error`, never raw `toast`) confirm actions; untinted, tone on the icon only, at most
three, never infinite, no "Undo".
three, no "Undo", never infinite but for a task that runs in the background for minutes: `appToast.loading` until it
ends, then its outcome in the same toast (`id`), an error kept until dismissed with its close button (`closeButton`).

**Accessibility.** Every input has a label; focus is never removed; dialogs trap focus and return it to the trigger;
when a row disappears (optimistic removal, confirmed delete) `useFocusAfterRemoval` keeps focus in the list. Color is
Expand Down
5 changes: 3 additions & 2 deletions docs/regulations/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ Every section but Bozze also needs `admin:access`, like the rest of the dashboar
(repository: a pull request, the document listed "In creazione" with its link until it merges, then active; the list
reloads every 15 s meanwhile; a closed one is "Non creato", with "Crea di nuovo") or private (opened at once); "Carica
un PDF" makes a private read-only document. The key is a slug of the title until edited, checked like the backend.
- **Import.** "Importa dal repository" runs `documents.sync` and lists what it skipped, with the backend's reason, above
the sections until the page is left.
- **Import.** "Importa dal repository" runs `documents.sync` in the background (`documents-sync.ts`, it reads the whole repository):
the dialog closes at once, a loading toast becomes the outcome when it ends, even on another page, and the button
stays disabled meanwhile. What it skipped, with the backend's reason, shows above the sections until the next import.
- **PDFs.** Every PDF opens in `PdfDialog` (versions, the latest of a sola consultazione document, uploads, the
editor's preview "Apri a tutta altezza", the differences), with Download in its toolbar.
- Pages act on the document's `editable`, the draft's `can` and the IdP permissions, never on a kind alone.
Expand Down
23 changes: 15 additions & 8 deletions src/components/shell/toast.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import { toast } from "sonner"
import { type ExternalToast, toast } from "sonner"

/**
* Toasts with these durations: success/info 4s, warning 6s, error 8s. They go to the one
* `Toaster` mounted in the root document. Copy follows the toast formula in docs/design.md: "Group deleted.",
* "Couldn't delete the group."
* `id` turns an earlier toast (a `loading` one) into this one; `duration: Infinity` keeps it until dismissed, so pair it
* with `closeButton`: the only dismissal a keyboard can reach.
*/
type AppToastOptions = Pick<ExternalToast, "id" | "duration" | "closeButton">

/**
* Toasts with these durations: success/info 4s, warning 6s, error 8s; loading stays until its `id` gets another
* toast. They go to the one `Toaster` mounted in the root document. Copy follows the toast formula in docs/design.md:
* "Group deleted.", "Couldn't delete the group."
*/
export const appToast = {
success: (message: string) => toast.success(message, { duration: 4000 }),
info: (message: string) => toast.info(message, { duration: 4000 }),
warning: (message: string) => toast.warning(message, { duration: 6000 }),
error: (message: string) => toast.error(message, { duration: 8000 }),
success: (message: string, options?: AppToastOptions) => toast.success(message, { duration: 4000, ...options }),
info: (message: string, options?: AppToastOptions) => toast.info(message, { duration: 4000, ...options }),
warning: (message: string, options?: AppToastOptions) => toast.warning(message, { duration: 6000, ...options }),
error: (message: string, options?: AppToastOptions) => toast.error(message, { duration: 8000, ...options }),
loading: (message: string) => toast.loading(message),
}
5 changes: 3 additions & 2 deletions src/components/ui/sonner.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CircleCheck, CircleX, Info, TriangleAlert } from "lucide-react"
import { CircleCheck, CircleX, Info, LoaderCircle, TriangleAlert } from "lucide-react"
import { useEffect, useState } from "react"
import { Toaster as Sonner, type ToasterProps } from "sonner"

Expand All @@ -7,6 +7,7 @@ const icons = {
info: <Info className="size-4" />,
warning: <TriangleAlert className="size-4" />,
error: <CircleX className="size-4" />,
loading: <LoaderCircle className="size-4 animate-spin" />,
}

/** The app's one Toaster: bottom-right, three visible, untinted `app-toast` surfaces. */
Expand All @@ -31,7 +32,7 @@ const Toaster = ({ ...props }: ToasterProps) => {
duration={4000}
icons={icons}
className="toaster group"
toastOptions={{ classNames: { toast: "app-toast" } }}
toastOptions={{ classNames: { toast: "app-toast" }, closeButtonAriaLabel: "Chiudi la notifica" }}
{...props}
/>
)
Expand Down
33 changes: 24 additions & 9 deletions src/features/regulations/documents-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,15 @@ import {
IconButton,
InlineAlert,
SectionHeading,
Spinner,
StatusBadge,
useOpenGeneration,
} from "@/components/primitives"
import { PageBar, PageContent, useCan } from "@/components/shell"
import { appToast, PageBar, PageContent, useCan } from "@/components/shell"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"

import { setDocumentsSync, useDocumentsSync } from "./documents-sync"
import { NewDocumentDialog } from "./new-document-dialog"
import { DOCUMENT_KIND_LABELS, formatDay } from "./regulations-format"
import { failureMessage, useRefreshAfter } from "./regulations-hooks"
Expand Down Expand Up @@ -64,7 +66,7 @@ export function DocumentsPage({ documents }: { documents: DocumentInfo[] }) {
const create = useServerFn(createRegulationDocument)
const refresh = useRefreshAfter()
const [syncOpen, setSyncOpen] = useState(false)
const [syncResult, setSyncResult] = useState<SyncResult | null>(null)
const { running: syncing, result: syncResult } = useDocumentsSync()
const [newOpen, setNewOpen] = useState(false)
const generation = useOpenGeneration(newOpen)
const [retrying, setRetrying] = useState<DocumentInfo | null>(null)
Expand All @@ -91,24 +93,35 @@ export function DocumentsPage({ documents }: { documents: DocumentInfo[] }) {
),
})).filter((group) => group.documents.length > 0)

/** Runs in the background: the dialog closes at once and one toast follows the import until it ends. */
async function runSync() {
setDocumentsSync({ running: true, result: null })
const toastId = appToast.loading("Importazione dei documenti in corso…")
let result: SyncResult
try {
result = await sync()
} catch (caught) {
console.error(caught)
throw new Error(failureMessage(caught, "Non è stato possibile importare i documenti."), { cause: caught })
setDocumentsSync({ running: false })
appToast.error(failureMessage(caught, "Non è stato possibile importare i documenti."), {
id: toastId,
duration: Infinity,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
closeButton: true,
})
return
}
setSyncResult(result)
setDocumentsSync({ result })
const changes = [
result.imported.length ? plural(result.imported.length, "documento nuovo", "documenti nuovi") : null,
result.updated.length ? plural(result.updated.length, "aggiornato", "aggiornati") : null,
].filter(Boolean)
await refresh(
changes.length
? `Importazione completata: ${changes.join(", ")}.`
: "Importazione completata: nessun documento nuovo o cambiato."
: "Importazione completata: nessun documento nuovo o cambiato.",
toastId
)
setDocumentsSync({ running: false })
}

async function runRetry() {
Expand All @@ -131,8 +144,8 @@ export function DocumentsPage({ documents }: { documents: DocumentInfo[] }) {
right={
canManage ? (
<>
<Button variant="outline" className={buttonMotion} onClick={() => setSyncOpen(true)}>
<RefreshCw aria-hidden />
<Button variant="outline" className={buttonMotion} disabled={syncing} onClick={() => setSyncOpen(true)}>
{syncing ? <Spinner /> : <RefreshCw aria-hidden />}
Importa dal repository
</Button>
<Button className={buttonMotion} onClick={() => setNewOpen(true)}>
Expand Down Expand Up @@ -196,7 +209,9 @@ export function DocumentsPage({ documents }: { documents: DocumentInfo[] }) {
description="Legge documents.json e i sorgenti attuali del repository documents: registra i documenti nuovi e una nuova versione di quelli di sola consultazione cambiati. Le bozze aperte non si toccano."
confirmLabel="Importa"
cancelLabel="Annulla"
onConfirm={runSync}
onConfirm={async () => {
runSync().catch((error) => console.error(error))
}}
/>
<ConfirmDialog
open={retryOpen}
Expand All @@ -221,7 +236,7 @@ export function DocumentsPage({ documents }: { documents: DocumentInfo[] }) {
)
}

/** What the last import left out and why: it stays until the page is left, as it may need action. */
/** What the last import left out and why: it stays until the next import, as it may need action. */
function SkippedAlert({ result }: { result: SyncResult }) {
return (
<InlineAlert tone="warning">
Expand Down
33 changes: 33 additions & 0 deletions src/features/regulations/documents-sync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { useSyncExternalStore } from "react"

import type { SyncResult } from "./regulations.contract"

type DocumentsSync = { running: boolean; result: SyncResult | null }

const idle: DocumentsSync = { running: false, result: null }
let state = idle
const listeners = new Set<() => void>()

function subscribe(listener: () => void) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
}

/**
* The import reads the whole repository and runs in the background: it outlives the Documenti page, so
* leaving and coming back still shows it running, and then what it left out.
*/
export function useDocumentsSync() {
return useSyncExternalStore(
subscribe,
() => state,
() => idle
)
}

export function setDocumentsSync(next: Partial<DocumentsSync>) {
state = { ...state, ...next }
for (const listener of listeners) listener()
}
10 changes: 5 additions & 5 deletions src/features/regulations/regulations-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,20 @@ import { appToast } from "@/components/shell"
import { errorHasCode, errorMessage } from "@/lib/errors"

/**
* After a successful mutation: reload every loader, then confirm. A failed reload is not a failed mutation, so it
* warns instead of offering to repeat it.
* After a successful mutation: reload every loader, then confirm, in place of the toast `toastId` when given. A failed
* reload is not a failed mutation, so it warns instead of offering to repeat it.
*/
export function useRefreshAfter() {
const router = useRouter()
return async (message: string) => {
return async (message: string, toastId?: string | number) => {
try {
await router.invalidate({ sync: true })
} catch (caught) {
console.error(caught)
appToast.warning(`${message.replace(/\.$/, "")}, ma la pagina non si è aggiornata.`)
appToast.warning(`${message.replace(/\.$/, "")}, ma la pagina non si è aggiornata.`, { id: toastId })
return
}
appToast.success(message)
appToast.success(message, { id: toastId })
}
}

Expand Down
10 changes: 10 additions & 0 deletions src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,16 @@ tr:focus-visible {
color: var(--pn-danger-fg);
}

[data-sonner-toast].app-toast[data-type="loading"] [data-icon] {
color: var(--pn-fg-muted);
}

[data-sonner-toast].app-toast [data-close-button] {
border-color: var(--pn-line);
background: var(--pn-surface-raised);
color: var(--pn-fg-muted);
}

[data-sonner-toast].app-toast [data-button] {
height: 28px;
padding: 0 10px;
Expand Down
Loading