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,72 +97,58 @@ 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) {
const insert = prefix + suffix;
if(noSelection) {
return {
changes : {
from,
to,
insert : prefix + suffix
},
range : EditorSelection.cursor(from + prefix.length)
};
}
const before = doc.sliceString(
Math.max(0, from),
from + prefix.length
);
const after = doc.sliceString(
to - suffix.length,
to
);
const alreadyWrapped = before === prefix && after === suffix;
if(alreadyWrapped) {
return {
changes : [
{
from : from,
to : from + prefix.length,
insert : ''
},
{
from : to - suffix.length,
to : to,
insert : ''
}
],
range : EditorSelection.range(
from,
to - prefix.length - suffix.length,
)
};
}
return { return {
changes : { changes : { from, to, insert },
from, range : EditorSelection.cursor(from + prefix.length)
to,
insert : prefix + doc.sliceString(from, to) + suffix
},
range : EditorSelection.range(
from,
to + suffix.length + prefix.length
)
}; };
}) }
);
const hasWrapper =
selected.startsWith(prefix) &&
selected.endsWith(suffix);
if(hasWrapper) {
return {
changes : [
{
from : to - suffix.length,
to,
insert : ''
},
{
from,
to : from + prefix.length,
insert : ''
}
],
range : EditorSelection.range(from, to - prefix.length - suffix.length)
};
}
return {
changes : {
from,
to,
insert : prefix + selected + suffix
},
range : EditorSelection.range(
from,
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;