- Block editor: 13 block types with contentEditable + vanilla JS event delegation
- Slash menu /: 14 commands, 100% vanilla JS (zero Alpine conflicts)
- Keyboard: Enter=new block, Shift+Enter=soft break, arrows navigate blocks
- Drag & drop: SortableJS with 6-dot handles on block-wrapper
- Move to Trash: DELETE /board/api/pages/{id} + instant sidebar cleanup
- Placeholders: 'New page' + 'Type / for commands' in gray (CSS :empty::before)
- Redirect after delete stays in project context via workspaceKey
- Fixes: title auto-save, cursor positioning, x-for keys, Sortable guard
383 lines
24 KiB
HTML
383 lines
24 KiB
HTML
{% extends "base.html" %}
|
|
{% block page_icon %}📄{% endblock %}
|
|
{% block page_title %}{{ page.title }}{% endblock %}
|
|
|
|
{% block content %}
|
|
<div class="page-editor-wrapper" x-data="editor('{{ page.id }}', '{{ page.title|e }}', '{{ page.content_format }}', '{{ page.content|e }}')" x-init="init()">
|
|
|
|
<div class="page-cover-area">
|
|
<div class="page-title-block">
|
|
<span class="page-icon-emoji">📄</span>
|
|
<div class="page-title-input" contenteditable="true" id="_titleEl"
|
|
@paste.prevent="pastePlain($event)"
|
|
@input="dirty=true;autoSave()"
|
|
@keydown.enter.prevent="focusBlock()"
|
|
spellcheck="false">{{ page.title }}</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="blocks-container" id="_blocksCt" @click="onCtClick($event)">
|
|
|
|
<template x-for="idx in blocks.length" :key="'b'+idx">
|
|
<div class="block-wrapper" :data-bid="blocks[idx-1].id"
|
|
@mouseenter="hoverBid=blocks[idx-1].id" @mouseleave="hoverBid=null">
|
|
|
|
<div class="block-handle" :class="{visible:hoverBid===blocks[idx-1].id}">
|
|
<svg viewBox="0 0 16 16" width="14" height="14">
|
|
<circle cx="4" cy="3" r="1.3"/><circle cx="11" cy="3" r="1.3"/>
|
|
<circle cx="4" cy="8" r="1.3"/><circle cx="11" cy="8" r="1.3"/>
|
|
<circle cx="4" cy="13" r="1.3"/><circle cx="11" cy="13" r="1.3"/>
|
|
</svg>
|
|
</div>
|
|
<div class="block-actions" :class="{visible:hoverBid===blocks[idx-1].id}">
|
|
<button class="block-add-btn" @click="addAfter(idx-1)">+</button>
|
|
</div>
|
|
|
|
<div x-show="blocks[idx-1].type==='paragraph'" class="block-content" :data-bid="blocks[idx-1].id" contenteditable="true" data-placeholder="Type '/' for commands..." spellcheck="false"></div>
|
|
<h1 x-show="blocks[idx-1].type==='heading_1'" class="block-content block-h1" :data-bid="blocks[idx-1].id" contenteditable="true" data-placeholder="Heading 1" spellcheck="false"></h1>
|
|
<h2 x-show="blocks[idx-1].type==='heading_2'" class="block-content block-h2" :data-bid="blocks[idx-1].id" contenteditable="true" data-placeholder="Heading 2" spellcheck="false"></h2>
|
|
<h3 x-show="blocks[idx-1].type==='heading_3'" class="block-content block-h3" :data-bid="blocks[idx-1].id" contenteditable="true" data-placeholder="Heading 3" spellcheck="false"></h3>
|
|
<div x-show="blocks[idx-1].type==='bulleted_list'" class="block-content block-bullet" :data-bid="blocks[idx-1].id" contenteditable="true" data-placeholder="List" spellcheck="false"></div>
|
|
<div x-show="blocks[idx-1].type==='numbered_list'" class="block-content block-numbered" :data-bid="blocks[idx-1].id" contenteditable="true" data-placeholder="List" spellcheck="false"></div>
|
|
<div x-show="blocks[idx-1].type==='to_do'" class="block-content block-todo">
|
|
<input type="checkbox" class="todo-checkbox" :checked="blocks[idx-1].checked" @change="blocks[idx-1].checked=$event.target.checked;dirty=true;autoSave()">
|
|
<div :data-bid="blocks[idx-1].id" contenteditable="true" data-placeholder="To-do" spellcheck="false"></div>
|
|
</div>
|
|
<div x-show="blocks[idx-1].type==='toggle'" class="block-content block-toggle">
|
|
<button class="toggle-chevron" :class="{open:blocks[idx-1].expanded}" @click="blocks[idx-1].expanded=!blocks[idx-1].expanded;autoSave()">▶</button>
|
|
<div :data-bid="blocks[idx-1].id" contenteditable="true" data-placeholder="Toggle" spellcheck="false"></div>
|
|
</div>
|
|
<blockquote x-show="blocks[idx-1].type==='quote'" class="block-content block-quote" :data-bid="blocks[idx-1].id" contenteditable="true" data-placeholder="Quote" spellcheck="false"></blockquote>
|
|
<div x-show="blocks[idx-1].type==='code'" class="block-content block-code">
|
|
<div class="code-lang-label" x-text="blocks[idx-1].language||'Plain Text'"></div>
|
|
<pre><code :data-bid="blocks[idx-1].id" contenteditable="true" spellcheck="false"></code></pre>
|
|
</div>
|
|
<hr x-show="blocks[idx-1].type==='divider'" class="block-divider">
|
|
<div x-show="blocks[idx-1].type==='callout'" class="block-content block-callout" :style="{background:(blocks[idx-1].style&&blocks[idx-1].style.bgColor)||'var(--blue-bg)'}">
|
|
<span class="callout-icon" x-text="blocks[idx-1].icon||'💡'">💡</span>
|
|
<div :data-bid="blocks[idx-1].id" contenteditable="true" data-placeholder="Type something..." spellcheck="false"></div>
|
|
</div>
|
|
<div x-show="blocks[idx-1].type==='image'" class="block-content block-image-wrapper">
|
|
<img :src="blocks[idx-1].src" style="max-width:100%;border-radius:4px" x-show="blocks[idx-1].src">
|
|
<div class="image-placeholder" x-show="!blocks[idx-1].src" @click="imgInputs[blocks[idx-1].id]?.click()" @drop.prevent="dropImg($event,idx-1)" @dragover.prevent>
|
|
<span>🖼 Click or drop image</span>
|
|
<input type="file" accept="image/*" style="display:none" :ref="el=>{if(el)imgInputs[blocks[idx-1].id]=el}" @change="uploadImg(idx-1,$event)">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</template>
|
|
|
|
<div class="blocks-empty" x-show="blocks.length===0" @click="addAt(0)">Press '/' for commands, or just start typing...</div>
|
|
</div>
|
|
|
|
<!-- Slash menu: built in vanilla JS, not Alpine -->
|
|
<div id="_slashMenu" class="slash-menu" style="display:none;position:fixed;z-index:999"></div>
|
|
|
|
<!-- Format Toolbar: Alpine for show/hide only -->
|
|
<div class="format-toolbar" x-show="fmt.open" :style="{top:fmt.top+'px',left:fmt.left+'px'}" @mousedown.prevent>
|
|
<button @click="fmtApply('bold')"><strong>B</strong></button>
|
|
<button @click="fmtApply('italic')"><em>I</em></button>
|
|
<button @click="fmtApply('underline')"><u>U</u></button>
|
|
<button @click="fmtApply('strikeThrough')"><s>S</s></button>
|
|
<button @click="fmtLink()">🔗</button>
|
|
</div>
|
|
|
|
<div class="editor-statusbar">
|
|
<span x-show="saving">Saving...</span>
|
|
<span x-show="!saving&&dirty">Unsaved</span>
|
|
<span x-show="!saving&&!dirty&&lastSaved">Saved <span x-text="lastSaved"></span></span>
|
|
<span class="statusbar-right" x-text="blocks.length+' blocks'"></span>
|
|
</div>
|
|
|
|
</div>
|
|
{% endblock %}
|
|
|
|
{% block scripts %}
|
|
<script>
|
|
// ═══════════════════════════════════════════
|
|
// FlowDeck Block Editor — Notion Clone v4
|
|
// Slash menu: pure vanilla JS (zero Alpine)
|
|
// Blocks: Alpine x-for + vanilla JS keydown
|
|
// ═══════════════════════════════════════════
|
|
|
|
let _bid=0;
|
|
function genId(){return 'b'+(++_bid)+'_'+Date.now().toString(36);}
|
|
|
|
// Slash commands data
|
|
const SLASH_GROUPS=[
|
|
{name:'BASIC',items:[
|
|
{id:'paragraph',name:'Text',icon:'¶'},
|
|
{id:'heading_1',name:'Heading 1',icon:'H1'},
|
|
{id:'heading_2',name:'Heading 2',icon:'H2'},
|
|
{id:'heading_3',name:'Heading 3',icon:'H3'},
|
|
{id:'bulleted_list',name:'Bulleted list',icon:'•'},
|
|
{id:'numbered_list',name:'Numbered list',icon:'1.'},
|
|
{id:'to_do',name:'To-do',icon:'☐'},
|
|
{id:'toggle',name:'Toggle',icon:'▶'},
|
|
{id:'quote',name:'Quote',icon:'❝'},
|
|
{id:'callout',name:'Callout',icon:'💡'},
|
|
{id:'divider',name:'Divider',icon:'—'},
|
|
{id:'code',name:'Code block',icon:'<>'},
|
|
]},
|
|
{name:'MEDIA',items:[
|
|
{id:'image',name:'Image',icon:'🖼'},
|
|
]},
|
|
];
|
|
|
|
// ── Slash Menu (100% vanilla JS, no Alpine) ──
|
|
const SlashMenu={
|
|
_open:false,_idx:-1,_sel:0,_q:'',_items:[],
|
|
_el:null,_inp:null,_list:null,
|
|
|
|
init(){
|
|
this._el=document.getElementById('_slashMenu');
|
|
if(!this._el)return;
|
|
this._inp=document.createElement('input');
|
|
this._inp.type='text';this._inp.placeholder='Filter...';
|
|
this._inp.style.cssText='width:100%;padding:6px 10px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);font-size:14px;outline:none;box-sizing:border-box';
|
|
this._inp.oninput=()=>this.filter();
|
|
this._inp.onkeydown=e=>this._onKey(e);
|
|
const hdr=document.createElement('div');
|
|
hdr.style.cssText='padding:8px;border-bottom:1px solid var(--border)';
|
|
hdr.appendChild(this._inp);
|
|
this._list=document.createElement('div');
|
|
this._list.style.cssText='overflow-y:auto;max-height:340px';
|
|
this._el.appendChild(hdr);
|
|
this._el.appendChild(this._list);
|
|
document.addEventListener('mousedown',e=>{if(!this._el.contains(e.target))this.close();});
|
|
},
|
|
|
|
open(idx,el){
|
|
if(!this._el)this.init();
|
|
this._idx=idx;this._q='';this._sel=0;this._inp.value='';
|
|
this.filter();
|
|
const r=el.getBoundingClientRect();
|
|
this._el.style.display='block';
|
|
const mh=this._el.offsetHeight||400;
|
|
this._el.style.top=Math.max(0,(r.bottom+4+mh>window.innerHeight)?r.top-mh-4:r.bottom+4)+'px';
|
|
this._el.style.left=Math.min(r.left,window.innerWidth-330)+'px';
|
|
this._inp.focus();this._open=true;
|
|
},
|
|
|
|
close(){
|
|
this._el.style.display='none';this._open=false;
|
|
this._inp.value='';this._q='';
|
|
},
|
|
|
|
filter(){
|
|
const q=(this._inp.value||'').toLowerCase();this._q=q;
|
|
let html='';
|
|
for(const g of SLASH_GROUPS){
|
|
let items=g.items;
|
|
if(q)items=items.filter(c=>c.name.toLowerCase().includes(q)||c.id.includes(q));
|
|
if(!items.length)continue;
|
|
html+=`<div style="padding:6px 12px 4px;font-size:11px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:.5px">${g.name}</div>`;
|
|
items.forEach((c,i)=>{
|
|
const sel=(this._items.length===this._sel);
|
|
if(sel)this._selItem=c.id;
|
|
this._items.push(c);
|
|
html+=`<div class="slash-item${sel?' selected':''}" data-sid="${c.id}" style="display:flex;align-items:center;gap:10px;padding:8px 12px;font-size:14px;color:var(--text-primary);cursor:pointer;transition:background .1s"
|
|
onmousedown="event.preventDefault()" onclick="SlashMenu.select('${c.id}')" onmouseenter="this.classList.add('selected')" onmouseleave="this.classList.remove('selected')">
|
|
<span style="width:28px;height:28px;display:flex;align-items:center;justify-content:center;font-size:16px;background:var(--bg-secondary);border-radius:4px;flex-shrink:0">${c.icon}</span>
|
|
<span style="flex:1;font-weight:500">${c.name}</span>
|
|
</div>`;
|
|
});
|
|
}
|
|
this._list.innerHTML=html;
|
|
if(this._items.length)this._selItem=this._items[0].id;
|
|
},
|
|
|
|
_onKey(e){
|
|
if(e.key==='ArrowDown'){e.preventDefault();this._sel=Math.min(this._sel+1,this._items.length-1);this._renderSel();}
|
|
else if(e.key==='ArrowUp'){e.preventDefault();this._sel=Math.max(this._sel-1,0);this._renderSel();}
|
|
else if(e.key==='Enter'){e.preventDefault();const c=this._items[this._sel];if(c)this.select(c.id);}
|
|
else if(e.key==='Escape'){e.preventDefault();this.close();}
|
|
},
|
|
|
|
_renderSel(){
|
|
const items=this._list.querySelectorAll('.slash-item');
|
|
items.forEach((el,i)=>{el.classList.toggle('selected',i===this._sel);});
|
|
},
|
|
|
|
select(id){
|
|
const ed=document.querySelector('.page-editor-wrapper');
|
|
if(!ed?.__x)return;
|
|
ed.__x.$data.applySlash(id);
|
|
this.close();
|
|
},
|
|
|
|
get isOpen(){return this._open;},
|
|
};
|
|
|
|
// ── Cursor helpers ──
|
|
function curPos(el){const s=window.getSelection();if(!s.rangeCount)return 0;const r=s.getRangeAt(0).cloneRange();r.selectNodeContents(el);r.setEnd(s.getRangeAt(0).endContainer,s.getRangeAt(0).endOffset);return r.toString().length;}
|
|
function curEnd(el){const r=document.createRange();r.selectNodeContents(el);r.collapse(false);const s=window.getSelection();s.removeAllRanges();s.addRange(r);}
|
|
function curStart(el){const r=document.createRange();r.selectNodeContents(el);r.collapse(true);const s=window.getSelection();s.removeAllRanges();s.addRange(r);}
|
|
|
|
// ── Editor component ──
|
|
function editor(pid,title,fmt,raw){
|
|
const self={
|
|
pid,pageTitle:title,blocks:[],hoverBid:null,
|
|
dirty:false,saving:false,lastSaved:'',st:null,
|
|
imgInputs:{},
|
|
fmt:{open:false,top:0,left:0,idx:-1},
|
|
|
|
init(){
|
|
_bid=Math.floor(Math.random()*10000);
|
|
if(fmt==='blocks'&&raw){try{this.blocks=JSON.parse(raw);this.blocks.forEach(b=>{if(!b.id)b.id=genId()});}catch(e){this.blocks=[];}}
|
|
else if(raw&&raw.trim())this.blocks=this.md2b(raw);
|
|
if(!this.blocks.length)this.blocks=[this.mkB('paragraph','')];
|
|
|
|
SlashMenu.init();
|
|
|
|
// Poll until DOM ready, then setup
|
|
let n=0;
|
|
const setup=()=>{
|
|
const ct=document.getElementById('_blocksCt');
|
|
if(!ct||!ct.querySelector('[data-bid]')){if(++n<60)requestAnimationFrame(setup);return;}
|
|
|
|
// Fill content
|
|
for(const b of this.blocks){
|
|
const el=ct.querySelector(`[data-bid="${b.id}"]:not(button):not(input)`);
|
|
if(el&&b.type!=='divider')el.textContent=b.content||'';
|
|
}
|
|
const b0=this.blocks[0];
|
|
if(b0){const f=ct.querySelector(`[data-bid="${b0.id}"]:not(button):not(input)`);if(f){f.focus();curEnd(f);}}
|
|
|
|
// === KEYDOWN (vanilla JS) ===
|
|
ct.addEventListener('keydown',e=>this.onKd(e,ct));
|
|
ct.addEventListener('paste',e=>{e.preventDefault();document.execCommand('insertText',false,(e.clipboardData||window.clipboardData).getData('text/plain'));this.dirty=true;this.autoSave();});
|
|
|
|
// SortableJS
|
|
if(typeof Sortable!=='undefined')Sortable.create(ct,{draggable:'.block-wrapper',handle:'.block-handle',animation:150,ghostClass:'sortable-ghost',dragClass:'sortable-drag',onEnd:evt=>{if(evt.oldIndex===evt.newIndex)return;const[item]=this.blocks.splice(evt.oldIndex,1);this.blocks.splice(evt.newIndex,0,item);this.dirty=true;this.autoSave();}});
|
|
};
|
|
requestAnimationFrame(setup);
|
|
},
|
|
|
|
mkB(type,content,extras){const b={id:genId(),type,content:content||'',...(extras||{})};if(type==='toggle')b.expanded=true;if(type==='to_do')b.checked=false;return b;},
|
|
|
|
focusFirstBlock(){const b=this.blocks[0];if(b){const el=this.getEl(b.id);if(el){el.focus();curEnd(el);}}},
|
|
focusBlock(){this.focusFirstBlock();},
|
|
onCtClick(e){
|
|
if(e.target===document.getElementById('_blocksCt')||e.target.classList.contains('blocks-empty')){
|
|
if(!this.blocks.length)this.addAt(0);
|
|
else{const b=this.blocks[this.blocks.length-1];const el=b&&this.getEl(b.id);if(el){el.focus();curEnd(el);}}
|
|
}
|
|
},
|
|
getEl(bid){const ct=document.getElementById('_blocksCt');return ct?ct.querySelector(`[data-bid="${bid}"]:not(button):not(input)`):null;},
|
|
getIdx(bid){return this.blocks.findIndex(b=>b.id===bid);},
|
|
|
|
addAt(idx,type,content){const b=this.mkB(type||'paragraph',content||'');this.blocks.splice(idx,0,b);this.dirty=true;this.autoSave();requestAnimationFrame(()=>{const el=this.getEl(b.id);if(el&&type!=='divider'){el.focus();curEnd(el);}});return b;},
|
|
addAfter(idx,type){return this.addAt(idx+1,type);},
|
|
|
|
removeBlock(idx){
|
|
if(this.blocks.length<=1){const b=this.blocks[0];b.type='paragraph';b.content='';const el=this.getEl(b.id);if(el)el.textContent='';this.dirty=true;this.autoSave();requestAnimationFrame(()=>{if(el)el.focus();});return;}
|
|
this.blocks.splice(idx,1);const fi=Math.max(0,idx-1);this.dirty=true;this.autoSave();
|
|
requestAnimationFrame(()=>{const el=this.getEl(this.blocks[fi]?.id);if(el){el.focus();curEnd(el);}});
|
|
},
|
|
|
|
// ── THE KEY HANDLER ──
|
|
onKd(e,ct){
|
|
const el=document.activeElement;
|
|
if(!el||!el.hasAttribute('data-bid'))return;
|
|
const bid=el.dataset.bid,idx=this.getIdx(bid);
|
|
if(idx<0)return;
|
|
const block=this.blocks[idx];
|
|
|
|
// Slash menu open
|
|
if(SlashMenu.isOpen){
|
|
if(e.key==='Escape'){e.preventDefault();SlashMenu.close();return;}
|
|
if(e.key==='ArrowDown'||e.key==='ArrowUp'||e.key==='Enter'){e.preventDefault();SlashMenu._inp.dispatchEvent(new KeyboardEvent('keydown',{key:e.key,bubbles:true}));return;}
|
|
if(e.key==='Backspace'&&!SlashMenu._q&&(el.textContent||'').trim()==='/'){e.preventDefault();SlashMenu.close();return;}
|
|
return;
|
|
}
|
|
|
|
// After content keys, check for slash
|
|
if(e.key.length===1||e.key==='Backspace'||e.key==='Delete'){
|
|
const b2=bid;setTimeout(()=>{const e2=this.getEl(b2);if(e2&&e2.textContent?.trim()==='/'&&!SlashMenu.isOpen)SlashMenu.open(this.getIdx(b2),e2);},15);
|
|
}
|
|
|
|
// ENTER
|
|
if(e.key==='Enter'){
|
|
if(e.shiftKey){this.dirty=true;this.autoSave();return;}
|
|
e.preventDefault();
|
|
const text=el.textContent||'',pos=curPos(el),before=text.substring(0,pos),after=text.substring(pos);
|
|
if(!before.trim()&&!after.trim()){const nt=(block.type==='bulleted_list'||block.type==='numbered_list'||block.type==='to_do')?block.type:'paragraph';this.addAt(idx+1,nt);return;}
|
|
el.textContent=before;block.content=before;
|
|
const nt=(block.type==='bulleted_list'||block.type==='numbered_list'||block.type==='to_do')?block.type:'paragraph';
|
|
const nb=this.addAt(idx+1,nt,after);this.dirty=true;this.autoSave();
|
|
requestAnimationFrame(()=>{const nel=this.getEl(nb.id);if(nel){nel.textContent=after;nel.focus();curStart(nel);}});
|
|
return;
|
|
}
|
|
|
|
// ARROW UP
|
|
if(e.key==='ArrowUp'){const pos=curPos(el);if(pos===0&&idx>0){e.preventDefault();const prev=this.getEl(this.blocks[idx-1]?.id);if(prev){prev.focus();curEnd(prev);}}return;}
|
|
// ARROW DOWN
|
|
if(e.key==='ArrowDown'){const pos=curPos(el),len=(el.textContent||'').length;if(pos>=len&&idx<this.blocks.length-1){e.preventDefault();const next=this.getEl(this.blocks[idx+1]?.id);if(next){next.focus();curStart(next);}}return;}
|
|
|
|
// BACKSPACE
|
|
if(e.key==='Backspace'){const text=el.textContent||'';if(!text.trim()){if(block.type!=='paragraph'){e.preventDefault();block.type='paragraph';block.content='';el.textContent='';this.dirty=true;this.autoSave();requestAnimationFrame(()=>el.focus());}else if(this.blocks.length>1){e.preventDefault();this.removeBlock(idx);}}return;}
|
|
|
|
// SPACE: check markdown
|
|
if(e.key===' '){const b2=bid;setTimeout(()=>this.checkMd(b2),10);}
|
|
|
|
// Ctrl shortcuts
|
|
if((e.ctrlKey||e.metaKey)&&!e.altKey){const m={b:'bold',i:'italic',u:'underline'};if(m[e.key]){e.preventDefault();document.execCommand(m[e.key]);this.dirty=true;this.autoSave();}}
|
|
if(e.key==='Tab'&&block.type==='code'){e.preventDefault();document.execCommand('insertText',false,' ');}
|
|
this.dirty=true;this.autoSave();
|
|
},
|
|
|
|
checkMd(bid){
|
|
const idx=this.getIdx(bid);if(idx<0)return;
|
|
const block=this.blocks[idx],el=this.getEl(bid);if(!el)return;
|
|
const text=el.textContent||'';
|
|
const sc={'# ':'heading_1','## ':'heading_2','### ':'heading_3','- ':'bulleted_list','* ':'bulleted_list','+ ':'bulleted_list','1. ':'numbered_list','[] ':'to_do','[ ] ':'to_do','> ':'quote'};
|
|
for(const[pfx,type] of Object.entries(sc)){if(text===pfx||text.startsWith(pfx)){block.type=type;block.content='';if(type==='toggle')block.expanded=true;if(type==='to_do')block.checked=false;this.dirty=true;this.autoSave();requestAnimationFrame(()=>{const nel=this.getEl(bid);if(nel){nel.textContent='';if(type!=='divider')nel.focus();}});return;}}
|
|
if(text==='---'){block.type='divider';block.content='';this.addAfter(idx,'paragraph');this.dirty=true;this.autoSave();}
|
|
if(text==='```'){block.type='code';block.content='';block.language='Plain Text';this.dirty=true;this.autoSave();requestAnimationFrame(()=>{const nel=this.getEl(bid);if(nel){nel.textContent='';nel.focus();}});}
|
|
},
|
|
|
|
// ── Slash apply (called from SlashMenu.select) ──
|
|
applySlash(id){
|
|
const idx=SlashMenu._idx;
|
|
if(idx<0||idx>=this.blocks.length)return;
|
|
const block=this.blocks[idx],el=this.getEl(block.id);
|
|
if(el)el.textContent='';block.content='';
|
|
if(id==='divider'){block.type='divider';block.content='';this.addAfter(idx,'paragraph');}
|
|
else{block.type=id;if(id==='toggle')block.expanded=true;if(id==='to_do')block.checked=false;if(id==='code')block.language='Plain Text';
|
|
requestAnimationFrame(()=>{const nel=this.getEl(block.id);if(nel){nel.textContent='';nel.focus();}});}
|
|
this.dirty=true;this.autoSave();
|
|
},
|
|
|
|
// ── Format toolbar ──
|
|
showFmt(idx){const s=window.getSelection();if(!s.rangeCount||s.isCollapsed){this.fmt.open=false;return;}const r=s.getRangeAt(0).getBoundingClientRect();this.fmt.open=true;this.fmt.idx=idx;this.fmt.top=Math.max(r.top-44,0);this.fmt.left=Math.min(r.left+r.width/2-120,window.innerWidth-260);this._sel={range:s.getRangeAt(0).cloneRange(),idx};},
|
|
fmtApply(f){this.fmt.open=false;if(!this._sel)return;const s=window.getSelection();s.removeAllRanges();s.addRange(this._sel.range);document.execCommand(f==='strikeThrough'?'strikeThrough':f);this._sel=null;this.dirty=true;this.autoSave();},
|
|
fmtLink(){this.fmt.open=false;const u=prompt('URL:');if(u){document.execCommand('createLink',false,u);this.dirty=true;this.autoSave();}},
|
|
|
|
dropImg(e,idx){const f=e.dataTransfer.files[0];if(f?.type?.startsWith('image/'))this.upFile(idx,f);},
|
|
uploadImg(idx,e){if(e.target.files[0])this.upFile(idx,e.target.files[0]);},
|
|
upFile(idx,file){const b=this.blocks[idx];const r=new FileReader();r.onload=ev=>{b.src=ev.target.result;this.dirty=true;this.autoSave();};r.readAsDataURL(file);},
|
|
pastePlain(e){e.preventDefault();document.execCommand('insertText',false,(e.clipboardData||window.clipboardData).getData('text/plain'));this.dirty=true;this.autoSave();},
|
|
|
|
autoSave(){clearTimeout(this.st);this.st=setTimeout(()=>this.save(),1500);},
|
|
save(){
|
|
if(this.saving)return;
|
|
const ct=document.getElementById('_blocksCt');
|
|
for(const b of this.blocks){if(b.type==='divider')continue;const el=ct?ct.querySelector(`[data-bid="${b.id}"]:not(button):not(input)`):null;if(el)b.content=el.textContent||'';}
|
|
const t=document.getElementById('_titleEl');if(t)this.pageTitle=t.textContent?.trim()||'Untitled';
|
|
this.saving=true;
|
|
const csrf=document.cookie.match(/csrf_token=([^;]+)/);
|
|
fetch(`/board/api/pages/${this.pid}/blocks`,{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':csrf?csrf[1]:''},body:JSON.stringify({title:this.pageTitle,blocks:this.blocks.map(b=>{const c={id:b.id,type:b.type,content:b.content};['checked','expanded','language','icon','src','alt','style'].forEach(k=>{if(b[k]!=null)c[k]=b[k];});return c;})})})
|
|
.then(r=>r.json()).then(()=>{this.saving=false;this.dirty=false;this.lastSaved=new Date().toLocaleTimeString();}).catch(()=>{this.saving=false;});
|
|
},
|
|
|
|
md2b(md){const bl=[];let cb=null;for(const line of md.split('\n')){if(cb){if(line.trim()==='```'){bl.push(cb);cb=null;}else cb.content+=(cb.content?'\n':'')+line;continue;}const t=line.trim();if(!t)continue;if(t.startsWith('```')){cb=this.mkB('code','',{language:t.substring(3).trim()||'Plain Text'});continue;}if(t.startsWith('# ')&&!t.startsWith('## '))bl.push(this.mkB('heading_1',t.substring(2)));else if(t.startsWith('## ')&&!t.startsWith('### '))bl.push(this.mkB('heading_2',t.substring(3)));else if(t.startsWith('### '))bl.push(this.mkB('heading_3',t.substring(4)));else if(t==='---'||t==='***')bl.push(this.mkB('divider',''));else if(/^[-*+] /.test(t))bl.push(this.mkB('bulleted_list',t.substring(2)));else if(/^\d+\. /.test(t))bl.push(this.mkB('numbered_list',t.replace(/^\d+\. /,'')));else if(t.startsWith('- [ ] ')||t.startsWith('* [ ] '))bl.push(this.mkB('to_do',t.substring(6)));else if(t.startsWith('- [x] ')||t.startsWith('* [x] '))bl.push(this.mkB('to_do',t.substring(6),{checked:true}));else if(t.startsWith('> '))bl.push(this.mkB('quote',t.substring(2)));else bl.push(this.mkB('paragraph',t));}if(cb)bl.push(cb);return bl;},
|
|
};
|
|
return self;
|
|
}
|
|
|
|
// ── Global: selection → toolbar ──
|
|
document.addEventListener('mouseup',()=>{setTimeout(()=>{const s=window.getSelection();if(!s||s.isCollapsed)return;const ed=document.querySelector('.page-editor-wrapper');if(!ed?.__x)return;const d=ed.__x.$data;const ct=document.getElementById('_blocksCt');if(!ct?.contains(s.anchorNode))return;const bel=s.anchorNode.parentElement?.closest('[data-bid]');if(bel){const idx=d.getIdx(bel.dataset.bid);if(idx>=0)d.showFmt(idx);}},80);});
|
|
</script>
|
|
{% endblock %}
|