Skip to content

Commit

Permalink
[field] Treat empty arrays as null/undefined values for changes
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Oct 6, 2020
1 parent 4de838e commit 2253183
Showing 1 changed file with 33 additions and 20 deletions.
53 changes: 33 additions & 20 deletions packages/@sanity/field/src/diff/changes/buildChangeList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export function buildChangeList(
}
}

return [getFieldChange(schemaType, diff, path, titlePath, context)]
return getFieldChange(schemaType, diff, path, titlePath, context)
}

export function buildObjectChangeList(
Expand Down Expand Up @@ -195,7 +195,7 @@ export function buildArrayChangeList(

if (children.length === 0) {
// This can happen when there are no changes to the actual element, it's just been moved
acc.push(getFieldChange(memberType, itemDiff.diff, itemPath, itemTitlePath, itemContext))
acc.push(...getFieldChange(memberType, itemDiff.diff, itemPath, itemTitlePath, itemContext))
} else {
acc.push(...children)
}
Expand Down Expand Up @@ -224,14 +224,21 @@ function getFieldChange(
path: Path,
titlePath: ChangeTitlePath,
{itemDiff, parentDiff}: DiffContext = {}
): FieldChangeNode {
): FieldChangeNode[] {
const {fromValue, toValue, type} = diff

// Treat undefined => [] as no change
if (type === 'array' && isEmpty(fromValue) && isEmpty(toValue)) {
return []
}

let error
if (typeof diff.fromValue !== 'undefined') {
error = getValueError(diff.fromValue, schemaType)
if (typeof fromValue !== 'undefined') {
error = getValueError(fromValue, schemaType)
}

if (!error && typeof diff.toValue !== 'undefined') {
error = getValueError(diff.toValue, schemaType)
if (!error && typeof toValue !== 'undefined') {
error = getValueError(toValue, schemaType)
}

let showHeader: DiffComponentOptions['showHeader'] = ShowDiffHeader.Always
Expand All @@ -243,19 +250,21 @@ function getFieldChange(
component = typeof diffComponent === 'function' ? diffComponent : diffComponent.component
}

return {
type: 'field',
diff,
path,
error,
itemDiff,
parentDiff,
titlePath,
schemaType,
showHeader,
key: pathToString(path) || 'root',
diffComponent: error ? undefined : component
}
return [
{
type: 'field',
diff,
path,
error,
itemDiff,
parentDiff,
titlePath,
schemaType,
showHeader,
key: pathToString(path) || 'root',
diffComponent: error ? undefined : component
}
]
}

function reduceTitlePaths(changes: ChangeNode[], byLength = 1): ChangeNode[] {
Expand All @@ -264,3 +273,7 @@ function reduceTitlePaths(changes: ChangeNode[], byLength = 1): ChangeNode[] {
return change
})
}

function isEmpty(item: unknown): boolean {
return (Array.isArray(item) && item.length === 0) || item === null || typeof item === 'undefined'
}

0 comments on commit 2253183

Please sign in to comment.