added replace and replaceAll commands

This commit is contained in:
Chrissi2812 2019-06-03 12:18:59 +02:00
parent 525619ad26
commit 2544e40f99
No known key found for this signature in database
GPG Key ID: B4B82C7E618271DA
2 changed files with 45 additions and 1 deletions

View File

@ -121,9 +121,16 @@
placeholder="Search..." placeholder="Search..."
type="text" type="text"
v-model="searchTerm" v-model="searchTerm"
><input
@keydown.enter.prevent="editor.commands.replace(replaceWith)"
placeholder="Replace..."
type="text"
v-model="replaceWith"
> >
<button @click="editor.commands.find(searchTerm)">Find</button> <button @click="editor.commands.find(searchTerm)">Find</button>
<button @click="editor.commands.clearSearch()">Clear</button> <button @click="editor.commands.clearSearch()">Clear</button>
<button @click="editor.commands.replace(replaceWith)">Replace</button>
<button @click="editor.commands.replaceAll(replaceWith)">Replace All</button>
</div> </div>
</span> </span>
@ -168,6 +175,7 @@ export default {
return { return {
searching: false, searching: false,
searchTerm: null, searchTerm: null,
replaceWith: null,
editor: new Editor({ editor: new Editor({
extensions: [ extensions: [
new Blockquote(), new Blockquote(),

View File

@ -47,6 +47,8 @@ export default class Search extends Extension {
commands() { commands() {
return { return {
find: attrs => this.find(attrs), find: attrs => this.find(attrs),
replace: attrs => this.replace(attrs),
replaceAll: attrs => this.replaceAll(attrs),
clearSearch: () => this.clear(), clearSearch: () => this.clear(),
toggleSearch: () => this.toggleSearch(), toggleSearch: () => this.toggleSearch(),
} }
@ -104,6 +106,40 @@ export default class Search extends Extension {
}) })
} }
replace(replace) {
return (state, dispatch) => {
const { from, to } = this.results[0]
dispatch(state.tr.insertText(replace, from, to))
}
}
rebaseNextResult(replace, index) {
const nextIndex = index + 1
if (!this.results[nextIndex]) return
const nextStep = this.results[nextIndex]
const { from, to } = nextStep
const offset = (to - from - replace.length) * nextIndex
this.results[nextIndex] = {
to: to - offset,
from: from - offset,
}
}
replaceAll(replace) {
return ({ tr }, dispatch) => {
this.results.forEach(({ from, to }, index) => {
tr.insertText(replace, from, to)
this.rebaseNextResult(replace, index)
})
dispatch(tr)
}
}
find(searchTerm) { find(searchTerm) {
return (state, dispatch) => { return (state, dispatch) => {
this.searchTerm = (this.options.disableRegex) ? searchTerm.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&') : searchTerm this.searchTerm = (this.options.disableRegex) ? searchTerm.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&') : searchTerm