diff --git a/src/app/App.tsx b/src/app/App.tsx index 509653de..f738eee3 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -4,6 +4,7 @@ import Footer from '@/components/brand/Footer' import HomeRoute from './routes/HomeRoute' import NewReportRoute from './routes/NewReportRoute' import EditorRoute from './routes/EditorRoute' +import SvgEditorRoute from './routes/SvgEditorRoute' import NotFoundRoute from './routes/NotFoundRoute' export default function App() { @@ -16,6 +17,7 @@ export default function App() { } /> } /> } /> + } /> } /> diff --git a/src/app/routes/SvgEditorRoute.tsx b/src/app/routes/SvgEditorRoute.tsx new file mode 100644 index 00000000..7d133493 --- /dev/null +++ b/src/app/routes/SvgEditorRoute.tsx @@ -0,0 +1,1664 @@ +import { useEffect, useRef } from 'react' +import { Link } from 'react-router-dom' +import '@/styles/svg-editor.css' + +export default function SvgEditorRoute() { + const canvasRef = useRef(null) + const canvasInnerRef = useRef(null) + const sidebarRef = useRef(null) + const cleanupRef = useRef<(() => void) | null>(null) + + useEffect(() => { + const meta = document.createElement('meta') + meta.name = 'robots' + meta.content = 'noindex,nofollow' + document.head.appendChild(meta) + return () => { + document.head.removeChild(meta) + } + }, []) + + useEffect(() => { + const canvas = canvasRef.current + const canvasInner = canvasInnerRef.current + const sidebar = sidebarRef.current + if (!canvas || !canvasInner || !sidebar) return + + initSvgEditor(canvas, canvasInner, sidebar) + + return () => { + if (cleanupRef.current) cleanupRef.current() + } + }, []) + + return ( + + + + + + + + + + + ← + + + SVG Anatomy Editor + Points, zones & clickable categories + + + + + + + File + + + Export SVG + + + + + Mode + + Select / move + + + Add point + + + Add polygon + + + Close polygon (Enter) + Cancel (Esc) + + Category for new elements + + + + + + Categories (shared color) + + + + + + + + + + + + + + Selected element + + — + + + + + + This zone opens a detail view + + + Detail view ID (e.g. head, front-leg) + + + + + + French name + + English name + + Category + + Radius (circle) + + + + + + + Fill opacity + + + + + + + + Polygon editing: + + Drag a yellow handle to move it + + Click a white mid-handle to insert a vertex + + Alt+click or right-click a yellow handle to delete it + + Redraw this polygon + + + + Delete + + + + + + + Elements (0) + + + + + + + + ) +} + +function initSvgEditor( + canvas: HTMLDivElement, + canvasInner: HTMLDivElement, + _sidebar: HTMLDivElement, +) { + let mode = 'select' + let selected: SVGElement | null = null + let polygonPoints: number[][] = [] + let dragging: SVGElement | null = null + let draggingHandle: { + vIdx: number + points: number[][] + originalPoint: number[] + polygon: SVGElement + } | null = null + let dragStart: { + x: number + y: number + snap?: ReturnType + siblingSnaps?: { el: SVGElement; snap: ReturnType }[] + } | null = null + let zoom = 1 + let svgRoot: SVGSVGElement | null = null + + const CATEGORY_TEMPLATES: Record = { + articulation: { color: '#fb5607', name: 'Articulations' }, + charniere: { color: '#d00000', name: 'Charnières vertébrales' }, + 'cadran-crane': { color: '#06a77d', name: 'Cadrans du crâne' }, + 'os-overlay': { color: '#f72585', name: 'Os overlay' }, + 'spine-zone': { color: '#7209b7', name: 'Zones colonne' }, + } + let CATEGORIES: Record< + string, + { color: string; name: string; visible: boolean; special?: string } + > = {} + + const DETAIL_ZONE_STYLE = { + fill: '#808080', + fillOpacity: '0.20', + stroke: '#606060', + strokeWidth: '2', + strokeDasharray: '8,4', + } + + const SPECIAL_BEHAVIORS = [ + { id: 'vertebral-precision', desc: 'Specify which vertebrae are involved' }, + { id: 'joint-detail', desc: 'Detail a joint (mobility, pain, etc.)' }, + ] + + const zoomContainer = document.getElementById('svg-editor-zoom-controls') + if (zoomContainer) { + zoomContainer.textContent = '' + const btnIn = document.createElement('button') + btnIn.textContent = '+' + btnIn.addEventListener('click', () => { + zoom *= 1.2 + applyZoom() + }) + const btnOut = document.createElement('button') + btnOut.textContent = '−' + btnOut.addEventListener('click', () => { + zoom /= 1.2 + applyZoom() + }) + const btnReset = document.createElement('button') + btnReset.textContent = '⌂' + btnReset.addEventListener('click', () => { + zoom = 1 + applyZoom() + }) + zoomContainer.append(btnIn, btnOut, btnReset) + } + + setupGlobalListeners() + setupGlobalDragDrop() + showWelcomeScreen() + + function showWelcomeScreen() { + canvasInner.textContent = '' + const welcome = document.createElement('div') + welcome.className = 'welcome' + welcome.id = 'svg-editor-welcome' + + const icon = document.createElement('div') + icon.className = 'welcome-icon' + icon.textContent = '📐' + + const h2 = document.createElement('h2') + h2.textContent = 'SVG Anatomy Editor' + + const p = document.createElement('p') + p.textContent = 'Upload an SVG file to begin. If your file already has points/zones with ' + const code1 = document.createElement('code') + code1.textContent = 'data-anno-id' + const code2 = document.createElement('code') + code2.textContent = 'data-anno-category' + p.appendChild(code1) + p.appendChild(document.createTextNode(' and ')) + p.appendChild(code2) + p.appendChild(document.createTextNode(', they will be detected and configured automatically.')) + + const btn = document.createElement('button') + btn.className = 'primary welcome-btn' + btn.textContent = 'Choose an SVG file' + btn.addEventListener('click', () => { + const fi = document.getElementById('svg-editor-file-import') as HTMLInputElement | null + fi?.click() + }) + + const hint = document.createElement('div') + hint.className = 'welcome-hint' + hint.textContent = 'or drag & drop an SVG file anywhere' + + welcome.append(icon, h2, p, btn, hint) + canvasInner.appendChild(welcome) + + svgRoot = null + CATEGORIES = {} + selected = null + dragging = null + draggingHandle = null + refreshCategoryList() + refreshCategorySelects() + getEl('svg-editor-count').textContent = '0' + getEl('svg-editor-element-list').textContent = '' + getEl('svg-editor-edit-section').style.display = 'none' + } + + function setupGlobalDragDrop() { + canvas.addEventListener('dragover', (e) => { + e.preventDefault() + canvas.classList.add('dragging-over') + }) + canvas.addEventListener('dragleave', (e) => { + if (e.target === canvas) canvas.classList.remove('dragging-over') + }) + canvas.addEventListener('drop', (e) => { + e.preventDefault() + canvas.classList.remove('dragging-over') + const file = e.dataTransfer?.files[0] + if (file && (file.name.endsWith('.svg') || file.type === 'image/svg+xml')) { + const reader = new FileReader() + reader.onload = (ev) => loadSVG(ev.target?.result as string) + reader.readAsText(file, 'UTF-8') + } else { + alert('Drop an SVG file.') + } + }) + } + + function loadSVG(svgText: string) { + const parser = new DOMParser() + const doc = parser.parseFromString(svgText, 'image/svg+xml') + const parsedSvg = doc.querySelector('svg') + if (!parsedSvg) { + alert('Invalid file: no SVG element found.') + showWelcomeScreen() + return + } + + canvasInner.textContent = '' + canvasInner.appendChild(document.importNode(parsedSvg, true)) + svgRoot = canvasInner.querySelector('svg') + if (!svgRoot) { + alert('Invalid file: no SVG element found.') + showWelcomeScreen() + return + } + + if (!svgRoot.getAttribute('viewBox')) { + const wAttr = svgRoot.getAttribute('width') + const hAttr = svgRoot.getAttribute('height') + const w = wAttr ? parseFloat(wAttr) : 1000 + const h = hAttr ? parseFloat(hAttr) : 1000 + svgRoot.setAttribute('viewBox', `0 0 ${w} ${h}`) + } + + svgRoot.removeAttribute('width') + svgRoot.removeAttribute('height') + svgRoot.style.width = '100%' + svgRoot.style.height = 'auto' + svgRoot.style.maxWidth = '100%' + + CATEGORIES = {} + selected = null + dragging = null + draggingHandle = null + zoom = 1 + + migrateOldAttributes() + normalizeDetailZones() + fixDuplicateIds() + detectCategories() + applyAllCategoryColors() + + setupSVGListeners() + refreshCategoryList() + refreshCategorySelects() + refreshElementList() + } + + function normalizeDetailZones() { + if (!svgRoot) return + svgRoot.querySelectorAll('[data-anno-opens-detail]').forEach((el) => { + el.classList.add('detail-zone') + if (el.getAttribute('fill') !== 'transparent') { + el.setAttribute('fill', DETAIL_ZONE_STYLE.fill) + if (!el.getAttribute('fill-opacity')) { + el.setAttribute('fill-opacity', DETAIL_ZONE_STYLE.fillOpacity) + } + if (el.tagName.toLowerCase() === 'polygon') { + el.setAttribute('stroke', DETAIL_ZONE_STYLE.stroke) + if (!el.getAttribute('stroke-dasharray')) { + el.setAttribute('stroke-dasharray', DETAIL_ZONE_STYLE.strokeDasharray) + } + } + } + }) + } + + function migrateOldAttributes() { + if (!svgRoot) return + const MIGRATIONS: [string, string][] = [ + ['data-bone-id', 'data-anno-id'], + ['data-bone-fr', 'data-anno-name-fr'], + ['data-bone-en', 'data-anno-name-en'], + ['data-category', 'data-anno-category'], + ['data-opens-detail', 'data-anno-opens-detail'], + ] + MIGRATIONS.forEach(([oldAttr, newAttr]) => { + svgRoot!.querySelectorAll(`[${oldAttr}]`).forEach((el) => { + if (!el.hasAttribute(newAttr)) { + el.setAttribute(newAttr, el.getAttribute(oldAttr)!) + } + el.removeAttribute(oldAttr) + }) + }) + } + + function fixDuplicateIds() { + if (!svgRoot) return + const byId: Record> = {} + svgRoot.querySelectorAll('[data-anno-id]').forEach((el) => { + const id = el.getAttribute('data-anno-id')! + const cat = el.getAttribute('data-anno-category') || 'unknown' + if (!byId[id]) byId[id] = {} + if (!byId[id][cat]) byId[id][cat] = [] + byId[id][cat].push(el) + }) + + for (const [id, byCat] of Object.entries(byId)) { + const cats = Object.keys(byCat) + if (cats.length > 1) { + cats.slice(1).forEach((cat) => { + const newId = id + '-' + cat + byCat[cat].forEach((el) => { + el.setAttribute('data-anno-id', newId) + if (el.getAttribute('id') === id) el.setAttribute('id', newId) + }) + }) + } + } + } + + function detectCategories() { + if (!svgRoot) return + svgRoot.querySelectorAll('[data-anno-category]').forEach((el) => { + const cat = el.getAttribute('data-anno-category')! + const special = el.getAttribute('data-anno-special') || '' + const storedName = el.getAttribute('data-anno-category-name') || '' + + if (CATEGORIES[cat]) { + if (special && !CATEGORIES[cat].special) { + CATEGORIES[cat].special = special + } + if (storedName && CATEGORIES[cat].name === cat) { + CATEGORIES[cat].name = storedName + } + return + } + + if (CATEGORY_TEMPLATES[cat]) { + CATEGORIES[cat] = { ...CATEGORY_TEMPLATES[cat], visible: true } + } else { + const sample = svgRoot!.querySelector( + `[data-anno-category="${cat}"]:not([fill="transparent"])`, + ) + const fill = sample ? sample.getAttribute('fill') : null + const color = fill && fill.startsWith('#') ? fill : '#00aaff' + CATEGORIES[cat] = { color, name: storedName || cat, visible: true } + } + if (special) CATEGORIES[cat].special = special + }) + } + + function applyAllCategoryColors() { + if (!svgRoot) return + for (const [cat, info] of Object.entries(CATEGORIES)) { + svgRoot.querySelectorAll(`[data-anno-category="${cat}"]`).forEach((el) => { + if (el.getAttribute('fill') === 'transparent') return + el.setAttribute('fill', info.color) + if (el.tagName.toLowerCase() === 'polygon') { + el.setAttribute('stroke', info.color) + } + }) + } + } + + function setupSVGListeners() { + if (!svgRoot) return + svgRoot.addEventListener('click', svgClickHandler) + svgRoot.addEventListener('mousedown', svgMousedownHandler) + svgRoot.addEventListener('contextmenu', svgContextMenuHandler) + } + + function svgClickHandler(e: MouseEvent) { + if (mode === 'point') { + const p = getSVGPoint(e) + addCircleAt(p.x, p.y) + e.stopPropagation() + } else if (mode === 'polygon') { + const p = getSVGPoint(e) + polygonPoints.push([p.x, p.y]) + updatePolygonPreview() + e.stopPropagation() + } else if (mode === 'select') { + const target = e.target as Element + const midhandle = target.closest('.polygon-midhandle') + if (midhandle && selected && selected.tagName.toLowerCase() === 'polygon') { + const edgeIdx = parseInt(midhandle.getAttribute('data-edge-idx')!) + const points = parsePoints(selected.getAttribute('points')!) + const p = getSVGPoint(e) + points.splice(edgeIdx + 1, 0, [p.x, p.y]) + selected.setAttribute('points', pointsToStr(points)) + showPolygonHandles(selected) + e.stopPropagation() + return + } + if (target.closest('.polygon-handle')) { + e.stopPropagation() + return + } + const annoTarget = target.closest('[data-anno-id]') as SVGElement | null + if (annoTarget) { + selectElement(annoTarget) + e.stopPropagation() + } else { + deselect() + } + } + } + + function svgContextMenuHandler(e: MouseEvent) { + if ((e.target as Element).closest('.polygon-handle')) { + e.preventDefault() + } + } + + function svgMousedownHandler(e: MouseEvent) { + if (mode !== 'select') return + + const target = e.target as Element + const handle = target.closest('.polygon-handle') + if (handle && selected && selected.tagName.toLowerCase() === 'polygon') { + const vIdx = parseInt(handle.getAttribute('data-vertex-idx')!) + const points = parsePoints(selected.getAttribute('points')!) + + if (e.altKey || e.button === 2) { + if (points.length > 3) { + points.splice(vIdx, 1) + selected.setAttribute('points', pointsToStr(points)) + showPolygonHandles(selected) + } else { + alert('A polygon must have at least 3 vertices.') + } + e.preventDefault() + e.stopPropagation() + return + } + + const p = getSVGPoint(e) + draggingHandle = { + vIdx, + points, + originalPoint: [...points[vIdx]], + polygon: selected, + } + dragStart = { x: p.x, y: p.y } + e.preventDefault() + e.stopPropagation() + return + } + + if (target.classList.contains('polygon-midhandle')) { + return + } + + const annoTarget = target.closest('[data-anno-id]') as SVGElement | null + if (!annoTarget) return + selectElement(annoTarget) + dragging = annoTarget + const p = getSVGPoint(e) + const id = annoTarget.getAttribute('data-anno-id')! + const cat = annoTarget.getAttribute('data-anno-category') + const parent = annoTarget.parentNode as Element | null + const siblingSnaps: { el: SVGElement; snap: ReturnType }[] = [] + if (parent) { + parent.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`).forEach((sib) => { + if (sib === annoTarget) return + if (sib.getAttribute('data-anno-category') !== cat) return + const snap = snapshotPosition(sib as SVGElement) + if (snap) siblingSnaps.push({ el: sib as SVGElement, snap }) + }) + } + dragStart = { + x: p.x, + y: p.y, + snap: snapshotPosition(annoTarget), + siblingSnaps, + } + e.preventDefault() + } + + function onMouseMove(e: MouseEvent) { + if (draggingHandle) { + const p = getSVGPoint(e) + const dx = p.x - dragStart!.x + const dy = p.y - dragStart!.y + const newPoint = [ + draggingHandle.originalPoint[0] + dx, + draggingHandle.originalPoint[1] + dy, + ] + draggingHandle.points[draggingHandle.vIdx] = newPoint + draggingHandle.polygon.setAttribute( + 'points', + pointsToStr(draggingHandle.points), + ) + showPolygonHandles(draggingHandle.polygon) + return + } + + if (!dragging) return + const p = getSVGPoint(e) + const dx = p.x - dragStart!.x + const dy = p.y - dragStart!.y + moveElement(dragging, dx, dy, dragStart!.snap!) + dragStart!.siblingSnaps?.forEach(({ el: sibEl, snap }) => { + moveElement(sibEl, dx, dy, snap!) + }) + if (dragging === selected && dragging.tagName.toLowerCase() === 'polygon') { + showPolygonHandles(dragging) + } + updateCoordsDisplay() + } + + function onMouseUp() { + dragging = null + draggingHandle = null + dragStart = null + } + + function onKeyDown(e: KeyboardEvent) { + const tag = (e.target as Element).tagName + if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA') return + if (e.key === 'Enter' && mode === 'polygon') finalizePolygon() + if (e.key === 'Escape') { + if (mode === 'polygon') cancelPolygon() + else deselect() + } + if (e.key === 'Delete' && selected) deleteSelected() + if (e.key === '1') setMode('select') + if (e.key === '2') setMode('point') + if (e.key === '3') setMode('polygon') + } + + function setupGlobalListeners() { + document.addEventListener('mousemove', onMouseMove) + document.addEventListener('mouseup', onMouseUp) + document.addEventListener('keydown', onKeyDown) + + getEl('svg-editor-filter-input').addEventListener('input', refreshElementList) + + ;['svg-editor-edit-fr', 'svg-editor-edit-en', 'svg-editor-edit-category'].forEach( + (id) => { + getEl(id).addEventListener('change', applyEdit) + }, + ) + + function syncSliderNum(rangeId: string, numId: string) { + const range = getEl(rangeId) as HTMLInputElement + const num = getEl(numId) as HTMLInputElement + range.addEventListener('input', () => { + num.value = range.value + if (selected) applyEdit() + }) + num.addEventListener('input', () => { + const v = parseFloat(num.value) + if (!isNaN(v)) { + range.value = String( + Math.max(parseFloat(range.min), Math.min(parseFloat(range.max), v)), + ) + } + if (selected) applyEdit() + }) + } + syncSliderNum('svg-editor-edit-radius', 'svg-editor-edit-radius-num') + syncSliderNum('svg-editor-edit-opacity', 'svg-editor-edit-opacity-num') + + ;(getEl('svg-editor-edit-opens-detail') as HTMLInputElement).addEventListener( + 'change', + () => { + const checked = (getEl('svg-editor-edit-opens-detail') as HTMLInputElement).checked + getEl('svg-editor-detail-target-row').style.display = checked ? 'block' : 'none' + getEl('svg-editor-osteo-fields').style.display = checked ? 'none' : 'block' + applyEdit() + }, + ) + getEl('svg-editor-edit-detail-target').addEventListener('change', applyEdit) + getEl('svg-editor-edit-detail-target').addEventListener('input', () => { + if (selected) applyEdit() + }) + + ;(getEl('svg-editor-file-import') as HTMLInputElement).addEventListener('change', (e) => { + const file = (e.target as HTMLInputElement).files?.[0] + if (!file) return + const reader = new FileReader() + reader.onload = (ev) => loadSVG(ev.target?.result as string) + reader.readAsText(file, 'UTF-8') + ;(e.target as HTMLInputElement).value = '' + }) + + getEl('svg-editor-export-btn').addEventListener('click', exportSVG) + + getEl('svg-editor-mode-select').addEventListener('click', () => setMode('select')) + getEl('svg-editor-mode-point').addEventListener('click', () => setMode('point')) + getEl('svg-editor-mode-polygon').addEventListener('click', () => setMode('polygon')) + getEl('svg-editor-finalize-polygon').addEventListener('click', finalizePolygon) + getEl('svg-editor-cancel-polygon').addEventListener('click', cancelPolygon) + getEl('svg-editor-add-cat-btn').addEventListener('click', addCategory) + getEl('svg-editor-delete-btn').addEventListener('click', deleteSelected) + getEl('svg-editor-restart-polygon').addEventListener('click', restartCurrentPolygon) + } + + function getEl(id: string): HTMLElement { + return document.getElementById(id) as HTMLElement + } + + function getSVGPoint(evt: MouseEvent) { + const pt = svgRoot!.createSVGPoint() + pt.x = evt.clientX + pt.y = evt.clientY + return pt.matrixTransform(svgRoot!.getScreenCTM()!.inverse()) + } + + function setMode(m: string) { + if (!svgRoot && (m === 'point' || m === 'polygon')) { + alert('Upload an SVG first.') + return + } + mode = m + canvas.className = 'svg-editor-canvas mode-' + m + document.querySelectorAll('[data-mode]').forEach((b) => { + b.classList.toggle('active', (b as HTMLElement).dataset.mode === m) + }) + getEl('svg-editor-polygon-controls').style.display = m === 'polygon' ? 'block' : 'none' + if (m !== 'polygon') cancelPolygon() + if (m !== 'select') { + deselect() + hidePolygonHandles() + } + } + + function snapshotPosition(svgEl: SVGElement) { + const tag = svgEl.tagName.toLowerCase() + if (tag === 'circle' || tag === 'ellipse') + return { + type: tag, + cx: parseFloat(svgEl.getAttribute('cx')!), + cy: parseFloat(svgEl.getAttribute('cy')!), + points: '', + } + if (tag === 'polygon') + return { type: 'polygon', cx: 0, cy: 0, points: svgEl.getAttribute('points')! } + return null + } + + function moveElement( + svgEl: SVGElement, + dx: number, + dy: number, + snap: NonNullable>, + ) { + if (snap.type === 'circle' || snap.type === 'ellipse') { + svgEl.setAttribute('cx', String(snap.cx + dx)) + svgEl.setAttribute('cy', String(snap.cy + dy)) + } else if (snap.type === 'polygon') { + const pts = snap.points + .split(/\s+/) + .filter((p: string) => p) + .map((p: string) => { + const [x, y] = p.split(',').map(Number) + return [(x + dx).toFixed(1), (y + dy).toFixed(1)] + }) + svgEl.setAttribute('points', pts.map((p: string[]) => p.join(',')).join(' ')) + } + } + + function cssEscape(s: string) { + return CSS.escape ? CSS.escape(s) : s.replace(/[^a-zA-Z0-9_-]/g, '\\$&') + } + + function selectElement(svgEl: SVGElement) { + deselect() + selected = svgEl + svgEl.classList.add('selected') + const id = svgEl.getAttribute('data-anno-id')! + const cat = svgEl.getAttribute('data-anno-category') + const parent = svgEl.parentNode as Element | null + if (parent) { + parent.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`).forEach((s) => { + if (s.getAttribute('data-anno-category') === cat) { + s.classList.add('selected') + } + }) + } + showEditPanel(svgEl) + if (svgEl.tagName.toLowerCase() === 'polygon') { + showPolygonHandles(svgEl) + } + refreshElementList() + } + + function deselect() { + document.querySelectorAll('.selected').forEach((svgEl) => svgEl.classList.remove('selected')) + hidePolygonHandles() + selected = null + getEl('svg-editor-edit-section').style.display = 'none' + refreshElementList() + } + + function showEditPanel(svgEl: SVGElement) { + getEl('svg-editor-edit-section').style.display = 'block' + ;(getEl('svg-editor-edit-fr') as HTMLInputElement).value = + svgEl.getAttribute('data-anno-name-fr') || '' + ;(getEl('svg-editor-edit-en') as HTMLInputElement).value = + svgEl.getAttribute('data-anno-name-en') || '' + ;(getEl('svg-editor-edit-category') as HTMLSelectElement).value = + svgEl.getAttribute('data-anno-category') || 'custom' + + const id = svgEl.getAttribute('data-anno-id')! + const cat = svgEl.getAttribute('data-anno-category') + const parent = svgEl.parentNode as Element | null + let visibleEl: SVGElement = svgEl + if (parent && id) { + const sibs = parent.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`) + sibs.forEach((s) => { + if ( + s.getAttribute('data-anno-category') === cat && + s.getAttribute('fill') !== 'transparent' + ) { + visibleEl = s as SVGElement + } + }) + } + + const opa = parseFloat(visibleEl.getAttribute('fill-opacity') || '0.65') + const opaPct = Math.round(opa * 100) + ;(getEl('svg-editor-edit-opacity') as HTMLInputElement).value = String(opaPct) + ;(getEl('svg-editor-edit-opacity-num') as HTMLInputElement).value = String(opaPct) + + const tag = svgEl.tagName.toLowerCase() + const radBlock = getEl('svg-editor-lbl-radius') + const radRow = getEl('svg-editor-radius-row') + const visibleTag = visibleEl.tagName.toLowerCase() + if (visibleTag === 'circle') { + radBlock.style.display = 'block' + radRow.style.display = 'flex' + const r = parseFloat(visibleEl.getAttribute('r') || '15') + ;(getEl('svg-editor-edit-radius') as HTMLInputElement).value = String(r) + ;(getEl('svg-editor-edit-radius-num') as HTMLInputElement).value = String(r) + } else { + radBlock.style.display = 'none' + radRow.style.display = 'none' + } + + const polyActions = getEl('svg-editor-polygon-edit-actions') + if (polyActions) polyActions.style.display = tag === 'polygon' ? 'block' : 'none' + + const opensDetail = + visibleEl.getAttribute('data-anno-opens-detail') || + svgEl.getAttribute('data-anno-opens-detail') || + '' + const checkbox = getEl('svg-editor-edit-opens-detail') as HTMLInputElement + const detailInput = getEl('svg-editor-edit-detail-target') as HTMLInputElement + const detailRow = getEl('svg-editor-detail-target-row') + const detailBlock = getEl('svg-editor-detail-toggle-block') + + const osteoFields = getEl('svg-editor-osteo-fields') + if (tag === 'polygon') { + detailBlock.style.display = 'block' + checkbox.checked = !!opensDetail + detailInput.value = opensDetail + detailRow.style.display = opensDetail ? 'block' : 'none' + osteoFields.style.display = opensDetail ? 'none' : 'block' + } else { + detailBlock.style.display = 'none' + checkbox.checked = false + detailInput.value = '' + osteoFields.style.display = 'block' + } + + updateCoordsDisplay() + } + + function updateCoordsDisplay() { + if (!selected) return + const tag = selected.tagName.toLowerCase() + let txt = '' + if (tag === 'circle' || tag === 'ellipse') { + txt = `cx=${Math.round(parseFloat(selected.getAttribute('cx')!))}, cy=${Math.round(parseFloat(selected.getAttribute('cy')!))}` + } else if (tag === 'polygon') { + const pts = selected + .getAttribute('points')! + .split(/\s+/) + .filter((p) => p).length + txt = `polygon (${pts} vertices)` + } + getEl('svg-editor-coords-display').textContent = txt + } + + function applyEdit() { + if (!selected) return + const fr = (getEl('svg-editor-edit-fr') as HTMLInputElement).value.trim() + const en = (getEl('svg-editor-edit-en') as HTMLInputElement).value.trim() + const cat = (getEl('svg-editor-edit-category') as HTMLSelectElement).value + const opacityPct = (getEl('svg-editor-edit-opacity') as HTMLInputElement).value + const opacity = (parseFloat(opacityPct) / 100).toString() + const radius = (getEl('svg-editor-edit-radius') as HTMLInputElement).value + + const oldId = selected.getAttribute('data-anno-id')! + const oldCat = selected.getAttribute('data-anno-category') + const parent = selected.parentNode as Element | null + const siblings = parent + ? Array.from(parent.querySelectorAll(`[data-anno-id="${cssEscape(oldId)}"]`)).filter( + (s) => s.getAttribute('data-anno-category') === oldCat, + ) + : [selected] + + const opensDetailEnabled = (getEl('svg-editor-edit-opens-detail') as HTMLInputElement).checked + const detailTarget = (getEl('svg-editor-edit-detail-target') as HTMLInputElement).value.trim() + + siblings.forEach((s) => { + if (opensDetailEnabled && detailTarget) { + s.setAttribute('data-anno-opens-detail', detailTarget) + s.removeAttribute('data-anno-name-fr') + s.removeAttribute('data-anno-name-en') + s.removeAttribute('data-anno-category') + s.removeAttribute('data-anno-category-name') + s.removeAttribute('data-anno-special') + } else { + s.removeAttribute('data-anno-opens-detail') + s.removeAttribute('stroke-dasharray') + if (fr) s.setAttribute('data-anno-name-fr', fr) + if (en) s.setAttribute('data-anno-name-en', en) + if (cat) { + s.setAttribute('data-anno-category', cat) + if (CATEGORIES[cat]?.name) { + s.setAttribute('data-anno-category-name', CATEGORIES[cat].name) + } + const catSpecial = CATEGORIES[cat]?.special + if (catSpecial?.trim()) { + s.setAttribute('data-anno-special', catSpecial.trim()) + } else { + s.removeAttribute('data-anno-special') + } + } + } + + if (opensDetailEnabled && detailTarget) { + let title = s.querySelector(':scope > title') as SVGTitleElement | null + if (!title) { + title = document.createElementNS('http://www.w3.org/2000/svg', 'title') as SVGTitleElement + s.insertBefore(title, s.firstChild) + } + title.textContent = 'Zoom: ' + detailTarget + if (s.getAttribute('fill') !== 'transparent') { + s.setAttribute('fill', DETAIL_ZONE_STYLE.fill) + s.setAttribute('fill-opacity', opacity || DETAIL_ZONE_STYLE.fillOpacity) + if (s.tagName.toLowerCase() === 'polygon') { + s.setAttribute('stroke', DETAIL_ZONE_STYLE.stroke) + s.setAttribute('stroke-width', DETAIL_ZONE_STYLE.strokeWidth) + s.setAttribute('stroke-dasharray', DETAIL_ZONE_STYLE.strokeDasharray) + } + } + s.classList.add('detail-zone') + } else { + s.classList.remove('detail-zone') + let title = s.querySelector(':scope > title') as SVGTitleElement | null + if (!title) { + title = document.createElementNS('http://www.w3.org/2000/svg', 'title') as SVGTitleElement + s.insertBefore(title, s.firstChild) + } + title.textContent = (fr || '') + (en ? ' / ' + en : '') + + if (s.getAttribute('fill') !== 'transparent' && cat && CATEGORIES[cat]) { + s.setAttribute('fill', CATEGORIES[cat].color) + if (s.tagName.toLowerCase() === 'polygon') { + s.setAttribute('stroke', CATEGORIES[cat].color) + } + } + if (opacity && s.getAttribute('fill') !== 'transparent') + s.setAttribute('fill-opacity', opacity) + + const stag = s.tagName.toLowerCase() + if (stag === 'circle' && radius) { + if (s.getAttribute('fill') === 'transparent') { + s.setAttribute('r', String(Math.max(1, parseFloat(radius) + 12))) + } else { + s.setAttribute('r', radius) + } + } + } + }) + + refreshElementList() + refreshCategoryList() + } + + function deleteSelected() { + if (!selected) return + if (!confirm('Delete this element?')) return + const id = selected.getAttribute('data-anno-id')! + const cat = selected.getAttribute('data-anno-category') + const parent = selected.parentNode as Element | null + if (parent) { + parent.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`).forEach((s) => { + if (s.getAttribute('data-anno-category') === cat) s.parentNode?.removeChild(s) + }) + } + selected = null + getEl('svg-editor-edit-section').style.display = 'none' + refreshElementList() + refreshCategoryList() + } + + function addCircleAt(x: number, y: number) { + if (!svgRoot) return + const cat = (getEl('svg-editor-default-category') as HTMLSelectElement).value || 'custom' + const color = CATEGORIES[cat]?.color || '#00aaff' + + let overlayG = svgRoot.querySelector('#osteo-overlays') + if (!overlayG) { + overlayG = document.createElementNS('http://www.w3.org/2000/svg', 'g') + overlayG.setAttribute('id', 'osteo-overlays') + svgRoot.appendChild(overlayG) + } + + const id = 'point-' + Date.now().toString(36) + + const hit = document.createElementNS('http://www.w3.org/2000/svg', 'circle') + hit.setAttribute('cx', String(Math.round(x))) + hit.setAttribute('cy', String(Math.round(y))) + hit.setAttribute('r', '28') + hit.setAttribute('fill', 'transparent') + hit.setAttribute('pointer-events', 'all') + hit.setAttribute('data-anno-id', id) + hit.setAttribute('data-anno-name-fr', 'Nouveau point') + hit.setAttribute('data-anno-name-en', 'New point') + hit.setAttribute('data-anno-category', cat) + if (CATEGORIES[cat]?.name) hit.setAttribute('data-anno-category-name', CATEGORIES[cat].name) + if (CATEGORIES[cat]?.special) hit.setAttribute('data-anno-special', CATEGORIES[cat].special!) + hit.setAttribute('style', 'cursor:pointer') + const t1 = document.createElementNS('http://www.w3.org/2000/svg', 'title') + t1.textContent = 'Nouveau point' + hit.appendChild(t1) + overlayG.appendChild(hit) + + const vis = document.createElementNS('http://www.w3.org/2000/svg', 'circle') + vis.setAttribute('cx', String(Math.round(x))) + vis.setAttribute('cy', String(Math.round(y))) + vis.setAttribute('r', '16') + vis.setAttribute('fill', color) + vis.setAttribute('fill-opacity', '0.65') + vis.setAttribute('stroke', '#000') + vis.setAttribute('stroke-width', '1.5') + vis.setAttribute('pointer-events', 'none') + vis.setAttribute('id', id) + vis.setAttribute('data-anno-id', id) + vis.setAttribute('data-anno-name-fr', 'Nouveau point') + vis.setAttribute('data-anno-name-en', 'New point') + vis.setAttribute('data-anno-category', cat) + if (CATEGORIES[cat]?.name) vis.setAttribute('data-anno-category-name', CATEGORIES[cat].name) + if (CATEGORIES[cat]?.special) vis.setAttribute('data-anno-special', CATEGORIES[cat].special!) + const t2 = document.createElementNS('http://www.w3.org/2000/svg', 'title') + t2.textContent = 'Nouveau point' + vis.appendChild(t2) + overlayG.appendChild(vis) + + setMode('select') + selectElement(hit as unknown as SVGElement) + refreshElementList() + refreshCategoryList() + setTimeout(() => (getEl('svg-editor-edit-fr') as HTMLInputElement).focus(), 50) + } + + function updatePolygonPreview() { + if (!svgRoot) return + svgRoot + .querySelectorAll('.polygon-preview, .polygon-preview-pt') + .forEach((p) => p.remove()) + if (polygonPoints.length < 1) return + + if (polygonPoints.length >= 2) { + const poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon') + poly.setAttribute('points', polygonPoints.map((p) => p.join(',')).join(' ')) + poly.classList.add('polygon-preview') + poly.setAttribute('pointer-events', 'none') + svgRoot.appendChild(poly) + } + polygonPoints.forEach(([x, y]) => { + const pt = document.createElementNS('http://www.w3.org/2000/svg', 'circle') + pt.setAttribute('cx', String(x)) + pt.setAttribute('cy', String(y)) + pt.setAttribute('r', '6') + pt.classList.add('polygon-preview-pt') + pt.setAttribute('pointer-events', 'none') + svgRoot!.appendChild(pt) + }) + } + + let _polygonRestartMemo: { + id: string + fr: string + en: string + cat: string + fill: string + fillOpacity: string + stroke: string + strokeWidth: string + } | null = null + + function finalizePolygon() { + if (!svgRoot) return + if (polygonPoints.length < 3) { + alert('Need at least 3 points.') + return + } + + const memo = _polygonRestartMemo + _polygonRestartMemo = null + + const cat = memo + ? memo.cat + : (getEl('svg-editor-default-category') as HTMLSelectElement).value || 'custom' + const color = memo ? memo.fill : CATEGORIES[cat]?.color || '#00aaff' + + let overlayG = svgRoot.querySelector('#osteo-overlays') + if (!overlayG) { + overlayG = document.createElementNS('http://www.w3.org/2000/svg', 'g') + overlayG.setAttribute('id', 'osteo-overlays') + svgRoot.appendChild(overlayG) + } + + const id = memo ? memo.id : 'zone-' + Date.now().toString(36) + const poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon') + poly.setAttribute( + 'points', + polygonPoints.map((p) => p.map(Math.round).join(',')).join(' '), + ) + poly.setAttribute('fill', color) + poly.setAttribute('fill-opacity', memo ? memo.fillOpacity || '0.30' : '0.30') + poly.setAttribute('stroke', memo ? memo.stroke || color : color) + poly.setAttribute('stroke-width', memo ? memo.strokeWidth || '2' : '2') + poly.setAttribute('pointer-events', 'all') + poly.setAttribute('style', 'cursor:pointer') + poly.setAttribute('id', id) + poly.setAttribute('data-anno-id', id) + poly.setAttribute('data-anno-name-fr', memo ? memo.fr || 'Nouvelle zone' : 'Nouvelle zone') + poly.setAttribute('data-anno-name-en', memo ? memo.en || 'New zone' : 'New zone') + poly.setAttribute('data-anno-category', cat) + if (CATEGORIES[cat]?.name) + poly.setAttribute('data-anno-category-name', CATEGORIES[cat].name) + if (CATEGORIES[cat]?.special) + poly.setAttribute('data-anno-special', CATEGORIES[cat].special!) + const t = document.createElementNS('http://www.w3.org/2000/svg', 'title') + t.textContent = + poly.getAttribute('data-anno-name-fr') + ' / ' + poly.getAttribute('data-anno-name-en') + poly.appendChild(t) + overlayG.appendChild(poly) + + cancelPolygon() + setMode('select') + selectElement(poly as unknown as SVGElement) + refreshElementList() + refreshCategoryList() + if (!memo) setTimeout(() => (getEl('svg-editor-edit-fr') as HTMLInputElement).focus(), 50) + } + + function cancelPolygon() { + polygonPoints = [] + svgRoot + ?.querySelectorAll('.polygon-preview, .polygon-preview-pt') + .forEach((p) => p.remove()) + } + + function refreshCategoryList() { + const list = getEl('svg-editor-category-list') + + const activeEl = document.activeElement as HTMLElement | null + if (activeEl && list.contains(activeEl)) { + list.querySelectorAll('.cat-row').forEach((row) => { + const cat = (row as HTMLElement).dataset.cat! + const countEl = row.querySelector('.count') + if (countEl && svgRoot) { + const n = svgRoot.querySelectorAll( + `[data-anno-category="${cat}"]:not([fill="transparent"])`, + ).length + countEl.textContent = String(n) + } + }) + return + } + + list.textContent = '' + + if (Object.keys(CATEGORIES).length === 0) { + const emptyMsg = document.createElement('div') + emptyMsg.style.cssText = 'font-size:12px; color:var(--color-ink-muted); padding:8px; text-align:center;' + emptyMsg.textContent = 'No categories yet. Use the form below to add one.' + list.appendChild(emptyMsg) + return + } + + for (const [cat, info] of Object.entries(CATEGORIES)) { + const count = svgRoot + ? svgRoot.querySelectorAll(`[data-anno-category="${cat}"]:not([fill="transparent"])`).length + : 0 + + const hasSpecial = !!(info.special?.trim()) + const row = document.createElement('div') + row.className = 'cat-row' + row.dataset.cat = cat + + const chk = document.createElement('input') + chk.type = 'checkbox' + chk.checked = info.visible + chk.title = 'Visibility' + + const colorInput = document.createElement('input') + colorInput.type = 'color' + colorInput.value = info.color + colorInput.title = 'Color' + + const nameSpan = document.createElement('span') + nameSpan.className = 'name' + nameSpan.title = cat + nameSpan.textContent = info.name + + const countSpan = document.createElement('span') + countSpan.className = 'count' + countSpan.textContent = String(count) + + const specialBtn = document.createElement('button') + specialBtn.className = 'special-btn' + (hasSpecial ? ' has-value' : '') + specialBtn.title = 'Special behavior' + specialBtn.textContent = '⚡' + + const delBtn = document.createElement('button') + delBtn.className = 'delete' + delBtn.title = 'Delete category' + delBtn.textContent = '×' + + row.append(chk, colorInput, nameSpan) + if (hasSpecial) { + const badge = document.createElement('span') + badge.className = 'special-badge' + badge.title = 'Behavior: ' + (info.special || '') + badge.textContent = '⚡ ' + (info.special || '') + row.appendChild(badge) + } + row.append(countSpan, specialBtn, delBtn) + + chk.addEventListener('change', () => { + info.visible = chk.checked + canvasInner.classList.toggle('hide-' + cat, !info.visible) + }) + + colorInput.addEventListener('change', () => { + info.color = colorInput.value + svgRoot?.querySelectorAll(`[data-anno-category="${cat}"]`).forEach((svgEl) => { + if (svgEl.getAttribute('fill') === 'transparent') return + svgEl.setAttribute('fill', info.color) + if (svgEl.tagName.toLowerCase() === 'polygon') { + svgEl.setAttribute('stroke', info.color) + } + }) + refreshElementList() + }) + + nameSpan.addEventListener('click', () => { + const newName = prompt('Rename category:', info.name) + if (newName?.trim()) { + info.name = newName.trim() + svgRoot?.querySelectorAll(`[data-anno-category="${cat}"]`).forEach((svgEl) => { + svgEl.setAttribute('data-anno-category-name', info.name) + }) + refreshCategoryList() + refreshCategorySelects() + } + }) + + specialBtn.addEventListener('click', () => openSpecialDialog(cat)) + delBtn.addEventListener('click', () => deleteCategory(cat)) + + list.appendChild(row) + } + } + + function refreshCategorySelects() { + const def = getEl('svg-editor-default-category') as HTMLSelectElement + const editSel = getEl('svg-editor-edit-category') as HTMLSelectElement + const defVal = def.value + const editVal = editSel.value + + def.textContent = '' + editSel.textContent = '' + + for (const [cat, info] of Object.entries(CATEGORIES)) { + const opt1 = document.createElement('option') + opt1.value = cat + opt1.textContent = info.name + ' (' + cat + ')' + def.appendChild(opt1) + + const opt2 = document.createElement('option') + opt2.value = cat + opt2.textContent = info.name + ' (' + cat + ')' + editSel.appendChild(opt2) + } + + if (defVal) def.value = defVal + if (editVal) editSel.value = editVal + } + + function openSpecialDialog(catId: string) { + const info = CATEGORIES[catId] + if (!info) return + const current = info.special || '' + + const lines = SPECIAL_BEHAVIORS.map((b, i) => `${i + 1}. ${b.id} — ${b.desc}`).join('\n') + const txt = `Special behavior for category "${info.name}". + +Suggestions: +${lines} + +Type a name (suggested or custom), or leave empty to remove. +Current: ${current || '(none)'}` + + const result = prompt(txt, current) + if (result === null) return + + const trimmed = result.trim() + info.special = trimmed + + svgRoot?.querySelectorAll(`[data-anno-category="${catId}"]`).forEach((svgEl) => { + if (trimmed) { + svgEl.setAttribute('data-anno-special', trimmed) + } else { + svgEl.removeAttribute('data-anno-special') + } + }) + + refreshCategoryList() + refreshElementList() + } + + function addCategory() { + const name = (getEl('svg-editor-new-cat-name') as HTMLInputElement).value.trim() + const color = (getEl('svg-editor-new-cat-color') as HTMLInputElement).value + if (!name) { + alert('Give the category a name.') + return + } + const slug = name + .toLowerCase() + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, '') + if (!slug) { + alert('Invalid name.') + return + } + + if (CATEGORIES[slug]) { + alert('This category already exists.') + return + } + + CATEGORIES[slug] = { color, name, visible: true } + ;(getEl('svg-editor-new-cat-name') as HTMLInputElement).value = '' + refreshCategoryList() + refreshCategorySelects() + } + + function deleteCategory(cat: string) { + if (!svgRoot) return + const count = svgRoot.querySelectorAll( + `[data-anno-category="${cat}"]:not([fill="transparent"])`, + ).length + let msg = `Delete category "${CATEGORIES[cat].name}"?` + if (count > 0) msg += `\n\nIt contains ${count} element(s) that will also be deleted.` + if (!confirm(msg)) return + + svgRoot.querySelectorAll(`[data-anno-category="${cat}"]`).forEach((svgEl) => { + svgEl.parentNode?.removeChild(svgEl) + }) + + delete CATEGORIES[cat] + refreshCategoryList() + refreshCategorySelects() + refreshElementList() + } + + function refreshElementList() { + if (!svgRoot) return + const filter = ((getEl('svg-editor-filter-input') as HTMLInputElement).value || '').toLowerCase() + const seen = new Set() + const items: { + id: string + fr: string + cat: string + catName: string + color: string + detail: string + }[] = [] + + svgRoot.querySelectorAll('[data-anno-id]').forEach((svgEl) => { + const id = svgEl.getAttribute('data-anno-id')! + if (seen.has(id)) return + const cat = svgEl.getAttribute('data-anno-category') || '' + seen.add(id) + + const fr = svgEl.getAttribute('data-anno-name-fr') || '' + const catName = CATEGORIES[cat] ? CATEGORIES[cat].name : cat || 'no cat.' + + if ( + filter && + !id.toLowerCase().includes(filter) && + !fr.toLowerCase().includes(filter) && + !catName.toLowerCase().includes(filter) + ) + return + + const visibleEl: Element = + svgRoot!.querySelector(`[data-anno-id="${cssEscape(id)}"]:not([fill="transparent"])`) || + svgEl + const color = visibleEl.getAttribute('fill') || '#888' + const detail = + visibleEl.getAttribute('data-anno-opens-detail') || + svgEl.getAttribute('data-anno-opens-detail') || + '' + + items.push({ id, fr, cat, catName, color, detail }) + }) + + items.sort((a, b) => (a.cat || '').localeCompare(b.cat || '') || a.fr.localeCompare(b.fr)) + + getEl('svg-editor-count').textContent = String(items.length) + + const list = getEl('svg-editor-element-list') + const selId = selected ? selected.getAttribute('data-anno-id') : null + list.textContent = '' + + items.forEach(({ id, fr, catName, color, detail }) => { + const div = document.createElement('div') + div.className = 'element-item' + (id === selId ? ' selected' : '') + div.dataset.id = id + + const swatch = document.createElement('span') + swatch.className = 'swatch' + swatch.style.background = color + + const nameSpan = document.createElement('span') + nameSpan.className = 'name' + nameSpan.textContent = detail ? 'Detail: ' + detail : fr || id + + const catSpan = document.createElement('span') + catSpan.className = 'cat' + catSpan.textContent = detail ? 'detail' : catName + + div.append(swatch, nameSpan, catSpan) + list.appendChild(div) + + div.addEventListener('click', () => { + const candidates = svgRoot!.querySelectorAll( + `[data-anno-id="${cssEscape(id)}"]`, + ) + let target: SVGElement | null = null + candidates.forEach((c) => { + if (target) return + if (c.getAttribute('fill') === 'transparent') return + target = c as SVGElement + }) + if (!target && candidates.length > 0) { + target = candidates[0] as SVGElement + } + if (target) { + setMode('select') + selectElement(target) + scrollSvgElementIntoView(target) + flashSelected(target) + } + }) + }) + } + + function parsePoints(str: string) { + return str + .trim() + .split(/\s+/) + .filter((p) => p) + .map((p) => p.split(',').map(Number)) + } + function pointsToStr(points: number[][]) { + return points.map((p) => p.map((v) => Math.round(v * 10) / 10).join(',')).join(' ') + } + + function showPolygonHandles(polygon: SVGElement) { + hidePolygonHandles() + if (!svgRoot) return + const points = parsePoints(polygon.getAttribute('points')!) + + let handlesG = svgRoot.querySelector('#polygon-handles') + if (!handlesG) { + handlesG = document.createElementNS('http://www.w3.org/2000/svg', 'g') + handlesG.setAttribute('id', 'polygon-handles') + svgRoot.appendChild(handlesG) + } + svgRoot.appendChild(handlesG) + + for (let i = 0; i < points.length; i++) { + const [x1, y1] = points[i] + const [x2, y2] = points[(i + 1) % points.length] + const mx = (x1 + x2) / 2 + const my = (y1 + y2) / 2 + const m = document.createElementNS('http://www.w3.org/2000/svg', 'circle') + m.setAttribute('cx', String(mx)) + m.setAttribute('cy', String(my)) + m.setAttribute('r', '6') + m.classList.add('polygon-midhandle') + m.setAttribute('data-edge-idx', String(i)) + const t = document.createElementNS('http://www.w3.org/2000/svg', 'title') + t.textContent = 'Click to insert a vertex here' + m.appendChild(t) + handlesG.appendChild(m) + } + + points.forEach(([x, y], i) => { + const h = document.createElementNS('http://www.w3.org/2000/svg', 'circle') + h.setAttribute('cx', String(x)) + h.setAttribute('cy', String(y)) + h.setAttribute('r', '8') + h.classList.add('polygon-handle') + h.setAttribute('data-vertex-idx', String(i)) + const t = document.createElementNS('http://www.w3.org/2000/svg', 'title') + t.textContent = 'Drag to move | Alt+click or right-click to delete' + h.appendChild(t) + handlesG!.appendChild(h) + }) + } + + function hidePolygonHandles() { + const g = svgRoot?.querySelector('#polygon-handles') + if (g) g.textContent = '' + } + + function restartCurrentPolygon() { + if (!selected || selected.tagName.toLowerCase() !== 'polygon') return + if (!confirm('Erase this polygon and redraw it?')) return + _polygonRestartMemo = { + id: selected.getAttribute('data-anno-id') || '', + fr: selected.getAttribute('data-anno-name-fr') || '', + en: selected.getAttribute('data-anno-name-en') || '', + cat: selected.getAttribute('data-anno-category') || '', + fill: selected.getAttribute('fill') || '', + fillOpacity: selected.getAttribute('fill-opacity') || '', + stroke: selected.getAttribute('stroke') || '', + strokeWidth: selected.getAttribute('stroke-width') || '', + } + selected.parentNode?.removeChild(selected) + deselect() + setMode('polygon') + } + + function scrollSvgElementIntoView(svgEl: SVGElement) { + const elRect = svgEl.getBoundingClientRect() + const cRect = canvasInner.getBoundingClientRect() + + const visible = + elRect.left >= cRect.left && + elRect.right <= cRect.right && + elRect.top >= cRect.top && + elRect.bottom <= cRect.bottom + if (visible) return + + const dx = elRect.left + elRect.width / 2 - (cRect.left + cRect.width / 2) + const dy = elRect.top + elRect.height / 2 - (cRect.top + cRect.height / 2) + + canvasInner.scrollTo({ + left: canvasInner.scrollLeft + dx, + top: canvasInner.scrollTop + dy, + behavior: 'smooth', + }) + } + + function flashSelected(svgEl: SVGElement) { + const id = svgEl.getAttribute('data-anno-id') + const cat = svgEl.getAttribute('data-anno-category') + if (!id || !svgRoot) return + const all = svgRoot.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`) + all.forEach((e) => { + if (e.getAttribute('data-anno-category') !== cat) return + e.classList.remove('flashing') + void (e as HTMLElement).getBoundingClientRect() + e.classList.add('flashing') + setTimeout(() => e.classList.remove('flashing'), 1200) + }) + } + + function exportSVG() { + if (!svgRoot) { + alert('No SVG loaded. Upload a file first.') + return + } + const clone = svgRoot.cloneNode(true) as SVGSVGElement + clone.querySelectorAll('.polygon-preview, .polygon-preview-pt').forEach((p) => p.remove()) + const handles = clone.querySelector('#polygon-handles') + if (handles) handles.remove() + clone.querySelectorAll('.selected, .flashing').forEach((p) => { + p.classList.remove('selected') + p.classList.remove('flashing') + }) + + const ser = new XMLSerializer() + const txt = `\n` + ser.serializeToString(clone) + + const blob = new Blob([txt], { type: 'image/svg+xml;charset=utf-8' }) + const url = URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url + a.download = 'horse_anatomy_edited.svg' + document.body.appendChild(a) + a.click() + document.body.removeChild(a) + URL.revokeObjectURL(url) + } + + function applyZoom() { + if (!svgRoot) return + svgRoot.style.transform = `scale(${zoom})` + svgRoot.style.transformOrigin = 'top left' + } +} diff --git a/src/styles/svg-editor.css b/src/styles/svg-editor.css new file mode 100644 index 00000000..c1342422 --- /dev/null +++ b/src/styles/svg-editor.css @@ -0,0 +1,447 @@ +.svg-editor-root { + display: flex; + height: 100vh; + overflow: hidden; + font-family: var(--font-sans); + color: var(--color-ink); + background: var(--color-bg); +} + +.svg-editor-root * { box-sizing: border-box; margin: 0; padding: 0; } + +.svg-editor-canvas { + flex: 1; + position: relative; + background: var(--color-surface); + overflow: hidden; + padding: 10px; +} +.svg-editor-canvas-inner { + width: 100%; + height: 100%; + overflow: auto; + position: relative; +} +.svg-editor-canvas-inner svg { + display: block; + max-width: 100%; + height: auto; +} + +.svg-editor-canvas.mode-point svg, +.svg-editor-canvas.mode-polygon svg { cursor: crosshair; } +.svg-editor-canvas.mode-select svg { cursor: default; } + +.svg-editor-root [data-anno-id] { transition: filter 0.1s; } +.svg-editor-root [data-anno-id]:hover { + filter: brightness(1.3) drop-shadow(0 0 4px rgba(184, 90, 63, 0.7)); +} +.svg-editor-root [data-anno-id].selected { + filter: drop-shadow(0 0 12px var(--color-accent)) drop-shadow(0 0 6px var(--color-accent)) brightness(1.15); + stroke: var(--color-accent) !important; + stroke-width: 4 !important; + stroke-opacity: 1 !important; +} + +.svg-editor-root .polygon-handle { + cursor: move; + fill: #ffd54f; + stroke: var(--color-accent); + stroke-width: 2; + transition: r 0.1s; +} +.svg-editor-root .polygon-handle:hover { + fill: #ffe082; + stroke-width: 3; +} +.svg-editor-root .polygon-midhandle { + cursor: copy; + fill: var(--color-surface); + stroke: var(--color-accent); + stroke-width: 1.5; + fill-opacity: 0.7; +} +.svg-editor-root .polygon-midhandle:hover { + fill: #ffd54f; + fill-opacity: 1; +} + +@keyframes svg-editor-flash-pulse { + 0%, 100% { + stroke-width: 4; + stroke: var(--color-accent); + filter: drop-shadow(0 0 12px var(--color-accent)) brightness(1.15); + } + 50% { + stroke-width: 10; + stroke: #ffd54f; + filter: drop-shadow(0 0 24px #ffd54f) drop-shadow(0 0 12px var(--color-accent)) brightness(1.4); + } +} + +.svg-editor-root [data-anno-id].flashing { + animation: svg-editor-flash-pulse 0.6s ease-in-out 2; +} + +.svg-editor-root .polygon-preview { + fill: rgba(184, 90, 63, 0.2); + stroke: var(--color-accent); + stroke-width: 2; + stroke-dasharray: 5,3; +} +.svg-editor-root .polygon-preview-pt { fill: var(--color-accent); } + +.svg-editor-sidebar { + width: 380px; + background: var(--color-surface); + border-left: 1px solid var(--color-border); + display: flex; + flex-direction: column; + overflow: hidden; +} +.svg-editor-sidebar header { + padding: 14px 16px; + background: var(--color-accent); + color: white; +} +.svg-editor-sidebar header h1 { font-size: 16px; font-weight: 600; } +.svg-editor-sidebar header .sub { font-size: 11px; opacity: 0.8; margin-top: 4px; } + +.svg-editor-sidebar-content { + flex: 1; + overflow-y: auto; + padding: 14px 16px; +} + +.svg-editor-root .section { margin-bottom: 20px; } +.svg-editor-root .section h3 { + font-size: 11px; + text-transform: uppercase; + color: var(--color-ink-muted); + margin-bottom: 8px; + letter-spacing: 0.5px; +} + +.svg-editor-root button, +.svg-editor-root .btn { + display: block; + width: 100%; + padding: 9px 12px; + margin-bottom: 6px; + background: var(--color-surface-strong); + border: 1px solid var(--color-border); + border-radius: 6px; + cursor: pointer; + font-size: 13px; + text-align: left; + transition: all 0.1s; + font-family: inherit; + color: var(--color-ink); +} +.svg-editor-root button:hover { background: var(--color-border); } +.svg-editor-root button.active { + background: var(--color-accent); + color: white; + border-color: var(--color-accent); +} +.svg-editor-root button.danger { + background: #fef2f2; + border-color: #fecaca; + color: var(--color-danger); +} +.svg-editor-root button.danger:hover { background: #fee2e2; } +.svg-editor-root button.primary { + background: var(--color-accent); + color: white; + border-color: var(--color-accent); +} +.svg-editor-root button.primary:hover { background: var(--color-accent-strong); } + +.svg-editor-root input, +.svg-editor-root select { + display: block; + width: 100%; + padding: 8px 10px; + margin-bottom: 6px; + border: 1px solid var(--color-border); + border-radius: 6px; + font-size: 13px; + background: var(--color-surface); + font-family: inherit; + color: var(--color-ink); +} +.svg-editor-root input[type="color"] { padding: 2px; height: 32px; cursor: pointer; } +.svg-editor-root input[type="file"] { background: var(--color-surface-strong); cursor: pointer; } +.svg-editor-root label { + font-size: 11px; + color: var(--color-ink-muted); + margin-bottom: 2px; + display: block; + margin-top: 8px; +} + +.svg-editor-root .element-list { + max-height: 280px; + overflow-y: auto; + border: 1px solid var(--color-border); + border-radius: 6px; + background: var(--color-bg); +} +.svg-editor-root .element-item { + padding: 6px 10px; + border-bottom: 1px solid var(--color-border); + cursor: pointer; + font-size: 12px; + display: flex; + align-items: center; + gap: 8px; +} +.svg-editor-root .element-item:last-child { border-bottom: none; } +.svg-editor-root .element-item:hover { background: var(--color-surface-strong); } +.svg-editor-root .element-item.selected { + background: color-mix(in srgb, var(--color-accent) 12%, transparent); + color: var(--color-accent-strong); + font-weight: 600; +} +.svg-editor-root .element-item .swatch { + width: 12px; + height: 12px; + border-radius: 3px; + border: 1px solid rgba(0,0,0,0.15); + flex-shrink: 0; +} +.svg-editor-root .element-item .name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.svg-editor-root .element-item .cat { + font-size: 10px; + color: var(--color-ink-muted); + margin-left: auto; + padding: 1px 6px; + background: var(--color-surface-strong); + border-radius: 8px; + flex-shrink: 0; +} + +.svg-editor-root .coords { + font-family: monospace; + font-size: 11px; + color: var(--color-ink-muted); + padding: 4px 8px; + background: var(--color-bg); + border-radius: 4px; + margin-bottom: 8px; +} + +.svg-editor-zoom-controls { + position: absolute; + bottom: 20px; + left: 20px; + background: var(--color-surface); + border: 1px solid var(--color-border); + border-radius: 6px; + padding: 4px; + display: flex; + gap: 4px; + box-shadow: 0 2px 8px rgba(0,0,0,0.08); +} +.svg-editor-zoom-controls button { + width: 32px; + height: 32px; + padding: 0; + margin: 0; + font-size: 16px; + display: flex; + align-items: center; + justify-content: center; +} + +.svg-editor-root input[type="checkbox"] { width: auto; display: inline; margin: 0 6px 0 0; } + +.svg-editor-root .cat-row { + display: flex; + align-items: center; + gap: 6px; + padding: 6px 4px; + background: var(--color-bg); + border-radius: 6px; + margin-bottom: 4px; + border: 1px solid var(--color-border); +} +.svg-editor-root .cat-row input[type="color"] { width: 32px; height: 28px; padding: 0; margin: 0; flex-shrink: 0; } +.svg-editor-root .cat-row input[type="checkbox"] { margin: 0 4px 0 4px; flex-shrink: 0; } +.svg-editor-root .cat-row .name { + flex: 1; + font-size: 13px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.svg-editor-root .cat-row .count { + font-size: 10px; + color: var(--color-ink-muted); + padding: 1px 5px; + background: var(--color-surface-strong); + border-radius: 8px; +} +.svg-editor-root .cat-row .delete { + width: 28px; + height: 28px; + padding: 0; + margin: 0; + font-size: 13px; + display: flex; + align-items: center; + justify-content: center; + background: transparent; + border: none; + cursor: pointer; +} +.svg-editor-root .cat-row .delete:hover { background: #fef2f2; color: var(--color-danger); } +.svg-editor-root .cat-row .special-btn { + width: 28px; + height: 28px; + padding: 0; + margin: 0; + font-size: 13px; + display: flex; + align-items: center; + justify-content: center; + background: transparent; + border: none; + cursor: pointer; + color: var(--color-ink-muted); +} +.svg-editor-root .cat-row .special-btn:hover { background: #fff8e1; color: #d97706; } +.svg-editor-root .cat-row .special-btn.has-value { color: #d97706; } +.svg-editor-root .cat-row .special-badge { + font-size: 10px; + padding: 1px 6px; + background: #fff8e1; + color: #92400e; + border: 1px solid #ffd54f; + border-radius: 8px; + flex-shrink: 0; +} + +.svg-editor-root .add-cat { display: flex; gap: 6px; margin-top: 8px; } +.svg-editor-root .add-cat input { margin: 0; } +.svg-editor-root .add-cat input[type="color"] { width: 36px; flex-shrink: 0; } +.svg-editor-root .add-cat input[type="text"] { flex: 1; } +.svg-editor-root .add-cat button { width: auto; padding: 6px 12px; margin: 0; flex-shrink: 0; } + +.svg-editor-root .slider-row { + display: flex; + gap: 8px; + align-items: center; + margin-bottom: 6px; +} +.svg-editor-root .slider-row input[type="range"] { + flex: 1; + margin: 0; + padding: 0; + height: 28px; + cursor: pointer; + accent-color: var(--color-accent); +} +.svg-editor-root .slider-row input[type="number"] { + width: 60px; + margin: 0; + padding: 6px 4px; + text-align: center; + font-variant-numeric: tabular-nums; +} + +.svg-editor-root .detail-toggle { + margin-top: 4px; + padding: 8px 10px; + background: #fff8e1; + border: 1px solid #ffd54f; + border-radius: 6px; + font-size: 13px; +} +.svg-editor-root .detail-toggle label { margin: 0; color: #92400e; font-size: 13px; } +.svg-editor-root .detail-toggle input[type="text"] { margin-top: 4px; margin-bottom: 0; } + +.svg-editor-root .element-item .detail-badge { + background: #ffd54f; + color: #6b4500; + font-size: 10px; + padding: 1px 6px; + border-radius: 8px; + font-weight: 600; + margin-left: 4px; + flex-shrink: 0; +} + +.svg-editor-root [data-anno-opens-detail] { stroke-dasharray: 8,4; } +.svg-editor-root .detail-zone { cursor: pointer; } + +.svg-editor-root .welcome { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + min-height: 100%; + text-align: center; + color: var(--color-ink-muted); + padding: 60px 20px; +} +.svg-editor-root .welcome-icon { font-size: 80px; margin-bottom: 20px; opacity: 0.7; } +.svg-editor-root .welcome h2 { + color: var(--color-accent); + margin-bottom: 16px; + font-size: 24px; + font-family: var(--font-serif); +} +.svg-editor-root .welcome p { + max-width: 480px; + margin-bottom: 30px; + line-height: 1.5; + font-size: 14px; +} +.svg-editor-root .welcome p code { + background: var(--color-surface-strong); + padding: 2px 6px; + border-radius: 3px; + font-size: 90%; + font-family: monospace; +} +.svg-editor-root .welcome-btn { + width: auto !important; + padding: 14px 28px !important; + font-size: 15px !important; + margin: 0 !important; +} +.svg-editor-root .welcome-hint { + margin-top: 16px; + color: var(--color-ink-muted); + font-size: 13px; +} + +.svg-editor-canvas.dragging-over { background: color-mix(in srgb, var(--color-accent) 8%, var(--color-surface)); } +.svg-editor-canvas.dragging-over .welcome { color: var(--color-accent); } +.svg-editor-canvas.dragging-over::after { + content: 'Drop SVG here'; + position: absolute; + inset: 10px; + display: flex; + align-items: center; + justify-content: center; + font-size: 32px; + color: var(--color-accent); + background: color-mix(in srgb, var(--color-accent) 8%, transparent 15%); + border: 4px dashed var(--color-accent); + border-radius: 8px; + pointer-events: none; + z-index: 10; +} + +.svg-editor-root .hide-articulation [data-anno-category="articulation"], +.svg-editor-root .hide-charniere [data-anno-category="charniere"], +.svg-editor-root .hide-cadran-crane [data-anno-category="cadran-crane"], +.svg-editor-root .hide-os-overlay [data-anno-category="os-overlay"], +.svg-editor-root .hide-spine-zone [data-anno-category="spine-zone"], +.svg-editor-root .hide-custom [data-anno-category="custom"] { display: none; }