Files
baserow/web-frontend/modules/core/utils/markdown.js
Tsering Paljor 674e4b12a8 feat: Add markdown support to more Builder elements (#6124)
* WIP

* Remove formula conversion related changes

* Move the file input click guard to formatted text component

* Move format types into their own components

* Use a shared markdown-it instance

* Move the formatter into data explorer

* Move minification logic into BaserowFormulaMinified

* Renderer should own the root element

* Ensure long choice names are truncated

* Ensure line height doesn't grow for paragraphs

* Add tests

* Add changelog

* Add specific tests for choice element
2026-10-09 09:36:32 +04:00

43 lines
1.6 KiB
JavaScript

import MarkdownIt from 'markdown-it'
// One markdown-it parser for the whole app. Creating one per component adds up
// when many small texts render at once, e.g. the cells of a table. Rendering is
// synchronous, so `renderMarkdown` configures the shared parser, uses it and
// restores it before any other caller (or, on the server, any other request)
// can touch it.
const Markdown = MarkdownIt?.default || MarkdownIt
const md = new Markdown()
const baseRules = { ...md.renderer.rules }
/**
* Renders markdown to HTML with the shared parser.
*
* @param {string} content The markdown to render.
* @param {Object} [options]
* @param {Object} [options.rules] Renderer rules merged over the defaults, e.g.
* to add CSS classes to the rendered tags.
* @param {boolean} [options.inline] Only the inline syntax (emphasis, links,
* code, ...) applies and the result has no wrapping paragraph.
* @param {string[]} [options.disabledRules] Names of markdown-it rules to
* switch off, e.g. `['image', 'link']`. Unknown names are ignored.
* @returns {string} The rendered HTML.
*/
export function renderMarkdown(
content,
{ rules = {}, inline = false, disabledRules = [] } = {}
) {
md.renderer.rules = { ...baseRules, ...rules }
if (disabledRules.length > 0) {
md.disable(disabledRules, true)
}
try {
return inline ? md.renderInline(content) : md.render(content)
} finally {
// Leave the shared parser as the next call expects to find it.
if (disabledRules.length > 0) {
md.enable(disabledRules, true)
}
md.renderer.rules = { ...baseRules }
}
}