| b69ab31 | | | 1 | /** |
| b69ab31 | | | 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| b69ab31 | | | 3 | * |
| b69ab31 | | | 4 | * This source code is licensed under the MIT license found in the |
| b69ab31 | | | 5 | * LICENSE file in the root directory of this source tree. |
| b69ab31 | | | 6 | */ |
| b69ab31 | | | 7 | |
| b69ab31 | | | 8 | import {useAtomValue} from 'jotai'; |
| b69ab31 | | | 9 | import {localStorageBackedAtom, readAtom, writeAtom} from '../jotaiUtils'; |
| b69ab31 | | | 10 | import type {ActionMenuItem} from './types'; |
| b69ab31 | | | 11 | |
| b69ab31 | | | 12 | /** |
| b69ab31 | | | 13 | * Used to keep track of smart actions by order of use. |
| b69ab31 | | | 14 | * Use {@link bumpSmartAction} to add/update an action to the cache. |
| b69ab31 | | | 15 | * Do not modify the cache directly. |
| b69ab31 | | | 16 | */ |
| b69ab31 | | | 17 | const smartActionsOrder = localStorageBackedAtom<Array<string>>('isl.smart-actions-order', []); |
| b69ab31 | | | 18 | |
| b69ab31 | | | 19 | /** |
| b69ab31 | | | 20 | * Given an array of smart actions, returns the same actions sorted by usage. |
| b69ab31 | | | 21 | */ |
| b69ab31 | | | 22 | export function useSortedActions(actions: Array<ActionMenuItem>) { |
| b69ab31 | | | 23 | const cache = useAtomValue(smartActionsOrder); |
| b69ab31 | | | 24 | return [...actions].sort((a, b) => { |
| b69ab31 | | | 25 | const aIndex = cache.indexOf(a.id) >= 0 ? cache.indexOf(a.id) : Infinity; |
| b69ab31 | | | 26 | const bIndex = cache.indexOf(b.id) >= 0 ? cache.indexOf(b.id) : Infinity; |
| b69ab31 | | | 27 | return aIndex - bIndex; |
| b69ab31 | | | 28 | }); |
| b69ab31 | | | 29 | } |
| b69ab31 | | | 30 | |
| b69ab31 | | | 31 | /** |
| b69ab31 | | | 32 | * Marks an action as used, updating the cache. |
| b69ab31 | | | 33 | */ |
| b69ab31 | | | 34 | export function bumpSmartAction(action: string) { |
| b69ab31 | | | 35 | const cache = readAtom(smartActionsOrder); |
| b69ab31 | | | 36 | const index = cache.indexOf(action); |
| b69ab31 | | | 37 | let newCache = [...cache]; |
| b69ab31 | | | 38 | // Remove the action if it's already in the cache |
| b69ab31 | | | 39 | if (index !== -1) { |
| b69ab31 | | | 40 | newCache.splice(index, 1); |
| b69ab31 | | | 41 | } |
| b69ab31 | | | 42 | // For now, use LRU ordering |
| b69ab31 | | | 43 | // TODO: Consider using frecency ordering |
| b69ab31 | | | 44 | newCache = [action, ...newCache]; |
| b69ab31 | | | 45 | writeAtom(smartActionsOrder, newCache); |
| b69ab31 | | | 46 | } |