document.addEventListener('DOMContentLoaded', () => { const ja = document.documentElement.lang.startsWith('ja'); const id = location.pathname.split('/').filter(Boolean).pop(); const result = document.querySelector('[data-import-result]'); const rows = () => Array.from(document.querySelectorAll('[data-import-item]')); const fields = ['target_path', 'quartier', 'street', 'spot']; const namePattern = /^[a-z0-9][a-z0-9_-]{1,63}$/; const style = document.createElement('style'); style.textContent = '.import-bulk-replace{display:flex;gap:.45rem;align-items:center;flex-wrap:wrap;margin:.7rem 0}.import-row-warning{display:block;color:var(--danger);font-size:.72rem;max-width:15rem;white-space:normal}.import-row-hint{color:var(--muted)}tr.import-invalid{background:color-mix(in srgb,var(--danger) 8%,transparent)}'; document.head.appendChild(style); document.querySelectorAll('[data-field=spot]').forEach(input => { if (!input.value) input.placeholder = ja ? '未定義(Street所属)' : 'Undefined (Street inbox)'; const status = document.createElement('small'); status.className = 'import-row-warning'; input.closest('td').appendChild(status); }); const validateRow = row => { const get = name => row.querySelector(`[data-field=${name}]`).value.trim(); const sourceDepth = row.querySelector('code').textContent.split('/').filter(Boolean).length; const quartier = get('quartier'), street = get('street'), spot = get('spot'); const status = row.querySelector('.import-row-warning'); let error = '', hint = ''; if (street && !quartier) error = ja ? 'StreetにはQuartierが必要です' : 'Street requires a Quartier'; else if (spot && !street) error = ja ? 'SpotにはStreetが必要です' : 'Spot requires a Street'; else if ([quartier, street, spot].some(value => value && !namePattern.test(value))) error = ja ? 'City名は英小文字・数字・_・-を2〜64文字で指定してください' : 'City names require 2–64 lowercase letters, digits, _ or -'; else if (spot === street && spot) hint = ja ? '同名のため未定義Spotとして配置されます' : 'Same name: assigned to the undefined Spot'; else if (!spot && street) hint = ja ? '未定義SpotとしてStreetへ所属します' : 'Assigned to the Street undefined Spot'; else if (spot && sourceDepth <= 3) hint = ja ? `Spot PathはStreet配下の _${spot} になります` : `Spot Path will be _${spot} below the Street`; status.textContent = error || hint; status.classList.toggle('import-row-hint', !error); row.classList.toggle('import-invalid', !!error); return !error; }; const validateAll = () => rows().every(validateRow); rows().forEach(row => fields.forEach(field => row.querySelector(`[data-field=${field}]`).addEventListener('input', () => validateRow(row)))); validateAll(); const actions = document.querySelector('.import-actions'); if (actions) { const bulk = document.createElement('div'); bulk.className = 'import-bulk-replace'; bulk.innerHTML = `${ja ? '一括置換' : 'Bulk replace'}→`; actions.before(bulk); bulk.querySelector('[data-replace-apply]').addEventListener('click', () => { const from = bulk.querySelector('[data-replace-from]').value; if (!from) return; const to = bulk.querySelector('[data-replace-to]').value; const scope = bulk.querySelector('[data-replace-field]').value; const targets = scope === 'all' ? fields : [scope]; rows().forEach(row => targets.forEach(field => { const input = row.querySelector(`[data-field=${field}]`); input.value = input.value.split(from).join(to); })); validateAll(); }); } document.querySelector('.import-table-wrap')?.addEventListener('keydown', event => { if (event.key !== 'Tab' || !event.target.matches('input[data-field]:not([type=checkbox])')) return; const column = event.target.dataset.field; const inputs = rows().map(row => row.querySelector(`input[data-field=${column}]`)).filter(Boolean); const current = inputs.indexOf(event.target); const next = current + (event.shiftKey ? -1 : 1); if (next < 0 || next >= inputs.length) return; event.preventDefault(); inputs[next].focus(); inputs[next].select(); }); const collect = () => rows().map(row => ({ sequence: Number(row.dataset.sequence), selected: row.querySelector('[data-field=selected]').checked, target_path: row.querySelector('[data-field=target_path]').value, quartier: row.querySelector('[data-field=quartier]').value, street: row.querySelector('[data-field=street]').value, spot: row.querySelector('[data-field=spot]').value, })); const call = async (method, body) => { if (result) result.textContent = '…'; const response = await fetch('/_/api/v1/import/' + encodeURIComponent(id), {method, headers: {'Content-Type': 'application/json'}, body: body ? JSON.stringify(body) : undefined}); const data = await response.json().catch(() => ({})); if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`); return data; }; document.querySelector('[data-save-plan]')?.addEventListener('click', async () => { if (!validateAll()) return; try { await call('PATCH', {items: collect()}); result.textContent = ja ? '計画を保存しました' : 'Plan saved'; } catch (error) { result.textContent = error.message; } }); document.querySelector('[data-commit-import]')?.addEventListener('click', async () => { if (!validateAll()) return; try { await call('PATCH', {items: collect()}); await call('POST', {conflict: document.querySelector('[data-conflict]').value}); location.reload(); } catch (error) { result.textContent = error.message; } }); document.querySelector('[data-rollback-import]')?.addEventListener('click', async () => { if (!confirm(ja ? 'このimportで作成したPathを取り消しますか?' : 'Roll back paths created by this import?')) return; try { await call('DELETE'); location.reload(); } catch (error) { result.textContent = error.message; } }); });