|
| 1 | +type debounceOptions<'a> = { |
| 2 | + maxWait?: int, |
| 3 | + leading?: bool, |
| 4 | + trailing?: bool, |
| 5 | + equalityFn?: (. 'a, 'a) => bool, |
| 6 | +} |
| 7 | + |
| 8 | +type debouncedReturn<'a> = {@as("0") value: 'a} // TODO: add second position |
| 9 | + |
| 10 | +/** |
| 11 | +```rescript |
| 12 | +let debounced = useDebounce(someValue, 500) |
| 13 | +debounced.value->Js.log |
| 14 | +```` |
| 15 | +*/ |
| 16 | +@module("use-debounce") |
| 17 | +external useDebounce: ('a, int) => debouncedReturn<'a> = "useDebounce" |
| 18 | + |
| 19 | +@module("use-debounce") |
| 20 | +external useDebounceWithOptions: ('a, int, debounceOptions<'a>) => debouncedReturn<'a> = |
| 21 | + "useDebounce" |
| 22 | + |
| 23 | +type debounceCallbackOptions = { |
| 24 | + maxWait?: int, |
| 25 | + leading?: bool, |
| 26 | + trailing?: bool, |
| 27 | +} |
| 28 | + |
| 29 | +@module("use-debounce") |
| 30 | +external useDebouncedCallbackOriginal: ('a, int, ~options: debounceCallbackOptions=?) => 'a = |
| 31 | + "useDebouncedCallback" |
| 32 | + |
| 33 | +// FIXME: flush()'s type signature is `unit => ReturnType<callback>`, but couldn't find a way |
| 34 | +// to achieve it in ReScript so left the return type as unit. |
| 35 | +type methods = {cancel: unit => unit, isPending: unit => int, flush: unit => unit} |
| 36 | +%%private(external getMethods: 'a => methods = "%identity") |
| 37 | + |
| 38 | +/** |
| 39 | +```rescript |
| 40 | +let (debouncedCallback, _debouncedCallbackMethods) = useDebouncedCallback(e => { |
| 41 | + e->ReactEvent.Synthetic.preventDefault |
| 42 | +}, 500, ~options={maxWait: 500}) |
| 43 | +<input onClick={debouncedCallback} /> |
| 44 | +```` |
| 45 | +*/ |
| 46 | +let useDebouncedCallback = (callback, timeout, ~options) => { |
| 47 | + let deboucedCallback = useDebouncedCallbackOriginal(callback, timeout, ~options) |
| 48 | + (deboucedCallback, getMethods(deboucedCallback)) |
| 49 | +} |
| 50 | + |
| 51 | +type throttleCallbackOptions = { |
| 52 | + leading?: bool, |
| 53 | + trailing?: bool, |
| 54 | +} |
| 55 | + |
| 56 | +@module("use-debounce") |
| 57 | +external useThrottledCallbackOriginal: ('a, int, ~options: throttleCallbackOptions=?) => 'a = |
| 58 | + "useThrottledCallback" |
| 59 | + |
| 60 | +let useThrottledCallback = (callback, timeout, ~options) => { |
| 61 | + let throttledCallback = useThrottledCallbackOriginal(callback, timeout, ~options) |
| 62 | + (throttledCallback, getMethods(throttledCallback)) |
| 63 | +} |
0 commit comments