TabStoreProvider.tsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * TabStoreProvider —— 初始化 Tab Zustand store 并通过 React Context 提供
  3. *
  4. * 每个窗口独立挂载,tab 状态不跨窗口广播。
  5. */
  6. import { createContext, useContext, useEffect, useRef, type ReactNode } from "react";
  7. import { useStore } from "zustand";
  8. import { shouldExposeE2EStoreBridge } from "@/lib/e2eStoreBridge.js";
  9. import { createTabStore, type TabStore, type TabStoreState } from "./tabStore.js";
  10. declare global {
  11. interface Window {
  12. __zcodeTabStoreE2E?: TabStore;
  13. }
  14. }
  15. const TabStoreContext = createContext<TabStore | null>(null);
  16. const fallbackTabStore = createTabStore(null);
  17. export function TabStoreProvider({ children }: { children: ReactNode }) {
  18. // 只在首次渲染时创建 store,避免 HMR 重复创建
  19. const storeRef = useRef<TabStore | null>(null);
  20. if (!storeRef.current) {
  21. storeRef.current = createTabStore();
  22. }
  23. useEffect(() => {
  24. if (!shouldExposeE2EStoreBridge() || !storeRef.current) {
  25. return;
  26. }
  27. const store = storeRef.current;
  28. // V4 draft 没有 taskId,E2E 若按 activeTaskId=null 反查 workspace,
  29. // 多 workspace 会命中任意草稿桶。只在 E2E 构建暴露当前窗口导航 store,供 helper
  30. // 按 workspaceIdentity?.trim() || workspacePath 精确读取当前草稿。
  31. window.__zcodeTabStoreE2E = store;
  32. return () => {
  33. if (window.__zcodeTabStoreE2E === store) {
  34. delete window.__zcodeTabStoreE2E;
  35. }
  36. };
  37. }, []);
  38. return <TabStoreContext.Provider value={storeRef.current}>{children}</TabStoreContext.Provider>;
  39. }
  40. /**
  41. * 消费 Tab store 的 hook
  42. *
  43. * 用法:
  44. * const tabs = useTabStore(s => s.tabs);
  45. * const addTab = useTabStore(s => s.addTab);
  46. */
  47. export function useTabStore<T>(selector: (state: TabStoreState) => T): T {
  48. const store = useContext(TabStoreContext);
  49. if (!store) {
  50. throw new Error("useTabStore 必须在 TabStoreProvider 内使用");
  51. }
  52. return useStore(store, selector);
  53. }
  54. /** 供可独立渲染的展示组件读取;无 Root provider 时回退为空 tab 状态。 */
  55. export function useOptionalTabStore<T>(selector: (state: TabStoreState) => T): T {
  56. const store = useContext(TabStoreContext);
  57. return useStore(store ?? fallbackTabStore, selector);
  58. }
  59. /**
  60. * 获取 tab store 的原始引用(用于非 React 上下文,如 useEffect 中的订阅)
  61. */
  62. export function useTabStoreApi(): TabStore {
  63. const store = useContext(TabStoreContext);
  64. if (!store) {
  65. throw new Error("useTabStoreApi 必须在 TabStoreProvider 内使用");
  66. }
  67. return store;
  68. }