Merge pull request #324 from Chrissi2812/search

add text search and replace
This commit is contained in:
Philipp Kühn
2019-06-04 21:15:15 +02:00
committed by GitHub
7 changed files with 478 additions and 1 deletions

View File

@@ -0,0 +1,264 @@
<template>
<div class="editor">
<editor-menu-bar :editor="editor" v-slot="{ commands, isActive }">
<div class="menubar">
<button
class="menubar__button"
:class="{ 'is-active': isActive.bold() }"
@click="commands.bold"
>
<icon name="bold" />
</button>
<button
class="menubar__button"
:class="{ 'is-active': isActive.italic() }"
@click="commands.italic"
>
<icon name="italic" />
</button>
<button
class="menubar__button"
:class="{ 'is-active': isActive.strike() }"
@click="commands.strike"
>
<icon name="strike" />
</button>
<button
class="menubar__button"
:class="{ 'is-active': isActive.underline() }"
@click="commands.underline"
>
<icon name="underline" />
</button>
<button
class="menubar__button"
:class="{ 'is-active': isActive.code() }"
@click="commands.code"
>
<icon name="code" />
</button>
<button
class="menubar__button"
:class="{ 'is-active': isActive.paragraph() }"
@click="commands.paragraph"
>
<icon name="paragraph" />
</button>
<button
class="menubar__button"
:class="{ 'is-active': isActive.heading({ level: 1 }) }"
@click="commands.heading({ level: 1 })"
>
H1
</button>
<button
class="menubar__button"
:class="{ 'is-active': isActive.bullet_list() }"
@click="commands.bullet_list"
>
<icon name="ul" />
</button>
<button
class="menubar__button"
:class="{ 'is-active': isActive.ordered_list() }"
@click="commands.ordered_list"
>
<icon name="ol" />
</button>
<button
class="menubar__button"
:class="{ 'is-active': isActive.blockquote() }"
@click="commands.blockquote"
>
<icon name="quote" />
</button>
<button
class="menubar__button"
:class="{ 'is-active': isActive.code_block() }"
@click="commands.code_block"
>
<icon name="code" />
</button>
<button
class="menubar__button"
@click="commands.undo"
>
<icon name="undo" />
</button>
<button
class="menubar__button"
@click="commands.redo"
>
<icon name="redo" />
</button>
<span
class="menubar__button"
@click="editor.commands.toggleSearch"
>
Search
<div
class="search-modal"
@click.stop
v-if="editor.extensions.options.search.searching"
>
<input
ref="search"
@keydown.enter.prevent="editor.commands.find(searchTerm)"
placeholder="Search..."
type="text"
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.clearSearch()">Clear</button>
<button @click="editor.commands.replace(replaceWith)">Replace</button>
<button @click="editor.commands.replaceAll(replaceWith)">Replace All</button>
</div>
</span>
</div>
</editor-menu-bar>
<editor-content class="editor__content" :editor="editor" />
</div>
</template>
<script>
import Icon from 'Components/Icon'
import { Editor, EditorContent, EditorMenuBar } from 'tiptap'
import {
Blockquote,
CodeBlock,
HardBreak,
Heading,
HorizontalRule,
OrderedList,
BulletList,
ListItem,
TodoItem,
TodoList,
Bold,
Code,
Italic,
Link,
Strike,
Underline,
History,
Search,
} from 'tiptap-extensions'
export default {
components: {
EditorContent,
EditorMenuBar,
Icon,
},
data() {
return {
searching: false,
searchTerm: null,
replaceWith: null,
editor: new Editor({
extensions: [
new Blockquote(),
new BulletList(),
new CodeBlock(),
new HardBreak(),
new Heading({ levels: [1, 2, 3] }),
new HorizontalRule(),
new Search({
disableRegex: false,
}),
new ListItem(),
new OrderedList(),
new TodoItem(),
new TodoList(),
new Link(),
new Bold(),
new Code(),
new Italic(),
new Strike(),
new Underline(),
new History(),
],
onUpdate: ({ getJSON }) => {
this.json = getJSON()
},
onToggleSearch: searching => {
this.$nextTick(() => {
if (searching) {
this.$refs.search.focus()
}
})
},
content: `
<h2>
Hi there,
</h2>
<p>
this is a very <em>basic</em> example of tiptap.
</p>
<pre><code>body { display: none; }</code></pre>
<ul>
<li>
A regular list
</li>
<li>
With regular items
</li>
</ul>
<blockquote>
It's amazing 👏
<br />
mom
</blockquote>
`,
}),
}
},
beforeDestroy() {
this.editor.destroy()
},
}
</script>
<style>
.menubar__button {
position: relative;
}
.search-modal {
position: absolute;
top: 100%;
display: flex;
background: #fff;
padding: .5em;
box-shadow: 0 2px 4px #0003;
border-radius: 2px;
left: 0;
margin-top: 0.25em;
border: solid 2px;
}
.find {
background: rgba(255, 213, 0, 0.5);
}
</style>

View File

@@ -24,6 +24,9 @@
<router-link class="subnavigation__link" to="/tables">
Tables
</router-link>
<router-link class="subnavigation__link" to="/search">
Search
</router-link>
<router-link class="subnavigation__link" to="/suggestions">
Suggestions
</router-link>

