Skip to content
Open
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/block-tools/src/util/normalizeBlock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export function normalizeBlock(
annotations: [],
blockObjects: [],
inlineObjects: [],
nestedBlocks: [],
}

if (node._type !== (options.blockTypeName || 'block')) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,68 @@
import type {Schema} from '@portabletext/schema'
import type {FieldDefinition, OfDefinition, Schema} from '@portabletext/schema'
import type {ArraySchemaType, ObjectSchemaType, SchemaType} from '@sanity/types'
import type {PortableTextMemberSchemaTypes} from './portable-text-member-schema-types'

/**
* Safely get the `of` array from a schema type, returning undefined if
* the type doesn't have one or if accessing it throws (Sanity schema
* getters can throw on certain types).
*/
function safeGetOf(schemaType: SchemaType): readonly SchemaType[] | undefined {
try {
if (schemaType.jsonType === 'array') {
const arrayOf = (schemaType as ArraySchemaType).of
return Array.isArray(arrayOf) ? arrayOf : undefined
}
} catch {
// Sanity schema getters can throw — ignore
}
return undefined
}

function isBlockType(type: SchemaType): boolean {
if (type.type) {
return isBlockType(type.type)
}
return type.name === 'block'
}

function sanityFieldToOfDefinition(memberType: SchemaType): OfDefinition {
if (isBlockType(memberType)) {
return {type: 'block' as const}
}
const objectType = memberType as ObjectSchemaType
return {
type: objectType.name,
name: objectType.name,
title: objectType.title,
...(objectType.fields?.length
? {fields: objectType.fields.map(sanityFieldToFieldDefinition)}
: {}),
}
}

function sanityFieldToFieldDefinition(field: {
name: string
type: SchemaType
}): FieldDefinition {
const base: FieldDefinition = {
name: field.name,
type: field.type.jsonType as FieldDefinition['type'],
title: field.type.title,
}

// Carry `of` through on array fields
const ofMembers = safeGetOf(field.type)
if (ofMembers?.length) {
return {
...base,
of: ofMembers.map(sanityFieldToOfDefinition),
}
}

return base
}

/**
* @public
* Convert Sanity-specific schema types for Portable Text to a first-class
Expand All @@ -24,11 +86,7 @@ export function portableTextMemberSchemaTypesToSchema(
},
blockObjects: schema.blockObjects.map((blockObject) => ({
name: blockObject.name,
fields: blockObject.fields.map((field) => ({
name: field.name,
type: field.type.jsonType,
title: field.type.title,
})),
fields: blockObject.fields.map(sanityFieldToFieldDefinition),
title: blockObject.title,
})),
decorators: schema.decorators.map((decorator) => ({
Expand All @@ -38,13 +96,14 @@ export function portableTextMemberSchemaTypesToSchema(
})),
inlineObjects: schema.inlineObjects.map((inlineObject) => ({
name: inlineObject.name,
fields: inlineObject.fields.map((field) => ({
name: field.name,
type: field.type.jsonType,
title: field.type.title,
})),
fields: inlineObject.fields.map(sanityFieldToFieldDefinition),
title: inlineObject.title,
})),
nestedBlocks: schema.nestedBlocks.map((nestedBlock) => ({
name: nestedBlock.name,
fields: nestedBlock.fields.map(sanityFieldToFieldDefinition),
title: nestedBlock.title,
})),
span: {
name: schema.span.name,
},
Expand Down
72 changes: 72 additions & 0 deletions packages/sanity-bridge/src/portable-text-member-schema-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export type PortableTextMemberSchemaTypes = {
blockObjects: ObjectSchemaType[]
decorators: BlockDecoratorDefinition[]
inlineObjects: ObjectSchemaType[]
nestedBlocks: ObjectSchemaType[]
portableText: ArraySchemaType<PortableTextBlock>
span: ObjectSchemaType
styles: BlockStyleDefinition[]
Expand Down Expand Up @@ -67,6 +68,10 @@ export function createPortableTextMemberSchemaTypes(
const blockObjectTypes = (portableTextType.of?.filter(
(field) => field.name !== blockType.name,
) || []) as ObjectSchemaType[]

// Walk block object fields to find nested block types
const nestedBlockTypes = collectNestedBlockTypes(blockObjectTypes)

return {
styles: resolveEnabledStyles(blockType),
decorators: resolveEnabledDecorators(spanType),
Expand All @@ -76,10 +81,77 @@ export function createPortableTextMemberSchemaTypes(
portableText: portableTextType,
inlineObjects: inlineObjectTypes,
blockObjects: blockObjectTypes,
nestedBlocks: nestedBlockTypes,
annotations: (spanType as SpanSchemaType).annotations,
}
}

/**
* Safely get the `of` array from a schema type, returning undefined if
* the type doesn't have one or if accessing it throws (Sanity schema
* getters can throw on certain types).
*/
function safeGetOf(schemaType: SchemaType): readonly SchemaType[] | undefined {
try {
if (schemaType.jsonType === 'array') {
const arrayOf = (schemaType as ArraySchemaType).of
return Array.isArray(arrayOf) ? arrayOf : undefined
}
} catch {
// Sanity schema getters can throw — ignore
}
return undefined
}

