Skip to content

Commit

Permalink
feat: #967 增加代码块是否自动换行配置 fix: #978 尝试修复editor.keepDocumentScrollAfter…
Browse files Browse the repository at this point in the history
…Init=true失效的问题
  • Loading branch information
sunsonliu committed Nov 17, 2024
1 parent 8f9a319 commit 2e54a7e
Show file tree
Hide file tree
Showing 13 changed files with 93 additions and 34 deletions.
3 changes: 2 additions & 1 deletion examples/scripts/preview-demo.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ var cherryConfig = {
toolbar: false,
// 配置目录
toc: {
updateLocationHash: false, // 要不要更新URL的hash
updateLocationHash: true, // 要不要更新URL的hash
defaultModel: 'full', // pure: 精简模式/缩略模式,只有一排小点; full: 完整模式,会展示所有标题
position: 'fixed', // 悬浮目录的悬浮方式。当滚动条在cherry内部时,用absolute;当滚动条在cherry外部时,用fixed
cssText: 'right: 20px;',
Expand All @@ -74,6 +74,7 @@ var cherryConfig = {
defaultModel: 'previewOnly',
keepDocumentScrollAfterInit: true,
},
autoScrollByHashAfterInit: true,
callback: {
onClickPreview: function(e) {
const {target} = e;
Expand Down
5 changes: 1 addition & 4 deletions src/Cherry.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,10 +239,7 @@ const defaultConfig = {
// theme: 'red',
},
codeBlock: {
/**
* @deprecated 不再支持theme的配置,统一在`themeSettings.codeBlockTheme`中配置
*/
// theme: 'dark', // 默认为深色主题
// theme: 'dark', // @deprecated 不再支持theme的配置,统一在`themeSettings.codeBlockTheme`中配置
wrap: true, // 超出长度是否换行,false则显示滚动条
lineNumber: true, // 默认显示行号
copyCode: true, // 是否显示“复制”按钮
Expand Down
39 changes: 39 additions & 0 deletions src/Cherry.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ import {
getCodeThemeFromLocal,
testHasLocal,
changeCodeTheme,
getCodeWrapFromLocal,
saveCodeWrapToLocal,
} from './utils/config';
import NestedError, { $expectTarget } from './utils/error';
import getPosBydiffs from './utils/recount-pos';
Expand Down Expand Up @@ -132,6 +134,7 @@ export default class Cherry extends CherryStatic {
* @private
*/
init() {
this.storeDocumentScroll();
let mountEl = this.options.id ? document.getElementById(this.options.id) : this.options.el;

if (!mountEl) {
Expand Down Expand Up @@ -236,6 +239,30 @@ export default class Cherry extends CherryStatic {
// this.editText(null, this.editor.editor);
this.createToc();
this.$event.bindCallbacksByOptions(this.options);
this.restoreDocumentScroll();
}

/**
* 记忆页面的滚动高度,在cherry初始化后恢复到这个高度
*/
storeDocumentScroll() {
if (!this.options.editor.keepDocumentScrollAfterInit) {
return;
}
this.needRestoreDocumentScroll = true;
this.documentElementScrollTop = document.documentElement.scrollTop;
this.documentElementScrollLeft = document.documentElement.scrollLeft;
}

/**
* 在cherry初始化后恢复到这个高度
*/
restoreDocumentScroll() {
if (!this.options.editor.keepDocumentScrollAfterInit || !this.needRestoreDocumentScroll) {
return;
}
this.needRestoreDocumentScroll = false;
window.scrollTo(this.documentElementScrollLeft, this.documentElementScrollTop);
}

destroy() {
Expand Down Expand Up @@ -556,15 +583,27 @@ export default class Cherry extends CherryStatic {
}
if (codeBlockTheme === 'dark') codeBlockTheme = 'tomorrow-night';
else if (codeBlockTheme === 'light') codeBlockTheme = 'solarized-light';
// @ts-ignore
const codeWrap = getCodeWrapFromLocal(this.nameSpace, this.options.engine.syntax.codeBlock.wrap);
const wrapperDom = createElement('div', ['cherry', 'clearfix', mainTheme].join(' '), {
'data-toolbarTheme': toolbarTheme,
'data-inlineCodeTheme': inlineCodeTheme,
'data-codeBlockTheme': codeBlockTheme,
'data-codeWrap': codeWrap === 'wrap' ? 'wrap' : 'nowrap',
});
this.wrapperDom = wrapperDom;
return wrapperDom;
}

getCodeWrap() {
return this.wrapperDom.dataset.codeWrap || 'wrap';
}

setCodeWrap(codeWrap) {
this.wrapperDom.dataset.codeWrap = codeWrap === 'wrap' ? 'wrap' : 'nowrap';
saveCodeWrapToLocal(this.nameSpace, codeWrap);
}

/**
* @private
* @returns {Toolbar}
Expand Down
25 changes: 0 additions & 25 deletions src/Editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -427,35 +427,11 @@ export default class Editor {
this.refreshWritingStatus();
};

/**
* 记忆页面的滚动高度,在cherry初始化后恢复到这个高度
*/
storeDocumentScroll() {
if (!this.options.keepDocumentScrollAfterInit) {
return;
}
this.needRestoreDocumentScroll = true;
this.documentElementScrollTop = document.documentElement.scrollTop;
this.documentElementScrollLeft = document.documentElement.scrollLeft;
}

/**
* 在cherry初始化后恢复到这个高度
*/
restoreDocumentScroll() {
if (!this.options.keepDocumentScrollAfterInit || !this.needRestoreDocumentScroll) {
return;
}
this.needRestoreDocumentScroll = false;
window.scrollTo(this.documentElementScrollLeft, this.documentElementScrollTop);
}

/**
*
* @param {*} previewer
*/
init(previewer) {
this.storeDocumentScroll();
const textArea = this.options.editorDom.querySelector(`#${this.options.id}`);
if (!(textArea instanceof HTMLTextAreaElement)) {
throw new Error('The specific element is not a textarea.');
Expand Down Expand Up @@ -596,7 +572,6 @@ export default class Editor {
}
// 处理特殊字符,主要将base64等大文本替换成占位符,以提高可读性
this.dealSpecialWords();
this.restoreDocumentScroll();
}

/**
Expand Down
3 changes: 1 addition & 2 deletions src/core/hooks/CodeBlock.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ export default class CodeBlock extends ParagraphBase {
this.codeCache = {};
this.customLang = [];
this.customParser = {};
this.wrap = config.wrap; // 超出是否换行
this.lineNumber = config.lineNumber; // 是否显示行号
this.copyCode = config.copyCode; // 是否显示“复制”按钮
this.expandCode = config.expandCode; // 是否显示“展开”按钮
Expand Down Expand Up @@ -178,7 +177,7 @@ export default class CodeBlock extends ParagraphBase {
* @param {string} lang
*/
wrapCode($code, lang) {
return `<code class="language-${lang}${this.wrap ? ' wrap' : ''}">${$code}</code>`;
return `<code class="language-${lang}">${$code}</code>`;
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/locales/en_US.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,5 @@ export default {
disableShortcut: 'Disable all shortcuts',
recoverShortcut: 'Restore default',
search: 'Search',
autoWrap: 'Auto Wrap',
};
1 change: 1 addition & 0 deletions src/locales/ru_RU.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,5 @@ export default {
disableShortcut: 'Отключить все горячие клавиши',
recoverShortcut: 'Восстановить по умолчанию',
search: 'Поиск',
autoWrap: 'Автоперенос строк',
};
1 change: 1 addition & 0 deletions src/locales/zh_CN.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,5 @@ export default {
disableShortcut: '禁用所有快捷键',
recoverShortcut: '恢复默认',
search: '搜索',
autoWrap: '自动换行',
};
1 change: 0 additions & 1 deletion src/sass/ch-icon.scss
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@
.ch-icon-chevronsLeft:before { content: "\EA70" }
.ch-icon-chevronsRight:before { content: "\EA71" }
.ch-icon-trendingUp:before { content: "\EA72" }
.ch-icon-inlineCode:before { content: "\EA0B" }
.ch-icon-codeBlock:before { content: "\EA74" }
.ch-icon-expand:before { content: "\EA75" }
.ch-icon-unExpand:before { content: "\EA76" }
Expand Down
4 changes: 4 additions & 0 deletions src/sass/markdown.scss
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,10 @@
div[data-type='codeBlock'] {
@import 'prism/tomorrow-night';

div[data-code-wrap='wrap'] & code[class*=language-]{
white-space: pre-wrap;
}

[data-code-block-theme='default'] & {
@import 'prism/default';
}
Expand Down
14 changes: 14 additions & 0 deletions src/toolbars/hooks/CodeTheme.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export default class CodeTheme extends MenuBase {
this.updateMarkdown = false;
this.noIcon = true;
this.subMenuConfig = [
{ noIcon: false, name: 'autoWrap', iconName: 'br', onclick: this.bindSubClick.bind(this, 'wrap') },
{ noIcon: true, name: 'light', onclick: this.bindSubClick.bind(this, 'default') },
{ noIcon: true, name: 'dark', onclick: this.bindSubClick.bind(this, 'dark') },
{ noIcon: true, name: 'one light', onclick: this.bindSubClick.bind(this, 'one-light') },
Expand All @@ -40,12 +41,25 @@ export default class CodeTheme extends MenuBase {
];
}

getActiveSubMenuIndex(subMenuDomPanel) {
const wrap = this.$cherry.getCodeWrap();
return wrap === 'wrap' ? 0 : -1;
}

/**
* 响应点击事件
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @param {string} codeTheme 具体的代码块主题
*/
onClick(shortKey = '', codeTheme) {
if (codeTheme === 'wrap') {
// 切换是否自动换行
const wrap = this.$cherry.getCodeWrap();
const newWrap = wrap === 'wrap' ? 'nowrap' : 'wrap';
this.$cherry.wrapperDom.dataset.codeWrap = newWrap;
this.$cherry.setCodeWrap(newWrap);
return;
}
this.$cherry.$event.emit('changeCodeBlockTheme', codeTheme);
changeCodeTheme(this.$cherry, codeTheme);
}
Expand Down
28 changes: 28 additions & 0 deletions src/utils/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,31 @@ export function changeCodeTheme($cherry, codeTheme) {

saveCodeThemeToLocal($cherry.nameSpace, newTheme);
}

/**
* 获取代码块是否换行的配置
* @param {string} nameSpace
* @param {boolean} defaultWrap
* @returns {string} 主题名
*/
export function getCodeWrapFromLocal(nameSpace = 'cherry', defaultWrap = true) {
let res = defaultWrap ? 'wrap' : 'nowrap';
if (typeof localStorage !== 'undefined') {
const localTheme = localStorage.getItem(`${nameSpace}-codeWrap`);
if (localTheme) {
res = localTheme;
}
}
return res;
}

/**
* 保存当前代码主题
* @param {string} nameSpace
* @param {string} wrap
*/
export function saveCodeWrapToLocal(nameSpace, wrap) {
if (typeof localStorage !== 'undefined') {
localStorage.setItem(`${nameSpace}-codeWrap`, wrap);
}
}
2 changes: 1 addition & 1 deletion vscodePlugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "cherry-markdown",
"displayName": "cherry-markdown",
"description": "A markdown previewer powered by [cherry-markdown](https://github.com/Tencent/cherry-markdown)",
"version": "0.0.16",
"version": "0.0.18",
"publisher": "cherryMarkdownPublisher",
"license": "Apache License",
"keywords": [
Expand Down

0 comments on commit 2e54a7e

Please sign in to comment.