import { addBoom, addComponent, addLooseComponent, connectComponentToEdge, connectComponentToNode, connectNodes, componentFamilyFor, connectionMedium, connectionPortsFor, connectionRoleFor, createDefaultRig, createFreeRig, deleteComponent, detachComponent, duplicateComponent, duplicateLooseComponent, moveComponent, parseRigJson, removeOrphanEndpoints, updateAttachmentMode, updateLeader, updateMainline, updateNodeProperties, validateRig, } from './rig-model.mjs'; import { exportRigPng, exportRigSvg } from './features/rig/ui/rig-export.mjs'; import { createRigSvgRenderer } from './features/rig/ui/rig-svg-renderer.mjs'; import { componentDisplayLabel, componentLabel, wireLabel } from './features/rig/ui/rig-visual-catalog.mjs'; import { loadRigDrafts, saveRigDrafts } from './features/rig/domain/rig-draft-storage.mjs'; import { getCurrentAccountSession } from './features/account/ui/account-control.mjs'; import { loadAccountConfig } from './features/account/domain/account-config.mjs'; import { websiteApiBase } from './features/account/data/account-api.mjs'; import { createRigPrivateStorage } from './features/rig/data/rig-private-storage.mjs'; import { saveRigForAccount, synchronizeRigsForAccount } from './features/rig/data/rig-account-service.mjs'; import { chooseRigSyncConflict, rigSyncConflictViews } from './features/rig/domain/rig-sync-conflicts.mjs'; import { getLocale, t } from './shared/i18n.mjs'; import { downloadBlob } from './shared/download.mjs'; const elements = { canvas: document.querySelector('#rig-canvas'), edgesLayer: document.querySelector('#edges-layer'), snapLayer: document.querySelector('#snap-layer'), nodesLayer: document.querySelector('#nodes-layer'), jsonPreview: document.querySelector('#json-preview'), propertiesForm: document.querySelector('#properties-form'), selectionEmpty: document.querySelector('#selection-empty'), duplicateButton: document.querySelector('#duplicate-button'), deleteButton: document.querySelector('#delete-button'), detachButton: document.querySelector('#detach-button'), selectedLabel: document.querySelector('#selected-label'), selectedNumberRow: document.querySelector('#selected-number-row'), selectedNumberLabel: document.querySelector('#selected-number-label'), selectedNumber: document.querySelector('#selected-number'), selectedNumberUnit: document.querySelector('#selected-number-unit'), selectedPosition: document.querySelector('#selected-position'), selectedRole: document.querySelector('#selected-role'), selectedFamily: document.querySelector('#selected-family'), selectedPorts: document.querySelector('#selected-ports'), attachmentModeRow: document.querySelector('#attachment-mode-row'), attachmentModeLabel: document.querySelector('#attachment-mode-label'), attachmentMode: document.querySelector('#attachment-mode'), boomMountStyleRow: document.querySelector('#boom-mount-style-row'), boomMountStyle: document.querySelector('#boom-mount-style'), boomMountContext: document.querySelector('#boom-mount-context'), cageMountStyleRow: document.querySelector('#cage-mount-style-row'), cageMountStyle: document.querySelector('#cage-mount-style'), cageMountContext: document.querySelector('#cage-mount-context'), rigContextSummary: document.querySelector('#rig-context-summary'), mainlineSettingsSection: document.querySelector('#mainline-settings-section'), leaderSettingsSection: document.querySelector('#leader-settings-section'), mainlineContext: document.querySelector('#mainline-context'), leaderContext: document.querySelector('#leader-context'), mainlineMaterial: document.querySelector('#mainline-material'), mainlineDiameter: document.querySelector('#mainline-diameter'), leaderMaterial: document.querySelector('#leader-material'), leaderLength: document.querySelector('#leader-length'), leaderDiameter: document.querySelector('#leader-diameter'), statusDot: document.querySelector('#status-dot'), statusTitle: document.querySelector('#status-title'), statusCopy: document.querySelector('#status-copy'), toast: document.querySelector('#toast'), jsonFileInput: document.querySelector('#json-file-input'), guidedModeButton: document.querySelector('#guided-mode-button'), freeModeButton: document.querySelector('#free-mode-button'), magnetControls: document.querySelector('#magnet-controls'), magnetButton: document.querySelector('#magnet-button'), whiteBackgroundButton: document.querySelector('#white-background-button'), connectionKind: document.querySelector('#connection-kind'), modeDescription: document.querySelector('#mode-description'), testInstruction: document.querySelector('#test-instruction'), wireToolButtons: [...document.querySelectorAll('[data-wire-kind]')], saveAccountButton: document.querySelector('#save-account-button'), accountRigsPanel: document.querySelector('#account-rigs-panel'), accountRigsStatus: document.querySelector('#account-rigs-status'), accountRigSelect: document.querySelector('#account-rig-select'), accountRigConflicts: document.querySelector('#account-rig-conflicts'), openAccountRigButton: document.querySelector('#open-account-rig-button'), deleteAccountRigButton: document.querySelector('#delete-account-rig-button'), syncAccountRigsButton: document.querySelector('#sync-account-rigs-button'), }; let draftStorage = null; try { draftStorage = window.localStorage; } catch { /* Storage can be disabled by the browser. */ } const restoredDrafts = loadRigDrafts(draftStorage); const rigsByMode = restoredDrafts ? { guided: restoredDrafts.guided, free: restoredDrafts.free } : { guided: createDefaultRig(), free: createFreeRig() }; let mode = restoredDrafts?.activeMode ?? 'guided'; let rig = rigsByMode[mode]; let magnetEnabled = true; let whiteBackground = document.documentElement.dataset.theme === 'light'; let selectedId = null; let drag = null; let snapCandidate = null; let wireDraft = null; let toastTimer = null; let draftSaveTimer = null; let draftSaveFailureAnnounced = false; let rigPrivateStorage = null; try { rigPrivateStorage = createRigPrivateStorage(); } catch { /* IndexedDB peut être indisponible. */ } let accountRigInventory = []; let accountRigConflicts = []; let accountRigRefresh = 0; let accountRigMutationActive = false; let pendingAccountRigRefresh = null; let accountRigSyncController = null; const ACCOUNT_RIG_SYNC_POLL_MILLISECONDS = 60_000; function isCurrentAccountRigSession(expected) { const current = getCurrentAccountSession(); return !!expected && current?.user.id === expected.user.id && current.accessToken === expected.accessToken; } const node = (id) => rig.nodes.find((item) => item.id === id) ?? null; const isAttached = (id) => rig.edges.some((edge) => edge.to === id); function applyCanvasTheme(isWhite) { whiteBackground = isWhite; elements.canvas.classList.toggle('white-background', whiteBackground); elements.whiteBackgroundButton.setAttribute('aria-pressed', String(whiteBackground)); elements.whiteBackgroundButton.textContent = t(whiteBackground ? 'rig.darkBackground' : 'rig.whiteBackground'); } const renderer = createRigSvgRenderer({ canvas: elements.canvas, edgesLayer: elements.edgesLayer, snapLayer: elements.snapLayer, nodesLayer: elements.nodesLayer, getRig: () => rig, getState: () => ({ selectedId, drag, snapCandidate, wireDraft, mode }), connectionPlan, onNodePointerDown: startDrag, onNodeClick: handleNodeClick, }); function canDetachAndReattach(id) { const incomingDirect = rig.edges.filter((edge) => edge.to === id && connectionMedium(edge) === 'direct'); const outgoing = rig.edges.filter((edge) => edge.from === id); return incomingDirect.length === 1 && outgoing.length === 0; } function automaticConnectionKind(item) { if (elements.connectionKind.value !== 'auto') return elements.connectionKind.value; if (['bead', 'slider', 'swivel', 'leaderConnector'].includes(item?.type)) return 'mainline'; if (item?.type === 'hook') return 'leader'; return 'branch'; } function connectionPlan(item, candidate) { if (!item || !candidate) return null; let plannedRig = rig; let kind = automaticConnectionKind(item); if (candidate.type === 'edge' && item.type === 'cage' && elements.connectionKind.value === 'auto') { plannedRig = updateNodeProperties(plannedRig, item.id, { mountStyle: 'inline', attachmentMode: 'sliding' }); kind = 'mainline'; } if (candidate.type === 'edge' && item.type === 'boom' && item.properties?.mountStyle === 'inline' && elements.connectionKind.value === 'auto') kind = 'mainline'; const target = candidate.type === 'node' ? node(candidate.targetId) : null; if (target?.type === 'endpoint' && item.type === 'boom' && item.properties?.mountStyle === 'inline' && elements.connectionKind.value === 'auto') { plannedRig = updateNodeProperties(plannedRig, item.id, { mountStyle: 'end', attachmentMode: 'fixed' }); kind = 'mainline'; } const result = candidate.type === 'edge' ? connectComponentToEdge(plannedRig, item.id, candidate.edgeId, kind, candidate) : connectComponentToNode(plannedRig, item.id, candidate.targetId, kind); const connected = result.rig.edges.some((edge) => edge.to === item.id); return { result, kind, valid: connected && !result.reason }; } function findSnapCandidate(nodeId) { const reattaching = Boolean(drag?.detached); if ((!reattaching && mode !== 'free') || !magnetEnabled || isAttached(nodeId)) return null; const dragged = node(nodeId); if (!dragged) return null; let nearestNode = null; for (const target of rig.nodes) { if (target.id === nodeId || target.type === 'junction') continue; const baseCandidate = { type: 'node', targetId: target.id }; const plan = connectionPlan(dragged, baseCandidate); if (!plan?.valid) continue; const dropPoint = renderer.nodeDropPoint(target, plan.kind); const distance = Math.hypot(dragged.x - dropPoint.x, dragged.y - dropPoint.y); const candidate = { ...baseCandidate, x: dropPoint.x, y: dropPoint.y, distance }; if (distance <= 72 && (!nearestNode || distance < nearestNode.distance)) nearestNode = candidate; } if (nearestNode) return nearestNode; let nearestEdge = null; for (const edge of rig.edges) { if (connectionMedium(edge) === 'direct' || edge.from === nodeId || edge.to === nodeId) continue; const start = renderer.connectionPoint(node(edge.from), edge, 'source'); const end = renderer.connectionPoint(node(edge.to), edge, 'target'); if (!start || !end) continue; const projected = renderer.pointToSegment(dragged, start, end); const candidate = { type: 'edge', edgeId: edge.id, x: projected.x, y: projected.y, distance: projected.distance }; if (projected.distance <= 58 && connectionPlan(dragged, candidate)?.valid && (!nearestEdge || projected.distance < nearestEdge.distance)) nearestEdge = candidate; } return nearestEdge; } function renderStatus() { const validation = validateRig(rig, { includeDetails: true }); elements.statusDot.className = 'status-dot'; if (validation.errors.length) { elements.statusDot.classList.add('error'); elements.statusTitle.textContent = t('rig.status.invalid'); elements.statusCopy.textContent = localizedValidationMessage(validation.errorDetails[0]); } else if (validation.warnings.length && !(mode === 'free' && rig.nodes.length === 2)) { elements.statusDot.classList.add('warning'); elements.statusTitle.textContent = t('rig.status.warning'); elements.statusCopy.textContent = localizedValidationMessage(validation.warningDetails[0]); } else { elements.statusTitle.textContent = t(mode === 'free' && rig.nodes.length === 2 ? 'rig.status.freeReady' : 'rig.status.coherent'); elements.statusCopy.textContent = mode === 'free' && rig.nodes.length === 2 ? t('rig.status.freeCopy') : t('rig.status.counts', { nodes: rig.nodes.length, edges: rig.edges.length }); } } function localizedErrorMessage(error) { return error?.translationKey ? t(error.translationKey, error.translationVariables) : error?.message ?? t('common.unknownError'); } function localizedValidationMessage(detail) { const variables = { ...detail.variables }; if (variables.labelKey) variables.label = t(variables.labelKey); if (variables.portKey) variables.port = t(variables.portKey); return t(detail.key, variables); } function localizedRegistryText(key, fallback) { if (!key) return fallback; const value = t(key); return value === key ? fallback : value; } function selectedNumberConfig(item) { if (item.type === 'cage') return [t('inventory.property.weight'), 'weightG', 'g', 5, 300, 5]; if (item.type === 'bead') return [t('rig.diameter'), 'diameterMm', 'mm', 1, 30, 1]; if (item.type === 'swivel') return [t('inventory.property.size'), 'size', '', 1, 30, 1]; if (item.type === 'hook') return [t('inventory.property.size'), 'size', 'n°', 1, 30, 1]; if (item.type === 'boom') return [t('rig.length'), 'lengthCm', 'cm', 2, 80, 1]; if (item.type === 'anchor') return [t('rig.diameter'), 'diameterMm', 'mm', 0.05, 1, 0.01]; return null; } function renderInspector() { const item = selectedId ? node(selectedId) : null; const lineCounts = rig.edges.reduce((counts, edge) => { if (connectionMedium(edge) === 'direct') counts.direct += 1; else counts[edge.kind] = (counts[edge.kind] ?? 0) + 1; return counts; }, { mainline: 0, leader: 0, branch: 0, direct: 0 }); const segmentLabel = (count) => t('rig.segment', { count, suffix: count === 1 ? '' : 's' }); elements.rigContextSummary.textContent = [ t('rig.context.mainline', { segments: segmentLabel(lineCounts.mainline) }), lineCounts.leader ? t('rig.context.leader', { segments: segmentLabel(lineCounts.leader) }) : null, lineCounts.branch ? t('rig.context.branch', { segments: segmentLabel(lineCounts.branch) }) : null, lineCounts.direct ? t('rig.context.direct', { count: lineCounts.direct, suffix: lineCounts.direct > 1 ? 's' : '' }) : null, ].filter(Boolean).join(' · '); elements.mainlineSettingsSection.hidden = lineCounts.mainline === 0; elements.leaderSettingsSection.hidden = lineCounts.leader === 0; elements.mainlineContext.textContent = `· ${segmentLabel(lineCounts.mainline)}`; elements.leaderContext.textContent = `· ${segmentLabel(lineCounts.leader)}`; elements.propertiesForm.hidden = !item; elements.selectionEmpty.hidden = Boolean(item); elements.duplicateButton.disabled = !item || ['anchor', 'endpoint', 'junction'].includes(item.type) || (mode === 'guided' && ['slider', 'boom'].includes(item.type)); const protectedEndpoint = item?.type === 'endpoint' && isAttached(item.id); elements.deleteButton.disabled = !item || item.type === 'anchor' || item.type === 'junction' || protectedEndpoint; elements.detachButton.hidden = mode !== 'free'; elements.detachButton.disabled = !item || !isAttached(item.id) || ['anchor', 'endpoint', 'junction'].includes(item.type); if (!item) return; elements.selectedLabel.value = componentDisplayLabel(item); const role = connectionRoleFor(item); const family = componentFamilyFor(item); elements.selectedRole.textContent = `${localizedRegistryText(role.labelKey, role.label)} · ${localizedRegistryText(role.descriptionKey, role.description)}`; elements.selectedFamily.textContent = localizedRegistryText(family.labelKey, family.label); elements.selectedPorts.replaceChildren(...connectionPortsFor(item).map((port) => { const connected = rig.edges.some((edge) => (edge.from === item.id && edge.fromPort === port.id) || (edge.to === item.id && edge.toPort === port.id)); const row = document.createElement('li'); row.dataset.connected = String(connected); const name = document.createElement('span'); name.textContent = localizedRegistryText(port.labelKey, port.label ?? port.id); const status = document.createElement('small'); status.textContent = t(connected ? 'rig.port.busy' : 'rig.port.free'); row.append(name, status); return row; })); elements.selectedPosition.textContent = `x ${Math.round(item.x)} · y ${Math.round(item.y)}`; const config = selectedNumberConfig(item); elements.selectedNumberRow.hidden = !config; const showsAttachmentMode = item.type === 'boom' || (item.type === 'cage' && !['boom', 'clip'].includes(item.properties?.mountStyle)); elements.attachmentModeRow.hidden = !showsAttachmentMode; elements.boomMountStyleRow.hidden = item.type !== 'boom'; elements.cageMountStyleRow.hidden = item.type !== 'cage'; if (showsAttachmentMode) { elements.attachmentModeLabel.textContent = t(item.type === 'boom' ? 'rig.boomLink' : 'rig.cageLink'); elements.attachmentMode.value = item.properties?.attachmentMode ?? 'sliding'; } if (item.type === 'cage') { const attached = isAttached(item.id); elements.cageMountStyle.value = item.properties?.mountStyle ?? 'branch'; elements.cageMountStyle.disabled = attached; elements.cageMountContext.textContent = t(attached ? 'rig.cage.attachedHelp' : 'rig.cage.detachedHelp'); } if (item.type === 'boom') { const attached = isAttached(item.id); elements.boomMountStyle.value = item.properties?.mountStyle ?? 'inline'; elements.boomMountStyle.disabled = attached; elements.boomMountContext.textContent = t(attached ? 'rig.boom.attachedHelp' : 'rig.boom.detachedHelp'); } if (config) { const [label, property, unit, min, max, step] = config; elements.selectedNumberLabel.textContent = label; elements.selectedNumberUnit.textContent = unit; elements.selectedNumber.min = min; elements.selectedNumber.max = max; elements.selectedNumber.step = step; elements.selectedNumber.value = item.properties?.[property] ?? min; elements.selectedNumber.dataset.property = property; } } function renderPreview() { const compact = { schema: rig.schema, metadata: rig.metadata, settings: rig.settings, nodes: rig.nodes.map(({ id, type, family, x, y, properties }) => ({ id, type, family, x, y, properties })), edges: rig.edges.map(({ id, from, fromPort, to, toPort, kind, medium, properties }) => ({ id, from, fromPort, to, toPort, kind, medium, properties, })), }; elements.jsonPreview.textContent = JSON.stringify(compact, null, 2); window.clearTimeout(draftSaveTimer); draftSaveTimer = window.setTimeout(persistRigDrafts, 250); } function persistRigDrafts() { rigsByMode[mode] = rig; const saved = saveRigDrafts(draftStorage, { activeMode: mode, guided: rigsByMode.guided, free: rigsByMode.free, }); if (!saved && !draftSaveFailureAnnounced) { draftSaveFailureAnnounced = true; showToast(t('rig.toast.draftSaveFailed'), 'error'); } } function render() { const cleanup = removeOrphanEndpoints(rig); if (cleanup.removedIds.length) { rig = cleanup.rig; if (cleanup.removedIds.includes(selectedId)) selectedId = null; } renderer.syncCanvasGeometry(); renderer.alignDirectAttachments(); renderer.drawEdges(); renderer.drawSnapCandidate(); renderer.drawNodes(); renderInspector(); renderStatus(); renderPreview(); document.querySelector('#rig-title').textContent = mode === 'free' ? t('rig.mode.free') : t('rig.defaultName'); const firstMainline = rig.edges.find((edge) => edge.kind === 'mainline'); elements.mainlineMaterial.value = rig.settings?.mainline?.material ?? firstMainline?.properties?.material ?? 'nylon'; elements.mainlineDiameter.value = rig.settings?.mainline?.diameterMm ?? firstMainline?.properties?.diameterMm ?? 0.28; const firstLeader = rig.edges.find((edge) => edge.kind === 'leader'); const leaderSettings = rig.settings?.leader ?? firstLeader?.properties ?? {}; elements.leaderMaterial.value = leaderSettings.material ?? 'fluorocarbone'; elements.leaderLength.value = leaderSettings.lengthCm ?? 60; elements.leaderDiameter.value = leaderSettings.diameterMm ?? 0.22; elements.guidedModeButton.classList.toggle('active', mode === 'guided'); elements.guidedModeButton.setAttribute('aria-pressed', String(mode === 'guided')); elements.freeModeButton.classList.toggle('active', mode === 'free'); elements.freeModeButton.setAttribute('aria-pressed', String(mode === 'free')); elements.magnetControls.hidden = mode !== 'free'; document.querySelectorAll('.free-only').forEach((element) => { element.hidden = mode !== 'free'; }); elements.wireToolButtons.forEach((button) => { const active = mode === 'free' && wireDraft?.kind === button.dataset.wireKind; button.classList.toggle('active', active); button.setAttribute('aria-pressed', String(active)); }); elements.modeDescription.textContent = t(mode === 'free' ? 'rig.mode.freeDescription' : 'rig.intro'); elements.testInstruction.textContent = t(mode === 'free' ? 'rig.mode.freeTest' : 'rig.testInstruction'); } function showToast(message, kind = 'success') { window.clearTimeout(toastTimer); elements.toast.textContent = message; elements.toast.className = `toast visible${kind === 'error' ? ' error' : ''}`; toastTimer = window.setTimeout(() => { elements.toast.className = 'toast'; }, 3200); } function refreshAccountSaveButton() { const available = !!getCurrentAccountSession() && !!rigPrivateStorage; elements.saveAccountButton.disabled = accountRigMutationActive || !available; elements.saveAccountButton.title = t(available ? 'rig.saveAccountReady' : 'rig.saveAccountHint'); } function refreshAccountRigControls() { const available = !!getCurrentAccountSession() && !!rigPrivateStorage; const hasInventory = accountRigInventory.length > 0; refreshAccountSaveButton(); elements.syncAccountRigsButton.disabled = accountRigMutationActive || !available; elements.accountRigSelect.disabled = accountRigMutationActive || !hasInventory; elements.openAccountRigButton.disabled = accountRigMutationActive || !hasInventory; elements.deleteAccountRigButton.disabled = accountRigMutationActive || !hasInventory; elements.accountRigConflicts.querySelectorAll('button').forEach((button) => { button.disabled = accountRigMutationActive; }); } async function runAccountRigMutation(mutation) { if (accountRigMutationActive) return; accountRigMutationActive = true; refreshAccountRigControls(); try { await mutation(); } finally { accountRigMutationActive = false; refreshAccountRigControls(); const pending = pendingAccountRigRefresh; pendingAccountRigRefresh = null; if (pending) requestAccountRigRefresh(pending); } } function requestAccountRigRefresh(options) { if (accountRigMutationActive) { pendingAccountRigRefresh = options; return; } void runAccountRigMutation(() => refreshAccountRigs(options)); } function refreshAccountRigsWhenVisible() { if (document.visibilityState !== 'visible' || !getCurrentAccountSession()) return; requestAccountRigRefresh({ synchronize: true }); } function renderAccountRigInventory(inventory) { accountRigInventory = inventory; const previous = elements.accountRigSelect.value; elements.accountRigSelect.replaceChildren(); if (inventory.length === 0) { elements.accountRigSelect.add(new Option(t('rig.accountRigsEmpty'), '')); } else { const formatter = new Intl.DateTimeFormat(getLocale(), { dateStyle: 'short', timeStyle: 'short' }); for (const record of inventory) { elements.accountRigSelect.add(new Option( `${record.document.metadata.name} · ${formatter.format(new Date(record.updatedAt))}`, record.id, )); } const preferred = inventory.some((record) => record.id === previous) ? previous : inventory.some((record) => record.id === rig.metadata?.id) ? rig.metadata.id : inventory[0].id; elements.accountRigSelect.value = preferred; } elements.accountRigsStatus.textContent = t('rig.accountRigsCount', { count: inventory.length }); refreshAccountRigControls(); } function rigConflictVersion(label, record, newest) { const version = document.createElement('div'); version.className = `account-rig-conflict-version${newest ? ' newest' : ''}`; const caption = document.createElement('small'); caption.textContent = `${label}${newest ? ` · ${t('rig.conflict.newer')}` : ''}`; const name = document.createElement('b'); name.textContent = record?.document.metadata.name ?? t('rig.conflict.deleted'); const details = document.createElement('span'); details.textContent = record ? `${record.document.metadata.technique} · ${new Intl.DateTimeFormat(getLocale(), { dateStyle: 'medium', timeStyle: 'short', }).format(new Date(record.updatedAt))}` : t('rig.conflict.deletedCopy'); version.append(caption, name, details); return version; } function renderAccountRigConflicts(items = accountRigConflicts) { accountRigConflicts = items; elements.accountRigConflicts.hidden = items.length === 0; elements.accountRigConflicts.replaceChildren(...items.map((conflict) => { const card = document.createElement('article'); card.className = 'account-rig-conflict-card'; card.dataset.rigConflict = conflict.entityId; const title = document.createElement('strong'); title.textContent = t('rig.conflict.heading', { name: conflict.local.document.metadata.name, }); const copy = document.createElement('p'); copy.textContent = t('rig.conflict.copy'); const versions = document.createElement('div'); versions.className = 'account-rig-conflict-versions'; const localNewest = !conflict.remote || Date.parse(conflict.local.updatedAt) >= Date.parse(conflict.remote.updatedAt); versions.append( rigConflictVersion(t('rig.conflict.local'), conflict.local, localNewest), rigConflictVersion(t('rig.conflict.remote'), conflict.remote, !localNewest), ); const actions = document.createElement('div'); actions.className = 'account-rig-conflict-actions'; for (const [choice, key, primary] of [ ['remote', 'rig.conflict.useRemote', false], ['local', 'rig.conflict.keepLocal', true], ]) { const button = document.createElement('button'); button.type = 'button'; button.className = `icon-button${primary ? ' primary' : ''}`; button.dataset.rigConflictChoice = choice; button.textContent = t(key); button.disabled = accountRigMutationActive; actions.append(button); } card.append(title, copy, versions, actions); return card; })); } async function refreshAccountRigs({ synchronize = false, announce = false } = {}) { const refresh = ++accountRigRefresh; const session = getCurrentAccountSession(); if (!session || !rigPrivateStorage) { accountRigInventory = []; accountRigConflicts = []; elements.accountRigsPanel.hidden = true; return; } elements.accountRigsPanel.hidden = false; elements.syncAccountRigsButton.disabled = true; let syncResult = null; let syncController = null; try { if (synchronize) { elements.accountRigsStatus.textContent = t('rig.accountRigsSyncing'); const config = await loadAccountConfig(); accountRigSyncController?.abort(); syncController = new AbortController(); accountRigSyncController = syncController; syncResult = await synchronizeRigsForAccount(session, websiteApiBase(window.location, config.apiBase), rigPrivateStorage, { signal: syncController.signal }); } const inventory = await rigPrivateStorage.loadInventory(session.user.id); if (refresh !== accountRigRefresh || !isCurrentAccountRigSession(session)) return; renderAccountRigInventory(inventory); const deviceId = await rigPrivateStorage.loadDeviceId(); const state = syncResult?.state ?? await rigPrivateStorage.loadSyncState(session.user.id, deviceId); const drafts = await rigPrivateStorage.loadConflictDrafts(session.user.id); if (refresh !== accountRigRefresh || !isCurrentAccountRigSession(session)) return; renderAccountRigConflicts(rigSyncConflictViews(state, drafts)); if (announce) { if (syncResult?.quotaExceeded > 0) showToast(t('rig.toast.accountQuota'), 'error'); else if (syncResult?.conflicts > 0) showToast(t('rig.toast.accountConflict')); else if (syncResult?.pending > 0) showToast(t('rig.toast.accountPending')); else showToast(t('rig.toast.accountSynchronized')); } } catch (error) { if (refresh !== accountRigRefresh || !isCurrentAccountRigSession(session)) return; const inventory = await rigPrivateStorage.loadInventory(session.user.id).catch(() => []); if (refresh !== accountRigRefresh || !isCurrentAccountRigSession(session)) return; renderAccountRigInventory(inventory); elements.accountRigsStatus.textContent = t('rig.accountRigsOffline'); if (error instanceof Error && error.message === 'algofish-server-401') { window.dispatchEvent(new CustomEvent('algofish:sessionexpired', { detail: { accountId: session.user.id }, })); } if (announce) showToast(t('rig.toast.accountSyncFailed'), 'error'); } finally { if (accountRigSyncController === syncController) accountRigSyncController = null; if (refresh === accountRigRefresh) refreshAccountRigControls(); } } async function resolveAccountRigConflict(entityId, choice) { const session = getCurrentAccountSession(); if (!session || !rigPrivateStorage) return; try { const deviceId = await rigPrivateStorage.loadDeviceId(); const [state, drafts, inventory] = await Promise.all([ rigPrivateStorage.loadSyncState(session.user.id, deviceId), rigPrivateStorage.loadConflictDrafts(session.user.id), rigPrivateStorage.loadInventory(session.user.id), ]); if (!isCurrentAccountRigSession(session)) return; const resolved = chooseRigSyncConflict(state, inventory, drafts, entityId, choice); await rigPrivateStorage.saveInventory(session.user.id, resolved.inventory); await rigPrivateStorage.saveConflictDrafts(session.user.id, resolved.drafts); if (!isCurrentAccountRigSession(session)) return; renderAccountRigInventory(resolved.inventory); renderAccountRigConflicts(rigSyncConflictViews(state, resolved.drafts)); await refreshAccountRigs({ synchronize: true, announce: true }); } catch { if (!isCurrentAccountRigSession(session)) return; showToast(t('rig.toast.conflictResolutionFailed'), 'error'); } } function select(id) { selectedId = id; render(); } function cancelWireTool(announce = false) { wireDraft = null; if (announce) showToast(t('rig.toast.wireCancelled')); } function handleNodeClick(id) { if (mode !== 'free' || !wireDraft) return select(id); if (!wireDraft.fromId) { wireDraft.fromId = id; selectedId = id; render(); showToast(t('rig.toast.startChosen', { kind: wireLabel(wireDraft.kind) })); return; } if (wireDraft.fromId === id) return showToast(t('rig.toast.chooseAnother'), 'error'); const kind = wireDraft.kind; const result = connectNodes(rig, wireDraft.fromId, id, kind); if (!result.edgeId) return showToast(t('rig.toast.connectionImpossible'), 'error'); rig = result.rig; wireDraft = null; selectedId = id; render(); const kindLabel = wireLabel(kind); showToast(t('rig.toast.wireAdded', { kind: `${kindLabel[0].toUpperCase()}${kindLabel.slice(1)}` })); } function canvasPoint(event) { const point = elements.canvas.createSVGPoint(); point.x = event.clientX; point.y = event.clientY; return point.matrixTransform(elements.canvas.getScreenCTM().inverse()); } function startDrag(event, id) { if (event.button !== 0 || (mode === 'free' && wireDraft)) return; event.preventDefault(); selectedId = id; drag = { id, origin: canvasPoint(event), canReattach: canDetachAndReattach(id), detached: false }; snapCandidate = findSnapCandidate(id); renderInspector(); window.addEventListener('pointermove', continueDrag); window.addEventListener('pointerup', endDrag, { once: true }); } function continueDrag(event) { if (!drag) return; const point = canvasPoint(event); if (drag.canReattach && !drag.detached && Math.hypot(point.x - drag.origin.x, point.y - drag.origin.y) >= 14) { const detached = detachComponent(rig, drag.id); rig = detached.rig; selectedId = detached.selectedId; drag.detached = true; } rig = moveComponent(rig, drag.id, point.x, point.y); snapCandidate = findSnapCandidate(drag.id); renderer.drawEdges(); renderer.drawSnapCandidate(); renderer.drawNodes(); renderInspector(); renderPreview(); } function endDrag() { const finishedDrag = drag; const candidate = snapCandidate; drag = null; snapCandidate = null; window.removeEventListener('pointermove', continueDrag); if (finishedDrag && candidate && !isAttached(finishedDrag.id)) { const plan = connectionPlan(node(finishedDrag.id), candidate); if (plan?.valid) { rig = plan.result.rig; selectedId = plan.result.selectedId; showToast(t('rig.toast.attached', { action: t(finishedDrag.detached ? 'rig.toast.reclipped' : 'rig.toast.clipped'), location: t(`rig.toast.location.${plan.kind}`), })); } else if (plan?.result.reason) showToast(t('rig.toast.connectionImpossible'), 'error'); } render(); } function switchMode(nextMode) { if (nextMode === mode) return; rigsByMode[mode] = rig; mode = nextMode; rig = rigsByMode[mode]; selectedId = null; snapCandidate = null; wireDraft = null; render(); showToast(t(mode === 'free' ? 'rig.toast.freeEnabled' : 'rig.toast.guidedRestored')); } document.querySelectorAll('[data-add]').forEach((button) => button.addEventListener('click', () => { const result = mode === 'free' ? addLooseComponent(rig, button.dataset.add) : addComponent(rig, button.dataset.add); rig = result.rig; selectedId = result.selectedId; render(); showToast( result.reasonKey ? t(result.reasonKey) : t('rig.toast.componentAdded', { component: componentLabel(button.dataset.add) }), result.reasonKey ? 'error' : 'success', ); })); document.querySelector('#add-boom-button').addEventListener('click', () => { const alreadyExists = mode === 'guided' && rig.nodes.some((item) => item.type === 'boom'); const result = mode === 'free' ? addLooseComponent(rig, 'boom') : addBoom(rig); rig = result.rig; selectedId = result.selectedId; render(); showToast(t(mode === 'free' ? 'rig.toast.boomLoose' : alreadyExists ? 'rig.toast.boomSelected' : 'rig.toast.boomConnected')); }); elements.duplicateButton.addEventListener('click', () => { if (!selectedId) return; const result = mode === 'free' ? duplicateLooseComponent(rig, selectedId) : duplicateComponent(rig, selectedId); rig = result.rig; selectedId = result.selectedId; render(); showToast(t(result.reasonKey ?? 'rig.toast.duplicated'), result.reasonKey ? 'error' : 'success'); }); elements.deleteButton.addEventListener('click', () => { if (!selectedId) return; const result = deleteComponent(rig, selectedId); rig = result.rig; selectedId = result.selectedId; render(); showToast(t('rig.toast.deleted')); }); elements.detachButton.addEventListener('click', () => { if (!selectedId) return; const result = detachComponent(rig, selectedId); rig = result.rig; selectedId = result.selectedId; render(); showToast(t('rig.toast.detached')); }); elements.guidedModeButton.addEventListener('click', () => switchMode('guided')); elements.freeModeButton.addEventListener('click', () => switchMode('free')); elements.wireToolButtons.forEach((button) => button.addEventListener('click', () => { const kind = button.dataset.wireKind; if (wireDraft?.kind === kind) { cancelWireTool(true); render(); return; } wireDraft = { kind, fromId: null }; selectedId = null; snapCandidate = null; render(); showToast(t('rig.toast.wireEnabled', { kind: wireLabel(kind) })); })); window.addEventListener('keydown', (event) => { if (event.key !== 'Escape' || !wireDraft) return; cancelWireTool(true); render(); }); elements.magnetButton.addEventListener('click', () => { magnetEnabled = !magnetEnabled; elements.magnetButton.classList.toggle('active', magnetEnabled); elements.magnetButton.setAttribute('aria-pressed', String(magnetEnabled)); elements.magnetButton.innerHTML = `⌁ ${t(magnetEnabled ? 'rig.magnet.on' : 'rig.magnet.off')}`; snapCandidate = null; renderer.drawSnapCandidate(); }); elements.selectedLabel.addEventListener('input', () => { if (!selectedId) return; rig = updateNodeProperties(rig, selectedId, { label: elements.selectedLabel.value, labelKey: null }); renderer.drawNodes(); renderPreview(); }); elements.selectedNumber.addEventListener('input', () => { if (!selectedId || !elements.selectedNumber.dataset.property) return; const value = Number(elements.selectedNumber.value); if (!Number.isFinite(value)) return; rig = updateNodeProperties(rig, selectedId, { [elements.selectedNumber.dataset.property]: value }); renderer.drawNodes(); renderPreview(); }); elements.attachmentMode.addEventListener('change', () => { if (!selectedId) return; rig = updateAttachmentMode(rig, selectedId, elements.attachmentMode.value); renderer.drawEdges(); renderer.drawNodes(); renderPreview(); }); elements.cageMountStyle.addEventListener('change', () => { if (!selectedId || elements.cageMountStyle.disabled) return; rig = updateNodeProperties(rig, selectedId, { mountStyle: elements.cageMountStyle.value }); render(); }); elements.boomMountStyle.addEventListener('change', () => { if (!selectedId || elements.boomMountStyle.disabled) return; rig = updateNodeProperties(rig, selectedId, { mountStyle: elements.boomMountStyle.value }); render(); }); elements.leaderLength.addEventListener('input', () => { const value = Number(elements.leaderLength.value); if (!Number.isFinite(value)) return; rig = updateLeader(rig, { lengthCm: value }); renderer.drawEdges(); renderPreview(); }); elements.mainlineMaterial.addEventListener('change', () => { rig = updateMainline(rig, { material: elements.mainlineMaterial.value }); renderer.drawNodes(); renderPreview(); }); elements.mainlineDiameter.addEventListener('input', () => { const value = Number(elements.mainlineDiameter.value); if (!Number.isFinite(value)) return; rig = updateMainline(rig, { diameterMm: value }); renderer.drawNodes(); renderPreview(); }); elements.leaderMaterial.addEventListener('change', () => { rig = updateLeader(rig, { material: elements.leaderMaterial.value }); renderPreview(); }); elements.leaderDiameter.addEventListener('input', () => { const value = Number(elements.leaderDiameter.value); if (!Number.isFinite(value)) return; rig = updateLeader(rig, { diameterMm: value }); renderPreview(); }); document.querySelector('#reset-button').addEventListener('click', () => { rig = mode === 'free' ? createFreeRig() : createDefaultRig(); rigsByMode[mode] = rig; selectedId = null; wireDraft = null; render(); showToast(t('rig.toast.reset')); }); elements.whiteBackgroundButton.addEventListener('click', () => { applyCanvasTheme(!whiteBackground); showToast(t(whiteBackground ? 'rig.toast.whiteBackground' : 'rig.toast.darkBackground')); }); window.addEventListener('algofish:themechange', (event) => { applyCanvasTheme(event.detail.theme === 'light'); }); window.addEventListener('algofish:localechange', () => { applyCanvasTheme(whiteBackground); render(); refreshAccountSaveButton(); if (!elements.accountRigsPanel.hidden) renderAccountRigInventory(accountRigInventory); renderAccountRigConflicts(); }); window.addEventListener('algofish:accountchange', () => { accountRigSyncController?.abort(); accountRigSyncController = null; accountRigRefresh += 1; accountRigInventory = []; renderAccountRigInventory([]); renderAccountRigConflicts([]); refreshAccountSaveButton(); requestAccountRigRefresh({ synchronize: true }); }); window.addEventListener('online', refreshAccountRigsWhenVisible); document.addEventListener('visibilitychange', refreshAccountRigsWhenVisible); window.setInterval(refreshAccountRigsWhenVisible, ACCOUNT_RIG_SYNC_POLL_MILLISECONDS); window.addEventListener('beforeunload', persistRigDrafts); document.querySelector('#save-json-button').addEventListener('click', () => { downloadBlob(new Blob([`${JSON.stringify(rig, null, 2)}\n`], { type: 'application/json' }), 'algofish-montage.json'); showToast(t('rig.toast.jsonSaved')); }); elements.saveAccountButton.addEventListener('click', () => { void runAccountRigMutation(async () => { const session = getCurrentAccountSession(); if (!session || !rigPrivateStorage) { showToast(t('rig.toast.accountRequired'), 'error'); refreshAccountSaveButton(); return; } elements.saveAccountButton.disabled = true; let savedLocally = false; let syncController = null; try { const saved = await saveRigForAccount(session, rig, rigPrivateStorage); if (!isCurrentAccountRigSession(session)) return; rig = saved.record.document; rigsByMode[mode] = rig; persistRigDrafts(); render(); savedLocally = true; renderAccountRigInventory(saved.inventory); const config = await loadAccountConfig(); if (!isCurrentAccountRigSession(session)) return; accountRigSyncController?.abort(); syncController = new AbortController(); accountRigSyncController = syncController; const result = await synchronizeRigsForAccount(session, websiteApiBase(window.location, config.apiBase), rigPrivateStorage, { signal: syncController.signal }); if (!isCurrentAccountRigSession(session)) return; await refreshAccountRigs(); if (result.quotaExceeded > 0) showToast(t('rig.toast.accountQuota'), 'error'); else if (result.conflicts > 0) showToast(t('rig.toast.accountConflict')); else if (result.pending > 0) showToast(t('rig.toast.accountPending')); else showToast(t('rig.toast.accountSaved')); } catch (error) { if (!isCurrentAccountRigSession(session)) return; if (error instanceof Error && error.message === 'algofish-server-401') { window.dispatchEvent(new CustomEvent('algofish:sessionexpired', { detail: { accountId: session.user.id }, })); } showToast(t(savedLocally ? 'rig.toast.accountPending' : 'rig.toast.accountSaveFailed'), savedLocally ? 'success' : 'error'); } finally { if (accountRigSyncController === syncController) accountRigSyncController = null; refreshAccountSaveButton(); } }); }); elements.syncAccountRigsButton.addEventListener('click', () => { requestAccountRigRefresh({ synchronize: true, announce: true }); }); elements.accountRigConflicts.addEventListener('click', (event) => { const button = event.target.closest('[data-rig-conflict-choice]'); const card = button?.closest('[data-rig-conflict]'); if (button && card) void runAccountRigMutation(() => resolveAccountRigConflict( card.dataset.rigConflict, button.dataset.rigConflictChoice)); }); elements.deleteAccountRigButton.addEventListener('click', () => { void runAccountRigMutation(async () => { const session = getCurrentAccountSession(); const rigId = elements.accountRigSelect.value; const record = accountRigInventory.find((candidate) => candidate.id === rigId); if (!session || !record || !window.confirm(t('rig.deleteAccountRigConfirm', { name: record.document.metadata.name, }))) return; const next = accountRigInventory.filter((candidate) => candidate.id !== rigId); try { // Persist the deletion intent before hiding the local record. If the page // closes between both writes, the next sync can still finish the deletion. await rigPrivateStorage.queueDeletion(session.user.id, rigId); await rigPrivateStorage.saveInventory(session.user.id, next); if (!isCurrentAccountRigSession(session)) return; renderAccountRigInventory(next); await refreshAccountRigs({ synchronize: true, announce: true }); } catch { if (!isCurrentAccountRigSession(session)) return; showToast(t('rig.toast.accountDeleteFailed'), 'error'); } }); }); elements.openAccountRigButton.addEventListener('click', () => { const record = accountRigInventory.find((candidate) => candidate.id === elements.accountRigSelect.value); if (!record) return; rig = structuredClone(record.document); mode = rig.metadata.technique === 'libre' ? 'free' : 'guided'; rigsByMode[mode] = rig; selectedId = null; wireDraft = null; render(); persistRigDrafts(); showToast(t('rig.toast.accountRigOpened', { name: record.document.metadata.name })); }); document.querySelector('#load-json-button').addEventListener('click', () => elements.jsonFileInput.click()); elements.jsonFileInput.addEventListener('change', async () => { const [file] = elements.jsonFileInput.files; if (!file) return; try { rig = parseRigJson(await file.text()); mode = rig.metadata?.technique === 'libre' ? 'free' : 'guided'; rigsByMode[mode] = rig; selectedId = null; wireDraft = null; render(); showToast(t('rig.toast.jsonLoaded')); } catch (error) { showToast(t('rig.toast.importFailed', { message: localizedErrorMessage(error) }), 'error'); } finally { elements.jsonFileInput.value = ''; } }); document.querySelector('#export-svg-button').addEventListener('click', async () => { try { await exportRigSvg(elements.canvas, rig); showToast(t('rig.toast.svgExported')); } catch (error) { showToast(t('rig.toast.exportFailed', { message: localizedErrorMessage(error) }), 'error'); } }); document.querySelector('#export-png-button').addEventListener('click', async () => { try { await exportRigPng(elements.canvas, rig); showToast(t('rig.toast.pngExported')); } catch (error) { showToast(t('rig.toast.exportFailed', { message: localizedErrorMessage(error) }), 'error'); } }); applyCanvasTheme(whiteBackground); render(); refreshAccountSaveButton(); requestAccountRigRefresh({ synchronize: true });