Skip to content

Commit 202c68a

Browse files
committed
feat: added conditions to reduce fragment and convert b,i tags to strong and em
1 parent 6b63818 commit 202c68a

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

src/fromRedactor.tsx

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -863,7 +863,7 @@ export const fromRedactor = (el: any, options?:IHtmlToJsonOptions) : IAnyObject
863863
}
864864
let noOfInlineElement = 0
865865
Array.from(el.parentNode?.childNodes || []).forEach((child: any) => {
866-
if (child.nodeType === 3 || child.nodeName === 'SPAN' || child.nodeName === 'A' || (options?.allowNonStandardTags && child.getAttribute('inline'))) {
866+
if (child.nodeType === 3 || child.nodeName === 'SPAN' || child.nodeName === 'A' || (options?.allowNonStandardTags && child.getAttribute('inline')) || child.nodeName in TEXT_TAGS) {
867867
noOfInlineElement += 1
868868
}
869869
})
@@ -1084,4 +1084,26 @@ function getTbodyChildren (rows: any[]) {
10841084

10851085
}, [])
10861086
return newTbodyChildren
1087+
}
1088+
1089+
export function replaceNonSemanticTags (el: HTMLElement) {
1090+
const nonSematicTagMap = {
1091+
b: 'strong',
1092+
i: 'em'
1093+
} as Record<string, string>
1094+
1095+
const nodes = el.querySelectorAll(Object.keys(nonSematicTagMap).join(','))
1096+
1097+
nodes.forEach((node) => {
1098+
const nodeName = node.nodeName.toLowerCase()
1099+
if(!(nodeName in nonSematicTagMap)) return
1100+
1101+
const strong = el.ownerDocument.createElement(nonSematicTagMap[nodeName])
1102+
strong.innerHTML = node.innerHTML
1103+
Array.from(node.attributes).forEach((attr) => {
1104+
if(attr.nodeValue)
1105+
strong.setAttribute(attr.nodeName, attr.nodeValue)
1106+
})
1107+
node.replaceWith(strong)
1108+
})
10871109
}

src/index.tsx

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
import "array-flat-polyfill"
2-
import { fromRedactor } from "./fromRedactor"
2+
import { fromRedactor, replaceNonSemanticTags } from "./fromRedactor"
33
import { toRedactor } from "./toRedactor"
44
import {jsonToMarkdownSerializer} from './jsonToMarkdown'
5+
import { IHtmlToJsonOptions } from "./types"
56
export * from "./types"
6-
export { fromRedactor as htmlToJson, toRedactor as jsonToHtml, jsonToMarkdownSerializer as jsonToMarkdown }
7+
export { toRedactor as jsonToHtml, jsonToMarkdownSerializer as jsonToMarkdown }
8+
9+
export const htmlToJson = (el: any, options?:IHtmlToJsonOptions) => {
10+
replaceNonSemanticTags(el)
11+
return fromRedactor(el, options)
12+
}

0 commit comments

Comments
 (0)