Skip to content

Commit

Permalink
Merge branch 'dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
sunsonliu committed Sep 23, 2024
2 parents bcb1b23 + fbf1f0c commit b749ef6
Show file tree
Hide file tree
Showing 22 changed files with 477 additions and 138 deletions.
197 changes: 197 additions & 0 deletions .github/workflows/pr-merge-dev-npm_preview.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
name: PR Merge Dev NPM Preview

# task:
# 1. 仅在主仓库中运行 (done)
# 2. 仅在pr合并时运行 (done)
# 3. 当pr合并时,获取pr合并后的commit id (done)
# 4. 根据commit id 修改package.json中的版本号和名称 (done)
# 5. 发布到npm (done)
# 6. 发布成功后,将发布的版本号和链接回复到当前pr下(done)
# 7. 发布成功后,将发布的版本号和链接回复到本repo的相关issue中 (done)
# 8. 修改README.md —— 提示dev版本需谨慎使用 (done)

on:
pull_request_target:
types:
- closed

permissions:
pull-requests: write
issues: write

jobs:
dev-deploy:
# 不需要在fork仓库的pr中运行, 仅当pr合并时运行
if: github.repository == 'Tencent/cherry-markdown' && github.event.pull_request.merged == true
runs-on: ubuntu-latest

steps:
# 检出仓库代码
- name: Checkout repository
uses:
actions/checkout@v4

# 获取PR合并后的SHA
- name: Get merge commit SHA
run: |
if [ "${{ github.event.pull_request.merged }}" == "true" ]; then
SHORT_SHA=$(echo "${{ github.event.pull_request.merge_commit_sha }}" | cut -c1-7)
echo "MERGE_COMMIT_SHORT_SHA=$SHORT_SHA" >> "$GITHUB_ENV"
else
echo "Not a merged PR, skipping"
fi

# 根据commit id 修改package.json中的版本号和名称
- name: dev package version and name
run: |
if [ -f package.json ]; then
# 获取当前版本号并添加 merge commit SHA
VERSION=$(node -p "require('./package.json').version")-dev.${{ env.MERGE_COMMIT_SHORT_SHA }}
# 设置环境变量
echo "PACKAGE_VERSION=$VERSION" >> "$GITHUB_ENV"
package_name="@cherry-markdown/preview-dev"
echo "PACKAGE_NAME=$package_name" >> "$GITHUB_ENV"
# 打印当前版本号
echo "Current version: $PACKAGE_VERSION"
# 修改 package.json 中的 name 和 version,并检查 scripts 中是否存在 publish 属性,如果存在则移除
jq --arg package_name "$package_name" --arg package_version "$VERSION" '
.name=$package_name |
.version=$package_version |
if .scripts.publish then del(.scripts.publish) else . end
' package.json > temp.json && mv temp.json package.json
# 打印修改后的 name 和 version
echo "Updated package.json:"
cat package.json | jq '.name, .version'
echo "$PACKAGE_VERSION"
# 检查 scripts 中是否存在 publish 属性,如果存在则移除
if jq -e '.scripts.publish' package.json > /dev/null; then
jq 'del(.scripts.publish)' package.json > temp.json && mv temp.json package.json
fi
else
echo "package.json 文件不存在"
fi
# 重写或创建 README.md 文件
echo -e '<p align="center"><img src="logo/new_logo.png" alt="cherry logo" width="50%"/></p>\n' > README.md
echo -e '# Cherry Markdown Writer\n' >> README.md
echo -e '> !WARNING\n This is a dev preview version of `Cherry Markdown`, please use it with caution. No responsibility for production versions.\n' >> README.md
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version: "18"
registry-url: https://registry.npmjs.org/

- name: yarn install
run: |
npm i yarn -g
yarn install
- name: build
run: yarn build

- name: npm publish
run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

- name: Comment on related issues
id: get-issues
uses: actions/github-script@v7
with:
result-encoding: string
retries: 3
retry-exempt-status-codes: 400,401
script: |
let issue_array =[context.issue.number];
// 添加issue到数组并去重
const addIssueToArray = (newIssues) => {
issue_array.push(...newIssues);
issue_array = [...new Set(issue_array)];
};
try {
// 获取pr的issue编号并且转换成数字数组
const getIssueRegex =(issueText)=>{
const issueRegex = /#(\d+)/g
return Array.from(issueText.matchAll(issueRegex), match => parseInt(match[1], 10));
};
const comment = `谢谢您的大力支持,请安装和此相关的测试版进行极速体验:
\`\`\`shell
npm install ${process.env.PACKAGE_NAME}@${process.env.package_version}
\`\`\`
[查看npm发布版本](https://www.npmjs.com/package/${process.env.PACKAGE_NAME}/v/${process.env.PACKAGE_VERSION}),请注意这是一个开发预览版本,请谨慎使用!`;

// 发布评论到issue
const createComment= async (issueNumbers) => {
if(typeof value === 'number' && !isNaN(value)) return;
issueNumbers.forEach(async (issueNumber) => {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
body: comment
});
});
};

