Skip to content
Snippets Groups Projects
Commit f932b07b authored by chris's avatar chris
Browse files

use debounce to delay search

parent ea6a55f0
No related branches found
No related tags found
1 merge request!190Find and replace
/* eslint react/prop-types: 0 */ /* eslint react/prop-types: 0 */
import React, { useState, useRef, useContext } from 'react'; import React, {
import { Decoration, DecorationSet } from 'prosemirror-view'; useState,
useRef,
useContext,
useCallback,
useEffect,
} from 'react';
import { debounce } from 'lodash';
import styled from 'styled-components'; import styled from 'styled-components';
import { grid, th } from '@pubsweet/ui-toolkit'; import { grid, th } from '@pubsweet/ui-toolkit';
import { WaxContext } from 'wax-prosemirror-core'; import { WaxContext } from 'wax-prosemirror-core';
...@@ -78,13 +84,22 @@ const FindComponent = ({ close, expand }) => { ...@@ -78,13 +84,22 @@ const FindComponent = ({ close, expand }) => {
const searchRef = useRef(null); const searchRef = useRef(null);
const [searchValue, setsearchValue] = useState(''); const [searchValue, setsearchValue] = useState('');
const [counterText, setCounterText] = useState('0 of 0'); const [counterText, setCounterText] = useState('0 of 0');
const delayedSearch = useCallback(
debounce(() => searchDocument(), 300),
[searchValue],
);
const findAndReplacePlugin = app.PmPlugins.get('findAndReplacePlugin'); const findAndReplacePlugin = app.PmPlugins.get('findAndReplacePlugin');
const onChange = () => { const onChange = () => {
setsearchValue(searchRef.current.value); setsearchValue(searchRef.current.value);
searchDocument();
}; };
useEffect(() => {
delayedSearch();
}, [searchValue, delayedSearch]);
const searchDocument = () => { const searchDocument = () => {
setCounterText('0 of 0'); setCounterText('0 of 0');
const results = []; const results = [];
...@@ -110,7 +125,7 @@ const FindComponent = ({ close, expand }) => { ...@@ -110,7 +125,7 @@ const FindComponent = ({ close, expand }) => {
}); });
mergedTextNodes.forEach(({ text, pos }) => { mergedTextNodes.forEach(({ text, pos }) => {
const search = RegExp(searchRef.current.value, 'gui'); const search = RegExp(searchValue, 'gui');
let m; let m;
// eslint-disable-next-line no-cond-assign // eslint-disable-next-line no-cond-assign
while ((m = search.exec(text))) { while ((m = search.exec(text))) {
...@@ -128,9 +143,9 @@ const FindComponent = ({ close, expand }) => { ...@@ -128,9 +143,9 @@ const FindComponent = ({ close, expand }) => {
if (results.length > 0) { if (results.length > 0) {
setCounterText(`1 of ${results.length}`); setCounterText(`1 of ${results.length}`);
tr.setMeta('search', true);
main.dispatch(tr);
} }
tr.setMeta('search', true);
main.dispatch(tr);
}; };
const closeFind = () => { const closeFind = () => {
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment