@gravity-ui/markdown-editor 14.3.1 → 14.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/build/cjs/bundle/Editor.d.ts +2 -0
  2. package/build/cjs/bundle/Editor.js +9 -2
  3. package/build/cjs/bundle/MarkdownEditorView.js +1 -0
  4. package/build/cjs/bundle/SplitModeView.js +1 -0
  5. package/build/cjs/bundle/config/markup.d.ts +41 -17
  6. package/build/cjs/bundle/config/markup.js +413 -308
  7. package/build/cjs/bundle/config/wysiwyg.d.ts +29 -18
  8. package/build/cjs/bundle/config/wysiwyg.js +526 -310
  9. package/build/cjs/bundle/sticky/sticky.css +1 -1
  10. package/build/cjs/bundle/types.d.ts +24 -0
  11. package/build/cjs/bundle/useMarkdownEditor.js +6 -2
  12. package/build/cjs/bundle/wysiwyg-preset.d.ts +11 -2
  13. package/build/cjs/bundle/wysiwyg-preset.js +1 -0
  14. package/build/cjs/extensions/behavior/Clipboard/utils.d.ts +1 -0
  15. package/build/cjs/extensions/behavior/Clipboard/utils.js +1 -0
  16. package/build/cjs/extensions/markdown/CodeBlock/handle-paste.js +5 -17
  17. package/build/cjs/extensions/yfm/YfmCut/YfmCutSpecs/const.d.ts +4 -0
  18. package/build/cjs/extensions/yfm/YfmCut/YfmCutSpecs/const.js +6 -1
  19. package/build/cjs/extensions/yfm/YfmCut/YfmCutSpecs/index.d.ts +8 -1
  20. package/build/cjs/extensions/yfm/YfmCut/YfmCutSpecs/index.js +11 -5
  21. package/build/cjs/extensions/yfm/YfmCut/YfmCutSpecs/parser.js +5 -1
  22. package/build/cjs/extensions/yfm/YfmCut/YfmCutSpecs/schema.d.ts +1 -1
  23. package/build/cjs/extensions/yfm/YfmCut/YfmCutSpecs/schema.js +8 -3
  24. package/build/cjs/extensions/yfm/YfmCut/YfmCutSpecs/serializer.d.ts +3 -1
  25. package/build/cjs/extensions/yfm/YfmCut/YfmCutSpecs/serializer.js +42 -24
  26. package/build/cjs/extensions/yfm/YfmFile/YfmFileSpecs/const.d.ts +12 -0
  27. package/build/cjs/extensions/yfm/YfmFile/YfmFileSpecs/const.js +30 -11
  28. package/build/cjs/extensions/yfm/YfmFile/YfmFileSpecs/index.d.ts +8 -1
  29. package/build/cjs/extensions/yfm/YfmFile/YfmFileSpecs/index.js +46 -24
  30. package/build/cjs/extensions/yfm/YfmFile/index.d.ts +1 -0
  31. package/build/cjs/extensions/yfm/YfmFile/index.js +1 -0
  32. package/build/cjs/index.d.ts +1 -1
  33. package/build/cjs/index.js +2 -1
  34. package/build/cjs/markup/codemirror/create.d.ts +8 -5
  35. package/build/cjs/markup/codemirror/create.js +43 -5
  36. package/build/cjs/markup/codemirror/directive-facet.d.ts +3 -0
  37. package/build/cjs/markup/codemirror/directive-facet.js +8 -0
  38. package/build/cjs/markup/codemirror/html-to-markdown/converters.d.ts +111 -0
  39. package/build/cjs/markup/codemirror/html-to-markdown/converters.js +214 -0
  40. package/build/cjs/markup/codemirror/html-to-markdown/handlers.d.ts +104 -0
  41. package/build/cjs/markup/codemirror/html-to-markdown/handlers.js +233 -0
  42. package/build/cjs/markup/codemirror/html-to-markdown/helpers.d.ts +1 -0
  43. package/build/cjs/markup/codemirror/html-to-markdown/helpers.js +21 -0
  44. package/build/cjs/markup/codemirror/index.d.ts +1 -0
  45. package/build/cjs/markup/codemirror/index.js +3 -1
  46. package/build/cjs/markup/codemirror/yfm.d.ts +5 -0
  47. package/build/cjs/markup/codemirror/yfm.js +26 -4
  48. package/build/cjs/markup/commands/inline.js +18 -8
  49. package/build/cjs/markup/commands/yfm.js +10 -1
  50. package/build/cjs/utils/clipboard.d.ts +14 -0
  51. package/build/cjs/utils/clipboard.js +36 -1
  52. package/build/cjs/utils/directive.d.ts +28 -0
  53. package/build/cjs/utils/directive.js +55 -0
  54. package/build/cjs/utils/index.d.ts +1 -0
  55. package/build/cjs/version.js +1 -1
  56. package/build/esm/bundle/Editor.d.ts +2 -0
  57. package/build/esm/bundle/Editor.js +9 -2
  58. package/build/esm/bundle/MarkdownEditorView.js +1 -0
  59. package/build/esm/bundle/SplitModeView.js +1 -0
  60. package/build/esm/bundle/config/markup.d.ts +41 -17
  61. package/build/esm/bundle/config/markup.js +411 -307
  62. package/build/esm/bundle/config/wysiwyg.d.ts +29 -18
  63. package/build/esm/bundle/config/wysiwyg.js +499 -284
  64. package/build/esm/bundle/sticky/sticky.css +1 -1
  65. package/build/esm/bundle/types.d.ts +24 -0
  66. package/build/esm/bundle/useMarkdownEditor.js +6 -2
  67. package/build/esm/bundle/wysiwyg-preset.d.ts +11 -2
  68. package/build/esm/bundle/wysiwyg-preset.js +1 -0
  69. package/build/esm/extensions/behavior/Clipboard/utils.d.ts +1 -0
  70. package/build/esm/extensions/behavior/Clipboard/utils.js +1 -0
  71. package/build/esm/extensions/markdown/CodeBlock/handle-paste.js +2 -14
  72. package/build/esm/extensions/yfm/YfmCut/YfmCutSpecs/const.d.ts +4 -0
  73. package/build/esm/extensions/yfm/YfmCut/YfmCutSpecs/const.js +5 -0
  74. package/build/esm/extensions/yfm/YfmCut/YfmCutSpecs/index.d.ts +8 -1
  75. package/build/esm/extensions/yfm/YfmCut/YfmCutSpecs/index.js +8 -3
  76. package/build/esm/extensions/yfm/YfmCut/YfmCutSpecs/parser.js +6 -2
  77. package/build/esm/extensions/yfm/YfmCut/YfmCutSpecs/schema.d.ts +1 -1
  78. package/build/esm/extensions/yfm/YfmCut/YfmCutSpecs/schema.js +8 -3
  79. package/build/esm/extensions/yfm/YfmCut/YfmCutSpecs/serializer.d.ts +3 -1
  80. package/build/esm/extensions/yfm/YfmCut/YfmCutSpecs/serializer.js +41 -24
  81. package/build/esm/extensions/yfm/YfmFile/YfmFileSpecs/const.d.ts +12 -0
  82. package/build/esm/extensions/yfm/YfmFile/YfmFileSpecs/const.js +21 -2
  83. package/build/esm/extensions/yfm/YfmFile/YfmFileSpecs/index.d.ts +8 -1
  84. package/build/esm/extensions/yfm/YfmFile/YfmFileSpecs/index.js +32 -10
  85. package/build/esm/extensions/yfm/YfmFile/index.d.ts +1 -0
  86. package/build/esm/extensions/yfm/YfmFile/index.js +2 -1
  87. package/build/esm/index.d.ts +1 -1
  88. package/build/esm/index.js +1 -1
  89. package/build/esm/markup/codemirror/create.d.ts +8 -5
  90. package/build/esm/markup/codemirror/create.js +42 -4
  91. package/build/esm/markup/codemirror/directive-facet.d.ts +3 -0
  92. package/build/esm/markup/codemirror/directive-facet.js +5 -0
  93. package/build/esm/markup/codemirror/html-to-markdown/converters.d.ts +111 -0
  94. package/build/esm/markup/codemirror/html-to-markdown/converters.js +210 -0
  95. package/build/esm/markup/codemirror/html-to-markdown/handlers.d.ts +104 -0
  96. package/build/esm/markup/codemirror/html-to-markdown/handlers.js +215 -0
  97. package/build/esm/markup/codemirror/html-to-markdown/helpers.d.ts +1 -0
  98. package/build/esm/markup/codemirror/html-to-markdown/helpers.js +17 -0
  99. package/build/esm/markup/codemirror/index.d.ts +1 -0
  100. package/build/esm/markup/codemirror/index.js +1 -0
  101. package/build/esm/markup/codemirror/yfm.d.ts +5 -0
  102. package/build/esm/markup/codemirror/yfm.js +25 -3
  103. package/build/esm/markup/commands/inline.js +18 -8
  104. package/build/esm/markup/commands/yfm.js +9 -1
  105. package/build/esm/utils/clipboard.d.ts +14 -0
  106. package/build/esm/utils/clipboard.js +32 -0
  107. package/build/esm/utils/directive.d.ts +28 -0
  108. package/build/esm/utils/directive.js +51 -0
  109. package/build/esm/utils/index.d.ts +1 -0
  110. package/build/esm/version.js +1 -1
  111. package/build/styles.css +1 -1
  112. package/package.json +10 -6
