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