Skip to content

Commit

Permalink
Add debounce to Ontology Multi-select
Browse files Browse the repository at this point in the history
  • Loading branch information
garrettjstevens committed Aug 2, 2023
1 parent 897b4e3 commit 094f8e4
Showing 1 changed file with 50 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
Tooltip,
Typography,
} from '@mui/material'
import { debounce } from '@mui/material/utils'
import highlightMatch from 'autosuggest-highlight/match'
import highlightParse from 'autosuggest-highlight/parse'
import { getParent } from 'mobx-state-tree'
Expand All @@ -19,6 +20,7 @@ import {
OntologyTerm,
isOntologyClass,
} from '../OntologyManager'
import { OntologyDBNode } from '../OntologyManager/OntologyStore/indexeddb-schema'

type TermValue = OntologyTerm

Expand Down Expand Up @@ -122,6 +124,45 @@ export function OntologyTermMultiSelect({
const [loading, setLoading] = React.useState(false)
const [errorMessage, setErrorMessage] = React.useState('')

const getOntologyTerms = React.useMemo(
() =>
debounce(
async (
request: { input: string; signal: AbortSignal },
callback: (results: OntologyDBNode[]) => void,
) => {
if (!ontology) {
return undefined
}
const { dataStore } = ontology
if (!dataStore) {
return undefined
}
const { input, signal } = request
try {
const matches: OntologyTerm[] = []
const tx = (await dataStore.db).transaction('nodes')
for await (const cursor of tx.objectStore('nodes')) {
if (signal.aborted) {
return
}
const node = cursor.value
if (
(node.lbl ?? '').toLowerCase().includes(input.toLowerCase())
) {
matches.push(node)
}
}
callback(matches)
} catch (error) {
setErrorMessage(String(error))
}
},
400,
),
[ontology],
)

React.useEffect(() => {
const aborter = new AbortController()
const { signal } = aborter
Expand All @@ -133,36 +174,22 @@ export function OntologyTermMultiSelect({

setLoading(true)

if (!ontology) {
return undefined
}
const { dataStore } = ontology
if (!dataStore) {
return undefined
}

;(async () => {
const matches: OntologyTerm[] = []
const tx = (await dataStore.db).transaction('nodes')
for await (const cursor of tx.objectStore('nodes')) {
if (signal.aborted) {
return
}
const node = cursor.value
if ((node.lbl ?? '').toLowerCase().includes(inputValue.toLowerCase())) {
matches.push(node)
}
void getOntologyTerms({ input: inputValue, signal }, (results) => {
let newOptions: readonly OntologyTerm[] = []
if (value.length) {
newOptions = value
}
if (results) {
newOptions = [...newOptions, ...results]
}
setOptions(matches)
setOptions(newOptions)
setLoading(false)
})().catch((error) => {
setErrorMessage(String(error))
})

return () => {
aborter.abort()
}
}, [value, inputValue, ontology])
}, [getOntologyTerms, inputValue, value])

if (!ontology) {
return null
Expand Down

0 comments on commit 094f8e4

Please sign in to comment.