Skip to content

Commit

Permalink
refactor: add legacyMarkdownAdapter for improved parsing of markdown …
Browse files Browse the repository at this point in the history
…source
  • Loading branch information
jiaojiaojiaoCpbr committed Oct 21, 2024
1 parent 08e568c commit 4081098
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
12 changes: 8 additions & 4 deletions packages/simple-markdown/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
* Many of the regexes and original logic has been adapted from
* the wonderful [marked.js](https://github.com/chjj/marked)
*/
import {legacyMarkdownAdapter} from "./legacyMarkdownAdapter";
import type {Capture, MatchFunction, State} from "./troublesome-types";
import type * as React from "react";

Expand Down Expand Up @@ -450,17 +451,20 @@ var parserFor = function (
source: string,
state?: State | null,
): Array<SingleASTNode> {
var legacyAdaptedStr = legacyMarkdownAdapter(source);
latestState = populateInitialState(state, defaultState);
if (!latestState.inline && !latestState.disableAutoBlockNewlines) {
source = source + "\n\n";
}
var str =
!latestState.inline && !latestState.disableAutoBlockNewlines
? legacyAdaptedStr + "\n\n"
: legacyAdaptedStr;

// We store the previous capture so that match functions can
// use some limited amount of lookbehind. Lists use this to
// ensure they don't match arbitrary '- ' or '* ' in inline
// text (see the list rule for more information). This stores
// the full regex capture object, if there is one.
latestState.prevCapture = null;
return nestedParse(preprocess(source), latestState);
return nestedParse(preprocess(str), latestState);
};

return outerParse;
Expand Down
19 changes: 19 additions & 0 deletions packages/simple-markdown/src/legacyMarkdownAdapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export const legacyMarkdownAdapter = (str: string) => {
// heading 前只有一個 \n 時,將 \n 改為 \n\n
const addedNewLineAboveHeadingStr = str.replace(
/(?<=[^\n]\n *)(#{1,6}.*)/g,
"\n$1",
);
// heading 後只有一個 \n 時,將 \n 改為 \n\n
const addedNewLineUnderHeadingStr = addedNewLineAboveHeadingStr.replace(
/(?<=\n *)(#{1,6}[^\n]*)(?=\n[^\n])/g,
"$1\n",
);
// hr 後只有一個 \n 時,將 \n 改為 \n\n
const addedNewLineUnderHrStr = addedNewLineUnderHeadingStr.replace(
/(?<=\n *)([-*_]{3,})(?=\n[^\n])/g,
"$1\n",
);

return addedNewLineUnderHrStr;
};

0 comments on commit 4081098

Please sign in to comment.