@tooee/commands 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/build-context.d.ts +5 -0
  2. package/dist/build-context.d.ts.map +1 -1
  3. package/dist/build-context.js +4 -3
  4. package/dist/build-context.js.map +1 -1
  5. package/dist/command-store-wrapper.d.ts.map +1 -1
  6. package/dist/command-store-wrapper.js.map +1 -1
  7. package/dist/command-store.d.ts.map +1 -1
  8. package/dist/command-store.js.map +1 -1
  9. package/dist/context.d.ts +20 -3
  10. package/dist/context.d.ts.map +1 -1
  11. package/dist/context.js +68 -34
  12. package/dist/context.js.map +1 -1
  13. package/dist/hooks/use-latest.d.ts.map +1 -1
  14. package/dist/hooks/use-latest.js.map +1 -1
  15. package/dist/hooks/use-lazy-ref.d.ts.map +1 -1
  16. package/dist/hooks/use-lazy-ref.js.map +1 -1
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/key-dispatch.d.ts.map +1 -1
  22. package/dist/key-dispatch.js.map +1 -1
  23. package/dist/match.d.ts.map +1 -1
  24. package/dist/match.js.map +1 -1
  25. package/dist/mode.d.ts.map +1 -1
  26. package/dist/mode.js.map +1 -1
  27. package/dist/parse.d.ts.map +1 -1
  28. package/dist/parse.js +17 -2
  29. package/dist/parse.js.map +1 -1
  30. package/dist/screen-focus.d.ts.map +1 -1
  31. package/dist/screen-focus.js.map +1 -1
  32. package/dist/sequence.d.ts.map +1 -1
  33. package/dist/sequence.js.map +1 -1
  34. package/dist/store.d.ts.map +1 -1
  35. package/dist/store.js.map +1 -1
  36. package/dist/types.d.ts +1 -0
  37. package/dist/types.d.ts.map +1 -1
  38. package/dist/use-actions.d.ts.map +1 -1
  39. package/dist/use-actions.js.map +1 -1
  40. package/dist/use-command.d.ts.map +1 -1
  41. package/dist/use-command.js.map +1 -1
  42. package/package.json +1 -1
  43. package/src/build-context.ts +12 -3
  44. package/src/command-store-wrapper.ts +14 -0
  45. package/src/command-store.ts +37 -0
  46. package/src/context.tsx +138 -36
  47. package/src/hooks/use-latest.ts +1 -0
  48. package/src/hooks/use-lazy-ref.ts +1 -0
  49. package/src/index.ts +18 -0
  50. package/src/key-dispatch.ts +35 -0
  51. package/src/match.ts +6 -0
  52. package/src/mode.tsx +5 -0
  53. package/src/parse.ts +36 -2
  54. package/src/screen-focus.tsx +2 -0
  55. package/src/sequence.ts +11 -0
  56. package/src/store.ts +7 -0
  57. package/src/types.ts +2 -0
  58. package/src/use-actions.ts +4 -0
  59. package/src/use-command.ts +3 -0
@@ -65,23 +65,30 @@ const collectCandidates = function collectCandidates(
65
65
 
66
66
  for (const command of commands?.values() ?? []) {
67
67
  const commandModes = command.modes ?? DEFAULT_MODES;
68
+
68
69
  if (!commandModes.includes(currentMode) || (command.when && !command.when(cmdCtx))) {
69
70
  continue;
70
71
  }
72
+
71
73
  const hotkey = config.keymap?.[command.id] ?? command.defaultHotkey;
74
+
72
75
  if (hotkey === undefined || hotkey === "") {
73
76
  continue;
74
77
  }
78
+
75
79
  const parsed = getParsedHotkey(hotkey);
80
+
76
81
  if (parsed.steps.length === 0) {
77
82
  continue;
78
83
  }
84
+
79
85
  if (parsed.steps.length === 1) {
80
86
  singleStep.push({ command, parsed });
81
87
  } else {
82
88
  multiStep.push({ command, hotkey, parsed });
83
89
  }
84
90
  }
91
+
85
92
  return { multiStep, singleStep };
86
93
  };
87
94
 
