Skip to content
Open
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
30 changes: 30 additions & 0 deletions packages/core/src/extensions/commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,36 @@ describe('insertMarkdown', () => {
`)
})

it('keeps a block suffix outside and places the cursor in its paragraph', () => {
using fixture = setupFixture()
const { editor, n } = fixture
fixture.set(n.doc(n.paragraph('Before<a>After')))

editor.commands.insertMarkdown('```collection\ncollection: people\n```', {
selection: 'after-block',
})
editor.commands.insertText({ text: 'Next ' })

expect(docToMarkdown(fixture.doc)).toBe(
'Before\n\n```collection\ncollection: people\n```\n\nNext After\n',
)
})

it('creates a trailing paragraph when an inserted block ends the document', () => {
using fixture = setupFixture()
const { editor, n } = fixture
fixture.set(n.doc(n.paragraph('Before<a>')))

editor.commands.insertMarkdown('```collection\ncollection: people\n```', {
selection: 'after-block',
})
editor.commands.insertText({ text: 'Next' })

expect(docToMarkdown(fixture.doc)).toBe(
'Before\n\n```collection\ncollection: people\n```\n\nNext\n',
)
})

it('undoes an inserted fragment as a single history entry', () => {
using fixture = setupFixture()
const { editor, n } = fixture
Expand Down
31 changes: 28 additions & 3 deletions packages/core/src/extensions/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@ import { markdownToDoc } from '../converters/md-to-pm.ts'
import { isNodeOfType, type NodeName } from './node-names.ts'
import { getNodeBuildersForSchema } from './schema.ts'

export interface InsertMarkdownOptions {
/**
* Where the caret lands after a code-block fragment. `after-block` keeps
* any paragraph suffix outside the inserted block and creates an ordinary
* following paragraph when needed.
*/
selection?: 'end' | 'after-block'
Comment on lines +14 to +19

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel this is not the correct way to add "an ordinary following paragraph" after a code block. We probably should provide a more general way, like a ProseMirror command.

}

function selectText(anchor: number, head?: number): Command {
return (state, dispatch) => {
if (dispatch) {
Expand All @@ -32,7 +41,7 @@ function selectTextBetween($anchor: ResolvedPos, $head: ResolvedPos, bias?: numb
}
}

function insertMarkdown(markdown: string): Command {
function insertMarkdown(markdown: string, options: InsertMarkdownOptions = {}): Command {
return (state, dispatch) => {
if (!markdown.trim()) return false
const nodes = getNodeBuildersForSchema(state.schema)
Expand All @@ -42,14 +51,30 @@ function insertMarkdown(markdown: string): Command {
content.childCount === 1 && isNodeOfType(content.child(0), 'paragraph')
const slice = isSingleParagraph
? new Slice(content, 1, 1)
: new Slice(content, 0, Slice.maxOpen(content).openEnd)
: options.selection === 'after-block'
? new Slice(content, 0, 0)
: new Slice(content, 0, Slice.maxOpen(content).openEnd)
if (dispatch) {
const tr = state.tr
const selection = tr.selection
if (!isTextSelection(selection) || !selection.empty) {
tr.setSelection(TextSelection.near(selection.$from))
}
dispatch(tr.replaceSelection(slice).scrollIntoView())
tr.replaceSelection(slice)
if (options.selection === 'after-block') {
const $selection = tr.selection.$from
for (let depth = $selection.depth; depth > 0; depth -= 1) {
if (!isNodeOfType($selection.node(depth), 'codeBlock')) continue
const after = $selection.after(depth)
const nodeAfter = tr.doc.resolve(after).nodeAfter
if (nodeAfter === null || !isNodeOfType(nodeAfter, 'paragraph')) {
tr.insert(after, nodes.paragraph())
}
tr.setSelection(TextSelection.near(tr.doc.resolve(after), 1))
break
}
}
dispatch(tr.scrollIntoView())
}
return true
}
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ export {
type InlineMarkOptions,
} from './extensions/inline-text-to-mark-chunks.ts'
export { EDITOR_KEY_BINDINGS } from './extensions/key-bindings.ts'
export type { InsertMarkdownOptions } from './extensions/commands.ts'
export {
defineLinkClickHandler,
type LinkClickHandler,
Expand Down
17 changes: 17 additions & 0 deletions packages/react/src/components/code-block-view.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,23 @@
display: none;
}

.Root[data-custom] pre {
display: none;
}

/* Host widgets own their list layout. Keep the outer editor's prose list
* rules out, while a Markdown view nested inside the widget remains styled by
* its own `.ProseMirror` surface. */
.Root .CustomContent ul:not(.CustomContent :global(.ProseMirror) ul),
.Root .CustomContent ol:not(.CustomContent :global(.ProseMirror) ol) {
padding-left: 0;
list-style: none;
}

.Root .CustomContent li:not(.CustomContent :global(.ProseMirror) li) {
margin-top: 0;
}

.Root[data-preview] .Toolbar {
display: none;
}
Expand Down
10 changes: 10 additions & 0 deletions packages/react/src/components/code-block-view.module.d.css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@ declare const styles = {
'Root': '' as string,
'Root': '' as string,
'Root': '' as string,
'Root': '' as string,
'CustomContent': '' as string,
'CustomContent': '' as string,
'Root': '' as string,
'CustomContent': '' as string,
'CustomContent': '' as string,
'Root': '' as string,
'CustomContent': '' as string,
'CustomContent': '' as string,
'Root': '' as string,
'Toolbar': '' as string,
'Preview': '' as string,
'MermaidPreview': '' as string,
Expand Down
148 changes: 147 additions & 1 deletion packages/react/src/components/code-block-view.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import '../testing/index.ts'

import { isNodeOfType } from '@meowdown/core'
import { readClipboard } from '@meowdown/vitest/clipboard'
import { TextSelection } from '@prosekit/pm/state'
import { NodeSelection, TextSelection } from '@prosekit/pm/state'
import type { EditorView } from '@prosekit/pm/view'
import { createRef } from 'react'
import { describe, expect, it, vi } from 'vitest'
Expand All @@ -21,6 +22,151 @@ const tokens = page.locate('.ProseMirror pre code [class*="tok-"]')
const CODE_BLOCK_MD = '```rust\nfn main() {}\n```'

describe('code block language selector', () => {
it('falls back to the built-in code block when the host declines to render it', async () => {
await render(<ProseKitEditor initialMarkdown={CODE_BLOCK_MD} renderCodeBlock={() => null} />)
await expect.element(selector).toHaveTextContent('Rust')
await expect.element(page.locate('.ProseMirror pre[data-language="rust"]')).toBeVisible()
})

it('keeps host widget lists outside the editor prose list styling', async () => {
await render(
<ProseKitEditor
initialMarkdown={'before\n\n```collection\ntag: people\n```\n\nafter'}
renderCodeBlock={({ language }) => {
return language === 'collection' ? (
<ul data-testid="collection-list">
<li data-testid="collection-list-item">Person</li>
</ul>
) : null
}}
/>,
)

const list = page.getByTestId('collection-list').element()
const item = page.getByTestId('collection-list-item').element()
expect(getComputedStyle(list).listStyleType).toBe('none')
expect(getComputedStyle(list).paddingLeft).toBe('0px')
expect(getComputedStyle(item).marginTop).toBe('0px')
})

it('renders host content in document order and updates the body as one undoable change', async () => {
const ref = createRef<EditorHandle>()
const onDocChange = vi.fn()
const markdown = 'before\n\n```collection\ntag: people\n```\n\nafter'

await render(
<ProseKitEditor
ref={ref}
initialMarkdown={markdown}
onDocChange={onDocChange}
renderCodeBlock={({ language, code, updateCode }) => {
return language === 'collection' ? (
<button
type="button"
data-testid="collection-view"
onClick={() => updateCode('tag: people\nview: board')}
>
{code}
</button>
) : null
}}
/>,
)

const customView = page.getByTestId('collection-view')
await expect.element(customView).toHaveTextContent('tag: people')
await expect
.element(page.locate('.ProseMirror pre[data-language="collection"]'))
.not.toBeVisible()
const before = page.getByText('before').element()
const custom = customView.element()
const after = page.getByText('after').element()
expect(before.compareDocumentPosition(custom) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
expect(custom.compareDocumentPosition(after) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()

const editor = ref.current?.editor
if (!editor) throw new Error('editor not mounted')
let codeBlockPosition: number | undefined
editor.state.doc.descendants((node, pos) => {
if (isNodeOfType(node, 'codeBlock')) {
codeBlockPosition = pos
return false
}
return true
})
if (codeBlockPosition == null) throw new Error('code block not found')
editor.view.dispatch(
editor.state.tr.setSelection(
TextSelection.near(editor.state.doc.resolve(codeBlockPosition + 1)),
),
)
await expect.element(page.locate('.ProseMirror pre[data-language="collection"]')).toBeVisible()
await expect.element(customView).toBeVisible()
const currentCodeBlock = editor.state.doc.nodeAt(codeBlockPosition)
if (!currentCodeBlock) throw new Error('code block not found')
editor.view.dispatch(
editor.state.tr.setSelection(
TextSelection.near(editor.state.doc.resolve(codeBlockPosition + currentCodeBlock.nodeSize)),
),
)
await expect
.element(page.locate('.ProseMirror pre[data-language="collection"]'))
.not.toBeVisible()

await customView.click()
await vi.waitFor(() => {
expect(ref.current?.getMarkdown()).toContain('```collection\ntag: people\nview: board\n```')
})
expect(onDocChange).toHaveBeenCalled()

ref.current?.editor?.commands.undo()
await vi.waitFor(() => {
expect(ref.current?.getMarkdown()).toBe(`${markdown}\n`)
})
await expect.element(customView).toHaveTextContent('tag: people')
})

it('removes a host-rendered code block as a node selection and restores it with undo', async () => {
const ref = createRef<EditorHandle>()
const markdown = 'before\n\n```collection\ntag: people\n```\n\nafter'

await render(
<ProseKitEditor
ref={ref}
initialMarkdown={markdown}
renderCodeBlock={({ language }) => {
return language === 'collection' ? (
<div data-testid="collection-view">Collection</div>
) : null
}}
/>,
)

const editor = ref.current?.editor
if (!editor) throw new Error('editor not mounted')
let codeBlockPosition: number | undefined
editor.state.doc.descendants((node, pos) => {
if (isNodeOfType(node, 'codeBlock')) {
codeBlockPosition = pos
return false
}
return true
})
if (codeBlockPosition == null) throw new Error('code block not found')
editor.view.dispatch(
editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, codeBlockPosition)),
)
editor.view.focus()
await userEvent.keyboard('{Backspace}')

await expect.element(page.getByTestId('collection-view')).not.toBeInTheDocument()
expect(ref.current?.getMarkdown()).not.toContain('```collection')

ref.current?.editor?.commands.undo()
await expect.element(page.getByTestId('collection-view')).toBeInTheDocument()
expect(ref.current?.getMarkdown()).toBe(`${markdown}\n`)
})

it('shows the current language for a code block', async () => {
await render(<ProseKitEditor initialMarkdown={CODE_BLOCK_MD} />)
await expect.element(selector).toBeInTheDocument()
Expand Down
Loading
Loading