Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dict search UI #80

Merged
merged 4 commits into from
Nov 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 80 additions & 35 deletions ui/src/components/sources/SourceShow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ import NoteCreate from "../notes/NoteCreate.tsx"
import { StopKeyboardContext, useStopKeyboard } from "./SourceShow_SourceComponent.ts"
import { getUsage, useFocusTextWithKeyboard } from "./SourceShow_SourceNavComponent.ts"
import { otherTranslationTexts, useChangeTermWithKeyboard } from "./SourceShow_TermsComponent.ts"
import { useFocusTokenWithKeyboard } from "./SourceShow_TokensComponent.ts"
import { SelectedToken, useFocusTokenWithKeyboard } from "./SourceShow_TokensComponent.ts"
import {
PartCreateForm,
PartUpdateForm,
SourceDetailMenu,
SourceEditHeader,
SourcePartDetailMenu,
} from "./SourceShow_Update.tsx"
import React, { useContext, useEffect, useMemo, useRef, useState } from "react"
import React, { SyntheticEvent, useContext, useEffect, useMemo, useRef, useState } from "react"
import { useFetcher } from "react-router-dom"

export interface ISourceShowData {
Expand Down Expand Up @@ -249,24 +249,38 @@ const SourceNavComponent: React.FC<{ readonly source: Source; readonly safeSet:
[createNoteData, setStopKeyboardEvents],
)

const [selectedToken, setSelectedToken] = useState<Token | null>(null)
const [selectedToken, setSelectedToken] = useState<SelectedToken | null>(null)
const isTokenSelected = selectedToken !== null
const [partFocusIndex, textFocusIndex, focusElement, setText] = useFocusTextWithKeyboard(
const [partFocusIndex, textFocusIndex, setText] = useFocusTextWithKeyboard(
source.parts,
isTokenSelected,
() =>
setCreateNoteData(createNoteDataFromUsage(getUsage(source, partFocusIndex, textFocusIndex))),
() => setSelectedToken(null),
)
const setTextOnClick = (
e: SyntheticEvent<HTMLDivElement>,
textFocused: boolean,
partIndex: number,
textIndex: number,
// eslint-disable-next-line max-params
) => {
if (textFocused) return
e.preventDefault()
setText(partIndex, textIndex)
setCustomToken(null)
setSelectedToken(null)
}

const textRefs = useRef<(HTMLDivElement | null)[][]>([])
useEffect(() => {
const [customToken, setCustomToken] = useState<SelectedToken | null>(null)
const onCustomToken = (token: SelectedToken | null) => {
setCustomToken(token)
setSelectedToken(null)
const textElement = textRefs.current[partFocusIndex][textFocusIndex]
if (!textElement) return
focusElement(textElement)
scrollTo(textElement)
}, [focusElement, partFocusIndex, textFocusIndex])
}
const onTokenSearch = (token: SelectedToken) => {
setCustomToken(null)
setSelectedToken(token)
}

return (
<>
Expand All @@ -277,23 +291,16 @@ const SourceNavComponent: React.FC<{ readonly source: Source; readonly safeSet:
setCreateNoteData(null)
setSelectedToken(null)
}}
onClose={() => {
setCreateNoteData(null)
}}
onClose={() => setCreateNoteData(null)}
/>
)}
<SourcePartsWrapper sourceId={source.id} parts={source.parts} safeSet={safeSet}>
{(tokenizedText, partIndex, textIndex) => {
const textFocused = partIndex === partFocusIndex && textIndex === textFocusIndex
return (
<div
ref={(ref) => {
if (!textRefs.current[partIndex]) textRefs.current[partIndex] = []
textRefs.current[partIndex][textIndex] = ref
}}
tabIndex={-1}
className={joinClasses(textFocused ? "py-4 bg-gray-std" : "", "group py-2")}
onClick={preventDefault(() => setText(partIndex, textIndex))}
onClick={(e) => setTextOnClick(e, textFocused, partIndex, textIndex)}
>
<div className={joinClasses(textClassBase, textFocused ? "text-light" : "")}>
{tokenizedText.text}
Expand All @@ -302,8 +309,8 @@ const SourceNavComponent: React.FC<{ readonly source: Source; readonly safeSet:
<TokensComponent
tokens={tokenizedText.tokens}
isTokenSelected={isTokenSelected}
onTokenSelect={(tokenIndex) => setSelectedToken(tokenizedText.tokens[tokenIndex])}
onTokenChange={(tokenElement) => focusElement(tokenElement)}
onTokenSelect={setSelectedToken}
onCustomToken={onCustomToken}
/>
) : null}
<div className={textFocused ? "text-2xl" : translationClassBase}>
Expand All @@ -322,6 +329,9 @@ const SourceNavComponent: React.FC<{ readonly source: Source; readonly safeSet:
}}
/>
) : null}
{textFocused && customToken ? (
<SearchTokensComponent customToken={customToken} onTokenSearch={onTokenSearch} />
) : null}
</div>
)
}}
Expand All @@ -333,16 +343,21 @@ const SourceNavComponent: React.FC<{ readonly source: Source; readonly safeSet:
const TokensComponent: React.FC<{
readonly tokens: Token[]
readonly isTokenSelected: boolean
readonly onTokenSelect: (tokenFocusIndex: number) => void
readonly onTokenChange: (tokenElement: HTMLDivElement) => void
}> = ({ tokens, isTokenSelected, onTokenSelect, onTokenChange }) => {
const [tokenFocusIndex] = useFocusTokenWithKeyboard(tokens, isTokenSelected, onTokenSelect)
readonly onTokenSelect: (token: SelectedToken) => void
readonly onCustomToken: (token: SelectedToken | null) => void
}> = ({ tokens, isTokenSelected, onTokenSelect, onCustomToken }) => {
const [tokenFocusIndex] = useFocusTokenWithKeyboard(
tokens,
isTokenSelected,
onTokenSelect,
onCustomToken,
)

const tokenRefs = useRef<(HTMLDivElement | null)[]>([])
useEffect(() => {
const element = tokenRefs.current[tokenFocusIndex]
if (element) onTokenChange(element)
}, [onTokenChange, tokenFocusIndex])
if (element) scrollTo(element)
}, [tokenFocusIndex])

