Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(docs): upload images into a document
Pouzor6d6a91c970ff
diff --git a/docs/documentation.md b/docs/documentation.mdindex fbc2f46..660930b 100644--- a/docs/documentation.md+++ b/docs/documentation.md@@ -106,7 +106,15 @@ a draft taken against an older version is discarded, because replaying it wouldrevert a change made elsewhere.`/` at the start of a line opens the insert menu: the generated blocks above,-plus table, checklist, callout, wiki-link and date.+plus table, checklist, callout, wiki-link, date and image.++**Images** — `/image` opens a file dialog; dropping a file on the source or+pasting a screenshot does the same without the menu. The file goes to+`POST /api/v1/media/upload` and the editor writes ``+at the caret. PNG, JPEG and WebP, 10 MB each. The upload happens at once but the+document still saves only when you save it. A file is not tied to its document:+removing the markdown, or the document, leaves it on disk, and the `.md` export+carries the link, not the file.`[[` opens the link picker, anywhere in the line: filter by title, pick, and thefinished link is written for you. It offers documents only — a device with no@@ -273,6 +281,5 @@ into `localStorage` with no search and no history.## Not built yet-Export/import of the tree as `.md` files, a print/handbook view, an aggregated-open-tasks view, and image upload inside a document (would reuse-`api/routes/media.py`, full-mode only) — the planned second lot.+Import of a tree of `.md` files, a print/handbook view, an aggregated open-tasks+view, and bundling uploaded media into the export — the planned second lot.diff --git a/frontend/src/documentation/__tests__/DocEditorMedia.test.tsx b/frontend/src/documentation/__tests__/DocEditorMedia.test.tsxnew file mode 100644index 0000000..5fed6f4--- /dev/null+++ b/frontend/src/documentation/__tests__/DocEditorMedia.test.tsx@@ -0,0 +1,170 @@+import { useState } from 'react'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { toast } from 'sonner'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { mediaApi } from '@/api/client'+import { DocEditor } from '../components/DocEditor'++vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())+vi.mock('@/api/client', () => ({+ documentsApi: { block: vi.fn() },+ mediaApi: { upload: vi.fn() },+}))++const api = vi.mocked(mediaApi)++const png = (name = 'rack.png') => new File(['x'], name, { type: 'image/png' })+const source = () => screen.getByLabelText('Document source') as HTMLTextAreaElement++/** A stateful host, so the textarea really holds what was typed. */+function setupLive(initial = '') {+ const onChange = vi.fn()+ function Host() {+ const [body, setBody] = useState(initial)+ return (+ <DocEditor+ body={body}+ onChange={(next) => { onChange(next); setBody(next) }}+ onSave={vi.fn()}+ onCancel={vi.fn()}+ dirty+ saving={false}+ />+ )+ }+ render(<Host />)+ return { onChange }+}++const drop = (files: File[]) =>+ fireEvent.drop(source(), { dataTransfer: { files, types: ['Files'] } })++const paste = (files: File[], text = '') =>+ fireEvent.paste(source(), { clipboardData: { files, getData: () => text } })++beforeEach(() => {+ vi.clearAllMocks()+ api.upload.mockResolvedValue({ url: '/api/v1/media/abc.png', filename: 'abc.png' })+})++describe('DocEditor — media', () => {+ it('uploads the file picked from /image and puts it where the slash was', async () => {+ const user = userEvent.setup()+ setupLive()++ await user.click(source())+ await user.keyboard('Intro{Enter}/')+ await user.click(await screen.findByText('/image'))+ // The slash is gone before any file is chosen, so cancelling the dialog+ // leaves nothing behind.+ await waitFor(() => expect(source().value).toBe('Intro\n'))++ await user.upload(screen.getByLabelText('Upload an image'), png())++ await waitFor(() => expect(source().value).toBe('Intro\n'))+ expect(api.upload).toHaveBeenCalledTimes(1)+ })++ it('uploads a dropped image and inserts it at the caret', async () => {+ const user = userEvent.setup()+ setupLive()+ await user.click(source())+ await user.keyboard('Before ')++ drop([png()])++ await waitFor(() => expect(source().value).toBe('Before '))+ })++ it('puts each dropped file on a line of its own', async () => {+ api.upload+ .mockResolvedValueOnce({ url: '/api/v1/media/a.png', filename: 'a.png' })+ .mockResolvedValueOnce({ url: '/api/v1/media/b.png', filename: 'b.png' })+ setupLive()++ drop([png('front.png'), png('back.png')])++ await waitFor(() =>+ expect(source().value).toBe('\n'),+ )+ })++ it('uploads a pasted screenshot', async () => {+ setupLive()++ paste([png('image.png')])++ await waitFor(() => expect(source().value).toBe(''))+ })++ it('leaves a paste that carries text to the browser', () => {+ setupLive()++ // What a spreadsheet copies: the cells as text, and a picture of them.+ const handled = !paste([png()], 'a\tb')++ expect(handled).toBe(false)+ expect(api.upload).not.toHaveBeenCalled()+ })++ it('leaves a drop that carries no file to the browser', () => {+ setupLive()++ const handled = !fireEvent.drop(source(), { dataTransfer: { files: [], types: ['text/plain'] } })++ expect(handled).toBe(false)+ expect(api.upload).not.toHaveBeenCalled()+ })++ it('refuses an unsupported file without asking the server', async () => {+ const { onChange } = setupLive()++ drop([new File(['x'], 'notes.txt', { type: 'text/plain' })])++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Only PNG, JPEG or WebP can go in a document'))+ expect(api.upload).not.toHaveBeenCalled()+ expect(onChange).not.toHaveBeenCalled()+ })++ it('says why an upload failed and leaves the document alone', async () => {+ api.upload.mockRejectedValue({ response: { data: { detail: 'File too large (max 10 MB)' } } })+ const { onChange } = setupLive('text')++ drop([png()])++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('File too large (max 10 MB)'))+ expect(onChange).not.toHaveBeenCalled()+ expect(screen.queryByText('Inserting…')).not.toBeInTheDocument()+ })++ it('keeps the files that made it when a later one fails', async () => {+ api.upload+ .mockResolvedValueOnce({ url: '/api/v1/media/a.png', filename: 'a.png' })+ .mockRejectedValueOnce(new Error('network'))+ setupLive()++ drop([png('front.png'), png('back.png')])++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Upload failed'))+ expect(source().value).toBe('')+ })++ it('keeps what was typed while the file was uploading', async () => {+ const user = userEvent.setup()+ let finish: (value: { url: string; filename: string }) => void = () => {}+ api.upload.mockReturnValue(new Promise((resolve) => { finish = resolve }))+ setupLive()++ await user.click(source())+ await user.keyboard('a')+ drop([png()])+ expect(await screen.findByText('Inserting…')).toBeInTheDocument()+ await user.keyboard('b')++ finish({ url: '/api/v1/media/abc.png', filename: 'abc.png' })++ await waitFor(() => expect(source().value).toBe('ab'))+ })+})diff --git a/frontend/src/documentation/__tests__/media.test.ts b/frontend/src/documentation/__tests__/media.test.tsnew file mode 100644index 0000000..78eab7c--- /dev/null+++ b/frontend/src/documentation/__tests__/media.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest'++import { isSupportedMedia, mediaMarkdown, uploadError } from '../media'++const file = (name: string, type: string) => new File(['x'], name, { type })++describe('isSupportedMedia', () => {+ it('takes the image formats the server stores', () => {+ expect(isSupportedMedia(file('a.png', 'image/png'))).toBe(true)+ expect(isSupportedMedia(file('a.jpg', 'image/jpeg'))).toBe(true)+ expect(isSupportedMedia(file('a.webp', 'image/webp'))).toBe(true)+ })++ it('refuses everything else, an unknown type included', () => {+ expect(isSupportedMedia(file('a.gif', 'image/gif'))).toBe(false)+ expect(isSupportedMedia(file('a.txt', 'text/plain'))).toBe(false)+ expect(isSupportedMedia(file('a', ''))).toBe(false)+ })+})++describe('mediaMarkdown', () => {+ it('writes an image, named after the file without its extension', () => {+ expect(mediaMarkdown(file('rack.front.png', 'image/png'), '/api/v1/media/abc.png')).toBe(+ '',+ )+ })++ it('drops the brackets that would close the alt text early', () => {+ expect(mediaMarkdown(file('plan [v2].png', 'image/png'), '/u.png')).toBe('')+ })++ it('falls back to a plain alt when the name leaves nothing', () => {+ expect(mediaMarkdown(file('.png', 'image/png'), '/u.png')).toBe('')+ })+})++describe('uploadError', () => {+ it("relays the server's reason", () => {+ expect(uploadError({ response: { data: { detail: 'File too large (max 10 MB)' } } })).toBe(+ 'File too large (max 10 MB)',+ )+ })++ it('falls back when there is none to relay', () => {+ expect(uploadError(new Error('network'))).toBe('Upload failed')+ expect(uploadError({ response: { data: { detail: [{ msg: 'x' }] } } })).toBe('Upload failed')+ })+})diff --git a/frontend/src/documentation/components/DocEditor.tsx b/frontend/src/documentation/components/DocEditor.tsxindex 050769e..816417e 100644--- a/frontend/src/documentation/components/DocEditor.tsx+++ b/frontend/src/documentation/components/DocEditor.tsx@@ -1,9 +1,11 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { Bold, Italic, Link2, List, ListChecks, Save, Table, X } from 'lucide-react'+import { toast } from 'sonner'-import { documentsApi } from '@/api/client'+import { documentsApi, mediaApi } from '@/api/client'import { caretPoint, placeMenu, type CaretPoint, type Placement } from '@/documentation/caret'import { useDocHistory } from '@/documentation/history'+import { IMAGE_TYPES, SUPPORTED_LABEL, isSupportedMedia, mediaMarkdown, uploadError } from '@/documentation/media'import { Button } from '@/components/ui/button'import { cn } from '@/lib/utils'import { Markdown } from '../markdown/Markdown'@@ -72,6 +74,7 @@ export function DocEditor({devices = [],}: Props) {const textarea = useRef<HTMLTextAreaElement>(null)+ const fileInput = useRef<HTMLInputElement>(null)const pane = useRef<HTMLDivElement>(null)const caretRef = useRef<CaretPoint | null>(null)// Where the `/` that opened the menu sits in the body. Recorded on the way in@@ -107,7 +110,18 @@ export function DocEditor({},})): []- return [...generated, ...PLAIN_SNIPPETS]+ const image: SlashCommand = {+ id: 'image',+ label: '/image',+ hint: 'Upload an image — or drop or paste one',+ // Inserts nothing itself: it takes the `/` away and opens the file+ // dialog, and the picked file lands at the caret once it is uploaded.+ insert: () => {+ fileInput.current?.click()+ return ''+ },+ }+ return [...generated, ...PLAIN_SNIPPETS, image]}, [deviceId])const visible = useMemo(() => {@@ -182,6 +196,36 @@ export function DocEditor({[body, history, onChange],)+ // An upload outlives the render that started it. Inserting through the+ // callback captured back then would write over a stale body and lose+ // whatever was typed while the file was on its way.+ const insertLatest = useRef(insertAtCursor)+ useEffect(() => {+ insertLatest.current = insertAtCursor+ }, [insertAtCursor])++ /** Upload `files` and write their markdown at the caret. */+ const uploadFiles = useCallback(async (files: File[]) => {+ const accepted = files.filter(isSupportedMedia)+ if (accepted.length < files.length) toast.error(`Only ${SUPPORTED_LABEL} can go in a document`)+ if (accepted.length === 0) return+ setInserting(true)+ const uploaded: string[] = []+ try {+ for (const file of accepted) {+ const { url } = await mediaApi.upload(file)+ uploaded.push(mediaMarkdown(file, url))+ }+ } catch (error) {+ toast.error(uploadError(error))+ } finally {+ // What made it up is inserted even when a later file failed: it is on+ // the server either way, and unreferenced it would only be an orphan.+ if (uploaded.length > 0) insertLatest.current(uploaded.join('\n'), null)+ setInserting(false)+ }+ }, [])+const runCommand = useCallback(async (command: SlashCommand) => {// Read before the await: closing the menu lets the reset effect run.@@ -395,8 +439,40 @@ export function DocEditor({onChange(event.target.value)}}onKeyDown={handleKeyDown}+ onDragOver={(event) => {+ // Without this the browser navigates to the dropped file.+ if (event.dataTransfer.types.includes('Files')) event.preventDefault()+ }}+ onDrop={(event) => {+ const files = Array.from(event.dataTransfer.files)+ if (files.length === 0) return+ event.preventDefault()+ void uploadFiles(files)+ }}+ onPaste={(event) => {+ const files = Array.from(event.clipboardData.files)+ // A spreadsheet or a word processor copies a picture of the+ // selection beside its text; the text is what was meant.+ if (files.length === 0 || event.clipboardData.getData('text/plain')) return+ event.preventDefault()+ void uploadFiles(files)+ }}className="h-full w-full resize-none bg-transparent p-4 font-mono text-xs leading-relaxed outline-none"/>+ <input+ ref={fileInput}+ type="file"+ multiple+ accept={IMAGE_TYPES.join(',')}+ aria-label="Upload an image"+ className="hidden"+ onChange={(event) => {+ const files = Array.from(event.target.files ?? [])+ // Cleared so picking the same file twice in a row still fires.+ event.target.value = ''+ void uploadFiles(files)+ }}+ />{slashOpen && (<EditorMenuitems={visible}diff --git a/frontend/src/documentation/media.ts b/frontend/src/documentation/media.tsnew file mode 100644index 0000000..c57a1b4--- /dev/null+++ b/frontend/src/documentation/media.ts@@ -0,0 +1,34 @@+/**+ * What a document can embed, and the markdown an upload becomes.+ *+ * The list mirrors `ALLOWED_TYPES` in the backend's `api/routes/media.py`,+ * which stays the authority: checking here only spares a round trip and lets+ * the refusal name the formats instead of relaying a 415.+ */++export const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp']++/** The same list, as a sentence can carry it. */+export const SUPPORTED_LABEL = 'PNG, JPEG or WebP'++export function isSupportedMedia(file: File): boolean {+ return IMAGE_TYPES.includes(file.type)+}++/**+ * The markdown that shows an uploaded file.+ *+ * The alt text is the file name without its extension. Brackets are dropped+ * rather than escaped: they would close the alt early, and the source is meant+ * to stay readable.+ */+export function mediaMarkdown(file: File, url: string): string {+ const alt = file.name.replace(/\.[^.]+$/, '').replace(/[[\]\s]+/g, ' ').trim() || 'image'+ return ``+}++/** The server's own reason when it gave one — it names the limit that was hit. */+export function uploadError(error: unknown): string {+ const detail = (error as { response?: { data?: { detail?: unknown } } })?.response?.data?.detail+ return typeof detail === 'string' ? detail : 'Upload failed'+}