fix(docs): resolve docs editor live preview, multi-route editing, and disk save persistence

This commit is contained in:
2026-10-27 17:26:44 +05:30
parent dc11be2ffa
commit 7d2acbec47
7 changed files with 18273 additions and 15620 deletions
File diff suppressed because one or more lines are too long
+32 -1
View File
@@ -371,7 +371,8 @@ func NewRouter(pm *ProcessManager) http.Handler {
}
var payload struct {
HTML string `json:"html"`
HTML string `json:"html"`
Data interface{} `json:"data"`
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil || len(payload.HTML) < 100 {
writeJSON(w, http.StatusBadRequest, map[string]interface{}{
@@ -391,9 +392,39 @@ func NewRouter(pm *ProcessManager) http.Handler {
}
_ = os.WriteFile("web/docs/FASTAPI_BACKEND_API_DOCS.html", []byte(payload.HTML), 0644)
// Save data.json and scratch/faithful_docs_data.json
var dataBytes []byte
if payload.Data != nil {
dataBytes, _ = json.MarshalIndent(payload.Data, "", " ")
} else {
// Extract from <script id="api-data" type="application/json">
startTag := `<script id="api-data" type="application/json">`
endTag := `</script>`
startIdx := strings.Index(payload.HTML, startTag)
if startIdx != -1 {
rem := payload.HTML[startIdx+len(startTag):]
endIdx := strings.Index(rem, endTag)
if endIdx != -1 {
rawJSON := rem[:endIdx]
var tmp interface{}
if err := json.Unmarshal([]byte(rawJSON), &tmp); err == nil {
dataBytes, _ = json.MarshalIndent(tmp, "", " ")
} else {
dataBytes = []byte(rawJSON)
}
}
}
}
if len(dataBytes) > 0 {
_ = os.WriteFile("web/docs/data.json", dataBytes, 0644)
_ = os.WriteFile("scratch/faithful_docs_data.json", dataBytes, 0644)
}
writeJSON(w, http.StatusOK, map[string]interface{}{
"status": "ok",
"bytes_written": len(payload.HTML),
"data_written": len(dataBytes),
})
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+8857 -8929
View File
File diff suppressed because it is too large Load Diff
+154 -33
View File
@@ -111,7 +111,17 @@ 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}
function fixSel(){
if(sel.k==='meta')return sel;
const s=D.sections[sel.s];
if(!s)return{k:'meta'};
if(sel.k==='ep'){
if(!s.eps[sel.e])return{k:'sec',s:sel.s};
ensureEndpoints(s.eps[sel.e]);
sel.sub=Math.max(0,Math.min(sel.sub||0,s.eps[sel.e].endpoints.length-1));
}
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;
@@ -122,65 +132,176 @@ 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];
const cs=()=>D.sections[sel.s],ce=()=>cs()?.eps[sel.e];
function ensureEndpoints(e){
if(!e)return;
if(!Array.isArray(e.endpoints)||e.endpoints.length===0){
e.endpoints=[{
id:e.id||uid(e.title||'sub-ep'),
title:e.title||'Default Endpoint',
method:e.method==='MULTI'?'POST':(e.method||'POST'),
subpath:e.path||'/',
full_url:e.full_url||'',
path:e.path||'/',
port:e.port||'',
resp:e.resp||'image/png',
summary:e.summary||'',
desc:e.desc||'',
params:Array.isArray(e.params)?e.params:[],
chips:Array.isArray(e.chips)?e.chips:[],
subs:Array.isArray(e.subs)?e.subs:[],
curl:e.curl||''
}];
}
}
function curSubEp(){
const e=ce();
if(!e)return null;
ensureEndpoints(e);
const idx=Math.max(0,Math.min(sel.sub||0,e.endpoints.length-1));
sel.sub=idx;
return e.endpoints[idx];
}
function syncEp(e){
if(!e)return;
ensureEndpoints(e);
const sub=curSubEp();
if(e.endpoints.length===1){
e.title=sub.title;
e.api_key=sub.title;
e.method=sub.method;
e.path=sub.path;
e.full_url=sub.full_url||'';
e.port=sub.port||e.port||'';
e.resp=sub.resp||'image/png';
e.summary=sub.summary||'';
e.desc=sub.desc||'';
e.params=sub.params||[];
e.chips=sub.chips||[];
e.subs=sub.subs||[];
e.curl=sub.curl||'';
} else {
e.method='MULTI';
e.title=e.endpoints[0].title;
e.api_key=e.endpoints[0].title;
e.summary=e.endpoints[0].summary;
e.desc=e.endpoints[0].desc;
e.path=e.endpoints[0].path;
e.full_url=e.endpoints[0].full_url||'';
e.params=e.endpoints[0].params||[];
e.chips=e.endpoints[0].chips||[];
}
}
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)})}}
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 || 'Untitled')}</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 issues(sub){
if(!sub)return[];
const out=[],all=D.sections.flatMap(s=>s.eps);
if(!sub.params||!sub.params.some(p=>p.n&&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(!sub.path||!sub.path.startsWith('/'))out.push('Path should start with “/”.');
const names=(sub.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(!sub.title||!sub.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'})}`}
else{
const e=ce();
ensureEndpoints(e);
const sub=curSubEp();
const w=issues(sub);
const subTabs=`
<div style="background:var(--card);border:1px solid var(--line);border-radius:14px;padding:12px 16px;margin:18px 0 20px;">
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;flex-wrap:wrap;gap:8px;">
<span style="font-weight:600;font-size:13px;color:var(--ink2);">
${e.endpoints.length > 1 ? `Multi-Route Service (${e.endpoints.length} endpoints):` : `Single Endpoint Service:`}
</span>
<div style="display:flex;gap:6px;">
<button type="button" class="btn sm" data-a="addsubep">+ Add Route</button>
${e.endpoints.length > 1 ? `<button type="button" class="btn sm bad" data-a="delsubep" data-i="${sel.sub}">Delete Route</button>` : ''}
</div>
</div>
<div style="display:flex;gap:6px;flex-wrap:wrap;">
${e.endpoints.map((se, i) => `
<button type="button" class="btn sm ${i === sel.sub ? 'pri' : ''}" data-a="selsub" data-i="${i}" style="font-family:var(--mono);font-size:12px;padding:5px 10px;">
<span style="opacity:0.85;margin-right:4px;">${esc(se.method)}</span>
<span>${esc(se.title || se.path || ('Route ' + (i + 1)))}</span>
</button>
`).join('')}
</div>
</div>`;
h=`<h2>${esc(sub.title||e.title||'Untitled endpoint')}</h2><p class="sub"><code>${esc(sub.method)} ${esc(sub.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 service</button><button class="btn sm bad" data-a="edel">Delete service</button></div>
${subTabs}
<div class="g">${F('Method','method',sub.method,{o:METHODS})}${F('Path','path',sub.path,{c:'w4',m:1})}${F('Title','title',sub.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',sub.port||e.port||'',{m:1,c:'w3'})}${F('Full Direct URL','full_url',sub.full_url||'',{c:'w4',m:1,ph:'https://apigp0006...'})}${F('Returns','resp',sub.resp||'image/png',{m:1,c:'w3',ph:'image/png'})}${F('One-line summary','summary',sub.summary||'',{c:'wf'})}${F('Description','desc',sub.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>${(sub.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">${(sub.params||[]).length} parameters, ${(sub.params||[]).filter(p=>p.rq).length} required.</p>${(sub.params||[]).map((p,i)=>`<div class="card"><div class="rh"><b>${esc(p.n||'unnamed')}</b>${acts('p',i,sub.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">${(sub.chips||[]).length} accepted values. One per line, or comma separated.</p>${F('','chips',(sub.chips||[]).join('\n'),{ta:6,t:'list',c:'wf',m:1})}<div class="pchips">${(sub.chips||[]).slice(0,60).map(c=>`<span>${esc(c)}</span>`).join('')}${(sub.chips||[]).length>60?`<span>+${sub.chips.length-60} more</span>`:''}</div>
<h3>Request example <button class="btn sm" data-a="autoc" ${sub.curl?'':'disabled'}>Use automatic example</button></h3><p class="sub">${sub.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',sub.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}
function warn(){const w=issues(curSubEp());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>`:'')}
function chipsView(){const e=curSubEp(),c=$('#form .pchips');if(!c||!e||!e.chips)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}
function setp(path,v,t){
const o=sel.k==='meta'?D:sel.k==='sec'?cs():curSubEp();
if(!o)return;
const 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;
if(sel.k==='ep'){
if(path==='port'){ ce().port = v; }
syncEp(ce());
}
}
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()}
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,sub:0};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.'}};
const uid=t=>{const all=new Set(D.sections.flatMap(s=>s.eps.flatMap(e=>[e.id,...(e.endpoints||[]).map(se=>se.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||[]),...((e.endpoints||[]).flatMap(se=>se.params||[]))]).find(p=>p.n==='secretKey');return f?{...f}:{n:'secretKey',al:'',ty:'string',lc:'multipart/form-data',rq:true,df:'abcdef',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==='sel'){now();sel=d.k==='meta'?{k:'meta'}:d.k==='sec'?{k:'sec',s:+d.s}:{k:'ep',s:+d.s,e:+d.e,sub:0};ch=false;draw();$('#form').scrollTop=0;if(sel.k==='ep')post({type:'focus',id:ce().id,subIdx:0});return}
if(a==='selsub'){now();sel.sub=i;ch=false;draw();post({type:'focus',id:ce().id,subIdx:i});return}
if(a==='addsubep'){const parent=ce();ensureEndpoints(parent);parent.endpoints.push({id:uid(parent.title+'-route'),method:'POST',path:'/new/route/',subpath:'new_route/',full_url:'',title:'New Route '+(parent.endpoints.length+1),summary:'',desc:'',subs:[],params:[SK()],chips:[],resp:'image/png',curl:''});sel.sub=parent.endpoints.length-1;syncEp(parent);now();draw();post({type:'focus',id:parent.id,subIdx:sel.sub});return}
if(a==='delsubep'){const parent=ce();ensureEndpoints(parent);if(parent.endpoints.length>1){if(!confirm('Delete route “'+curSubEp().title+'”? You can undo this.'))return;parent.endpoints.splice(sel.sub,1);sel.sub=Math.max(0,sel.sub-1);syncEp(parent);now();draw();post({type:'focus',id:parent.id,subIdx:sel.sub});}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==='adde'){const s=D.sections[+d.s];const newId=uid('new endpoint');s.eps.push({id:newId,method:'POST',path:'/new/endpoint/',port:s.port||'',resp:'image/png',title:'New endpoint',summary:'',desc:'',subs:[],params:[SK()],chips:[],curl:'',endpoints:[{id:newId,method:'POST',path:'/new/endpoint/',subpath:'endpoint/',full_url:'',title:'New endpoint',summary:'',desc:'',subs:[],params:[SK()],chips:[],resp:'image/png',curl:''}]});sel={k:'ep',s:+d.s,e:s.eps.length-1,sub:0}}
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==='edup'){const c=structuredClone(ce());c.title+=' (copy)';c.id=uid(c.title);if(c.endpoints&&c.endpoints.length){c.endpoints.forEach((sub,k)=>{sub.id=uid(c.title+'-route-'+(k+1));});}cs().eps.splice(sel.e+1,0,c);sel.e++;sel.sub=0}
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()});
else if(a==='adsub'){curSubEp().subs.push({m:'POST',p:'/',d:''});syncEp(ce());}
else if(a==='delsub'){curSubEp().subs.splice(i,1);syncEp(ce());}
else if(a==='adp'){curSubEp().params.push({n:'new_param',al:'',ty:'string',lc:'multipart/form-data',rq:false,df:'None',ds:''});syncEp(ce());}
else if(a==='adsk'){curSubEp().params.push(SK());syncEp(ce());}
else if(a==='pup'||a==='pdn'){mv(curSubEp().params,i,a==='pup'?-1:1);syncEp(ce());}
else if(a==='pdel'){curSubEp().params.splice(i,1);syncEp(ce());}
else if(a==='sortc'){curSubEp().chips.sort((p,q)=>p.localeCompare(q,undefined,{numeric:true}));syncEp(ce());}
else if(a==='dedupc'){curSubEp().chips=[...new Set(curSubEp().chips)];syncEp(ce());}
else if(a==='autoc'){curSubEp().curl='';syncEp(ce());}
else return;
now();draw();if(sel.k==='ep')post({type:'focus',id:ce().id,subIdx:sel.sub});});
/* ---------- 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)});
@@ -192,7 +313,7 @@ async function save(){if(!D)return;try{const html=await buildHtml();
const resp = await fetch('/docs/editor/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ html })
body: JSON.stringify({ html, data: D })
});
if (resp.ok) {
saved=JSON.stringify(D);dirty=false;saveDraft();updateUI();toast('Saved directly to server! Changes are now live in /docs/');
+26 -16
View File
File diff suppressed because one or more lines are too long