|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { |
| 4 | + getLocalStorageItem, |
| 5 | + removeLocalStorageItem, |
| 6 | + setLocalStorageItem, |
| 7 | +} from '@/lib/browser/local-storage'; |
| 8 | +import { create } from 'zustand'; |
| 9 | +import { type StorageValue, persist } from 'zustand/middleware'; |
| 10 | + |
| 11 | +const AI_CHAT_MIN_WIDTH = 384; |
| 12 | +const AI_CHAT_MAX_WIDTH = 640; |
| 13 | +const MIN_CONTENT_WIDTH = 720; |
| 14 | + |
| 15 | +type AIChatWidthStore = { |
| 16 | + width: number; |
| 17 | + toggleWidth: () => void; |
| 18 | + setWidth: (width: number) => number; |
| 19 | + syncWidth: () => void; |
| 20 | +}; |
| 21 | + |
| 22 | +type PersistedState = Pick<AIChatWidthStore, 'width'>; |
| 23 | + |
| 24 | +export const useAIChatWidthStore = create<AIChatWidthStore>()( |
| 25 | + persist( |
| 26 | + (set, get) => ({ |
| 27 | + width: AI_CHAT_MIN_WIDTH, |
| 28 | + toggleWidth: () => |
| 29 | + get().setWidth( |
| 30 | + get().width >= AI_CHAT_MAX_WIDTH ? AI_CHAT_MIN_WIDTH : AI_CHAT_MAX_WIDTH |
| 31 | + ), |
| 32 | + setWidth: (width) => { |
| 33 | + const clamped = clampWidth(width); |
| 34 | + if (get().width !== clamped) { |
| 35 | + set({ width: clamped }); |
| 36 | + } |
| 37 | + setWidthOnViewport(clamped); |
| 38 | + return clamped; |
| 39 | + }, |
| 40 | + syncWidth: () => setWidthOnViewport(get().width), |
| 41 | + }), |
| 42 | + { |
| 43 | + name: '@gitbook/ai-chat-width', |
| 44 | + storage: { |
| 45 | + getItem: (name) => |
| 46 | + getLocalStorageItem<StorageValue<PersistedState> | null>(name, null), |
| 47 | + setItem: (name, value) => setLocalStorageItem(name, value), |
| 48 | + removeItem: (name) => removeLocalStorageItem(name), |
| 49 | + }, |
| 50 | + partialize: (state) => ({ width: state.width }), |
| 51 | + onRehydrateStorage: () => (state) => state?.syncWidth(), |
| 52 | + } |
| 53 | + ) |
| 54 | +); |
| 55 | + |
| 56 | +/** |
| 57 | + * Whether the panel is at its maximum width. |
| 58 | + */ |
| 59 | +export const useIsAIChatMaxWidth = () => |
| 60 | + useAIChatWidthStore((state) => state.width >= AI_CHAT_MAX_WIDTH); |
| 61 | + |
| 62 | +// Hoisted so the synchronous persist rehydrate (during create() above) can call them before this point. |
| 63 | +function setWidthOnViewport(width: number) { |
| 64 | + if (typeof document !== 'undefined') { |
| 65 | + document.documentElement.style.setProperty('--ai-chat-width', `${capToViewport(width)}px`); |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +function clampWidth(width: number) { |
| 70 | + return Math.min(AI_CHAT_MAX_WIDTH, Math.max(AI_CHAT_MIN_WIDTH, Math.round(width))); |
| 71 | +} |
| 72 | + |
| 73 | +// Cap a width so the remaining content keeps a usable minimum at the current viewport. |
| 74 | +function capToViewport(width: number) { |
| 75 | + return typeof window === 'undefined' |
| 76 | + ? width |
| 77 | + : Math.min(width, Math.max(AI_CHAT_MIN_WIDTH, window.innerWidth - MIN_CONTENT_WIDTH)); |
| 78 | +} |
0 commit comments