Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/comark/src/plugins/breaks.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { defineComarkPlugin } from '../utils/helpers.ts'
import { visit } from '../utils/index.ts'

// Tags whose text content is whitespace-sensitive and must keep literal newlines
const IGNORED_TAGS = new Set(['pre', 'code', 'math', 'script', 'style', 'textarea'])

export default defineComarkPlugin(() => ({
name: 'breaks',
post(state) {
visit(
state.tree,
(node) => Array.isArray(node) && node.length > 2,
(node) => Array.isArray(node) && node.length > 2 && !IGNORED_TAGS.has(node[0] as string),
(node) => {
const parent = node as any[]
const newParent = [parent[0], parent[1]]
Expand Down
18 changes: 18 additions & 0 deletions packages/comark/test/breaks.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import { parse } from '../src/parse'
import breaks from '../src/plugins/breaks'
import math from '../src/plugins/math'

describe('breaks plugin', () => {
it('should replace all occurrences of \n with the comark :br component', async () => {
Expand All @@ -9,4 +10,21 @@ describe('breaks plugin', () => {

expect(tree.nodes).toEqual([['p', {}, 'She said "hello world" to', ['br', {}], 'him.']])
})

it('should not replace \n inside code blocks', async () => {
const md = 'soft\nbreak\n\n```\nline1\nline2\n```'
const tree = await parse(md, { plugins: [breaks()] })

expect(tree.nodes).toEqual([
['p', {}, 'soft', ['br', {}], 'break'],
['pre', {}, ['code', {}, 'line1\nline2']],
])
})

it('should not replace \n inside math blocks', async () => {
const md = '$$\nx = 1 \\\\\ny = 2\n$$'
const tree = await parse(md, { plugins: [math(), breaks()] })

expect(tree.nodes).toEqual([['math', { class: 'math block', content: 'x = 1 \\\\\ny = 2' }, 'x = 1 \\\\\ny = 2']])
})
})
2 changes: 1 addition & 1 deletion test/bundle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ describe('package bundle size', { timeout: 60_000 }, () => {
"@comark/react": "40.5k (58 files)",
"@comark/svelte": "40.6k (66 files)",
"@comark/vue": "57.3k (62 files)",
"comark": "373k (136 files)",
"comark": "374k (136 files)",
}
`)
})
Expand Down
Loading