{"id":13725283,"url":"https://github.com/HubSpot/draft-convert","last_synced_at":"2025-05-07T19:33:40.244Z","repository":{"id":9899220,"uuid":"62980900","full_name":"HubSpot/draft-convert","owner":"HubSpot","description":"Extensibly serialize \u0026 deserialize Draft.js ContentState with HTML.","archived":false,"fork":false,"pushed_at":"2023-02-25T23:23:33.000Z","size":775,"stargazers_count":483,"open_issues_count":82,"forks_count":94,"subscribers_count":143,"default_branch":"master","last_synced_at":"2024-11-09T10:02:41.316Z","etag":null,"topics":["draft","draft-js","javascript","react","rich-text-editor"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/HubSpot.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-07-10T04:08:10.000Z","updated_at":"2024-10-25T10:06:12.000Z","dependencies_parsed_at":"2024-05-10T06:42:21.971Z","dependency_job_id":"5bde00ed-ca17-4915-abb0-39105c55b6e2","html_url":"https://github.com/HubSpot/draft-convert","commit_stats":{"total_commits":176,"total_committers":16,"mean_commits":11.0,"dds":"0.30113636363636365","last_synced_commit":"69dcefe9f7dfa76eb08751099126991ade95b6d2"},"previous_names":[],"tags_count":45,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HubSpot%2Fdraft-convert","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HubSpot%2Fdraft-convert/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HubSpot%2Fdraft-convert/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HubSpot%2Fdraft-convert/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/HubSpot","download_url":"https://codeload.github.com/HubSpot/draft-convert/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224645295,"owners_count":17346113,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["draft","draft-js","javascript","react","rich-text-editor"],"created_at":"2024-08-03T01:02:18.179Z","updated_at":"2024-11-14T15:31:05.783Z","avatar_url":"https://github.com/HubSpot.png","language":"JavaScript","readme":"# **draft-convert**\n\n[![npm version](https://badge.fury.io/js/draft-convert.svg)](https://www.npmjs.com/package/draft-convert) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)\n\n*Extensibly serialize \u0026 deserialize [**Draft.js**](http://draftjs.org/) content with HTML*\n\n*See [**draft-extend**](http://github.com/HubSpot/draft-extend) for more on how to use draft-convert with plugins*\n\n## Installation\n\n`npm install draft-convert --save` or `yarn add draft-convert`\n\nJump to:\n\n- [convertToHTML](#converttohtml)\n- [convertFromHTML](#convertfromhtml)\n- [Middleware functions](#middleware-functions)\n\n## convertToHTML\n\n**Extensibly serialize Draft.js [`ContentState`](http://facebook.github.io/draft-js/docs/api-reference-content-state.html#content) to HTML.**\n\n**Basic usage:**\n```javascript\nconst html = convertToHTML(editorState.getCurrentContent());\n```\n**Advanced usage:**\n```javascript\n// convert to HTML with blue text, paragraphs, and links\nconst html = convertToHTML({\n  styleToHTML: (style) =\u003e {\n    if (style === 'BOLD') {\n      return \u003cspan style={{color: 'blue'}} /\u003e;\n    }\n  },\n  blockToHTML: (block) =\u003e {\n    if (block.type === 'PARAGRAPH') {\n      return \u003cp /\u003e;\n    }\n  },\n  entityToHTML: (entity, originalText) =\u003e {\n    if (entity.type === 'LINK') {\n      return \u003ca href={entity.data.url}\u003e{originalText}\u003c/a\u003e;\n    }\n    return originalText;\n  }\n})(editorState.getCurrentContent());\n\n// convert content state to HTML with functionality defined in the plugins applied\nconst html = compose(\n    FirstPlugin,\n    SecondPlugin,\n    ThirdPlugin\n)(convertToHTML)(editorState.getCurrentContent());\n```\n\n\n`styleToHTML`, `blockToHtml`, and `entityToHTML` are functions that take Draft content data and may return a `ReactElement` or an object of shape `{start, end}`  defining strings for the beginning and end tags of the style, block, or entity. `entityToHTML` may return either a string with or without HTML if the use case demands it. `blockToHTML` also may return an optional `empty` property to handle alternative behavior for empty blocks. To use this along with a `ReactElement` return value an object of shape `{element: ReactElement, empty: ReactElement}` may be returned. If no additional functionality is necessary `convertToHTML` can be invoked with just a `ContentState` to serialize using just the default Draft functionality. `convertToHTML` can be passed as an argument to a plugin to modularly augment its functionality.\n\n**Legacy alternative conversion options**\n`styleToHTML` and `blockToHTML` options may be plain objects keyed by style or block type with values of `ReactElement` s or `{start, end}`  objects. These objects will eventually be removed in favor of the functions described above.\n\n**Type info:**\n```javascript\ntype ContentStateConverter = (contentState: ContentState) =\u003e string\n\ntype Tag =\n  ReactElement |\n  {start: string, end: string, empty?: string} |\n  {element: ReactElement, empty?: ReactElement}\n\ntype RawEntity = {\n    type: string,\n    mutability: DraftEntityMutability,\n    data: Object\n}\n\ntype RawBlock = {\n    type: string,\n    depth: number,\n    data?: object,\n    text: string\n}\n\ntype convertToHTML = ContentStateConverter | ({\n    styleToHTML?: (style: string) =\u003e Tag,\n    blockToHTML?: (block: RawBlock) =\u003e Tag),\n    entityToHTML?: (entity: RawEntity, originalText: string) =\u003e Tag | string\n}) =\u003e ContentStateConverter\n```\n\n## convertFromHTML\n\n**Extensibly deserialize HTML to Draft.js [`ContentState`](http://facebook.github.io/draft-js/docs/api-reference-content-state.html#content).**\n\n**Basic usage:**\n```javascript\nconst editorState = EditorState.createWithContent(convertFromHTML(html));\n```\n\n**Advanced usage:**\n```javascript\n// convert HTML to ContentState with blue text, links, and at-mentions\nconst contentState = convertFromHTML({\n    htmlToStyle: (nodeName, node, currentStyle) =\u003e {\n        if (nodeName === 'span' \u0026\u0026 node.style.color === 'blue') {\n            return currentStyle.add('BLUE');\n        } else {\n            return currentStyle;\n        }\n    },\n    htmlToEntity: (nodeName, node, createEntity) =\u003e {\n        if (nodeName === 'a') {\n            return createEntity(\n                'LINK',\n                'MUTABLE',\n                {url: node.href}\n            )\n        }\n    },\n    textToEntity: (text, createEntity) =\u003e {\n        const result = [];\n        text.replace(/\\@(\\w+)/g, (match, name, offset) =\u003e {\n            const entityKey = createEntity(\n                'AT-MENTION',\n                'IMMUTABLE',\n                {name}\n            );\n            result.push({\n                entity: entityKey,\n                offset,\n                length: match.length,\n                result: match\n            });\n        });\n        return result;\n    },\n    htmlToBlock: (nodeName, node) =\u003e {\n        if (nodeName === 'blockquote') {\n            return {\n                type: 'blockquote',\n                data: {}\n            };\n        }\n    }\n})(html);\n\n// convert HTML to ContentState with functionality defined in the draft-extend plugins applied\nconst fromHTML = compose(\n    FirstPlugin,\n    SecondPlugin,\n    ThirdPlugin\n)(convertFromHTML);\nconst contentState = fromHTML(html);\n```\n\nIf no additional functionality is necessary `convertToHTML` can be invoked with just an HTML string to deserialize using just the default Draft functionality. Any `convertFromHTML` can be passed as an argument to a plugin to modularly augment its functionality. A `flat` option may be provided to force nested block elements to split into flat, separate blocks. For example, the HTML input `\u003cp\u003eline one\u003cbr /\u003elinetwo\u003c/p\u003e` will produce two `unstyled` blocks in `flat` mode.\n\n**Type info:**\n```javascript\ntype HTMLConverter = (html: string, {flat: ?boolean}, DOMBuilder: ?Function, generateKey: ?Function) =\u003e ContentState\n\ntype EntityKey = string\n\ntype convertFromHTML = HTMLConverter | ({\n    htmlToStyle: ?(nodeName: string, node: Node) =\u003e DraftInlineStyle,\n    htmlToBlock: ?(nodeName: string, node: Node) =\u003e ?(DraftBlockType | {type: DraftBlockType, data: object} | false),\n    htmlToEntity: ?(\n        nodeName: string,\n        node: Node,\n        createEntity: (type: string, mutability: string, data: object) =\u003e EntityKey,\n        getEntity: (key: EntityKey) =\u003e Entity,\n        mergeEntityData: (key: string, data: object) =\u003e void,\n        replaceEntityData: (key: string, data: object) =\u003e void\n    ): ?EntityKey,\n    textToEntity: ?(\n        text: string,\n        createEntity: (type: string, mutability: string, data: object) =\u003e EntityKey,\n        getEntity: (key: EntityKey) =\u003e Entity,\n        mergeEntityData: (key: string, data: object) =\u003e void,\n        replaceEntityData: (key: string, data: object) =\u003e void\n    ) =\u003e Array\u003c{entity: EntityKey, offset: number, length: number, result: ?string}\u003e\n}) =\u003e HTMLConverter\n```\n\n## Middleware functions\n\nAny conversion option for `convertToHTML`  or `convertFromHTML` may also accept a middleware function of shape `(next) =\u003e (…args) =\u003e result` , where `…args` are the normal configuration function paramaters and `result` is the expected return type for that function. These functions can transform results of the default conversion included in `convertToHTML` or `convertFromHTML` by leveraging the result of `next(...args)`. These middleware functions are most useful when passed as the result of composition of [`draft-extend`](http://github.com/HubSpot/draft-extend) plugins. If you choose to use them independently, a `__isMiddleware` property must be set to `true` on the function for `draft-convert` to properly handle it.\n\n","funding_links":[],"categories":["Common Utilities","JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FHubSpot%2Fdraft-convert","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FHubSpot%2Fdraft-convert","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FHubSpot%2Fdraft-convert/lists"}