Skip to content

Commit

Permalink
feat(structure): add ability to override the tool's canHandleIntent l…
Browse files Browse the repository at this point in the history
…ogic
  • Loading branch information
marcusforsberg committed Oct 11, 2024
1 parent e3cc6d5 commit ab49713
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
18 changes: 13 additions & 5 deletions packages/sanity/src/structure/structureTool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,7 @@ export const structureTool = definePlugin<StructureToolOptions | void>((options)
title: options?.title || 'Structure',
icon,
component: lazy(() => import('./components/structureTool')),
canHandleIntent: (intent, params) => {
if (intent === 'create') return canHandleCreateIntent(params)
if (intent === 'edit') return canHandleEditIntent(params)
return false
},
canHandleIntent: options?.canHandleIntent || canHandleIntent,
getIntentState,
// Controlled by sanity/src/structure/components/structureTool/StructureTitle.tsx
controlsDocumentTitle: true,
Expand All @@ -125,6 +121,18 @@ export const structureTool = definePlugin<StructureToolOptions | void>((options)
}
})

/**
* The default implementation of the `canHandleIntent` function for the Structure Tool.
*/
export function canHandleIntent(
intent: string,
params: Record<string, unknown>,
): boolean | {[key: string]: boolean} {
if (intent === 'create') return canHandleCreateIntent(params)
if (intent === 'edit') return canHandleEditIntent(params)
return false
}

function canHandleCreateIntent(params: Record<string, unknown>) {
// We can't handle create intents without a `type` parameter
if (!('type' in params)) {
Expand Down
22 changes: 22 additions & 0 deletions packages/sanity/src/structure/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
type I18nTextRecord,
type InitialValueTemplateItem,
type LocaleSource,
type Tool,
} from 'sanity'

import {
Expand Down Expand Up @@ -147,6 +148,27 @@ export interface StructureToolOptions {
* The title that will be displayed for the tool. Defaults to Structure
*/
title?: string
/**
* Determines whether the tool can handle the given intent.
* By default, the Structure tool can handle create and edit intents for all document types.
* This function can be used to override this behavior; for example you could have multiple
* Structure tools in the same workspace, each handling intents for different document types.
*
* @example
* ```ts
* // This Structure Tool only wants to handle intents for "author" documents
* structureTool({
* title: 'Authors',
* name: 'authors',
* canHandleIntent: (intent, params) => {
* if (params.type !== 'author') return false
*
* return canHandleIntent(intent, params)
* },
* })
* ```
*/
canHandleIntent?: Tool['canHandleIntent']
}

/**
Expand Down

0 comments on commit ab49713

Please sign in to comment.