Skip to content

Commit

Permalink
polish keyboard events, especially shake for TermsComponent
Browse files Browse the repository at this point in the history
  • Loading branch information
s12chung committed Nov 23, 2023
1 parent 83c48b3 commit d1ab08d
Showing 1 changed file with 25 additions and 22 deletions.
47 changes: 25 additions & 22 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,26 +17,29 @@ export function useChangeTermWithKeyboard(
const pagesLen = useMemo<number>(() => totalPages(terms, maxPageSize), [terms])
const [shake, setShake] = useTimedState(100)

const changeTermFocusIndex = (
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)))
}
const changePage = (e: KeyboardEvent, change: (index: number, length: number) => number) => {
if (pagesLen === 1) {
setShake(true)
e.preventDefault()
return
}
setPageIndex(change(pageIndex, pagesLen))
setTermFocusIndex(0)
}
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)

Expand Down Expand Up @@ -70,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

0 comments on commit d1ab08d

Please sign in to comment.