View File

@@ -33,4 +33,8 @@
background-color: rgba($color-black, 0.1);
}
}
span#{&}__button {
font-size: 13.3333px;
}
}

View File

@@ -68,6 +68,13 @@ const routes = [
githubUrl: 'https://github.com/scrumpy/tiptap/tree/master/examples/Components/Routes/TodoList',
},
},
{
path: '/search',
component: () => import('Components/Routes/Search'),
meta: {
githubUrl: 'https://github.com/scrumpy/tiptap/tree/master/examples/Components/Routes/Search',
},
},
{
path: '/suggestions',
component: () => import('Components/Routes/Suggestions'),

View File

@@ -0,0 +1,198 @@
import { Extension, Plugin } from 'tiptap'
import { Decoration, DecorationSet } from 'prosemirror-view'
export default class Search extends Extension {
constructor(options = {}) {
super(options)
this.results = []
this.searchTerm = null
this._updating = false
}
get name() {
return 'search'
}
init() {
this.editor.events.push('toggleSearch')
}
get defaultOptions() {
return {
autoSelectNext: true,
findClass: 'find',
searching: false,
caseSensitive: false,
disableRegex: true,
alwaysSearch: false,
}
}
toggleSearch() {
return () => {
this.options.searching = !this.options.searching
this.editor.emit('toggleSearch', this.options.searching)
return true
}
}
keys() {
return {
'Mod-f': this.toggleSearch(),
}
}
commands() {
return {
find: attrs => this.find(attrs),
replace: attrs => this.replace(attrs),
replaceAll: attrs => this.replaceAll(attrs),
clearSearch: () => this.clear(),
toggleSearch: () => this.toggleSearch(),
}
}
get findRegExp() {
return RegExp(this.searchTerm, !this.options.caseSensitive ? 'gui' : 'gu')
}
get decorations() {
return this.results.map(deco => (
Decoration.inline(deco.from, deco.to, { class: this.options.findClass })
))
}
_search(doc) {
this.results = []
const mergedTextNodes = []
let index = 0
if (!this.searchTerm) {
return
}
doc.descendants((node, pos) => {
if (node.isText) {
if (mergedTextNodes[index]) {
mergedTextNodes[index] = {
text: mergedTextNodes[index].text + node.text,
pos: mergedTextNodes[index].pos,
}
} else {
mergedTextNodes[index] = {
text: node.text,
pos,
}
}
} else {
index += 1
}
})
mergedTextNodes.forEach(({ text, pos }) => {
const search = this.findRegExp
let m
// eslint-disable-next-line no-cond-assign
while ((m = search.exec(text))) {
if (m[0] === '') {
break
}
this.results.push({
from: pos + m.index,
to: pos + m.index + m[0].length,
})
}
})
}
replace(replace) {
return (state, dispatch) => {
const { from, to } = this.results[0]
dispatch(state.tr.insertText(replace, from, to))
}
}
rebaseNextResult(replace, index, lastOffset = 0) {
const nextIndex = index + 1
if (!this.results[nextIndex]) return null
const { from: currentFrom, to: currentTo } = this.results[index]
const offset = (currentTo - currentFrom - replace.length) + lastOffset
const { from, to } = this.results[nextIndex]
this.results[nextIndex] = {
to: to - offset,
from: from - offset,
}
return offset
}
replaceAll(replace) {
return ({ tr }, dispatch) => {
let offset
this.results.forEach(({ from, to }, index) => {
tr.insertText(replace, from, to)
offset = this.rebaseNextResult(replace, index, offset)
})
dispatch(tr)
}
}
find(searchTerm) {
return (state, dispatch) => {
this.searchTerm = (this.options.disableRegex) ? searchTerm.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&') : searchTerm
this.updateView(state, dispatch)
}
}
clear() {
return (state, dispatch) => {
this.searchTerm = null
this.updateView(state, dispatch)
}
}
updateView({ tr }, dispatch) {
this._updating = true
dispatch(tr)
this._updating = false
}
createDeco(doc) {
this._search(doc)
return this.decorations ? DecorationSet.create(doc, this.decorations) : []
}
get plugins() {
return [
new Plugin({
state: {
init() { return DecorationSet.empty },
apply: (tr, old) => {
if (this._updating
|| this.options.searching
|| (tr.docChanged && this.options.alwaysSearch)) {
return this.createDeco(tr.doc)
}
if (tr.docChanged) {
return old.map(tr.mapping, tr.doc)
}
return old
},
},
props: {
decorations(state) { return this.getState(state) },
},
}),
]
}
}

View File

@@ -26,6 +26,7 @@ export { default as Underline } from './marks/Underline'
export { default as Collaboration } from './extensions/Collaboration'
export { default as History } from './extensions/History'
export { default as Placeholder } from './extensions/Placeholder'
export { default as Search } from './extensions/Search'
export { default as Suggestions } from './plugins/Suggestions'
export { default as Highlight } from './plugins/Highlight'

View File

@@ -84,7 +84,7 @@ export default class Editor extends Emitter {
}
this.events.forEach(name => {
this.on(name, this.options[camelCase(`on ${name}`)])
this.on(name, this.options[camelCase(`on ${name}`)] || (() => {}))
})
this.emit('init', {