Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: CodeBlock所见即所得支持 #549

Merged
merged 3 commits into from
Aug 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Cherry.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ const defaultConfig = {
wrap: true, // 超出长度是否换行,false则显示滚动条
lineNumber: true, // 默认显示行号
copyCode: true, // 是否显示“复制”按钮
editCode: true, // 是否显示“编辑”按钮
customRenderer: {
// 自定义语法渲染器
},
Expand Down
6 changes: 6 additions & 0 deletions src/core/hooks/CodeBlock.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export default class CodeBlock extends ParagraphBase {
this.wrap = config.wrap; // 超出是否换行
this.lineNumber = config.lineNumber; // 是否显示行号
this.copyCode = config.copyCode; // 是否显示“复制”按钮
this.editCode = config.editCode; // 是否显示“编辑”按钮
this.mermaid = config.mermaid; // mermaid的配置,目前仅支持格式设置,svg2img=true 展示成图片,false 展示成svg
this.indentedCodeBlock = typeof config.indentedCodeBlock === 'undefined' ? true : config.indentedCodeBlock; // 是否支持缩进代码块
this.INLINE_CODE_REGEX = /(`+)(.+?(?:\n.+?)*?)\1/g;
Expand Down Expand Up @@ -199,6 +200,11 @@ export default class CodeBlock extends ParagraphBase {
}
cacheCode = `<div data-sign="${sign}" data-type="codeBlock" data-lines="${lines}">
${getCodePreviewLangSelectElement($lang)}
${
this.editCode
? '<div class="cherry-edit-code-block" style="display:none;"><i class="ch-icon ch-icon-edit" title="edit"></i></div>'
: ''
}
${
this.copyCode
? '<div class="cherry-copy-code-block" style="display:none;"><i class="ch-icon ch-icon-copy" title="copy"></i></div>'
Expand Down
14 changes: 10 additions & 4 deletions src/sass/cherry.scss
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,7 @@
}

div[data-type='codeBlock']:hover {
.cherry-copy-code-block {
.cherry-copy-code-block, .cherry-edit-code-block {
display: block !important;
position: relative;
width: 25px;
Expand All @@ -650,26 +650,32 @@
border: 1px solid #ddd;
cursor: pointer;
float: right;
right: 10px;
//right: 10px; right: 10+25+10px
top: 15px;
color: #fff;
border-radius: 5px;
margin-left: -27px;
transition: all 0.3s;
z-index: 2;
}
.cherry-copy-code-block {
right: 10px;
}
.cherry-edit-code-block {
Kaed3mi marked this conversation as resolved.
Show resolved Hide resolved
right: 10+25+10px;
}

// 浅色系
[data-code-block-theme='default'] &,
[data-code-block-theme='funky'] &,
[data-code-block-theme='solarized-light'] &,
[data-code-block-theme='coy'] & {
.cherry-copy-code-block {
.cherry-copy-code-block, .cherry-edit-code-block {
background-color: #3582fb;
}
}

.cherry-copy-code-block:hover {
.cherry-copy-code-block:hover, .cherry-edit-code-block:hover {
color: #3582fb;
background-color: #eee;
border-color: #3582fb;
Expand Down
5 changes: 5 additions & 0 deletions src/sass/previewer.scss
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,11 @@
}
}
}
.cherry-previewer-codeBlock-content-handler {
.cherry-previewer-codeBlock-content-handler__input {
position: absolute;
}
}
.cherry-previewer-table-hover-handler {
position: absolute;
pointer-events: none;
Expand Down
19 changes: 19 additions & 0 deletions src/toolbars/PreviewerBubble.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import imgSizeHander from '@/utils/imgSizeHander';
import TableHandler from '@/utils/tableContentHander';
import CodeHandler from '@/utils/codeBlockContentHandler';
import { drawioDialog } from '@/utils/dialog';
import Event from '@/Event';
import { copyToClip } from '@/utils/copy';
Expand Down Expand Up @@ -250,6 +251,7 @@ export default class PreviewerBubble {
}
break;
}
this.$dealCodeBlockEditorMode(e);
}

$onChange(e) {
Expand All @@ -270,6 +272,16 @@ export default class PreviewerBubble {
return this.$getClosestNode(node.parentNode, targetNodeName);
}

/**
* 处理编辑代码块的操作
*/
$dealCodeBlockEditorMode(e) {
const { target } = e;
if (target.className === 'cherry-edit-code-block' || target.parentNode?.className === 'cherry-edit-code-block') {
this.$showCodeBlockPreviewerBubbles('click', e.target);
}
}

/**
* 处理复制代码块的操作
*/
Expand Down Expand Up @@ -325,6 +337,13 @@ export default class PreviewerBubble {
this.bubbleHandler[trigger] = handler;
}

$showCodeBlockPreviewerBubbles(trigger, htmlElement) {
this.$createPreviewerBubbles(trigger, trigger === 'click' ? 'codeBlock-content-handler' : 'none');
const handler = new CodeHandler(trigger, htmlElement, this.bubble[trigger], this.previewerDom, this.editor.editor);
handler.showBubble();
this.bubbleHandler[trigger] = handler;
}

/**
* 为选中的图片增加操作工具栏
* @param {HTMLImageElement} htmlElement 用户点击的图片dom
Expand Down
201 changes: 201 additions & 0 deletions src/utils/codeBlockContentHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { getCodeBlockRule } from '@/utils/regexp';
import codemirror from 'codemirror';

export default class CodeBlockHandler {
/**
* 用来存放所有的数据
*/
codeBlockEditor = {
info: {}, // 当前点击的预览区域code的相关信息
editorDom: {}, // 编辑器容器
};

constructor(trigger, target, container, previewerDom, codeMirror) {
// 触发方式 click / hover
this.trigger = trigger;
this.target = target;
this.previewerDom = previewerDom;
this.container = container;
this.codeMirror = codeMirror;
this.$initReg();
this.$findCodeInEditor();
}

$initReg() {
this.codeBlockReg = this.codeBlockReg ? this.codeBlockReg : getCodeBlockRule().reg;
}

emit(type, event = {}, callback = () => {}) {
switch (type) {
case 'remove':
return this.$remove();
case 'scroll':
return this.$refreshPosition();
case 'previewUpdate':
return this.$refreshPosition();
case 'mouseup':
return this.trigger === 'click' && this.$tryRemoveMe(event, callback);
}
}
$remove() {
this.codeBlockEditor = { info: {}, codeBlockCodes: [], editorDom: {} };
}
/**
* 刷新定位
*/
$refreshPosition() {
if (this.trigger === 'click') {
this.$setInputOffset();
}
}
$tryRemoveMe(event, callback) {
const dom = document.querySelector('.cherry-previewer-codeBlock-content-handler__input');
if (!dom.contains(event.target)) {
this.$remove();
callback();
}
}
/**
* 定位代码块源代码在左侧Editor的位置
*/
$findCodeInEditor() {
this.$collectCodeBlockDom();
this.$collectCodeBlockCode();
this.$setSelection(this.codeBlockEditor.info.codeBlockIndex, 'code', this.trigger === 'click');
}
/**
* 找到预览区被点击编辑按钮的代码块,并记录这个代码块在预览区域所有代码块中的顺位
*/
$collectCodeBlockDom() {
const list = Array.from(this.previewerDom.querySelectorAll('[data-type="codeBlock"]'));
const { target } = this;
const codeBlockNode =
target.className === 'cherry-edit-code-block' ? target.parentNode : target.parentNode.parentNode;
this.codeBlockEditor.info = {
codeBlockNode,
codeBlockIndex: list.indexOf(codeBlockNode),
};
}
$collectCodeBlockCode() {
const codeBlockCodes = [];
this.codeMirror.getValue().replace(this.codeBlockReg, function (whole, ...args) {
const match = whole.replace(/^\n*/, '');
const offsetBegin = args[args.length - 2] + whole.match(/^\n*/)[0].length;
if (!match.startsWith('```mermaid')) {
codeBlockCodes.push({
code: match,
offset: offsetBegin,
});
}
});
this.codeBlockEditor.codeBlockCodes = codeBlockCodes;
}
$setSelection(index, type = 'code', select = true) {
const codeBlockCode = this.codeBlockEditor.codeBlockCodes[index];
// console.log('选中代码块: ');
// console.log(codeBlockCode);
const whole = this.codeMirror.getValue();
const beginLine = whole.slice(0, codeBlockCode.offset).match(/\n/g)?.length ?? 0;
const endLine = beginLine + codeBlockCode.code.match(/\n/g).length;
const endCh = codeBlockCode.code.slice(0, -3).match(/[^\n]+\n*$/)[0].length;
this.codeBlockEditor.info.selection = [
{ line: beginLine + 1, ch: 0 },
{ line: endLine - 1, ch: endCh },
];
select && this.codeMirror.setSelection(...this.codeBlockEditor.info.selection);
}
showBubble() {
if (this.trigger === 'click') {
this.$drawEditor();
}
}
$drawEditor() {
const dom = document.createElement('div');
dom.className = 'cherry-previewer-codeBlock-content-handler__input';
const input = document.createElement('textarea');
input.id = 'codeMirrorEditor';
dom.appendChild(input);
const editorInstance = codemirror.fromTextArea(input, {
mode: '',
theme: 'default',
scrollbarStyle: 'null', // 取消滚动动画
lineNumbers: true, // 显示行号
autofocus: true, // 自动对焦
lineWrapping: true, // 自动换行
});
const editor = this.codeMirror;
editorInstance.on('change', () => {
editor.replaceSelection(editorInstance.getValue(), 'around');
});
this.codeBlockEditor.editorDom.inputDiv = dom;
this.codeBlockEditor.editorDom.inputDom = editorInstance;
this.$updateEditorPosition();
this.container.appendChild(this.codeBlockEditor.editorDom.inputDiv);
this.codeBlockEditor.editorDom.inputDom.focus();
this.codeBlockEditor.editorDom.inputDom.refresh();
editorInstance.setValue(this.codeMirror.getSelection());
editorInstance.setCursor(Number.MAX_VALUE, Number.MAX_VALUE); // 指针设置至CodeBlock末尾
}

/**
* 更新编辑器的位置(尺寸和位置)
*/
$updateEditorPosition() {
this.$setInputOffset();
const spanStyle = getComputedStyle(this.codeBlockEditor.info.codeBlockNode);
this.codeBlockEditor.editorDom.inputDom.getWrapperElement().style.fontSize = spanStyle.fontSize || '16px';
this.codeBlockEditor.editorDom.inputDom.getWrapperElement().style.fontFamily = spanStyle.fontFamily;
this.codeBlockEditor.editorDom.inputDom.getWrapperElement().style.lineHeight = spanStyle.lineHeight;
this.codeBlockEditor.editorDom.inputDom.getWrapperElement().style.padding = spanStyle.padding;
this.codeBlockEditor.editorDom.inputDom.getWrapperElement().style.paddingBottom = '0px';
this.codeBlockEditor.editorDom.inputDom.getWrapperElement().style.zIndex = '1';
}

/**
* 设置codemirror偏移
*/
$setInputOffset() {
const codeBlockInfo = this.$getPosition();
const { inputDiv } = this.codeBlockEditor.editorDom;
// 设置文本框的偏移及大小
this.setStyle(inputDiv, 'width', `${codeBlockInfo.width}px`);
this.setStyle(inputDiv, 'height', `${codeBlockInfo.height}px`);
this.setStyle(inputDiv, 'top', `${codeBlockInfo.top}px`);
this.setStyle(inputDiv, 'left', `${codeBlockInfo.left}px`);
}

setStyle(element, property, value) {
const info = element.getBoundingClientRect();
if (info[property] !== value) {
element.style[property] = value;
}
}

$getPosition() {
const node = this.codeBlockEditor.info.codeBlockNode;
const position = node.getBoundingClientRect();
const editorPosition = this.previewerDom.parentNode.getBoundingClientRect();
return {
top: position.top - editorPosition.top,
height: position.height,
width: position.width,
left: position.left - editorPosition.left,
maxHeight: editorPosition.height,
};
}
}
Loading