feat(assets): Upload-Button, Drag-and-drop und Einfügen im Editor
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
af499620f0
commit
a4ea00f8da
9 files changed
+266
-3
No files matched your search
@@ -0,0 +1,36 @@
|
||||
import './assets.less';
|
||||
import React, { useRef } from 'react';
|
||||
import cx from 'classnames';
|
||||
import { imageFiles, formatBytes } from './assetClient.js';
|
||||
|
||||
// Button in der Snippet-Bar (ADR 0004 §5): Dateiauswahl, Fortschritt und Fehlertexte direkt am Button.
|
||||
// Sichtbar nur bei Git-verknüpften Brews (assetUpload.available).
|
||||
const AssetUploadButton = ({ assetUpload })=>{
|
||||
const input = useRef(null);
|
||||
if(!assetUpload?.available) return null;
|
||||
const { cfg, busy, percent, name, errors, done, upload, dismiss } = assetUpload;
|
||||
const accept = cfg.types.map((t)=>`image/${t}`).join(',');
|
||||
|
||||
return (
|
||||
<div className='assetUpload'>
|
||||
<button className={cx('editorTool', 'assetUploadButton', { active: !busy })}
|
||||
disabled={busy}
|
||||
title={`Bild ins Git-Repository hochladen (${cfg.types.join(', ').toUpperCase()}, max. ${formatBytes(cfg.maxBytes)}). Auch per Drag-and-drop oder Einfügen. Hinweis: Metadaten (z. B. GPS) bleiben erhalten, Bilder sind über den Teilen-Link öffentlich.`}
|
||||
onClick={()=>input.current?.click()}>
|
||||
<i className={busy ? 'fas fa-spinner fa-spin' : 'fas fa-image'} />
|
||||
</button>
|
||||
<input ref={input} type='file' hidden multiple accept={accept}
|
||||
onChange={(e)=>{ const files = imageFiles(e.target.files); e.target.value = ''; upload(files); }} />
|
||||
{(busy || errors.length > 0 || done > 0) && (
|
||||
<div className={cx('assetUploadStatus', { error: errors.length > 0 })} role='status'>
|
||||
{busy && <span>„{name}“ wird hochgeladen{percent != null ? ` (${percent} %)` : ''} …</span>}
|
||||
{!busy && done > 0 && errors.length === 0 && <span>{done === 1 ? 'Bild eingefügt.' : `${done} Bilder eingefügt.`} Hinweis: Fotos können Metadaten (z. B. GPS) enthalten und sind über den Teilen-Link öffentlich.</span>}
|
||||
{!busy && errors.map((msg, i)=><span key={i}>{msg}</span>)}
|
||||
{!busy && <button className='dismiss' onClick={dismiss} title='Schließen'><i className='fas fa-times' /></button>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AssetUploadButton;
|
||||
@@ -0,0 +1,76 @@
|
||||
import request from '../../homebrew/utils/request-middleware.js';
|
||||
|
||||
// Client-Seite des Bild-Uploads (ADR 0004 §5). Reine Funktionen und dünne API-Hülle, ohne React.
|
||||
|
||||
export const MIME_TYPE = { 'image/png': 'png', 'image/jpeg': 'jpeg', 'image/gif': 'gif', 'image/webp': 'webp' };
|
||||
|
||||
const MIB = 1024 * 1024;
|
||||
export const formatBytes = (n)=>{
|
||||
if(n >= MIB) return `${+(n / MIB).toFixed(1)} MiB`;
|
||||
if(n >= 1024) return `${Math.round(n / 1024)} KiB`;
|
||||
return `${n} Byte`;
|
||||
};
|
||||
|
||||
// Vorabprüfung mit den Limits des Servers, spart den Upload. Der Server prüft ohnehin erneut.
|
||||
export const validateFile = (file, cfg)=>{
|
||||
const type = MIME_TYPE[file.type];
|
||||
if(!type || !cfg.types.includes(type))
|
||||
return `„${file.name}“: Dieser Dateityp ist nicht erlaubt. Erlaubt sind: ${cfg.types.join(', ').toUpperCase()}.`;
|
||||
if(file.size > cfg.maxBytes)
|
||||
return `„${file.name}“ ist zu groß (${formatBytes(file.size)}). Erlaubt sind höchstens ${formatBytes(cfg.maxBytes)}.`;
|
||||
if(file.size === 0) return `„${file.name}“ ist leer.`;
|
||||
return null;
|
||||
};
|
||||
|
||||
export const imageFiles = (fileList)=>Array.from(fileList ?? []).filter((f)=>f.type?.startsWith('image/'));
|
||||
|
||||
// Verständliche Meldung zu einem Fehler der API (A01–A07, G02–G05, G08, 412, 401)
|
||||
export const describeError = (err)=>{
|
||||
const code = err?.HBErrorCode;
|
||||
const msg = err?.message;
|
||||
if(err?.status === 412) return msg || 'Die Seite ist veraltet. Bitte neu laden.';
|
||||
if(err?.status === 401) return 'Bitte melde dich an und prüfe, ob du Autor dieses Brews bist.';
|
||||
if(code === 'G02') return 'Anmeldung am Git-Server fehlgeschlagen. Prüfe den Token der Verbindung (Schreibrecht nötig).';
|
||||
if(code === 'G03') return 'Repository oder Branch nicht gefunden.';
|
||||
if(code === 'G04') return 'Der Git-Server ist nicht erreichbar. Bitte später erneut versuchen.';
|
||||
if(code === 'G05') return 'Speichern im Repository gerade nicht möglich. Bitte erneut versuchen.';
|
||||
return msg || 'Das Bild konnte nicht hochgeladen werden.';
|
||||
};
|
||||
|
||||
const unwrap = (promise)=>promise.then((res)=>res.body).catch((err)=>{
|
||||
const body = err.response?.body ?? {};
|
||||
const e = new Error(body.message || err.message);
|
||||
e.status = err.response?.status;
|
||||
e.HBErrorCode = body.HBErrorCode;
|
||||
e.body = body;
|
||||
throw e;
|
||||
});
|
||||
|
||||
export const assetApi = {
|
||||
config : ()=>unwrap(request.get('/api/git/assets/config')),
|
||||
upload : (editId, file, { onProgress } = {})=>{
|
||||
const req = request.post(`/api/git/brews/${editId}/assets`)
|
||||
.set('Content-Type', file.type)
|
||||
.set('X-HB-Filename', encodeURIComponent(file.name || 'image'))
|
||||
.send(file);
|
||||
if(onProgress) req.on('progress', (e)=>{ if(e.direction === 'upload' && e.percent != null) onProgress(Math.round(e.percent)); });
|
||||
return unwrap(req);
|
||||
}
|
||||
};
|
||||
|
||||
// Dateien nacheinander hochladen. Liefert Markdown für alle erfolgreichen und die Fehlermeldungen.
|
||||
export const uploadFiles = async (editId, files, cfg, { api = assetApi, onProgress } = {})=>{
|
||||
const markdown = [];
|
||||
const errors = [];
|
||||
for (const [i, file] of files.entries()) {
|
||||
const invalid = validateFile(file, cfg);
|
||||
if(invalid) { errors.push(invalid); continue; }
|
||||
try {
|
||||
const res = await api.upload(editId, file, { onProgress: (p)=>onProgress?.({ index: i, total: files.length, percent: p, name: file.name }) });
|
||||
markdown.push(res.markdown ?? `![${file.name.replace(/\.[^.]+$/, '')}](${res.url})`);
|
||||
} catch (err) {
|
||||
errors.push(`„${file.name}“: ${describeError(err)}`);
|
||||
}
|
||||
}
|
||||
return { markdown, errors };
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
@import '@sharedStyles/core.less';
|
||||
|
||||
.assetUpload {
|
||||
position : relative;
|
||||
display : inline-block;
|
||||
.assetUploadStatus {
|
||||
position : absolute;
|
||||
z-index : 20;
|
||||
top : 100%;
|
||||
right : 0;
|
||||
display : grid;
|
||||
gap : 4px;
|
||||
width : 280px;
|
||||
padding : 8px 24px 8px 8px;
|
||||
font-size : 12px;
|
||||
color : white;
|
||||
background-color : #333333;
|
||||
&.error span { color : #ff9a9a; font-weight : 800; }
|
||||
.dismiss {
|
||||
position : absolute;
|
||||
top : 4px;
|
||||
right : 4px;
|
||||
color : white;
|
||||
cursor : pointer;
|
||||
background : none;
|
||||
border : none;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { gitApi } from '../git/gitApi.js';
|
||||
import { assetApi, imageFiles, uploadFiles } from './assetClient.js';
|
||||
|
||||
export const LINK_EVENT = 'hb:git-link-changed';
|
||||
|
||||
// Bild-Upload im Editor (ADR 0004 §5): Zustand für Button, Drag-and-drop und Einfügen aus der Zwischenablage.
|
||||
// `containerRef`: Wurzelelement des Editors, `inject(text)`: Text an der Cursorposition einfügen.
|
||||
export const useAssetUpload = ({ editId, containerRef, inject, active = true })=>{
|
||||
const [cfg, setCfg] = useState(null); // null: unbekannt/aus
|
||||
const [linked, setLinked] = useState(false);
|
||||
const [state, setState] = useState({ busy: false, percent: null, name: '', errors: [], done: 0 });
|
||||
const busyRef = useRef(false);
|
||||
|
||||
useEffect(()=>{
|
||||
let live = true;
|
||||
assetApi.config().then((c)=>live && setCfg(c.enabled ? c : null)).catch(()=>live && setCfg(null));
|
||||
return ()=>{ live = false; };
|
||||
}, []);
|
||||
|
||||
useEffect(()=>{
|
||||
if(!editId || !cfg) { setLinked(false); return; }
|
||||
let live = true;
|
||||
const refresh = ()=>gitApi.status(editId).then((s)=>live && setLinked(!!s.linked)).catch(()=>live && setLinked(false));
|
||||
refresh();
|
||||
window.addEventListener(LINK_EVENT, refresh);
|
||||
return ()=>{ live = false; window.removeEventListener(LINK_EVENT, refresh); };
|
||||
}, [editId, cfg]);
|
||||
|
||||
const available = !!(cfg && linked && editId);
|
||||
|
||||
const upload = useCallback(async (files)=>{
|
||||
if(!available || busyRef.current || !files.length) return;
|
||||
busyRef.current = true;
|
||||
setState({ busy: true, percent: 0, name: files[0].name, errors: [], done: 0 });
|
||||
const { markdown, errors } = await uploadFiles(editId, files, cfg, {
|
||||
onProgress : ({ percent, name })=>setState((s)=>({ ...s, percent, name }))
|
||||
});
|
||||
if(markdown.length) inject(`${markdown.join('\n')}\n`);
|
||||
busyRef.current = false;
|
||||
setState({ busy: false, percent: null, name: '', errors, done: markdown.length });
|
||||
}, [available, editId, cfg, inject]);
|
||||
|
||||
// Drag-and-drop und Einfügen im Text-Editor (Capture-Phase, vor CodeMirror). Nur Bilddateien, Text bleibt unberührt.
|
||||
useEffect(()=>{
|
||||
const root = containerRef?.current;
|
||||
if(!root || !available || !active) return;
|
||||
const inText = (e)=>!!e.target.closest?.('.codeEditor.brewText');
|
||||
const hasFiles = (dt)=>!!dt && (Array.from(dt.types ?? []).includes('Files') || dt.files?.length > 0);
|
||||
const onDragOver = (e)=>{
|
||||
if(inText(e) && hasFiles(e.dataTransfer)) { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }
|
||||
};
|
||||
const onDrop = (e)=>{
|
||||
if(!inText(e)) return;
|
||||
const files = imageFiles(e.dataTransfer?.files);
|
||||
if(!files.length) return;
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
upload(files);
|
||||
};
|
||||
const onPaste = (e)=>{
|
||||
if(!inText(e)) return;
|
||||
const files = imageFiles(e.clipboardData?.files);
|
||||
if(!files.length) return;
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
upload(files);
|
||||
};
|
||||
root.addEventListener('dragover', onDragOver, true);
|
||||
root.addEventListener('drop', onDrop, true);
|
||||
root.addEventListener('paste', onPaste, true);
|
||||
return ()=>{
|
||||
root.removeEventListener('dragover', onDragOver, true);
|
||||
root.removeEventListener('drop', onDrop, true);
|
||||
root.removeEventListener('paste', onPaste, true);
|
||||
};
|
||||
}, [containerRef, available, active, upload]);
|
||||
|
||||
const dismiss = useCallback(()=>setState((s)=>({ ...s, errors: [], done: 0 })), []);
|
||||
|
||||
return { available, cfg, upload, dismiss, ...state };
|
||||
};
|
||||
@@ -25,7 +25,7 @@ const GitNavItem = ({ brew, lastSavedTime, onLinkedChange })=>{
|
||||
}
|
||||
}, [status]);
|
||||
|
||||
useEffect(()=>{ onLinkedChange?.(!!status?.linked); }, [status?.linked]);
|
||||
useEffect(()=>{ onLinkedChange?.(!!status?.linked); window.dispatchEvent(new Event('hb:git-link-changed')); }, [status?.linked]); // zweiter Teil: ADR 0004 (Upload-Button)
|
||||
|
||||
if(!editId || !status) return null;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import CodeEditor from '@components/codeEditor/codeEditor.jsx';
|
||||
import SnippetBar from './snippetbar/snippetbar.jsx';
|
||||
import MetadataEditor from './metadataEditor/metadataEditor.jsx';
|
||||
import SettingsEditor from './settingsEditor/settingsEditor.jsx';
|
||||
import { useAssetUpload } from '../../fork/assets/useAssetUpload.js'; // [fork] ADR-0004
|
||||
|
||||
const EDITOR_THEME_KEY = 'HB_editor_theme';
|
||||
const EDITOR_SETTINGS_KEY = 'HB_edit_settings';
|
||||
@@ -167,6 +168,7 @@ const Editor = forwardRef(
|
||||
const handleInject = (injectText)=>{
|
||||
codeEditor.current?.injectText(injectText);
|
||||
};
|
||||
const assetUpload = useAssetUpload({ editId: brew.editId, containerRef: editor, inject: handleInject, active: view === 'text' }); // [fork] ADR-0004
|
||||
|
||||
const handleViewChange = (newView)=>{
|
||||
setMoveArrows(newView === 'text');
|
||||
@@ -389,6 +391,7 @@ const Editor = forwardRef(
|
||||
themeBundle={themeBundle}
|
||||
cursorPos={codeEditor.current?.getCursorPosition() || {}}
|
||||
updateBrew={updateBrew}
|
||||
assetUpload={assetUpload}
|
||||
/>
|
||||
|
||||
{renderEditor()}
|
||||
|
||||
@@ -264,7 +264,7 @@ const MetadataEditor = ({
|
||||
defaultValue={metadata.lang || ''}
|
||||
keepValueOnClose={true}
|
||||
placeholder='en'
|
||||
valuePatterns="^[a-z]{2,3}(-[A-Z][a-z]{3})?(-[A-Z]{2})?$"
|
||||
valuePatterns='^[a-z]{2,3}(-[A-Z][a-z]{3})?(-[A-Z]{2})?$'
|
||||
onSelect={(value)=>handleLanguage(value)}
|
||||
onEntry={(e)=>{
|
||||
e.target.setCustomValidity(''); //Clear the validation popup while typing
|
||||
|
||||
@@ -8,6 +8,7 @@ import cx from 'classnames';
|
||||
|
||||
import { loadHistory } from '../../utils/versionHistory.js';
|
||||
import { brewSnippetsToJSON } from '@shared/helpers.js';
|
||||
import AssetUploadButton from '../../../fork/assets/AssetUploadButton.jsx'; // [fork] ADR-0004
|
||||
|
||||
/*eslint-disable camelcase*/
|
||||
import Legacy5ePHB from '@themes/Legacy/5ePHB/snippets.js';
|
||||
@@ -46,7 +47,8 @@ const SnippetBar = ({
|
||||
formatCode = ()=>{},
|
||||
cursorPos = {},
|
||||
themeBundle = [],
|
||||
updateBrew = ()=>{}
|
||||
updateBrew = ()=>{},
|
||||
assetUpload = null // [fork] ADR-0004
|
||||
})=>{
|
||||
const [snippets, setSnippets] = useState([]);
|
||||
const [historyExists, setHistoryExists] = useState(false);
|
||||
@@ -216,6 +218,7 @@ const SnippetBar = ({
|
||||
onClick={formatCode} >
|
||||
<i className='fas fa-wand-magic-sparkles' />
|
||||
</button>
|
||||
{view === 'text' && <AssetUploadButton assetUpload={assetUpload} />}
|
||||
</div></>}
|
||||
|
||||
<div className='tabs'>
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { validateFile, describeError, uploadFiles, formatBytes } from '../../client/fork/assets/assetClient.js';
|
||||
|
||||
const cfg = { enabled: true, maxBytes: 1000, maxBytesPerBrew: 5000, types: ['png', 'jpeg'] };
|
||||
const file = (name, type, size)=>({ name, type, size });
|
||||
|
||||
describe('Asset-Client (ADR 0004 §5)', ()=>{
|
||||
test('Vorabprüfung: Typ, Größe, leer', ()=>{
|
||||
expect(validateFile(file('a.png', 'image/png', 10), cfg)).toBeNull();
|
||||
expect(validateFile(file('a.gif', 'image/gif', 10), cfg)).toMatch(/nicht erlaubt.*PNG, JPEG/);
|
||||
expect(validateFile(file('a.svg', 'image/svg+xml', 10), cfg)).toMatch(/nicht erlaubt/);
|
||||
expect(validateFile(file('a.png', 'image/png', 2048), cfg)).toMatch(/zu groß \(2 KiB\).*1000 Byte/);
|
||||
expect(validateFile(file('a.png', 'image/png', 0), cfg)).toMatch(/leer/);
|
||||
expect(formatBytes(5 * 1024 * 1024)).toBe('5 MiB');
|
||||
});
|
||||
|
||||
test('Fehlertexte für Server-Codes', ()=>{
|
||||
expect(describeError({ HBErrorCode: 'G02' })).toMatch(/Token/);
|
||||
expect(describeError({ HBErrorCode: 'G04' })).toMatch(/nicht erreichbar/);
|
||||
expect(describeError({ HBErrorCode: 'A03', message: 'Limit erreicht' })).toBe('Limit erreicht');
|
||||
expect(describeError({ status: 412, message: 'veraltet' })).toBe('veraltet');
|
||||
expect(describeError({})).toMatch(/nicht hochgeladen/);
|
||||
});
|
||||
|
||||
test('uploadFiles: Markdown der erfolgreichen, Fehler der übrigen, ungültige gar nicht erst senden', async ()=>{
|
||||
const api = { upload : jest.fn(async (id, f)=>{
|
||||
if(f.name === 'boese.png') throw Object.assign(new Error('Das Bild ist zu groß.'), { HBErrorCode: 'A01' });
|
||||
return { url: `/git-assets/s/${f.name}`, markdown: `` };
|
||||
}) };
|
||||
const res = await uploadFiles('e1', [file('ok.png', 'image/png', 5), file('boese.png', 'image/png', 5), file('x.gif', 'image/gif', 5)], cfg, { api });
|
||||
expect(res.markdown).toEqual(['']);
|
||||
expect(res.errors).toHaveLength(2);
|
||||
expect(res.errors[0]).toMatch(/boese.png.*zu groß/);
|
||||
expect(res.errors[1]).toMatch(/x.gif.*nicht erlaubt/);
|
||||
expect(api.upload).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user