Skip to content

Commit

Permalink
add keypress helpers, refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
sroertgen committed Aug 31, 2023
1 parent 1daba36 commit 2bc9322
Show file tree
Hide file tree
Showing 3 changed files with 129 additions and 63 deletions.
8 changes: 7 additions & 1 deletion src/components/LabelFilter.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { css } from "@emotion/react"

function UnderlinedText(props) {
return <span style={{ textDecoration: "underline" }}>{props.children}</span>
}

const LabelFilter = ({ labels, toggleClick }) => {
const style = css`
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 2px 30px;
padding: 2px;
`
const handleClick = (e) => {
toggleClick(e)
Expand All @@ -16,7 +21,8 @@ const LabelFilter = ({ labels, toggleClick }) => {
checked={label[1]}
onChange={() => handleClick(label[0])}
/>
{label[0]}
<UnderlinedText>{label[0][0]}</UnderlinedText>
{label[0].slice(1)}
</label>
))

Expand Down
71 changes: 9 additions & 62 deletions src/templates/App.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React, { useEffect, useState } from "react"
import Document from "flexsearch/dist/module/document.js"
import escapeRegExp from "lodash.escaperegexp"
import { i18n, getFilePath } from "../common"
import NestedList from "../components/nestedList"
Expand All @@ -12,6 +11,7 @@ import { conceptStyle } from "../styles/concepts.css.js"
import { getConfigAndConceptSchemes } from "../hooks/configAndConceptSchemes"
import { useSkoHubContext } from "../context/Context.jsx"
import { withPrefix } from "gatsby"
import { handleKeypresses, importIndex } from "./helpers"

const App = ({ pageContext, children }) => {
const { data } = useSkoHubContext()
Expand All @@ -36,6 +36,8 @@ const App = ({ pageContext, children }) => {
)
)

handleKeypresses(labels, setLabels)

if (!showTreeControls && tree && tree.hasTopConcept) {
for (const topConcept of tree.hasTopConcept) {
if (topConcept.narrower?.length > 0) {
Expand All @@ -45,64 +47,6 @@ const App = ({ pageContext, children }) => {
}
}

const importIndex = async () => {
/** FIXME the document options need to be imported from somewhere
* maybe store them in a separate file and create it in gatsby-node.js ?
* maybe along with all the necessary keys
**/
const idx = new Document({
tokenize: "full",
charset: "latin",
id: "id",
document: {
id: "id",
// store: ["prefLabel", "altLabel"], /* not working flexsearchside */
index: [
"notation",
"prefLabel",
"altLabel",
"hiddenLabel",
"definition",
"example",
],
},
})
// filter from labels object the selected entries
// and append the needed keys
// add reg, which is not specific to a key
const keys = Object.entries(labels)
.filter((label) => label[1] === true)
.flatMap((label) => [
`${label[0]}.cfg`,
`${label[0]}.ctx`,
`${label[0]}.map`,
`${label[0]}.store` /* might be useful later, when importing with stores works in flexsearch */,
`${label[0]}.tag`,
])
.concat(["reg"])
for (let i = 0, key; i < keys.length; i += 1) {
key = keys[i]
let data
try {
data = await fetch(
withPrefix(
getFilePath(
(conceptSchemeId.endsWith("/")
? conceptSchemeId.slice(0, -1)
: conceptSchemeId) + `/search/${pageContext.language}/${key}`,
`json`
)
)
)
const jsonData = await data.json()
idx.import(key, jsonData ?? null)
} catch (e) {
console.log(e) // eslint-disable-line no-console
}
}
setIndex(idx)
}

// get concept scheme id from context
useEffect(() => {
if (data?.currentScheme?.id) {
Expand All @@ -112,7 +56,8 @@ const App = ({ pageContext, children }) => {

// Fetch and load the serialized index
useEffect(() => {
conceptSchemeId && importIndex()
conceptSchemeId &&
importIndex(conceptSchemeId, labels, setIndex, pageContext.language)
}, [conceptSchemeId, pageContext.language, labels])

// Fetch and load the tree
Expand All @@ -137,6 +82,7 @@ const App = ({ pageContext, children }) => {
})

const toggleClick = (e) => setLabels({ ...labels, [e]: !labels[e] })

return (
<Layout languages={pageContext.languages} language={pageContext.language}>
<SEO
Expand All @@ -153,13 +99,14 @@ const App = ({ pageContext, children }) => {
<div className="Concept" css={style}>
<nav className="block nav-block">
<input
id="searchInput"
type="text"
className="inputStyle"
onChange={(e) => setQuery(e.target.value || null)}
placeholder="Search"
placeholder="Search (Ctrl-k)"
autoFocus
/>
{/* filter languages to search */}
{/* filter labels to search */}
<LabelFilter labels={labels} toggleClick={(e) => toggleClick(e)} />
{showTreeControls && <TreeControls />}
<div className="concepts">
Expand Down
113 changes: 113 additions & 0 deletions src/templates/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { useEffect } from "react"
import Document from "flexsearch/dist/module/document.js"
import { i18n, getFilePath } from "../common"
import { withPrefix } from "gatsby"

export const handleKeypresses = (labels, setLabels) => {
useEffect(() => {
function handleKeyDown(e) {
// ctrl + k
if (e.ctrlKey && e.which === 75) {
e.preventDefault()
// Get the reference to the input element
const inputElement = document.getElementById("searchInput")
// Set the focus on the input element
inputElement.focus()
// alt + p
} else if (e.altKey && e.which === 80) {
e.preventDefault()
Object.keys(labels).includes("prefLabel") &&
setLabels({ ...labels, ["prefLabel"]: !labels["prefLabel"] })
// alt + n
} else if (e.altKey && e.which === 78) {
e.preventDefault()
Object.keys(labels).includes("notation") &&
setLabels({ ...labels, ["notation"]: !labels["notation"] })
// alt + a
} else if (e.altKey && e.which === 65) {
e.preventDefault()
Object.keys(labels).includes("altLabel") &&
setLabels({ ...labels, ["altLabel"]: !labels["altLabel"] })
// alt + d
} else if (e.altKey && e.which === 68) {
e.preventDefault()
Object.keys(labels).includes("definition") &&
setLabels({ ...labels, ["definition"]: !labels["definition"] })
// alt + e
} else if (e.altKey && e.which === 69) {
e.preventDefault()
Object.keys(labels).includes("example") &&
setLabels({ ...labels, ["example"]: !labels["example"] })
// alt + h
} else if (e.altKey && e.which === 72) {
e.preventDefault()
Object.keys(labels).includes("hiddenLabel") &&
setLabels({ ...labels, ["hiddenLabel"]: !labels["hiddenLabel"] })
}
}
document.addEventListener("keydown", handleKeyDown)
// Don't forget to clean up
return function cleanup() {
document.removeEventListener("keydown", handleKeyDown)
}
})
}

export const importIndex = async (
conceptSchemeId,
labels,
setIndex,
language
) => {
const idx = new Document({
tokenize: "full",
charset: "latin",
id: "id",
document: {
id: "id",
// store: ["prefLabel", "altLabel"], /* not working flexsearchside */
index: [
"notation",
"prefLabel",
"altLabel",
"hiddenLabel",
"definition",
"example",
],
},
})
// filter from labels object the selected entries
// and append the needed keys
// add reg, which is not specific to a key
const keys = Object.entries(labels)
.filter((label) => label[1] === true)
.flatMap((label) => [
`${label[0]}.cfg`,
`${label[0]}.ctx`,
`${label[0]}.map`,
`${label[0]}.store` /* might be useful later, when importing with stores works in flexsearch */,
`${label[0]}.tag`,
])
.concat(["reg"])
for (let i = 0, key; i < keys.length; i += 1) {
key = keys[i]
let data
try {
data = await fetch(
withPrefix(
getFilePath(
(conceptSchemeId.endsWith("/")
? conceptSchemeId.slice(0, -1)
: conceptSchemeId) + `/search/${language}/${key}`,
`json`
)
)
)
const jsonData = await data.json()
idx.import(key, jsonData ?? null)
} catch (e) {
console.log(e) // eslint-disable-line no-console
}
}
setIndex(idx)
}

0 comments on commit 2bc9322

Please sign in to comment.