Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

commandPaletteStore.ts

49 lines1.5 KB

1import { useEffect } from "react";
2import { create } from "zustand";
3​
4import {
5 type CommandPaletteUiAction,
6 type CommandPaletteUiState,
7 reduceCommandPaletteUiState,
8} from "./components/CommandPalette.logic";
9​
10const INITIAL_STATE: CommandPaletteUiState = {
11 open: false,
12 mode: "command",
13 openIntent: null,
14 session: 0,
15};
16​
17export const useCommandPaletteStore = create<CommandPaletteUiState>(() => INITIAL_STATE);
18​
19export function dispatchCommandPalette(action: CommandPaletteUiAction): void {
20 useCommandPaletteStore.setState((state) => reduceCommandPaletteUiState(state, action), true);
22​
23// The palette is only mounted on app-shell routes (not /pair, sign-in or
24// landings), so its shortcuts must stay inert elsewhere.
25let mountedPalettes = 0;
26​
27export function isCommandPaletteMounted(): boolean {
28 return mountedPalettes > 0;
30​
31/**
32 * Marks the palette as mounted while the calling component is. An unmounted
33 * palette cannot stay open, so the last unmount resets the store.
34 */
35export function useCommandPaletteMount(): void {
36 // oxlint-disable-next-line t3code/react-effect-budget -- The palette's mount gates its global shortcuts, and leaving the route while it is open calls no close handler, so only unmount can reset the store.
37 useEffect(() => {
38 mountedPalettes += 1;
39 return () => {
40 mountedPalettes -= 1;
41 if (mountedPalettes === 0) {
42 useCommandPaletteStore.setState(
43 (state) => ({ ...INITIAL_STATE, session: state.session + 1 }),
44 true,
45 );
46 }
47 };
48 }, []);