-
Notifications
You must be signed in to change notification settings - Fork 48
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: allow taps for looking up words
Fixes #845.
- Loading branch information
Showing
2 changed files
with
69 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
type IsTapCallback = (isTap: boolean) => void; | ||
|
||
type TapState = | ||
| { kind: 'idle' } | ||
| { | ||
kind: 'mousedown'; | ||
timeout: ReturnType<typeof setTimeout>; | ||
cb?: IsTapCallback; | ||
} | ||
| { kind: 'longpress' }; | ||
|
||
// A little utility function to track mouseup/down events so we can distinguish | ||
// between a tap and long-press. | ||
// | ||
// The caller notifies on each mouseDown / mouseUp event. | ||
// | ||
// Along with each call to `mouseDown`, the caller may pass a callback that | ||
// will be called once with a flag indicating if the mousedown resulted in a | ||
// tap (true) or a long-press (false). | ||
export class TapTracker { | ||
private tapState: TapState = { kind: 'idle' }; | ||
|
||
mouseDown(cb?: (isTap: boolean) => void) { | ||
// This shouldn't happen, but if it does, make sure we clean up. | ||
if (this.tapState.kind === 'mousedown') { | ||
clearTimeout(this.tapState.timeout); | ||
this.tapState.cb?.(true); | ||
} | ||
|
||
const timeout = setTimeout(() => { | ||
this.tapState = { kind: 'longpress' }; | ||
cb?.(false); | ||
}, 100); | ||
|
||
this.tapState = { kind: 'mousedown', timeout, cb }; | ||
} | ||
|
||
mouseUp() { | ||
if (this.tapState.kind === 'mousedown') { | ||
clearTimeout(this.tapState.timeout); | ||
this.tapState.cb?.(true); | ||
} | ||
this.tapState = { kind: 'idle' }; | ||
} | ||
} |