wrapselection to work with foreachselection

This commit is contained in:
Víctor Losada Hernández
2026-09-27 22:58:08 +02:00
parent 3ec85b6f52
commit 7b1c576eb7
@@ -97,53 +97,41 @@ const insertTab = (view)=>{
return true; return true;
}; };
const wrapSelection = (prefix, suffix)=>(view)=>{ const wrapSelection = (prefix, suffix)=>(view)=>forEachSelection(
view.dispatch( view,
view.state.changeByRange((range)=>{ (state, range)=>{
const { from, to } = range; const { from, to } = range;
const noSelection = from === to; const noSelection = from === to;
const selected = state.doc.sliceString(from, to);
const doc = view.state.doc;
if(noSelection) { if(noSelection) {
const insert = prefix + suffix;
return { return {
changes : { changes : { from, to, insert },
from,
to,
insert : prefix + suffix
},
range : EditorSelection.cursor(from + prefix.length) range : EditorSelection.cursor(from + prefix.length)
}; };
} }
const before = doc.sliceString( const hasWrapper =
Math.max(0, from), selected.startsWith(prefix) &&
from + prefix.length selected.endsWith(suffix);
);
const after = doc.sliceString( if(hasWrapper) {
to - suffix.length,
to
);
const alreadyWrapped = before === prefix && after === suffix;
if(alreadyWrapped) {
return { return {
changes : [ changes : [
{ {
from : from, from : to - suffix.length,
to : from + prefix.length, to,
insert : '' insert : ''
}, },
{ {
from : to - suffix.length, from,
to : to, to : from + prefix.length,
insert : '' insert : ''
} }
], ],
range : EditorSelection.range( range : EditorSelection.range(from, to - prefix.length - suffix.length)
from,
to - prefix.length - suffix.length,
)
}; };
} }
@@ -151,18 +139,16 @@ const wrapSelection = (prefix, suffix)=>(view)=>{
changes : { changes : {
from, from,
to, to,
insert : prefix + doc.sliceString(from, to) + suffix insert : prefix + selected + suffix
}, },
range : EditorSelection.range( range : EditorSelection.range(
from, from,
to + suffix.length + prefix.length to + prefix.length + suffix.length
) )
}; };
}) }
); );
return true;
};
const makeNbsp = (view)=>forEachSelection(view, (state, range)=>{ const makeNbsp = (view)=>forEachSelection(view, (state, range)=>{
const { from, to } = range; const { from, to } = range;