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

refactor(portable-text-editor): automatically resolve some validation errors #6705

Merged
merged 13 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
3 changes: 2 additions & 1 deletion packages/@sanity/portable-text-editor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
"build": "pkg-utils build --strict --check --clean",
"check:types": "tsc --project tsconfig.lib.json",
"clean": "rimraf lib",
"dev": "cd ./e2e-tests/ && ts-node serve",
"dev": "cd ./e2e-tests/ && tsx serve",
"lint": "eslint .",
"prepublishOnly": "turbo run build",
"prettier": "prettier --write './**/*.{ts,tsx,js,css,html}'",
Expand Down Expand Up @@ -97,6 +97,7 @@
"rimraf": "^3.0.2",
"rxjs": "^7.8.1",
"styled-components": "^6.1.11",
"tsx": "^4.10.3",
"vite": "^4.5.3"
},
"peerDependencies": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,19 +330,12 @@ describe('initialization', () => {
await waitFor(() => {
if (editorRef.current) {
expect(onChange).toHaveBeenCalledWith({
type: 'invalidValue',
value: initialValue,
resolution: {
action: 'Remove invalid marks',
description:
"Block with _key 'abc' contains marks (invalid) not supported by the current content model.",
item: {
_key: 'abc',
_type: 'myTestBlockType',
children: [{_key: 'def', _type: 'span', marks: ['invalid'], text: 'Test'}],
markDefs: [],
},
patches: [
{path: [{_key: 'abc'}, 'children', {_key: 'def'}, 'marks'], type: 'set', value: []},
],
i18n: {
action: 'inputs.portable-text.invalid-value.orphaned-marks.action',
description: 'inputs.portable-text.invalid-value.orphaned-marks.description',
Expand All @@ -351,26 +344,40 @@ describe('initialization', () => {
orphanedMarks: ['invalid'],
},
},
},
type: 'invalidValue',
value: [
{
_key: '123',
_type: 'myTestBlockType',
children: [{_key: '567', _type: 'span', marks: [], text: 'Hello'}],
markDefs: [],
},
{
item: {
_key: 'abc',
_type: 'myTestBlockType',
children: [{_key: 'def', _type: 'span', marks: ['invalid'], text: 'Test'}],
children: [
{
_key: 'def',
_type: 'span',
marks: ['invalid'],
text: 'Test',
},
],
markDefs: [],
},
],
patches: [
{
path: [
{
_key: 'abc',
},
'children',
{
_key: 'def',
},
'marks',
],
type: 'set',
value: [],
},
],
},
})
expect(onChange).not.toHaveBeenCalledWith({type: 'value', value: initialValue})
expect(onChange).toHaveBeenCalledWith({type: 'ready'})
}
})
expect(onChange).not.toHaveBeenCalledWith({type: 'value', value: initialValue})
expect(onChange).toHaveBeenCalledWith({type: 'ready'})
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import {describe, expect, it, jest} from '@jest/globals'
import {render, waitFor} from '@testing-library/react'
import {createRef, type RefObject} from 'react'

import {PortableTextEditor} from '../PortableTextEditor'
import {PortableTextEditorTester, schemaType} from './PortableTextEditorTester'

describe('when PTE would display warnings, instead it self solves', () => {
it('when child at index is missing required _key in block with _key', async () => {
const editorRef: RefObject<PortableTextEditor> = createRef()
const initialValue = [
{
_key: 'abc',
_type: 'myTestBlockType',
children: [
{
_type: 'span',
marks: [],
text: 'Hello with a new key',
},
],
markDefs: [],
style: 'normal',
},
]

const onChange = jest.fn()
render(
<PortableTextEditorTester
onChange={onChange}
ref={editorRef}
schemaType={schemaType}
value={initialValue}
/>,
)
await waitFor(() => {
expect(onChange).toHaveBeenCalledWith({type: 'value', value: initialValue})
expect(onChange).toHaveBeenCalledWith({type: 'ready'})
})
await waitFor(() => {
if (editorRef.current) {
expect(PortableTextEditor.getValue(editorRef.current)).toEqual([
{
_key: 'abc',
_type: 'myTestBlockType',
children: [
{
_key: '4',
_type: 'span',
text: 'Hello with a new key',
marks: [],
},
],
markDefs: [],
style: 'normal',
},
])
}
})
})
it('adds missing .markDefs', async () => {
const editorRef: RefObject<PortableTextEditor> = createRef()
const initialValue = [
{
_key: 'abc',
_type: 'myTestBlockType',
children: [
{
_key: 'def',
_type: 'span',
marks: [],
text: 'Hello with markDefs',
},
],
style: 'normal',
},
]

const onChange = jest.fn()
render(
<PortableTextEditorTester
onChange={onChange}
ref={editorRef}
schemaType={schemaType}
value={initialValue}
/>,
)
await waitFor(() => {
expect(onChange).toHaveBeenCalledWith({type: 'value', value: initialValue})
expect(onChange).toHaveBeenCalledWith({type: 'ready'})
})
await waitFor(() => {
if (editorRef.current) {
PortableTextEditor.focus(editorRef.current)
expect(PortableTextEditor.getValue(editorRef.current)).toEqual([
{
_key: 'abc',
_type: 'myTestBlockType',
children: [
{
_key: 'def',
_type: 'span',
text: 'Hello with markDefs',
marks: [],
},
],
markDefs: [],
style: 'normal',
},
])
}
})
})
skogsmaskin marked this conversation as resolved.
Show resolved Hide resolved
})
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,24 @@ export function useSyncValue(
if (hasChanges && isValid) {
const validationValue = [value[currentBlockIndex]]
const validation = validateValue(validationValue, schemaTypes, keyGenerator)
if (validation.valid) {
// Resolve validations that can be resolved automatically, without involving the user (but only if the value was changed)
if (
!validation.valid &&
validation.resolution?.autoResolve &&
validation.resolution?.patches.length > 0
) {
// Only apply auto resolution if the value has been populated before and is different from the last one.
if (!readOnly && previousValue.current && previousValue.current !== value) {
// Give a console warning about the fact that it did an auto resolution
console.warn(
`${validation.resolution.action} for block with _key '${validationValue[0]._key}'. ${validation.resolution?.description}`,
)
validation.resolution.patches.forEach((patch) => {
change$.next({type: 'patch', patch})
})
}
}
if (validation.valid || validation.resolution?.autoResolve) {
if (oldBlock._key === currentBlock._key) {
if (debug.enabled) debug('Updating block', oldBlock, currentBlock)
_updateBlock(slateEditor, currentBlock, oldBlock, currentBlockIndex)
Expand All @@ -168,7 +185,7 @@ export function useSyncValue(
'Validating and inserting new block in the end of the value',
currentBlock,
)
if (validation.valid) {
if (validation.valid || validation.resolution?.autoResolve) {
withPreserveKeys(slateEditor, () => {
Transforms.insertNodes(slateEditor, currentBlock, {
at: [currentBlockIndex],
Expand Down Expand Up @@ -255,6 +272,7 @@ function _replaceBlock(
withPreserveKeys(slateEditor, () => {
Transforms.insertNodes(slateEditor, currentBlock, {at: [currentBlockIndex]})
})
slateEditor.onChange()
if (selectionFocusOnBlock) {
Transforms.select(slateEditor, currentSelection)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ describe('plugin:withPortableTextMarksModel', () => {
focus: {path: [{_key: 'a'}, 'children', {_key: 'a1'}], offset: 0},
anchor: {path: [{_key: 'b'}, 'children', {_key: 'b1'}], offset: 1},
})
PortableTextEditor.toggleMark(editor, 'bold')
PortableTextEditor.toggleMark(editor, 'strong')
pedrobonamin marked this conversation as resolved.
Show resolved Hide resolved
const value = PortableTextEditor.getValue(editor)
expect(value).toMatchInlineSnapshot(`
Array [
Expand All @@ -215,7 +215,7 @@ describe('plugin:withPortableTextMarksModel', () => {
"_key": "a1",
"_type": "span",
"marks": Array [
"bold",
"strong",
],
"text": "123",
},
Expand All @@ -231,7 +231,7 @@ describe('plugin:withPortableTextMarksModel', () => {
"_key": "b1",
"_type": "span",
"marks": Array [
"bold",
"strong",
],
"text": "1",
},
Expand Down Expand Up @@ -287,7 +287,7 @@ describe('plugin:withPortableTextMarksModel', () => {
focus: {path: [{_key: 'a'}, 'children', {_key: 'a1'}], offset: 0},
anchor: {path: [{_key: 'a'}, 'children', {_key: 'a1'}], offset: 4},
})
PortableTextEditor.toggleMark(editor, 'bold')
PortableTextEditor.toggleMark(editor, 'strong')
expect(PortableTextEditor.getValue(editor)).toMatchInlineSnapshot(`
Array [
Object {
Expand All @@ -298,7 +298,7 @@ describe('plugin:withPortableTextMarksModel', () => {
"_key": "a1",
"_type": "span",
"marks": Array [
"bold",
"strong",
],
"text": "1234",
},
Expand All @@ -315,7 +315,7 @@ describe('plugin:withPortableTextMarksModel', () => {
focus: {path: [{_key: 'a'}, 'children', {_key: 'a1'}], offset: 1},
anchor: {path: [{_key: 'a'}, 'children', {_key: 'a1'}], offset: 3},
})
PortableTextEditor.toggleMark(editorRef.current, 'bold')
PortableTextEditor.toggleMark(editorRef.current, 'strong')
expect(PortableTextEditor.getValue(editorRef.current)).toMatchInlineSnapshot(`
Array [
Object {
Expand All @@ -326,7 +326,7 @@ describe('plugin:withPortableTextMarksModel', () => {
"_key": "a1",
"_type": "span",
"marks": Array [
"bold",
"strong",
],
"text": "1",
},
Expand All @@ -340,7 +340,7 @@ describe('plugin:withPortableTextMarksModel', () => {
"_key": "1",
"_type": "span",
"marks": Array [
"bold",
"strong",
],
"text": "4",
},
Expand All @@ -358,7 +358,7 @@ describe('plugin:withPortableTextMarksModel', () => {
focus: {path: [{_key: 'a'}, 'children', {_key: 'a1'}], offset: 0},
anchor: {path: [{_key: 'a'}, 'children', {_key: '1'}], offset: 1},
})
PortableTextEditor.toggleMark(editor, 'bold')
PortableTextEditor.toggleMark(editor, 'strong')
expect(PortableTextEditor.getValue(editor)).toMatchInlineSnapshot(`
Array [
Object {
Expand All @@ -369,7 +369,7 @@ Array [
"_key": "a1",
"_type": "span",
"marks": Array [
"bold",
"strong",
],
"text": "1234",
},
Expand Down Expand Up @@ -432,7 +432,7 @@ Array [
focus: {path: [{_key: 'a'}, 'children', {_key: 'a1'}], offset: 0},
anchor: {path: [{_key: 'a'}, 'children', {_key: 'b1'}], offset: 12},
})
PortableTextEditor.toggleMark(editor, 'bold')
PortableTextEditor.toggleMark(editor, 'strong')
expect(PortableTextEditor.getValue(editor)).toMatchInlineSnapshot(`
Array [
Object {
Expand All @@ -444,15 +444,15 @@ Array [
"_type": "span",
"marks": Array [
"abc",
"bold",
"strong",
],
"text": "A link",
},
Object {
"_key": "a2",
"_type": "span",
"marks": Array [
"bold",
"strong",
],
"text": ", not a link",
},
Expand Down Expand Up @@ -778,7 +778,7 @@ Array [
{
_key: 'a1',
_type: 'span',
marks: ['bold'],
marks: ['strong'],
text: '12',
},
{
Expand All @@ -788,7 +788,7 @@ Array [
text: '34',
},
],
markDefs: [{_key: 'bold', _type: 'strong'}],
markDefs: [{_key: 'strong', _type: 'strong'}],
style: 'normal',
},
]
Expand All @@ -811,9 +811,9 @@ Array [
focus: {path: [{_key: 'a'}, 'children', {_key: 'a1'}], offset: 0},
anchor: {path: [{_key: 'a'}, 'children', {_key: '2'}], offset: 2},
})
expect(PortableTextEditor.isMarkActive(editor, 'bold')).toBe(false)
PortableTextEditor.toggleMark(editor, 'bold')
expect(PortableTextEditor.isMarkActive(editor, 'bold')).toBe(true)
expect(PortableTextEditor.isMarkActive(editor, 'strong')).toBe(false)
PortableTextEditor.toggleMark(editor, 'strong')
expect(PortableTextEditor.isMarkActive(editor, 'strong')).toBe(true)
})
})

Expand Down
Loading
Loading