return (
<div className="ko-sans text-4xl justify-center mb-2 child:py-2 flex">
Expand Down Expand Up @@ -376,14 +391,46 @@ const TokensComponent: React.FC<{
)
}

const SearchTokensComponent: React.FC<{
readonly customToken: SelectedToken
readonly onTokenSearch: (token: SelectedToken) => void
}> = ({ customToken, onTokenSearch }) => {
useEffect(() => {
// keyboard trigger to show component adds a character, so timeout
const id = setTimeout(() => textRef.current?.focus(), 50)
return () => clearTimeout(id)
}, [])

const { setStopKeyboardEvents } = useContext(StopKeyboardContext)
useEffect(() => {
setStopKeyboardEvents(true)
return () => setStopKeyboardEvents(false)
}, [setStopKeyboardEvents])

const textRef = useRef<HTMLInputElement>(null)
return (
<form
className="mt-std space-x-basic"
onSubmit={preventDefault(() =>
onTokenSearch({ text: textRef.current?.value || "", partOfSpeech: "" }),
)}
>
<input ref={textRef} defaultValue={customToken.text} />
<button type="submit" className="btn-primary">
Submit
</button>
</form>
)
}

interface ITermsShowData {
terms: Term[]
}

const termsComponentClass = "grid-std text-left text-lg py-2 space-y-2"

