diff --git a/apps/editor/src/__test__/unit/editor.spec.ts b/apps/editor/src/__test__/unit/editor.spec.ts index a33a9d1fa3..b6deace1b3 100644 --- a/apps/editor/src/__test__/unit/editor.spec.ts +++ b/apps/editor/src/__test__/unit/editor.spec.ts @@ -61,6 +61,27 @@ describe('editor', () => { document.body.removeChild(container); }); + describe('convertPosToMatchEditorMode', () => { + const mdPos: [number, number] = [2, 1]; + const wwPos = 14; + + it('should convert position to match editor mode', () => { + editor.setMarkdown('Hello World\nwelcome to the world'); + + editor.changeMode('wysiwyg'); + expect(editor.convertPosToMatchEditorMode(mdPos)).toEqual([wwPos, wwPos]); + + editor.changeMode('markdown'); + expect(editor.convertPosToMatchEditorMode(wwPos)).toEqual([mdPos, mdPos]); + }); + + it('should occurs error when types of parameters is not matched', () => { + expect(() => { + editor.convertPosToMatchEditorMode(mdPos, wwPos); + }).toThrowError(); + }); + }); + it('setPlaceholder()', () => { editor.setPlaceholder('Please input text'); diff --git a/apps/editor/src/editorCore.ts b/apps/editor/src/editorCore.ts index 85e5ad1e36..2b025790fa 100644 --- a/apps/editor/src/editorCore.ts +++ b/apps/editor/src/editorCore.ts @@ -43,6 +43,8 @@ import { sanitizeHTML } from './sanitizer/htmlSanitizer'; import { createHTMLSchemaMap } from './wysiwyg/nodes/html'; import { getHTMLRenderConvertors } from './markdown/htmlRenderConvertors'; import { buildQuery } from './queries/queryManager'; +import { getEditorToMdPos, getMdToEditorPos } from './markdown/helper/pos'; +import { Pos } from '@t/toastmark'; /** * ToastUIEditorCore @@ -820,6 +822,33 @@ class ToastUIEditorCore { wwEditor: this.wwEditor.getElement(), }; } + + /** + * Convert position to match editor mode + * @param {number|Array.} start - start position + * @param {number|Array.} end - end position + * @param {string} mode - Editor mode name of want to match converted position to + */ + convertPosToMatchEditorMode(start: EditorPos, end = start, mode = this.mode) { + const { doc } = this.mdEditor.view.state; + const isFromArray = Array.isArray(start); + const isToArray = Array.isArray(end); + + let convertedFrom = start; + let convertedTo = end; + + if (isFromArray !== isToArray) { + throw new Error('Types of arguments must be same'); + } + + if (mode === 'markdown' && !isFromArray && !isToArray) { + [convertedFrom, convertedTo] = getEditorToMdPos(doc, start as number, end as number); + } else if (mode === 'wysiwyg' && isFromArray && isToArray) { + [convertedFrom, convertedTo] = getMdToEditorPos(doc, start as Pos, end as Pos); + } + + return [convertedFrom, convertedTo]; + } } // // (Not an official API)