// 获取当前提交的pr信息[title,body]
const { data: pullCommits } =
await github.rest.pulls.get({
owner:context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number
});
const pullCommitsIssueTitleNumbers = getIssueRegex(pullCommits.title);
addIssueToArray(pullCommitsIssueTitleNumbers);
const pullCommitsIssueBodyNumbers = getIssueRegex(pullCommits.body);
addIssueToArray(pullCommitsIssueBodyNumbers);

console.log('pullCommits-title',pullCommitsIssueTitleNumbers);
console.log('pullCommits-body',pullCommitsIssueBodyNumbers);

// 获取当前pr的issue信息[body]
const { data: listPrIssue } =
await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number
});
listPrIssue.forEach((item) => {
const listPrIssueIssueNumbers = getIssueRegex(item.body);
addIssueToArray(listPrIssueIssueNumbers);

console.log('listPrIssue',item.body);
console.log('listPrIssue',listPrIssueIssueNumbers);
});

// 获取当前pr的 review 信息[body]
const { data: listReviewComments } =
await github.rest.pulls.listReviewComments({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number
});
listReviewComments.forEach((item) => {
const listReviewCommentsIssueNumbers = getIssueRegex(item.body);
addIssueToArray(listReviewCommentsIssueNumbers);

console.log('listReviewComments',item.body);
console.log('listReviewComments',listReviewCommentsIssueNumbers);
});

createComment(issue_array);
}catch(error){
console.log('error',error);
}
File renamed without changes.
2 changes: 1 addition & 1 deletion client/src/components/CherryMarkdown/cherry.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,4 +283,4 @@ const initCherryMarkdown = () => {
})
}

