Files
pages/static/js/city-governance.js
T
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

165 lines
14 KiB
JavaScript
Raw 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.
document.addEventListener('DOMContentLoaded', () => {
const dialog = document.querySelector('[data-governance-dialog]');
if (!dialog) return;
const find = selector => dialog.querySelector(selector);
const form = find('form'), fields = find('fieldset'), result = find('[data-governance-result]');
const endpoint = dialog.dataset.endpoint;
const accessForm = find('[data-access-form]'), accessFields = accessForm.querySelector('fieldset');
const publicationForm=find('[data-publication-form]'), publicationFields=publicationForm.querySelector('fieldset');
let impact;
const autoForm=find('[data-auto-publication-form]');let autoState;
const clearAuto=()=>{autoState=null;autoForm.reset();autoForm.elements.confirm.setCustomValidity('');find('[data-auto-save]').disabled=true;find('[data-auto-impact]').replaceChildren();};
const clearPublication=()=>{impact=null; publicationForm.reset();find('[data-publication-impact]').replaceChildren();find('[data-publication-status]').textContent='';find('[data-publication-enable]').disabled=true;};
let accessState, entries = [];
const showAccess = () => {
const list = find('[data-access-entries]'); list.replaceChildren();
entries.forEach((entry,index) => {
const row = document.createElement('div'); row.className = 'city-access-row';
for (const [key,options] of [['kind',['user','group']],['name',null],['permission',['read','read_write']]]) {
const input = document.createElement(options ? 'select' : 'input');
if (options) options.forEach(value => { const option = document.createElement('option'); option.value = value; option.textContent = accessForm.dataset[value]; input.append(option); });
else { input.maxLength=64; input.required=true; input.placeholder=accessForm.dataset.name; }
input.setAttribute('aria-label', key==='name' ? accessForm.dataset.name : key==='kind' ? `${accessForm.dataset.user} / ${accessForm.dataset.group}` : `${accessForm.dataset.read} / ${accessForm.dataset.read_write}`);
input.value = entry[key]; input.addEventListener('input',()=>{ entry[key]=input.value; if(key==='kind'||key==='name') delete entry.id; }); row.append(input);
}
const remove = document.createElement('button'); remove.type='button'; remove.textContent='×'; remove.setAttribute('aria-label',dialog.dataset.remove); remove.addEventListener('click',()=>{ entries.splice(index,1); showAccess(); }); row.append(remove); list.append(row);
});
};
let state, owners = [], candidates = [], timer, generation = 0, searchGeneration = 0;
const label = policy => dialog.dataset[policy] || policy;
const api = async (url, method = 'GET', body) => {
const response = await fetch(url, {method, headers:{'Content-Type':'application/json'}, ...(body ? {body:JSON.stringify(body)} : {})});
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
return data;
};
const showPolicy = data => {
find('[data-governance-superior]').textContent = data.superior_allows_public ? dialog.dataset.yes : dialog.dataset.no;
find('[data-governance-effective]').textContent = data.draft_effective_public ? dialog.dataset.yes : dialog.dataset.no;
const chain = find('[data-governance-chain]'); chain.replaceChildren();
data.chain.forEach(item => { const li = document.createElement('li'); li.textContent = `${item.kind}: ${label(item.policy)}`; chain.append(li); });
};
const showOwners = () => {
const list = find('[data-governance-owners]'); list.replaceChildren();
owners.forEach(owner => {
const li = document.createElement('li'), text = document.createElement('span');
text.textContent = `${owner.display_name || owner.username} (${owner.username})${owner.active ? '' : ' · '+dialog.dataset.inactive}`;
li.append(text);
if (state.can_appoint) {
const button = document.createElement('button'); button.type = 'button'; button.textContent = '×'; button.setAttribute('aria-label',dialog.dataset.remove);
button.addEventListener('click', () => { owners = owners.filter(o => o.membership_uuid !== owner.membership_uuid); showOwners(); }); li.append(button);
}
list.append(li);
});
};
const members = async () => {
const seq = ++searchGeneration, opened = generation;
try {
const data = await api(endpoint+'/members?q='+encodeURIComponent(find('[data-governance-search]').value));
if (seq !== searchGeneration || opened !== generation || !dialog.open) return;
candidates = data;
const select = find('[data-governance-members]'); select.replaceChildren();
data.forEach(o => { const option = document.createElement('option'); option.value = o.membership_uuid; option.textContent = `${o.display_name || o.username} (${o.username})`; select.append(option); });
} catch (error) { if (opened === generation && dialog.open) result.textContent = error.message; }
};
document.querySelector('[data-governance-open]').addEventListener('click', async () => {
dialog.showModal(); const seq = ++generation; fields.disabled = true; accessFields.disabled=true; result.textContent = ''; form.reset(); accessForm.reset();
publicationFields.disabled=true; clearPublication();clearAuto();
try {
const [data,acl] = await Promise.all([api(endpoint),api(endpoint+'/access')]);
if (seq !== generation || !dialog.open) return;
if (data.epoch !== acl.epoch || data.topology_version !== acl.topology_version) throw new Error(dialog.dataset.conflict);
state = data; owners = [...data.owners]; form.elements.policy.value = data.policy;
accessState=acl; entries=acl.entries.map(e=>({...e})); accessForm.elements.mode.value=acl.mode; showAccess(); accessFields.disabled=false;
form.elements.policy.querySelector('[value=inherit]').disabled = data.kind === 'domain';
form.elements.policy.querySelector('[value=public]').disabled = !data.superior_allows_public;
find('[data-governance-appointments]').hidden = !data.can_appoint;
showPolicy(data); showOwners(); fields.disabled = false;
publicationFields.disabled=false;
if (data.can_appoint) members();
} catch (error) { result.textContent = error.message; }
});
find('[data-governance-close]').addEventListener('click', () => dialog.close());
dialog.addEventListener('close', () => { if (dialog.open) return; generation++; searchGeneration++; clearTimeout(timer); });
dialog.addEventListener('keydown', event => event.stopPropagation());
find('[data-governance-search]').addEventListener('input', () => { clearTimeout(timer); searchGeneration++; timer = setTimeout(members,200); });
find('[data-governance-add]').addEventListener('click', () => {
const selected = candidates.find(o => o.membership_uuid === find('[data-governance-members]').value);
if (selected && owners.length < 32 && !owners.some(o => o.membership_uuid === selected.membership_uuid)) { owners.push(selected); showOwners(); }
});
const save = async preview => {
if (!state || fields.disabled || accessFields.disabled) return;
const body = {epoch:state.epoch, topology_version:state.topology_version, policy:form.elements.policy.value, confirm_relaxation:form.elements.confirm_relaxation.checked};
if (state.can_appoint && JSON.stringify(owners.map(o => o.membership_uuid)) !== JSON.stringify(state.owners.map(o => o.membership_uuid))) body.owners = owners.map(o => o.membership_uuid);
fields.disabled = true; accessFields.disabled=true; const seq = generation;
publicationFields.disabled=true;
try {
const data = await api(endpoint+(preview ? '/preview' : ''), preview ? 'POST' : 'PATCH', body);
if (seq !== generation || !dialog.open) return;
showPolicy(data);
if (!preview) { state = data; accessState.epoch=data.epoch; owners = [...data.owners]; showOwners(); form.elements.confirm_relaxation.checked = false; result.textContent = dialog.dataset.saved; clearPublication(); }
else result.textContent = '';
} catch (error) { if (seq === generation) result.textContent = error.message; }
finally { if (seq === generation) {fields.disabled = false; accessFields.disabled=false; publicationFields.disabled=false;} }
};
form.addEventListener('submit', event => { event.preventDefault(); save(false); });
find('[data-governance-preview]').addEventListener('click', () => save(true));
find('[data-access-add]').addEventListener('click',()=>{ if(entries.length<64) { entries.push({kind:'user',name:'',permission:'read'}); showAccess(); } });
accessForm.addEventListener('submit',async event=>{
event.preventDefault(); if (!accessState || fields.disabled || accessFields.disabled) return;
const body={epoch:accessState.epoch,topology_version:accessState.topology_version,mode:accessForm.elements.mode.value,entries:accessForm.elements.mode.value==='inherit'?[]:entries.map(({kind,name,permission,id})=>({kind,name,permission,id}))};
fields.disabled=true; accessFields.disabled=true; const seq=generation;
publicationFields.disabled=true;clearPublication();
try { const data=await api(endpoint+'/access','PATCH',body); if(seq!==generation||!dialog.open)return; accessState=data; state.epoch=data.epoch; entries=data.entries.map(e=>({...e})); showAccess(); accessForm.elements.confirm.checked=false; result.textContent=accessForm.dataset.saved;
} catch(error) { if(seq===generation) result.textContent=error.message;
} finally { if(seq===generation) {fields.disabled=false;accessFields.disabled=false;publicationFields.disabled=false;} }
});
const publication = async operation => {
if(!state || fields.disabled || publicationFields.disabled) return;
const seq=generation; fields.disabled=true; accessFields.disabled=true; publicationFields.disabled=true;
const body=operation==='preview'?undefined:{epoch:state.epoch,topology_version:state.topology_version,publication_version:impact?.publication_version??state.publication_version,enabled:operation==='enable',confirm:publicationForm.elements.confirm.checked,impact_token:impact?.impact_token||''};
try {
const data=await api(endpoint+'/publication',operation==='preview'?'GET':'PATCH',body);
if(seq!==generation||!dialog.open)return;
if(data.epoch!==state.epoch||data.topology_version!==state.topology_version)throw new Error(dialog.dataset.conflict);
state.publication_version=data.publication_version;
impact=data;find('[data-publication-enable]').disabled=!data.eligible;publicationForm.elements.confirm.checked=false;
find('[data-publication-status]').textContent=publicationForm.dataset[data.enabled?'enabled':'disabled'];
const list=find('[data-publication-impact]');list.replaceChildren();
const ul=document.createElement('ul');
data.entries.forEach(e=>{const li=document.createElement('li');li.textContent=`${e.path} (${e.lang}) · ${e.revision_uuid}`;ul.append(li);});list.append(ul);
if(data.excluded.length){const p=document.createElement('p');p.textContent=publicationForm.dataset.excluded;list.append(p);const ul=document.createElement('ul');data.excluded.forEach(path=>{const li=document.createElement('li');li.textContent=path;ul.append(li);});list.append(ul);}
} catch(error){if(seq===generation){clearPublication();result.textContent=error.message;}}
finally{if(seq===generation){fields.disabled=false;accessFields.disabled=false;publicationFields.disabled=false;}}
};
find('[data-publication-preview]').addEventListener('click',()=>publication('preview'));
find('[data-publication-revoke]').addEventListener('click',()=>publication('revoke'));
publicationForm.addEventListener('submit',event=>{event.preventDefault();if(impact?.eligible)publication('enable');});
find('[data-auto-preview]').addEventListener('click',async()=>{
const seq=generation;clearAuto();
try {
const data=await api(endpoint+'/auto-publication');if(seq!==generation||!dialog.open)return;
autoState=data;autoForm.elements.mode.value=data.mode;
autoForm.elements.mode.querySelector('[value=automatic]').disabled=!data.can_automatic;
find('[data-auto-save]').disabled=false;
const list=document.createElement('ul');
(data.impact.entries||[]).forEach(entry=>{const li=document.createElement('li');li.textContent=entry.path+' · '+entry.lang;list.append(li);});
(data.impact.excluded||[]).forEach(path=>{const li=document.createElement('li');li.textContent=publicationForm.dataset.excluded+': '+path;list.append(li);});
if(!data.preview_complete){const note=document.createElement('p');note.textContent=publicationForm.dataset.error;list.append(note);}
const status=document.createElement('p');status.textContent=publicationForm.dataset[data.active?'enabled':'disabled'];find('[data-auto-impact]').append(status,list);
}catch(error){if(seq===generation)result.textContent=error.message;}
});
autoForm.addEventListener('submit',async event=>{
event.preventDefault();if(!autoState)return;
const seq=generation,mode=autoForm.elements.mode.value;
if(mode!=='required'&&!autoForm.elements.confirm.checked){autoForm.elements.confirm.setCustomValidity(autoForm.elements.confirm.parentElement.textContent.trim());autoForm.elements.confirm.reportValidity();return;}
find('[data-auto-save]').disabled=true;
try {
await api(endpoint+'/auto-publication','PATCH',{mode,version:autoState.version,epoch:autoState.epoch,topology_version:autoState.topology_version,confirm:autoForm.elements.confirm.checked,impact_token:autoState.impact.impact_token});
if(seq!==generation||!dialog.open)return;clearAuto();clearPublication();result.textContent=dialog.dataset.saved;
}catch(error){if(seq===generation){result.textContent=error.message;clearAuto();}}
});
autoForm.elements.confirm.addEventListener('change',()=>autoForm.elements.confirm.setCustomValidity(''));
autoForm.elements.mode.addEventListener('change',()=>autoForm.elements.confirm.setCustomValidity(''));
});