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 1 commit
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
8 changes: 7 additions & 1 deletion 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.copyCode; // 是否显示“编辑”按钮,由于和copy同时显示,则直接使用config.copy
Kaed3mi marked this conversation as resolved.
Show resolved Hide resolved
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,9 +200,14 @@ 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" ><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>'
? '<div class="cherry-copy-code-block" ><i class="ch-icon ch-icon-copy" title="copy"></i></div>'
Kaed3mi marked this conversation as resolved.
Show resolved Hide resolved
: ''
}
<pre class="language-${lang}">${this.wrapCode(cacheCode, lang)}</pre>
Expand Down
32 changes: 29 additions & 3 deletions src/sass/cherry.scss
Original file line number Diff line number Diff line change
Expand Up @@ -640,9 +640,17 @@
list-style: square;
}

.cherry-copy-code-block {
display: none;
}

.cherry-edit-code-block {
display: none;
}

div[data-type='codeBlock']:hover {
.cherry-copy-code-block {
display: block !important;
display: block;
Kaed3mi marked this conversation as resolved.
Show resolved Hide resolved
position: relative;
width: 25px;
text-align: center;
Expand All @@ -659,17 +667,35 @@
z-index: 2;
}

.cherry-edit-code-block {
Kaed3mi marked this conversation as resolved.
Show resolved Hide resolved
display: block;
position: relative;
width: 25px;
text-align: center;
height: 25px;
border: 1px solid #DDD;
cursor: pointer;
float: right;
right: 10+25+10px;
top: 15px;
color: #fff;
border-radius: 5px;
margin-left: -27px;
transition: all 0.3s;
z-index: 2;
}

// 浅色系
[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
14 changes: 14 additions & 0 deletions src/sass/previewer.scss
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,20 @@
}
}
}
.cherry-previewer-codeBlock-content-handler {
.cherry-previewer-codeBlock-content-handler__input {
position: absolute;
textarea {
Kaed3mi marked this conversation as resolved.
Show resolved Hide resolved
width: 100%;
height: 100%;
border: 0;
box-sizing: border-box;
resize: none;
outline: 1px solid #3582fb;
word-break: break-all;
}
}
}
.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
211 changes: 211 additions & 0 deletions src/utils/codeBlockContentHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
/**
* 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 'keyup':
return this.trigger === 'click';
Kaed3mi marked this conversation as resolved.
Show resolved Hide resolved
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) {
if ('.cherry-previewer-codeBlock-content-handler__input'.contains(event.target)) {
Kaed3mi marked this conversation as resolved.
Show resolved Hide resolved
this.$remove();
callback();
}
}
/**
* 定位代码块源代码在左侧Editor的位置
*/
$findCodeInEditor() {
this.$collectCodeBlockDom();
this.$collectCodeBlockCode();
this.$setSelection(this.codeBlockEditor.info.codeBlockIndex, 'code', this.trigger === 'click');
}
/**
* 定位代码块源代码在右侧Previewer的位置
Kaed3mi marked this conversation as resolved.
Show resolved Hide resolved
*/
$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),
};
console.log('codeBlockList: ');
console.log(list);
console.log('codeBlockNode: ');
console.log(codeBlockNode);
console.log('codeBlockNodeChildrenNodes: ');
console.log(codeBlockNode.childNodes);
Kaed3mi marked this conversation as resolved.
Show resolved Hide resolved
}
$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);
console.log(this.codeBlockEditor.info.code);
this.codeBlockEditor.editorDom.inputDom.focus();
this.codeBlockEditor.editorDom.inputDom.refresh();
editorInstance.setValue(this.codeMirror.getSelection());
editorInstance.setCursor(114514, 1919810);
Kaed3mi marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* 更新编辑器的位置(尺寸和位置)
*/
$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;
// console.log(codeBlockInfo);
// console.log(inputDiv);
// 设置文本框的偏移及大小
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(node = this.codeBlockEditor.info.codeBlockNode) {
Kaed3mi marked this conversation as resolved.
Show resolved Hide resolved
console.log(node);
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,
};
}
}