export default initCherryMarkdown;
export default initCherryMarkdown;
1 change: 1 addition & 0 deletions examples/scripts/preview-demo.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ var cherryConfig = {
},
editor: {
defaultModel: 'previewOnly',
keepDocumentScrollAfterInit: true,
},
callback: {
onClickPreview: function(e) {
Expand Down
21 changes: 11 additions & 10 deletions src/Cherry.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,8 @@ export default class Cherry extends CherryStatic {
if (this.options.autoScrollByHashAfterInit) {
setTimeout(this.scrollByHash.bind(this));
}
// 强制进行一次渲染
this.editText(null, this.editor.editor);
// 强制进行一次渲染 // 不记得为啥要强制渲染了,先屏蔽了
// this.editText(null, this.editor.editor);
if (this.options.toolbars.toc !== false) {
this.createToc();
}
Expand Down Expand Up @@ -528,6 +528,8 @@ export default class Cherry extends CherryStatic {
mainTheme = getThemeFromLocal(true, this.nameSpace);
} else {
mainTheme = this.options.themeSettings.mainTheme;
mainTheme = mainTheme.replace(/theme__/g, '');
mainTheme = `theme__${mainTheme}`;
}
if (typeof this.options.toolbars.theme === 'string') {
toolbarTheme = this.options.toolbars.theme === 'dark' ? 'dark' : 'light';
Expand All @@ -543,9 +545,12 @@ export default class Cherry extends CherryStatic {
}
// @ts-ignore
if (typeof this.options.engine.syntax.codeBlock.theme === 'string') {
inlineCodeTheme = /** @type {{theme?: string;}} */ (this.options.engine.syntax.codeBlock).theme;
codeBlockTheme = /** @type {{theme?: string;}} */ (this.options.engine.syntax.codeBlock).theme;
} else {
inlineCodeTheme = this.options.themeSettings.codeBlockTheme;
codeBlockTheme = this.options.themeSettings.codeBlockTheme;
}
if (testHasLocal(this.nameSpace, 'codeTheme')) {
codeBlockTheme = getCodeThemeFromLocal(this.nameSpace);
}
if (codeBlockTheme === 'dark') codeBlockTheme = 'tomorrow-night';
else if (codeBlockTheme === 'light') codeBlockTheme = 'solarized-light';
Expand All @@ -554,9 +559,6 @@ export default class Cherry extends CherryStatic {
'data-inlineCodeTheme': inlineCodeTheme,
'data-codeBlockTheme': codeBlockTheme,
});

wrapperDom.setAttribute('data-code-block-theme', getCodeThemeFromLocal(this.nameSpace));

this.wrapperDom = wrapperDom;
return wrapperDom;
}
Expand Down Expand Up @@ -884,11 +886,10 @@ export default class Cherry extends CherryStatic {
initText(codemirror) {
try {
const markdownText = codemirror.getValue();
this.lastMarkdownText = markdownText;
const html = this.engine.makeHtml(markdownText);
this.previewer.update(html);
setTimeout(() => {
this.$event.emit('afterInit', { markdownText, html });
}, 10);
this.$event.emit('afterInit', { markdownText, html });
} catch (e) {
throw new NestedError(e);
}
Expand Down
8 changes: 8 additions & 0 deletions src/Engine.js
Original file line number Diff line number Diff line change
Expand Up @@ -258,10 +258,18 @@ export default class Engine {
$md = this.$beforeMakeHtml($md);
$md = this.$dealParagraph($md);
$md = this.$afterMakeHtml($md);
this.$fireHookAction($md, 'paragraph', '$cleanCache');
$md = this.$deCacheBigData($md);
return $md;
}

makeHtmlForBlockquote(md) {
let $md = md;
$md = this.$dealParagraph($md);
$md = this.$fireHookAction($md, 'paragraph', 'afterMakeHtml');
return $md;
}

mounted() {
this.$fireHookAction('', 'sentence', 'mounted');
this.$fireHookAction('', 'paragraph', 'mounted');
Expand Down
14 changes: 10 additions & 4 deletions src/Previewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -946,15 +946,21 @@ export default class Previewer {
* @return {boolean} 是否有对应id的元素并执行滚动
*/
scrollToId(id) {
const dom = this.getDomContainer();
const previewDom = this.getDomContainer();
const scrollDom = this.getDomCanScroll(previewDom);
let $id = id.replace(/^\s*#/, '').trim();
$id = /[%:]/.test($id) ? $id : encodeURIComponent($id);
const target = dom.querySelector(`[id="${$id}"]`) ?? false;
const target = previewDom.querySelector(`[id="${$id}"]`) ?? false;
if (target === false) {
return false;
}
const scrollTop = dom.scrollTop + target.getBoundingClientRect().y - dom.getBoundingClientRect().y - 20;
dom.scrollTo({
let scrollTop = 0;
if (scrollDom.nodeName === 'HTML') {
scrollTop = scrollDom.scrollTop + target.getBoundingClientRect().y - 20;
} else {
scrollTop = scrollDom.scrollTop + target.getBoundingClientRect().y - scrollDom.getBoundingClientRect().y - 20;
}
scrollDom.scrollTo({
top: scrollTop,
left: 0,
behavior: 'smooth',
Expand Down
38 changes: 28 additions & 10 deletions src/core/ParagraphBase.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,11 +249,12 @@ export default class ParagraphBase extends SyntaxBase {
return;
}
const $sign = sign || this.$engine.md5(str);
const key = `${this.cacheKey}I${$sign}_L${lineCount}$`;
this.cache[$sign] = {
content: str,
using: true,
key,
};
return `${this.cacheKey}I${$sign}_L${lineCount}$`;
return key;
}

popCache(sign) {
Expand All @@ -263,15 +264,28 @@ export default class ParagraphBase extends SyntaxBase {
return this.cache[sign].content || '';
}

testHasCache(sign) {
if (!this.needCache || !this.cache[sign]) {
return false;
}
return this.cache[sign].key;
}

// 当缓存全部被消费后,调用此方法清理多大的缓存
resetCache() {
if (!this.needCache) {
return;
}
for (const key of Object.keys(this.cache)) {
if (!this.cache[key].using) delete this.cache[key];
}
for (const key of Object.keys(this.cache)) {
this.cache[key].using = false;
// 当缓存队列比较大时,随机抛弃500个缓存
if (Object.keys(this.cache).length > 3000) {
let limit = 0;
for (const key of Object.keys(this.cache)) {
limit += 1;
if (limit > 500) {
return;
}
delete this.cache[key];
}
}
}

Expand All @@ -285,7 +299,13 @@ export default class ParagraphBase extends SyntaxBase {
'g',
);
const $html = html.replace(regex, (match, cacheSign) => this.popCache(cacheSign.replace(/_L\d+$/, '')));
this.resetCache();
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(() => {
this.resetCache();
}, 1000);
return $html;
}

Expand All @@ -299,8 +319,6 @@ export default class ParagraphBase extends SyntaxBase {
if (!this.cache[this.sign]) {
return this.toHtml(wholeMatch, sentenceMakeFunc);
}
// hit & mark cache
this.cache[this.sign].using = true;
return `${this.cacheKey}I${this.sign}_L${lineCount}$`;
}

Expand Down
Loading

0 comments on commit b749ef6

Please sign in to comment.