Create empty array on inserted structure containing an array

This commit is contained in:
Jos de Jong 2020-09-16 13:33:56 +02:00
parent 34534bba0c
commit ac078e445b
2 changed files with 52 additions and 6 deletions

View File

@ -5,7 +5,7 @@ import { getParentPath } from '../logic/selection.js'
import { getIn } from '../utils/immutabilityHelpers.js'
import { compileJSONPointer } from '../utils/jsonPointer.js'
import { findUniqueName } from '../utils/stringUtils.js'
import { isObjectOrArray } from '../utils/typeUtils.js'
import { isObject } from '../utils/typeUtils.js'
/**
* Create a JSONPatch for an insert operation.
@ -270,15 +270,17 @@ export function createNewValue (doc, selection, type) {
case 'array':
return []
case 'structure':
case 'structure': {
const parentPath = getParentPath(selection)
const parent = getIn(doc, parentPath)
if (Array.isArray(parent) && !isEmpty(parent)) {
const jsonExample = first(parent)
const structure = cloneDeepWith(jsonExample, (value) => {
return isObjectOrArray(value)
? undefined // leave as is
return Array.isArray(value)
? []
: isObject(value)
? undefined // leave object as is, will recurse into it
: ''
})
@ -289,8 +291,10 @@ export function createNewValue (doc, selection, type) {
// no example structure
return ''
}
}
default: ''
default:
return ''
}
}

View File

@ -0,0 +1,42 @@
import assert from 'assert'
import { createNewValue } from './operations.js'
describe('operations', () => {
describe('createNewValue', () => {
it('should create a value of type "value"', () => {
assert.strictEqual(createNewValue({}, null, 'value'), '')
})
it('should create a value of type "object"', () => {
assert.deepStrictEqual(createNewValue({}, null, 'object'), {})
})
it('should create a value of type "array"', () => {
assert.deepStrictEqual(createNewValue({}, null, 'array'), [])
})
it('should create a simple value via type "structure"', () => {
assert.deepStrictEqual(createNewValue([1, 2, 3], { paths: [[0]] }, 'structure'), '')
})
it('should create a nested object via type "structure"', () => {
const doc = [
{
a: 2,
b: {
c: 3
},
d: [1, 2, 3]
}
]
assert.deepStrictEqual(createNewValue(doc, { paths: [[0]] }, 'structure'), {
a: '',
b: {
c: ''
},
d: []
})
})
})
})