addons/isl/src/smartActions/smartActionsOrdering.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318import {useAtomValue} from 'jotai';
b69ab319import {localStorageBackedAtom, readAtom, writeAtom} from '../jotaiUtils';
b69ab3110import type {ActionMenuItem} from './types';
b69ab3111
b69ab3112/**
b69ab3113 * Used to keep track of smart actions by order of use.
b69ab3114 * Use {@link bumpSmartAction} to add/update an action to the cache.
b69ab3115 * Do not modify the cache directly.
b69ab3116 */
b69ab3117const smartActionsOrder = localStorageBackedAtom<Array<string>>('isl.smart-actions-order', []);
b69ab3118
b69ab3119/**
b69ab3120 * Given an array of smart actions, returns the same actions sorted by usage.
b69ab3121 */
b69ab3122export function useSortedActions(actions: Array<ActionMenuItem>) {
b69ab3123 const cache = useAtomValue(smartActionsOrder);
b69ab3124 return [...actions].sort((a, b) => {
b69ab3125 const aIndex = cache.indexOf(a.id) >= 0 ? cache.indexOf(a.id) : Infinity;
b69ab3126 const bIndex = cache.indexOf(b.id) >= 0 ? cache.indexOf(b.id) : Infinity;
b69ab3127 return aIndex - bIndex;
b69ab3128 });
b69ab3129}
b69ab3130
b69ab3131/**
b69ab3132 * Marks an action as used, updating the cache.
b69ab3133 */
b69ab3134export function bumpSmartAction(action: string) {
b69ab3135 const cache = readAtom(smartActionsOrder);
b69ab3136 const index = cache.indexOf(action);
b69ab3137 let newCache = [...cache];
b69ab3138 // Remove the action if it's already in the cache
b69ab3139 if (index !== -1) {
b69ab3140 newCache.splice(index, 1);
b69ab3141 }
b69ab3142 // For now, use LRU ordering
b69ab3143 // TODO: Consider using frecency ordering
b69ab3144 newCache = [action, ...newCache];
b69ab3145 writeAtom(smartActionsOrder, newCache);
b69ab3146}