Skip to content

Commit

Permalink
feat: 🎸 prevent duplicated ids for headings (Milkdown#1580)
Browse files Browse the repository at this point in the history
* feat: 🎸 prevent duplicated ids for headings

✅ Closes: Milkdown#1567

* test: add e2e
  • Loading branch information
Saul-Mirone authored Dec 9, 2024
1 parent 96f56aa commit a1f3676
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
18 changes: 17 additions & 1 deletion e2e/tests/input/heading.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, test } from '@playwright/test'
import { focusEditor, getMarkdown } from '../misc'
import { focusEditor, getMarkdown, waitNextFrame } from '../misc'

test.beforeEach(async ({ page }) => {
await page.goto('/preset-commonmark/')
Expand All @@ -21,3 +21,19 @@ test('heading', async ({ page }) => {
const markdown2 = await getMarkdown(page)
expect(markdown2).toBe('# Heading1\n\n## Heading 2\n')
})

test('should generate different id for same heading', async ({ page }) => {
const editor = page.locator('.editor')
await focusEditor(page)
await page.keyboard.type('# Heading1')
await page.keyboard.press('Enter')
await page.keyboard.type('# Heading1')
await page.keyboard.press('Enter')
await page.keyboard.type('## Heading1')
await page.keyboard.press('Enter')

await waitNextFrame(page)
await expect(editor.locator('h1').first()).toHaveAttribute('id', 'heading1')
await expect(editor.locator('h1').last()).toHaveAttribute('id', 'heading1-#2')
await expect(editor.locator('h2')).toHaveAttribute('id', 'heading1-#3')
})
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,20 @@ export const syncHeadingIdPlugin = $prose((ctx) => {
const tr = view.state.tr.setMeta('addToHistory', false)

let found = false
const idMap: Record<string, number> = {}

view.state.doc.descendants((node, pos) => {
if (node.type === headingSchema.type(ctx)) {
if (node.textContent.trim().length === 0) return

const attrs = node.attrs
const id = getId(node)
let id = getId(node)
if (idMap[id]) {
idMap[id]! += 1
id += `-#${idMap[id]}`
} else {
idMap[id] = 1
}

if (attrs.id !== id) {
found = true
Expand Down

0 comments on commit a1f3676

Please sign in to comment.