From 301a620a25acd3106bf3942fddfb7bc3e4b084c5 Mon Sep 17 00:00:00 2001 From: antoine Date: Sun, 3 Dec 2023 09:21:09 +0100 Subject: [PATCH] Allow to insert adjacent ordered lists --- __tests__/serialize.spec.js | 4 ++++ src/extensions/nodes/ordered-list.js | 17 ++++++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/__tests__/serialize.spec.js b/__tests__/serialize.spec.js index db56aeb..8a0e102 100644 --- a/__tests__/serialize.spec.js +++ b/__tests__/serialize.spec.js @@ -80,6 +80,10 @@ describe('serialize', () => { expect(serialize('
  1. example1
  2. example2
')) .toEqual('10. example1\n11. example2'); }); + test('adjacent ordered list', () => { + expect(serialize('
  1. example1
  1. example2
  1. example3
')) + .toEqual('1. example1\n\n\n1) example2\n\n\n1. example3'); // prosemirror-markdown insert 3 \n, only 2 are needed + }) test('fence', () => { expect(serialize('
example
')).toEqual('```js\nexample\n```'); }) diff --git a/src/extensions/nodes/ordered-list.js b/src/extensions/nodes/ordered-list.js index 207c898..d16bfd4 100644 --- a/src/extensions/nodes/ordered-list.js +++ b/src/extensions/nodes/ordered-list.js @@ -1,11 +1,20 @@ import { Node } from "@tiptap/core"; -import { defaultMarkdownSerializer } from "prosemirror-markdown"; const OrderedList = Node.create({ name: 'orderedList', }); +function findIndexOfAdjacentNode(node, parent, index) { + let i = 0; + for (; index - i > 0; i++) { + if (parent.child(index - i - 1).type.name !== node.type.name) { + break; + } + } + return i; +} + export default OrderedList.extend({ /** * @return {{markdown: MarkdownNodeSpec}} @@ -13,13 +22,15 @@ export default OrderedList.extend({ addStorage() { return { markdown: { - serialize(state,node) { + serialize(state, node, parent, index) { const start = node.attrs.start || 1 const maxW = String(start + node.childCount - 1).length const space = state.repeat(" ", maxW + 2) + const adjacentIndex = findIndexOfAdjacentNode(node, parent, index); + const separator = adjacentIndex % 2 ? ') ' : '. '; state.renderList(node, space, i => { const nStr = String(start + i) - return state.repeat(" ", maxW - nStr.length) + nStr + ". " + return state.repeat(" ", maxW - nStr.length) + nStr + separator; }) }, parse: {