|
| 1 | +const normalMerge = ['attrs', 'props', 'domProps'] |
| 2 | +const toArrayMerge = ['class', 'style', 'directives'] |
| 3 | +const functionalMerge = ['on', 'nativeOn'] |
| 4 | + |
| 5 | +const mergeJsxProps = objects => |
| 6 | + objects.reduce((a, b) => { |
| 7 | + for (const key in b) { |
| 8 | + if (a[key]) { |
| 9 | + if (normalMerge.indexOf(key) !== -1) { |
| 10 | + a[key] = { ...a[key], ...b[key] } |
| 11 | + } else if (toArrayMerge.indexOf(key) !== -1) { |
| 12 | + const arrA = a[key] instanceof Array ? a[key] : [a[key]] |
| 13 | + const arrB = b[key] instanceof Array ? b[key] : [b[key]] |
| 14 | + a[key] = [...arrA, ...arrB] |
| 15 | + } else if (functionalMerge.indexOf(key) !== -1) { |
| 16 | + for (const event in b[key]) { |
| 17 | + if (a[key][event]) { |
| 18 | + const arrA = a[key][event] instanceof Array ? a[key][event] : [a[key][event]] |
| 19 | + const arrB = b[key][event] instanceof Array ? b[key][event] : [b[key][event]] |
| 20 | + a[key][event] = [...arrA, ...arrB] |
| 21 | + } else { |
| 22 | + a[key][event] = b[key][event] |
| 23 | + } |
| 24 | + } |
| 25 | + } else if (key === 'hook') { |
| 26 | + for (let hook in b[key]) { |
| 27 | + if (a[key][hook]) { |
| 28 | + a[key][hook] = mergeFn(a[key][hook], b[key][hook]) |
| 29 | + } else { |
| 30 | + a[key][hook] = b[key][hook] |
| 31 | + } |
| 32 | + } |
| 33 | + } else { |
| 34 | + a[key] = b[key] |
| 35 | + } |
| 36 | + } else { |
| 37 | + a[key] = b[key] |
| 38 | + } |
| 39 | + } |
| 40 | + return a |
| 41 | + }, {}) |
| 42 | + |
| 43 | +const mergeFn = (fn1, fn2) => |
| 44 | + function() { |
| 45 | + fn1 && fn1.apply(this, arguments) |
| 46 | + fn2 && fn2.apply(this, arguments) |
| 47 | + } |
| 48 | + |
| 49 | +export default mergeJsxProps |
0 commit comments