Bulk snooze, alert rules judged on report, photos on notes
Bulk snooze: Snooze... and Wake on the ticked alerts, with undo that puts back each alert's earlier snooze exactly. Alert rules are judged for a server right after its agent reports, instead of at the next 15-minute pass; only that server's rule findings change, and the check is serialized with the pass so neither overwrites the other's state. Photos on server and device notes: up to 12 each, shrunk in the browser, accepted by their own bytes (JPEG/PNG/GIF/WebP, 4 MB), kept in the database and removed with the server or device. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
251a4a9d73
commit
a16996d975
27 files changed
+8442
-54
No files matched your search
@@ -1454,6 +1454,15 @@ export interface NoteItem {
|
||||
updatedBy: string | null;
|
||||
updatedAt: string;
|
||||
}
|
||||
/** A photo on a note, without its bytes (those are at `api.notePhotos.imageUrl`). */
|
||||
export interface NotePhoto {
|
||||
id: number;
|
||||
caption: string | null;
|
||||
contentType: string;
|
||||
size: number;
|
||||
createdBy: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
export interface AgendaItem {
|
||||
id: string;
|
||||
kind: AgendaKind;
|
||||
@@ -2896,6 +2905,20 @@ export const api = {
|
||||
get: (targetType: "server" | "device", targetId: number) => request<{ note: NoteItem | null }>(`/api/notes?targetType=${targetType}&targetId=${targetId}`),
|
||||
save: (targetType: "server" | "device", targetId: number, body: string) => request<{ note: NoteItem | null }>("/api/notes", { method: "PUT", body: JSON.stringify({ targetType, targetId, body }) }),
|
||||
},
|
||||
notePhotos: {
|
||||
list: (targetType: "server" | "device", targetId: number) => request<{ photos: NotePhoto[] }>(`/api/note-photos?targetType=${targetType}&targetId=${targetId}`),
|
||||
/** The bytes are the body, as they are (the app makes them small first). */
|
||||
add: async (targetType: "server" | "device", targetId: number, photo: Blob): Promise<{ photo: NotePhoto }> => {
|
||||
const res = await fetch(`/api/note-photos?targetType=${targetType}&targetId=${targetId}`, { method: "POST", headers: { "Content-Type": photo.type || "application/octet-stream" }, body: photo, credentials: "same-origin" });
|
||||
if (res.status === 401) throw new UnauthorizedError("unauthorized");
|
||||
if (res.status === 403) throw new ForbiddenError("forbidden");
|
||||
if (!res.ok) throw new Error(`Request failed (${res.status}): ${await res.text().catch(() => "")}`);
|
||||
return (await res.json()) as { photo: NotePhoto };
|
||||
},
|
||||
setCaption: (id: number, caption: string | null) => request<{ photo: NotePhoto }>(`/api/note-photos/${id}`, { method: "PUT", body: JSON.stringify({ caption }) }),
|
||||
remove: (id: number) => request<void>(`/api/note-photos/${id}`, { method: "DELETE" }),
|
||||
imageUrl: (id: number) => `/api/note-photos/${id}/image`,
|
||||
},
|
||||
network: {
|
||||
overview: () => request<NetworkOverview>("/api/network"),
|
||||
sync: (integrationId?: number) => request<{ statuses: Record<number, UnifiSyncStatus> }>("/api/network/sync", { method: "POST", body: JSON.stringify(integrationId ? { integrationId } : {}) }),
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { api, type NotePhoto } from "../api/client";
|
||||
import { confirmDialog, promptDialog } from "../utils/dialogs";
|
||||
import { readableError } from "../utils/errors";
|
||||
import { shrinkPhoto } from "../utils/shrinkPhoto";
|
||||
import { toast } from "../utils/toast";
|
||||
import TimeAgo from "./TimeAgo";
|
||||
|
||||
/** Most photos on one note; the server enforces the same. */
|
||||
const MAX_PHOTOS = 12;
|
||||
|
||||
/** The picture, large, over the page. Esc or a click outside closes it; the arrow keys move between pictures. */
|
||||
function Viewer({ photos, index, canEdit, onMove, onClose, onChanged }: { photos: NotePhoto[]; index: number; canEdit: boolean; onMove: (to: number) => void; onClose: () => void; onChanged: () => void }) {
|
||||
const photo = photos[index];
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
else if (e.key === "ArrowLeft" && index > 0) onMove(index - 1);
|
||||
else if (e.key === "ArrowRight" && index < photos.length - 1) onMove(index + 1);
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [index, photos.length, onMove, onClose]);
|
||||
if (!photo) return null;
|
||||
|
||||
async function caption() {
|
||||
const value = await promptDialog({ title: "Caption", message: "What is in the picture?", defaultValue: photo.caption ?? "", confirmLabel: "Save" });
|
||||
if (value === null) return;
|
||||
try {
|
||||
await api.notePhotos.setCaption(photo.id, value.trim() === "" ? null : value);
|
||||
onChanged();
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
}
|
||||
}
|
||||
async function remove() {
|
||||
if (!(await confirmDialog({ title: "Remove the photo", message: "Remove this photo from the note?", confirmLabel: "Remove", danger: true }))) return;
|
||||
try {
|
||||
await api.notePhotos.remove(photo.id);
|
||||
onChanged();
|
||||
if (photos.length <= 1) onClose();
|
||||
else onMove(Math.min(index, photos.length - 2));
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modal modal-blur d-block" role="dialog" aria-modal="true" aria-label="Photo" style={{ background: "rgba(0,0,0,0.78)" }} onClick={onClose}>
|
||||
<div className="modal-dialog modal-xl modal-dialog-centered" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="modal-content">
|
||||
<div className="modal-body text-center">
|
||||
<img src={api.notePhotos.imageUrl(photo.id)} alt={photo.caption ?? "A photo on the note"} style={{ maxWidth: "100%", maxHeight: "70vh", objectFit: "contain" }} />
|
||||
<div className="mt-2">
|
||||
{photo.caption && <div className="fw-bold">{photo.caption}</div>}
|
||||
<div className="text-secondary small">
|
||||
{photo.createdBy ? `${photo.createdBy}, ` : ""}
|
||||
<TimeAgo value={photo.createdAt} /> · {Math.max(1, Math.round(photo.size / 1024))} kB · {index + 1} of {photos.length}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button type="button" className="btn" disabled={index === 0} onClick={() => onMove(index - 1)} aria-label="Previous photo">
|
||||
‹
|
||||
</button>
|
||||
<button type="button" className="btn" disabled={index >= photos.length - 1} onClick={() => onMove(index + 1)} aria-label="Next photo">
|
||||
›
|
||||
</button>
|
||||
{canEdit && (
|
||||
<>
|
||||
<button type="button" className="btn" onClick={() => void caption()}>
|
||||
Caption…
|
||||
</button>
|
||||
<button type="button" className="btn btn-outline-danger" onClick={() => void remove()}>
|
||||
Remove
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<button type="button" className="btn btn-primary ms-auto" onClick={onClose} autoFocus>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The photos on a note — the rack as it is, a cable's label, the back of the NAS. Everyone signed in sees them; operators add (from the camera or the files), caption and remove.
|
||||
* Each is made small in the browser before it is sent. Shown only when there is one, or when the person can add one.
|
||||
*/
|
||||
export default function NotePhotos({ targetType, targetId, canEdit }: { targetType: "server" | "device"; targetId: number; canEdit: boolean }) {
|
||||
const [photos, setPhotos] = useState<NotePhoto[] | null>(null);
|
||||
const [open, setOpen] = useState<number | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
|
||||
function load() {
|
||||
return api.notePhotos
|
||||
.list(targetType, targetId)
|
||||
.then((r) => setPhotos(r.photos))
|
||||
.catch(() => setPhotos([]));
|
||||
}
|
||||
useEffect(() => {
|
||||
setPhotos(null);
|
||||
setOpen(null);
|
||||
void load();
|
||||
}, [targetType, targetId]);
|
||||
|
||||
async function add(files: FileList | null) {
|
||||
if (!files || files.length === 0) return;
|
||||
setBusy(true);
|
||||
let added = 0;
|
||||
try {
|
||||
for (const file of Array.from(files)) {
|
||||
if ((photos?.length ?? 0) + added >= MAX_PHOTOS) {
|
||||
toast.error(`There can be at most ${MAX_PHOTOS} photos on a note.`);
|
||||
break;
|
||||
}
|
||||
try {
|
||||
await api.notePhotos.add(targetType, targetId, await shrinkPhoto(file));
|
||||
added += 1;
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
}
|
||||
}
|
||||
if (added > 0) toast.success(added === 1 ? "Photo added." : `${added} photos added.`);
|
||||
} finally {
|
||||
if (input.current) input.current.value = "";
|
||||
setBusy(false);
|
||||
await load();
|
||||
}
|
||||
}
|
||||
|
||||
if (photos === null) return null;
|
||||
if (photos.length === 0 && !canEdit) return null;
|
||||
return (
|
||||
<div className="mt-3">
|
||||
<div className="d-flex align-items-center mb-2">
|
||||
<div className="text-secondary small fw-bold">Photos{photos.length > 0 ? ` (${photos.length})` : ""}</div>
|
||||
{canEdit && (
|
||||
<>
|
||||
<input ref={input} type="file" accept="image/*" multiple className="d-none" onChange={(e) => void add(e.target.files)} aria-label="Choose photos to add" />
|
||||
<button type="button" className="btn btn-sm ms-auto" disabled={busy || photos.length >= MAX_PHOTOS} onClick={() => input.current?.click()}>
|
||||
{busy ? "Adding…" : "Add photo"}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{photos.length === 0 ? (
|
||||
<div className="text-secondary small">None yet — add a picture of the rack or of a label.</div>
|
||||
) : (
|
||||
<div className="d-flex flex-wrap gap-2">
|
||||
{photos.map((p, i) => (
|
||||
<button key={p.id} type="button" className="btn p-0 border-0 text-start" style={{ width: 112 }} onClick={() => setOpen(i)} aria-label={p.caption ? `Open the photo: ${p.caption}` : "Open the photo"}>
|
||||
<img src={api.notePhotos.imageUrl(p.id)} alt={p.caption ?? ""} loading="lazy" width={112} height={112} style={{ width: 112, height: 112, objectFit: "cover", borderRadius: 4, display: "block" }} />
|
||||
{p.caption && (
|
||||
<div className="text-secondary small text-truncate" style={{ maxWidth: 112 }}>
|
||||
{p.caption}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{open !== null && photos[open] && <Viewer photos={photos} index={open} canEdit={canEdit} onMove={setOpen} onClose={() => setOpen(null)} onChanged={() => void load()} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, type NoteItem } from "../api/client";
|
||||
import { BlockSkeleton } from "./Skeleton";
|
||||
import NotePhotos from "./NotePhotos";
|
||||
import RunbookText from "./RunbookText";
|
||||
import TimeAgo from "./TimeAgo";
|
||||
import { readableError } from "../utils/errors";
|
||||
@@ -79,10 +80,13 @@ export default function NotesCard({ targetType, targetId, canEdit, bare = false
|
||||
</button>
|
||||
) : null;
|
||||
|
||||
const photos = !failed && note !== undefined && draft === null ? <NotePhotos targetType={targetType} targetId={targetId} canEdit={canEdit} /> : null;
|
||||
|
||||
if (bare) {
|
||||
return (
|
||||
<>
|
||||
{body}
|
||||
{photos}
|
||||
{edit && <div className="mt-3">{edit}</div>}
|
||||
</>
|
||||
);
|
||||
@@ -93,7 +97,10 @@ export default function NotesCard({ targetType, targetId, canEdit, bare = false
|
||||
<h3 className="card-title">Notes</h3>
|
||||
{edit && <div className="card-actions">{edit}</div>}
|
||||
</div>
|
||||
<div className="card-body">{body}</div>
|
||||
<div className="card-body">
|
||||
{body}
|
||||
{photos}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -28,15 +28,9 @@ const localInput = (d: Date) => {
|
||||
/** What a snooze says in a few words for a table row. */
|
||||
export const snoozeWords = (s: NonNullable<AlertItem["snoozed"]>) => `snoozed until ${formatDateTime(new Date(s.until))}`;
|
||||
|
||||
/**
|
||||
* "Remind me then": hide an alert until a time. It is not maintenance — nothing is promised about the thing — it is only left alone, and announced again at that time if it is
|
||||
* still there. If it goes away in the meantime, it is simply gone.
|
||||
*/
|
||||
export default function SnoozeDrawer({ alert, onClose, onSaved }: { alert: AlertItem; onClose: () => void; onSaved: () => void }) {
|
||||
/** The choices: a few presets and a time of one's own. `onPick` gets the time chosen. */
|
||||
function SnoozeChoices({ intro, busy, error, onPick }: { intro: string; busy: boolean; error: string | null; onPick: (when: Date) => void }) {
|
||||
const [custom, setCustom] = useState(localInput(at(1)));
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const presets: { label: string; when: Date }[] = [
|
||||
{ label: "1 hour", when: new Date(Date.now() + 3600_000) },
|
||||
{ label: "4 hours", when: new Date(Date.now() + 4 * 3600_000) },
|
||||
@@ -44,6 +38,39 @@ export default function SnoozeDrawer({ alert, onClose, onSaved }: { alert: Alert
|
||||
{ label: "In 3 days, at 09:00", when: at(3) },
|
||||
{ label: "Next Monday at 09:00", when: nextMonday() },
|
||||
];
|
||||
const customDate = new Date(custom);
|
||||
return (
|
||||
<>
|
||||
<div className="text-secondary mb-3">{intro}</div>
|
||||
<ErrorNotice error={error} />
|
||||
<div className="list-group mb-3">
|
||||
{presets.map((p) => (
|
||||
<button key={p.label} type="button" className="list-group-item list-group-item-action d-flex justify-content-between" disabled={busy} onClick={() => onPick(p.when)}>
|
||||
<span>{p.label}</span>
|
||||
<span className="text-secondary">{formatDateTime(p.when)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<label className="form-label" htmlFor="snooze-custom">
|
||||
Or a time of your own
|
||||
</label>
|
||||
<div className="d-flex gap-2">
|
||||
<input id="snooze-custom" type="datetime-local" className="form-control" value={custom} onChange={(e) => setCustom(e.target.value)} />
|
||||
<button type="button" className="btn btn-primary" disabled={busy || Number.isNaN(customDate.getTime())} onClick={() => onPick(customDate)}>
|
||||
Snooze
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Remind me then": hide an alert until a time. It is not maintenance — nothing is promised about the thing — it is only left alone, and announced again at that time if it is
|
||||
* still there. If it goes away in the meantime, it is simply gone.
|
||||
*/
|
||||
export default function SnoozeDrawer({ alert, onClose, onSaved }: { alert: AlertItem; onClose: () => void; onSaved: () => void }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function snooze(when: Date) {
|
||||
setBusy(true);
|
||||
@@ -60,30 +87,27 @@ export default function SnoozeDrawer({ alert, onClose, onSaved }: { alert: Alert
|
||||
}
|
||||
}
|
||||
|
||||
const customDate = new Date(custom);
|
||||
return (
|
||||
<DetailDrawer title="Snooze" subtitle={alert.message} onClose={onClose}>
|
||||
<div className="text-secondary mb-3">
|
||||
Hide this until then. It is announced again at that time if it is still there; if it goes away before, it is just gone. Snoozing is not maintenance: nothing is promised about the thing.
|
||||
</div>
|
||||
<ErrorNotice error={error} />
|
||||
<div className="list-group mb-3">
|
||||
{presets.map((p) => (
|
||||
<button key={p.label} type="button" className="list-group-item list-group-item-action d-flex justify-content-between" disabled={busy} onClick={() => void snooze(p.when)}>
|
||||
<span>{p.label}</span>
|
||||
<span className="text-secondary">{formatDateTime(p.when)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<label className="form-label" htmlFor="snooze-custom">
|
||||
Or a time of your own
|
||||
</label>
|
||||
<div className="d-flex gap-2">
|
||||
<input id="snooze-custom" type="datetime-local" className="form-control" value={custom} onChange={(e) => setCustom(e.target.value)} />
|
||||
<button type="button" className="btn btn-primary" disabled={busy || Number.isNaN(customDate.getTime())} onClick={() => void snooze(customDate)}>
|
||||
Snooze
|
||||
</button>
|
||||
</div>
|
||||
<SnoozeChoices intro="Hide this until then. It is announced again at that time if it is still there; if it goes away before, it is just gone. Snoozing is not maintenance: nothing is promised about the thing." busy={busy} error={error} onPick={(when) => void snooze(when)} />
|
||||
</DetailDrawer>
|
||||
);
|
||||
}
|
||||
|
||||
/** The same for several alerts at once: `onSubmit` does it (and says how it went), and this closes when it has. */
|
||||
export function SnoozeBulkDrawer({ count, onSubmit, onClose }: { count: number; onSubmit: (when: Date) => Promise<void>; onClose: () => void }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
return (
|
||||
<DetailDrawer title={`Snooze ${count} alert${count === 1 ? "" : "s"}`} onClose={onClose}>
|
||||
<SnoozeChoices
|
||||
intro="Hide them all until then. Each is announced again at that time if it is still there; one that goes away before is just gone. Snoozing is not maintenance: nothing is promised about the things."
|
||||
busy={busy}
|
||||
error={null}
|
||||
onPick={(when) => {
|
||||
setBusy(true);
|
||||
void onSubmit(when).finally(() => setBusy(false));
|
||||
}}
|
||||
/>
|
||||
</DetailDrawer>
|
||||
);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import SilenceButton from "../components/SilenceButton";
|
||||
import RunPlaybookButton from "../components/RunPlaybookButton";
|
||||
import RunbookEntry from "../components/RunbookEntry";
|
||||
import AckDrawer, { ackWords } from "../components/AckDrawer";
|
||||
import SnoozeDrawer, { snoozeWords } from "../components/SnoozeDrawer";
|
||||
import SnoozeDrawer, { SnoozeBulkDrawer, snoozeWords } from "../components/SnoozeDrawer";
|
||||
import { useAlertsReport } from "../hooks/useAlertsReport";
|
||||
import { summariseAlerts } from "../utils/alertSummary";
|
||||
import { EmptyRow } from "../components/EmptyState";
|
||||
@@ -99,7 +99,7 @@ function AlertsNow({ user, tabs }: { user: CurrentUser; tabs: React.ReactNode })
|
||||
const [snoozing, setSnoozing] = useState<AlertItem | null>(null);
|
||||
// Alerts ticked for a bulk action, and which bulk form is open.
|
||||
const [picked, setPicked] = useState<Set<string>>(new Set());
|
||||
const [bulkForm, setBulkForm] = useState<"ack" | "silence" | null>(null);
|
||||
const [bulkForm, setBulkForm] = useState<"ack" | "silence" | "snooze" | null>(null);
|
||||
// Held-back alerts are nested under the one that explains them (on by default; remembered), and each parent opens to show them.
|
||||
const [grouped, setGrouped] = useState(() => {
|
||||
try {
|
||||
@@ -220,6 +220,17 @@ function AlertsNow({ user, tabs }: { user: CurrentUser; tabs: React.ReactNode })
|
||||
const ok = await doBulk({ call: api.bulk.alerts, body: { action: "unacknowledge", alertIds: pickedIds }, done: (r) => `${plural(r.changed, "acknowledgement")} removed.`, reload: afterBulk });
|
||||
if (ok) setPicked(new Set());
|
||||
}
|
||||
async function bulkSnooze(when: Date) {
|
||||
const ok = await doBulk({ call: api.bulk.alerts, body: { action: "snooze", alertIds: pickedIds, until: when.toISOString() }, done: (r) => `${plural(r.changed, "alert")} snoozed until ${formatDateTime(when)}.`, reload: afterBulk });
|
||||
if (ok) {
|
||||
setBulkForm(null);
|
||||
setPicked(new Set());
|
||||
}
|
||||
}
|
||||
async function bulkWake() {
|
||||
const ok = await doBulk({ call: api.bulk.alerts, body: { action: "unsnooze", alertIds: pickedIds }, done: (r) => `${plural(r.changed, "alert")} woken.`, reload: afterBulk });
|
||||
if (ok) setPicked(new Set());
|
||||
}
|
||||
async function bulkSilence(v: { minutes: number; reason: string }) {
|
||||
const ok = await doBulk({ call: api.bulk.alerts, body: { action: "silence", alertIds: pickedIds, minutes: v.minutes, reason: v.reason }, done: (r) => `${plural(r.changed, "thing")} put under maintenance.`, reload: afterBulk });
|
||||
if (ok) {
|
||||
@@ -586,6 +597,12 @@ function AlertsNow({ user, tabs }: { user: CurrentUser; tabs: React.ReactNode })
|
||||
<button type="button" className="btn btn-sm" onClick={() => void bulkUnack()}>
|
||||
Remove acknowledgement
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" onClick={() => setBulkForm("snooze")}>
|
||||
Snooze…
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" onClick={() => void bulkWake()}>
|
||||
Wake
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" onClick={() => setBulkForm("silence")}>
|
||||
Silence…
|
||||
</button>
|
||||
@@ -593,6 +610,7 @@ function AlertsNow({ user, tabs }: { user: CurrentUser; tabs: React.ReactNode })
|
||||
</>
|
||||
)}
|
||||
{bulkForm === "ack" && <AckBulkDrawer count={pickedIds.length} onSubmit={bulkAck} onClose={() => setBulkForm(null)} />}
|
||||
{bulkForm === "snooze" && <SnoozeBulkDrawer count={pickedIds.length} onSubmit={bulkSnooze} onClose={() => setBulkForm(null)} />}
|
||||
{bulkForm === "silence" && <SilenceBulkDrawer noun={pickedIds.length === 1 ? "alert" : "alerts"} count={pickedIds.length} canSilenceDependents={false} onSubmit={bulkSilence} onClose={() => setBulkForm(null)} />}
|
||||
|
||||
{snoozing && <SnoozeDrawer alert={snoozing} onClose={() => setSnoozing(null)} onSaved={() => { void load(true); reloadBadge(); }} />}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/** The most a photo may be, on its longer side, and the most the app will send (the server's own limit is 4 MB). */
|
||||
export const MAX_EDGE = 1600;
|
||||
export const MAX_SEND_BYTES = 3.5 * 1024 * 1024;
|
||||
|
||||
const canvasToBlob = (canvas: HTMLCanvasElement, type: string, quality: number) => new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, type, quality));
|
||||
|
||||
/**
|
||||
* Makes a photo small before it is sent: a phone's picture is several megabytes, and 1600 pixels on the long side, as a JPEG, is a few hundred kilobytes and enough to read a label.
|
||||
* The way the phone was held is honoured (EXIF orientation), and the picture is drawn again, which also leaves out where it was taken. A GIF is sent as it is (so it still moves) and
|
||||
* a small PNG too (a screenshot stays sharp); one that cannot be drawn (a format the browser does not know) is sent as it is if it is small enough, and refused with a reason if not.
|
||||
*/
|
||||
export async function shrinkPhoto(file: File): Promise<Blob> {
|
||||
if (file.type === "image/gif") {
|
||||
if (file.size > MAX_SEND_BYTES) throw new Error("That GIF is too big — keep it under 3 MB.");
|
||||
return file;
|
||||
}
|
||||
if (file.type === "image/png" && file.size <= 1.5 * 1024 * 1024) return file;
|
||||
let bitmap: ImageBitmap;
|
||||
try {
|
||||
bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
|
||||
} catch {
|
||||
if (["image/jpeg", "image/png", "image/webp"].includes(file.type) && file.size <= MAX_SEND_BYTES) return file;
|
||||
throw new Error("This browser could not read that picture. Try a JPEG or a PNG.");
|
||||
}
|
||||
try {
|
||||
const scale = Math.min(1, MAX_EDGE / Math.max(bitmap.width, bitmap.height));
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
|
||||
canvas.height = Math.max(1, Math.round(bitmap.height * scale));
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) throw new Error("This browser could not draw that picture.");
|
||||
ctx.fillStyle = "#ffffff"; // a transparent picture becomes white rather than black
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
||||
for (const quality of [0.85, 0.7, 0.55]) {
|
||||
const blob = await canvasToBlob(canvas, "image/jpeg", quality);
|
||||
if (blob && blob.size <= MAX_SEND_BYTES) return blob;
|
||||
}
|
||||
throw new Error("That picture is still too big after making it smaller.");
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user