Skip to content

Commit

Permalink
feat: added conditions to reduce fragment and convert b,i tags to str…
Browse files Browse the repository at this point in the history
…ong and em
  • Loading branch information
Jayesh2812 committed Nov 14, 2024
1 parent db40c98 commit 8767cea
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
24 changes: 23 additions & 1 deletion src/fromRedactor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -863,7 +863,7 @@ export const fromRedactor = (el: any, options?:IHtmlToJsonOptions) : IAnyObject
}
let noOfInlineElement = 0
Array.from(el.parentNode?.childNodes || []).forEach((child: any) => {
if (child.nodeType === 3 || child.nodeName === 'SPAN' || child.nodeName === 'A' || (options?.allowNonStandardTags && child.getAttribute('inline'))) {
if (child.nodeType === 3 || child.nodeName === 'SPAN' || child.nodeName === 'A' || (options?.allowNonStandardTags && child.getAttribute('inline')) || child.nodeName in TEXT_TAGS) {
noOfInlineElement += 1
}
})
Expand Down Expand Up @@ -1084,4 +1084,26 @@ function getTbodyChildren (rows: any[]) {

}, [])
return newTbodyChildren
}

export function replaceNonSemanticTags (el: HTMLElement) {
const nonSematicTagMap = {
b: 'strong',
i: 'em'
} as Record<string, string>

const nodes = el.querySelectorAll(Object.keys(nonSematicTagMap).join(','))

nodes.forEach((node) => {
const nodeName = node.nodeName.toLowerCase()
if(!(nodeName in nonSematicTagMap)) return

const strong = el.ownerDocument.createElement(nonSematicTagMap[nodeName])
strong.innerHTML = node.innerHTML
Array.from(node.attributes).forEach((attr) => {
if(attr.nodeValue)
strong.setAttribute(attr.nodeName, attr.nodeValue)
})
node.replaceWith(strong)
})
}
10 changes: 8 additions & 2 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import "array-flat-polyfill"
import { fromRedactor } from "./fromRedactor"
import { fromRedactor, replaceNonSemanticTags } from "./fromRedactor"
import { toRedactor } from "./toRedactor"
import {jsonToMarkdownSerializer} from './jsonToMarkdown'
import { IHtmlToJsonOptions } from "./types"
export * from "./types"
export { fromRedactor as htmlToJson, toRedactor as jsonToHtml, jsonToMarkdownSerializer as jsonToMarkdown }
export { toRedactor as jsonToHtml, jsonToMarkdownSerializer as jsonToMarkdown }

export const htmlToJson = (el: any, options?:IHtmlToJsonOptions) => {
replaceNonSemanticTags(el)
return fromRedactor(el, options)
}

0 comments on commit 8767cea

Please sign in to comment.