Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(notebooks): support GFM task lists in markdown notebooks (#63320)

Marius Andrac0821f34eeae
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 8eb167b9fb27..1d23d5d8f4f2 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -965,9 +965,9 @@ snapshots:
components-markdown-notebook--invalid-component-props--light:
hash: v1.k794b7964.a0f81daf461faf93c867c077248b946287a439398dd099fe7e0896645a81d278.QJbiVYwNj2gJ2Q7zZlK91DZu72dTwuLpQqcqSQ_f3Ls
components-markdown-notebook--lists-and-links--dark:
- hash: v1.k794b7964.f297156d1df3c6035912804191bb37f1f600e0aef7d89c57586f9f2dd16fde7b.UUkk7YL8gZFJax8sdj6zy8iCbLyCvaPfSCoJxehtNlM
+ hash: v1.k794b7964.3858121270db1e00d8c8a51b6aae447c9281ff262a313ca715c7ba5c64e950dd.0RuqWjHaOZOXUQCcWrKYjJh9KeuJGkKGxudLQR_SLFg
components-markdown-notebook--lists-and-links--light:
- hash: v1.k794b7964.de20a22b8743ce35a27d05890701a69a760f2c0a06f111964d9a48bb32feb5d3.V032JeIsD8hjIUOMI0myvgUmyMtfJ33bmRhIGEPnoe8
+ hash: v1.k794b7964.29dbeae01ed0803f3c9838ba2dbaf2e7f824fccb443c36ced60511ec78ad08bc.2sxyRNkZutPI04EoDMgkkwN5e8ARuibPE0gGgyWALhI
components-markdown-notebook--malformed-markdown-recovery--dark:
hash: v1.k794b7964.52d7777de0917b35b334a9b384fafff389562bf1a19cfc951fe6237a54f0eb83.KAPga8GO3wSl5G64hoJPHUoqm5yEozhVTV1lsrxCSEM
components-markdown-notebook--malformed-markdown-recovery--light:
diff --git a/frontend/src/lib/components/MarkdownNotebook/EditableListBlock.tsx b/frontend/src/lib/components/MarkdownNotebook/EditableListBlock.tsx
index e9ebad7c2c3b..e57bd7d5d9e6 100644
--- a/frontend/src/lib/components/MarkdownNotebook/EditableListBlock.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/EditableListBlock.tsx
@@ -9,7 +9,7 @@ import {
useRef,
} from 'react'
-import { shouldUseMarkdownPaste } from './documentModel'
+import { getTaskItemShortcut, shouldUseMarkdownPaste } from './documentModel'
import { getInlineLinkPasteResult, getSelectionRange } from './domSelection'
import { RestoreSelectionRequest, TextSelectionPointerStartEvent } from './editorTypes'
import { splitInlineNodesAt } from './inlineContent'
@@ -126,12 +126,44 @@ export function EditableListBlock({
const handleListBlockInput = (event: FormEvent<HTMLDivElement>): void => {
event.stopPropagation()
+ if (event.target instanceof HTMLInputElement) {
+ // Checkbox toggles go through onChange, not the contenteditable input flow
+ return
+ }
const element = getListItemContentElement(event.target) ?? getActiveListItemContentElement()
if (!element) {
return
}
- updateListItemChildrenFromElement(element)
+ const details = getListItemDetails(element)
+ if (!details) {
+ return
+ }
+
+ const children = htmlElementToInlineNodes(element)
+ const taskShortcut =
+ details.item.checked === undefined && !(details.item.ordered ?? node.ordered)
+ ? getTaskItemShortcut(children)
+ : null
+ if (taskShortcut) {
+ const selection = getSelectionRange(element, node.id)
+ const caretOffset = Math.max(0, (selection?.start ?? taskShortcut.markerLength) - taskShortcut.markerLength)
+ updateListItem(details.itemIndex, details.itemId, (item) => ({
+ ...item,
+ checked: taskShortcut.checked,
+ children: taskShortcut.children,
+ }))
+ restoreSelectionRef.current = {
+ nodeId: node.id,
+ listItemIndex: details.itemIndex,
+ listItemId: details.itemId,
+ start: caretOffset,
+ end: caretOffset,
+ }
+ return
+ }
+
+ updateListItemChildren(details.itemIndex, details.itemId, children)
}
const handleListBlockPaste = (event: ReactClipboardEvent<HTMLDivElement>): void => {
@@ -200,11 +232,36 @@ export function EditableListBlock({
updateListItemChildrenFromElement(element)
}
+ const toggleListItemChecked = (itemIndex: number, itemId: string | undefined): void => {
+ updateListItem(itemIndex, itemId, (item) => ({ ...item, checked: !item.checked }))
+ }
+
const renderListItems = (items: RenderedListItem[], ordered: boolean): ReactNode =>
items.map((item) => {
const itemOrdered = item.ordered ?? ordered
+ const isTaskItem = !itemOrdered && item.checked !== undefined
return (
- <li key={`${node.id}:${item.id ?? item.keyPath}`}>
+ <li
+ key={`${node.id}:${item.id ?? item.keyPath}`}
+ className={isTaskItem ? 'MarkdownNotebook__list-item--task' : undefined}
+ >
+ {isTaskItem ? (
+ // The checkbox replaces the bullet; contentEditable={false} keeps the caret
+ // and text selection out of it inside the editable list block.
+ <span
+ className="MarkdownNotebook__task-checkbox"
+ contentEditable={false}
+ onMouseDown={(event) => event.stopPropagation()}
+ onPointerDown={(event) => event.stopPropagation()}
+ >
+ <input
+ type="checkbox"
+ checked={!!item.checked}
+ disabled={mode !== 'edit'}
+ onChange={() => toggleListItemChecked(item.index, item.id)}
+ />
+ </span>
+ ) : null}
<EditableListItemContent node={node} item={item} setListItemRef={setListItemRef} />
{item.childrenItems.length
? renderItems(item.childrenItems, item.childrenItems[0].ordered ?? itemOrdered)
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
index a01c0222b259..06260c10c66d 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
@@ -983,6 +983,32 @@ h3.MarkdownNotebook__text-block--heading {
color: var(--color-text-secondary);
}
+/* Task items: the checkbox is the bullet */
+.MarkdownNotebook__list-block li.MarkdownNotebook__list-item--task {
+ position: relative;
+ list-style: none;
+}
+
+.MarkdownNotebook__task-checkbox {
+ position: absolute;
+ top: calc(0.125rem + 0.275em);
+ left: -1.375rem;
+ display: inline-flex;
+ user-select: none;
+}
+
+.MarkdownNotebook__task-checkbox input {
+ width: 1em;
+ height: 1em;
+ margin: 0;
+ accent-color: var(--primary);
+ cursor: pointer;
+}
+
+.MarkdownNotebook__task-checkbox input:disabled {
+ cursor: default;
+}
+
.MarkdownNotebook__list-item-content {
min-height: 1.55em;
padding: 0.125rem 0.25rem;
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx
index 2d8fcecee7e2..a766d62bf3b6 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx
@@ -180,6 +180,10 @@ export const ListsAndLinks: Story = {
- Session replay
- Feature flags
+- [x] Ship the onboarding experiment
+- [ ] Review session recordings
+ - [ ] Share findings with the team
+
[Open PostHog](https://posthog.com)`,
},
}
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index 5083ea04f27e..998c44417893 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -5942,6 +5942,102 @@ Tail with **bold** text`)
}
)
+ it.each([
+ ['[] ', '- [ ]'],
+ ['[ ] ', '- [ ]'],
+ ['[x] ', '- [x]'],
+ ])('converts a task list shortcut "%s" at the start of a text row into a task list', (shortcut, markdown) => {
+ const onChange = jest.fn()
+ const { container } = render(createElement(MarkdownNotebook, { value: withNotebookTitle(' '), onChange }))
+ const textBlock = getBodyTextBlock(container)
+
+ textBlock.textContent = shortcut
+ fireEvent.input(textBlock)
+
+ const taskItem = container.querySelector('li.MarkdownNotebook__list-item--task')
+ const checkbox = taskItem?.querySelector('input[type="checkbox"]') as HTMLInputElement
+ const listItem = container.querySelector('.MarkdownNotebook__list-item-content')
+
+ expect(taskItem).toBeInstanceOf(HTMLElement)
+ expect(checkbox.checked).toEqual(markdown === '- [x]')
+ expect(document.activeElement).toEqual(listItem)
+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n${markdown}`)
+ })
+
+ it('converts a typed task marker at the start of a bullet list item into a task item', () => {
+ const onChange = jest.fn()
+ const { container } = render(createElement(MarkdownNotebook, { value: withNotebookTitle('- alpha'), onChange }))
+ const listItems = getEditableListItems(container)
+
+ act(() => {
+ listItems[0].textContent = '[x] alpha'
+ })
+ selectTextInElement(listItems[0], '[x] '.length, '[x] '.length)
+ fireEvent.input(listItems[0])
+
+ const checkbox = container.querySelector(
+ 'li.MarkdownNotebook__list-item--task input[type="checkbox"]'
+ ) as HTMLInputElement
+
+ expect(checkbox).toBeInstanceOf(HTMLInputElement)
+ expect(checkbox.checked).toEqual(true)
+ expect(getEditableListItems(container)[0].textContent).toEqual('alpha')
+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n- [x] alpha`)
+ })
+
+ it('renders task checkboxes instead of bullets and toggles them through clicks', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('- [ ] open\n- [x] done'),
+ onChange,
+ })
+ )
+ const taskItems = Array.from(container.querySelectorAll('li.MarkdownNotebook__list-item--task'))
+ const checkboxes = Array.from(
+ container.querySelectorAll('.MarkdownNotebook__task-checkbox input[type="checkbox"]')
+ ) as HTMLInputElement[]
+
+ expect(taskItems).toHaveLength(2)
+ expect(checkboxes.map((checkbox) => checkbox.checked)).toEqual([false, true])
+
+ fireEvent.click(checkboxes[0])
+
+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n- [x] open\n- [x] done`)
+ })
+
+ it('keeps a task marker on an ordered list item as literal text without a checkbox', () => {
+ const { container } = render(createElement(MarkdownNotebook, { value: withNotebookTitle('1. [x] not a task') }))
+
+ expect(container.querySelector('li.MarkdownNotebook__list-item--task')).toBeNull()
+ expect(getEditableListItems(container)[0].textContent).toEqual('[x] not a task')
+ })
+
+ it('disables task checkboxes in view mode', () => {
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: withNotebookTitle('- [ ] open'), mode: 'view' })
+ )
+ const checkbox = container.querySelector(
+ '.MarkdownNotebook__task-checkbox input[type="checkbox"]'
+ ) as HTMLInputElement
+
+ expect(checkbox).toBeInstanceOf(HTMLInputElement)
+ expect(checkbox.disabled).toEqual(true)
+ })
+
+ it('creates a new unchecked task item when pressing Enter in a task item', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: withNotebookTitle('- [x] done'), onChange })
+ )
+ const listItems = getEditableListItems(container)
+
+ pressEnterInListItem(listItems[0], 'done'.length)
+ updateActiveContentEditableText('next')
+
+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n- [x] done\n- [ ] next`)
+ })
+
it('keeps ordered list items stable when creating several items from the keyboard', () => {
expectNoDuplicateKeyWarnings(() => {
const onChange = jest.fn()
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index 220fb5ee421e..3449d824ae77 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -50,6 +50,7 @@ import {
getNotebookStringProp,
getPromptSource,
getSlashCommandQuery,
+ getTaskItemShortcut,
getTextBlockShortcutReplacement,
hasNotebookContent,
getDiscussionCommentRefId,
@@ -1453,6 +1454,8 @@ export function MarkdownNotebook({
children: after,
depth: item.depth,
ordered: item.ordered ?? node.ordered,
+ // A new item split off a task starts as an unchecked task
+ checked: item.checked !== undefined ? false : undefined,
}
const nextItems = [...node.items]
nextItems[targetItemIndex] = { ...item, children: before }
@@ -4381,6 +4384,29 @@ export function MarkdownNotebook({
return
}
+ const listNode = nodes.find((node) => node.id === nodeId)
+ let taskShortcut: ReturnType<typeof getTaskItemShortcut> = null
+ if (listNode?.type === 'list') {
+ const item = listNode.items[getListItemIndex(listNode.items, itemIndex, itemId)]
+ if (item && item.checked === undefined && !(item.ordered ?? listNode.ordered)) {
+ taskShortcut = getTaskItemShortcut(nextChildren)
+ }
+ }
+ if (taskShortcut) {
+ const caretOffset = Math.max(
+ 0,
+ (getCollapsedSelectionRange(inlineEditableElement, nodeId)?.start ?? taskShortcut.markerLength) -
+ taskShortcut.markerLength
+ )
+ restoreSelectionRef.current = {
+ nodeId,
+ listItemIndex: itemIndex,
+ listItemId: itemId,
+ start: caretOffset,
+ end: caretOffset,
+ }
+ }
+
updateNode(nodeId, (currentNode) => {
if (currentNode.type !== 'list') {
return currentNode
@@ -4392,7 +4418,11 @@ export function MarkdownNotebook({
return {
...currentNode,
items: currentNode.items.map((item, index) =>
- index === targetItemIndex ? { ...item, children: nextChildren } : item
+ index === targetItemIndex
+ ? taskShortcut
+ ? { ...item, checked: taskShortcut.checked, children: taskShortcut.children }
+ : { ...item, children: nextChildren }
+ : item
),
}
})
diff --git a/frontend/src/lib/components/MarkdownNotebook/README.md b/frontend/src/lib/components/MarkdownNotebook/README.md
index 242eca79ed99..1d9889b68cf0 100644
--- a/frontend/src/lib/components/MarkdownNotebook/README.md
+++ b/frontend/src/lib/components/MarkdownNotebook/README.md
@@ -24,7 +24,7 @@ See [COMPONENTS.md](./COMPONENTS.md) for how to register embeddable components (
## Supported markdown
-Inline: bold (`**`/`__`), italic (`*`/`_`, underscores only at word boundaries), underline (`<u>`), strikethrough (`~~`), inline code, links (http/https only; balanced parentheses in hrefs supported), hard breaks, ref anchors (`<ref id="x">highlighted text</ref>`, lowercase inline tags so they can never collide with uppercase component tags), and mentions (`<mention id="5">@Name</mention>`; the text is the display label, the id is the member). Blocks: paragraphs, headings (`#`–`######` parse and round-trip; the UI offers H1–H3), blockquotes (including quoted lists), ordered/unordered lists with nesting, GFM tables with column alignment (header and body rows must start with `|`), fenced code blocks (language tag preserved; the serializer picks a fence longer than any backtick run in the content), dividers (`---`/`***`/`___`, stored as a reserved `Divider` component tag), images (`![alt](src)`, stored as the `Image` component), and JSX-like component tags.
+Inline: bold (`**`/`__`), italic (`*`/`_`, underscores only at word boundaries), underline (`<u>`), strikethrough (`~~`), inline code, links (http/https only; balanced parentheses in hrefs supported), hard breaks, ref anchors (`<ref id="x">highlighted text</ref>`, lowercase inline tags so they can never collide with uppercase component tags), and mentions (`<mention id="5">@Name</mention>`; the text is the display label, the id is the member). Blocks: paragraphs, headings (`#`–`######` parse and round-trip; the UI offers H1–H3), blockquotes (including quoted lists), ordered/unordered lists with nesting, GFM task lists (`- [ ]`/`- [x]` on bullet items; the checkbox replaces the bullet and `1. [x]` stays literal), GFM tables with column alignment (header and body rows must start with `|`), fenced code blocks (language tag preserved; the serializer picks a fence longer than any backtick run in the content), dividers (`---`/`***`/`___`, stored as a reserved `Divider` component tag), images (`![alt](src)`, stored as the `Image` component), and JSX-like component tags.
### Round-trip guarantee
diff --git a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts b/frontend/src/lib/components/MarkdownNotebook/documentModel.ts
index 0c05fbeba8a1..e4c1edc713f4 100644
--- a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/documentModel.ts
@@ -1,5 +1,5 @@
import { RestoreInlineSelectionRequest, RestoreSelectionRequest } from './editorTypes'
-import { removeInlineRefMark } from './inlineContent'
+import { removeInlineRefMark, splitInlineNodesAt } from './inlineContent'
import {
COMMENT_COMPONENT_TAG,
DIVIDER_COMPONENT_TAG,
@@ -303,13 +303,18 @@ export function normalizeNotebookTitlePasteBodyNode(node: NotebookBlockNode): No
}
}
-export function getListShortcut(text: string): { ordered: boolean; start?: number } | null {
+export function getListShortcut(text: string): { ordered: boolean; start?: number; checked?: boolean } | null {
const normalizedText = text.replace(/\u00a0/g, ' ')
const orderedMatch = normalizedText.match(/^(\d+)[.)]\s*$/)
if (orderedMatch) {
return { ordered: true, start: Number(orderedMatch[1]) }
}
+ const taskMatch = normalizedText.match(/^(?:[-*+•] )?\[( ?|x|X)\]\s+$/)
+ if (taskMatch) {
+ return { ordered: false, checked: taskMatch[1].toLowerCase() === 'x' }
+ }
+
if (/^[-*+•]\s+$/.test(normalizedText)) {
return { ordered: false }
}
@@ -317,6 +322,28 @@ export function getListShortcut(text: string): { ordered: boolean; start?: numbe
return null
}
+/**
+ * Detects a GFM task marker (`[ ] `, `[] `, `[x] `) typed at the start of a bullet list item,
+ * returning the item content with the marker stripped so the item can become a task.
+ */
+export function getTaskItemShortcut(
+ children: NotebookInlineNode[]
+): { checked: boolean; children: NotebookInlineNode[]; markerLength: number } | null {
+ const taskMatch = getInlineText(children)
+ .replace(/\u00a0/g, ' ')
+ .match(/^\[( ?|x|X)\] /)
+ if (!taskMatch) {
+ return null
+ }
+
+ const [, strippedChildren] = splitInlineNodesAt(children, taskMatch[0].length)
+ return {
+ checked: taskMatch[1].toLowerCase() === 'x',
+ children: strippedChildren,
+ markerLength: taskMatch[0].length,
+ }
+}
+
export type TextBlockShortcutReplacement = {
nodes: NotebookBlockNode[]
restoreSelection: RestoreSelectionRequest
@@ -407,6 +434,7 @@ export function getTextBlockShortcutReplacement(
depth: 0,
ordered: listShortcut.ordered,
start: listShortcut.start,
+ checked: listShortcut.checked,
},
],
},
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdown.ts b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
index 4529d6b8f515..6c2e795a79b4 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdown.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
@@ -38,6 +38,7 @@ const COMPONENT_START_REGEX = /^<[A-Z][A-Za-z0-9]*(\s|>|\/)/
const ORDERED_LIST_REGEX = /^\s*\d+[.)](?:\s+|$)/
const BULLET_LIST_REGEX = /^\s*[-*+•](?:\s+|$)/
const LIST_ITEM_REGEX = /^(\s*)(\d+[.)]|[-*+•])(?:\s+(.*))?$/
+const TASK_LIST_ITEM_REGEX = /^\[([ xX])\](?:\s+(.*))?$/
const HEADING_REGEX = /^(#{1,6})\s+(.*)$/
const IMAGE_BLOCK_REGEX = /^!\[((?:\\.|[^\]\\])*)\]\(((?:\\.|[^)\\])*)\)$/
const DIVIDER_BLOCK_REGEX = /^(?:-{3,}|\*{3,}|_{3,})$/
@@ -187,7 +188,8 @@ export function serializeNode(node: NotebookBlockNode): string {
} else {
orderedCounters[depth] = undefined
}
- return `${linePrefix}${' '.repeat(depth)}${marker} ${serializeInlineNodes(
+ const checkbox = !ordered && item.checked !== undefined ? (item.checked ? '[x] ' : '[ ] ') : ''
+ return `${linePrefix}${' '.repeat(depth)}${marker} ${checkbox}${serializeInlineNodes(
trimTrailingHardBreaks(item.children)
)}`
})
@@ -713,13 +715,16 @@ function parseListItemLine(line: string, listItemIndex: number): NotebookListBlo
}
const orderedMatch = match[2].match(/^(\d+)[.)]$/)
+ // GFM task markers only apply to bullet items — `1. [x]` stays literal text
+ const taskMatch = orderedMatch ? null : (match[3] ?? '').match(TASK_LIST_ITEM_REGEX)
return {
id: createStableNodeId(`list-item:${String(listItemIndex)}:${line}`, 0),
- children: parseInlineMarkdown(match[3] ?? ''),
+ children: parseInlineMarkdown(taskMatch ? (taskMatch[2] ?? '') : (match[3] ?? '')),
depth: getListItemDepth(match[1]),
ordered: orderedMatch !== null,
start: orderedMatch ? Number(orderedMatch[1]) : undefined,
+ checked: taskMatch ? taskMatch[1].toLowerCase() === 'x' : undefined,
}
}
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
index 2efb5d103ed8..3668315f2684 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
@@ -8,7 +8,7 @@ import {
NotebookTableBlockNode,
NotebookTextBlockNode,
} from './types'
-import { getNodeText } from './utils'
+import { getInlineText, getNodeText } from './utils'
function makeDocument(nodes: NotebookBlockNode[]): NotebookDocument {
return { type: 'doc', nodes, errors: [] }
@@ -65,6 +65,8 @@ const TEXT_PIECES = [
'#tag',
'- not a list',
'1. not ordered',
+ '[x] not a task',
+ '[ ] also not a task',
'| not | a | table |',
'<Important note',
'```',
@@ -147,6 +149,7 @@ describe('markdown round trip', () => {
depth,
ordered,
start: ordered ? 1 : undefined,
+ checked: !ordered && random() < 0.3 ? random() < 0.5 : undefined,
}
})
return { id: '', type: 'list', ordered, start: ordered ? 1 : undefined, items }
@@ -617,4 +620,69 @@ describe('markdown round trip', () => {
expect(list.items.map((item) => item.depth)).toEqual([0, 1, 0])
})
})
+
+ describe('task lists', () => {
+ it('parses checked and unchecked task markers on bullet items', () => {
+ const nodes = parseMarkdownNotebook('- [ ] open\n- [x] done\n- [X] also done\n- plain').nodes
+ const list = nodes[0] as NotebookListBlockNode
+
+ expect(list.items.map((item) => item.checked)).toEqual([false, true, true, undefined])
+ expect(list.items.map((item) => getInlineText(item.children))).toEqual([
+ 'open',
+ 'done',
+ 'also done',
+ 'plain',
+ ])
+ })
+
+ it('serializes task state back to GFM markers and reaches a fixpoint', () => {
+ const markdown = '- [ ] open\n- [x] done\n - [ ] nested open\n- plain'
+
+ expect(serializeMarkdownNotebook(parseMarkdownNotebook(markdown))).toEqual(markdown)
+ })
+
+ it('parses an empty task item without a trailing space', () => {
+ const list = parseMarkdownNotebook('- [ ]').nodes[0] as NotebookListBlockNode
+
+ expect(list.items[0].checked).toEqual(false)
+ expect(list.items[0].children).toEqual([])
+ })
+
+ it('keeps a task marker on an ordered item as literal text', () => {
+ const list = parseMarkdownNotebook('1. [x] not a task').nodes[0] as NotebookListBlockNode
+
+ expect(list.items[0].checked).toBeUndefined()
+ expect(getNodeText(list)).toEqual('[x] not a task')
+ })
+
+ it('does not parse a marker without following whitespace as a task', () => {
+ const list = parseMarkdownNotebook('- [x](https://posthog.com/docs) linked')
+ .nodes[0] as NotebookListBlockNode
+
+ expect(list.items[0].checked).toBeUndefined()
+ })
+
+ it('round-trips literal task-marker text in a bullet item without creating a task', () => {
+ const document = makeDocument([
+ {
+ id: '',
+ type: 'list',
+ ordered: false,
+ items: [{ children: [text('[x] literal marker')], depth: 0, ordered: false, start: undefined }],
+ },
+ ])
+ const result = roundTrip(document)
+ const list = result.nodes[0] as NotebookListBlockNode
+
+ expect(list.items[0].checked).toBeUndefined()
+ expect(getNodeText(list)).toEqual('[x] literal marker')
+ expect(stripIds(roundTrip(result))).toEqual(stripIds(result))
+ })
+
+ it('round-trips task items inside a blockquoted list', () => {
+ const markdown = '> - [x] quoted done\n> - [ ] quoted open'
+
+ expect(serializeMarkdownNotebook(parseMarkdownNotebook(markdown))).toEqual(markdown)
+ })
+ })
})
diff --git a/frontend/src/lib/components/MarkdownNotebook/types.ts b/frontend/src/lib/components/MarkdownNotebook/types.ts
index 4f9e9d6d796c..739bd706e852 100644
--- a/frontend/src/lib/components/MarkdownNotebook/types.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/types.ts
@@ -49,6 +49,8 @@ export type NotebookListItem = {
depth: number
ordered?: boolean
start?: number
+ /** GFM task list state (`- [ ]` / `- [x]`); only bullet items can be tasks. */
+ checked?: boolean
}
export type NotebookListBlockNode = {
diff --git a/frontend/src/lib/components/MarkdownNotebook/utils.ts b/frontend/src/lib/components/MarkdownNotebook/utils.ts
index 4885d2454519..2f4cf4613815 100644
--- a/frontend/src/lib/components/MarkdownNotebook/utils.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/utils.ts
@@ -151,6 +151,7 @@ function getListItemFingerprint(item: NotebookListItem): Omit<NotebookListItem,
depth: item.depth,
ordered: item.ordered,
start: item.start,
+ checked: item.checked,
}
}
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.ts
index 49db30be0af7..4c7126cb0fbd 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.ts
@@ -139,6 +139,119 @@ describe('markdownNotebookDowngrade', () => {
})
})
+ it('converts task lists to taskList with checked taskItems, nesting by depth', () => {
+ expect(convertMarkdownToNotebookContent('- [x] Done\n- [ ] Open\n - [ ] Nested open')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'taskList',
+ content: [
+ {
+ type: 'taskItem',
+ attrs: { checked: true },
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Done' }] }],
+ },
+ {
+ type: 'taskItem',
+ attrs: { checked: false },
+ content: [
+ { type: 'paragraph', content: [{ type: 'text', text: 'Open' }] },
+ {
+ type: 'taskList',
+ content: [
+ {
+ type: 'taskItem',
+ attrs: { checked: false },
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Nested open' }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ })
+ })
+
+ it('splits a plain item after a task run into a sibling bulletList', () => {
+ expect(convertMarkdownToNotebookContent('- [x] Task\n- Plain')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'taskList',
+ content: [
+ {
+ type: 'taskItem',
+ attrs: { checked: true },
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Task' }] }],
+ },
+ ],
+ },
+ { type: 'bulletList', content: [listItem('Plain')] },
+ ],
+ })
+ })
+
+ it('keeps the checked state of a task item that follows a plain item by splitting into a sibling taskList', () => {
+ expect(convertMarkdownToNotebookContent('- plain\n- [x] done')).toEqual({
+ type: 'doc',
+ content: [
+ { type: 'bulletList', content: [listItem('plain')] },
+ {
+ type: 'taskList',
+ content: [
+ {
+ type: 'taskItem',
+ attrs: { checked: true },
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'done' }] }],
+ },
+ ],
+ },
+ ],
+ })
+ })
+
+ it('splits a nested task run inside a plain list into a nested taskList without losing checked state', () => {
+ expect(convertMarkdownToNotebookContent('- Parent\n - [ ] Child task\n - Plain child')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ { type: 'paragraph', content: [{ type: 'text', text: 'Parent' }] },
+ {
+ type: 'taskList',
+ content: [
+ {
+ type: 'taskItem',
+ attrs: { checked: false },
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Child task' }],
+ },
+ ],
+ },
+ ],
+ },
+ { type: 'bulletList', content: [listItem('Plain child')] },
+ ],
+ },
+ ],
+ },
+ ],
+ })
+ })
+
it('wraps blockquoted lists in a blockquote', () => {
expect(convertMarkdownToNotebookContent('> - One\n> - Two')).toEqual({
type: 'doc',
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts
index c4484d22390e..cef40c748264 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts
@@ -51,13 +51,13 @@ export function convertMarkdownToNotebookContent(markdown: string): JSONContent
const document = parseMarkdownNotebook(markdown)
const content = document.nodes.flatMap((node) => {
const converted = convertBlockNode(node)
- return converted ? [converted] : []
+ return converted ? [converted].flat() : []
})
return { type: 'doc', content }
}
-function convertBlockNode(node: NotebookBlockNode): JSONContent | null {
+function convertBlockNode(node: NotebookBlockNode): JSONContent | JSONContent[] | null {
if (node.type === 'paragraph') {
return makeParagraph(convertInlineNodes(node.children))
}
@@ -69,8 +69,8 @@ function convertBlockNode(node: NotebookBlockNode): JSONContent | null {
return { type: 'blockquote', content: [makeParagraph(convertInlineNodes(node.children))] }
}
if (node.type === 'list') {
- const list = convertListNode(node)
- return node.blockquote ? { type: 'blockquote', content: [list] } : list
+ const lists = convertListNode(node)
+ return node.blockquote ? { type: 'blockquote', content: lists } : lists
}
if (node.type === 'table') {
return convertTableNode(node)
@@ -131,39 +131,64 @@ function convertComponentNode(node: NotebookComponentBlockNode): JSONContent | n
return makeParagraph(makeTextWithHardBreaks(serializeNode(node)))
}
-function convertListNode(node: NotebookListBlockNode): JSONContent {
+function convertListNode(node: NotebookListBlockNode): JSONContent[] {
// Inverse of `serializeList` in markdownNotebookV2.ts: items with greater depth nest into the
- // previous shallower item's listItem as a child list.
- const rootList = makeList(node.ordered, node.start)
- const listStack: JSONContent[] = [rootList]
+ // previous shallower item's listItem as a child list. taskList and bulletList items cannot
+ // mix, so a task/plain change at the same depth splits into sibling lists — checked state is
+ // never dropped.
+ const rootLists: JSONContent[] = []
+ const listStack: JSONContent[] = []
+ const isTaskItem = (item: NotebookListBlockNode['items'][number]): boolean =>
+ !(item.ordered ?? node.ordered) && item.checked !== undefined
+
+ const attachList = (list: JSONContent): void => {
+ const parentItems = listStack[listStack.length - 1]?.content
+ const parentItem = parentItems?.[parentItems.length - 1]
+ if (parentItem) {
+ parentItem.content = [...(parentItem.content ?? []), list]
+ } else {
+ rootLists.push(list)
+ }
+ listStack.push(list)
+ }
for (const item of node.items) {
+ const task = isTaskItem(item)
const depth = Math.max(0, item.depth)
while (listStack.length - 1 > depth) {
listStack.pop()
}
+ if (!listStack.length) {
+ attachList(makeList(node.ordered, node.start, task))
+ }
while (listStack.length - 1 < depth) {
- const parentItems = listStack[listStack.length - 1].content ?? []
- const parentItem = parentItems[parentItems.length - 1]
- if (!parentItem) {
+ if (!(listStack[listStack.length - 1].content ?? []).length) {
// Nothing to nest under — keep the item at the current depth.
break
}
- const nestedList = makeList(item.ordered ?? node.ordered, item.start)
- parentItem.content = [...(parentItem.content ?? []), nestedList]
- listStack.push(nestedList)
+ attachList(makeList(item.ordered ?? node.ordered, item.start, task))
+ }
+ if ((listStack[listStack.length - 1].type === 'taskList') !== task) {
+ listStack.pop()
+ attachList(makeList(item.ordered ?? node.ordered, item.start, task))
}
const currentList = listStack[listStack.length - 1]
+ const itemNode: JSONContent = task
+ ? { type: 'taskItem', attrs: { checked: item.checked ?? false } }
+ : { type: 'listItem' }
currentList.content = [
...(currentList.content ?? []),
- { type: 'listItem', content: [makeParagraph(convertInlineNodes(item.children))] },
+ { ...itemNode, content: [makeParagraph(convertInlineNodes(item.children))] },
]
}
- return rootList
+ return rootLists
}
-function makeList(ordered: boolean, start: number | undefined): JSONContent {
+function makeList(ordered: boolean, start: number | undefined, task: boolean): JSONContent {
+ if (!ordered && task) {
+ return { type: 'taskList', content: [] }
+ }
return {
type: ordered ? 'orderedList' : 'bulletList',
...(ordered && start !== undefined && start !== 1 ? { attrs: { start } } : {}),