|
| 1 | +import { showAndLogErrorMessage } from "../helpers"; |
| 2 | +import { |
| 3 | + ExplorerSelectionCommandFunction, |
| 4 | + TreeViewContextMultiSelectionCommandFunction, |
| 5 | + TreeViewContextSingleSelectionCommandFunction, |
| 6 | +} from "./commands"; |
| 7 | + |
| 8 | +// A hack to match types that are not an array, which is useful to help avoid |
| 9 | +// misusing createSingleSelectionCommand, e.g. where T accidentally gets instantiated |
| 10 | +// as DatabaseItem[] instead of DatabaseItem. |
| 11 | +type NotArray = object & { length?: never }; |
| 12 | + |
| 13 | +// A way to get the type system to help assert that one type is a supertype of another. |
| 14 | +type CreateSupertypeOf<Super, Sub extends Super> = Sub; |
| 15 | + |
| 16 | +// This asserts that SelectionCommand is assignable to all of the different types of |
| 17 | +// SelectionCommand defined in commands.ts. The intention is the output from the helpers |
| 18 | +// in this file can be used with any of the select command types and cna handle any of |
| 19 | +// the inputs. |
| 20 | +type SelectionCommand<T extends NotArray> = CreateSupertypeOf< |
| 21 | + TreeViewContextMultiSelectionCommandFunction<T> & |
| 22 | + TreeViewContextSingleSelectionCommandFunction<T> & |
| 23 | + ExplorerSelectionCommandFunction<T>, |
| 24 | + (singleItem: T, multiSelect?: T[] | undefined) => Promise<void> |
| 25 | +>; |
| 26 | + |
| 27 | +export function createSingleSelectionCommand<T extends NotArray>( |
| 28 | + f: (argument: T) => Promise<void>, |
| 29 | + itemName: string, |
| 30 | +): SelectionCommand<T> { |
| 31 | + return async (singleItem, multiSelect) => { |
| 32 | + if (multiSelect === undefined || multiSelect.length === 1) { |
| 33 | + return f(singleItem); |
| 34 | + } else { |
| 35 | + void showAndLogErrorMessage(`Please select a single ${itemName}.`); |
| 36 | + return; |
| 37 | + } |
| 38 | + }; |
| 39 | +} |
| 40 | + |
| 41 | +export function createMultiSelectionCommand<T extends NotArray>( |
| 42 | + f: (argument: T[]) => Promise<void>, |
| 43 | +): SelectionCommand<T> { |
| 44 | + return async (singleItem, multiSelect) => { |
| 45 | + if (multiSelect !== undefined && multiSelect.length > 0) { |
| 46 | + return f(multiSelect); |
| 47 | + } else { |
| 48 | + return f([singleItem]); |
| 49 | + } |
| 50 | + }; |
| 51 | +} |
0 commit comments