The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(cmd menu): add hooks (#27044)
Charis9d6d29c4db9e
diff --git a/apps/studio/components/interfaces/Support/SupportForm.tsx b/apps/studio/components/interfaces/Support/SupportForm.tsxindex 1771064a222..c4a40f69596 100644--- a/apps/studio/components/interfaces/Support/SupportForm.tsx+++ b/apps/studio/components/interfaces/Support/SupportForm.tsx@@ -1,3 +1,4 @@+import { useSupabaseClient } from '@supabase/auth-helpers-react'import { CLIENT_LIBRARIES } from 'common/constants'import {AlertCircle,@@ -70,7 +71,12 @@ export interface SupportFormProps {}const SupportForm = ({ setSentCategory, setSelectedProject }: SupportFormProps) => {- const { handleDocsSearchDebounced, searchState, searchState: state } = useDocsSearch()+ const supabaseClient = useSupabaseClient()+ const {+ handleDocsSearchDebounced,+ searchState,+ searchState: state,+ } = useDocsSearch(supabaseClient)const [subject, setSubject] = useState('')const [docsResults, setDocsResults] = useState<Page[]>([])diff --git a/package-lock.json b/package-lock.jsonindex 336365e3ddd..37ba851ef47 100644--- a/package-lock.json+++ b/package-lock.json@@ -13459,7 +13459,8 @@},"node_modules/@supabase/auth-helpers-react": {"version": "0.4.2",- "license": "MIT",+ "resolved": "https://registry.npmjs.org/@supabase/auth-helpers-react/-/auth-helpers-react-0.4.2.tgz",+ "integrity": "sha512-zRj1leYMKJVYQeHFvZiUzlmHM+ATWFR/V7Q9F0yXSWEnMcNHL0CKnIBqhkjtSQ2trE+YaoCvFEHjxISppxIZXQ==","peerDependencies": {"@supabase/supabase-js": "^2.19.0"}@@ -13989,8 +13990,9 @@},"node_modules/@testing-library/user-event": {"version": "13.5.0",+ "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-13.5.0.tgz",+ "integrity": "sha512-5Kwtbo3Y/NowpkbRuSepbyMFkZmHgD+vPzYB/RJ4oxt5Gj/avFFBYjhw27cqSVPVw/3a67NK1PbiIr9k4Gwmdg==","dev": true,- "license": "MIT","dependencies": {"@babel/runtime": "^7.12.5"},@@ -14799,9 +14801,9 @@"license": "MIT"},"node_modules/@types/react": {- "version": "18.3.2",- "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.2.tgz",- "integrity": "sha512-Btgg89dAnqD4vV7R3hlwOxgqobUQKgx3MmrQRi0yYbs/P0ym8XozIAlkqVilPqHQwXs4e9Tf63rrCgl58BcO4w==",+ "version": "18.3.3",+ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.3.tgz",+ "integrity": "sha512-hti/R0pS0q1/xx+TsI73XIqk26eBsISZ2R0wUijXIngRK9R/e7Xw/cXVxQK7R5JjW+SV4zGcn5hXjudkN/pLIw==","dependencies": {"@types/prop-types": "*","csstype": "^3.0.2"@@ -24746,8 +24748,9 @@},"node_modules/jest-environment-jsdom": {"version": "29.7.0",+ "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-29.7.0.tgz",+ "integrity": "sha512-k9iQbsf9OyOfdzWH8HDmrRT0gSIcX+FLNW7IQq94tFX0gynPwqDTW0Ho6iMVNjGz/nb+l/vW3dWM2bbLLpkbXA==","dev": true,- "license": "MIT","dependencies": {"@jest/environment": "^29.7.0","@jest/fake-timers": "^29.7.0",@@ -42862,9 +42865,16 @@"valtio": "*"},"devDependencies": {+ "@supabase/auth-helpers-react": "^0.4.2",+ "@testing-library/dom": "^10.1.0",+ "@testing-library/react": "^16.0.0",+ "@testing-library/user-event": "^13.5.0","@types/common-tags": "^1.8.4",+ "@types/react": "^18.3.3",+ "@types/react-dom": "^18.3.0","api-types": "*","jest": "^29.7.0",+ "jest-environment-jsdom": "^29.7.0","ts-jest": "^29.1.2"},"peerDependencies": {@@ -42873,6 +42883,52 @@"react-dom": "*"}},+ "packages/ui-patterns/node_modules/@testing-library/dom": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.1.0.tgz",+ "integrity": "sha512-wdsYKy5zupPyLCW2Je5DLHSxSfbIp6h80WoHOQc+RPtmPGA52O9x5MJEkv92Sjonpq+poOAtUKhh1kBGAXBrNA==",+ "dev": true,+ "dependencies": {+ "@babel/code-frame": "^7.10.4",+ "@babel/runtime": "^7.12.5",+ "@types/aria-query": "^5.0.1",+ "aria-query": "5.3.0",+ "chalk": "^4.1.0",+ "dom-accessibility-api": "^0.5.9",+ "lz-string": "^1.5.0",+ "pretty-format": "^27.0.2"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "packages/ui-patterns/node_modules/@testing-library/react": {+ "version": "16.0.0",+ "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.0.0.tgz",+ "integrity": "sha512-guuxUKRWQ+FgNX0h0NS0FIq3Q3uLtWVpBzcLOggmfMoUpgBnzBzvLLd4fbm6yS8ydJd94cIfY4yP9qUQjM2KwQ==",+ "dev": true,+ "dependencies": {+ "@babel/runtime": "^7.12.5"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@testing-library/dom": "^10.0.0",+ "@types/react": "^18.0.0",+ "@types/react-dom": "^18.0.0",+ "react": "^18.0.0",+ "react-dom": "^18.0.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },"packages/ui-patterns/node_modules/@types/hast": {"version": "3.0.4","resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz",@@ -42886,11 +42942,42 @@"resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.2.tgz","integrity": "sha512-dqId9J8K/vGi5Zr7oo212BGii5m3q5Hxlkwy3WpYuKPklmBEvsbMYYyLxAQpSffdLl/gdW0XUpKWFvYmyoWCoQ=="},+ "packages/ui-patterns/node_modules/ansi-styles": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",+ "dev": true,+ "dependencies": {+ "color-convert": "^2.0.1"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },"packages/ui-patterns/node_modules/argparse": {"version": "2.0.1","resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz","integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="},+ "packages/ui-patterns/node_modules/chalk": {+ "version": "4.1.2",+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",+ "dev": true,+ "dependencies": {+ "ansi-styles": "^4.1.0",+ "supports-color": "^7.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/chalk?sponsor=1"+ }+ },"packages/ui-patterns/node_modules/framer-motion": {"version": "11.1.9","resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-11.1.9.tgz",@@ -42915,6 +43002,15 @@}}},+ "packages/ui-patterns/node_modules/has-flag": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",+ "dev": true,+ "engines": {+ "node": ">=8"+ }+ },"packages/ui-patterns/node_modules/mdast-util-to-hast": {"version": "13.1.0","resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.1.0.tgz",@@ -43071,6 +43167,18 @@"sql-formatter": "bin/sql-formatter-cli.cjs"}},+ "packages/ui-patterns/node_modules/supports-color": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",+ "dev": true,+ "dependencies": {+ "has-flag": "^4.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },"packages/ui-patterns/node_modules/unified": {"version": "11.0.4","resolved": "https://registry.npmjs.org/unified/-/unified-11.0.4.tgz",diff --git a/packages/common/hooks/useDocsSearch.ts b/packages/common/hooks/useDocsSearch.tsindex f16dd122fb8..7d90c25a1f4 100644--- a/packages/common/hooks/useDocsSearch.ts+++ b/packages/common/hooks/useDocsSearch.ts@@ -1,4 +1,4 @@-import { useSupabaseClient } from '@supabase/auth-helpers-react'+import type { SupabaseClient } from '@supabase/supabase-js'import { compact, debounce, uniqBy } from 'lodash'import { useCallback, useMemo, useReducer, useRef } from 'react'@@ -186,9 +186,8 @@ function reducer(state: SearchState, action: Action): SearchState {}}-const useDocsSearch = () => {+const useDocsSearch = (supabaseClient: SupabaseClient) => {const [state, dispatch] = useReducer(reducer, { status: 'initial', key: 0 })- const supabaseClient = useSupabaseClient()const key = useRef(0)const handleSearch = useCallback(@@ -199,24 +198,26 @@ const useDocsSearch = () => {let sourcesLoaded = 0- supabaseClient.rpc('docs_search_fts', { query: query.trim() }).then(({ data, error }) => {- sourcesLoaded += 1- if (error || !Array.isArray(data)) {- dispatch({- type: 'errored',- key: localKey,- sourcesLoaded,- message: error?.message ?? '',- })- } else {- dispatch({- type: 'resultsReturned',- key: localKey,- sourcesLoaded,- results: data,- })- }- })+ supabaseClient+ .rpc('docs_search_fts', { query: query.trim() })+ .then(({ data, error }: { data: any; error: any }) => {+ sourcesLoaded += 1+ if (error || !Array.isArray(data)) {+ dispatch({+ type: 'errored',+ key: localKey,+ sourcesLoaded,+ message: error?.message ?? '',+ })+ } else {+ dispatch({+ type: 'resultsReturned',+ key: localKey,+ sourcesLoaded,+ results: data,+ })+ }+ })fetch(`${process.env.NEXT_PUBLIC_SUPABASE_URL}${FUNCTIONS_URL}search-embeddings`, {method: 'POST',diff --git a/packages/ui-patterns/Cmdk/DocsSearch.tsx b/packages/ui-patterns/Cmdk/DocsSearch.tsxindex 58ac912536f..df393436b8c 100644--- a/packages/ui-patterns/Cmdk/DocsSearch.tsx+++ b/packages/ui-patterns/Cmdk/DocsSearch.tsx@@ -1,3 +1,4 @@+import { useSupabaseClient } from '@supabase/auth-helpers-react'import {type DocsSearchResult as Page,type DocsSearchResultSection as PageSection,@@ -22,12 +23,13 @@ const questions = []const DocsSearch = () => {+ const supabaseClient = useSupabaseClient()const {searchState: state,handleDocsSearch: handleSearch,handleDocsSearchDebounced: debouncedSearch,resetSearch,- } = useDocsSearch()+ } = useDocsSearch(supabaseClient)const { search, setSearch, inputRef, site, setIsOpen } = useCommandMenu()const initialLoad = useRef(true)const router = useRouter()diff --git a/packages/ui-patterns/CommandMenu/api/CommandProvider.tsx b/packages/ui-patterns/CommandMenu/api/CommandProvider.tsxnew file mode 100644index 00000000000..06bc2393a09--- /dev/null+++ b/packages/ui-patterns/CommandMenu/api/CommandProvider.tsx@@ -0,0 +1,48 @@+import { useConstant } from 'common'+import { useEffect, type PropsWithChildren } from 'react'++import { useToggleCommandMenu } from './hooks/viewHooks'+import { CommandContext } from '../internal/Context'+import { initCommandsState } from '../internal/state/commandsState'+import { initPagesState } from '../internal/state/pagesState'+import { initQueryState } from '../internal/state/queryState'+import { initViewState } from '../internal/state/viewState'++const CommandProviderInternal = ({ children }: PropsWithChildren) => {+ const combinedState = useConstant(() => ({+ commandsState: initCommandsState(),+ pagesState: initPagesState(),+ queryState: initQueryState(),+ viewState: initViewState(),+ }))++ return <CommandContext.Provider value={combinedState}>{children}</CommandContext.Provider>+}++const CommandShortcut = () => {+ const toggleOpen = useToggleCommandMenu()++ useEffect(() => {+ const handleKeydown = (evt: KeyboardEvent) => {+ if (evt.key === 'k' && evt.metaKey) {+ evt.preventDefault()+ toggleOpen()+ }+ }++ document.addEventListener('keydown', handleKeydown)++ return () => document.removeEventListener('keydown', handleKeydown)+ }, [toggleOpen])++ return null+}++const CommandProvider = ({ children }: PropsWithChildren) => (+ <CommandProviderInternal>+ <CommandShortcut />+ {children}+ </CommandProviderInternal>+)++export { CommandProvider }diff --git a/packages/ui-patterns/CommandMenu/api/hooks/commandsHooks.test.tsx b/packages/ui-patterns/CommandMenu/api/hooks/commandsHooks.test.tsxnew file mode 100644index 00000000000..a0c80d59c82--- /dev/null+++ b/packages/ui-patterns/CommandMenu/api/hooks/commandsHooks.test.tsx@@ -0,0 +1,254 @@+/**+ * @jest-environment jsdom+ */++import '@testing-library/jest-dom'+import { act, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { Fragment, useState } from 'react'++import { CommandProvider } from '../CommandProvider'+import type { ICommand } from '../types'+import { useCommands, useRegisterCommands } from './commandsHooks'++const oneCommand = [+ {+ id: 'command-one',+ name: 'Command one',+ action: () => alert('One!'),+ },+]++const twoCommands = [+ ...oneCommand,+ {+ id: 'command-two',+ name: 'Command two',+ action: () => alert('Two!'),+ },+]++let mockCommandMenuRenderCount = 0++const MockCommandMenu = () => {+ mockCommandMenuRenderCount+++ const commandSections = useCommands()++ return (+ <div>+ {commandSections.map((section) => (+ <Fragment key={section.id}>+ <h2>{section.name}</h2>+ <ul>+ {section.commands.map((cmd) => (+ <li key={cmd.id}>{cmd.name}</li>+ ))}+ </ul>+ </Fragment>+ ))}+ </div>+ )+}++const SimpleComponent = ({ commands }: { commands: Array<ICommand> }) => {+ useRegisterCommands('Section', commands)++ return <span>Simple</span>+}++const ToggledComponent = ({ commands }: { commands: Array<ICommand> }) => {+ const [visible, setVisible] = useState(true)++ return (+ <>+ <button onClick={() => setVisible((vis) => !vis)}>Toggle</button>+ {visible && <SimpleComponent commands={commands} />}+ </>+ )+}++const DisableableComponent = ({ commands }: { commands: Array<ICommand> }) => {+ const [enabled, setIsEnabled] = useState(true)+ useRegisterCommands('Section', commands, { enabled })++ return (+ <button onClick={() => setIsEnabled((enabled) => !enabled)}>+ {enabled ? 'Disable commands' : 'Enable commands'}+ </button>+ )+}++const ChangeableCommands = () => {+ const [commands, setCommands] = useState([{ ...twoCommands[0] }])+ useRegisterCommands('Section', commands, { deps: [commands] })++ return <button onClick={() => setCommands([{ ...twoCommands[1] }])}>Use second command</button>+}++const RerenderableComponent = () => {+ const [renderFlag, setRerenderFlag] = useState(0)++ // Define commands inline so the array identity changes each render+ const commands = [...oneCommand]+ useRegisterCommands('Section', commands) // Note no dependency array++ return (+ <>+ <button onClick={() => setRerenderFlag((flag) => ++flag)}>Rerender</button>+ <span>Render flag: {renderFlag}</span>+ </>+ )+}++describe('useRegisterCommand', () => {+ beforeEach(() => {+ mockCommandMenuRenderCount = 0+ })++ it('registers a command when component mounts', () => {+ render(+ <CommandProvider>+ <SimpleComponent commands={oneCommand} />+ <MockCommandMenu />+ </CommandProvider>+ )++ // @ts-ignore+ expect(screen.getByRole('heading')).toHaveTextContent('Section')+ expect(screen.getByRole('listitem')).toHaveTextContent('Command one')+ })++ it('registers multiple commands when component mounts', () => {+ render(+ <CommandProvider>+ <SimpleComponent commands={twoCommands} />+ <MockCommandMenu />+ </CommandProvider>+ )++ expect(screen.getByRole('heading')).toHaveTextContent('Section')++ const items = screen.getAllByRole('listitem')+ expect(items).toHaveLength(2)+ expect(items[0]).toHaveTextContent('Command one')+ expect(items[1]).toHaveTextContent('Command two')+ })++ it('unregisters and reregisters a command when component unmounts and remounts', async () => {+ act(() => {+ render(+ <CommandProvider>+ <ToggledComponent commands={oneCommand} />+ <MockCommandMenu />+ </CommandProvider>+ )+ })++ expect(screen.getByRole('listitem')).toHaveTextContent('Command one')++ act(() => {+ userEvent.click(screen.getByRole('button'))+ })+ await waitFor(() => {+ expect(screen.queryByRole('listitem')).toBeNull()+ })++ act(() => {+ userEvent.click(screen.getByRole('button'))+ })+ await waitFor(() => {+ expect(screen.getByRole('listitem')).toHaveTextContent('Command one')+ })+ })++ it('unregisters multiple commands when component unmounts', async () => {+ act(() => {+ render(+ <CommandProvider>+ <ToggledComponent commands={twoCommands} />+ <MockCommandMenu />+ </CommandProvider>+ )+ })++ expect(screen.getAllByRole('listitem')).toHaveLength(2)++ act(() => {+ userEvent.click(screen.getByRole('button'))+ })+ await waitFor(() => {+ expect(screen.queryAllByRole('listitem')).toHaveLength(0)+ })+ })++ it('unregisters and reregisters a command when enabled changes', async () => {+ act(() => {+ render(+ <CommandProvider>+ <DisableableComponent commands={oneCommand} />+ <MockCommandMenu />+ </CommandProvider>+ )+ })++ expect(screen.getByRole('listitem')).toHaveTextContent('Command one')++ act(() => {+ userEvent.click(screen.getByRole('button'))+ })+ await waitFor(() => {+ expect(screen.queryByRole('listitem')).toBeNull()+ })++ act(() => {+ userEvent.click(screen.getByRole('button'))+ })+ await waitFor(() => {+ expect(screen.getByRole('listitem')).toHaveTextContent('Command one')+ })+ })++ it('reregisters commands when dependencies change', async () => {+ act(() => {+ render(+ <CommandProvider>+ <ChangeableCommands />+ <MockCommandMenu />+ </CommandProvider>+ )+ })++ expect(screen.getByText('Command one')).toBeVisible()++ act(() => {+ userEvent.click(screen.getByRole('button'))+ })+ await waitFor(() => {+ expect(screen.queryByText('Command one')).toBeNull()+ })+ expect(screen.getByRole('listitem')).toHaveTextContent('Command two')+ })++ it("doesn't trigger command menu rerender when dependencies are unchanged", async () => {+ expect(mockCommandMenuRenderCount).toBe(0)++ act(() => {+ render(+ <CommandProvider>+ <RerenderableComponent />+ <MockCommandMenu />+ </CommandProvider>+ )+ })++ // React renders twice in dev mode+ expect(mockCommandMenuRenderCount).toBe(2)++ act(() => {+ userEvent.click(screen.getByRole('button'))+ })+ await waitFor(() => screen.getByText('Render flag: 1'))++ expect(mockCommandMenuRenderCount).toBe(2)+ })+})diff --git a/packages/ui-patterns/CommandMenu/api/hooks/commandsHooks.ts b/packages/ui-patterns/CommandMenu/api/hooks/commandsHooks.tsnew file mode 100644index 00000000000..d67b483e7c4--- /dev/null+++ b/packages/ui-patterns/CommandMenu/api/hooks/commandsHooks.ts@@ -0,0 +1,67 @@+import { isEqual } from 'lodash'+import { useEffect, useMemo, useRef } from 'react'+import { useSnapshot } from 'valtio'++import type { ICommand, CommandOptions } from '../types'+import { useCommandContext } from '../../internal/Context'+import { useCurrentPage } from './pagesHooks'+import { PageDefinition, isCommandsPage } from '../../internal/state/pagesState'++const useCommands = () => {+ const { commandsState } = useCommandContext()+ const { commandSections } = useSnapshot(commandsState)++ const _currPage = useCurrentPage()+ const currPage = _currPage as PageDefinition+ if (currPage && isCommandsPage(currPage)) return currPage.sections++ return commandSections+}++const useRegisterCommands = (+ sectionName: string,+ commands: ICommand[],+ options: CommandOptions = {}+) => {+ const { commandsState } = useCommandContext()+ const { registerSection } = useSnapshot(commandsState)++ const prevDeps = useRef(options?.deps)+ options.enabled ??= true+ const prevEnabled = useRef<boolean | undefined>(options.enabled)++ const unsubscribe = useRef<() => void>()++ /**+ * useEffect handles the registration on first render, since React runs the+ * first render twice in development. (Otherwise the first render would leave+ * a dangling subscription.)+ *+ * It also handles final cleanup, since useMemo can't do this.+ *+ * useMemo handles the registration on subsequent renders, to ensure it+ * happens synchronously.+ */+ useMemo(() => {+ if (!isEqual(prevDeps.current, options.deps) || prevEnabled.current !== options.enabled) {+ unsubscribe.current?.()++ unsubscribe.current = options.enabled+ ? registerSection(sectionName, commands, options)+ : undefined++ prevDeps.current = options.deps+ prevEnabled.current = options.enabled+ }+ }, [registerSection, sectionName, commands, options])++ useEffect(() => {+ unsubscribe.current = options.enabled+ ? registerSection(sectionName, commands, options)+ : undefined++ return () => unsubscribe.current?.()+ }, [])+}++export { useCommands, useRegisterCommands }diff --git a/packages/ui-patterns/CommandMenu/api/hooks/pagesHooks.test.tsx b/packages/ui-patterns/CommandMenu/api/hooks/pagesHooks.test.tsxnew file mode 100644index 00000000000..efdd8724dd1--- /dev/null+++ b/packages/ui-patterns/CommandMenu/api/hooks/pagesHooks.test.tsx@@ -0,0 +1,140 @@+/**+ * @jest-environment jsdom+ */++import '@testing-library/jest-dom'+import { act, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { useEffect, useState } from 'react'++import { CommandProvider } from '../CommandProvider'+import { useCurrentPage, useRegisterPage, useSetPage } from './pagesHooks'+import { PageType } from '../utils'++const PageAdderOne = ({ enabled = true }) => {+ useRegisterPage('Page one', { type: PageType.Commands, sections: [] }, { enabled })+ const setPage = useSetPage()++ useEffect(() => {+ if (enabled) {+ setPage('Page one')+ }+ }, [enabled])++ return <div>Page Adder One</div>+}++const TogglePageAdder = () => {+ const [mounted, setIsMounted] = useState(true)++ return (+ <>+ <button onClick={() => setIsMounted((mounted) => !mounted)}>+ {mounted ? 'Dismount' : 'Mount'}+ </button>+ {mounted && <PageAdderOne />}+ </>+ )+}++const TogglePageEnabled = () => {+ const [enabled, setIsEnabled] = useState(true)++ return (+ <>+ <button onClick={() => setIsEnabled((enabled) => !enabled)}>+ {enabled ? 'Disable' : 'Enable'}+ </button>+ <PageAdderOne enabled={enabled} />+ </>+ )+}++const PageDisplay = () => {+ const currentPage = useCurrentPage()++ return <div data-testid="current-page">{currentPage?.name ?? '[None]'}</div>+}++describe('useRegisterPage', () => {+ it('registers a page on mount', async () => {+ act(() => {+ render(+ <CommandProvider>+ <PageAdderOne />+ <PageDisplay />+ </CommandProvider>+ )+ })++ await waitFor(() => {+ expect(screen.getByTestId('current-page')).toHaveTextContent('Page one')+ })+ })++ it("doesn't register a page on mount if disabled", async () => {+ act(() => {+ render(+ <CommandProvider>+ <PageAdderOne enabled={false} />+ <PageDisplay />+ </CommandProvider>+ )+ })++ await waitFor(() => {+ expect(screen.getByTestId('current-page')).toHaveTextContent('[None]')+ })+ })++ it('unregisters a page on dismount', async () => {+ act(() => {+ render(+ <CommandProvider>+ <TogglePageAdder />+ <PageDisplay />+ </CommandProvider>+ )+ })++ await waitFor(() => {+ expect(screen.getByTestId('current-page')).toHaveTextContent('Page one')+ })++ act(() => {+ userEvent.click(screen.getByRole('button'))+ })+ await waitFor(() => {+ expect(screen.getByTestId('current-page')).toHaveTextContent('[None]')+ })+ })++ it('unregisters and reregisters a page if disabled toggled', async () => {+ act(() => {+ render(+ <CommandProvider>+ <TogglePageEnabled />+ <PageDisplay />+ </CommandProvider>+ )+ })++ await waitFor(() => {+ expect(screen.getByTestId('current-page')).toHaveTextContent('Page one')+ })++ act(() => {+ userEvent.click(screen.getByRole('button'))+ })+ await waitFor(() => {+ expect(screen.getByTestId('current-page')).toHaveTextContent('[None]')+ })++ act(() => {+ userEvent.click(screen.getByRole('button'))+ })+ await waitFor(() => {+ expect(screen.getByTestId('current-page')).toHaveTextContent('Page one')+ })+ })+})diff --git a/packages/ui-patterns/CommandMenu/api/hooks/pagesHooks.ts b/packages/ui-patterns/CommandMenu/api/hooks/pagesHooks.tsnew file mode 100644index 00000000000..9136ef3d474--- /dev/null+++ b/packages/ui-patterns/CommandMenu/api/hooks/pagesHooks.ts@@ -0,0 +1,94 @@+import { isEqual } from 'lodash'+import { useEffect, useMemo, useRef } from 'react'+import { useSnapshot } from 'valtio'++import { useCommandContext } from '../../internal/Context'+import { type PageDefinition, isComponentPage } from '../../internal/state/pagesState'+import { useSetQuery } from './queryHooks'++const useCurrentPage = () => {+ const { pagesState } = useCommandContext()+ const { commandPages, pageStack } = useSnapshot(pagesState)++ const topOfStack = pageStack.at(-1)+ const result = useMemo(+ () =>+ topOfStack && commandPages[topOfStack]+ ? { ...commandPages[topOfStack], name: topOfStack }+ : undefined,+ [commandPages, topOfStack]+ )++ return result+}++const usePageComponent = () => {+ const _currentPage = useCurrentPage()++ const currentPage = _currentPage as PageDefinition+ if (!currentPage || !isComponentPage(currentPage)) return undefined++ return currentPage.component+}++const useSetPage = () => {+ const { pagesState } = useCommandContext()+ const setQuery = useSetQuery()++ return (name: string, preserveQuery: boolean = false) => {+ pagesState.appendPageStack(name)+ if (!preserveQuery) setQuery('')+ }+}++const usePopPage = () => {+ const { pagesState } = useCommandContext()+ const { popPageStack } = useSnapshot(pagesState)++ return popPageStack+}++const EMPTY_ARRAY = [] as any[]++const useRegisterPage = (+ name: string,+ definition: PageDefinition,+ { deps = EMPTY_ARRAY, enabled = true }: { deps?: any[]; enabled?: boolean } = {}+) => {+ const { pagesState } = useCommandContext()+ const { registerNewPage } = useSnapshot(pagesState)++ const prevDeps = useRef(deps)+ const prevEnabled = useRef(enabled)++ const unsubscribe = useRef<() => void>()++ /**+ * useEffect handles the registration on first render, since React runs the+ * first render twice in development. (Otherwise the first render would leave+ * a dangling subscription.)+ *+ * It also handles final cleanup, since useMemo can't do this.+ *+ * useMemo handles the registration on subsequent renders, to ensure it+ * happens synchronously.+ */+ useMemo(() => {+ if (!isEqual(prevDeps.current, deps) || prevEnabled.current !== enabled) {+ unsubscribe.current?.()++ unsubscribe.current = enabled ? registerNewPage(name, definition) : undefined++ prevDeps.current = deps+ prevEnabled.current = enabled+ }+ }, [registerNewPage, name, definition, deps, enabled])++ useEffect(() => {+ unsubscribe.current = enabled ? registerNewPage(name, definition) : undefined++ return () => unsubscribe.current?.()+ }, [])+}++export { useCurrentPage, useRegisterPage, useSetPage, usePopPage, usePageComponent }diff --git a/packages/ui-patterns/CommandMenu/api/hooks/queryHooks.ts b/packages/ui-patterns/CommandMenu/api/hooks/queryHooks.tsnew file mode 100644index 00000000000..6cde00a9e5b--- /dev/null+++ b/packages/ui-patterns/CommandMenu/api/hooks/queryHooks.ts@@ -0,0 +1,17 @@+import { useSnapshot } from 'valtio'++import { useCommandContext } from '../../internal/Context'++const useQuery = () => {+ const { queryState } = useCommandContext()+ const { query } = useSnapshot(queryState)+ return query+}++const useSetQuery = () => {+ const { queryState } = useCommandContext()+ const { setQuery } = useSnapshot(queryState)+ return setQuery+}++export { useQuery, useSetQuery }diff --git a/packages/ui-patterns/CommandMenu/api/hooks/viewHooks.ts b/packages/ui-patterns/CommandMenu/api/hooks/viewHooks.tsnew file mode 100644index 00000000000..85e0c9560d4--- /dev/null+++ b/packages/ui-patterns/CommandMenu/api/hooks/viewHooks.ts@@ -0,0 +1,70 @@+import { useLayoutEffect, useRef } from 'react'+import { useSnapshot } from 'valtio'++import { useCommandContext } from '../../internal/Context'+import { type DialogSize } from '../../internal/state/viewState'++const useCommandMenuInitiated = () => {+ const { viewState } = useCommandContext()+ const { initiated } = useSnapshot(viewState)+ return initiated+}++const useCommandMenuVisible = () => {+ const { viewState } = useCommandContext()+ const { open } = useSnapshot(viewState)+ return open+}++const useSetCommandMenuOpen = () => {+ const { viewState } = useCommandContext()+ const { setOpen } = useSnapshot(viewState)+ return setOpen+}++const useToggleCommandMenu = () => {+ const { viewState } = useCommandContext()+ const { toggleOpen } = useSnapshot(viewState)+ return toggleOpen+}++const useIsCommandNavigating = () => {+ const { viewState } = useCommandContext()+ const { isNavigating } = useSnapshot(viewState)+ return isNavigating+}++const useSetIsCommandNavigating = () => {+ const { viewState } = useCommandContext()+ const { setIsNavigating } = useSnapshot(viewState)+ return setIsNavigating+}++const useCommandMenuSize = () => {+ const { viewState } = useCommandContext()+ const { size } = useSnapshot(viewState)+ return size+}++const useSetCommandMenuSize = (newSize: DialogSize) => {+ const { viewState } = useCommandContext()+ const { setSize, size } = useSnapshot(viewState)++ const originalSize = useRef(size)++ useLayoutEffect(() => {+ setSize(newSize)+ return () => setSize(originalSize.current)+ }, [setSize])+}++export {+ useCommandMenuInitiated,+ useCommandMenuVisible,+ useSetCommandMenuOpen,+ useToggleCommandMenu,+ useIsCommandNavigating,+ useSetIsCommandNavigating,+ useCommandMenuSize,+ useSetCommandMenuSize,+}diff --git a/packages/ui-patterns/CommandMenu/api/types.ts b/packages/ui-patterns/CommandMenu/api/types.tsnew file mode 100644index 00000000000..4021f8266a1--- /dev/null+++ b/packages/ui-patterns/CommandMenu/api/types.ts@@ -0,0 +1,2 @@+export type { ICommand } from '../internal/Command'+export type { CommandOptions } from '../internal/state/commandsState'diff --git a/packages/ui-patterns/CommandMenu/api/utils.ts b/packages/ui-patterns/CommandMenu/api/utils.tsnew file mode 100644index 00000000000..491708a8436--- /dev/null+++ b/packages/ui-patterns/CommandMenu/api/utils.ts@@ -0,0 +1 @@+export { PageType } from '../internal/state/pagesState'diff --git a/packages/ui-patterns/CommandMenu/internal/Context.tsx b/packages/ui-patterns/CommandMenu/internal/Context.tsxnew file mode 100644index 00000000000..4c28b7dc527--- /dev/null+++ b/packages/ui-patterns/CommandMenu/internal/Context.tsx@@ -0,0 +1,24 @@+import { createContext, useContext } from 'react'++import { type ICommandsState } from '../internal/state/commandsState'+import { type IPagesState } from '../internal/state/pagesState'+import { type IQueryState } from '../internal/state/queryState'+import { type IViewState } from '../internal/state/viewState'++const CommandContext = createContext<+ | {+ commandsState: ICommandsState+ pagesState: IPagesState+ queryState: IQueryState+ viewState: IViewState+ }+ | undefined+>(undefined)++const useCommandContext = () => {+ const ctx = useContext(CommandContext)+ if (!ctx) throw Error('`useCommandContext` must be used within a `CommandProvider`')+ return ctx+}++export { CommandContext, useCommandContext }diff --git a/packages/ui-patterns/package.json b/packages/ui-patterns/package.jsonindex 94774c28bfe..cdce0f619bf 100644--- a/packages/ui-patterns/package.json+++ b/packages/ui-patterns/package.json@@ -32,9 +32,16 @@"valtio": "*"},"devDependencies": {+ "@supabase/auth-helpers-react": "^0.4.2",+ "@testing-library/dom": "^10.1.0",+ "@testing-library/react": "^16.0.0",+ "@testing-library/user-event": "^13.5.0","@types/common-tags": "^1.8.4",+ "@types/react": "^18.3.3",+ "@types/react-dom": "^18.3.0","api-types": "*","jest": "^29.7.0",+ "jest-environment-jsdom": "^29.7.0","ts-jest": "^29.1.2"},"peerDependencies": {diff --git a/packages/ui-patterns/tsconfig.json b/packages/ui-patterns/tsconfig.jsonindex f214f6e2ac1..a87fac9dc9b 100644--- a/packages/ui-patterns/tsconfig.json+++ b/packages/ui-patterns/tsconfig.json@@ -12,4 +12,4 @@"build","node_modules"]-}\ No newline at end of file+}