@@ -1,5 +1,6 @@
1
1
  import { ExtensionAuto } from '../../../core';
2
2
  import { FileUploadHandler } from '../../../utils/upload';
3
+ import '@diplodoc/file-extension/runtime/styles.css';
3
4
  export declare type YfmFileOptions = {
4
5
  fileUploadHandler?: FileUploadHandler;
5
6
  needToSetDimensionsForUploadedImages?: boolean;
@@ -4,6 +4,7 @@ exports.YfmFile = void 0;
4
4
  const YfmFilePaste_1 = require("./YfmFilePaste");
5
5
  const YfmFileSpecs_1 = require("./YfmFileSpecs");
6
6
  const YfmFileWidget_1 = require("./YfmFileWidget");
7
+ require("@diplodoc/file-extension/runtime/styles.css");
7
8
  const YfmFile = (builder, opts = {}) => {
8
9
  builder.use(YfmFileSpecs_1.YfmFileSpecs, opts);
9
10
  builder.use(YfmFileWidget_1.YfmFileWidget, opts);
@@ -11,7 +11,7 @@ export * from './forms';
11
11
  export * from './view';
12
12
  export * from './utils';
13
13
  export * from './bundle';
14
- export { ReactRendererFacet, getImageDimensions } from './markup';
14
+ export { DirectiveSyntaxFacet, ReactRendererFacet, getImageDimensions } from './markup';
15
15
  export * as MarkupCommands from './markup/commands';
16
16
  export * as MarkupHelpers from './markup/commands/helpers';
17
17
  export { Lang, configure } from './configure';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.serializeForClipboard = exports.getLastChildOfNode = exports.getChildrenOfNode = exports.findSelectedNodeOfType = exports.get$Cursor = exports.isWholeSelection = exports.isNodeSelection = exports.isTextSelection = exports.getPlaceholderContent = exports.isSameNodeType = exports.markTypeFactory = exports.nodeTypeFactory = exports.isSelectableNode = exports.isCodeBlock = exports.isNodeEmpty = exports.findFirstTextblockChild = exports.isMarkActive = exports.findMark = exports.inlineNodeInputRule = exports.nodeInputRule = exports.markInputRule = exports.isMac = exports.configure = exports.Lang = exports.MarkupHelpers = exports.MarkupCommands = exports.getImageDimensions = exports.ReactRendererFacet = void 0;
3
+ exports.serializeForClipboard = exports.getLastChildOfNode = exports.getChildrenOfNode = exports.findSelectedNodeOfType = exports.get$Cursor = exports.isWholeSelection = exports.isNodeSelection = exports.isTextSelection = exports.getPlaceholderContent = exports.isSameNodeType = exports.markTypeFactory = exports.nodeTypeFactory = exports.isSelectableNode = exports.isCodeBlock = exports.isNodeEmpty = exports.findFirstTextblockChild = exports.isMarkActive = exports.findMark = exports.inlineNodeInputRule = exports.nodeInputRule = exports.markInputRule = exports.isMac = exports.configure = exports.Lang = exports.MarkupHelpers = exports.MarkupCommands = exports.getImageDimensions = exports.ReactRendererFacet = exports.DirectiveSyntaxFacet = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  tslib_1.__exportStar(require("./common"), exports);
6
6
  tslib_1.__exportStar(require("./core"), exports);
@@ -16,6 +16,7 @@ tslib_1.__exportStar(require("./view"), exports);
16
16
  tslib_1.__exportStar(require("./utils"), exports);
17
17
  tslib_1.__exportStar(require("./bundle"), exports);
18
18
  var markup_1 = require("./markup");
19
+ Object.defineProperty(exports, "DirectiveSyntaxFacet", { enumerable: true, get: function () { return markup_1.DirectiveSyntaxFacet; } });
19
20
  Object.defineProperty(exports, "ReactRendererFacet", { enumerable: true, get: function () { return markup_1.ReactRendererFacet; } });
20
21
  Object.defineProperty(exports, "getImageDimensions", { enumerable: true, get: function () { return markup_1.getImageDimensions; } });
21
22
  exports.MarkupCommands = tslib_1.__importStar(require("./markup/commands"));
@@ -1,11 +1,12 @@
1
1
  import { autocompletion } from '@codemirror/autocomplete';
2
2
  import type { Extension, StateCommand } from '@codemirror/state';
3
- import { EditorView, EditorViewConfig, KeyBinding, placeholder } from '@codemirror/view';
3
+ import { EditorView, type EditorViewConfig, KeyBinding, placeholder } from '@codemirror/view';
4
4
  import type { ParseInsertedUrlAsImage } from '../../bundle';
5
- import { EventMap } from '../../bundle/Editor';
6
- import { ReactRenderStorage } from '../../extensions';
7
- import { Receiver } from '../../utils';
8
- import { FileUploadHandler } from './files-upload-facet';
5
+ import type { EventMap } from '../../bundle/Editor';
6
+ import type { ReactRenderStorage } from '../../extensions';
7
+ import type { Receiver } from '../../utils';
8
+ import type { DirectiveSyntaxContext } from '../../utils/directive';
9
+ import { type FileUploadHandler } from './files-upload-facet';
9
10
  import { type YfmLangOptions } from './yfm';
10
11
  export type { YfmLangOptions };
11
12
  declare type Autocompletion = Parameters<typeof autocompletion>[0];
@@ -19,6 +20,7 @@ export declare type CreateCodemirrorParams = {
19
20
  onScroll: (event: Event) => void;
20
21
  reactRenderer: ReactRenderStorage;
21
22
  uploadHandler?: FileUploadHandler;
23
+ parseHtmlOnPaste?: boolean;
22
24
  parseInsertedUrlAsImage?: ParseInsertedUrlAsImage;
23
25
  needImageDimensions?: boolean;
24
26
  enableNewImageSizeCalculation?: boolean;
@@ -30,6 +32,7 @@ export declare type CreateCodemirrorParams = {
30
32
  receiver?: Receiver<EventMap>;
31
33
  yfmLangOptions?: YfmLangOptions;
32
34
  autocompletion?: Autocompletion;
35
+ directiveSyntax: DirectiveSyntaxContext;
33
36
  };
34
37
  export declare function createCodemirror(params: CreateCodemirrorParams): EditorView;
35
38
  export declare function withLogger(action: string, command: StateCommand): StateCommand;
@@ -6,18 +6,20 @@ const commands_1 = require("@codemirror/commands");
6
6
  const language_1 = require("@codemirror/language");
7
7
  const view_1 = require("@codemirror/view");
8
8
  const action_names_1 = require("../../bundle/config/action-names");
9
- const utils_1 = require("../../extensions/behavior/Clipboard/utils");
10
9
  const logger_1 = require("../../logger");
11
10
  const shortcuts_1 = require("../../shortcuts");
11
+ const clipboard_1 = require("../../utils/clipboard");
12
12
  const commands_2 = require("../commands");
13
+ const directive_facet_1 = require("./directive-facet");
13
14
  const files_upload_facet_1 = require("./files-upload-facet");
14
15
  const gravity_1 = require("./gravity");
16
+ const converters_1 = require("./html-to-markdown/converters");
15
17
  const pairing_chars_1 = require("./pairing-chars");
16
18
  const react_facet_1 = require("./react-facet");
17
19
  const plugin_1 = require("./search-plugin/plugin");
18
20
  const yfm_1 = require("./yfm");
19
21
  function createCodemirror(params) {
20
- const { doc, reactRenderer, onCancel, onScroll, onSubmit, onChange, onDocChange, disabledExtensions = {}, keymaps = [], receiver, yfmLangOptions, extensions: extraExtensions, placeholder: placeholderContent, autocompletion: autocompletionConfig, parseInsertedUrlAsImage, } = params;
22
+ const { doc, reactRenderer, onCancel, onScroll, onSubmit, onChange, onDocChange, disabledExtensions = {}, keymaps = [], receiver, yfmLangOptions, extensions: extraExtensions, placeholder: placeholderContent, autocompletion: autocompletionConfig, parseHtmlOnPaste, parseInsertedUrlAsImage, directiveSyntax, } = params;
21
23
  const extensions = [gravity_1.gravityTheme, (0, view_1.placeholder)(placeholderContent)];
22
24
  if (!disabledExtensions.history) {
23
25
  extensions.push((0, commands_1.history)());
@@ -63,14 +65,50 @@ function createCodemirror(params) {
63
65
  ...commands_1.defaultKeymap,
64
66
  ...(disabledExtensions.history ? [] : commands_1.historyKeymap),
65
67
  ...keymaps,
66
- ]), (0, autocomplete_1.autocompletion)(autocompletionConfig), (0, yfm_1.yfmLang)(yfmLangOptions), react_facet_1.ReactRendererFacet.of(reactRenderer), pairing_chars_1.PairingCharactersExtension, view_1.EditorView.lineWrapping, view_1.EditorView.contentAttributes.of({ spellcheck: 'true' }), view_1.EditorView.domEventHandlers({
68
+ ]), (0, autocomplete_1.autocompletion)(autocompletionConfig), (0, yfm_1.yfmLang)(yfmLangOptions), react_facet_1.ReactRendererFacet.of(reactRenderer), directive_facet_1.DirectiveSyntaxFacet.of(directiveSyntax), pairing_chars_1.PairingCharactersExtension, view_1.EditorView.lineWrapping, view_1.EditorView.contentAttributes.of({ spellcheck: 'true' }), view_1.EditorView.domEventHandlers({
67
69
  scroll(event) {
68
70
  onScroll(event);
69
71
  },
70
72
  paste(event, editor) {
71
73
  var _a;
72
- if (event.clipboardData && parseInsertedUrlAsImage) {
73
- const { imageUrl, title } = parseInsertedUrlAsImage((_a = event.clipboardData.getData(utils_1.DataTransferType.Text)) !== null && _a !== void 0 ? _a : '') || {};
74
+ if (!event.clipboardData)
75
+ return;
76
+ // if clipboard contains YFM content - avoid any meddling with pasted content
77
+ // since text/yfm will contain valid markdown
78
+ const yfmContent = event.clipboardData.getData(clipboard_1.DataTransferType.Yfm);
79
+ if (yfmContent) {
80
+ event.preventDefault();
81
+ editor.dispatch(editor.state.replaceSelection(yfmContent));
82
+ return;
83
+ }
84
+ // checking if a copy buffer content is suitable for convertion
85
+ const shouldSkipHtml = (0, clipboard_1.shouldSkipHtmlConversion)(event.clipboardData);
86
+ // if we have text/html inside copy/paste buffer
87
+ const htmlContent = event.clipboardData.getData(clipboard_1.DataTransferType.Html);
88
+ // if we pasting markdown from VsCode we need skip html transformation
89
+ if (htmlContent && parseHtmlOnPaste && !shouldSkipHtml) {
90
+ let parsedMarkdownMarkup;
91
+ try {
92
+ const parser = new DOMParser();
93
+ const htmlDoc = parser.parseFromString(htmlContent, 'text/html');
94
+ const converter = new converters_1.MarkdownConverter();
95
+ parsedMarkdownMarkup = converter.processNode(htmlDoc.body).trim();
96
+ }
97
+ catch (e) {
98
+ // The code is pretty new and there might be random issues we haven't caught yet,
99
+ // especially with invalid HTML or weird DOM parsing errors.
100
+ // If something goes wrong, I just want to fall back to the "default pasting"
101
+ // rather than break the entire experience for the user.
102
+ logger_1.logger.error(e);
103
+ }
104
+ if (parsedMarkdownMarkup !== undefined) {
105
+ event.preventDefault();
106
+ editor.dispatch(editor.state.replaceSelection(parsedMarkdownMarkup));
107
+ return;
108
+ }
109
+ }
110
+ if (parseInsertedUrlAsImage) {
111
+ const { imageUrl, title } = parseInsertedUrlAsImage((_a = event.clipboardData.getData(clipboard_1.DataTransferType.Text)) !== null && _a !== void 0 ? _a : '') || {};
74
112
  if (!imageUrl) {
75
113
  return;
76
114
  }
@@ -0,0 +1,3 @@
1
+ import { Facet } from '@codemirror/state';
2
+ import type { DirectiveSyntaxContext } from '../../utils/directive';
3
+ export declare const DirectiveSyntaxFacet: Facet<DirectiveSyntaxContext, Omit<DirectiveSyntaxContext, "shouldSerializeToDirective">>;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DirectiveSyntaxFacet = void 0;
4
+ const state_1 = require("@codemirror/state");
5
+ exports.DirectiveSyntaxFacet = state_1.Facet.define({
6
+ combine: ([context]) => context,
7
+ static: true,
8
+ });
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Interface defining methods for visiting different types of HTML nodes.
3
+ * Each method corresponds to a specific HTML element type and returns its Markdown representation.
4
+ */
5
+ export interface HTMLNodeVisitor {
6
+ /** Converts a text node to Markdown */
7
+ visitText(node: Text): string;
8
+ /** Converts an anchor element to Markdown link syntax */
9
+ visitLink(node: HTMLAnchorElement): string;
10
+ /** Converts a header element to Markdown heading syntax */
11
+ visitHeader(node: HTMLElement, level: number): string;
12
+ /** Converts a paragraph element to Markdown */
13
+ visitParagraph(node: HTMLElement): string;
14
+ /** Converts formatting elements (bold, italic, etc.) to Markdown */
15
+ visitFormatting(node: HTMLElement): string;
16
+ /** Converts code elements to Markdown inline code syntax */
17
+ visitCode(node: HTMLElement): string;
18
+ /** Handles generic HTML elements with no specific Markdown conversion */
19
+ visitGeneric(node: HTMLElement): string;
20
+ /** Converts an HTML div element to Markdown format, adding a single newline */
21
+ visitDiv(node: HTMLElement): string;
22
+ /** Converts an HTML br element to a newline in Markdown */
23
+ visitBr(): string;
24
+ /** Converts a table row element to Markdown */
25
+ visitTableRow(node: HTMLTableRowElement): string;
26
+ /** Converts an HTML table element to Markdown table format */
27
+ visitTable(node: HTMLTableElement): string;
28
+ /** Convert img tag to Markdown image format */
29
+ visitImage(node: HTMLImageElement): string;
30
+ }
31
+ /**
32
+ * Main converter class that implements the visitor interface to convert HTML to Markdown.
33
+ * Uses the Chain of Responsibility pattern for handling different node types.
34
+ */
35
+ export declare class MarkdownConverter implements HTMLNodeVisitor {
36
+ private handler;
37
+ constructor();
38
+ /**
39
+ * Converts a text node to Markdown, escaping special characters.
40
+ */
41
+ visitText(node: Text): string;
42
+ /**
43
+ * Converts an HTML anchor element to Markdown link syntax.
44
+ */
45
+ visitLink(node: HTMLAnchorElement): string;
46
+ /**
47
+ * Converts an HTML heading element to Markdown heading syntax.
48
+ */
49
+ visitHeader(node: HTMLElement, level: number): string;
50
+ /**
51
+ * Converts an HTML paragraph to Markdown format.
52
+ */
53
+ visitParagraph(node: HTMLElement): string;
54
+ /**
55
+ * Applies Markdown formatting (bold, italic, etc.) to text content.
56
+ */
57
+ visitFormatting(node: HTMLElement): string;
58
+ /**
59
+ * Converts HTML code elements to Markdown inline code syntax.
60
+ */
61
+ visitCode(node: HTMLElement): string;
62
+ /**
63
+ * Handles generic HTML elements by processing their children.
64
+ */
65
+ visitGeneric(node: HTMLElement): string;
66
+ /**
67
+ * Converts an HTML div element to Markdown format, adding a single newline.
68
+ */
69
+ visitDiv(node: HTMLElement): string;
70
+ /**
71
+ * Converts an HTML br element to a newline in Markdown.
72
+ */
73
+ visitBr(): string;
74
+ /**
75
+ * Converts an HTML table row element to Markdown table row format.
76
+ */
77
+ visitTableRow(node: HTMLTableRowElement): string;
78
+ /**
79
+ * Converts an HTML table element to Markdown table format.
80
+ */
81
+ visitTable(node: HTMLTableElement): string;
82
+ /**
83
+ * Converts img tag to Markdown image format
84
+ */
85
+ visitImage(node: HTMLImageElement): string;
86
+ /**
87
+ * Processes a single node using the handler chain.
88
+ */
89
+ processNode(node: Node): string;
90
+ /**
91
+ * Creates and links together handlers in a specific order implementing the Chain of Responsibility pattern.
92
+ * @returns The first handler in the chain
93
+ */
94
+ private setupHandlerChain;
95
+ /**
96
+ * Recursively collects and processes text content from a node and its children.
97
+ */
98
+ private collectTextContent;
99
+ /**
100
+ * Collects raw text content from code elements.
101
+ */
102
+ private collectCodeContent;
103
+ /**
104
+ * Processes all child nodes of a given node.
105
+ */
106
+ private processChildren;
107
+ /**
108
+ * Gets the first handler in the chain.
109
+ */
110
+ private getHandler;
111
+ }
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MarkdownConverter = void 0;
4
+ const handlers_1 = require("./handlers");
5
+ const helpers_1 = require("./helpers");
6
+ /**
7
+ * Main converter class that implements the visitor interface to convert HTML to Markdown.
8
+ * Uses the Chain of Responsibility pattern for handling different node types.
9
+ */
10
+ class MarkdownConverter {
11
+ constructor() {
12
+ // Set up the chain of responsibility for handling different node types
13
+ this.handler = this.setupHandlerChain();
14
+ }
15
+ /**
16
+ * Converts a text node to Markdown, escaping special characters.
17
+ */
18
+ visitText(node) {
19
+ return (node.textContent || '').replace(/\n+/g, '').replace(/([<>])/g, '\\$1');
20
+ }
21
+ /**
22
+ * Converts an HTML anchor element to Markdown link syntax.
23
+ */
24
+ visitLink(node) {
25
+ var _a;
26
+ const linkText = this.collectTextContent(node);
27
+ const url = node.href || '';
28
+ // Handle links with formatted content vs plain text differently
29
+ const formattedText = node.childNodes.length === 1 && ((_a = node.firstChild) === null || _a === void 0 ? void 0 : _a.nodeType) === Node.TEXT_NODE
30
+ ? (0, helpers_1.applyFormatting)(linkText, node) // Plain text link
31
+ : Array.from(node.childNodes)
32
+ .map((child) => {
33
+ if (child.nodeType === Node.ELEMENT_NODE) {
34
+ return (0, helpers_1.applyFormatting)(child.textContent || '', child);
35
+ }
36
+ return child.textContent || '';
37
+ })
38
+ .join(''); // Apply formatting for each formatted child node
39
+ return `[${formattedText}](${url} "${linkText.replace(/"/g, '\\"')}")`;
40
+ }
41
+ /**
42
+ * Converts an HTML heading element to Markdown heading syntax.
43
+ */
44
+ visitHeader(node, level) {
45
+ const headerContent = this.collectTextContent(node);
46
+ return '#'.repeat(level) + ' ' + headerContent + '\n';
47
+ }
48
+ /**
49
+ * Converts an HTML paragraph to Markdown format.
50
+ */
51
+ visitParagraph(node) {
52
+ const content = this.processChildren(node);
53
+ return content.trim() + '\n\n';
54
+ }
55
+ /**
56
+ * Applies Markdown formatting (bold, italic, etc.) to text content.
57
+ */
58
+ visitFormatting(node) {
59
+ var _a;
60
+ if (node.childNodes.length === 1 && ((_a = node.firstChild) === null || _a === void 0 ? void 0 : _a.nodeType) === Node.TEXT_NODE) {
61
+ const text = this.collectTextContent(node);
62
+ return (0, helpers_1.applyFormatting)(text, node);
63
+ }
64
+ return (0, helpers_1.applyFormatting)(this.visitGeneric(node), node);
65
+ }
66
+ /**
67
+ * Converts HTML code elements to Markdown inline code syntax.
68
+ */
69
+ visitCode(node) {
70
+ const codeContent = this.collectCodeContent(node);
71
+ if (codeContent.includes('\n')) {
72
+ return '```\n' + codeContent + '\n```\n';
73
+ }
74
+ else if (codeContent.includes('`')) {
75
+ return '`` ' + codeContent + ' ``';
76
+ }
77
+ else {
78
+ return `\`${codeContent}\``;
79
+ }
80
+ }
81
+ /**
82
+ * Handles generic HTML elements by processing their children.
83
+ */
84
+ visitGeneric(node) {
85
+ return this.processChildren(node);
86
+ }
87
+ /**
88
+ * Converts an HTML div element to Markdown format, adding a single newline.
89
+ */
90
+ visitDiv(node) {
91
+ const content = this.processChildren(node);
92
+ return content + '\n'; // Add a single newline for <div>
93
+ }
94
+ /**
95
+ * Converts an HTML br element to a newline in Markdown.
96
+ */
97
+ visitBr() {
98
+ return '\n'; // Single newline for <br>
99
+ }
100
+ /**
101
+ * Converts an HTML table row element to Markdown table row format.
102
+ */
103
+ visitTableRow(node) {
104
+ const cells = Array.from(node.children).map((cell) => {
105
+ return this.visitGeneric(cell).trim() || '';
106
+ });
107
+ return '||\n' + cells.join('\n|\n') + '\n||';
108
+ }
109
+ /**
110
+ * Converts an HTML table element to Markdown table format.
111
+ */
112
+ visitTable(node) {
113
+ const rows = [];
114
+ const tableRows = Array.from(node.querySelectorAll('tr'));
115
+ tableRows.forEach((row) => {
116
+ rows.push(this.visitTableRow(row));
117
+ });
118
+ return '\n\n#|\n' + rows.join('\n') + '\n|#\n\n';
119
+ }
120
+ /**
121
+ * Converts img tag to Markdown image format
122
+ */
123
+ visitImage(node) {
124
+ const imgElement = node;
125
+ const altText = imgElement.alt || '';
126
+ const src = imgElement.src || '';
127
+ return `![${altText}](${src})`;
128
+ }
129
+ /**
130
+ * Processes a single node using the handler chain.
131
+ */
132
+ processNode(node) {
133
+ const result = this.getHandler().handle(node, this);
134
+ return result;
135
+ }
136
+ /**
137
+ * Creates and links together handlers in a specific order implementing the Chain of Responsibility pattern.
138
+ * @returns The first handler in the chain
139
+ */
140
+ setupHandlerChain() {
141
+ // Create handlers for each type of node
142
+ const textHandler = new handlers_1.TextNodeHandler();
143
+ const linkHandler = new handlers_1.LinkHandler();
144
+ const headerHandler = new handlers_1.HeaderHandler();
145
+ const paragraphHandler = new handlers_1.ParagraphHandler();
146
+ const formattingHandler = new handlers_1.FormattingHandler();
147
+ const codeHandler = new handlers_1.CodeHandler();
148
+ const genericHandler = new handlers_1.GenericHandler();
149
+ const orderedListHandler = new handlers_1.OrderedListHandler();
150
+ const unorderedListHandler = new handlers_1.UnorderedListHandler();
151
+ const divHandler = new handlers_1.DivHandler();
152
+ const brHandler = new handlers_1.BrHandler();
153
+ const tableRowHandler = new handlers_1.TableRowHandler();
154
+ const tableHandler = new handlers_1.TableHandler();
155
+ const imageHandler = new handlers_1.ImageHandler(); // New handler for <img>
156
+ // Chain handlers together in priority order
157
+ textHandler
158
+ .setNext(linkHandler)
159
+ .setNext(headerHandler)
160
+ .setNext(paragraphHandler)
161
+ .setNext(divHandler)
162
+ .setNext(brHandler)
163
+ .setNext(orderedListHandler)
164
+ .setNext(unorderedListHandler)
165
+ .setNext(formattingHandler)
166
+ .setNext(codeHandler)
167
+ .setNext(imageHandler) // Add image handler
168
+ .setNext(tableHandler)
169
+ .setNext(tableRowHandler)
170
+ .setNext(genericHandler);
171
+ return textHandler;
172
+ }
173
+ /**
174
+ * Recursively collects and processes text content from a node and its children.
175
+ */
176
+ collectTextContent(node) {
177
+ // handle seo elements (hide it's content)
178
+ if (node.className === 'visually-hidden') {
179
+ return '';
180
+ }
181
+ if (node.nodeType === Node.TEXT_NODE) {
182
+ return this.visitText(node);
183
+ }
184
+ return Array.from(node.childNodes)
185
+ .map((child) => this.collectTextContent(child))
186
+ .join('');
187
+ }
188
+ /**
189
+ * Collects raw text content from code elements.
190
+ */
191
+ collectCodeContent(node) {
192
+ if (node.nodeType === Node.TEXT_NODE) {
193
+ return node.textContent || '';
194
+ }
195
+ return Array.from(node.childNodes)
196
+ .map((child) => this.collectCodeContent(child))
197
+ .join('');
198
+ }
199
+ /**
200
+ * Processes all child nodes of a given node.
201
+ */
202
+ processChildren(node) {
203
+ return Array.from(node.childNodes)
204
+ .map((child) => this.processNode(child))
205
+ .join('');
206
+ }
207
+ /**
208
+ * Gets the first handler in the chain.
209
+ */
210
+ getHandler() {
211
+ return this.handler;
212
+ }
213
+ }
214
+ exports.MarkdownConverter = MarkdownConverter;
@@ -0,0 +1,104 @@
1
+ import { HTMLNodeVisitor } from './converters';
2
+ /**
3
+ * Base handler class implementing the Chain of Responsibility pattern for HTML node processing.
4
+ * Each concrete handler decides whether it can process a node or should pass it to the next handler.
5
+ */
6
+ export declare abstract class NodeHandler {
7
+ protected next: NodeHandler | null;
8
+ /**
9
+ * Sets up the next handler in the chain
10
+ */
11
+ setNext(handler: NodeHandler): NodeHandler;
12
+ /**
13
+ * Process the given node or delegate to the next handler
14
+ */
15
+ abstract handle(node: Node, visitor: HTMLNodeVisitor): string;
16
+ /**
17
+ * Delegates processing to the next handler in the chain
18
+ */
19
+ protected handleNext(node: Node, visitor: HTMLNodeVisitor): string;
20
+ }
21
+ /**
22
+ * Handles text nodes, converting them to markdown text
23
+ */
24
+ export declare class TextNodeHandler extends NodeHandler {
25
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
26
+ }
27
+ /**
28
+ * Handles anchor elements, converting them to markdown links
29
+ */
30
+ export declare class LinkHandler extends NodeHandler {
31
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
32
+ }
33
+ /**
34
+ * Handles header elements (h1-h6), converting them to markdown headers
35
+ */
36
+ export declare class HeaderHandler extends NodeHandler {
37
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
38
+ }
39
+ /**
40
+ * Handles paragraph elements, converting them to markdown paragraphs
41
+ */
42
+ export declare class ParagraphHandler extends NodeHandler {
43
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
44
+ }
45
+ /**
46
+ * Handles text formatting elements (b, strong, i, em), converting them to markdown formatting
47
+ */
48
+ export declare class FormattingHandler extends NodeHandler {
49
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
50
+ }
51
+ /**
52
+ * Handles code elements, converting them to markdown code blocks or inline code
53
+ */
54
+ export declare class CodeHandler extends NodeHandler {
55
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
56
+ }
57
+ /**
58
+ * Fallback handler for any HTML elements not handled by other specific handlers
59
+ */
60
+ export declare class GenericHandler extends NodeHandler {
61
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
62
+ }
63
+ /**
64
+ * Handles ordered list elements, converting them to markdown ordered lists
65
+ */
66
+ export declare class OrderedListHandler extends NodeHandler {
67
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
68
+ }
69
+ /**
70
+ * Handles unordered list elements, converting them to markdown unordered lists
71
+ */
72
+ export declare class UnorderedListHandler extends NodeHandler {
73
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
74
+ }
75
+ /**
76
+ * Handles div elements, converting them to markdown paragraphs
77
+ */
78
+ export declare class DivHandler extends NodeHandler {
79
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
80
+ }
81
+ /**
82
+ * Handles br elements, converting them to markdown newlines
83
+ */
84
+ export declare class BrHandler extends NodeHandler {
85
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
86
+ }
87
+ /**
88
+ * Handles table row elements, converting them to markdown table rows
89
+ */
90
+ export declare class TableRowHandler extends NodeHandler {
91
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
92
+ }
93
+ /**
94
+ * Handles table elements, converting them to markdown tables
95
+ */
96
+ export declare class TableHandler extends NodeHandler {
97
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
98
+ }
99
+ /**
100
+ * Handles image elements, converting them to markdown images
101
+ */
102
+ export declare class ImageHandler extends NodeHandler {
103
+ handle(node: Node, visitor: HTMLNodeVisitor): string;
104
+ }