Files
Unified_Dashboard_Suite_Go/web/docs/editor.html
T

255 lines
28 KiB
HTML
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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>API Docs Editor</title>
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,[email protected],600;12..96,800&family=Instrument+Sans:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root{--paper:#F3EDE0;--card:#FBF8F1;--soft:#ECE5D6;--ink:#232831;--ink2:#575B63;--ink3:#6E6B62;--line:#DAD1BC;--acc:#1F6B61;--accfg:#fff;--tint:#D8E8E1;--ok:#1B6B45;--warn:#9A5208;--bad:#B3261E;
--display:'Bricolage Grotesque','Segoe UI Variable Display',system-ui,sans-serif;--sans:'Instrument Sans','Segoe UI',system-ui,sans-serif;--mono:'JetBrains Mono',ui-monospace,Consolas,monospace;color-scheme:light}
*{box-sizing:border-box;margin:0;padding:0}[hidden]{display:none!important}
body{background:var(--paper);color:var(--ink);font:15px/1.55 var(--sans);height:100vh;display:flex;flex-direction:column;-webkit-font-smoothing:antialiased}
button,input,select,textarea{font:inherit;color:inherit}button{cursor:pointer}
:focus-visible{outline:2px solid var(--acc);outline-offset:2px}
.btn{padding:8px 14px;border-radius:10px;border:1px solid var(--line);background:var(--card);font-weight:500;font-size:14px;transition:border-color .2s,transform .1s}
.btn:hover{border-color:var(--ink3)}.btn:active{transform:scale(.97)}.btn:disabled{opacity:.4;pointer-events:none}
.pri{background:var(--acc);border-color:var(--acc);color:var(--accfg);font-weight:600}.pri:hover{border-color:var(--acc);filter:brightness(1.08)}
.sm{padding:5px 10px;font-size:13px;border-radius:8px}.bad{color:var(--bad)}
header{display:flex;align-items:center;gap:10px;padding:12px 20px;background:var(--card);border-bottom:1px solid var(--line)}
header h1{font:800 18px var(--display);letter-spacing:-.02em;margin-right:6px}
.chip{display:inline-flex;align-items:center;gap:8px;padding:5px 12px;border-radius:99px;background:var(--soft);border:1px solid var(--line);font-size:13px;color:var(--ink2)}
.chip i{width:8px;height:8px;border-radius:50%;background:var(--ink3)}.chip.ok i{background:var(--ok)}.chip.wait i{background:var(--warn);animation:pl 1s infinite}.chip.dirty i{background:var(--warn)}
@keyframes pl{50%{opacity:.25}}
.sp{flex:1}
.app{flex:1;display:grid;grid-template-columns:300px minmax(0,1fr) minmax(0,var(--pv,46%));min-height:0}
.app.nopv{grid-template-columns:300px minmax(0,1fr)}
#tree{background:var(--card);border-right:1px solid var(--line);overflow:auto;padding:14px}
#tree input{width:100%;margin-bottom:10px}
.th,.ti,.tm{display:flex;gap:10px;align-items:center;width:100%;text-align:left;border:0;background:none;border-radius:9px;padding:7px 10px;font-size:14px;color:var(--ink2)}
.th{font-weight:600;color:var(--ink);margin-top:14px}.th em{margin-left:auto;font:400 12px var(--mono);color:var(--ink3);font-style:normal}
.ti{padding-left:26px}.ti span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.th:hover,.ti:hover,.tm:hover{background:var(--soft)}.on{background:var(--tint)!important;color:var(--ink)!important}
.dot{width:8px;height:8px;border-radius:50%;flex:none;background:var(--ink)}.dot.GET{background:none;border:2px solid var(--ink)}
.sw{width:10px;height:10px;border-radius:3px;flex:none}
.ta{width:100%;border:1px dashed var(--line);background:none;color:var(--ink3);font-size:13px;margin-top:6px;padding:7px;border-radius:9px}.ta:hover{color:var(--ink);border-color:var(--ink3)}
#form{overflow:auto;padding:34px 44px 140px}
#pv{border-left:1px solid var(--line);background:var(--paper);display:flex;flex-direction:column;min-width:0}
#pv .pvh{padding:9px 14px;font-size:13px;color:var(--ink3);border-bottom:1px solid var(--line);display:flex;gap:10px;align-items:center}
#pv iframe{flex:1;border:0;width:100%;background:#fff}
h2{font:800 28px/1.15 var(--display);letter-spacing:-.025em}
h3{font:700 16px var(--display);margin:40px 0 4px;display:flex;align-items:center;gap:12px}
.sub{color:var(--ink3);font-size:13.5px;margin-bottom:14px}
.bar{display:flex;gap:8px;flex-wrap:wrap;margin:16px 0 4px}
.g{display:grid;grid-template-columns:repeat(6,1fr);gap:16px;margin-top:18px}
.fl{display:block;grid-column:span 2}.fl.w3{grid-column:span 3}.fl.w4{grid-column:span 4}.fl.wf{grid-column:1/-1}
.fl>span{display:block;font-size:13px;font-weight:500;color:var(--ink2);margin-bottom:6px}
input,select,textarea{width:100%;padding:9px 12px;border-radius:10px;border:1px solid var(--line);background:var(--soft);font-size:14.5px}
textarea{resize:vertical;line-height:1.6}.mono{font-family:var(--mono);font-size:13.5px}
input:focus,select:focus,textarea:focus{outline:0;border-color:var(--acc);box-shadow:0 0 0 3px color-mix(in srgb,var(--acc) 22%,transparent)}
.card{border:1px solid var(--line);background:var(--card);border-radius:16px;padding:18px;margin-top:12px}
.card .g{margin-top:0}.card .rh{display:flex;gap:6px;justify-content:space-between;align-items:center;margin-bottom:14px}.card .rh b{font:500 14px var(--mono)}
.sr{display:grid;grid-template-columns:110px 1.2fr 2fr auto;gap:10px;margin-top:10px;align-items:end}
.warn{margin-top:18px;border:1px solid color-mix(in srgb,var(--warn) 45%,var(--line));background:color-mix(in srgb,var(--warn) 10%,transparent);border-radius:12px;padding:12px 16px;font-size:14px;color:var(--ink)}.warn li{margin-left:18px}
.pchips{display:flex;flex-wrap:wrap;gap:6px;margin-top:12px;max-height:130px;overflow:auto}.pchips span{font:400 12.5px var(--mono);padding:3px 9px;border-radius:7px;background:var(--soft);border:1px solid var(--line)}
.hue{display:flex;gap:12px;align-items:center}.hue input{padding:0;height:8px;accent-color:var(--acc)}.hue i{width:30px;height:30px;border-radius:9px;flex:none}
.empty{max-width:560px;margin:10vh auto;text-align:center;color:var(--ink2)}.empty h2{color:var(--ink);margin-bottom:14px}.empty ol{text-align:left;margin:22px auto;padding-left:22px;line-height:2}
.banner{display:flex;gap:12px;align-items:center;flex-wrap:wrap;background:var(--tint);border-radius:12px;padding:12px 16px;margin-bottom:22px;font-size:14px}
#st{position:fixed;left:50%;bottom:26px;translate:-50% 0;background:var(--ink);color:var(--paper);padding:11px 20px;border-radius:12px;font-weight:500;z-index:50}
code{font-family:var(--mono);font-size:.92em}
@media(max-width:1100px){.app,.app.nopv{grid-template-columns:260px minmax(0,1fr)}#pv{display:none}}
@media(max-width:760px){.app,.app.nopv{grid-template-columns:1fr;grid-template-rows:34vh 1fr}#form{padding:22px}.g{grid-template-columns:1fr 1fr}.sr{grid-template-columns:1fr 1fr}}
@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}
</style>
</head>
<body>
<header>
<h1>API Docs Editor</h1><span class="chip wait" id="status"><i></i><span>Looking for your docs…</span></span>
<span class="chip" id="sessionPill" title="Security session expires in 10 minutes" style="font-family:var(--mono);font-size:12.5px;"><i style="background:var(--ok);"></i><span id="timerCountdown">10:00</span></span>
<span class="sp"></span>
<button class="btn" id="undo" disabled title="Undo (outside text fields)">Undo</button><button class="btn" id="redo" disabled>Redo</button>
<button class="btn" id="pvb">Hide preview</button><button class="btn" id="dl" disabled>Download copy</button><button class="btn pri" id="save" disabled>Save Changes</button>
<a href="/docs/" target="_blank" class="btn" style="text-decoration:none;">View Docs ↗</a>
<a href="/docs/editor/logout" class="btn bad" style="text-decoration:none;">Log out</a>
</header>
<div class="app" id="app">
<nav id="tree" aria-label="Docs outline"></nav>
<main id="form"><div class="empty"><h2>Looking for your docs</h2><p>Checking this folder for the docs file…</p></div></main>
<aside id="pv"><div class="pvh"><span>Live preview of your docs</span></div><iframe id="docs" title="Docs preview"></iframe></aside>
</div>
<input type="file" id="fi" accept=".html,text/html" hidden><div id="st" hidden></div>
<script>
const $=s=>document.querySelector(s),esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const CANDIDATES=[...new URLSearchParams(location.search).getAll('docs'),'/docs/index.html','/docs/','FASTAPI_BACKEND_API_DOCS.html','fastapi_backend_api_docs.html','API_DOCS.html','api_docs.html','api-docs.html','index.html','docs.html'];
const METHODS=['POST','GET','PUT','PATCH','DELETE'],slug=s=>s.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'item';
let D=null,saved='',file='',sel={k:'meta'},past=[],future=[],last='',dirty=false,fh=null,pvOn=true,src='';
const frame=$('#docs'),toast=m=>{const t=$('#st');t.textContent=m;t.hidden=false;clearTimeout(toast.t);toast.t=setTimeout(()=>t.hidden=true,2800)};
const setStatus=(c,t)=>{const s=$('#status');s.className='chip '+c;s.lastChild.textContent=t};
/* ---------- discovery: embed the docs and ask it for its data ---------- */
const waiters=[];
addEventListener('message',ev=>{const m=ev.data;if(ev.source!==frame.contentWindow||!m||m.apidocs!==1)return;waiters.splice(0).forEach(w=>w(m))});
const post=o=>frame.contentWindow&&frame.contentWindow.postMessage({apidocs:1,...o},'*');
function waitFor(type,ms){return new Promise(res=>{const t=setTimeout(()=>res(null),ms),h=m=>{if(m.type===type){clearTimeout(t);res(m)}else waiters.push(h)};waiters.push(h)})}
async function probe(set,ms=2600){set();const end=Date.now()+ms;
while(Date.now()<end){const p=waitFor('data',350);post({type:'hello'});const m=await p;if(m)return m}return null}
async function discover(){setStatus('wait','Looking for your docs…');
for(const c of CANDIDATES){const m=await probe(()=>{frame.removeAttribute('srcdoc');frame.src=c+(c.includes('?')?'&':'?')+'embed=1'});if(m)return connect(m.data,m.file||c,c)}
failed()}
function connect(data,name,s){src=s;file=name;D=data;saved=JSON.stringify(D);last=saved;past=[];future=[];sel={k:'meta'};dirty=false;
['dl','save'].forEach(i=>$('#'+i).disabled=false);updateUI();draw();restoreDraft()}
function failed(){setStatus('','Docs file not found');$('#tree').innerHTML='';$('#form').innerHTML=`<div class="empty"><h2>I couldn’t find the docs file</h2><p>The editor looks for <code>FASTAPI_BACKEND_API_DOCS.html</code> in the same folder. Put both files in one folder, keep the docs file’s name, and reload. If it’s named differently, you can also open it by hand:</p><p style="margin-top:22px"><button class="btn pri" id="open">Choose docs file</button> <button class="btn" id="retry">Look again</button></p></div>`}
$('#form').addEventListener('click',async e=>{if(e.target.id==='retry')discover();if(e.target.id==='open')$('#fi').click()});
$('#fi').onchange=async e=>{const f=e.target.files[0];if(!f)return;const text=await f.text();
const m=await probe(()=>{frame.srcdoc=text},3000);if(!m)return alert('That file has no editable data block. Pick the redesigned FASTAPI_BACKEND_API_DOCS.html.');connect(m.data,f.name,'srcdoc')};
/* ---------- state, history, drafts ---------- */
const snap=()=>{const j=JSON.stringify(D);if(j===last)return;past.push(last);if(past.length>200)past.shift();future=[];last=j;dirty=j!==saved;updateUI();pushPreview();saveDraft()};
let tm;const touch=()=>{dirty=true;updateUI();clearTimeout(tm);tm=setTimeout(snap,500);pushPreviewSoon()};
const now=()=>{clearTimeout(tm);snap()};
function restoreState(j){D=JSON.parse(j);last=j;dirty=j!==saved;sel=fixSel();updateUI();draw();pushPreview();saveDraft()}
$('#undo').onclick=()=>{now();if(!past.length)return;future.push(last);restoreState(past.pop())};
$('#redo').onclick=()=>{if(!future.length)return;past.push(last);restoreState(future.pop())};
function fixSel(){if(sel.k==='meta')return sel;const s=D.sections[sel.s];if(!s)return{k:'meta'};if(sel.k==='ep'&&!s.eps[sel.e])return{k:'sec',s:sel.s};return sel}
const dkey=()=>'apidocs-editor-draft:'+file;
function saveDraft(){try{dirty?localStorage.setItem(dkey(),JSON.stringify({t:Date.now(),d:D})):localStorage.removeItem(dkey())}catch{}}
function restoreDraft(){try{const r=JSON.parse(localStorage.getItem(dkey())||'null');if(!r||JSON.stringify(r.d)===saved)return;
const b=document.createElement('div');b.className='banner';b.innerHTML=`<span>You have unsaved edits from ${new Date(r.t).toLocaleString()}.</span><button class="btn sm pri" data-r>Restore them</button><button class="btn sm" data-d>Discard</button>`;
$('#form').prepend(b);b.onclick=e=>{if(e.target.dataset.r!==undefined){past.push(last);D=r.d;last=JSON.stringify(D);dirty=true;updateUI();draw();pushPreview()}if(e.target.dataset.d!==undefined)localStorage.removeItem(dkey());b.remove()}}catch{}}
function updateUI(){$('#undo').disabled=!past.length;$('#redo').disabled=!future.length;setStatus(dirty?'dirty':'ok',file+(dirty?' · unsaved changes':' · connected'))}
let pt;const pushPreviewSoon=()=>{clearTimeout(pt);pt=setTimeout(pushPreview,350)};
const pushPreview=()=>{if(D)post({type:'render',data:D})};
/* ---------- outline ---------- */
const cs=()=>D.sections[sel.s],ce=()=>cs().eps[sel.e];
function tree(){const q=(($('#tf')||{}).value||'').toLowerCase();
$('#tree').innerHTML=`<input id="tf" placeholder="Filter endpoints" value="${esc(q)}"><button class="tm ${sel.k==='meta'?'on':''}" data-a="sel" data-k="meta">Page settings</button>`+
D.sections.map((s,i)=>`<button class="th ${sel.k==='sec'&&sel.s===i?'on':''}" data-a="sel" data-k="sec" data-s="${i}"><i class="sw" style="background:hsl(${+s.hue||250} 70% 55%)"></i>${esc(s.title)}<em>${s.eps.length}</em></button>`+
s.eps.map((e,j)=>`<button class="ti ${sel.k==='ep'&&sel.s===i&&sel.e===j?'on':''}" data-a="sel" data-k="ep" data-s="${i}" data-e="${j}" ${q&&!(e.title+e.path).toLowerCase().includes(q)?'hidden':''}><i class="dot ${esc(e.method)}"></i><span>${esc(e.title)}</span></button>`).join('')+`<button class="ta" data-a="adde" data-s="${i}">Add endpoint</button>`).join('')+`<button class="ta" style="margin-top:22px" data-a="adds">Add family</button>`;
const f=$('#tf');f.oninput=()=>{const v=f.value.toLowerCase();document.querySelectorAll('.ti').forEach(b=>{const e=D.sections[+b.dataset.s].eps[+b.dataset.e];b.hidden=!!v&&!(e.title+e.path).toLowerCase().includes(v)})}}
/* ---------- forms ---------- */
const F=(l,p,v,o={})=>`<label class="fl ${o.c||''}"><span>${l}</span>${o.ta?`<textarea class="${o.m?'mono':''}" data-b="${p}" ${o.t?`data-t="${o.t}"`:''} rows="${o.ta}" ${o.ph?`placeholder="${esc(o.ph)}"`:''}>${esc(v)}</textarea>`:o.o?`<select data-b="${p}" ${o.t?`data-t="${o.t}"`:''}>${o.o.map(x=>{x=Array.isArray(x)?x:[x,x];return`<option value="${esc(x[0])}" ${String(x[0])===String(v)?'selected':''}>${esc(x[1])}</option>`}).join('')}</select>`:`<input class="${o.m?'mono':''}" data-b="${p}" value="${esc(v)}" ${o.t?`data-t="${o.t}"`:''} ${o.ph?`placeholder="${esc(o.ph)}"`:''}>`}</label>`;
const acts=(a,i,n)=>`<div style="display:flex;gap:6px"><button class="btn sm" data-a="${a}up" data-i="${i}" ${i?'':'disabled'} aria-label="Move up">↑</button><button class="btn sm" data-a="${a}dn" data-i="${i}" ${i<n-1?'':'disabled'} aria-label="Move down">↓</button><button class="btn sm bad" data-a="${a}del" data-i="${i}">Delete</button></div>`;
function issues(e){const out=[],all=D.sections.flatMap(s=>s.eps);
if(!e.params.some(p=>p.n.trim()))out.push('This endpoint has no parameters. Add at least its main ones so the docs never show an empty table.');
if(!e.path.startsWith('/'))out.push('Path should start with “/”.');
if(all.some(x=>x!==e&&x.path===e.path&&x.method===e.method))out.push('Another endpoint already uses this method and path.');
const names=e.params.map(p=>p.n.trim());if(names.some((n,i)=>!n))out.push('A parameter has no name.');
if(names.some((n,i)=>n&&names.indexOf(n)!==i))out.push('Two parameters share the same name.');
if(!e.title.trim())out.push('This endpoint has no title.');return out}
function form(){let h='';const f=$('#form'),y=f.scrollTop;
if(sel.k==='meta'){const m=D.meta;h=`<h2>Page settings</h2><p class="sub">Shown at the top of the docs and used in every code example.</p><div class="g">${F('Browser tab title','meta.title',m.title,{c:'w3'})}${F('Headline','meta.heading',m.heading||'',{c:'w3'})}${F('Base URL for examples','meta.baseUrl',m.baseUrl,{c:'w3',m:1,ph:'http://localhost'})}${F('Intro paragraph','meta.intro',m.intro,{ta:3,c:'wf'})}${F('Authentication note','meta.authNote',m.authNote,{ta:2,c:'wf'})}</div>`}
else if(sel.k==='sec'){const s=cs();h=`<h2>${esc(s.title)}</h2><p class="sub">${s.eps.length} endpoints in this family.</p><div class="bar"><button class="btn sm" data-a="sup" ${sel.s?'':'disabled'}>Move up</button><button class="btn sm" data-a="sdn" ${sel.s<D.sections.length-1?'':'disabled'}>Move down</button><button class="btn sm bad" data-a="sdel">Delete family</button></div><div class="g">${F('Title','title',s.title,{c:'w4'})}${F('Port','port',s.port||'',{m:1})}${F('Category label','tag',s.tag||'',{c:'w3'})}<label class="fl w3"><span>Colour</span><div class="hue"><i style="background:hsl(${+s.hue||250} 70% 55%)"></i><input type="range" min="0" max="360" data-b="hue" data-t="num" value="${+s.hue||250}"></div></label>${F('Description','lead',s.lead||'',{ta:3,c:'wf'})}</div>`}
else{const e=ce(),w=issues(e);h=`<h2>${esc(e.title||'Untitled endpoint')}</h2><p class="sub"><code>${esc(e.method)} ${esc(e.path)}</code></p>${w.length?`<ul class="warn">${w.map(x=>`<li>${esc(x)}</li>`).join('')}</ul>`:''}<div class="bar"><button class="btn sm" data-a="eup" ${sel.e?'':'disabled'}>Move up</button><button class="btn sm" data-a="edn" ${sel.e<cs().eps.length-1?'':'disabled'}>Move down</button><button class="btn sm" data-a="edup">Duplicate</button><button class="btn sm bad" data-a="edel">Delete endpoint</button></div>
<div class="g">${F('Method','method',e.method,{o:METHODS})}${F('Path','path',e.path,{c:'w4',m:1})}${F('Title','title',e.title,{c:'w4'})}<label class="fl"><span>Family</span><select data-mv>${D.sections.map((s,i)=>`<option value="${i}" ${i===sel.s?'selected':''}>${esc(s.title)}</option>`).join('')}</select></label>${F('Port','port',e.port,{m:1,c:'w3'})}${F('Returns','resp',e.resp,{m:1,c:'w3',ph:'image/png'})}${F('One-line summary','summary',e.summary,{c:'wf'})}${F('Description','desc',e.desc,{ta:4,c:'wf'})}</div>
<h3>Extra routes <button class="btn sm" data-a="adsub">Add route</button></h3><p class="sub">Other paths that share this endpoint’s parameters.</p>${e.subs.map((x,i)=>`<div class="sr">${F('Method',`subs.${i}.m`,x.m,{o:METHODS,c:''})}${F('Path',`subs.${i}.p`,x.p,{m:1,c:''})}${F('What it does',`subs.${i}.d`,x.d,{c:''})}<button class="btn sm bad" style="height:38px" data-a="delsub" data-i="${i}">Remove</button></div>`).join('')||'<p class="sub">None yet.</p>'}
<h3>Parameters <button class="btn sm" data-a="adp">Add parameter</button><button class="btn sm" data-a="adsk">Add secretKey</button></h3><p class="sub">${e.params.length} parameters, ${e.params.filter(p=>p.rq).length} required.</p>${e.params.map((p,i)=>`<div class="card"><div class="rh"><b>${esc(p.n||'unnamed')}</b>${acts('p',i,e.params.length)}</div><div class="g">${F('Name',`params.${i}.n`,p.n,{m:1})}${F('Also accepts',`params.${i}.al`,p.al,{m:1,ph:'optional alias'})}${F('Required',`params.${i}.rq`,p.rq,{o:[[true,'Required'],[false,'Optional']],t:'bool'})}${F('Type',`params.${i}.ty`,p.ty,{m:1,ph:'string or file (binary)'})}${F('Sent as',`params.${i}.lc`,p.lc,{m:1,ph:'multipart/form-data'})}${F('Default',`params.${i}.df`,p.df,{m:1,ph:'None'})}${F('What it does',`params.${i}.ds`,p.ds,{ta:2,c:'wf'})}</div></div>`).join('')}
<h3>Presets <button class="btn sm" data-a="sortc">Sort</button><button class="btn sm" data-a="dedupc">Remove duplicates</button></h3><p class="sub">${e.chips.length} accepted values. One per line, or comma separated.</p>${F('','chips',e.chips.join('\n'),{ta:6,t:'list',c:'wf',m:1})}<div class="pchips">${e.chips.slice(0,60).map(c=>`<span>${esc(c)}</span>`).join('')}${e.chips.length>60?`<span>+${e.chips.length-60} more</span>`:''}</div>
<h3>Request example <button class="btn sm" data-a="autoc" ${e.curl?'':'disabled'}>Use automatic example</button></h3><p class="sub">${e.curl?'This endpoint uses your custom cURL. The Python and JavaScript tabs stay automatic.':'Built automatically from the required parameters. Type here to write your own cURL instead.'} Use <code>{{base}}</code> for the base URL.</p>${F('','curl',e.curl,{ta:6,c:'wf',m:1,ph:'Leave empty for the automatic example'})}`}
f.innerHTML=h;f.scrollTop=y}
const draw=()=>{tree();form()};
function warn(){const w=issues(ce());let el=$('#form .warn');if(!w.length){el&&el.remove();return}
if(!el){el=document.createElement('ul');el.className='warn';$('#form .sub').after(el)}el.innerHTML=w.map(x=>`<li>${esc(x)}</li>`).join('')}
function chipsView(){const e=ce(),c=$('#form .pchips');if(!c)return;c.innerHTML=e.chips.slice(0,60).map(x=>`<span>${esc(x)}</span>`).join('')+(e.chips.length>60?`<span>+${e.chips.length-60} more</span>`:'')}
/* ---------- editing ---------- */
function setp(path,v,t){const o=sel.k==='meta'?D:sel.k==='sec'?cs():ce(),ks=path.split('.');let r=o;ks.slice(0,-1).forEach(k=>r=r[k]);r[ks.at(-1)]=t==='num'?+v||0:t==='bool'?v==='true':t==='list'?v.split(/[\n,]+/).map(x=>x.trim()).filter(Boolean):v}
document.addEventListener('input',e=>{const b=e.target.dataset.b;if(!b)return;setp(b,e.target.value,e.target.dataset.t);touch();
const h=$('#form h2');if(h&&b==='title')h.textContent=e.target.value||'Untitled endpoint';
if(sel.k==='sec'&&b==='hue'){tree();$('.hue i').style.background=`hsl(${e.target.value} 70% 55%)`}else if(b==='title'||b==='path'||b==='method')tree();if(sel.k==='ep')warn()});
document.addEventListener('change',e=>{if(e.target.matches('[data-mv]')){const to=+e.target.value,[x]=cs().eps.splice(sel.e,1);D.sections[to].eps.push(x);sel={k:'ep',s:to,e:D.sections[to].eps.length-1};now();draw()}
else if(e.target.dataset.b&&(/\.rq$/.test(e.target.dataset.b)||e.target.dataset.b==='method')){now();draw()}
else if(e.target.dataset.b==='chips'){now();chipsView()}
else if(e.target.dataset.b)now()});
const mv=(a,i,d)=>{const j=i+d;[a[i],a[j]]=[a[j],a[i]]};
const uid=t=>{const all=new Set(D.sections.flatMap(s=>s.eps.map(e=>e.id)));let b=slug(t),n=b,k=2;while(all.has(n))n=b+'-'+k++;return n};
const SK=()=>{const f=D.sections.flatMap(s=>s.eps).flatMap(e=>e.params).find(p=>p.n==='secretKey');return f?{...f}:{n:'secretKey',al:'',ty:'string',lc:'multipart/form-data',rq:true,df:'',ds:'Authentication key.'}};
document.addEventListener('click',e=>{const x=e.target.closest('[data-a]');if(!x)return;const a=x.dataset.a,i=+x.dataset.i,d=x.dataset;let ch=true;
if(a==='sel'){now();sel=d.k==='meta'?{k:'meta'}:d.k==='sec'?{k:'sec',s:+d.s}:{k:'ep',s:+d.s,e:+d.e};ch=false;draw();$('#form').scrollTop=0;if(sel.k==='ep')post({type:'focus',id:ce().id});return}
if(a==='adds'){D.sections.push({id:'sec-'+uid('family'),key:slug('family'+D.sections.length),icon:'✨',title:'New family',tag:'',lead:'',port:'',hue:Math.floor(Math.random()*360),eps:[]});sel={k:'sec',s:D.sections.length-1}}
else if(a==='adde'){const s=D.sections[+d.s];s.eps.push({id:uid('new endpoint'),method:'POST',path:'/new/endpoint/',port:s.port||'',resp:'image/png',title:'New endpoint',summary:'',desc:'',subs:[],params:[SK()],chips:[],curl:''});sel={k:'ep',s:+d.s,e:s.eps.length-1}}
else if(a==='sup'||a==='sdn'){const j=sel.s+(a==='sup'?-1:1);mv(D.sections,sel.s,a==='sup'?-1:1);sel.s=j}
else if(a==='sdel'){if(cs().eps.length&&!confirm('Delete “'+cs().title+'” and its '+cs().eps.length+' endpoints? You can undo this.'))return;D.sections.splice(sel.s,1);sel={k:'meta'}}
else if(a==='eup'||a==='edn'){const j=sel.e+(a==='eup'?-1:1);mv(cs().eps,sel.e,a==='eup'?-1:1);sel.e=j}
else if(a==='edup'){const c=structuredClone(ce());c.title+=' (copy)';c.id=uid(c.title);cs().eps.splice(sel.e+1,0,c);sel.e++}
else if(a==='edel'){if(!confirm('Delete “'+ce().title+'”? You can undo this.'))return;cs().eps.splice(sel.e,1);sel={k:'sec',s:sel.s}}
else if(a==='adsub')ce().subs.push({m:'POST',p:'/',d:''});else if(a==='delsub')ce().subs.splice(i,1);
else if(a==='adp')ce().params.push({n:'new_param',al:'',ty:'string',lc:'multipart/form-data',rq:false,df:'None',ds:''});else if(a==='adsk')ce().params.push(SK());
else if(a==='pup'||a==='pdn')mv(ce().params,i,a==='pup'?-1:1);else if(a==='pdel')ce().params.splice(i,1);
else if(a==='sortc')ce().chips.sort((p,q)=>p.localeCompare(q,undefined,{numeric:true}));else if(a==='dedupc')ce().chips=[...new Set(ce().chips)];
else if(a==='autoc')ce().curl='';else return;
now();draw()});
/* ---------- saving ---------- */
const idb=()=>new Promise((res,rej)=>{const r=indexedDB.open('apidocs-editor',1);r.onupgradeneeded=()=>r.result.createObjectStore('h');r.onsuccess=()=>res(r.result);r.onerror=()=>rej(r.error)});
const hget=async k=>{try{const d=await idb();return await new Promise(r=>{const q=d.transaction('h').objectStore('h').get(k);q.onsuccess=()=>r(q.result);q.onerror=()=>r(null)})}catch{return null}};
const hset=async(k,v)=>{try{const d=await idb();d.transaction('h','readwrite').objectStore('h').put(v,k)}catch{}};
async function buildHtml(){now();const p=waitFor('html',5000);post({type:'export',data:D});const m=await p;if(!m)throw new Error('The docs page did not answer. Reload both files and try again.');return m.html}
async function save(){if(!D)return;try{const html=await buildHtml();
try {
const resp = await fetch('/docs/editor/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ html })
});
if (resp.ok) {
saved=JSON.stringify(D);dirty=false;saveDraft();updateUI();toast('Saved directly to server! Changes are now live in /docs/');
return;
}
} catch(err){console.warn('Server save error:', err);}
if(!window.showSaveFilePicker)return download(html);
let h=fh||await hget(dkey());if(h&&(await h.queryPermission({mode:'readwrite'}))!=='granted'&&(await h.requestPermission({mode:'readwrite'}))!=='granted')h=null;
if(!h){toast('Choose the docs file in this folder to overwrite it');h=await showSaveFilePicker({suggestedName:file,types:[{description:'HTML',accept:{'text/html':['.html']}}]});await hset(dkey(),h)}
fh=h;const w=await h.createWritable();await w.write(html);await w.close();saved=JSON.stringify(D);dirty=false;saveDraft();updateUI();toast('Saved to '+h.name+'. Reload the docs page to see it.')}
catch(e){if(e.name!=='AbortError')alert('Could not save in place: '+e.message+'\nUse Download copy and replace the docs file yourself.')}}
function download(html){const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([html],{type:'text/html'}));a.download=file||'FASTAPI_BACKEND_API_DOCS.html';a.click();toast('Downloaded. Replace the old docs file with it.')}
$('#save').onclick=save;$('#dl').onclick=async()=>{try{download(await buildHtml())}catch(e){alert(e.message)}};
$('#pvb').onclick=()=>{pvOn=!pvOn;$('#pv').hidden=!pvOn;$('#app').classList.toggle('nopv',!pvOn);$('#pvb').textContent=pvOn?'Hide preview':'Show preview'};
addEventListener('beforeunload',e=>{if(dirty){e.preventDefault();e.returnValue=''}});
addEventListener('keydown',e=>{if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'){e.preventDefault();save()}
const inField=/INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName);if(!inField&&(e.ctrlKey||e.metaKey)){const k=e.key.toLowerCase();if(k==='z'&&!e.shiftKey){e.preventDefault();$('#undo').click()}else if(k==='y'||(k==='z'&&e.shiftKey)){e.preventDefault();$('#redo').click()}}});
discover();
/* ---------- 10-Minute Session Auto-Logout ---------- */
let sessionRemaining = 600;
async function checkSession(){
try {
const res = await fetch('/docs/session');
if (!res.ok) { window.location.href = '/docs/editor/logout'; return; }
const data = await res.json();
if (data.authenticated && typeof data.remaining_seconds === 'number') {
sessionRemaining = data.remaining_seconds;
updateSessionDisplay();
} else { window.location.href = '/docs/editor/logout'; }
} catch(err){}
}
function updateSessionDisplay(){
const el = document.getElementById('timerCountdown');
const pill = document.getElementById('sessionPill');
if (!el) return;
const m = Math.floor(sessionRemaining / 60);
const s = sessionRemaining % 60;
el.textContent = `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
if (pill && sessionRemaining <= 60) {
pill.style.borderColor = 'var(--bad)';
pill.style.color = 'var(--bad)';
}
}
setInterval(() => {
sessionRemaining--;
if (sessionRemaining <= 0) {
toast('Admin session expired after 10 minutes. Logging out...');
setTimeout(() => { window.location.href = '/docs/editor/logout'; }, 600);
return;
}
updateSessionDisplay();
}, 1000);
setInterval(checkSession, 25000);
checkSession();
</script>
</body>
</html>