Skip to content

feat(react): create useSendIntent hook #595

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/react/src/_exports/sdk-react.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export {
useNavigateToStudioDocument,
} from '../hooks/dashboard/useNavigateToStudioDocument'
export {useRecordDocumentHistoryEvent} from '../hooks/dashboard/useRecordDocumentHistoryEvent'
export {useSendIntent} from '../hooks/dashboard/useSendIntent'
export {useStudioWorkspacesByProjectIdDataset} from '../hooks/dashboard/useStudioWorkspacesByProjectIdDataset'
export {useDatasets} from '../hooks/datasets/useDatasets'
export {useApplyDocumentActions} from '../hooks/document/useApplyDocumentActions'
Expand Down
121 changes: 121 additions & 0 deletions packages/react/src/hooks/dashboard/useSendIntent.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import {type DocumentHandle} from '@sanity/sdk'
import {renderHook} from '@testing-library/react'
import {beforeEach, describe, expect, it, vi} from 'vitest'

import {useSendIntent} from './useSendIntent'

// Mock the useWindowConnection hook
const mockSendMessage = vi.fn()
vi.mock('../comlink/useWindowConnection', () => ({
useWindowConnection: vi.fn(() => ({
sendMessage: mockSendMessage,
})),
}))

describe('useSendIntent', () => {
const mockDocumentHandle: DocumentHandle = {
documentId: 'test-document-id',
documentType: 'test-document-type',
projectId: 'test-project-id',
dataset: 'test-dataset',
}

beforeEach(() => {
vi.clearAllMocks()
// Reset mock implementation to default behavior
mockSendMessage.mockImplementation(() => {})
})

it('should return sendIntent function', () => {
const {result} = renderHook(() => useSendIntent({documentHandle: mockDocumentHandle}))

expect(result.current).toEqual({
sendIntent: expect.any(Function),
})
})

it('should send intent message when sendIntent is called', () => {
const {result} = renderHook(() => useSendIntent({documentHandle: mockDocumentHandle}))

result.current.sendIntent()

expect(mockSendMessage).toHaveBeenCalledWith('dashboard/v1/events/intents/send-intent', {
document: {
id: 'test-document-id',
type: 'test-document-type',
},
resource: {
id: 'test-project-id.test-dataset',
},
})
})

it('should handle errors gracefully', () => {
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
mockSendMessage.mockImplementation(() => {
throw new Error('Test error')
})

const {result} = renderHook(() => useSendIntent({documentHandle: mockDocumentHandle}))

expect(() => result.current.sendIntent()).toThrow('Test error')
expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to send intent:', expect.any(Error))

consoleErrorSpy.mockRestore()
})

it('should use memoized sendIntent function', () => {
const {result, rerender} = renderHook(({params}) => useSendIntent(params), {
initialProps: {params: {documentHandle: mockDocumentHandle}},
})

const firstSendIntent = result.current.sendIntent

// Rerender with the same params
rerender({params: {documentHandle: mockDocumentHandle}})

expect(result.current.sendIntent).toBe(firstSendIntent)
})

it('should create new sendIntent function when documentHandle changes', () => {
const {result, rerender} = renderHook(({params}) => useSendIntent(params), {
initialProps: {params: {documentHandle: mockDocumentHandle}},
})

const firstSendIntent = result.current.sendIntent

const newDocumentHandle: DocumentHandle = {
documentId: 'new-document-id',
documentType: 'new-document-type',
projectId: 'new-project-id',
dataset: 'new-dataset',
}

rerender({params: {documentHandle: newDocumentHandle}})

expect(result.current.sendIntent).not.toBe(firstSendIntent)
})

it('should send intent message with params when provided', () => {
const intentParams = {view: 'editor', tab: 'content'}
const {result} = renderHook(() =>
useSendIntent({
documentHandle: mockDocumentHandle,
params: intentParams,
}),
)

result.current.sendIntent()

expect(mockSendMessage).toHaveBeenCalledWith('dashboard/v1/events/intents/send-intent', {
document: {
id: 'test-document-id',
type: 'test-document-type',
},
resource: {
id: 'test-project-id.test-dataset',
},
params: intentParams,
})
})
})
132 changes: 132 additions & 0 deletions packages/react/src/hooks/dashboard/useSendIntent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'
import {type DocumentHandle, type FrameMessage} from '@sanity/sdk'
import {useCallback} from 'react'

import {useWindowConnection} from '../comlink/useWindowConnection'

/**
* Message type for sending intents to the dashboard
* @internal
*/
export interface IntentMessage {
type: 'dashboard/v1/events/intents/send-intent'
data: {
intentName?: string
document: {
id: string
type: string
}
resource?: {
id: string
}
params?: Record<string, string>
}
}

/**
* Return type for the useSendIntent hook
* @public
*/
interface SendIntent {
sendIntent: () => void
}

/**
* Parameters for the useSendIntent hook
* @public
*/
interface UseSendIntentParams {
intentName?: string
documentHandle: DocumentHandle
params?: Record<string, string>
}

/**
* @public
*
* A hook for sending intent messages to the Dashboard with a document handle.
* This allows applications to signal intent for specific documents to the Dashboard.
*
* @param params - Object containing:
* - `intentName` - Optional specific name of the intent to send
* - `documentHandle` - The document handle containing document ID, type, project ID and dataset, like `{documentId: '123', documentType: 'book', projectId: 'abc123', dataset: 'production'}`
* - `params` - Optional parameters to include in the intent
* @returns An object containing:
* - `sendIntent` - Function to send the intent message
*
* @example
* ```tsx
* import {useSendIntent} from '@sanity/sdk-react'
* import {Button} from '@sanity/ui'
* import {Suspense} from 'react'
*
* function SendIntentButton({documentId, documentType, projectId, dataset}) {
* const {sendIntent} = useSendIntent({
* intentName: 'edit-document',
* documentHandle: {documentId, documentType, projectId, dataset},
* params: {view: 'editor'}
* })
*
* return (
* <Button
* onClick={() => sendIntent()}
* text="Send Intent"
* />
* )
* }
*
* // Wrap the component with Suspense since the hook may suspend
* function MyComponent({documentId, documentType, projectId, dataset}) {
* return (
* <Suspense fallback={<Button text="Loading..." disabled />}>
* <SendIntentButton
* documentId={documentId}
* documentType={documentType}
* projectId={projectId}
* dataset={dataset}
* />
* </Suspense>
* )
* }
* ```
*/
export function useSendIntent(params: UseSendIntentParams): SendIntent {
const {intentName, documentHandle, params: intentParams} = params
const {sendMessage} = useWindowConnection<IntentMessage, FrameMessage>({
name: SDK_NODE_NAME,
connectTo: SDK_CHANNEL_NAME,
})

const sendIntent = useCallback(() => {
try {
const {projectId, dataset} = documentHandle

const message: IntentMessage = {
type: 'dashboard/v1/events/intents/send-intent',
data: {
...(intentName ? {intentName} : {}),
...{
document: {
id: documentHandle.documentId,
type: documentHandle.documentType,
},
resource: {
id: `${projectId}.${dataset}`,
},
},
...(intentParams && Object.keys(intentParams).length > 0 ? {params: intentParams} : {}),
},
}

sendMessage(message.type, message.data)
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to send intent:', error)
throw error
}
}, [intentName, documentHandle, intentParams, sendMessage])

return {
sendIntent,
}
}
Loading