/**
* Walk object types recursively to find objects that contain an array field
* whose `of` includes a block type. Those objects are "nested blocks" —
* they contain their own PTE content.
*/
function collectNestedBlockTypes(
objectTypes: ObjectSchemaType[],
): ObjectSchemaType[] {
const nestedBlocks: ObjectSchemaType[] = []
const seen = new Set<string>()

function walkObjectType(objectType: ObjectSchemaType) {
if (seen.has(objectType.name)) {
return
}
seen.add(objectType.name)

for (const field of objectType.fields ?? []) {
const ofMembers = safeGetOf(field.type)
if (ofMembers) {
for (const memberType of ofMembers) {
if (findBlockType(memberType)) {
// This object has an array-of-blocks field — it's a nested block
if (!nestedBlocks.some((nb) => nb.name === objectType.name)) {
nestedBlocks.push(objectType)
}
} else if (
memberType.jsonType === 'object' &&
memberType.name !== objectType.name
) {
walkObjectType(memberType as ObjectSchemaType)
}
}
} else if (
field.type.jsonType === 'object' &&
field.type.name !== objectType.name
) {
walkObjectType(field.type as ObjectSchemaType)
}
}
}

for (const objectType of objectTypes) {
walkObjectType(objectType)
}

return nestedBlocks
}

function resolveEnabledStyles(blockType: ObjectSchemaType) {
const styleField = blockType.fields?.find(
(btField) => btField.name === 'style',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ describe(sanitySchemaToPortableTextSchema.name, () => {
},
],
blockObjects: [],
nestedBlocks: [],
inlineObjects: [],
}

Expand Down Expand Up @@ -297,3 +298,75 @@ describe(sanitySchemaToPortableTextSchema.name, () => {
)
})
})

describe('nested blocks', () => {
test('table schema with nested block content', () => {
const tableCellType = defineType({
name: 'tableCell',
type: 'object',
fields: [
defineField({
name: 'content',
type: 'array',
of: [{type: 'block'}],
}),
defineField({
name: 'colspan',
type: 'number',
}),
],
})
const tableRowType = defineType({
name: 'tableRow',
type: 'object',
fields: [
defineField({
name: 'cells',
type: 'array',
of: [{type: 'tableCell'}],
}),
],
})
const tableType = defineType({
name: 'table',
type: 'object',
fields: [
defineField({
name: 'rows',
type: 'array',
of: [{type: 'tableRow'}],
}),
],
})
const portableTextType = defineType({
type: 'array',
name: 'body',
of: [{type: 'block', name: 'block'}, {type: 'table'}],
})

const sanitySchema = SanitySchema.compile({
types: [portableTextType, tableType, tableRowType, tableCellType],
})

const schema = sanitySchemaToPortableTextSchema(sanitySchema.get('body'))

// Table should be a block object
expect(schema.blockObjects.map((bo) => bo.name)).toContain('table')

// tableCell should be detected as a nested block (it contains array-of-blocks)
expect(schema.nestedBlocks.map((nb) => nb.name)).toContain('tableCell')

// tableCell should have content and colspan fields
const tableCell = schema.nestedBlocks.find((nb) => nb.name === 'tableCell')
expect(tableCell).toBeDefined()
expect(tableCell!.fields.map((f) => f.name)).toContain('content')
expect(tableCell!.fields.map((f) => f.name)).toContain('colspan')

// The content field should have of with a block type
const contentField = tableCell!.fields.find((f) => f.name === 'content')
expect(contentField).toBeDefined()
expect(contentField!.type).toBe('array')
expect(contentField!.of).toBeDefined()
expect(contentField!.of!.some((m) => m.type === 'block')).toBe(true)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,7 @@ describe(compileSchemaDefinitionToPortableTextMemberSchemaTypes.name, () => {
},
],
inlineObjects: [],
nestedBlocks: [],
span: {
name: 'span',
},
Expand Down
Loading
Loading