Skip to content
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

feat(sanity): refine error UI #7520

Merged
merged 6 commits into from
Sep 24, 2024
Merged
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
4 changes: 2 additions & 2 deletions packages/@sanity/types/src/transactionLog/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export interface TransactionLogEventWithEffects extends TransactionLogEvent {
*/
export interface TransactionLogEventWithMutations extends TransactionLogEvent {
/**
* Array of mutations that occured in this transaction. Note that the transaction
* Array of mutations that occurred in this transaction. Note that the transaction
* log has an additional mutation type not typically seen in other APIs;
* `createSquashed` ({@link CreateSquashedMutation}).
*/
Expand Down Expand Up @@ -83,7 +83,7 @@ export interface CreateSquashedMutation {
createdAt: string

/**
* The document as it exists after squashing has occured
* The document as it exists after squashing has occurred
*/
document: {
_id: string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export class VisionErrorBoundary extends Component<
/>
</div>

<Heading>An error occured</Heading>
<Heading>An error occurred</Heading>

<Card border radius={2} overflow="auto" padding={4} tone="inherit">
<Stack space={4}>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import {CopyIcon, SyncIcon} from '@sanity/icons'
import {Inline} from '@sanity/ui'
import {type ComponentProps, type ComponentType} from 'react'

import {Button, Tooltip} from '../../../ui-components'
import {strings} from './strings'
import {useCopyErrorDetails} from './useCopyErrorDetails'

/**
* @internal
*/
export interface ErrorActionsProps extends Pick<ComponentProps<typeof Button>, 'size'> {
error: unknown
eventId: string | null
onRetry?: () => void
}

/**
* @internal
*/
export const ErrorActions: ComponentType<ErrorActionsProps> = ({error, eventId, onRetry, size}) => {
const copyErrorDetails = useCopyErrorDetails(error, eventId)

return (
<Inline space={3}>
{onRetry && (
<Button
onClick={onRetry}
text={strings['retry.title']}
tone="primary"
icon={SyncIcon}
size={size}
/>
)}
<Tooltip content={strings['copy-error-details.description']}>
<Button
onClick={copyErrorDetails}
text={strings['copy-error-details.title']}
tone="default"
mode="ghost"
icon={CopyIcon}
size={size}
/>
</Tooltip>
</Inline>
)
}
3 changes: 3 additions & 0 deletions packages/sanity/src/core/components/errorActions/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './ErrorActions'
export * from './types'
export * from './useCopyErrorDetails'
10 changes: 10 additions & 0 deletions packages/sanity/src/core/components/errorActions/strings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// These strings are not internationalized because `ErrorActions` is used inside
// `StudioErrorBoundary`, which is rendered outside of `LocaleProvider`.
export const strings = {
'retry.title': 'Retry',
'copy-error-details.description': 'These technical details may be useful for developers.',
'copy-error-details.title': 'Copy error details',
'copy-error-details.toast.get-failed': 'Failed to get error details',
'copy-error-details.toast.copy-failed': 'Failed to copy error details',
'copy-error-details.toast.succeeded': 'Copied error details to clipboard',
} as const
7 changes: 7 additions & 0 deletions packages/sanity/src/core/components/errorActions/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* @internal
*/
export interface ErrorWithId {
error: unknown
eventId?: string | null
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import {describe, expect, it} from '@jest/globals'
import {firstValueFrom, map, of} from 'rxjs'

import {type ErrorWithId} from './types'
import {serializeError} from './useCopyErrorDetails'

describe('serializeError', () => {
it('includes error properties if an instance of `Error` is provided', async () => {
const error = await reassembleError({
error: new Error('Test', {
cause: 'Unit test',
}),
})

expect((error.error as any).message).toBe('Test')
expect((error.error as any).cause).toBe('Unit test')
})

it('includes record-like errors', async () => {
const error = await reassembleError({
error: {
someProperty: 'someValue',
},
})

expect((error.error as any).someProperty).toBe('someValue')
})

const nonRecordCases = [123, 'someString', ['some', 'array'], Symbol('Some error')]

it.each(nonRecordCases)('does not include non-record errors', async (errorCase) => {
const {error} = await reassembleError({
error: errorCase,
})
expect(error).toBeUndefined()
})

it('includes event id if one is provided', async () => {
const {eventId} = await reassembleError({
error: new Error(),
eventId: '123',
})

expect(eventId).toBe('123')
})
})

/**
* Helper that serializes and then immediately deserializes the provided error so that assertions
* about the serialization process can be made.
*/
function reassembleError(error: ErrorWithId): Promise<ErrorWithId> {
return firstValueFrom(
of(error).pipe(
serializeError(),
map((serializedError) => JSON.parse(serializedError)),
),
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import {useToast} from '@sanity/ui'
import {pick} from 'lodash'
import {useCallback} from 'react'
import {catchError, EMPTY, map, of, type OperatorFunction, tap} from 'rxjs'

import {isRecord} from '../../util'
import {strings} from './strings'
import {type ErrorWithId} from './types'

const TOAST_ID = 'copyErrorDetails'

/**
* @internal
*/
export function useCopyErrorDetails(error: unknown, eventId?: string | null): () => void {
const toast = useToast()

return useCallback(() => {
of<ErrorWithId>({error, eventId})
.pipe(
serializeError(),
catchError((serializeErrorError) => {
console.error(serializeErrorError)
toast.push({
status: 'error',
title: strings['copy-error-details.toast.get-failed'],
id: TOAST_ID,
})
return EMPTY
}),
tap((errorDetailsString) => {
navigator.clipboard.writeText(errorDetailsString)
toast.push({
status: 'success',
title: strings['copy-error-details.toast.succeeded'],
id: TOAST_ID,
})
}),
catchError((copyErrorError) => {
console.error(copyErrorError)
toast.push({
status: 'error',
title: strings['copy-error-details.toast.copy-failed'],
id: TOAST_ID,
})
return EMPTY
}),
)
.subscribe()
}, [error, eventId, toast])
}

/**
* @internal
*/
export function serializeError(): OperatorFunction<ErrorWithId, string> {
return map<ErrorWithId, string>(({error, eventId}) => {
// Extract the non-enumerable properties of the provided `error` object. This is particularly
// useful if the provided `error` value is an instance of `Error`, whose properties are
// non-enumerable.
const errorInfo = isRecord(error) ? pick(error, Object.getOwnPropertyNames(error)) : undefined
return JSON.stringify({error: errorInfo, eventId}, null, 2)
})
}
1 change: 1 addition & 0 deletions packages/sanity/src/core/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export * from './contextMenuButton'
export * from './DefaultDocument'
export * from './documentStatus'
export * from './documentStatusIndicator'
export * from './errorActions'
export * from './globalErrorHandler'
export * from './hookCollection'
export * from './Hotkeys'
Expand Down
75 changes: 40 additions & 35 deletions packages/sanity/src/core/studio/StudioErrorBoundary.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
/* eslint-disable i18next/no-literal-string */
/* eslint-disable @sanity/i18n/no-attribute-string-literals */
import {
Box,
Card,
Code,
Container,
ErrorBoundary,
type ErrorBoundaryProps,
Heading,
Stack,
Text,
} from '@sanity/ui'
import {type ErrorInfo, type ReactNode, useCallback, useState} from 'react'
import {type ComponentType, type ErrorInfo, type ReactNode, useCallback, useState} from 'react'
import {ErrorActions, isDev, isProd} from 'sanity'
import {styled} from 'styled-components'
import {useHotModuleReload} from 'use-hot-module-reload'

import {Button} from '../../ui-components'
import {SchemaError} from '../config'
import {errorReporter} from '../error/errorReporter'
import {CorsOriginError} from '../store'
Expand Down Expand Up @@ -42,15 +45,17 @@ const INITIAL_STATE = {
eventId: null,
} satisfies ErrorBoundaryState

export function StudioErrorBoundary({
const View = styled(Box)`
align-items: center;
`

export const StudioErrorBoundary: ComponentType<StudioErrorBoundaryProps> = ({
children,
heading = 'An error occured',
}: StudioErrorBoundaryProps) {
heading = 'An error occurred',
}) => {
const [{error, eventId}, setError] = useState<ErrorBoundaryState>(INITIAL_STATE)

const message = isRecord(error) && typeof error.message === 'string' && error.message
const stack = isRecord(error) && typeof error.stack === 'string' && error.stack

const handleResetError = useCallback(() => setError(INITIAL_STATE), [])
const handleCatchError: ErrorBoundaryProps['onCatch'] = useCallback((params) => {
const report = errorReporter.reportError(params.error, {
Expand Down Expand Up @@ -80,37 +85,37 @@ export function StudioErrorBoundary({
}

return (
<Card
height="fill"
overflow="auto"
paddingY={[4, 5, 6, 7]}
paddingX={4}
sizing="border"
tone="critical"
>
<Container width={3}>
<Stack space={4}>
{/* TODO: better error boundary */}

<Heading>{heading}</Heading>

<div>
<Button onClick={handleResetError} text="Retry" tone="default" />
</div>

<Card border radius={2} overflow="auto" padding={4} tone="inherit">
<Card height="fill" overflow="auto" paddingY={[4, 5, 6, 7]} paddingX={4} sizing="border">
<View display="flex" height="fill">
<Container width={3}>
<Stack space={6}>
<Stack space={4}>
{message && (
<Code size={1}>
<strong>Error: {message}</strong>
</Code>
<Heading>{heading}</Heading>
<Text>An error occurred that Sanity Studio was unable to recover from.</Text>
{isProd && (
<Text>
<strong>To report this error,</strong> copy the error details and share them with
your development team or Sanity Support.
</Text>
)}
{isDev && (
<Card border radius={2} overflow="auto" padding={4} tone="critical">
<Stack space={4}>
{message && (
<Code size={1}>
<strong>Error: {message}</strong>
</Code>
)}
{stack && <Code size={1}>{stack}</Code>}
{eventId && <Code size={1}>Event ID: {eventId}</Code>}
</Stack>
</Card>
)}
{stack && <Code size={1}>{stack}</Code>}
{eventId && <Code size={1}>Event ID: {eventId}</Code>}
</Stack>
</Card>
</Stack>
</Container>
<ErrorActions error={error} eventId={eventId} onRetry={handleResetError} size="large" />
</Stack>
</Container>
</View>
</Card>
)
}
2 changes: 0 additions & 2 deletions packages/sanity/src/structure/i18n/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,8 +320,6 @@ const structureLocaleStrings = defineLocalesResources('structure', {
'panes.document-header-title.new.text': 'New {{schemaType}}',
/** The text used in the document header title if no other title can be determined */
'panes.document-header-title.untitled.text': 'Untitled',
/** The text for the retry button on the document list pane */
'panes.document-list-pane.error.retry-button.text': 'Retry',
/** The error text on the document list pane */
'panes.document-list-pane.error.text': 'Error: <Code>{{error}}</Code>',
/** The error title on the document list pane */
Expand Down
Loading
Loading