Skip to content

Commit

Permalink
feat: #642 close 增加配置,是否在初始化时保持页面的滚动位置
Browse files Browse the repository at this point in the history
  • Loading branch information
sunsonliu committed Dec 6, 2023
1 parent 5bbb803 commit b58de6d
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Cherry.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ const defaultConfig = {
autofocus: true,
},
writingStyle: 'normal', // 书写风格,normal 普通 | typewriter 打字机 | focus 专注,默认normal
keepDocumentScrollAfterInit: true, // 在初始化后是否保持网页的滚动,true:保持滚动;false:网页自动滚动到cherry初始化的位置
},
toolbars: {
theme: 'dark', // light or dark
Expand Down
23 changes: 23 additions & 0 deletions src/Editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -371,11 +371,33 @@ export default class Editor {
this.refreshWritingStatus();
};

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

/**
* 在cherry初始化后恢复到这个高度
*/
restoreDocumentScroll() {
if (!this.options.keepDocumentScrollAfterInit) {
return;
}
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 @@ -510,6 +532,7 @@ export default class Editor {
}
// 处理特殊字符,主要将base64等大文本替换成占位符,以提高可读性
this.dealSpecialWords();
this.restoreDocumentScroll();
}

/**
Expand Down
2 changes: 2 additions & 0 deletions types/cherry.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ export interface CherryEditorOptions {
codemirror?: object;
/** 书写风格,normal 普通 | typewriter 打字机 | focus 专注,默认normal */
writingStyle?: string;
/** 在初始化后是否保持网页的滚动,true:保持滚动;false:网页自动滚动到cherry初始化的位置 */
keepDocumentScrollAfterInit?: boolean;
}

export type CherryLifecycle = (text: string, html: string) => void;
Expand Down
1 change: 1 addition & 0 deletions types/editor.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export type EditorConfiguration = {
toolbars: any;
value?: string;
convertWhenPaste?: boolean;
keepDocumentScrollAfterInit?: boolean;
codemirror: CodeMirror.EditorConfiguration;
onKeydown: EditorEventCallback<EditorEventMap['onKeydown']>;
onFocus: EditorEventCallback<EditorEventMap['onFocus']>;
Expand Down

0 comments on commit b58de6d

Please sign in to comment.