Skip to content

Commit

Permalink
refactor: select without prefix and suffix
Browse files Browse the repository at this point in the history
  • Loading branch information
pd4d10 committed Oct 4, 2023
1 parent 7e79ac6 commit d65a86f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 27 deletions.
16 changes: 8 additions & 8 deletions packages/bytemd/src/__snapshots__/editor.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ exports[`wrap text > find word 1`] = `
"main": 0,
"ranges": [
{
"anchor": 0,
"head": 11,
"anchor": 1,
"head": 5,
},
],
},
Expand Down Expand Up @@ -107,8 +107,8 @@ exports[`wrap text > no word 1`] = `
"main": 0,
"ranges": [
{
"anchor": 0,
"head": 7,
"anchor": 1,
"head": 1,
},
],
},
Expand Down Expand Up @@ -137,8 +137,8 @@ exports[`wrap text > with same prefix and suffix 1`] = `
"main": 0,
"ranges": [
{
"anchor": 0,
"head": 6,
"anchor": 1,
"head": 5,
},
],
},
Expand Down Expand Up @@ -167,8 +167,8 @@ exports[`wrap text > with selection 1`] = `
"main": 0,
"ranges": [
{
"anchor": 1,
"head": 10,
"anchor": 2,
"head": 4,
},
],
},
Expand Down
46 changes: 27 additions & 19 deletions packages/bytemd/src/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,39 @@ import selectFiles from 'select-files'
*
* `text -> *text*`
*/
export function wrapText(editor: EditorView, before: string, after = before) {
const range =
export function wrapText(editor: EditorView, prefix: string, suffix = prefix) {
const selection =
editor.state.selection.ranges.find((r) => !r.empty) ?? // find the first selection
editor.state.wordAt(editor.state.selection.main.head) ?? // if not, try to find the word
editor.state.selection.main

const { from, to } = range
const { from, to } = selection
const text = editor.state.sliceDoc(from, to) // use from/to instead of anchor/head for reverse select

const shouldUnwrap = text.startsWith(before) && text.endsWith(after)
editor.dispatch({
changes: {
from,
to,
insert: shouldUnwrap
? text.slice(before.length, -after.length)
: before + text + after,
},
selection: {
anchor: from,
head: shouldUnwrap
? to - before.length - after.length
: to + before.length + after.length,
},
})
const shouldUnwrap =
editor.state.sliceDoc(from - prefix.length, from) === prefix &&
editor.state.sliceDoc(to, to + suffix.length) === suffix
if (shouldUnwrap) {
editor.dispatch({
changes: {
from: from - prefix.length,
to: to + suffix.length,
insert: text,
},
selection: {
anchor: from - prefix.length,
head: to - prefix.length,
},
})
} else {
editor.dispatch({
changes: { from, to, insert: prefix + text + suffix },
selection: {
anchor: from + prefix.length,
head: to + prefix.length,
},
})
}
editor.focus()
}

Expand Down

0 comments on commit d65a86f

Please sign in to comment.