Files
pages/static/js/city-organizer.js
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

166 lines
14 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// City-only organization. Document URLs are not renamed by these actions.
window.PagesWikiCityOrganizer = ({svg, getCity, reload, dismissMenus, canPlan}) => {
if (!canPlan) return null;
const ja = document.documentElement.lang.startsWith('ja');
const words = ja ? {
rename:'表示名を変更', title:'表示名', save:'保存', cancel:'キャンセル',
merge:'既存Spotに統合', create:'新しいSpotにまとめる', move:'別のStreetに移す', clear:'選択を解除',
selected:'件を選択中', target:'統合先Spot', street:'配置先Street', path:'SpotのPath境界', name:'識別名',
advanced:'詳細設定', unchanged:'PageのURL・UUID・内容は変更しません。Spotの入れ子は作りません。',
mergeHelp:'選択したPageをまとめます。選択元のSpot全体を統合した場合、元Spotは地図から除去し、関連リンクを統合先へ引き継ぎます。',
moveHelp:'SpotのUUIDを保ってStreetとPath境界を変更します。既存PageはURLを変えず、明示的な所属として引き継ぎます。',
renameHelp:'地図の表示名だけを変更します。識別名と既存リンクは維持されます。',
empty:'選べる宛先がありません。新しいSpotを作成してください。', busy:'保存中…', failed:'操作に失敗しました。',
city_changed:'地図が更新されています。閉じて地図を更新し、選択内容を確認してから再実行してください。',
city_invalid_selection:'選択が無効です。地図を更新して選択し直してください。',
city_invalid_target:'選択元と異なる有効な宛先を指定してください。',
city_invalid_title:'表示名を1〜160文字で入力してください。', city_name_conflict:'識別名が使用済みです。詳細設定で変更してください。',
city_too_many_pages:'一度に処理できるPage数を超えています。選択を分けてください。',
city_too_many_relations:'関連リンクが多すぎます。選択するSpotを分けてください。',
boundary:'Pathは配置先の配下に指定し、ほかのSpotの境界と重ならないようにしてください。',
forbidden:'この操作にはドメイン管理権限が必要です。', refresh:'地図を更新', hint:'Ctrl / ⌘ + クリックで複数選択'
} : {
rename:'Rename display title', title:'Display title', save:'Save', cancel:'Cancel',
merge:'Merge into Spot', create:'Create Spot from selection', move:'Move to Street', clear:'Clear selection',
selected:'selected', target:'Destination Spot', street:'Destination Street', path:'Spot Path boundary', name:'Identifier',
advanced:'Advanced', unchanged:'Page URLs, UUIDs and content are preserved. Spots cannot contain other Spots.',
mergeHelp:'Combine the selected Pages. Whole source Spots are removed from the map; their relations are transferred to the destination.',
moveHelp:'Keep Spot UUIDs while changing Street and Path boundaries. Existing Pages retain their URLs and are kept as explicit members.',
renameHelp:'Change the map title only. Identifiers and existing links remain unchanged.',
empty:'No destination is available. Create a new Spot instead.', busy:'Saving…', failed:'Operation failed.',
city_changed:'The map changed. Close this dialog, refresh and review the selection before retrying.',
city_invalid_selection:'Invalid selection. Refresh and select again.', city_invalid_target:'Choose a valid destination outside the selection.',
city_invalid_title:'Enter a title of 1–160 characters.', city_name_conflict:'Identifier already exists. Change it in Advanced.',
city_too_many_pages:'Too many Pages for one operation. Split the selection.',
city_too_many_relations:'Too many relations. Select fewer Spots.',
boundary:'The Path must be under the destination and must not overlap another Spot boundary.',
forbidden:'Domain administrator access is required.', refresh:'Refresh map', hint:'Ctrl / ⌘ + click to select multiple items'
};
const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const selection = new Map();
const spots = () => (getCity()?.quartiers || []).flatMap(q => q.streets.flatMap(s => s.spots.map(p => ({...p, street:s, quartier:q}))));
const streets = () => (getCity()?.quartiers || []).flatMap(q => q.streets.map(s => ({...s, quartier:q})));
const pageKey = (spot, page) => `page:${spot}:${page}`;
const pick = target => {
const page = target.closest?.('.city-map-page-link');
const spot = target.closest?.('[data-city-type="Spot"]');
if (!spot) return null;
const item = spots().find(p => p.uuid === spot.dataset.cityUuid);
if (!item) return null;
if (page) return {key:pageKey(item.uuid,page.dataset.pageUuid),spot_uuid:item.uuid,page_uuid:page.dataset.pageUuid,title:page.getAttribute('aria-label')};
return {key:`spot:${item.uuid}`,spot_uuid:item.uuid,title:item.title || item.name};
};
const bar = document.createElement('div');
bar.className='city-selection-bar'; bar.hidden=true;
bar.innerHTML=`<span data-city-selected-count aria-live="polite"></span>`;
svg.closest('.city-canvas-wrap').append(bar);
const button = (container, title, icon, action, attribute) => {
const el=document.createElement('button'); el.type='button';el.title=title;el.setAttribute('aria-label',title);
if(attribute)el.setAttribute(attribute,'');if(container.getAttribute('role')==='menu')el.setAttribute('role','menuitem');el.textContent=icon;el.addEventListener('click',action);container.append(el);return el;
};
const syncSelection = () => {
bar.hidden=selection.size===0;
bar.querySelector('[data-city-selected-count]').textContent=`${selection.size} ${words.selected}`;
moveButton.disabled=[...selection.values()].some(p=>p.page_uuid);
svg.querySelectorAll('[data-city-type="Spot"]').forEach(el=>el.classList.toggle('city-is-selected',selection.has(`spot:${el.dataset.cityUuid}`)));
svg.querySelectorAll('.city-map-page-link').forEach(el=>el.classList.toggle('city-is-selected',selection.has(pageKey(el.closest('[data-city-uuid]').dataset.cityUuid,el.dataset.pageUuid))));
};
const add = item => {
if(item.page_uuid)selection.delete(`spot:${item.spot_uuid}`);
else for(const [key,value] of selection)if(value.spot_uuid===item.spot_uuid)selection.delete(key);
selection.set(item.key,item);
};
button(bar,words.merge,'↪',()=>organize('merge'),'data-city-merge');
button(bar,words.create,'+',()=>organize('create'),'data-city-create-selection');
const moveButton=button(bar,words.move,'⇄',()=>organize('move'),'data-city-move-selection');
button(bar,words.clear,'×',()=>{selection.clear();syncSelection();},'data-city-clear-selection');
svg.addEventListener('pointerdown',event=>{if((event.ctrlKey||event.metaKey)&&pick(event.target))event.stopPropagation();},true);
svg.addEventListener('click',event=>{
if(!(event.ctrlKey||event.metaKey)||event.cityDragSuppressed)return;
const item=pick(event.target);if(!item)return;
event.preventDefault();event.stopImmediatePropagation();
if(selection.has(item.key))selection.delete(item.key);else if(selection.size<200)add(item);
syncSelection();
},true);
const errorText = error => words[error.message] || (/Path|boundar/.test(error.message)?words.boundary:error.message || words.failed);
const post = async (url, body) => {
const response=await fetch(url,{method:'POST',headers:{'Content-Type':'application/json','Accept':'application/json'},body:JSON.stringify(body)});
const data=await response.json().catch(()=>({}));
if(!response.ok)throw new Error(response.status===403||response.status===401?'forbidden':data.error||`HTTP ${response.status}`);
return data;
};
let dialog=null;
const openDialog = (title, content, submit) => {
dismissMenus();dialog?.close();
const previous=document.activeElement,el=document.createElement('dialog');dialog=el;el.className='city-organize-dialog';
el.innerHTML=`<form><h2>${escape(title)}</h2>${content}<p class="muted">${escape(words.unchanged)}</p><p data-city-organize-error role="alert"></p><footer><button type="button" data-city-dialog-cancel>${escape(words.cancel)}</button><button type="submit">${escape(words.save)}</button></footer></form>`;
document.body.append(el);let busy=false;
el.addEventListener('close',()=>{el.remove();if(dialog===el)dialog=null;if(previous?.isConnected)previous.focus();});
el.addEventListener('cancel',event=>{if(busy)event.preventDefault();});
// Stop outer map-popup Escape handlers; native dialog cancellation still runs.
el.addEventListener('keydown',event=>{if(event.key==='Escape')event.stopPropagation();});
el.querySelector('[data-city-dialog-cancel]').addEventListener('click',()=>el.close());
el.querySelector('form').addEventListener('submit',async event=>{
event.preventDefault();if(busy)return;busy=true;
const error=el.querySelector('[data-city-organize-error]'),buttons=el.querySelectorAll('button');
buttons.forEach(b=>b.disabled=true);error.textContent=words.busy;
try {await submit(new FormData(event.target));selection.clear();syncSelection();await reload();el.close();}
catch(e){error.textContent=errorText(e);}
finally{busy=false;buttons.forEach(b=>b.disabled=false);}
});
el.showModal();el.querySelector('input,select')?.focus();return el;
};
const rename = (type, item) => {
const version=getCity().version;
const el=openDialog(words.rename,`<label>${escape(words.title)}<input name="title" value="${escape(item.title||item.name)}" required maxlength="160"></label><p>${escape(words.renameHelp)}</p>`,data=>post(`/_/api/v1/city/${type==='Spot'?'spots':'zones'}/${encodeURIComponent(item.uuid)}/title`,{kind:type.toLowerCase(),title:data.get('title'),base_version:version}));
el.querySelector('input').select();
};
const organize = action => {
if(!selection.size)return;
const entries=[...selection.values()],base_version=getCity().version;
const request={action:action==='move'?'move':'merge',base_version,spots:entries.filter(p=>!p.page_uuid).map(p=>p.spot_uuid),pages:entries.filter(p=>p.page_uuid).map(({spot_uuid,page_uuid})=>({spot_uuid,page_uuid}))};
if(action==='move'&&request.pages.length)return;
const options=streets(),firstSource=spots().find(p=>p.uuid===entries[0].spot_uuid);
const defaultStreet=firstSource?.street.uuid||options[0]?.uuid;
const name=`spot-${crypto.randomUUID().slice(0,8)}`;
const choices=spots().filter(p=>!entries.some(e=>e.spot_uuid===p.uuid)&&!p.name.endsWith('-undefined')&&!p.path_prefix.endsWith('/_undefined'));
let fields=`<ul class="city-selection-summary">${entries.map(e=>`<li>${escape(e.title)}</li>`).join('')}</ul><p>${escape(action==='move'?words.moveHelp:words.mergeHelp)}</p>`;
if(action==='merge')fields+=`<label>${escape(words.target)}<select name="target" required>${choices.map(p=>`<option value="${p.uuid}">${escape(p.quartier.title)} / ${escape(p.street.title)} / ${escape(p.title)}</option>`).join('')}</select></label>${choices.length?'':`<p>${escape(words.empty)}</p>`}`;
else {
fields+=`<label>${escape(words.street)}<select name="street" required>${options.map(s=>`<option value="${s.uuid}" ${s.uuid===defaultStreet?'selected':''}>${escape(s.quartier.title)} / ${escape(s.title)}</option>`).join('')}</select></label>`;
if(action==='create')fields+=`<label>${escape(words.title)}<input name="title" required maxlength="160"></label><details><summary>${escape(words.advanced)}</summary><label>${escape(words.name)}<input name="name" value="${name}" required pattern="[a-z0-9][a-z0-9_-]{1,63}"></label></details>`;
if(action==='create'||entries.length===1)fields+=`<label>${escape(words.path)}<input name="path" required></label>`;
}
const el=openDialog(words[action],fields,data=>{
if(action==='merge')request.target_spot_uuid=data.get('target');
else if(action==='create')request.new_spot={street_uuid:data.get('street'),name:data.get('name'),title:data.get('title'),path_prefix:data.get('path')};
else {request.street_uuid=data.get('street');request.path_prefix=data.get('path')||'';}
return post('/_/api/v1/city/organize',request);
});
if(action!=='merge'){
const form=el.querySelector('form');
const updatePath=()=>{const street=options.find(s=>s.uuid===form.elements.street.value),leaf=action==='create'?form.elements.name.value:firstSource.path_prefix.split('/').pop();if(form.elements.path)form.elements.path.value=street.path_prefix.replace(/\/$/,'')+'/'+leaf;};
form.elements.street.addEventListener('change',updatePath);form.elements.name?.addEventListener('input',updatePath);updatePath();
}
};
return {
syncSelection,
refresh(){const current=spots();for(const [key,item] of selection)if(!current.some(s=>s.uuid===item.spot_uuid&&(!item.page_uuid||s.pages.some(p=>p.page_uuid===item.page_uuid))))selection.delete(key);syncSelection();},
decorateInspector(container,type,item){
const heading=container.querySelector('h2');if(heading)button(heading,words.rename,'✎',()=>rename(type,item),'data-city-rename');
if(heading&&type==='Spot')button(heading,words.move,'⇄',()=>{selection.clear();add({key:`spot:${item.uuid}`,spot_uuid:item.uuid,title:item.title||item.name});syncSelection();organize('move');},'data-city-move-selection');
},
context(menu,type,item,event){
const hit=pick(event.target);
if(!hit?.page_uuid)button(menu,words.rename,words.rename,()=>rename(type,item),'data-city-rename');
if(type==='Spot'){
if(hit&&!selection.has(hit.key)){selection.clear();add(hit);syncSelection();}
if(hit?.page_uuid){menu.querySelector('strong').textContent=hit.title;menu.querySelector('[data-delete-city]')?.remove();}
button(menu,words.merge,words.merge,()=>organize('merge'),'data-city-merge');
button(menu,words.create,words.create,()=>organize('create'),'data-city-create-selection');
if(![...selection.values()].some(p=>p.page_uuid))button(menu,words.move,words.move,()=>organize('move'),'data-city-move-selection');
}
}
};
};