Refactor architecture into eight components and consolidate reliability work
Build and publish container images / images (push) Successful in 9m34s
Release container images / release (push) Successful in 36s

Extract Grammaratur, Dregarnuhr, Geduldh, Mestionora, Ordoschnellic, Schutzaria, Kunstzeal and Seheweit behind compatible application contracts.

Include accumulated editor resilience, navigation and theme UX, remote CLI, storage/schema and DR groundwork, tests and design/operations documentation.

Verified: uncached full Go suite; go vet ./...; race tests for all eight components; 11 targeted Chromium tests; Node suites; 19 Python CLI tests; reproducible editor build. No push, release tag or deployment in this checkpoint.
This commit is contained in:
Anya Tokugawa committed 2026-11-01 15:23:31 +09:00
1 parent 9dd425f765
commit d5d21b7841
302 files changed
+20037 -3492

No files matched your search

+89
View File
@@ -0,0 +1,89 @@
// These commands resolve Wiki paths only. They never run shell commands or open
// user-supplied URL schemes, and all writes remain in the authorized editor.
(() => {
function resolvePath(value, current = '/') {
if (/^[a-z][a-z0-9+.-]*:/i.test(value) || value.startsWith('//') || /[\\\u0000-\u001f\u007f]/.test(value)) {
throw new Error('invalid_path');
}
const parts = (value.startsWith('/') ? [] : current.split('/').filter(Boolean));
for (const part of value.split('/')) {
if (!part || part === '.') continue;
if (part === '..') parts.pop();
else parts.push(part);
}
return '/' + parts.join('/');
}
function destination(value, current = '/') {
value = value.trim();
let command = 'cd';
const match = /^(cd|vi|view)(?:\s+(.*))?$/s.exec(value);
if (match) {
command = match[1];
value = match[2] || (command === 'cd' ? '/' : current);
}
const path = resolvePath(value, current);
// Each segment is literal. In particular #, ?, % and Unicode belong to the
// Path, not URL syntax; never decode user input a second time.
const encoded = path.split('/').map(encodeURIComponent).join('/');
return {command, path, href: command === 'vi' ? '/e/-' + encoded : command === 'view' ? encoded : '/v/browser' + encoded};
}
if (typeof module !== 'undefined' && module.exports) module.exports = {resolvePath, destination};
if (typeof document === 'undefined') return;
window.PagesWikiPaths = {resolvePath, destination};
const root = document.querySelector('[data-browser-address]');
if (!root) return;
const current = root.dataset.path;
const input = root.querySelector('input');
const error = document.getElementById('browser-address-error');
const navigate = value => {
try {
const target = destination(value, current);
error.textContent = '';
location.assign(target.href);
} catch (_) {
error.textContent = root.dataset.invalidLabel;
input.focus();
}
};
root.addEventListener('submit', event => {
event.preventDefault();
navigate('cd ' + input.value);
});
input.addEventListener('keydown', event => {
if (event.key === 'Escape') { input.value = current; error.textContent = ''; input.blur(); }
});
input.addEventListener('input', () => { error.textContent = ''; });
document.querySelector('[data-browser-up]')?.addEventListener('click', () => navigate('cd ..'));
const dialog = document.querySelector('[data-browser-create-dialog]');
const name = dialog.querySelector('[name="path"]');
const createError = dialog.querySelector('[role="alert"]');
let mode = 'vi';
document.querySelectorAll('[data-browser-create]').forEach(button => button.addEventListener('click', () => {
mode = button.dataset.browserCreate;
dialog.querySelector('h2').textContent = button.title;
dialog.querySelector('[type="submit"]').textContent = mode === 'vi' ? root.dataset.editLabel : root.dataset.openLabel;
name.value = '';
name.setCustomValidity('');
createError.textContent = '';
dialog.querySelector('[data-browser-format]').hidden = mode !== 'vi';
dialog.showModal();
name.focus();
}));
dialog.querySelector('[data-browser-create-cancel]').addEventListener('click', () => dialog.close());
name.addEventListener('input', () => { name.setCustomValidity(''); createError.textContent = ''; });
dialog.querySelector('form').addEventListener('submit', event => {
event.preventDefault();
try {
if (!name.value.trim()) throw new Error('invalid_path');
const path = resolvePath(name.value.trim(), current);
if (mode === 'vi' && path === '/') throw new Error('invalid_path');
let href = destination(mode + ' ' + path, current).href;
if (mode === 'vi' && dialog.querySelector('[name="format"]').value === 'plain') href += '?edittype=plain';
location.assign(href);
} catch (_) {
createError.textContent = root.dataset.invalidLabel;
name.setCustomValidity(root.dataset.invalidLabel);
name.reportValidity();
}
});
})();
+4 -3
View File
@@ -8,6 +8,7 @@
// API may suggest a descendant as a fallback portal (also in undefined
// buckets); such a Page must keep its independently selectable building.
const surroundingPages=spot=>uniquePages(spot).filter(p=>!(p.page_uuid===spot.portal_page_uuid&&p.path===spot.path_prefix));
const displayTitle = spot => spot.display_title || spot.title || spot.name;
const undefinedSpot=spot=>spot.name?.endsWith('-undefined')||spot.path_prefix?.endsWith('/_undefined');
const pageName=p=>p.label||(p.path||'').split('/').filter(Boolean).pop()||p.page_uuid;
const pageURL=p=>p.path?p.path.split('/').map(encodeURIComponent).join('/'):`/o/uuid:${encodeURIComponent(p.page_uuid)}`;
@@ -73,14 +74,14 @@
group.append(el('path',{d:`M${x-w/2+12} ${y-h/2+35}V${y+h/2-35}M${x+w/2-12} ${y-h/2+35}V${y+h/2-35}`,class:'estate-balustrade'}));
}
function entry(group,spot,x,y,onSpot,isUndefined,large=false) {
const g=el('g',{class:large?'city-spot-monument':'city-spot-entry',role:large?'img':'button',...(large?{}:{tabindex:0}),'aria-label':spot.title||spot.name});
const g=el('g',{class:large?'city-spot-monument':'city-spot-entry',role:large?'img':'button',...(large?{}:{tabindex:0}),'aria-label':displayTitle(spot)});
if(!isUndefined)use(g,'city-palazzo',x-61,y-49,122,92);
else {g.append(el('circle',{cx:x,cy:y-5,r:25,class:'estate-fountain'}),el('circle',{cx:x,cy:y-5,r:12,class:'estate-fountain-inner'}));}
label(g,'city-spot-point-label',x,y+59,isUndefined?(document.documentElement.lang.startsWith('ja')?'未分類のPage':'Unclassified Pages'):spot.title||spot.name,large?260:195,large?20:17);
label(g,'city-spot-point-label',x,y+59,displayTitle(spot),large?260:195,large?20:17);
group.append(g);
}
function spotGroup(spot,onSpot,focused=false) {
const group=el('g',{class:'city-node city-spot-tile','data-city-type':'Spot','data-city-uuid':spot.uuid,role:'group','aria-label':spot.title||spot.name});
const group=el('g',{class:'city-node city-spot-tile','data-city-type':'Spot','data-city-uuid':spot.uuid,role:'group','aria-label':displayTitle(spot)});
group.addEventListener('click',event=>{if(event.target.closest('a'))return;event.stopPropagation();if(!focused)onSpot(spot);});return group;
}
function streetScene(street,roads,page,onSpot) {
+10 -9
View File
@@ -22,6 +22,7 @@
let suspended = false;
let navigation = null;
let organizer = null;
const displayTitle = item => item?.display_title || item?.title || item?.name || '';
const label = key => svg.dataset[key] || key;
const popupMode = new URLSearchParams(location.search).get('popup') === '1';
if (popupMode) { document.documentElement.classList.add('city-map-popup-mode'); document.body.classList.add('city-map-popup-mode'); }
@@ -42,7 +43,7 @@
};
const show = (type, item, parent = '') => {
inspector.dataset.cityType=type;inspector.dataset.cityUuid=item.uuid;
inspector.innerHTML = `<h2>${escapeHTML(item.title || item.name)}</h2><dl><dt>Type</dt><dd>${type}</dd><dt>Name</dt><dd>${escapeHTML(item.name)}</dd><dt>Path</dt><dd><code>${escapeHTML(item.path_prefix || '—')}</code></dd>${parent ? `<dt>Location</dt><dd>${escapeHTML(parent)}</dd>` : ''}<dt>State</dt><dd>${escapeHTML(item.state)}</dd></dl>${item.description || item.summary ? `<p>${escapeHTML(item.description || item.summary)}</p>` : ''}<p><a class="city-detail-link" href="${escapeHTML(detailURL(type,item))}">Details →</a></p>${document.querySelector('.city-planner') ? `<button type="button" class="city-delete" data-delete-city-node data-city-type="${type}" data-city-uuid="${item.uuid}">${document.documentElement.lang.startsWith('ja') ? 'この要素を削除' : 'Delete this element'}</button>` : ''}`;
inspector.innerHTML = `<h2>${escapeHTML(displayTitle(item))}</h2><dl><dt>Type</dt><dd>${type}</dd><dt>Name</dt><dd>${escapeHTML(item.name)}</dd><dt>Path</dt><dd><code>${escapeHTML(item.path_prefix || '—')}</code></dd>${parent ? `<dt>Location</dt><dd>${escapeHTML(parent)}</dd>` : ''}<dt>State</dt><dd>${escapeHTML(item.state)}</dd></dl>${item.description || item.summary ? `<p>${escapeHTML(item.description || item.summary)}</p>` : ''}<p><a class="city-detail-link" href="${escapeHTML(detailURL(type,item))}">Details →</a></p>${document.querySelector('.city-planner') ? `<button type="button" class="city-delete" data-delete-city-node data-city-type="${type}" data-city-uuid="${item.uuid}">${document.documentElement.lang.startsWith('ja') ? 'この要素を削除' : 'Delete this element'}</button>` : ''}`;
inspector.querySelector('[data-delete-city-node]')?.addEventListener('click', event => deleteNode(event.currentTarget.dataset.cityType, item));
organizer?.decorateInspector(inspector,type,item);
};
@@ -62,9 +63,9 @@
const pageList = pages.length ? `<h3>Pages</h3><ul>${pages.map(page => `<li><a href="${escapeHTML(window.PagesWikiCityEstates.pageURL(page))}">${escapeHTML(page.label || page.path || page.page_uuid)}</a> <small>${escapeHTML(page.edge_type)}</small>${canPlan ? ` <button type="button" data-remove-page="${page.page_uuid}" data-edge="${page.edge_type}" aria-label="Remove">×</button>` : ''}</li>`).join('')}</ul>` : '<p class="muted">No Pages</p>';
inspector.insertAdjacentHTML('beforeend', pageList);
const relations = city.relations.filter(relation => relation.source_spot_uuid === spot.uuid);
if (relations.length) inspector.insertAdjacentHTML('beforeend', `<h3>Relations</h3><ul>${relations.map(relation => { const target = city.quartiers.flatMap(q => q.streets.flatMap(s => s.spots)).find(item => item.uuid === relation.target_spot_uuid); return `<li>${escapeHTML(relation.relation_type)} → ${escapeHTML(target?.title || relation.target_spot_uuid)}${canPlan ? ` <button type="button" data-remove-relation="${relation.target_spot_uuid}" data-relation="${relation.relation_type}" aria-label="Remove">×</button>` : ''}</li>`; }).join('')}</ul>`);
if (relations.length) inspector.insertAdjacentHTML('beforeend', `<h3>Relations</h3><ul>${relations.map(relation => { const target = city.quartiers.flatMap(q => q.streets.flatMap(s => s.spots)).find(item => item.uuid === relation.target_spot_uuid); return `<li>${escapeHTML(relation.relation_type)} → ${escapeHTML(displayTitle(target) || relation.target_spot_uuid)}${canPlan ? ` <button type="button" data-remove-relation="${relation.target_spot_uuid}" data-relation="${relation.relation_type}" aria-label="Remove">×</button>` : ''}</li>`; }).join('')}</ul>`);
if (canPlan) {
const options = city.quartiers.flatMap(q => q.streets.flatMap(s => s.spots)).filter(item => item.uuid !== spot.uuid).map(item => `<option value="${item.uuid}">${escapeHTML(item.title)}</option>`).join('');
const options = city.quartiers.flatMap(q => q.streets.flatMap(s => s.spots)).filter(item => item.uuid !== spot.uuid).map(item => `<option value="${item.uuid}">${escapeHTML(displayTitle(item))}</option>`).join('');
inspector.insertAdjacentHTML('beforeend', `<details><summary>SpotGraph</summary><form data-spot-page><label>Page path<input name="path" placeholder="/guide/page" required></label><label>Edge<select name="edge_type"><option>primary</option><option>guide</option><option>reference</option><option>example</option><option>attachment</option><option>related</option></select></label><button>Add Page</button></form><form data-spot-relation><label>Destination<select name="target_spot_uuid">${options}</select></label><label>Relation<select name="relation_type"><option>related</option><option>depends_on</option><option>supersedes</option><option>implements</option><option>learn_before</option><option>operated_by</option></select></label><button>Add relation</button></form></details>`);
inspector.querySelector('[data-spot-page]')?.addEventListener('submit', async event => { event.preventDefault(); const response = await fetch(`/_/api/v1/city/spots/${spot.uuid}/pages`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(Object.fromEntries(new FormData(event.target)))}); if (response.ok) await load(); else alert((await response.json()).error); });
inspector.querySelector('[data-spot-relation]')?.addEventListener('submit', async event => { event.preventDefault(); const response = await fetch(`/_/api/v1/city/spots/${spot.uuid}/relations`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(Object.fromEntries(new FormData(event.target)))}); if (response.ok) await load(); else alert((await response.json()).error); });
@@ -85,7 +86,7 @@
const closeContext = () => { contextMenu?.remove(); contextMenu = null; };
const deleteNode = async (type, item) => {
const ja = document.documentElement.lang.toLowerCase().startsWith('ja');
if (!confirm(ja ? `${item.title || item.name} を削除しますか? 下位要素も案内図から削除されます。ドキュメント自体は削除されません。` : `Delete ${item.title || item.name}? Descendants are removed from the map; documents are preserved.`)) return;
if (!confirm(ja ? `${displayTitle(item)} を削除しますか? 下位要素も案内図から削除されます。ドキュメント自体は削除されません。` : `Delete ${displayTitle(item)}? Descendants are removed from the map; documents are preserved.`)) return;
const plural = type === 'Spot' ? 'spots' : 'zones';
const options = {method:'DELETE', headers:{'Content-Type':'application/json'}};
if (type !== 'Spot') options.body = JSON.stringify({kind:type.toLowerCase()});
@@ -99,7 +100,7 @@
const url = event.target.closest?.('.city-map-page-link')?.getAttribute('href') || detailURL(type, item);
contextMenu = document.createElement('div');
contextMenu.className = 'city-context-menu'; contextMenu.setAttribute('role', 'menu');
contextMenu.innerHTML = `<strong>${escapeHTML(item.title || item.name)}</strong><a role="menuitem" href="${escapeHTML(url)}">${ja ? '詳細を開く' : 'Open details'}</a><a role="menuitem" href="${escapeHTML(url)}" target="_blank" rel="noopener">${ja ? '新しいタブで開く' : 'Open in new tab'}</a><button type="button" role="menuitem" data-copy-city-link>${ja ? 'リンクをコピー' : 'Copy link'}</button>${document.querySelector('.city-planner') ? `<button type="button" class="city-context-delete" role="menuitem" data-delete-city>${ja ? '削除' : 'Delete'}</button>` : ''}`;
contextMenu.innerHTML = `<strong>${escapeHTML(displayTitle(item))}</strong><a role="menuitem" href="${escapeHTML(url)}">${ja ? '詳細を開く' : 'Open details'}</a><a role="menuitem" href="${escapeHTML(url)}" target="_blank" rel="noopener">${ja ? '新しいタブで開く' : 'Open in new tab'}</a><button type="button" role="menuitem" data-copy-city-link>${ja ? 'リンクをコピー' : 'Copy link'}</button>${document.querySelector('.city-planner') ? `<button type="button" class="city-context-delete" role="menuitem" data-delete-city>${ja ? '削除' : 'Delete'}</button>` : ''}`;
document.body.append(contextMenu);
organizer?.context(contextMenu,type,item,event);
const rect = contextMenu.getBoundingClientRect();
@@ -132,7 +133,7 @@
function updateCityTrail() {
let trail=document.querySelector('[data-city-trail]'); if(!trail){trail=document.createElement('nav');trail.className='city-trail';trail.dataset.cityTrail='';document.querySelector('.city-toolbar').prepend(trail);}
const q=city.quartiers.find(item=>item.uuid===cityView.quartier), s=q?.streets.find(item=>item.uuid===cityView.street),p=s?.spots.find(item=>item.uuid===cityView.spot);
trail.innerHTML=`<button type="button" data-city-level="domain">City</button>${q?`<span>›</span><button type="button" data-city-level="quartier">${escapeHTML(q.title)}</button>`:''}${s?`<span>›</span><button type="button" data-city-level="street">${escapeHTML(s.title)}</button>`:''}${cityView.level==='spot'&&p?`<span>›</span><span aria-current="location">${escapeHTML(p.title)}</span>`:''}`;
trail.innerHTML=`<button type="button" data-city-level="domain">City</button>${q?`<span>›</span><button type="button" data-city-level="quartier">${escapeHTML(q.title)}</button>`:''}${s?`<span>›</span><button type="button" data-city-level="street">${escapeHTML(s.title)}</button>`:''}${cityView.level==='spot'&&p?`<span>›</span><span aria-current="location">${escapeHTML(displayTitle(p))}</span>`:''}`;
trail.querySelector('[data-city-level="domain"]')?.addEventListener('click',()=>{cityView={level:'domain',quartier:null,street:null};renderScene();});
trail.querySelector('[data-city-level="quartier"]')?.addEventListener('click',()=>{cityView={level:'quartier',quartier:q.uuid,street:null};renderScene();});
trail.querySelector('[data-city-level="street"]')?.addEventListener('click',()=>{cityView={level:'street',quartier:q.uuid,street:s.uuid};renderScene();});
@@ -251,7 +252,7 @@
}
}
function renderDirectory(data) {
const jump=(type,item)=>`<button type="button" data-city-jump="${type}" data-city-id="${item.uuid}">${escapeHTML(item.title||item.name)}</button>`;
const jump=(type,item)=>`<button type="button" data-city-jump="${type}" data-city-id="${item.uuid}">${escapeHTML(displayTitle(item))}</button>`;
directory.innerHTML = `<div class="city-directory-grid">${data.quartiers.map(q => `<article><h3>${jump('quartier',q)}</h3>${q.description ? `<p>${escapeHTML(q.description)}</p>` : ''}${q.streets.map(s => `<h4>${jump('street',s)}</h4><ul>${s.spots.map(p => `<li>${jump('spot',p)}</li>`).join('')}</ul>`).join('')}</article>`).join('')}</div>`;
directory.querySelectorAll('[data-city-jump]').forEach(button=>button.addEventListener('click',()=>{
const type=button.dataset.cityJump,id=button.dataset.cityId;
@@ -270,9 +271,9 @@
}
function installCityAutoPlan() {
const planner=document.querySelector('.city-planner');if(!planner||document.querySelector('[data-city-autoplan]'))return;
const ja=document.documentElement.lang.startsWith('ja'),panel=document.createElement('details');panel.className='city-autoplan';panel.dataset.cityAutoplan='';panel.innerHTML=`<summary>${ja?'URL Pathから都市を自動生成':'Generate City from URL Paths'}</summary><p class="muted">${ja?'第1階層をQuartier、第2階層をStreet、第3階層をSpotとしてdry-runします。浅いPageは未定義Spotへ所属します。':'Dry-run: level 1 becomes Quartier, level 2 Street, and level 3 Spot. Shallow Pages use an undefined Spot.'}</p><button type="button" data-autoplan-preview>${ja?'計画を表示':'Preview plan'}</button><button type="button" data-autoplan-apply hidden>${ja?'計画を適用':'Apply plan'}</button><span data-autoplan-result></span><div class="city-autoplan-results" data-autoplan-results></div>`;planner.before(panel);
const ja=document.documentElement.lang.startsWith('ja'),panel=document.createElement('details');panel.className='city-autoplan';panel.dataset.cityAutoplan='';panel.innerHTML=`<summary>${ja?'URL Pathから都市を自動生成':'Generate City from URL Paths'}</summary><p class="muted">${ja?'第1階層をQuartier、第2階層をStreet、第3階層をSpotとしてdry-runします。浅いPageはStreetの入口にまとめます。':'Dry-run: level 1 becomes Quartier, level 2 Street, and level 3 Spot. Shallow Pages are grouped at their Street entrance.'}</p><button type="button" data-autoplan-preview>${ja?'計画を表示':'Preview plan'}</button><button type="button" data-autoplan-apply hidden>${ja?'計画を適用':'Apply plan'}</button><span data-autoplan-result></span><div class="city-autoplan-results" data-autoplan-results></div>`;planner.before(panel);
const result=panel.querySelector('[data-autoplan-result]'),results=panel.querySelector('[data-autoplan-results]'),apply=panel.querySelector('[data-autoplan-apply]');
panel.querySelector('[data-autoplan-preview]').addEventListener('click',async()=>{result.textContent='…';const response=await fetch('/_/api/v1/city/autoplan');const data=await response.json();if(!response.ok){result.textContent=data.error||'Failed';return}result.textContent=`${data.count} Pages`;const rows=(data.items||[]).slice(0,300);results.innerHTML=`<table><thead><tr><th>Path</th><th>Quartier</th><th>Street</th><th>Spot</th><th>${ja?'処理':'Action'}</th></tr></thead><tbody>${rows.map(item=>`<tr><td><code>${escapeHTML(item.path)}</code></td><td>${escapeHTML(item.Quartier)}</td><td>${escapeHTML(item.Street)}</td><td class="${item.undefined_spot?'is-undefined':''}">${escapeHTML(item.Spot)}</td><td>${escapeHTML(item.action)}</td></tr>`).join('')}</tbody></table>${data.count>rows.length?`<p>+ ${data.count-rows.length}</p>`:''}`;apply.hidden=!data.count;});
panel.querySelector('[data-autoplan-preview]').addEventListener('click',async()=>{result.textContent='…';const response=await fetch('/_/api/v1/city/autoplan');const data=await response.json();if(!response.ok){result.textContent=data.error||'Failed';return}result.textContent=`${data.count} Pages`;const rows=(data.items||[]).slice(0,300);results.innerHTML=`<table><thead><tr><th>Path</th><th>Quartier</th><th>Street</th><th>Spot</th><th>${ja?'処理':'Action'}</th></tr></thead><tbody>${rows.map(item=>`<tr><td><code>${escapeHTML(item.path)}</code></td><td>${escapeHTML(item.Quartier)}</td><td>${escapeHTML(item.Street)}</td><td class="${item.undefined_spot?'is-undefined':''}">${escapeHTML(item.undefined_spot ? item.Street : item.Spot)}</td><td>${escapeHTML(item.action)}</td></tr>`).join('')}</tbody></table>${data.count>rows.length?`<p>+ ${data.count-rows.length}</p>`:''}`;apply.hidden=!data.count;});
apply.addEventListener('click',async()=>{if(!confirm(ja?'この計画をCityへ適用しますか?':'Apply this plan to the City?'))return;apply.disabled=true;result.textContent='…';const response=await fetch('/_/api/v1/city/autoplan',{method:'POST'}),data=await response.json();apply.disabled=false;if(!response.ok){result.textContent=data.error||'Failed';return}result.textContent=`${data.applied} Pages`;await load();});
}
function reset() { transform = { x: 0, y: 0, scale: 1 }; applyTransform(); }
+5 -4
View File
@@ -37,6 +37,7 @@ window.PagesWikiCityOrganizer = ({svg, getCity, reload, dismissMenus, canPlan})
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 displayTitle = item => item.display_title || item.title || item.name;
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})));
@@ -48,7 +49,7 @@ window.PagesWikiCityOrganizer = ({svg, getCity, reload, dismissMenus, canPlan})
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};
return {key:`spot:${item.uuid}`,spot_uuid:item.uuid,title:displayTitle(item)};
};
const bar = document.createElement('div');
bar.className='city-selection-bar'; bar.hidden=true;
@@ -112,7 +113,7 @@ window.PagesWikiCityOrganizer = ({svg, getCity, reload, dismissMenus, canPlan})
};
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}));
const el=openDialog(words.rename,`<label>${escape(words.title)}<input name="title" value="${escape(displayTitle(item))}" 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 => {
@@ -125,7 +126,7 @@ window.PagesWikiCityOrganizer = ({svg, getCity, reload, dismissMenus, canPlan})
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>`}`;
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(displayTitle(p))}</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>`;
@@ -148,7 +149,7 @@ window.PagesWikiCityOrganizer = ({svg, getCity, reload, dismissMenus, canPlan})
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');
if(heading&&type==='Spot')button(heading,words.move,'⇄',()=>{selection.clear();add({key:`spot:${item.uuid}`,spot_uuid:item.uuid,title:displayTitle(item)});syncSelection();organize('move');},'data-city-move-selection');
},
context(menu,type,item,event){
const hit=pick(event.target);
+54
View File
@@ -0,0 +1,54 @@
// Lazy, bounded projection. No CDN, HTML injection, or document writes.
const selector = '.page-html pre code, .periodical-body pre code, #preview pre code, .preview pre code, .preview-content pre code, .public-document pre code';
const seen = new WeakMap(), queue = new Set();
let scheduled = false, bundle;
const idle = callback => window.requestIdleCallback ? requestIdleCallback(callback, {timeout:1000}) : setTimeout(callback, 0);
function language(code) {
return [...code.classList, ...code.parentElement.classList].find(c => /^(language|lang)-/.test(c))?.replace(/^(language|lang)-/, '') || '';
}
function schedule() {
if (scheduled || !queue.size) return;
scheduled = true;
idle(async () => {
try {
const code = queue.values().next().value; queue.delete(code);
if (!code?.isConnected) return;
const text = code.textContent, mode = language(code);
const signature = mode + '\0' + text;
if (!mode || text.length > 32768 || seen.get(code) === signature) return;
bundle ||= import('/static/vendor/codemirror/editor.bundle.js?v=command-ux-1');
await bundle;
if (!code.isConnected || code.textContent !== text || language(code) !== mode) { watch(code); return; }
seen.set(code, signature);
window.PagesWikiEditor.highlightCodeBlock(code, mode);
} catch (_) { /* Keep the readable plain-text fallback. */ }
finally { scheduled = false; schedule(); }
});
}
const visible = 'IntersectionObserver' in window ? new IntersectionObserver(entries => {
for (const entry of entries) if (entry.isIntersecting) { visible.unobserve(entry.target); queue.add(entry.target); }
schedule();
}, {rootMargin:'100px'}) : null;
function watch(code) {
if (!language(code) || code.textContent.length > 32768 || seen.get(code) === language(code) + '\0' + code.textContent) return;
if (visible) visible.observe(code); else { queue.add(code); schedule(); }
}
function scan(root) {
if (root.matches?.(selector)) watch(root);
root.querySelectorAll?.(selector).forEach(watch);
}
scan(document);
new MutationObserver(records => {
for (const record of records) {
// Preview replacements and fetched projections are processed incrementally.
for (const node of record.addedNodes) if (node.nodeType === 1) scan(node);
for (const node of record.removedNodes) if (node.nodeType === 1) {
const release = code => { visible?.unobserve(code); queue.delete(code); };
if (node.matches('code')) release(node);
node.querySelectorAll('code').forEach(release);
}
if (record.type === 'attributes' && record.target.matches('pre,code')) scan(record.target);
const code = record.target.nodeType === 1 ? record.target.closest?.('pre code') : record.target.parentElement?.closest('pre code');
if (code?.matches(selector)) watch(code);
}
}).observe(document.body, {childList:true, subtree:true, characterData:true, attributes:true, attributeFilter:['class']});
+84
View File
@@ -0,0 +1,84 @@
(() => {
const bar = document.querySelector('[data-command-bar]'), paths = window.PagesWikiPaths;
if (!bar || !paths) return;
document.body.append(bar); // Escape transformed/clipped headers.
const input = bar.querySelector('input'), list = bar.querySelector('[role=listbox]'), status = bar.querySelector('[role=status]');
const browser = bar.dataset.browser === 'true', current = bar.dataset.commandPath || '/';
let previous, request, generation = 0, options = [], index = -1, seed = '', completing = false, composing = false;
const interactive = target => target?.closest?.('input,textarea,select,button,a,summary,[contenteditable]:not([contenteditable=false]),[role=textbox],[role=button],.cm-editor');
const reset = () => {
generation++; request?.abort(); completing = false; options = []; index = -1;
list.replaceChildren(); list.hidden = true; status.textContent = ''; input.setAttribute('aria-expanded', 'false'); input.removeAttribute('aria-activedescendant');
};
const open = text => {
previous = document.activeElement; bar.hidden = false; reset(); input.value = text;
input.focus(); input.setSelectionRange(input.value.length, input.value.length);
};
const close = () => {
reset(); input.value = ''; if (!browser) bar.hidden = true; input.blur();
if (previous?.isConnected && !bar.contains(previous)) previous.focus();
};
const choose = i => {
index = (i + options.length) % options.length;
input.value = options[index].value;
input.setSelectionRange(input.value.length, input.value.length);
[...list.children].forEach((el,n) => el.setAttribute('aria-selected', String(n === index)));
input.setAttribute('aria-activedescendant', list.children[index].id);
list.children[index].scrollIntoView({block:'nearest'});
};
async function complete(backwards) {
if (options.length && !(options.length === 1 && input.value.endsWith('/')) && (input.value === seed || input.value === options[index]?.value)) { choose(index + (backwards ? -1 : 1)); return; }
if (completing) return;
reset(); seed = input.value;
const match = /^(cd|vi|view)\s+(.*)$/s.exec(seed);
if (!match || input.selectionStart !== input.value.length || input.selectionEnd !== input.value.length) return;
const raw = match[2], slash = raw.lastIndexOf('/');
const directory = slash < 0 ? '' : raw.slice(0, slash + 1), prefix = raw.slice(slash + 1);
let parent;
try { parent = paths.resolvePath(directory || '.', current); } catch { status.textContent = bar.dataset.invalid; return; }
const ticket = generation; request = new AbortController(); completing = true;
try {
const url = '/_/api/v1/path-picker?' + new URLSearchParams({path:parent, mode:'children', prefix});
const response = await fetch(url, {signal:request.signal, headers:{Accept:'application/json'}, cache:'no-store'});
if (!response.ok || !response.headers.get('content-type')?.includes('application/json')) throw Error('unavailable');
const data = await response.json();
if (ticket !== generation || input.value !== seed) return;
options = (data.entries || []).filter(e => typeof e.name === 'string' && e.name.toLowerCase().startsWith(prefix.toLowerCase())).slice(0,100).map(e => ({value:match[1] + ' ' + directory + e.name + (e.kind === 'folder' ? '/' : ''), label:e.name + (e.kind === 'folder' ? '/' : '')}));
status.textContent = !options.length ? bar.dataset.empty : data.truncated || data.entries.length > 100 ? bar.dataset.more : '';
for (const [i,item] of options.entries()) {
const option = document.createElement('div'); option.role = 'option'; option.id = 'wiki-command-option-' + i; option.textContent = item.label;
option.addEventListener('mousedown', event => event.preventDefault());
option.addEventListener('click', () => { choose(i); input.focus(); }); list.append(option);
}
list.hidden = !options.length; input.setAttribute('aria-expanded', String(!!options.length));
if (options.length) choose(backwards ? options.length - 1 : 0);
} catch (error) { if (ticket === generation && error.name !== 'AbortError') status.textContent = bar.dataset.unavailable; }
finally { if (ticket === generation) completing = false; }
}
bar.addEventListener('submit', event => {
event.preventDefault();
if (composing || !input.value.trim()) return;
try {
if (!/^(cd|vi|view)(?:\s|$)/.test(input.value.trim())) throw Error('invalid');
location.assign(paths.destination(input.value, current).href);
} catch { status.textContent = bar.dataset.invalid; }
});
input.addEventListener('input', reset);
input.addEventListener('compositionstart', () => { composing = true; reset(); });
input.addEventListener('compositionend', () => { composing = false; });
bar.addEventListener('focusout', event => { if (!bar.contains(event.relatedTarget)) reset(); });
input.addEventListener('keydown', event => {
if (event.isComposing || event.keyCode === 229 || event.ctrlKey || event.metaKey || event.altKey) return;
if (event.key === 'Escape') { event.preventDefault(); close(); }
if (event.key === 'Tab' && /^(cd|vi|view)\s/.test(input.value) && input.selectionStart === input.value.length && input.selectionEnd === input.value.length) { event.preventDefault(); complete(event.shiftKey); }
if (options.length && ['ArrowDown','ArrowUp'].includes(event.key)) { event.preventDefault(); choose(index + (event.key === 'ArrowDown' ? 1 : -1)); }
});
bar.querySelector('[data-command-close]').addEventListener('click', close);
document.addEventListener('keydown', event => {
if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey || event.repeat || interactive(event.target) || document.querySelector('dialog[open],.auth-menu details[open],.theme-picker[open]') || String(window.getSelection() || '')) return;
if (browser && (event.key === 'Process' || event.keyCode === 229)) { open(''); return; }
if (event.isComposing) return;
if (!browser && event.key === 'g') { event.preventDefault(); open(''); }
else if (browser && event.key.length === 1) { event.preventDefault(); open(event.key); }
}, true);
})();
+25
View File
@@ -0,0 +1,25 @@
(function(root) {
// Conservative three-way merge: each side is treated as one changed range.
// Multiple scattered changes may conflict, but are never silently discarded.
function merge(base, local, remote) {
if (local === remote || remote === base) return local
if (local === base) return remote
const change = text => {
let from = 0, end = 0
while (from < base.length && from < text.length && base[from] === text[from]) from++
while (end < base.length-from && end < text.length-from && base[base.length-1-end] === text[text.length-1-end]) end++
return {from, to:base.length-end, insert:text.slice(from,text.length-end)}
}
const a = change(local), b = change(remote)
// Adjacent/identical insertion points require a decision too.
if (!(a.to < b.from || b.to < a.from)) return null
const [first,last] = [a,b].sort((x,y) => x.from-y.from)
return base.slice(0,first.from)+first.insert+base.slice(first.to,last.from)+last.insert+base.slice(last.to)
}
function validDraft(draft, now = Date.now()) {
return draft?.version === 1 && typeof draft.text === 'string' && typeof draft.baseBody === 'string'
&& typeof draft.baseRevision === 'string' && ['html','markdown','code','plain'].includes(draft.format)
&& Number.isFinite(draft.savedAt) && now-draft.savedAt < 7*86400000 && draft.savedAt <= now+60000
}
root.PagesEditorCore = {merge,validDraft}
})(typeof window === 'undefined' ? globalThis : window)
+427 -388
View File
@@ -1,406 +1,445 @@
/* Editing state is independent of projection HTML. No save follows a failed conversion. */
window.PagesEditor = {
autosaveTimer: null,
init() {
const editor =
document.getElementById(
"editor",
)
const preview =
document.getElementById(
"preview",
)
const editType =
document.getElementById(
"edit-type",
)
if (
!editor
||
!preview
) {
return
}
const renderPreview =
async () => {
this.previewController?.abort()
const controller = new AbortController()
this.previewController = controller
const sequence = (this.previewSequence || 0) + 1
this.previewSequence = sequence
const source = editor.value
if (editType.value === "code") {
preview.classList.add("code-preview")
preview.textContent =
editor.value
return editor.value
}
try {
const res =
await fetch(
"/_/api/v1/render/markdown",
{
method: "POST",
signal: controller.signal,
headers: {
"Content-Type":
"application/json",
},
body: JSON.stringify({
...(editType.value === "html" ? {html: source} : {markdown: source}),
path: window.PagesWikiCurrentPath || location.pathname,
projection: true,
}),
},
)
if (controller.signal.aborted || sequence !== this.previewSequence) return
if (!res.ok) {
preview.classList.add("code-preview")
preview.innerText =
source
return editor.value
}
const data =
await res.json()
if (controller.signal.aborted || sequence !== this.previewSequence) return
preview.classList.remove("code-preview")
preview.innerHTML =
data.html
if (window.PagesWikiLoadChildren) {
window.PagesWikiLoadChildren(preview)
}
return data.html
} catch (error) {
if (controller.signal.aborted || sequence !== this.previewSequence) return
preview.classList.add("code-preview")
preview.textContent = source
return source
}
}
this.renderPreview =
renderPreview
this.editor = document.getElementById('editor')
this.preview = document.getElementById('preview')
this.mount = document.getElementById('editor-mount')
if (!this.editor || !this.preview || !this.mount) return
this.baseRevision = this.mount.dataset.baseRevision || ''
this.baseBody = document.getElementById('editor-base')?.value || ''
this.initialText = this.editor.value
this.owner = this.mount.dataset.owner || ''
this.serial = 0
this.paused = false
// The editor also runs on explicitly configured HTTP instances.
// This is a draft namespace, not an authentication credential.
this.tab = globalThis.crypto?.randomUUID?.() || Date.now().toString(36)+'-'+Math.random().toString(36).slice(2)
this.ja = document.documentElement.lang.startsWith('ja')
this.expireDrafts()
this.editor.addEventListener('input', () => this.changed())
document.querySelectorAll('[data-editor-action]').forEach(button => button.addEventListener('click', event => {
event.preventDefault()
switch (button.dataset.editorAction) {
case 'save': this.saveNow(); break
case 'rename': window.PagesPathActions.renameCurrentPath(); break
case 'delete': window.PagesPathActions.removeCurrentPath(); break
case 'html': window.switchEditorFormat('html'); break
case 'markdown': window.switchEditorFormat('markdown'); break
case 'preview': window.toggleEditorPreview(); break
}
const action = button.dataset.editorAction
if (action === 'save') this.saveNow()
if (action === 'rename') window.PagesPathActions?.renameCurrentPath()
if (action === 'delete') window.PagesPathActions?.removeCurrentPath()
if (action === 'html' || action === 'markdown') this.switchFormat(action)
if (action === 'preview') window.toggleEditorPreview()
if (action === 'tools') this.tools()
if (action === 'language') this.languageDialog()
if (action === 'restore') this.historyDialog()
}))
editor.addEventListener(
"input",
async () => {
clearTimeout(this.previewTimer)
this.previewController?.abort()
this.previewTimer = setTimeout(renderPreview, 150)
clearTimeout(
this.autosaveTimer,
)
this.autosaveTimer =
setTimeout(
() => {
this.autosave()
},
3000,
)
},
)
document.addEventListener(
"keydown",
(ev) => {
if (
(ev.ctrlKey || ev.metaKey)
&&
ev.key === "s"
) {
ev.preventDefault()
this.saveNow()
}
},
)
renderPreview()
document.addEventListener('keydown', event => {
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {event.preventDefault(); this.saveNow()}
})
window.addEventListener('beforeunload', event => {
if (this.dirty) { this.persist(); event.preventDefault(); event.returnValue = '' }
})
window.addEventListener('pagehide', () => { if (this.dirty) this.persist() })
window.addEventListener('offline', () => this.fail({kind:'offline'}))
window.addEventListener('online', () => { this.paused = true; this.status('reconnected'); this.checkState() })
document.addEventListener('visibilitychange', () => {
if (document.hidden) {if (this.dirty) this.persist()} else this.checkState()
})
this.stateTimer = setInterval(() => { if (!document.hidden) this.checkState() },30000)
this.renderPreview()
// CodeMirror is mounted by the next DOMContentLoaded listener.
setTimeout(() => this.offerRecovery(), 0)
},
async getCanonicalHTML() {
const editor =
document.getElementById(
"editor",
)
const editType =
document.getElementById(
"edit-type",
)
if (
editType.value
===
"html"
) {
return editor.value
t(key) {
const text = {
dirty:['未保存','Unsaved'], draft:['端末に下書きを保存済み','Draft saved on this device'], saved:['保存済み','Saved'], saving:['保存中…','Saving…'],
auth:['認証切れ:再ログイン後に保存してください','Session expired: sign in again, then save'],
forbidden:['権限がありません。下書きをダウンロードできます','Permission denied. You can download your draft'],
offline:['通信できません。保存を中断しました','Connection unavailable. Saving paused'],
failed:['保存・変換に失敗しました。本文は保持しています','Save/conversion failed. Your text is retained'],
storage:['端末保存に失敗しました。下書きをダウンロードしてください','Device storage failed. Download your draft'],
reconnected:['接続が戻りました。内容を確認して保存してください','Reconnected. Review your work and save'],
remote:['別の編集による更新があります。保存時に照合します','Another edit was saved. Changes will be checked when you save'],
conflict:['競合の確認(保存するまで反映されません)','Resolve conflict (not applied until saved)'],
base:['編集開始時','Base'], local:['自分の編集','Your changes'], latest:['最新の内容','Latest content'], result:['保存する内容(HTML/コード)','Result to save (HTML / code)'],
apply:['作業バッファへ反映','Apply to working buffer'], cancel:['閉じる','Close'], recovery:['未保存の下書きがあります','An unsaved draft is available'],
recover:['復元','Restore draft'], discard:['破棄','Discard'], export:['下書きダウンロード','Download draft'], tools:['挿入・下書き','Insert / drafts'],
privacy:['下書きはこの端末に平文で保存し、復元対象は7日以内です。期限切れはエディタ起動時に削除します。共有端末では作業後に削除してください。','Drafts are stored as plaintext on this device and recoverable for 7 days. Expired drafts are removed when the editor opens. Remove them after using a shared device.'],
language:['言語の編集・分岐(BCP 47)','Edit / fork language (BCP 47)'], open:['指定言語を開く','Open language'], fork:['現在の本文を指定言語へ分岐','Fork current text into language'],
exists:['指定言語には既に本文があります。編集として開いてください','This language already exists. Open it for editing'], history:['過去のリビジョンを復元','Restore a previous revision'],
signin:['再ログイン(別タブ)','Sign in again (new tab)'], insert:['挿入','Insert'], invalid:['言語タグを確認してください','Check the language tag'], identity:['別アカウントに切り替わっています。元のアカウントで開き直してください','Account changed. Reopen using the original account'],
incompatible:['ファイル形式が変更されています。下書きを退避して開き直してください','File type changed. Download your draft and reopen'], older:['さらに古い履歴','Older revisions'],
children:['子ページ一覧','Children'], table:['表','Table'], figure:['画像とキャプション','Image + caption'], note:['補足','Note'], code:['コードブロック','Code block'], quote:['引用','Quote'],
protected:['Markdown で表せない HTML は {=html} ブロックに保持します。ブロック内も編集でき、保存・プレビュー時に HTML として扱います。','HTML not representable in Markdown is retained in editable {=html} blocks and rendered as HTML on save / preview.'],
}
if (editType.value === "code") {
return editor.value
return text[key]?.[this.ja ? 0 : 1] || key
},
value(id) { return document.getElementById(id)?.value || '' },
format() {return this.value('edit-type')},
text() {return window.PagesWikiCodeMirror?.state.doc.toString() ?? this.editor.value},
status(key) {
const status = document.getElementById('editor-save-status')
if (status) {status.textContent = this.t(key); status.dataset.state = key}
},
keyPrefix() {return 'pageswiki.draft.v1:'+JSON.stringify([this.mount.dataset.domain,this.owner,this.value('object-uuid'),this.value('page-language')||'und'])+':'},
expireDrafts() {
try {
for (const key of Object.keys(localStorage)) {
if (!key.startsWith('pageswiki.draft.v1:')) continue
let draft
try {draft=JSON.parse(localStorage.getItem(key))} catch (_) {}
if (!PagesEditorCore.validDraft(draft)) localStorage.removeItem(key)
}
} catch (_) {this.status('storage')}
},
persist() {
if (!this.dirty) return
try {
const draft = {version:1, text:this.text(), format:this.format(), baseRevision:this.baseRevision, baseBody:this.baseBody, savedAt:Date.now()}
const data = JSON.stringify(draft)
if (new TextEncoder().encode(data).length > 2*1024*1024) throw Error('draft too large')
localStorage.setItem(this.keyPrefix()+this.tab,data)
this.draftStored = true
if (!this.paused && !this.saving) this.status('draft')
} catch (_) {this.draftStored = false; this.status('storage')}
},
clearDraft() {
clearTimeout(this.draftTimer)
try {localStorage.removeItem(this.keyPrefix()+this.tab)} catch (_) {}
},
offerRecovery() {
let candidate
try {
for (const key of Object.keys(localStorage)) {
if (!key.startsWith(this.keyPrefix())) continue
let draft
try {draft = JSON.parse(localStorage.getItem(key))} catch (_) {}
if (!PagesEditorCore.validDraft(draft)) {localStorage.removeItem(key); continue}
if (!candidate || draft.savedAt > candidate.draft.savedAt) candidate = {key,draft}
}
} catch (_) {this.status('storage'); return}
if (!candidate) return
this.paused = true
const {dialog,content,button} = this.dialog('recovery')
this.paragraph(content,this.t('privacy'))
this.paragraph(content,new Date(candidate.draft.savedAt).toLocaleString())
button('recover',() => {
// A stale draft must not change a plain file into HTML (or vice
// versa) merely because the editor was reopened in another mode.
const family = format => ['plain','code'].includes(format) ? format : 'html'
if (family(candidate.draft.format) !== family(this.format())) {this.fail({kind:'incompatible'}); return}
this.baseRevision = candidate.draft.baseRevision
this.baseBody = candidate.draft.baseBody
this.initialText = null
this.setText(candidate.draft.text,candidate.draft.format)
this.persist()
// Move this recovered snapshot, never remove another tab's newer
// draft. A failed local write must leave the recovery source intact.
if (this.draftStored && localStorage.getItem(candidate.key) === JSON.stringify(candidate.draft)) localStorage.removeItem(candidate.key)
dialog.close()
})
button('discard',() => {localStorage.removeItem(candidate.key); this.paused=false; dialog.close()})
button('export',() => this.download(candidate.draft.text,candidate.draft.format))
},
changed() {
this.serial++
this.dirty = true
this.status('dirty')
clearTimeout(this.draftTimer)
this.draftTimer = setTimeout(() => this.persist(),250)
clearTimeout(this.previewTimer)
this.previewController?.abort()
this.previewTimer = setTimeout(() => this.renderPreview(),300)
clearTimeout(this.autosaveTimer)
if (!this.paused) this.autosaveTimer = setTimeout(() => this.save(false),3000)
},
async request(url,options = {}) {
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(),15000)
const abort = () => controller.abort()
options.signal?.addEventListener('abort',abort,{once:true})
if (options.signal?.aborted) controller.abort()
try {
const response = await fetch(url,{...options,signal:controller.signal,credentials:'same-origin',cache:'no-store'})
if (response.status === 401 || response.redirected) throw {kind:'auth'}
if (response.status === 403) throw {kind:'forbidden'}
if (response.status === 409) throw {kind:'conflict'}
if (!response.ok) throw {kind:'failed'}
if (!response.headers.get('Content-Type')?.includes('application/json')) throw {kind:'auth'}
return await response.json()
} catch (error) {
if (error.kind) throw error
throw {kind:'offline'}
} finally {clearTimeout(timer); options.signal?.removeEventListener('abort',abort)}
},
post(url,body,options={}) {return this.request(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body),...options})},
fail(error) {
this.paused = true
clearTimeout(this.autosaveTimer)
this.persist()
this.status(error.kind || 'failed')
if (this.dirty && this.draftStored===false) {
const status=document.getElementById('editor-save-status')
if (status) status.textContent+=' / '+this.t('storage')
}
const res =
await fetch(
"/_/api/v1/render/markdown",
{
method: "POST",
headers: {
"Content-Type":
"application/json",
},
body: JSON.stringify({
markdown:
editor.value,
}),
},
)
if (!res.ok) {
return editor.value
}
const data =
await res.json()
},
async canonical(text = this.text(), format = this.format()) {
if (text === this.initialText && format === this.initialFormat) return this.baseBody
if (format !== 'markdown') return text
const data = await this.post('/_/api/v1/render/markdown',{markdown:text,authoring:true})
if (typeof data.html !== 'string') throw {kind:'failed'}
return data.html
},
async autosave() {
const objectUUID =
document.getElementById(
"object-uuid",
)
if (
!objectUUID
||
!objectUUID.value
) {
return
getCanonicalHTML() {return this.canonical()},
async renderPreview() {
this.previewController?.abort()
const controller = new AbortController()
this.previewController = controller
const text = this.text()
if (this.format() === 'code' || this.format() === 'plain') {this.preview.classList.add('code-preview'); this.preview.textContent=text; return}
try {
const data = await this.post('/_/api/v1/render/markdown',{
...(this.format()==='html' ? {html:text} : {markdown:text}),path:window.PagesWikiCurrentPath || '/',projection:true,authoring:true,
},{signal:controller.signal})
if (controller.signal.aborted || text !== this.text()) return
this.preview.classList.remove('code-preview')
this.preview.innerHTML = data.html
window.PagesWikiLoadChildren?.(this.preview)
} catch (error) {
if (controller.signal.aborted) return
this.preview.classList.add('code-preview'); this.preview.textContent=text
this.fail(error)
}
const canonicalHTML =
await this.getCanonicalHTML()
const pageLanguage =
document.getElementById(
"page-language",
)
const pageContentType =
document.getElementById("page-content-type")
const pageFilename =
document.getElementById("page-filename")
await fetch(
"/_/api/v1/revisions/save",
{
method: "POST",
headers: {
"Content-Type":
"application/json",
},
body: JSON.stringify({
object_uuid:
objectUUID.value,
body:
canonicalHTML,
message:
"autosave",
lang:
pageLanguage
? pageLanguage.value
: "und",
content_type:
pageContentType
? pageContentType.value
: "",
filename:
pageFilename
? pageFilename.value
: "",
}),
},
)
},
async saveNow() {
const objectUUID =
document.getElementById(
"object-uuid",
)
if (
!objectUUID
||
!objectUUID.value
) {
stateURL(extra={}) {
const query = new URLSearchParams({uuid:this.value('object-uuid'),lang:this.value('page-language')||'und',...extra})
return '/_/api/v1/editor/state?'+query
},
async state(extra={}) {
const data = await this.request(this.stateURL(extra))
if (data.principal_uuid !== this.owner) throw {kind:'identity'}
return data
},
async checkState() {
if (this.checking || this.saving) return
this.checking = true
try {
const latest = await this.state({metadata:'1'})
if (latest.revision_uuid !== this.baseRevision) this.status('remote')
} catch (error) {this.fail(error)} finally {this.checking=false}
},
autosave() {return this.save(false)},
saveNow() {return this.save(true)},
async save(manual) {
if (this.saving) return false
if (!this.dirty) return !this.paused
if (!manual && this.paused) return false
if (manual) this.mergeAttempts=0
this.persist()
this.saving = true
this.status('saving')
const text = this.text(), format = this.format(), serial = this.serial
let body
try {
body = await this.canonical(text,format)
const data = await this.post('/_/api/v1/revisions/save',{
object_uuid:this.value('object-uuid'),body,message:manual?'manual-save':'autosave',
lang:this.value('page-language')||'und',content_type:this.value('page-content-type'),filename:this.value('page-filename'),
base_revision_uuid:this.baseRevision,editor_principal_uuid:this.owner,
})
if (!data.revision_uuid) throw {kind:'failed'}
this.baseRevision = data.revision_uuid
this.baseBody = typeof data.body==='string' ? data.body : body
this.initialText = text; this.initialFormat = format
this.paused = false
this.mergeAttempts=0
if (serial === this.serial) {this.dirty=false; this.clearDraft(); this.status('saved')}
else {this.persist(); this.autosaveTimer=setTimeout(() => this.save(false),3000)}
return serial === this.serial
} catch (error) {
if (error.kind === 'conflict' && body !== undefined) {
try {await this.resolveConflict(body,serial)} catch (failure) {this.fail(failure)}
} else this.fail(error)
return false
} finally {this.saving=false}
},
async resolveConflict(local,serial) {
this.paused = true
const remote = await this.state()
if ((remote.content_type||'').split(';')[0]!==this.value('page-content-type').split(';')[0]) {this.fail({kind:'incompatible'}); return}
// If a save succeeded but its response was lost, acknowledge it safely.
if (serial === this.serial && local === remote.body) {
this.baseRevision=remote.revision_uuid; this.baseBody=remote.body
this.initialText=this.text(); this.initialFormat=this.format()
this.dirty=false; this.paused=false; this.clearDraft(); this.status('saved'); return
}
if (serial !== this.serial) {this.status('remote'); this.persist(); return}
const merged = PagesEditorCore.merge(this.baseBody,local,remote.body)
const apply = result => {
this.baseRevision=remote.revision_uuid; this.baseBody=remote.body
document.getElementById('page-filename').value=remote.filename||''
this.initialText=null
this.setText(result,['code','plain'].includes(this.format())?this.format():'html')
this.persist()
}
if (merged !== null && (this.mergeAttempts || 0)<3) {
this.mergeAttempts=(this.mergeAttempts || 0)+1
apply(merged)
// A second CAS still guards a writer racing this automatic merge.
this.paused=false
this.autosaveTimer=setTimeout(() => this.save(false),500)
return
}
const canonicalHTML =
await this.getCanonicalHTML()
const pageLanguage =
document.getElementById(
"page-language",
)
const pageContentType =
document.getElementById("page-content-type")
const pageFilename =
document.getElementById("page-filename")
const res =
await fetch(
"/_/api/v1/revisions/save",
{
method: "POST",
headers: {
"Content-Type":
"application/json",
},
body: JSON.stringify({
object_uuid:
objectUUID.value,
body:
canonicalHTML,
message:
"manual-save",
lang:
pageLanguage
? pageLanguage.value
: "und",
content_type:
pageContentType
? pageContentType.value
: "",
filename:
pageFilename
? pageFilename.value
: "",
}),
},
)
if (!res.ok) {
alert(
"save failed",
)
return
this.persist(); this.status('conflict')
const {dialog,content,button} = this.dialog('conflict')
this.area(content,'base',this.baseBody,true)
this.area(content,'local',local,true)
this.area(content,'latest',remote.body,true)
const result = this.area(content,'result',local,false)
button('apply',() => {
if (serial !== this.serial) {this.status('remote'); dialog.close(); return}
apply(result.value); dialog.close()
})
},
setText(text,format=this.format()) {
const oldFormat = this.format()
document.getElementById('edit-type').value=format
const status=document.getElementById('editor-format-status')
if (status) status.textContent=format
this.editor.value=text
if (oldFormat !== format && window.PagesWikiCodeMirror) {
window.PagesWikiCodeMirror.destroy()
window.PagesWikiCodeMirror = window.PagesWikiEditor.create(this.mount,text,format,{
keymap:this.mount.dataset.keymap,syntax:this.mount.dataset.syntax==='true',autocomplete:this.mount.dataset.autocomplete==='true',
})
} else if (window.PagesWikiCodeMirror) {
const cm=window.PagesWikiCodeMirror
cm.dispatch({changes:{from:0,to:cm.state.doc.length,insert:text}})
}
alert(
"saved",
)
document.querySelectorAll('[data-editor-action="html"],[data-editor-action="markdown"]').forEach(button => {
const selected=button.dataset.editorAction===format
button.classList.toggle('active',selected); button.setAttribute('aria-pressed',String(selected))
})
this.changed()
},
async switchFormat(format) {
// Representation switching is only lossless inside the HTML canonical
// family. Plain text/code must never silently turn into executable HTML.
if (!['html','markdown'].includes(format) || ['plain','code'].includes(this.format())) return
if (format===this.format() || this.saving) return
this.paused=true; this.persist()
const serial=this.serial
try {
let body=await this.canonical()
if (serial!==this.serial) return
if (format==='markdown') {
const data=await this.post('/_/api/v1/editor/convert',{html:body})
if (serial!==this.serial) return
if (typeof data.markdown!=='string') throw {kind:'failed'}
body=data.markdown
}
this.setText(body,format)
this.persist()
} catch (error) {this.fail(error)}
},
dialog(title) {
document.querySelector('#editor-dialog')?.remove()
const dialog=document.createElement('dialog'); dialog.id='editor-dialog'; dialog.className='editor-dialog'
const heading=document.createElement('h2'); heading.textContent=this.t(title); dialog.append(heading)
const content=document.createElement('div'); content.className='editor-dialog-content'; dialog.append(content)
const footer=document.createElement('footer'); dialog.append(footer)
const button=(label,action) => {
const b=document.createElement('button'); b.type='button'; b.textContent=this.t(label)
b.addEventListener('click',() => Promise.resolve().then(action).catch(error => this.fail(error)))
footer.append(b); return b
}
button('cancel',() => dialog.close())
dialog.addEventListener('close',() => dialog.remove())
document.body.append(dialog); dialog.showModal()
return {dialog,content,button}
},
paragraph(parent,text) {const p=document.createElement('p'); p.textContent=text; parent.append(p)},
area(parent,label,text,readOnly) {
const wrapper=document.createElement('label'); wrapper.textContent=this.t(label)
const area=document.createElement('textarea'); area.value=text; area.readOnly=readOnly; area.rows=6; wrapper.append(area); parent.append(wrapper); return area
},
download(text=this.text(),format=this.format()) {
const url=URL.createObjectURL(new Blob([text],{type:'text/plain;charset=utf-8'}))
const a=document.createElement('a'); a.href=url; a.download='pageswiki-draft.'+(format==='markdown'?'md':format==='html'?'html':'txt'); a.click()
setTimeout(() => URL.revokeObjectURL(url),1000)
},
tools() {
const {dialog,content,button}=this.dialog('tools')
this.paragraph(content,this.t('privacy'))
const select=document.createElement('select'); select.setAttribute('aria-label',this.t('insert'))
this.paragraph(content,this.t('protected'))
const parts=[['children','{{children}}'],['table','<table>\n<thead><tr><th>Column</th></tr></thead>\n<tbody><tr><td>Value</td></tr></tbody>\n</table>'],['figure','<figure><img src="/_/obj/sha256:HASH" alt="Description"><figcaption>Caption</figcaption></figure>'],['note','<aside class="note"><p>Note</p></aside>'],['code','<pre><code class="language-text">code</code></pre>'],['quote','<blockquote><p>Quote</p></blockquote>']]
parts.forEach(([label],i) => {const option=document.createElement('option'); option.value=i; option.textContent=this.t(label); select.append(option)})
content.append(select)
const login=document.createElement('a'); login.href='/_/auth/login?return='+encodeURIComponent(location.pathname+location.search); login.target='_blank'; login.rel='noopener'; login.textContent=this.t('signin'); content.append(login)
button('insert',() => {
const part=parts[Number(select.value)]
const source=this.format()==='markdown' && part[0]!=='children' ? '```{=html}\n'+part[1]+'\n```' : part[1]
const text='\n\n'+source+'\n\n'
const cm=window.PagesWikiCodeMirror
if (cm) cm.dispatch(cm.state.replaceSelection(text)); else this.setText(this.text()+text)
dialog.close(); cm?.focus()
})
button('export',() => this.download())
button('discard',() => {
this.clearDraft()
this.status('dirty'); dialog.close()
})
},
languageDialog() {
if (this.saving) return
this.paused=true; this.persist()
const {dialog,content,button}=this.dialog('language')
const input=document.createElement('input'); input.value=this.value('page-language')||'und'; input.placeholder='ja / en / ja-JP'; input.setAttribute('aria-label',this.t('language')); content.append(input)
const lang=() => {
try {return input.value==='und'?'und':Intl.getCanonicalLocales(input.value.trim())[0] || (()=>{throw Error()})()} catch (_) {throw {kind:'invalid'}}
}
button('open',() => {const url=new URL(location.href); url.searchParams.set('lang',lang()); location.href=url.toString()})
button('fork',async () => {
if (this.saving) return
const target=lang(), serial=this.serial
const state=await this.state({lang:target})
if (state.revision_uuid) {this.paragraph(content,this.t('exists')); return}
if (serial!==this.serial || this.saving) return
document.getElementById('page-language').value=state.lang
this.baseRevision=''; this.baseBody=''; this.initialText=''; this.initialFormat=this.format()
const url=new URL(location.href); url.searchParams.set('lang',state.lang); history.replaceState(null,'',url)
this.changed(); this.persist(); dialog.close()
})
},
async historyDialog() {
if (this.saving) return
this.paused=true; this.persist()
try {
const {dialog,content,button}=this.dialog('history')
const select=document.createElement('select'); select.setAttribute('aria-label',this.t('history'))
content.append(select)
let before=''
const load=async () => {
older.disabled=true
const rows=await this.request('/_/api/v1/revisions/list?'+new URLSearchParams({uuid:this.value('object-uuid'),limit:'50',before}))
rows.filter(row => row.lang===(this.value('page-language')||'und')).forEach(row => {const option=document.createElement('option'); option.value=row.uuid; option.textContent=new Date(row.created_at*1000).toLocaleString()+' '+row.message+' '+row.uuid.slice(0,8); select.append(option)})
before=rows.at(-1)?.uuid||before
older.disabled=rows.length<50
}
const older=button('older',load)
button('recover',async () => {
if (!select.value || this.saving) return
const serial=this.serial
const old=await this.state({revision:select.value})
if (serial!==this.serial || this.saving) return
if (!old.editable) throw {kind:'incompatible'}
this.setText(this.format()==='markdown'?old.markdown:old.body)
this.persist(); dialog.close()
})
await load()
} catch (error) {this.fail(error)}
},
}
document.addEventListener(
"DOMContentLoaded",
() => {
if (
document.body.classList.contains(
"mode-editor",
)
) {
PagesEditor.init()
}
},
)
document.addEventListener(
"DOMContentLoaded",
() => {
const sel =
document.getElementById(
"editor-type",
)
if (!sel) {
return
}
sel.addEventListener(
"change",
() => {
const u =
new URL(
location.href,
)
u.searchParams.set(
"edittype",
sel.value,
)
location.href =
u.toString()
},
)
},
)
// HTML/Markdown previews and diagram projections are produced by the common
// server boundary. Do not reinterpret authoring source in a second client pass.
document.addEventListener('DOMContentLoaded',() => {
if (!document.body.classList.contains('mode-editor')) return
PagesEditor.init()
PagesEditor.initialFormat=PagesEditor.format()
})
+1
View File
@@ -43,6 +43,7 @@
};
buttons.forEach(button => button.addEventListener('click', () => show(button.dataset.homePageTarget, true)));
document.addEventListener('home:search', () => show('search'));
pager.addEventListener('wheel', event => {
if (modalOpen()) return;
if (page === 1 && (event.deltaY > 0 || bookmarks.scrollTop > 0)) return;
+24
View File
@@ -0,0 +1,24 @@
// Type-to-search is intentionally limited to the home page. Never capture typing
// in another editor, a modal, an open menu, or an OS/browser keyboard shortcut.
(() => {
const input = document.querySelector('[data-home-type-search]');
if (!input) return;
document.addEventListener('keydown', event => {
if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey || event.isComposing) return;
if (event.target.closest?.('input,textarea,select,button,a,summary,[contenteditable]:not([contenteditable="false"]),[role="textbox"]')) return;
if ([...document.querySelectorAll('dialog[open],details[open],[role="dialog"]:not(dialog),[aria-modal="true"]:not(dialog)')]
.some(surface => !surface.hidden && surface.getClientRects().length)) return;
if (window.getSelection()?.toString()) return;
const composing = event.key === 'Process' || event.keyCode === 229;
if (!composing && ([...event.key].length !== 1 || event.key.trim() === '')) return;
document.dispatchEvent(new Event('home:search'));
if (input.closest('[inert]') || !input.getClientRects().length) return;
input.focus({preventScroll: true});
// Redirect IME's native composition to the input without synthesizing text.
if (composing) return;
event.preventDefault();
// Search inputs do not support setRangeText/selectionStart in all browsers.
input.value += event.key;
input.dispatchEvent(new Event('input', {bubbles: true}));
});
})();
+37
View File
@@ -0,0 +1,37 @@
(() => {
const picker = document.querySelector('[data-theme-picker]');
if (!picker) return;
const select = picker.querySelector('[data-theme-select]');
const status = picker.querySelector('[data-theme-status]');
const themeLink = [...document.querySelectorAll('link[rel="stylesheet"]')]
.find(link => link.getAttribute('href') === picker.dataset.currentCss);
if (!themeLink) { picker.hidden = true; return; }
let current = picker.dataset.currentId;
select.addEventListener('change', () => {
const option = select.selectedOptions[0];
const candidate = document.createElement('link');
candidate.rel = 'stylesheet';
candidate.href = option.dataset.css;
select.disabled = true;
status.textContent = '';
// Load before replacing, so failure cannot leave an unstyled page. Keeping
// the link's position preserves editor/component overrides and avoids reload.
candidate.media = 'not all';
candidate.onload = () => {
themeLink.href = candidate.href;
candidate.remove();
current = option.value;
const secure = location.protocol === 'https:' ? '; Secure' : '';
document.cookie = 'pageswiki_theme=' + encodeURIComponent(current) + '; Path=/; SameSite=Lax; Max-Age=' + (current ? 31536000 : 0) + secure;
select.disabled = false;
document.dispatchEvent(new Event('pageswiki:theme'));
};
candidate.onerror = () => {
candidate.remove(); select.value = current; select.disabled = false;
status.textContent = picker.dataset.failed;
};
document.head.append(candidate);
});
document.addEventListener('pointerdown', event => { if (!picker.contains(event.target)) picker.open = false; });
picker.addEventListener('keydown', event => { if (event.key === 'Escape') { picker.open = false; picker.querySelector('summary').focus(); } });
})();
+1 -1
View File
@@ -22,7 +22,7 @@
};
const shortcutSheet = () => {
const table=document.createElement('div'); table.className='viewer-shortcut-grid';
[['e','Edit'],['/','Find'],['v','Change view'],['c','Create child'],['u','Upload'],['s','Share'],['p','Permissions'],['Ctrl+↑','Parent'],['Ctrl+↓','Children'],['Ctrl+→','Previous'],['Ctrl+←','Next'],['?','This cheat sheet']].forEach(([key,label])=>{const k=document.createElement('kbd');k.textContent=key;const d=document.createElement('span');d.textContent=label;table.append(k,d);});
[['e','Edit'],['/','Find'],['g','Command: cd / vi / view · Tab completion'],['v','Change view'],['c','Create child'],['u','Upload'],['s','Share'],['p','Permissions'],['Ctrl+↑','Parent'],['Ctrl+↓','Children'],['Ctrl+→','Previous'],['Ctrl+←','Next'],['?','This cheat sheet']].forEach(([key,label])=>{const k=document.createElement('kbd');k.textContent=key;const d=document.createElement('span');d.textContent=label;table.append(k,d);});
openDialog('Keyboard shortcuts',table);
};
const childrenDialog = async () => {