Files
pages/internal/server/testdata/editor-resilience.js
T
Anya Tokugawa d5d21b7841
Build and publish container images / images (push) Successful in 9m34s
Release container images / release (push) Successful in 36s
Refactor architecture into eight components and consolidate reliability work
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.
2026-11-01 15:23:31 +09:00

115 lines
9.1 KiB
JavaScript

(async () => {
const assert=(ok,message)=>{if(!ok)throw Error(message)};
const delay=ms=>new Promise(r=>setTimeout(r,ms));
const wait=async fn=>{for(let i=0;i<150;i++){if(fn())return;await delay(25)}throw Error('Editor condition timed out')};
try {
const frame=document.createElement('iframe');frame.style='width:100%;height:930px;border:0';document.body.append(frame);
await new Promise(resolve=>{frame.onload=resolve;frame.src='/e/-/editor-fixture?edittype=html'});
const w=frame.contentWindow,d=frame.contentDocument;
await wait(()=>w.PagesWikiCodeMirror&&d.querySelector('#preview h1'));
const e=w.PagesEditor, cm=w.PagesWikiCodeMirror, realFetch=w.fetch;
e.paused=true;
assert(e.owner,'Owner namespace missing');
assert(e.baseRevision,'Base revision missing');
// Real CodeMirror updates must mark dirty and store an authoring draft.
cm.dispatch({changes:{from:0,to:cm.state.doc.length,insert:'<h1>Local</h1><p>one two three</p>'}});
assert(e.dirty,'CodeMirror did not mark dirty');e.persist();
const key=e.keyPrefix()+e.tab;
assert(JSON.parse(w.localStorage.getItem(key)).text.includes('Local'),'Missing local draft');
w.fetch=async()=>{throw Error('offline fixture')};
assert(await e.saveNow()===false&&e.paused,'Offline save was not paused');
assert(e.text().includes('Local')&&w.localStorage.getItem(key),'Offline save lost text');
w.fetch=async()=>new w.Response('expired',{status:401});
assert(await e.saveNow()===false&&d.querySelector('#editor-save-status').dataset.state==='auth','Expiry undetected');
w.fetch=realFetch;
assert(await e.saveNow(),'Manual retry failed');assert(!w.localStorage.getItem(key),'Saved draft not cleared');
// Another transaction changes the same title: manual review, never overwrite.
const base=e.baseRevision;
const remote=await e.post('/_/api/v1/revisions/save',{object_uuid:e.value('object-uuid'),body:'<h1>Remote</h1><p>one two three</p>',lang:'und',content_type:'text/html',base_revision_uuid:base,editor_principal_uuid:e.owner});
e.paused=true;e.setText('<h1>Mine</h1><p>one two three</p>');
assert(await e.saveNow()===false,'Stale edit silently saved');
assert(d.querySelector('#editor-dialog textarea[readonly]'),'Conflict comparison missing');
assert((await e.state()).revision_uuid===remote.revision_uuid,'Remote overwritten');
const areas=d.querySelectorAll('#editor-dialog textarea');areas[areas.length-1].value='<h1>Resolved</h1><p>one two three</p>';
d.querySelector('#editor-dialog footer button:last-child').click();await wait(()=>!d.querySelector('#editor-dialog'));
assert(await e.saveNow(),'Conflict resolution not saved');
// A save response can be lost; retry acknowledges the already saved head.
e.paused=true;e.setText('<h1>Acknowledged</h1>');
let lost=false;
w.fetch=async(url,opts)=>{const response=await realFetch(url,opts);if(String(url).includes('revisions/save')&&!lost){lost=true;throw Error('lost response')}return response};
assert(!await e.saveNow(),'Lost response incorrectly successful');
w.fetch=realFetch;await e.saveNow();assert(!e.dirty,'Retry did not acknowledge saved head');
// Preserve newly typed text while converting / saving an older snapshot.
e.paused=true;e.setText('# Markdown','markdown');
let release,entered=false;
w.fetch=async(url,opts)=>{if(String(url).includes('render/markdown')&&!JSON.parse(opts.body).projection){entered=true;await new Promise(r=>release=r)}return realFetch(url,opts)};
const pending=e.saveNow();await wait(()=>entered);
e.setText('# Newer');release();await pending;w.fetch=realFetch;
assert(e.dirty&&e.text()==='# Newer','Typing during save was lost');e.paused=true;clearTimeout(e.autosaveTimer);
assert(await e.saveNow(),'Newer text save failed');
// Format changes preserve preview visibility and complete a safe conversion.
w.setEditorPreviewVisible(false);e.paused=true;
await e.switchFormat('html');await e.switchFormat('markdown');
assert(d.querySelector('#preview').hidden,'Format switch changed preview state');
assert(e.text().includes('Newer'),'Format switch lost source');
// Recover a draft into a new tab key and remove only that recovered snapshot.
e.persist();const oldKey=e.keyPrefix()+e.tab;e.tab=w.crypto.randomUUID();
e.offerRecovery();d.querySelector('#editor-dialog footer button:nth-child(2)').click();
await wait(()=>!d.querySelector('#editor-dialog'));
assert(w.localStorage.getItem(e.keyPrefix()+e.tab),'Recovery not stored');
assert(!w.localStorage.getItem(oldKey),'Recovered draft would reappear after save');
// Restore is staged locally, then creates a new revision on confirmation.
const beforeRestore=(await e.state()).revision_uuid;
await e.historyDialog();
const revisions=d.querySelector('#editor-dialog select');revisions.selectedIndex=revisions.options.length-1;
d.querySelector('#editor-dialog footer button:last-child').click();await wait(()=>!d.querySelector('#editor-dialog'));
assert((await e.state()).revision_uuid===beforeRestore,'Restore wrote before confirmation');
assert(e.text().includes('Base'),'Old revision not loaded');assert(await e.saveNow(),'Restore save failed');
assert(e.baseRevision!==beforeRestore,'Restore did not append revision');
// Separate ranges automatically merge, then repeat CAS against the new head.
e.paused=true;e.setText('<p>left middle right</p>','html');assert(await e.saveNow(),'Merge base save failed');
await e.post('/_/api/v1/revisions/save',{object_uuid:e.value('object-uuid'),body:'<p>left middle RIGHT</p>',lang:'und',content_type:'text/html',base_revision_uuid:e.baseRevision,editor_principal_uuid:e.owner});
e.paused=true;e.setText('<p>LEFT middle right</p>');await e.saveNow();
await wait(()=>!e.dirty);
assert((await e.state()).body==='<p>LEFT middle RIGHT</p>','Automatic merge lost a side');
// Protected HTML survives an actual Markdown edit and canonical save.
const html='<figure data-custom="retained"><img src="/photo" alt="Photo"><figcaption>Caption</figcaption></figure>';
e.paused=true;e.setText(html,'html');await e.switchFormat('markdown');
assert(e.text().includes('{=html}'),'Lossy HTML was not protected');
e.setText(e.text().replace('Caption','Edited caption'));
assert(await e.saveNow(),'Protected HTML save failed');
assert((await e.state()).body===html.replace('Caption','Edited caption'),'Protected HTML attributes or structure changed');
// Conversion failure must never save raw Markdown as HTML.
e.paused=true;e.setText('# Conversion failure');
const head=e.baseRevision;
w.fetch=async(url,opts)=>String(url).includes('render/markdown')?new w.Response('failed',{status:503}):realFetch(url,opts);
assert(!await e.saveNow(),'Conversion failure saved anyway');w.fetch=realFetch;
assert((await e.state()).revision_uuid===head,'Conversion failure created revision');
// Fork uses a new empty head for the target language; original stays intact.
e.languageDialog();d.querySelector('#editor-dialog input').value='en';
d.querySelector('#editor-dialog footer button:last-child').click();await wait(()=>!d.querySelector('#editor-dialog'));
assert(e.value('page-language')==='en'&&e.baseRevision==='','Language fork did not reset head');
assert(await e.saveNow(),'Language fork save failed');
assert((await e.state({lang:'und'})).revision_uuid===head,'Fork changed source language');
// Mobile always starts in insert mode, regardless of desktop preference.
const originalMedia=w.matchMedia;w.matchMedia=q=>q==='(pointer: coarse) and (hover: none)'?{matches:true}:originalMedia(q);
w.PagesWikiCodeMirror.destroy();w.PagesWikiCodeMirror=w.PagesWikiEditor.create(e.mount,'{{child}}','markdown',{keymap:'vim',autocomplete:true});
assert(d.querySelector('#editor-vim-mode').textContent==='INSERT','Mobile Vim not disabled');
const mobile=w.PagesWikiCodeMirror;mobile.dispatch({selection:{anchor:7}});mobile.focus();
mobile.contentDOM.dispatchEvent(new w.KeyboardEvent('keydown',{key:' ',code:'Space',ctrlKey:true,bubbles:true}));
await wait(()=>d.querySelector('.cm-tooltip-autocomplete li'));
await delay(100);
mobile.contentDOM.dispatchEvent(new w.KeyboardEvent('keydown',{key:'Enter',code:'Enter',bubbles:true}));
assert(mobile.state.doc.toString()==='{{children}}','Macro completion duplicated brackets: '+mobile.state.doc);
// Escape must not enter Vim normal mode on mobile.
mobile.contentDOM.dispatchEvent(new w.KeyboardEvent('keydown',{key:'Escape',bubbles:true}));
assert(d.querySelector('#editor-vim-mode').textContent==='INSERT','Mobile Vim mode active');
w.matchMedia=originalMedia;
e.paused=true;clearTimeout(e.autosaveTimer);clearInterval(e.stateTimer);
e.tools();
const style=w.getComputedStyle(d.querySelector('#editor-dialog'));
assert(style.color!==style.backgroundColor&&style.backgroundColor!=='rgba(0, 0, 0, 0)','Dialog not themed');
document.body.dataset.vimReady='true';
} catch(error) {const box=document.createElement('div');box.id='error';box.textContent=error.stack||error.message;document.body.prepend(box)}
})();