fix(core): styles de-duplicate in mergeAttributes (#4610)

This commit is contained in:
sifat haque 2024-08-22 02:39:58 +06:00 committed by GitHub
parent 9e18d243e0
commit a22767e9e1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 39 additions and 1 deletions

View File

@ -0,0 +1,5 @@
---
"@tiptap/core": patch
---
Merging inline style attributes now can properly merge conflicting style attribute names, resulting in cleaner HTML output and correctness

View File

@ -23,7 +23,24 @@ export function mergeAttributes(...objects: Record<string, any>[]): Record<strin
mergedAttributes[key] = [...existingClasses, ...insertClasses].join(' ')
} else if (key === 'style') {
mergedAttributes[key] = [mergedAttributes[key], value].join('; ')
const newStyles: string[] = value ? value.split(';').map((style: string) => style.trim()).filter(Boolean) : []
const existingStyles: string[] = mergedAttributes[key] ? mergedAttributes[key].split(';').map((style: string) => style.trim()).filter(Boolean) : []
const styleMap = new Map<string, string>()
existingStyles.forEach(style => {
const [property, val] = style.split(':').map(part => part.trim())
styleMap.set(property, val)
})
newStyles.forEach(style => {
const [property, val] = style.split(':').map(part => part.trim())
styleMap.set(property, val)
})
mergedAttributes[key] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join('; ')
} else {
mergedAttributes[key] = value
}

View File

@ -65,4 +65,20 @@ describe('mergeAttributes', () => {
class: 'foo',
})
})
it('should overwrite styles', () => {
const value = mergeAttributes({ style: 'color: red' }, { style: 'color: green' })
expect(value).to.deep.eq({
style: 'color: green',
})
})
it('should merge several styles', () => {
const value = mergeAttributes({ style: 'color: red; background-color: red' }, { style: 'color: green; background-color: red; margin-left: 30px' })
expect(value).to.deep.eq({
style: 'color: green; background-color: red; margin-left: 30px',
})
})
})