|
| 1 | +const actions = ['up', 'down', 'left', 'right', 'space', 'enter', 'cancel'] as const; |
| 2 | +export type Action = (typeof actions)[number]; |
| 3 | + |
| 4 | +/** Global settings for Clack programs, stored in memory */ |
| 5 | +interface InternalClackSettings { |
| 6 | + actions: Set<Action>; |
| 7 | + aliases: Map<string, Action>; |
| 8 | +} |
| 9 | + |
| 10 | +export const settings: InternalClackSettings = { |
| 11 | + actions: new Set(actions), |
| 12 | + aliases: new Map<string, Action>([ |
| 13 | + // vim support |
| 14 | + ['k', 'up'], |
| 15 | + ['j', 'down'], |
| 16 | + ['h', 'left'], |
| 17 | + ['l', 'right'], |
| 18 | + ['\x03', 'cancel'], |
| 19 | + // opinionated defaults! |
| 20 | + ['escape', 'cancel'], |
| 21 | + ]), |
| 22 | +}; |
| 23 | + |
| 24 | +export interface ClackSettings { |
| 25 | + /** |
| 26 | + * Set custom global aliases for the default actions. |
| 27 | + * This will not overwrite existing aliases, it will only add new ones! |
| 28 | + * |
| 29 | + * @param aliases - An object that maps aliases to actions |
| 30 | + * @default { k: 'up', j: 'down', h: 'left', l: 'right', '\x03': 'cancel', 'escape': 'cancel' } |
| 31 | + */ |
| 32 | + aliases: Record<string, Action>; |
| 33 | +} |
| 34 | + |
| 35 | +export function updateSettings(updates: ClackSettings) { |
| 36 | + for (const _key in updates) { |
| 37 | + const key = _key as keyof ClackSettings; |
| 38 | + if (!Object.hasOwn(updates, key)) continue; |
| 39 | + const value = updates[key]; |
| 40 | + |
| 41 | + switch (key) { |
| 42 | + case 'aliases': { |
| 43 | + for (const alias in value) { |
| 44 | + if (!Object.hasOwn(value, alias)) continue; |
| 45 | + if (!settings.aliases.has(alias)) { |
| 46 | + settings.aliases.set(alias, value[alias]); |
| 47 | + } |
| 48 | + } |
| 49 | + break; |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * Check if a key is an alias for a default action |
| 57 | + * @param key - The raw key which might match to an action |
| 58 | + * @param action - The action to match |
| 59 | + * @returns boolean |
| 60 | + */ |
| 61 | +export function isActionKey(key: string | Array<string | undefined>, action: Action) { |
| 62 | + if (typeof key === 'string') { |
| 63 | + return settings.aliases.get(key) === action; |
| 64 | + } |
| 65 | + |
| 66 | + for (const value of key) { |
| 67 | + if (value === undefined) continue; |
| 68 | + if (isActionKey(value, action)) { |
| 69 | + return true; |
| 70 | + } |
| 71 | + } |
| 72 | + return false; |
| 73 | +} |
0 commit comments