40 lines
2.0 KiB
JavaScript
40 lines
2.0 KiB
JavaScript
|
|
/* Safe, deterministic editor operations. Exported for Node regression tests. */
|
||
|
|
(function (root, factory) {
|
||
|
|
const api=factory();
|
||
|
|
if(typeof module==='object' && module.exports)module.exports=api;
|
||
|
|
root.SiteForgeEditorHelpers=api;
|
||
|
|
})(typeof window!=='undefined'?window:globalThis, function(){
|
||
|
|
'use strict';
|
||
|
|
const deepCopy=value=>JSON.parse(JSON.stringify(value));
|
||
|
|
function reorder(items, from, to){
|
||
|
|
if(!Array.isArray(items)||!Number.isInteger(from)||!Number.isInteger(to)||from<0||to<0||from>=items.length||to>=items.length)return null;
|
||
|
|
if(from===to)return items.slice();
|
||
|
|
const next=items.slice();next.splice(to,0,next.splice(from,1)[0]);return next;
|
||
|
|
}
|
||
|
|
function duplicate(block, idFactory){
|
||
|
|
if(!block || typeof idFactory!=='function')throw Error('无效的区块');
|
||
|
|
const item=deepCopy(block);
|
||
|
|
const rewrite=node=>{
|
||
|
|
node.id=idFactory();
|
||
|
|
if(node.type==='layout')for(const col of node.columns||[])for(const child of col.blocks||[])rewrite(child);
|
||
|
|
};
|
||
|
|
rewrite(item);return item;
|
||
|
|
}
|
||
|
|
function filterBlocks(blocks, term, names={}){
|
||
|
|
const query=String(term||'').trim().toLocaleLowerCase();
|
||
|
|
if(!query)return blocks.map((block,index)=>({block,index}));
|
||
|
|
return blocks.flatMap((block,index)=>{
|
||
|
|
const description=[block.title,block.subtitle,block.type,names[block.type]?.name]
|
||
|
|
.concat(block.type==='layout'?(block.columns||[]).flatMap(c=>(c.blocks||[]).map(b=>b.title||b.type)):[])
|
||
|
|
.filter(x=>typeof x==='string').join(' ').toLocaleLowerCase();
|
||
|
|
return description.includes(query)?[{block,index}]:[];
|
||
|
|
});
|
||
|
|
}
|
||
|
|
function historyState(snapshots,cursor){return {canUndo:cursor>0,canRedo:cursor>=0&&cursor<snapshots.length-1};}
|
||
|
|
function clampNumber(value,min,max,fallback){const n=Number(value);return Number.isFinite(n)?Math.max(min,Math.min(max,n)):fallback;}
|
||
|
|
function shouldAcceptPreview(requestedPage,requestedSeq,currentPage,currentSeq){
|
||
|
|
return requestedPage===currentPage&&requestedSeq===currentSeq;
|
||
|
|
}
|
||
|
|
return {reorder,duplicate,filterBlocks,historyState,clampNumber,shouldAcceptPreview};
|
||
|
|
});
|