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.
446 lines
27 KiB
JavaScript
446 lines
27 KiB
JavaScript
/* Editing state is independent of projection HTML. No save follows a failed conversion. */
|
||
window.PagesEditor = {
|
||
init() {
|
||
this.editor = document.getElementById('editor')
|
||
this.preview = document.getElementById('preview')
|
||
this.mount = document.getElementById('editor-mount')
|
||
if (!this.editor || !this.preview || !this.mount) return
|
||
this.baseRevision = this.mount.dataset.baseRevision || ''
|
||
this.baseBody = document.getElementById('editor-base')?.value || ''
|
||
this.initialText = this.editor.value
|
||
this.owner = this.mount.dataset.owner || ''
|
||
this.serial = 0
|
||
this.paused = false
|
||
// The editor also runs on explicitly configured HTTP instances.
|
||
// This is a draft namespace, not an authentication credential.
|
||
this.tab = globalThis.crypto?.randomUUID?.() || Date.now().toString(36)+'-'+Math.random().toString(36).slice(2)
|
||
this.ja = document.documentElement.lang.startsWith('ja')
|
||
this.expireDrafts()
|
||
this.editor.addEventListener('input', () => this.changed())
|
||
document.querySelectorAll('[data-editor-action]').forEach(button => button.addEventListener('click', event => {
|
||
event.preventDefault()
|
||
const action = button.dataset.editorAction
|
||
if (action === 'save') this.saveNow()
|
||
if (action === 'rename') window.PagesPathActions?.renameCurrentPath()
|
||
if (action === 'delete') window.PagesPathActions?.removeCurrentPath()
|
||
if (action === 'html' || action === 'markdown') this.switchFormat(action)
|
||
if (action === 'preview') window.toggleEditorPreview()
|
||
if (action === 'tools') this.tools()
|
||
if (action === 'language') this.languageDialog()
|
||
if (action === 'restore') this.historyDialog()
|
||
}))
|
||
document.addEventListener('keydown', event => {
|
||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {event.preventDefault(); this.saveNow()}
|
||
})
|
||
window.addEventListener('beforeunload', event => {
|
||
if (this.dirty) { this.persist(); event.preventDefault(); event.returnValue = '' }
|
||
})
|
||
window.addEventListener('pagehide', () => { if (this.dirty) this.persist() })
|
||
window.addEventListener('offline', () => this.fail({kind:'offline'}))
|
||
window.addEventListener('online', () => { this.paused = true; this.status('reconnected'); this.checkState() })
|
||
document.addEventListener('visibilitychange', () => {
|
||
if (document.hidden) {if (this.dirty) this.persist()} else this.checkState()
|
||
})
|
||
this.stateTimer = setInterval(() => { if (!document.hidden) this.checkState() },30000)
|
||
this.renderPreview()
|
||
// CodeMirror is mounted by the next DOMContentLoaded listener.
|
||
setTimeout(() => this.offerRecovery(), 0)
|
||
},
|
||
t(key) {
|
||
const text = {
|
||
dirty:['未保存','Unsaved'], draft:['端末に下書きを保存済み','Draft saved on this device'], saved:['保存済み','Saved'], saving:['保存中…','Saving…'],
|
||
auth:['認証切れ:再ログイン後に保存してください','Session expired: sign in again, then save'],
|
||
forbidden:['権限がありません。下書きをダウンロードできます','Permission denied. You can download your draft'],
|
||
offline:['通信できません。保存を中断しました','Connection unavailable. Saving paused'],
|
||
failed:['保存・変換に失敗しました。本文は保持しています','Save/conversion failed. Your text is retained'],
|
||
storage:['端末保存に失敗しました。下書きをダウンロードしてください','Device storage failed. Download your draft'],
|
||
reconnected:['接続が戻りました。内容を確認して保存してください','Reconnected. Review your work and save'],
|
||
remote:['別の編集による更新があります。保存時に照合します','Another edit was saved. Changes will be checked when you save'],
|
||
conflict:['競合の確認(保存するまで反映されません)','Resolve conflict (not applied until saved)'],
|
||
base:['編集開始時','Base'], local:['自分の編集','Your changes'], latest:['最新の内容','Latest content'], result:['保存する内容(HTML/コード)','Result to save (HTML / code)'],
|
||
apply:['作業バッファへ反映','Apply to working buffer'], cancel:['閉じる','Close'], recovery:['未保存の下書きがあります','An unsaved draft is available'],
|
||
recover:['復元','Restore draft'], discard:['破棄','Discard'], export:['下書きダウンロード','Download draft'], tools:['挿入・下書き','Insert / drafts'],
|
||
privacy:['下書きはこの端末に平文で保存し、復元対象は7日以内です。期限切れはエディタ起動時に削除します。共有端末では作業後に削除してください。','Drafts are stored as plaintext on this device and recoverable for 7 days. Expired drafts are removed when the editor opens. Remove them after using a shared device.'],
|
||
language:['言語の編集・分岐(BCP 47)','Edit / fork language (BCP 47)'], open:['指定言語を開く','Open language'], fork:['現在の本文を指定言語へ分岐','Fork current text into language'],
|
||
exists:['指定言語には既に本文があります。編集として開いてください','This language already exists. Open it for editing'], history:['過去のリビジョンを復元','Restore a previous revision'],
|
||
signin:['再ログイン(別タブ)','Sign in again (new tab)'], insert:['挿入','Insert'], invalid:['言語タグを確認してください','Check the language tag'], identity:['別アカウントに切り替わっています。元のアカウントで開き直してください','Account changed. Reopen using the original account'],
|
||
incompatible:['ファイル形式が変更されています。下書きを退避して開き直してください','File type changed. Download your draft and reopen'], older:['さらに古い履歴','Older revisions'],
|
||
children:['子ページ一覧','Children'], table:['表','Table'], figure:['画像とキャプション','Image + caption'], note:['補足','Note'], code:['コードブロック','Code block'], quote:['引用','Quote'],
|
||
protected:['Markdown で表せない HTML は {=html} ブロックに保持します。ブロック内も編集でき、保存・プレビュー時に HTML として扱います。','HTML not representable in Markdown is retained in editable {=html} blocks and rendered as HTML on save / preview.'],
|
||
}
|
||
return text[key]?.[this.ja ? 0 : 1] || key
|
||
},
|
||
value(id) { return document.getElementById(id)?.value || '' },
|
||
format() {return this.value('edit-type')},
|
||
text() {return window.PagesWikiCodeMirror?.state.doc.toString() ?? this.editor.value},
|
||
status(key) {
|
||
const status = document.getElementById('editor-save-status')
|
||
if (status) {status.textContent = this.t(key); status.dataset.state = key}
|
||
},
|
||
keyPrefix() {return 'pageswiki.draft.v1:'+JSON.stringify([this.mount.dataset.domain,this.owner,this.value('object-uuid'),this.value('page-language')||'und'])+':'},
|
||
expireDrafts() {
|
||
try {
|
||
for (const key of Object.keys(localStorage)) {
|
||
if (!key.startsWith('pageswiki.draft.v1:')) continue
|
||
let draft
|
||
try {draft=JSON.parse(localStorage.getItem(key))} catch (_) {}
|
||
if (!PagesEditorCore.validDraft(draft)) localStorage.removeItem(key)
|
||
}
|
||
} catch (_) {this.status('storage')}
|
||
},
|
||
persist() {
|
||
if (!this.dirty) return
|
||
try {
|
||
const draft = {version:1, text:this.text(), format:this.format(), baseRevision:this.baseRevision, baseBody:this.baseBody, savedAt:Date.now()}
|
||
const data = JSON.stringify(draft)
|
||
if (new TextEncoder().encode(data).length > 2*1024*1024) throw Error('draft too large')
|
||
localStorage.setItem(this.keyPrefix()+this.tab,data)
|
||
this.draftStored = true
|
||
if (!this.paused && !this.saving) this.status('draft')
|
||
} catch (_) {this.draftStored = false; this.status('storage')}
|
||
},
|
||
clearDraft() {
|
||
clearTimeout(this.draftTimer)
|
||
try {localStorage.removeItem(this.keyPrefix()+this.tab)} catch (_) {}
|
||
},
|
||
offerRecovery() {
|
||
let candidate
|
||
try {
|
||
for (const key of Object.keys(localStorage)) {
|
||
if (!key.startsWith(this.keyPrefix())) continue
|
||
let draft
|
||
try {draft = JSON.parse(localStorage.getItem(key))} catch (_) {}
|
||
if (!PagesEditorCore.validDraft(draft)) {localStorage.removeItem(key); continue}
|
||
if (!candidate || draft.savedAt > candidate.draft.savedAt) candidate = {key,draft}
|
||
}
|
||
} catch (_) {this.status('storage'); return}
|
||
if (!candidate) return
|
||
this.paused = true
|
||
const {dialog,content,button} = this.dialog('recovery')
|
||
this.paragraph(content,this.t('privacy'))
|
||
this.paragraph(content,new Date(candidate.draft.savedAt).toLocaleString())
|
||
button('recover',() => {
|
||
// A stale draft must not change a plain file into HTML (or vice
|
||
// versa) merely because the editor was reopened in another mode.
|
||
const family = format => ['plain','code'].includes(format) ? format : 'html'
|
||
if (family(candidate.draft.format) !== family(this.format())) {this.fail({kind:'incompatible'}); return}
|
||
this.baseRevision = candidate.draft.baseRevision
|
||
this.baseBody = candidate.draft.baseBody
|
||
this.initialText = null
|
||
this.setText(candidate.draft.text,candidate.draft.format)
|
||
this.persist()
|
||
// Move this recovered snapshot, never remove another tab's newer
|
||
// draft. A failed local write must leave the recovery source intact.
|
||
if (this.draftStored && localStorage.getItem(candidate.key) === JSON.stringify(candidate.draft)) localStorage.removeItem(candidate.key)
|
||
dialog.close()
|
||
})
|
||
button('discard',() => {localStorage.removeItem(candidate.key); this.paused=false; dialog.close()})
|
||
button('export',() => this.download(candidate.draft.text,candidate.draft.format))
|
||
},
|
||
changed() {
|
||
this.serial++
|
||
this.dirty = true
|
||
this.status('dirty')
|
||
clearTimeout(this.draftTimer)
|
||
this.draftTimer = setTimeout(() => this.persist(),250)
|
||
clearTimeout(this.previewTimer)
|
||
this.previewController?.abort()
|
||
this.previewTimer = setTimeout(() => this.renderPreview(),300)
|
||
clearTimeout(this.autosaveTimer)
|
||
if (!this.paused) this.autosaveTimer = setTimeout(() => this.save(false),3000)
|
||
},
|
||
async request(url,options = {}) {
|
||
const controller = new AbortController()
|
||
const timer = setTimeout(() => controller.abort(),15000)
|
||
const abort = () => controller.abort()
|
||
options.signal?.addEventListener('abort',abort,{once:true})
|
||
if (options.signal?.aborted) controller.abort()
|
||
try {
|
||
const response = await fetch(url,{...options,signal:controller.signal,credentials:'same-origin',cache:'no-store'})
|
||
if (response.status === 401 || response.redirected) throw {kind:'auth'}
|
||
if (response.status === 403) throw {kind:'forbidden'}
|
||
if (response.status === 409) throw {kind:'conflict'}
|
||
if (!response.ok) throw {kind:'failed'}
|
||
if (!response.headers.get('Content-Type')?.includes('application/json')) throw {kind:'auth'}
|
||
return await response.json()
|
||
} catch (error) {
|
||
if (error.kind) throw error
|
||
throw {kind:'offline'}
|
||
} finally {clearTimeout(timer); options.signal?.removeEventListener('abort',abort)}
|
||
},
|
||
post(url,body,options={}) {return this.request(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body),...options})},
|
||
fail(error) {
|
||
this.paused = true
|
||
clearTimeout(this.autosaveTimer)
|
||
this.persist()
|
||
this.status(error.kind || 'failed')
|
||
if (this.dirty && this.draftStored===false) {
|
||
const status=document.getElementById('editor-save-status')
|
||
if (status) status.textContent+=' / '+this.t('storage')
|
||
}
|
||
},
|
||
async canonical(text = this.text(), format = this.format()) {
|
||
if (text === this.initialText && format === this.initialFormat) return this.baseBody
|
||
if (format !== 'markdown') return text
|
||
const data = await this.post('/_/api/v1/render/markdown',{markdown:text,authoring:true})
|
||
if (typeof data.html !== 'string') throw {kind:'failed'}
|
||
return data.html
|
||
},
|
||
getCanonicalHTML() {return this.canonical()},
|
||
async renderPreview() {
|
||
this.previewController?.abort()
|
||
const controller = new AbortController()
|
||
this.previewController = controller
|
||
const text = this.text()
|
||
if (this.format() === 'code' || this.format() === 'plain') {this.preview.classList.add('code-preview'); this.preview.textContent=text; return}
|
||
try {
|
||
const data = await this.post('/_/api/v1/render/markdown',{
|
||
...(this.format()==='html' ? {html:text} : {markdown:text}),path:window.PagesWikiCurrentPath || '/',projection:true,authoring:true,
|
||
},{signal:controller.signal})
|
||
if (controller.signal.aborted || text !== this.text()) return
|
||
this.preview.classList.remove('code-preview')
|
||
this.preview.innerHTML = data.html
|
||
window.PagesWikiLoadChildren?.(this.preview)
|
||
} catch (error) {
|
||
if (controller.signal.aborted) return
|
||
this.preview.classList.add('code-preview'); this.preview.textContent=text
|
||
this.fail(error)
|
||
}
|
||
},
|
||
stateURL(extra={}) {
|
||
const query = new URLSearchParams({uuid:this.value('object-uuid'),lang:this.value('page-language')||'und',...extra})
|
||
return '/_/api/v1/editor/state?'+query
|
||
},
|
||
async state(extra={}) {
|
||
const data = await this.request(this.stateURL(extra))
|
||
if (data.principal_uuid !== this.owner) throw {kind:'identity'}
|
||
return data
|
||
},
|
||
async checkState() {
|
||
if (this.checking || this.saving) return
|
||
this.checking = true
|
||
try {
|
||
const latest = await this.state({metadata:'1'})
|
||
if (latest.revision_uuid !== this.baseRevision) this.status('remote')
|
||
} catch (error) {this.fail(error)} finally {this.checking=false}
|
||
},
|
||
autosave() {return this.save(false)},
|
||
saveNow() {return this.save(true)},
|
||
async save(manual) {
|
||
if (this.saving) return false
|
||
if (!this.dirty) return !this.paused
|
||
if (!manual && this.paused) return false
|
||
if (manual) this.mergeAttempts=0
|
||
this.persist()
|
||
this.saving = true
|
||
this.status('saving')
|
||
const text = this.text(), format = this.format(), serial = this.serial
|
||
let body
|
||
try {
|
||
body = await this.canonical(text,format)
|
||
const data = await this.post('/_/api/v1/revisions/save',{
|
||
object_uuid:this.value('object-uuid'),body,message:manual?'manual-save':'autosave',
|
||
lang:this.value('page-language')||'und',content_type:this.value('page-content-type'),filename:this.value('page-filename'),
|
||
base_revision_uuid:this.baseRevision,editor_principal_uuid:this.owner,
|
||
})
|
||
if (!data.revision_uuid) throw {kind:'failed'}
|
||
this.baseRevision = data.revision_uuid
|
||
this.baseBody = typeof data.body==='string' ? data.body : body
|
||
this.initialText = text; this.initialFormat = format
|
||
this.paused = false
|
||
this.mergeAttempts=0
|
||
if (serial === this.serial) {this.dirty=false; this.clearDraft(); this.status('saved')}
|
||
else {this.persist(); this.autosaveTimer=setTimeout(() => this.save(false),3000)}
|
||
return serial === this.serial
|
||
} catch (error) {
|
||
if (error.kind === 'conflict' && body !== undefined) {
|
||
try {await this.resolveConflict(body,serial)} catch (failure) {this.fail(failure)}
|
||
} else this.fail(error)
|
||
return false
|
||
} finally {this.saving=false}
|
||
},
|
||
async resolveConflict(local,serial) {
|
||
this.paused = true
|
||
const remote = await this.state()
|
||
if ((remote.content_type||'').split(';')[0]!==this.value('page-content-type').split(';')[0]) {this.fail({kind:'incompatible'}); return}
|
||
// If a save succeeded but its response was lost, acknowledge it safely.
|
||
if (serial === this.serial && local === remote.body) {
|
||
this.baseRevision=remote.revision_uuid; this.baseBody=remote.body
|
||
this.initialText=this.text(); this.initialFormat=this.format()
|
||
this.dirty=false; this.paused=false; this.clearDraft(); this.status('saved'); return
|
||
}
|
||
if (serial !== this.serial) {this.status('remote'); this.persist(); return}
|
||
const merged = PagesEditorCore.merge(this.baseBody,local,remote.body)
|
||
const apply = result => {
|
||
this.baseRevision=remote.revision_uuid; this.baseBody=remote.body
|
||
document.getElementById('page-filename').value=remote.filename||''
|
||
this.initialText=null
|
||
this.setText(result,['code','plain'].includes(this.format())?this.format():'html')
|
||
this.persist()
|
||
}
|
||
if (merged !== null && (this.mergeAttempts || 0)<3) {
|
||
this.mergeAttempts=(this.mergeAttempts || 0)+1
|
||
apply(merged)
|
||
// A second CAS still guards a writer racing this automatic merge.
|
||
this.paused=false
|
||
this.autosaveTimer=setTimeout(() => this.save(false),500)
|
||
return
|
||
}
|
||
this.persist(); this.status('conflict')
|
||
const {dialog,content,button} = this.dialog('conflict')
|
||
this.area(content,'base',this.baseBody,true)
|
||
this.area(content,'local',local,true)
|
||
this.area(content,'latest',remote.body,true)
|
||
const result = this.area(content,'result',local,false)
|
||
button('apply',() => {
|
||
if (serial !== this.serial) {this.status('remote'); dialog.close(); return}
|
||
apply(result.value); dialog.close()
|
||
})
|
||
},
|
||
setText(text,format=this.format()) {
|
||
const oldFormat = this.format()
|
||
document.getElementById('edit-type').value=format
|
||
const status=document.getElementById('editor-format-status')
|
||
if (status) status.textContent=format
|
||
this.editor.value=text
|
||
if (oldFormat !== format && window.PagesWikiCodeMirror) {
|
||
window.PagesWikiCodeMirror.destroy()
|
||
window.PagesWikiCodeMirror = window.PagesWikiEditor.create(this.mount,text,format,{
|
||
keymap:this.mount.dataset.keymap,syntax:this.mount.dataset.syntax==='true',autocomplete:this.mount.dataset.autocomplete==='true',
|
||
})
|
||
} else if (window.PagesWikiCodeMirror) {
|
||
const cm=window.PagesWikiCodeMirror
|
||
cm.dispatch({changes:{from:0,to:cm.state.doc.length,insert:text}})
|
||
}
|
||
document.querySelectorAll('[data-editor-action="html"],[data-editor-action="markdown"]').forEach(button => {
|
||
const selected=button.dataset.editorAction===format
|
||
button.classList.toggle('active',selected); button.setAttribute('aria-pressed',String(selected))
|
||
})
|
||
this.changed()
|
||
},
|
||
async switchFormat(format) {
|
||
// Representation switching is only lossless inside the HTML canonical
|
||
// family. Plain text/code must never silently turn into executable HTML.
|
||
if (!['html','markdown'].includes(format) || ['plain','code'].includes(this.format())) return
|
||
if (format===this.format() || this.saving) return
|
||
this.paused=true; this.persist()
|
||
const serial=this.serial
|
||
try {
|
||
let body=await this.canonical()
|
||
if (serial!==this.serial) return
|
||
if (format==='markdown') {
|
||
const data=await this.post('/_/api/v1/editor/convert',{html:body})
|
||
if (serial!==this.serial) return
|
||
if (typeof data.markdown!=='string') throw {kind:'failed'}
|
||
body=data.markdown
|
||
}
|
||
this.setText(body,format)
|
||
this.persist()
|
||
} catch (error) {this.fail(error)}
|
||
},
|
||
dialog(title) {
|
||
document.querySelector('#editor-dialog')?.remove()
|
||
const dialog=document.createElement('dialog'); dialog.id='editor-dialog'; dialog.className='editor-dialog'
|
||
const heading=document.createElement('h2'); heading.textContent=this.t(title); dialog.append(heading)
|
||
const content=document.createElement('div'); content.className='editor-dialog-content'; dialog.append(content)
|
||
const footer=document.createElement('footer'); dialog.append(footer)
|
||
const button=(label,action) => {
|
||
const b=document.createElement('button'); b.type='button'; b.textContent=this.t(label)
|
||
b.addEventListener('click',() => Promise.resolve().then(action).catch(error => this.fail(error)))
|
||
footer.append(b); return b
|
||
}
|
||
button('cancel',() => dialog.close())
|
||
dialog.addEventListener('close',() => dialog.remove())
|
||
document.body.append(dialog); dialog.showModal()
|
||
return {dialog,content,button}
|
||
},
|
||
paragraph(parent,text) {const p=document.createElement('p'); p.textContent=text; parent.append(p)},
|
||
area(parent,label,text,readOnly) {
|
||
const wrapper=document.createElement('label'); wrapper.textContent=this.t(label)
|
||
const area=document.createElement('textarea'); area.value=text; area.readOnly=readOnly; area.rows=6; wrapper.append(area); parent.append(wrapper); return area
|
||
},
|
||
download(text=this.text(),format=this.format()) {
|
||
const url=URL.createObjectURL(new Blob([text],{type:'text/plain;charset=utf-8'}))
|
||
const a=document.createElement('a'); a.href=url; a.download='pageswiki-draft.'+(format==='markdown'?'md':format==='html'?'html':'txt'); a.click()
|
||
setTimeout(() => URL.revokeObjectURL(url),1000)
|
||
},
|
||
tools() {
|
||
const {dialog,content,button}=this.dialog('tools')
|
||
this.paragraph(content,this.t('privacy'))
|
||
const select=document.createElement('select'); select.setAttribute('aria-label',this.t('insert'))
|
||
this.paragraph(content,this.t('protected'))
|
||
const parts=[['children','{{children}}'],['table','<table>\n<thead><tr><th>Column</th></tr></thead>\n<tbody><tr><td>Value</td></tr></tbody>\n</table>'],['figure','<figure><img src="/_/obj/sha256:HASH" alt="Description"><figcaption>Caption</figcaption></figure>'],['note','<aside class="note"><p>Note</p></aside>'],['code','<pre><code class="language-text">code</code></pre>'],['quote','<blockquote><p>Quote</p></blockquote>']]
|
||
parts.forEach(([label],i) => {const option=document.createElement('option'); option.value=i; option.textContent=this.t(label); select.append(option)})
|
||
content.append(select)
|
||
const login=document.createElement('a'); login.href='/_/auth/login?return='+encodeURIComponent(location.pathname+location.search); login.target='_blank'; login.rel='noopener'; login.textContent=this.t('signin'); content.append(login)
|
||
button('insert',() => {
|
||
const part=parts[Number(select.value)]
|
||
const source=this.format()==='markdown' && part[0]!=='children' ? '```{=html}\n'+part[1]+'\n```' : part[1]
|
||
const text='\n\n'+source+'\n\n'
|
||
const cm=window.PagesWikiCodeMirror
|
||
if (cm) cm.dispatch(cm.state.replaceSelection(text)); else this.setText(this.text()+text)
|
||
dialog.close(); cm?.focus()
|
||
})
|
||
button('export',() => this.download())
|
||
button('discard',() => {
|
||
this.clearDraft()
|
||
this.status('dirty'); dialog.close()
|
||
})
|
||
},
|
||
languageDialog() {
|
||
if (this.saving) return
|
||
this.paused=true; this.persist()
|
||
const {dialog,content,button}=this.dialog('language')
|
||
const input=document.createElement('input'); input.value=this.value('page-language')||'und'; input.placeholder='ja / en / ja-JP'; input.setAttribute('aria-label',this.t('language')); content.append(input)
|
||
const lang=() => {
|
||
try {return input.value==='und'?'und':Intl.getCanonicalLocales(input.value.trim())[0] || (()=>{throw Error()})()} catch (_) {throw {kind:'invalid'}}
|
||
}
|
||
button('open',() => {const url=new URL(location.href); url.searchParams.set('lang',lang()); location.href=url.toString()})
|
||
button('fork',async () => {
|
||
if (this.saving) return
|
||
const target=lang(), serial=this.serial
|
||
const state=await this.state({lang:target})
|
||
if (state.revision_uuid) {this.paragraph(content,this.t('exists')); return}
|
||
if (serial!==this.serial || this.saving) return
|
||
document.getElementById('page-language').value=state.lang
|
||
this.baseRevision=''; this.baseBody=''; this.initialText=''; this.initialFormat=this.format()
|
||
const url=new URL(location.href); url.searchParams.set('lang',state.lang); history.replaceState(null,'',url)
|
||
this.changed(); this.persist(); dialog.close()
|
||
})
|
||
},
|
||
async historyDialog() {
|
||
if (this.saving) return
|
||
this.paused=true; this.persist()
|
||
try {
|
||
const {dialog,content,button}=this.dialog('history')
|
||
const select=document.createElement('select'); select.setAttribute('aria-label',this.t('history'))
|
||
content.append(select)
|
||
let before=''
|
||
const load=async () => {
|
||
older.disabled=true
|
||
const rows=await this.request('/_/api/v1/revisions/list?'+new URLSearchParams({uuid:this.value('object-uuid'),limit:'50',before}))
|
||
rows.filter(row => row.lang===(this.value('page-language')||'und')).forEach(row => {const option=document.createElement('option'); option.value=row.uuid; option.textContent=new Date(row.created_at*1000).toLocaleString()+' '+row.message+' '+row.uuid.slice(0,8); select.append(option)})
|
||
before=rows.at(-1)?.uuid||before
|
||
older.disabled=rows.length<50
|
||
}
|
||
const older=button('older',load)
|
||
button('recover',async () => {
|
||
if (!select.value || this.saving) return
|
||
const serial=this.serial
|
||
const old=await this.state({revision:select.value})
|
||
if (serial!==this.serial || this.saving) return
|
||
if (!old.editable) throw {kind:'incompatible'}
|
||
this.setText(this.format()==='markdown'?old.markdown:old.body)
|
||
this.persist(); dialog.close()
|
||
})
|
||
await load()
|
||
} catch (error) {this.fail(error)}
|
||
},
|
||
}
|
||
|
||
document.addEventListener('DOMContentLoaded',() => {
|
||
if (!document.body.classList.contains('mode-editor')) return
|
||
PagesEditor.init()
|
||
PagesEditor.initialFormat=PagesEditor.format()
|
||
})
|