const TermsComponent: React.FC<{
readonly token: Token
readonly token: SelectedToken
readonly onTermSelect: (term: Term) => void
}> = ({ token, onTermSelect }) => {
const fetcher = useFetcher<ITermsShowData>()
Expand All @@ -398,9 +445,6 @@ const TermsComponent: React.FC<{
onTermSelect,
)

const termRefs = useRef<(HTMLDivElement | null)[]>([])
useEffect(() => termRefs.current[termFocusIndex]?.focus(), [terms, pageIndex, termFocusIndex])

if (!fetcher.data) return <div className={termsComponentClass}>Loading...</div>
return (
<div className={termsComponentClass}>
Expand All @@ -411,9 +455,10 @@ const TermsComponent: React.FC<{
{paginate(terms, maxPageSize, pageIndex).map((term, index) => (
<div
key={term.id}
ref={(ref) => (termRefs.current[index] = ref)}
tabIndex={-1}
className={joinClasses(index === termFocusIndex ? "underline" : "", "py-1")}
className={joinClasses(
index === termFocusIndex ? "underline focus-ring" : "",
"py-1",
)}
>
<div className="text-xl">
<span className="font-bold">{term.text}</span>&nbsp;
Expand Down
34 changes: 5 additions & 29 deletions ui/src/components/sources/SourceShow_SourceNavComponent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,7 @@ export function useFocusTextWithKeyboard(
isTokenSelected: boolean,
onCreateTextNote: () => void,
onEscape: () => void,
): readonly [
number,
number,
(element: HTMLElement) => void,
(partFocusIndex: number, textFocusIndex: number) => void,
] {
const [focusElement, focusLastElement] = useFocusElement()
): readonly [number, number, (partFocusIndex: number, textFocusIndex: number) => void] {
const [partFocusIndex, textFocusIndex, decrementText, incrementText, setText] =
useChangeFocus(parts)

Expand All @@ -28,9 +22,9 @@ export function useFocusTextWithKeyboard(
switch (e.code) {
case "Escape":
if (!isTokenSelected) return
focusLastElement()
onEscape()
break
e.preventDefault()
return
default:
}

Expand All @@ -54,17 +48,9 @@ export function useFocusTextWithKeyboard(

e.preventDefault()
},
[
stopKeyboardEvents,
isTokenSelected,
focusLastElement,
onEscape,
decrementText,
incrementText,
onCreateTextNote,
],
[stopKeyboardEvents, isTokenSelected, onEscape, decrementText, incrementText, onCreateTextNote],
)
return [partFocusIndex, textFocusIndex, focusElement, setText] as const
return [partFocusIndex, textFocusIndex, setText] as const
}

export function getUsage(source: Source, partFocusIndex: number, textFocusIndex: number) {
Expand All @@ -78,16 +64,6 @@ export function getUsage(source: Source, partFocusIndex: number, textFocusIndex:
}
}

function useFocusElement(): readonly [(element: HTMLElement) => void, () => void] {
const [lastFocusedElement, setLastFocusedElement] = useState<HTMLElement | null>(null)
const focusElement = useCallback((element: HTMLElement) => {
setLastFocusedElement(element)
element.focus()
}, [])

return [focusElement, () => lastFocusedElement?.focus()] as const
}

function useChangeFocus(
parts: SourcePart[],
): readonly [
Expand Down
47 changes: 30 additions & 17 deletions ui/src/components/sources/SourceShow_TermsComponent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { pageSize, totalPages } from "../../utils/HtmlUtil.ts"
import { useKeyDownEffect, useTimedState } from "../../utils/JSXUtil.ts"
import { decrement, increment } from "../../utils/NumberUtil.ts"
import { StopKeyboardContext } from "./SourceShow_SourceComponent.ts"
import { useContext, useMemo, useState } from "react"
import { useCallback, useContext, useMemo, useState } from "react"

const maxPageSize = 5

Expand All @@ -17,39 +17,52 @@ export function useChangeTermWithKeyboard(
const pagesLen = useMemo<number>(() => totalPages(terms, maxPageSize), [terms])
const [shake, setShake] = useTimedState(100)

const { stopKeyboardEvents } = useContext(StopKeyboardContext)

useKeyDownEffect(
(e: KeyboardEvent) => {
if (stopKeyboardEvents) return
const changeTermFocusIndex = useCallback(
(e: KeyboardEvent, change: (index: number, length: number) => number) => {
if (terms.length === 1) {
setShake(true)
e.preventDefault()
return
}
setTermFocusIndex(change(termFocusIndex, pageSize(terms.length, maxPageSize, pageIndex)))
},
[pageIndex, setShake, termFocusIndex, terms.length],
)
const changePage = useCallback(
(e: KeyboardEvent, change: (index: number, length: number) => number) => {
if (pagesLen === 1) {
setShake(true)
e.preventDefault()
return
}
setPageIndex(change(pageIndex, pagesLen))
setTermFocusIndex(0)
},
[pageIndex, pagesLen, setShake],
)

const { stopKeyboardEvents } = useContext(StopKeyboardContext)

useKeyDownEffect(
(e: KeyboardEvent) => {
if (stopKeyboardEvents) return

switch (e.code) {
case "ArrowUp":
case "KeyW":
setTermFocusIndex(
decrement(termFocusIndex, pageSize(terms.length, maxPageSize, pageIndex)),
)
changeTermFocusIndex(e, decrement)
break
case "ArrowDown":
case "KeyS":
setTermFocusIndex(
increment(termFocusIndex, pageSize(terms.length, maxPageSize, pageIndex)),
)
changeTermFocusIndex(e, increment)
break
case "ArrowLeft":
case "KeyA":
setPageIndex(decrement(pageIndex, pagesLen))
setTermFocusIndex(0)
changePage(e, decrement)
break
case "ArrowRight":
case "KeyD":
setPageIndex(increment(pageIndex, pagesLen))
setTermFocusIndex(0)
changePage(e, increment)
break
case "Enter":
case "Space":
Expand All @@ -60,7 +73,7 @@ export function useChangeTermWithKeyboard(
}
e.preventDefault()
},
[stopKeyboardEvents, termFocusIndex, terms, pageIndex, pagesLen, onTermSelect, setShake],
[changePage, changeTermFocusIndex, onTermSelect, stopKeyboardEvents, termFocusIndex, terms],
)
return [termFocusIndex, pageIndex, pagesLen, maxPageSize, shake] as const
}
Expand Down
Loading