fix(docs): persist direct json data to server without saving/downloading html file, enable live auto-fetch in docs

This commit is contained in:
2026-10-27 17:50:54 +05:30
parent 7d2acbec47
commit 5b0f651c71
5 changed files with 36567 additions and 62 deletions
+64 -24
View File
@@ -69,7 +69,7 @@ code{font-family:var(--mono);font-size:.92em}
<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>
<button class="btn" id="pvb">Hide preview</button><button class="btn" id="dl" disabled>Download data.json</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>
@@ -94,7 +94,20 @@ const post=o=>frame.contentWindow&&frame.contentWindow.postMessage({apidocs:1,..
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…');
async function discover(){
setStatus('wait','Looking for your docs…');
try {
const res = await fetch('/docs/data.json?_t=' + Date.now(), { cache: 'no-store' });
if (res.ok) {
const live = await res.json();
if (live && live.sections && live.sections.length) {
frame.removeAttribute('srcdoc');
frame.src = '/docs/?embed=1';
connect(live, 'data.json', '/docs/data.json');
return;
}
}
} catch(e){}
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;
@@ -304,29 +317,56 @@ document.addEventListener('click',e=>{const x=e.target.closest('[data-a]');if(!x
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)});
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, data: D })
});
if (resp.ok) {
saved=JSON.stringify(D);dirty=false;saveDraft();updateUI();toast('Saved directly to server! Changes are now live in /docs/');
return;
async function save(){
if (!D) return;
const saveBtn = $('#save');
saveBtn.disabled = true;
saveBtn.textContent = 'Saving…';
now();
try {
const resp = await fetch('/docs/editor/save', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ data: D })
});
const result = await resp.json().catch(() => ({}));
if (resp.ok && result.status === 'ok') {
saved = JSON.stringify(D);
dirty = false;
saveDraft();
updateUI();
toast('Saved successfully to server! Changes are now live in /docs/');
return;
}
if (resp.status === 401) {
toast('Admin session required or expired. Logging in...');
setTimeout(() => { window.location.href = '/docs/editor'; }, 1500);
return;
}
toast('Save failed: ' + (result.error || 'Server error ' + resp.status));
} catch(err) {
console.error('Server save error:', err);
toast('Save error: ' + err.message);
} finally {
saveBtn.disabled = false;
saveBtn.textContent = 'Save Changes';
}
} 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)}};
}
function download(data){
const jsonStr = JSON.stringify(data || D, null, 2);
const blob = new Blob([jsonStr], { type: 'application/json' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'data.json';
a.click();
toast('Downloaded data.json');
}
$('#save').onclick = save;
$('#dl').onclick = () => download(D);
$('#dl').textContent = 'Download data.json';
$('#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()}