@@ -96,6 +103,7 @@ const runSurface = function runSurface(
96
103
  clearBufferAndTimer: () => void
97
104
  ): SurfaceDispatch {
98
105
  const cmdCtx = record.buildCtx();
106
+
99
107
  const candidates = collectCandidates(
100
108
  ctx.commandsBySurface.get(record.id),
101
109
  record.getMode(),
@@ -110,10 +118,12 @@ const runSurface = function runSurface(
110
118
  armTimer();
111
119
 
112
120
  const matchedIndex = hotkeys.findIndex((hotkey) => matchesBuffer(state.buffer, hotkey));
121
+
113
122
  if (matchedIndex !== -1) {
114
123
  clearBufferAndTimer();
115
124
  environment.store.trigger.sequenceReset();
116
125
  const matched = candidates.multiStep[matchedIndex].command;
126
+
117
127
  return {
118
128
  invoke: (): void => {
119
129
  void matched.handler(cmdCtx);
@@ -124,8 +134,10 @@ const runSurface = function runSurface(
124
134
 
125
135
  state.buffer = pruneBuffer(state.buffer, hotkeys);
126
136
  const pending = findPendingMatch(state.buffer, hotkeys);
137
+
127
138
  if (pending) {
128
139
  const firstCandidate = candidates.multiStep[pending.indexes[0]];
140
+
129
141
  const sequence: CommandSequenceState = {
130
142
  candidates: pending.indexes
131
143
  .map((index) => candidates.multiStep[index])
@@ -140,7 +152,9 @@ const runSurface = function runSurface(
140
152
  })),
141
153
  prefix: firstCandidate.parsed.steps.slice(0, pending.prefixLength),
142
154
  };
155
+
143
156
  environment.store.trigger.sequencePending({ state: sequence });
157
+
144
158
  return { outcome: "pending" };
145
159
  }
146
160
 
@@ -151,6 +165,7 @@ const runSurface = function runSurface(
151
165
  for (const { command, parsed } of candidates.singleStep) {
152
166
  if (matchStep(event, parsed.steps[0])) {
153
167
  environment.store.trigger.sequenceReset();
168
+
154
169
  return {
155
170
  invoke: (): void => {
156
171
  void command.handler(cmdCtx);
@@ -162,6 +177,7 @@ const runSurface = function runSurface(
162
177
 
163
178
  clearBufferAndTimer();
164
179
  environment.store.trigger.sequenceReset();
180
+
165
181
  return { outcome: "miss" };
166
182
  };
167
183
 
@@ -172,9 +188,12 @@ const finishDispatch = function finishDispatch(
172
188
  ): KeyDispatchResult {
173
189
  if (dispatch.outcome === "pending") {
174
190
  state.sequenceOwnerId = ownerId;
191
+
175
192
  return { handled: true };
176
193
  }
194
+
177
195
  state.sequenceOwnerId = null;
196
+
178
197
  return dispatch.outcome === "invoke"
179
198
  ? { handled: true, invoke: dispatch.invoke }
180
199
  : { handled: false };
@@ -198,15 +217,18 @@ export const createKeyDispatcher = function createKeyDispatcher(
198
217
  state.timer = null;
199
218
  }
200
219
  };
220
+
201
221
  const clearBufferAndTimer = (): void => {
202
222
  state.buffer = [];
203
223
  state.sequenceOwnerId = null;
204
224
  clearTimer();
205
225
  };
226
+
206
227
  const reset = (): void => {
207
228
  clearBufferAndTimer();
208
229
  environment.store.trigger.sequenceReset();
209
230
  };
231
+
210
232
  const armTimer = (): void => {
211
233
  clearTimer();
212
234
  state.timer = setTimeout(
@@ -214,16 +236,20 @@ export const createKeyDispatcher = function createKeyDispatcher(
214
236
  environment.getConfig().sequenceTimeoutMs ?? DEFAULT_SEQUENCE_TIMEOUT_MS
215
237
  );
216
238
  };
239
+
217
240
  const getParsedHotkey = (hotkey: string): ParsedHotkey => {
218
241
  const { leader } = environment.getConfig();
219
242
  const cacheKey = `${hotkey}:${leader ?? ""}`;
220
243
  let parsed = parseCache.get(cacheKey);
244
+
221
245
  if (!parsed) {
222
246
  parsed = parseHotkey(hotkey, leader);
223
247
  parseCache.set(cacheKey, parsed);
224
248
  }
249
+
225
250
  return parsed;
226
251
  };
252
+
227
253
  const dispatchTo = (
228
254
  record: SurfaceRecord,
229
255
  event: KeyEvent,
@@ -239,33 +265,42 @@ export const createKeyDispatcher = function createKeyDispatcher(
239
265
  armTimer,
240
266
  clearBufferAndTimer
241
267
  );
268
+
242
269
  const finish = (dispatch: SurfaceDispatch, ownerId: string): KeyDispatchResult =>
243
270
  finishDispatch(dispatch, ownerId, state);
244
271
 
245
272
  const key = (event: KeyEvent): KeyDispatchResult => {
246
273
  const ctx = environment.store.getSnapshot().context;
274
+
247
275
  if (state.buffer.length > 0 && state.sequenceOwnerId !== null) {
248
276
  const owner =
249
277
  state.sequenceOwnerId === ROOT_SURFACE_ID
250
278
  ? environment.rootRecord
251
279
  : (ctx.surfaces.find((record) => record.id === state.sequenceOwnerId) ?? null);
280
+
252
281
  if (owner) {
253
282
  return finish(dispatchTo(owner, event, ctx), state.sequenceOwnerId);
254
283
  }
284
+
255
285
  clearBufferAndTimer();
256
286
  }
257
287
 
258
288
  const modal = selectActiveModalSurface(ctx);
289
+
259
290
  if (modal) {
260
291
  return finish(dispatchTo(modal, event, ctx), modal.id);
261
292
  }
293
+
262
294
  const panel = selectActivePanelSurface(ctx);
295
+
263
296
  if (panel) {
264
297
  const dispatch = dispatchTo(panel, event, ctx);
298
+
265
299
  if (dispatch.outcome !== "miss" || panel.getMode() === "insert") {
266
300
  return finish(dispatch, panel.id);
267
301
  }
268
302
  }
303
+
269
304
  return finish(dispatchTo(environment.rootRecord, event, ctx), ROOT_SURFACE_ID);
270
305
  };
271
306
 
package/src/match.ts CHANGED
@@ -9,20 +9,26 @@ export const matchStep = function matchStep(event: KeyEvent, step: ParsedStep):
9
9
  if (event.name !== step.key) {
10
10
  return false;
11
11
  }
12
+
12
13
  if (event.ctrl !== step.ctrl) {
13
14
  return false;
14
15
  }
16
+
15
17
  if (event.meta !== step.meta) {
16
18
  return false;
17
19
  }
20
+
18
21
  if (event.shift !== step.shift) {
19
22
  return false;
20
23
  }
24
+
21
25
  if (event.option !== step.option) {
22
26
  return false;
23
27
  }
28
+
24
29
  if ((event.super ?? false) !== (step.super ?? false)) {
25
30
  return false;
26
31
  }
32
+
27
33
  return true;
28
34
  };
package/src/mode.tsx CHANGED
@@ -36,6 +36,7 @@ export const ModeProvider = function ModeProvider({
36
36
  modeRef.current = nextMode;
37
37
  onModeChangeRef.current?.(nextMode);
38
38
  }
39
+
39
40
  setMode(nextMode);
40
41
  }, []);
41
42
 
@@ -49,16 +50,20 @@ export const ModeProvider = function ModeProvider({
49
50
 
50
51
  export const useMode = function useMode(): Mode {
51
52
  const ctx = useContext(ModeContext);
53
+
52
54
  if (!ctx) {
53
55
  throw new Error("useMode must be used within a ModeProvider");
54
56
  }
57
+
55
58
  return ctx.mode;
56
59
  };
57
60
 
58
61
  export const useSetMode = function useSetMode(): (mode: Mode) => void {
59
62
  const ctx = useContext(ModeContext);
63
+
60
64
  if (!ctx) {
61
65
  throw new Error("useSetMode must be used within a ModeProvider");
62
66
  }
67
+
63
68
  return ctx.setMode;
64
69
  };
package/src/parse.ts CHANGED
@@ -12,6 +12,7 @@ const KEY_ALIASES: ReadonlyMap<string, string> = new Map([
12
12
 
13
13
  const normalizeKey = function normalizeKey(key: string): string {
14
14
  const lower = key.toLowerCase();
15
+
15
16
  return KEY_ALIASES.get(lower) ?? lower;
16
17
  };
17
18
 
@@ -21,13 +22,40 @@ const warnOnce = function warnOnce(message: string): void {
21
22
  if (warned.has(message)) {
22
23
  return;
23
24
  }
25
+
24
26
  warned.add(message);
25
27
  console.warn(message);
26
28
  };
27
29
 
30
+ /** A hotkey step split at `+`, before modifiers are read. */
31
+ interface SplitStep {
32
+ parts: string[];
33
+ /** True when the step's key is `+` itself. */
34
+ plusKey: boolean;
35
+ }
36
+
37
+ /**
38
+ * Split a step into modifier parts and a key. `+` joins modifiers, so a `+`
39
+ * key needs care: a bare `+`, or a trailing `++` as in `ctrl++`, is the `+`
40
+ * key itself.
41
+ */
42
+ const splitStep = function splitStep(step: string): SplitStep {
43
+ const lower = step.toLowerCase().trim();
44
+
45
+ if (lower === "+") {
46
+ return { parts: [], plusKey: true };
47
+ }
48
+
49
+ if (lower.endsWith("++")) {
50
+ return { parts: lower.slice(0, -2).split("+"), plusKey: true };
51
+ }
52
+
53
+ return { parts: lower.split("+"), plusKey: false };
54
+ };
55
+
28
56
  const parseStep = function parseStep(step: string): ParsedStep {
29
- const parts = step.toLowerCase().split("+");
30
- let key = "";
57
+ const { parts, plusKey } = splitStep(step);
58
+ let key = plusKey ? "+" : "";
31
59
  let ctrl = false;
32
60
  let meta = false;
33
61
  let shift = false;
@@ -36,6 +64,7 @@ const parseStep = function parseStep(step: string): ParsedStep {
36
64
 
37
65
  for (const part of parts) {
38
66
  const trimmed = part.trim();
67
+
39
68
  if (trimmed === "ctrl" || trimmed === "control") {
40
69
  ctrl = true;
41
70
  } else if (trimmed === "meta" || trimmed === "alt") {
@@ -67,6 +96,7 @@ export const parseHotkey = function parseHotkey(hotkey: string, leaderKey?: stri
67
96
 
68
97
  // Handle leader prefix
69
98
  const leaderMatch = /^<leader>(?<followingKey>.+)$/u.exec(trimmed);
99
+
70
100
  if (leaderMatch) {
71
101
  if (leaderKey === undefined || leaderKey === "") {
72
102
  // No leader configured: the hotkey must not spring to life on some
@@ -74,15 +104,19 @@ export const parseHotkey = function parseHotkey(hotkey: string, leaderKey?: stri
74
104
  warnOnce(
75
105
  `[tooee/commands] Hotkey "${trimmed}" uses <leader> but no leader key is configured; the hotkey is disabled.`
76
106
  );
107
+
77
108
  return { steps: [] };
78
109
  }
110
+
79
111
  const leaderStep = parseStep(leaderKey);
80
112
  const followStep = parseStep(leaderMatch.groups?.followingKey ?? "");
113
+
81
114
  return { steps: [leaderStep, followStep] };
82
115
  }
83
116
 
84
117
  // Space-separated = sequence
85
118
  const parts = trimmed.split(/\s+/u);
86
119
  const steps = parts.map(parseStep);
120
+
87
121
  return { steps };
88
122
  };
@@ -30,10 +30,12 @@ export const ScreenScopeProvider = function ScreenScopeProvider({
30
30
  children: ReactNode;
31
31
  }): ReactNode {
32
32
  const parent = useContext(ScreenScopeContext);
33
+
33
34
  const value = useMemo<ScreenScopeState>(
34
35
  () => ({ isFocused: parent.isFocused && active }),
35
36
  [parent.isFocused, active]
36
37
  );
38
+
37
39
  return <ScreenScopeContext value={value}>{children}</ScreenScopeContext>;
38
40
  };
39
41
 
package/src/sequence.ts CHANGED
@@ -36,21 +36,26 @@ export const matchesBuffer = function matchesBuffer(
36
36
  hotkey: ParsedHotkey
37
37
  ): boolean {
38
38
  const { steps } = hotkey;
39
+
39
40
  if (steps.length === 0) {
40
41
  return false;
41
42
  }
43
+
42
44
  if (buffer.length < steps.length) {
43
45
  return false;
44
46
  }
45
47
 
46
48
  const start = buffer.length - steps.length;
49
+
47
50
  for (let i = 0; i < steps.length; i += 1) {
48
51
  const event = buffer[start + i];
49
52
  const step = steps[i];
53
+
50
54
  if (event === undefined || step === undefined || !matchStep(event, step)) {
51
55
  return false;
52
56
  }
53
57
  }
58
+
54
59
  return true;
55
60
  };
56
61
 
@@ -74,11 +79,13 @@ export const findPendingMatch = function findPendingMatch(
74
79
 
75
80
  for (let hotkeyIndex = 0; hotkeyIndex < hotkeys.length; hotkeyIndex += 1) {
76
81
  const hotkey = hotkeys[hotkeyIndex];
82
+
77
83
  if (hotkey.steps.length <= prefixLength) {
78
84
  continue;
79
85
  }
80
86
 
81
87
  let matches = true;
88
+
82
89
  for (let i = 0; i < prefixLength; i += 1) {
83
90
  if (!matchStep(buffer[start + i], hotkey.steps[i])) {
84
91
  matches = false;
@@ -108,9 +115,11 @@ export const pruneBuffer = function pruneBuffer(
108
115
  hotkeys: readonly ParsedHotkey[]
109
116
  ): readonly KeyEvent[] {
110
117
  const maxLen = Math.max(0, ...hotkeys.map((h) => h.steps.length));
118
+
111
119
  if (maxLen > 0 && buffer.length > maxLen) {
112
120
  return buffer.slice(buffer.length - maxLen);
113
121
  }
122
+
114
123
  return buffer;
115
124
  };
116
125
 
@@ -143,6 +152,7 @@ export class SequenceTracker {
143
152
  for (let i = 0; i < hotkeys.length; i += 1) {
144
153
  if (matchesBuffer(this.buffer, hotkeys[i])) {
145
154
  this.reset();
155
+
146
156
  return { matchedIndex: i, pending: null };
147
157
  }
148
158
  }
@@ -161,6 +171,7 @@ export class SequenceTracker {
161
171
  const hadBuffer = this.buffer.length > 0;
162
172
  this.buffer = [];
163
173
  this.clearTimer();
174
+
164
175
  if (hadBuffer) {
165
176
  this.onReset?.();
166
177
  }
package/src/store.ts CHANGED
@@ -1,12 +1,19 @@
1
1
  export { ModeProvider } from "./mode.js";
2
+
2
3
  export type { ModeProviderProps } from "./mode.js";
4
+
3
5
  export { DEFAULT_SEQUENCE_TIMEOUT_MS, SequenceTracker } from "./sequence.js";
6
+
4
7
  export type {
5
8
  SequenceFeedResult,
6
9
  SequencePendingMatch,
7
10
  SequenceTrackerOptions,
8
11
  } from "./sequence.js";
12
+
9
13
  export { createBaseStore, selectGroups, selectSurfaceCommandMap } from "./command-store.js";
14
+
10
15
  export type { CommandStoreInstance, ContextGetter } from "./command-store.js";
16
+
11
17
  export { createCommandStore } from "./command-store-wrapper.js";
18
+
12
19
  export type { CreateCommandStoreOptions, KeyDispatchResult } from "./command-store-wrapper.js";
package/src/types.ts CHANGED
@@ -30,6 +30,7 @@ export interface CommandContext {
30
30
  mode: Mode;
31
31
  setMode: (mode: Mode) => void;
32
32
  commands: CommandCommands;
33
+ /** Close the app. By default this destroys the renderer. */
33
34
  exit: () => void;
34
35
  }
35
36
 
@@ -37,6 +38,7 @@ export interface CommandContext {
37
38
  export type CommandContextBase = Pick<CommandContext, "mode" | "setMode" | "commands" | "exit">;
38
39
 
39
40
  export type CommandHandler = (ctx: CommandContext) => void | Promise<void>;
41
+
40
42
  export type CommandWhen = (ctx: CommandContext) => boolean;
41
43
 
42
44
  export interface Command {
@@ -37,6 +37,7 @@ export const useActions = function useActions(actions: ActionDefinition[] | unde
37
37
 
38
38
  useEffect(() => {
39
39
  const { current } = actionsRef;
40
+
40
41
  if (!current || current.length === 0) {
41
42
  return () => {
42
43
  // Nothing was registered, so there is nothing to unregister.
@@ -53,9 +54,11 @@ export const useActions = function useActions(actions: ActionDefinition[] | unde
53
54
  // dispatch) is a no-op, so the missing-action path just returns. The
54
55
  // body runs synchronously up to the call, preserving dispatch timing.
55
56
  const currentAction = actionsRef.current?.[i];
57
+
56
58
  if (currentAction === undefined) {
57
59
  return;
58
60
  }
61
+
59
62
  await currentAction.handler(ctx);
60
63
  },
61
64
  hidden: action.hidden,
@@ -65,6 +68,7 @@ export const useActions = function useActions(actions: ActionDefinition[] | unde
65
68
  title: action.title,
66
69
  when: action.when ? (ctx) => actionsRef.current?.[i]?.when?.(ctx) ?? false : undefined,
67
70
  };
71
+
68
72
  return registry.register(command);
69
73
  });
70
74
 
@@ -58,13 +58,16 @@ export const useCommand = function useCommand(options: UseCommandOptions): void
58
58
  when: optionsRef.current.when
59
59
  ? (ctx) => {
60
60
  const { when } = optionsRef.current;
61
+
61
62
  if (!when) {
62
63
  return false;
63
64
  }
65
+
64
66
  return when(ctx);
65
67
  }
66
68
  : undefined,
67
69
  };
70
+
68
71
  return registry.register(command);
69
72
  }, [
70
73
  options.id,