mirror of
https://github.com/naturalcrit/homebrewery.git
synced 2026-03-26 21:18:12 +00:00
not really working but it will
This commit is contained in:
@@ -36,6 +36,53 @@ const highlightStyle = HighlightStyle.define([
|
|||||||
// …
|
// …
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
/*custom tokens */
|
||||||
|
import { Decoration, ViewPlugin, WidgetType } from "@codemirror/view";
|
||||||
|
import { tokenizeCustomMarkdown, customTags } from "./customMarkdownGrammar.js";
|
||||||
|
|
||||||
|
const customHighlightStyle = HighlightStyle.define([
|
||||||
|
{ tag: tags.heading1, color: "#000", fontWeight: "700" },
|
||||||
|
{ tag: tags.keyword, color: "#07a" }, // example for your markdown headings
|
||||||
|
{ tag: customTags.pageLine, color: "#f0a" },
|
||||||
|
{ tag: customTags.snippetBreak, class: "cm-snippet-break", color: "#0af" },
|
||||||
|
{ tag: customTags.inlineBlock, class: "cm-inline-block", backgroundColor: "#fffae6" },
|
||||||
|
{ tag: customTags.emoji, class: "cm-emoji", color: "#fa0" },
|
||||||
|
{ tag: customTags.superscript, class: "cm-superscript", verticalAlign: "super", fontSize: "0.8em" },
|
||||||
|
{ tag: customTags.subscript, class: "cm-subscript", verticalAlign: "sub", fontSize: "0.8em" },
|
||||||
|
{ tag: customTags.definitionTerm, class: "cm-dt", fontWeight: "bold", color: "#0a0" },
|
||||||
|
{ tag: customTags.definitionDesc, class: "cm-dd", color: "#070" },
|
||||||
|
]);
|
||||||
|
|
||||||
|
const customHighlightPlugin = ViewPlugin.fromClass(
|
||||||
|
class {
|
||||||
|
constructor(view) {
|
||||||
|
this.decorations = this.buildDecorations(view);
|
||||||
|
}
|
||||||
|
update(update) {
|
||||||
|
if (update.docChanged) {
|
||||||
|
this.decorations = this.buildDecorations(update.view);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buildDecorations(view) {
|
||||||
|
const widgets = [];
|
||||||
|
const tokens = tokenizeCustomMarkdown(view.state.doc.toString());
|
||||||
|
|
||||||
|
// sort by line number
|
||||||
|
tokens.sort((a, b) => a.line - b.line);
|
||||||
|
|
||||||
|
tokens.forEach((tok) => {
|
||||||
|
const line = view.state.doc.line(tok.line + 1); // CM lines are 1-based
|
||||||
|
widgets.push(Decoration.line({ class: `cm-${tok.type}` }).range(line.from));
|
||||||
|
});
|
||||||
|
|
||||||
|
return Decoration.set(widgets);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
decorations: (v) => v.decorations,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
const CodeEditor = forwardRef(
|
const CodeEditor = forwardRef(
|
||||||
(
|
(
|
||||||
{
|
{
|
||||||
@@ -116,6 +163,8 @@ const CodeEditor = forwardRef(
|
|||||||
lineNumbers(),
|
lineNumbers(),
|
||||||
themeExtension,
|
themeExtension,
|
||||||
syntaxHighlighting(highlightStyle),
|
syntaxHighlighting(highlightStyle),
|
||||||
|
customHighlightPlugin,
|
||||||
|
syntaxHighlighting(customHighlightStyle),
|
||||||
];
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
95
client/components/codeEditor/customMarkdownGrammar.js
Normal file
95
client/components/codeEditor/customMarkdownGrammar.js
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
// customMarkdownGrammar.js
|
||||||
|
|
||||||
|
// --- Custom tags with CM6-compatible class names ---
|
||||||
|
export const customTags = {
|
||||||
|
pageLine: "pageLine", // .cm-pageLine
|
||||||
|
snippetLine: "snippetLine", // .cm-snippetLine
|
||||||
|
columnSplit: "columnSplit", // .cm-columnSplit
|
||||||
|
snippetBreak: "snippetBreak", // .cm-snippetBreak
|
||||||
|
inlineBlock: "inline-block", // .cm-inline-block
|
||||||
|
block: "block", // .cm-block
|
||||||
|
emoji: "emoji", // .cm-emoji
|
||||||
|
superscript: "superscript", // .cm-superscript
|
||||||
|
subscript: "subscript", // .cm-subscript
|
||||||
|
definitionTerm: "dt-highlight", // .cm-dt-highlight
|
||||||
|
definitionDesc: "dd-highlight", // .cm-dd-highlight
|
||||||
|
injection: "injection", // .cm-injection
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Tokenizer function ---
|
||||||
|
export function tokenizeCustomMarkdown(text) {
|
||||||
|
const tokens = [];
|
||||||
|
const lines = text.split("\n");
|
||||||
|
|
||||||
|
// Track multi-line blocks
|
||||||
|
let inBlock = false;
|
||||||
|
let blockStart = 0;
|
||||||
|
|
||||||
|
lines.forEach((lineText, lineNumber) => {
|
||||||
|
// --- Page / snippet lines ---
|
||||||
|
if (/\\page/.test(lineText)) tokens.push({ line: lineNumber, type: customTags.pageLine });
|
||||||
|
if (/\\snippet/.test(lineText)) tokens.push({ line: lineNumber, type: customTags.snippetLine });
|
||||||
|
if (/^\\column(?:break)?$/.test(lineText)) tokens.push({ line: lineNumber, type: customTags.columnSplit });
|
||||||
|
if (/\\snippet/.test(lineText)) tokens.push({ line: lineNumber, type: customTags.snippetBreak });
|
||||||
|
|
||||||
|
// --- Emoji ---
|
||||||
|
if (/:\w+?:/.test(lineText)) tokens.push({ line: lineNumber, type: customTags.emoji });
|
||||||
|
|
||||||
|
// --- Superscript / Subscript ---
|
||||||
|
if (/\^\^/.test(lineText)) tokens.push({ line: lineNumber, type: customTags.subscript });
|
||||||
|
if (/\^/.test(lineText)) tokens.push({ line: lineNumber, type: customTags.superscript });
|
||||||
|
|
||||||
|
// --- Definition lists ---
|
||||||
|
if (/::/.test(lineText)) {
|
||||||
|
tokens.push({ line: lineNumber, type: customTags.definitionDesc });
|
||||||
|
tokens.push({ line: lineNumber, type: customTags.definitionTerm });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Track ranges already marked for injections
|
||||||
|
const injectionRanges = [];
|
||||||
|
|
||||||
|
if (line.includes("{") && line.includes("}")) {
|
||||||
|
const regex = /{[^{}]*}/gm;
|
||||||
|
let match;
|
||||||
|
while ((match = regex.exec(line)) != null) {
|
||||||
|
codeMirror?.markText(
|
||||||
|
{ line: lineNumber, ch: match.index },
|
||||||
|
{ line: lineNumber, ch: match.index + match[0].length },
|
||||||
|
{ className: "injection" },
|
||||||
|
);
|
||||||
|
injectionRanges.push([match.index, match.index + match[0].length]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now mark inline blocks, but skip overlapping injection ranges
|
||||||
|
if (line.includes("{{") && line.includes("}}")) {
|
||||||
|
const regex = /{{[^{}]*}}/gm;
|
||||||
|
let match;
|
||||||
|
while ((match = regex.exec(line)) != null) {
|
||||||
|
const start = match.index,
|
||||||
|
end = match.index + match[0].length;
|
||||||
|
const overlaps = injectionRanges.some(([iStart, iEnd]) => start < iEnd && end > iStart);
|
||||||
|
if (!overlaps) {
|
||||||
|
codeMirror?.markText(
|
||||||
|
{ line: lineNumber, ch: start },
|
||||||
|
{ line: lineNumber, ch: end },
|
||||||
|
{ className: "inline-block" },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Multi-line blocks `{{…}}` --- only start/end lines
|
||||||
|
if (lineText.trimLeft().startsWith("{{") && !lineText.trimLeft().endsWith("}}")) {
|
||||||
|
inBlock = true;
|
||||||
|
blockStart = lineNumber;
|
||||||
|
tokens.push({ line: lineNumber, type: customTags.block });
|
||||||
|
}
|
||||||
|
if (lineText.trimLeft().startsWith("}}") && inBlock) {
|
||||||
|
tokens.push({ line: lineNumber, type: customTags.block });
|
||||||
|
inBlock = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
@@ -1,16 +1,16 @@
|
|||||||
/*eslint max-lines: ["warn", {"max": 500, "skipBlankLines": true, "skipComments": true}]*/
|
/*eslint max-lines: ["warn", {"max": 500, "skipBlankLines": true, "skipComments": true}]*/
|
||||||
import './editor.less';
|
import "./editor.less";
|
||||||
import React from 'react';
|
import React from "react";
|
||||||
import createReactClass from 'create-react-class';
|
import createReactClass from "create-react-class";
|
||||||
import _ from 'lodash';
|
import _ from "lodash";
|
||||||
import dedent from 'dedent';
|
import dedent from "dedent";
|
||||||
import Markdown from '@shared/markdown.js';
|
import Markdown from "@shared/markdown.js";
|
||||||
|
|
||||||
import CodeEditor from '../../components/codeEditor/codeEditor.jsx';
|
import CodeEditor from "../../components/codeEditor/codeEditor.jsx";
|
||||||
import SnippetBar from './snippetbar/snippetbar.jsx';
|
import SnippetBar from "./snippetbar/snippetbar.jsx";
|
||||||
import MetadataEditor from './metadataEditor/metadataEditor.jsx';
|
import MetadataEditor from "./metadataEditor/metadataEditor.jsx";
|
||||||
|
|
||||||
const EDITOR_THEME_KEY = 'HB_editor_theme';
|
const EDITOR_THEME_KEY = "HB_editor_theme";
|
||||||
|
|
||||||
const PAGEBREAK_REGEX_V3 = /^(?=\\page(?:break)?(?: *{[^\n{}]*})?$)/m;
|
const PAGEBREAK_REGEX_V3 = /^(?=\\page(?:break)?(?: *{[^\n{}]*})?$)/m;
|
||||||
const SNIPPETBREAK_REGEX_V3 = /^\\snippet\ .*$/;
|
const SNIPPETBREAK_REGEX_V3 = /^\\snippet\ .*$/;
|
||||||
@@ -32,295 +32,348 @@ const DEFAULT_SNIPPET_TEXT = dedent`
|
|||||||
let isJumping = false;
|
let isJumping = false;
|
||||||
|
|
||||||
const Editor = createReactClass({
|
const Editor = createReactClass({
|
||||||
displayName : 'Editor',
|
displayName: "Editor",
|
||||||
getDefaultProps : function() {
|
getDefaultProps: function () {
|
||||||
return {
|
return {
|
||||||
brew : {
|
brew: {
|
||||||
text : '',
|
text: "",
|
||||||
style : ''
|
style: "",
|
||||||
},
|
},
|
||||||
|
|
||||||
onBrewChange : ()=>{},
|
onBrewChange: () => {},
|
||||||
reportError : ()=>{},
|
reportError: () => {},
|
||||||
|
|
||||||
onCursorPageChange : ()=>{},
|
onCursorPageChange: () => {},
|
||||||
onViewPageChange : ()=>{},
|
onViewPageChange: () => {},
|
||||||
|
|
||||||
editorTheme : 'default',
|
editorTheme: "default",
|
||||||
renderer : 'legacy',
|
renderer: "legacy",
|
||||||
|
|
||||||
currentEditorCursorPageNum : 1,
|
currentEditorCursorPageNum: 1,
|
||||||
currentEditorViewPageNum : 1,
|
currentEditorViewPageNum: 1,
|
||||||
currentBrewRendererPageNum : 1,
|
currentBrewRendererPageNum: 1,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
getInitialState : function() {
|
getInitialState: function () {
|
||||||
return {
|
return {
|
||||||
editorTheme : this.props.editorTheme,
|
editorTheme: this.props.editorTheme,
|
||||||
view : 'text', //'text', 'style', 'meta', 'snippet'
|
view: "text", //'text', 'style', 'meta', 'snippet'
|
||||||
snippetBarHeight : 26,
|
snippetBarHeight: 26,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
editor : React.createRef(null),
|
editor: React.createRef(null),
|
||||||
codeEditor : React.createRef(null),
|
codeEditor: React.createRef(null),
|
||||||
|
|
||||||
isText : function() {return this.state.view == 'text';},
|
isText: function () {
|
||||||
isStyle : function() {return this.state.view == 'style';},
|
return this.state.view == "text";
|
||||||
isMeta : function() {return this.state.view == 'meta';},
|
},
|
||||||
isSnip : function() {return this.state.view == 'snippet';},
|
isStyle: function () {
|
||||||
|
return this.state.view == "style";
|
||||||
componentDidMount : function() {
|
},
|
||||||
|
isMeta: function () {
|
||||||
|
return this.state.view == "meta";
|
||||||
|
},
|
||||||
|
isSnip: function () {
|
||||||
|
return this.state.view == "snippet";
|
||||||
|
},
|
||||||
|
|
||||||
|
componentDidMount: function () {
|
||||||
this.highlightCustomMarkdown();
|
this.highlightCustomMarkdown();
|
||||||
document.getElementById('BrewRenderer').addEventListener('keydown', this.handleControlKeys);
|
document.getElementById("BrewRenderer").addEventListener("keydown", this.handleControlKeys);
|
||||||
document.addEventListener('keydown', this.handleControlKeys);
|
document.addEventListener("keydown", this.handleControlKeys);
|
||||||
|
|
||||||
this.codeEditor.current.codeMirror?.on('cursorActivity', (cm)=>{this.updateCurrentCursorPage(cm.getCursor());});
|
this.codeEditor.current.codeMirror?.on("cursorActivity", (cm) => {
|
||||||
this.codeEditor.current.codeMirror?.on('scroll', _.throttle(()=>{this.updateCurrentViewPage(this.codeEditor.current.getTopVisibleLine());}, 200));
|
this.updateCurrentCursorPage(cm.getCursor());
|
||||||
|
});
|
||||||
|
this.codeEditor.current.codeMirror?.on(
|
||||||
|
"scroll",
|
||||||
|
_.throttle(() => {
|
||||||
|
this.updateCurrentViewPage(this.codeEditor.current.getTopVisibleLine());
|
||||||
|
}, 200),
|
||||||
|
);
|
||||||
|
|
||||||
const editorTheme = window.localStorage.getItem(EDITOR_THEME_KEY);
|
const editorTheme = window.localStorage.getItem(EDITOR_THEME_KEY);
|
||||||
if(editorTheme) {
|
if (editorTheme) {
|
||||||
this.setState({
|
this.setState({
|
||||||
editorTheme : editorTheme
|
editorTheme: editorTheme,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const snippetBar = document.querySelector('.editor > .snippetBar');
|
const snippetBar = document.querySelector(".editor > .snippetBar");
|
||||||
if(!snippetBar) return;
|
if (!snippetBar) return;
|
||||||
|
|
||||||
this.resizeObserver = new ResizeObserver((entries)=>{
|
this.resizeObserver = new ResizeObserver((entries) => {
|
||||||
const height = document.querySelector('.editor > .snippetBar').offsetHeight;
|
const height = document.querySelector(".editor > .snippetBar").offsetHeight;
|
||||||
this.setState({ snippetBarHeight: height });
|
this.setState({ snippetBarHeight: height });
|
||||||
});
|
});
|
||||||
|
|
||||||
this.resizeObserver.observe(snippetBar);
|
this.resizeObserver.observe(snippetBar);
|
||||||
},
|
},
|
||||||
|
|
||||||
componentDidUpdate : function(prevProps, prevState, snapshot) {
|
componentDidUpdate: function (prevProps, prevState, snapshot) {
|
||||||
|
|
||||||
this.highlightCustomMarkdown();
|
this.highlightCustomMarkdown();
|
||||||
if(prevProps.moveBrew !== this.props.moveBrew)
|
if (prevProps.moveBrew !== this.props.moveBrew) this.brewJump();
|
||||||
this.brewJump();
|
|
||||||
|
|
||||||
if(prevProps.moveSource !== this.props.moveSource)
|
if (prevProps.moveSource !== this.props.moveSource) this.sourceJump();
|
||||||
this.sourceJump();
|
|
||||||
|
|
||||||
if(this.props.liveScroll) {
|
if (this.props.liveScroll) {
|
||||||
if(prevProps.currentBrewRendererPageNum !== this.props.currentBrewRendererPageNum) {
|
if (prevProps.currentBrewRendererPageNum !== this.props.currentBrewRendererPageNum) {
|
||||||
this.sourceJump(this.props.currentBrewRendererPageNum, false);
|
this.sourceJump(this.props.currentBrewRendererPageNum, false);
|
||||||
} else if(prevProps.currentEditorViewPageNum !== this.props.currentEditorViewPageNum) {
|
} else if (prevProps.currentEditorViewPageNum !== this.props.currentEditorViewPageNum) {
|
||||||
this.brewJump(this.props.currentEditorViewPageNum, false);
|
this.brewJump(this.props.currentEditorViewPageNum, false);
|
||||||
} else if(prevProps.currentEditorCursorPageNum !== this.props.currentEditorCursorPageNum) {
|
} else if (prevProps.currentEditorCursorPageNum !== this.props.currentEditorCursorPageNum) {
|
||||||
this.brewJump(this.props.currentEditorCursorPageNum, false);
|
this.brewJump(this.props.currentEditorCursorPageNum, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
componentWillUnmount() {
|
componentWillUnmount() {
|
||||||
if(this.resizeObserver) this.resizeObserver.disconnect();
|
if (this.resizeObserver) this.resizeObserver.disconnect();
|
||||||
},
|
},
|
||||||
|
|
||||||
handleControlKeys : function(e){
|
handleControlKeys: function (e) {
|
||||||
if(!(e.ctrlKey && e.metaKey && e.shiftKey)) return;
|
if (!(e.ctrlKey && e.metaKey && e.shiftKey)) return;
|
||||||
const LEFTARROW_KEY = 37;
|
const LEFTARROW_KEY = 37;
|
||||||
const RIGHTARROW_KEY = 39;
|
const RIGHTARROW_KEY = 39;
|
||||||
if(e.keyCode == RIGHTARROW_KEY) this.brewJump();
|
if (e.keyCode == RIGHTARROW_KEY) this.brewJump();
|
||||||
if(e.keyCode == LEFTARROW_KEY) this.sourceJump();
|
if (e.keyCode == LEFTARROW_KEY) this.sourceJump();
|
||||||
if(e.keyCode == LEFTARROW_KEY || e.keyCode == RIGHTARROW_KEY) {
|
if (e.keyCode == LEFTARROW_KEY || e.keyCode == RIGHTARROW_KEY) {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
updateCurrentCursorPage : function(cursor) {
|
updateCurrentCursorPage: function (cursor) {
|
||||||
const lines = this.props.brew.text.split('\n').slice(1, cursor.line + 1);
|
const lines = this.props.brew.text.split("\n").slice(1, cursor.line + 1);
|
||||||
const pageRegex = this.props.brew.renderer == 'V3' ? PAGEBREAK_REGEX_V3 : /\\page/;
|
const pageRegex = this.props.brew.renderer == "V3" ? PAGEBREAK_REGEX_V3 : /\\page/;
|
||||||
const currentPage = lines.reduce((count, line)=>count + (pageRegex.test(line) ? 1 : 0), 1);
|
const currentPage = lines.reduce((count, line) => count + (pageRegex.test(line) ? 1 : 0), 1);
|
||||||
this.props.onCursorPageChange(currentPage);
|
this.props.onCursorPageChange(currentPage);
|
||||||
},
|
},
|
||||||
|
|
||||||
updateCurrentViewPage : function(topScrollLine) {
|
updateCurrentViewPage: function (topScrollLine) {
|
||||||
const lines = this.props.brew.text.split('\n').slice(1, topScrollLine + 1);
|
const lines = this.props.brew.text.split("\n").slice(1, topScrollLine + 1);
|
||||||
const pageRegex = this.props.brew.renderer == 'V3' ? PAGEBREAK_REGEX_V3 : /\\page/;
|
const pageRegex = this.props.brew.renderer == "V3" ? PAGEBREAK_REGEX_V3 : /\\page/;
|
||||||
const currentPage = lines.reduce((count, line)=>count + (pageRegex.test(line) ? 1 : 0), 1);
|
const currentPage = lines.reduce((count, line) => count + (pageRegex.test(line) ? 1 : 0), 1);
|
||||||
this.props.onViewPageChange(currentPage);
|
this.props.onViewPageChange(currentPage);
|
||||||
},
|
},
|
||||||
|
|
||||||
handleInject : function(injectText){
|
handleInject: function (injectText) {
|
||||||
this.codeEditor.current?.injectText(injectText, false);
|
this.codeEditor.current?.injectText(injectText, false);
|
||||||
},
|
},
|
||||||
|
|
||||||
handleViewChange : function(newView){
|
handleViewChange: function (newView) {
|
||||||
this.props.setMoveArrows(newView === 'text');
|
this.props.setMoveArrows(newView === "text");
|
||||||
|
|
||||||
this.setState({
|
this.setState(
|
||||||
view : newView
|
{
|
||||||
}, ()=>{
|
view: newView,
|
||||||
this.codeEditor.current?.codeMirror?.focus();
|
},
|
||||||
});
|
() => {
|
||||||
|
this.codeEditor.current?.codeMirror?.focus();
|
||||||
|
},
|
||||||
|
);
|
||||||
},
|
},
|
||||||
|
|
||||||
highlightCustomMarkdown : function(){
|
highlightCustomMarkdown: function () {
|
||||||
if(!this.codeEditor.current?.codeMirror) return;
|
if (!this.codeEditor.current?.codeMirror) return;
|
||||||
if((this.state.view === 'text') ||(this.state.view === 'snippet')) {
|
if (this.state.view === "text" || this.state.view === "snippet") {
|
||||||
const codeMirror = this.codeEditor.current.codeMirror;
|
const codeMirror = this.codeEditor.current.codeMirror;
|
||||||
|
|
||||||
codeMirror?.operation(()=>{ // Batch CodeMirror styling
|
codeMirror?.operation(() => {
|
||||||
|
// Batch CodeMirror styling
|
||||||
|
|
||||||
const foldLines = [];
|
const foldLines = [];
|
||||||
|
|
||||||
//reset custom text styles
|
//reset custom text styles
|
||||||
const customHighlights = codeMirror?.getAllMarks().filter((mark)=>{
|
const customHighlights = codeMirror?.getAllMarks().filter((mark) => {
|
||||||
// Record details of folded sections
|
// Record details of folded sections
|
||||||
if(mark.__isFold) {
|
if (mark.__isFold) {
|
||||||
const fold = mark.find();
|
const fold = mark.find();
|
||||||
foldLines.push({ from: fold.from?.line, to: fold.to?.line });
|
foldLines.push({ from: fold.from?.line, to: fold.to?.line });
|
||||||
}
|
}
|
||||||
return !mark.__isFold;
|
return !mark.__isFold;
|
||||||
}); //Don't undo code folding
|
}); //Don't undo code folding
|
||||||
|
|
||||||
for (let i=customHighlights.length - 1;i>=0;i--) customHighlights[i].clear();
|
for (let i = customHighlights.length - 1; i >= 0; i--) customHighlights[i].clear();
|
||||||
|
|
||||||
let userSnippetCount = 1; // start snippet count from snippet 1
|
let userSnippetCount = 1; // start snippet count from snippet 1
|
||||||
let editorPageCount = 1; // start page count from page 1
|
let editorPageCount = 1; // start page count from page 1
|
||||||
|
|
||||||
const whichSource = this.state.view === 'text' ? this.props.brew.text : this.props.brew.snippets;
|
const whichSource = this.state.view === "text" ? this.props.brew.text : this.props.brew.snippets;
|
||||||
_.forEach(whichSource?.split('\n'), (line, lineNumber)=>{
|
_.forEach(whichSource?.split("\n"), (line, lineNumber) => {
|
||||||
|
const tabHighlight = this.state.view === "text" ? "pageLine" : "snippetLine";
|
||||||
const tabHighlight = this.state.view === 'text' ? 'pageLine' : 'snippetLine';
|
const textOrSnip = this.state.view === "text";
|
||||||
const textOrSnip = this.state.view === 'text';
|
|
||||||
|
|
||||||
//reset custom line styles
|
//reset custom line styles
|
||||||
codeMirror?.removeLineClass(lineNumber, 'background', 'pageLine');
|
codeMirror?.removeLineClass(lineNumber, "background", "pageLine");
|
||||||
codeMirror?.removeLineClass(lineNumber, 'background', 'snippetLine');
|
codeMirror?.removeLineClass(lineNumber, "background", "snippetLine");
|
||||||
codeMirror?.removeLineClass(lineNumber, 'text');
|
codeMirror?.removeLineClass(lineNumber, "text");
|
||||||
codeMirror?.removeLineClass(lineNumber, 'wrap', 'sourceMoveFlash');
|
codeMirror?.removeLineClass(lineNumber, "wrap", "sourceMoveFlash");
|
||||||
|
|
||||||
// Don't process lines inside folded text
|
// Don't process lines inside folded text
|
||||||
// If the current lineNumber is inside any folded marks, skip line styling
|
// If the current lineNumber is inside any folded marks, skip line styling
|
||||||
if(foldLines.some((fold)=>lineNumber >= fold.from && lineNumber <= fold.to))
|
if (foldLines.some((fold) => lineNumber >= fold.from && lineNumber <= fold.to)) return;
|
||||||
return;
|
|
||||||
|
|
||||||
// Styling for \page breaks
|
// Styling for \page breaks
|
||||||
if((this.props.renderer == 'legacy' && line.includes('\\page')) ||
|
if (
|
||||||
(this.props.renderer == 'V3' && line.match(textOrSnip ? PAGEBREAK_REGEX_V3 : SNIPPETBREAK_REGEX_V3))) {
|
(this.props.renderer == "legacy" && line.includes("\\page")) ||
|
||||||
|
(this.props.renderer == "V3" &&
|
||||||
if((lineNumber > 0) && (textOrSnip)) // Since \page is optional on first line of document,
|
line.match(textOrSnip ? PAGEBREAK_REGEX_V3 : SNIPPETBREAK_REGEX_V3))
|
||||||
|
) {
|
||||||
|
if (lineNumber > 0 && textOrSnip)
|
||||||
|
// Since \page is optional on first line of document,
|
||||||
editorPageCount += 1; // don't use it to increment page count; stay at 1
|
editorPageCount += 1; // don't use it to increment page count; stay at 1
|
||||||
else if(this.state.view !== 'text') userSnippetCount += 1;
|
else if (this.state.view !== "text") userSnippetCount += 1;
|
||||||
|
|
||||||
// add back the original class 'background' but also add the new class '.pageline'
|
// add back the original class 'background' but also add the new class '.pageline'
|
||||||
codeMirror?.addLineClass(lineNumber, 'background', tabHighlight);
|
codeMirror?.addLineClass(lineNumber, "background", tabHighlight);
|
||||||
const pageCountElement = Object.assign(document.createElement('span'), {
|
const pageCountElement = Object.assign(document.createElement("span"), {
|
||||||
className : 'editor-page-count',
|
className: "editor-page-count",
|
||||||
textContent : textOrSnip ? editorPageCount : userSnippetCount
|
textContent: textOrSnip ? editorPageCount : userSnippetCount,
|
||||||
});
|
});
|
||||||
codeMirror?.setBookmark({ line: lineNumber, ch: line.length }, pageCountElement);
|
codeMirror?.setBookmark({ line: lineNumber, ch: line.length }, pageCountElement);
|
||||||
};
|
}
|
||||||
|
|
||||||
|
|
||||||
// New CodeMirror styling for V3 renderer
|
// New CodeMirror styling for V3 renderer
|
||||||
if(this.props.renderer === 'V3') {
|
if (this.props.renderer === "V3") {
|
||||||
if(line.match(/^\\column(?:break)?$/)){
|
if (line.match(/^\\column(?:break)?$/)) {
|
||||||
codeMirror?.addLineClass(lineNumber, 'text', 'columnSplit');
|
codeMirror?.addLineClass(lineNumber, "text", "columnSplit");
|
||||||
}
|
}
|
||||||
|
|
||||||
// definition lists
|
// definition lists
|
||||||
if(line.includes('::')){
|
if (line.includes("::")) {
|
||||||
if(/^:*$/.test(line) == true){ return; };
|
if (/^:*$/.test(line) == true) {
|
||||||
const regex = /^([^\n]*?:?\s?)(::[^\n]*)(?:\n|$)/ymd; // the `d` flag, for match indices, throws an ESLint error.
|
return;
|
||||||
|
}
|
||||||
|
const regex = /^([^\n]*?:?\s?)(::[^\n]*)(?:\n|$)/dmy; // the `d` flag, for match indices, throws an ESLint error.
|
||||||
let match;
|
let match;
|
||||||
while ((match = regex.exec(line)) != null){
|
while ((match = regex.exec(line)) != null) {
|
||||||
codeMirror?.markText({ line: lineNumber, ch: match.indices[0][0] }, { line: lineNumber, ch: match.indices[0][1] }, { className: 'dl-highlight' });
|
codeMirror?.markText(
|
||||||
codeMirror?.markText({ line: lineNumber, ch: match.indices[1][0] }, { line: lineNumber, ch: match.indices[1][1] }, { className: 'dt-highlight' });
|
{ line: lineNumber, ch: match.indices[0][0] },
|
||||||
codeMirror?.markText({ line: lineNumber, ch: match.indices[2][0] }, { line: lineNumber, ch: match.indices[2][1] }, { className: 'dd-highlight' });
|
{ line: lineNumber, ch: match.indices[0][1] },
|
||||||
|
{ className: "dl-highlight" },
|
||||||
|
);
|
||||||
|
codeMirror?.markText(
|
||||||
|
{ line: lineNumber, ch: match.indices[1][0] },
|
||||||
|
{ line: lineNumber, ch: match.indices[1][1] },
|
||||||
|
{ className: "dt-highlight" },
|
||||||
|
);
|
||||||
|
codeMirror?.markText(
|
||||||
|
{ line: lineNumber, ch: match.indices[2][0] },
|
||||||
|
{ line: lineNumber, ch: match.indices[2][1] },
|
||||||
|
{ className: "dd-highlight" },
|
||||||
|
);
|
||||||
const ddIndex = match.indices[2][0];
|
const ddIndex = match.indices[2][0];
|
||||||
const colons = /::/g;
|
const colons = /::/g;
|
||||||
const colonMatches = colons.exec(match[2]);
|
const colonMatches = colons.exec(match[2]);
|
||||||
if(colonMatches !== null){
|
if (colonMatches !== null) {
|
||||||
codeMirror?.markText({ line: lineNumber, ch: colonMatches.index + ddIndex }, { line: lineNumber, ch: colonMatches.index + colonMatches[0].length + ddIndex }, { className: 'dl-colon-highlight' });
|
codeMirror?.markText(
|
||||||
|
{ line: lineNumber, ch: colonMatches.index + ddIndex },
|
||||||
|
{ line: lineNumber, ch: colonMatches.index + colonMatches[0].length + ddIndex },
|
||||||
|
{ className: "dl-colon-highlight" },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Subscript & Superscript
|
// Subscript & Superscript
|
||||||
if(line.includes('^')) {
|
if (line.includes("^")) {
|
||||||
let startIndex = line.indexOf('^');
|
let startIndex = line.indexOf("^");
|
||||||
const superRegex = /\^(?!\s)(?=([^\n\^]*[^\s\^]))\1\^/gy;
|
const superRegex = /\^(?!\s)(?=([^\n\^]*[^\s\^]))\1\^/gy;
|
||||||
const subRegex = /\^\^(?!\s)(?=([^\n\^]*[^\s\^]))\1\^\^/gy;
|
const subRegex = /\^\^(?!\s)(?=([^\n\^]*[^\s\^]))\1\^\^/gy;
|
||||||
|
|
||||||
while (startIndex >= 0) {
|
while (startIndex >= 0) {
|
||||||
superRegex.lastIndex = subRegex.lastIndex = startIndex;
|
superRegex.lastIndex = subRegex.lastIndex = startIndex;
|
||||||
let isSuper = false;
|
let isSuper = false;
|
||||||
const match = subRegex.exec(line) || superRegex.exec(line);
|
const match = subRegex.exec(line) || superRegex.exec(line);
|
||||||
if(match) {
|
if (match) {
|
||||||
isSuper = !subRegex.lastIndex;
|
isSuper = !subRegex.lastIndex;
|
||||||
codeMirror?.markText({ line: lineNumber, ch: match.index }, { line: lineNumber, ch: match.index + match[0].length }, { className: isSuper ? 'superscript' : 'subscript' });
|
codeMirror?.markText(
|
||||||
|
{ line: lineNumber, ch: match.index },
|
||||||
|
{ line: lineNumber, ch: match.index + match[0].length },
|
||||||
|
{ className: isSuper ? "superscript" : "subscript" },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
startIndex = line.indexOf('^', Math.max(startIndex + 1, subRegex.lastIndex, superRegex.lastIndex));
|
startIndex = line.indexOf(
|
||||||
|
"^",
|
||||||
|
Math.max(startIndex + 1, subRegex.lastIndex, superRegex.lastIndex),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Highlight injectors {style}
|
// Injections: single-line {…}
|
||||||
if(line.includes('{') && line.includes('}')){
|
if (line.includes("{") && line.includes("}")) {
|
||||||
const regex = /(?:^|[^{\n])({(?=((?:[:=](?:"[\w,\-()#%. ]*"|[\w\-()#%.]*)|[^"':={}\s]*)*))\2})/gm;
|
const injectionRegex =
|
||||||
|
/(?:^|[^{\n])({(?=((?:[:=](?:"[\w,\-()#%. ]*"|[\w\-()#%.]*)|[^"':={}\s]*)*))\2})/gm;
|
||||||
let match;
|
let match;
|
||||||
while ((match = regex.exec(line)) != null) {
|
while ((match = injectionRegex.exec(line)) !== null) {
|
||||||
codeMirror?.markText({ line: lineNumber, ch: line.indexOf(match[1]) }, { line: lineNumber, ch: line.indexOf(match[1]) + match[1].length }, { className: 'injection' });
|
tokens.push({
|
||||||
|
line: lineNumber,
|
||||||
|
from: match.index,
|
||||||
|
to: match.index + match[1].length,
|
||||||
|
type: "injection",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
} else if (line.includes("{{") && line.includes("}}")) { // Inline blocks: single-line {{…}}
|
||||||
// Highlight inline spans {{content}}
|
const spanRegex = /{{(?=((?:[:=](?:"[\w,\-()#%. ]*"|[\w\-()#%.]*)|[^"':={}\s]*)*))\1 *|}}/g;
|
||||||
if(line.includes('{{') && line.includes('}}')){
|
|
||||||
const regex = /{{(?=((?:[:=](?:"[\w,\-()#%. ]*"|[\w\-()#%.]*)|[^"':={}\s]*)*))\1 *|}}/g;
|
|
||||||
let match;
|
let match;
|
||||||
let blockCount = 0;
|
let blockCount = 0;
|
||||||
while ((match = regex.exec(line)) != null) {
|
while ((match = spanRegex.exec(line)) !== null) {
|
||||||
if(match[0].startsWith('{')) {
|
if (match[0].startsWith("{{")) {
|
||||||
blockCount += 1;
|
blockCount += 1;
|
||||||
} else {
|
} else {
|
||||||
blockCount -= 1;
|
blockCount -= 1;
|
||||||
}
|
}
|
||||||
if(blockCount < 0) {
|
if (blockCount < 0) {
|
||||||
blockCount = 0;
|
blockCount = 0;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
codeMirror?.markText({ line: lineNumber, ch: match.index }, { line: lineNumber, ch: match.index + match[0].length }, { className: 'inline-block' });
|
tokens.push({
|
||||||
|
line: lineNumber,
|
||||||
|
from: match.index,
|
||||||
|
to: match.index + match[0].length,
|
||||||
|
type: "inline-block",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
} else if(line.trimLeft().startsWith('{{') || line.trimLeft().startsWith('}}')){
|
} else if (line.trimLeft().startsWith("{{") || line.trimLeft().startsWith("}}")) {
|
||||||
// Highlight block divs {{\n Content \n}}
|
// Highlight block divs {{\n Content \n}}
|
||||||
let endCh = line.length+1;
|
let endCh = line.length + 1;
|
||||||
|
|
||||||
const match = line.match(/^ *{{(?=((?:[:=](?:"[\w,\-()#%. ]*"|[\w\-()#%.]*)|[^"':={}\s]*)*))\1 *$|^ *}}$/);
|
const match = line.match(
|
||||||
if(match)
|
/^ *{{(?=((?:[:=](?:"[\w,\-()#%. ]*"|[\w\-()#%.]*)|[^"':={}\s]*)*))\1 *$|^ *}}$/,
|
||||||
endCh = match.index+match[0].length;
|
);
|
||||||
codeMirror?.markText({ line: lineNumber, ch: 0 }, { line: lineNumber, ch: endCh }, { className: 'block' });
|
if (match) endCh = match.index + match[0].length;
|
||||||
|
codeMirror?.markText(
|
||||||
|
{ line: lineNumber, ch: 0 },
|
||||||
|
{ line: lineNumber, ch: endCh },
|
||||||
|
{ className: "block" },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Emojis
|
// Emojis
|
||||||
if(line.match(/:[^\s:]+:/g)) {
|
if (line.match(/:[^\s:]+:/g)) {
|
||||||
let startIndex = line.indexOf(':');
|
let startIndex = line.indexOf(":");
|
||||||
const emojiRegex = /:[^\s:]+:/gy;
|
const emojiRegex = /:[^\s:]+:/gy;
|
||||||
|
|
||||||
while (startIndex >= 0) {
|
while (startIndex >= 0) {
|
||||||
emojiRegex.lastIndex = startIndex;
|
emojiRegex.lastIndex = startIndex;
|
||||||
const match = emojiRegex.exec(line);
|
const match = emojiRegex.exec(line);
|
||||||
if(match) {
|
if (match) {
|
||||||
let tokens = Markdown.marked.lexer(match[0]);
|
let tokens = Markdown.marked.lexer(match[0]);
|
||||||
tokens = tokens[0].tokens.filter((t)=>t.type == 'emoji');
|
tokens = tokens[0].tokens.filter((t) => t.type == "emoji");
|
||||||
if(!tokens.length)
|
if (!tokens.length) return;
|
||||||
return;
|
|
||||||
|
|
||||||
const startPos = { line: lineNumber, ch: match.index };
|
const startPos = { line: lineNumber, ch: match.index };
|
||||||
const endPos = { line: lineNumber, ch: match.index + match[0].length };
|
const endPos = { line: lineNumber, ch: match.index + match[0].length };
|
||||||
|
|
||||||
// Iterate over conflicting marks and clear them
|
// Iterate over conflicting marks and clear them
|
||||||
const marks = codeMirror?.findMarks(startPos, endPos);
|
const marks = codeMirror?.findMarks(startPos, endPos);
|
||||||
marks.forEach(function(marker) {
|
marks.forEach(function (marker) {
|
||||||
if(!marker.__isFold) marker.clear();
|
if (!marker.__isFold) marker.clear();
|
||||||
});
|
});
|
||||||
codeMirror?.markText(startPos, endPos, { className: 'emoji' });
|
codeMirror?.markText(startPos, endPos, { className: "emoji" });
|
||||||
}
|
}
|
||||||
startIndex = line.indexOf(':', Math.max(startIndex + 1, emojiRegex.lastIndex));
|
startIndex = line.indexOf(":", Math.max(startIndex + 1, emojiRegex.lastIndex));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -329,198 +382,226 @@ const Editor = createReactClass({
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
brewJump : function(targetPage=this.props.currentEditorCursorPageNum, smooth=true){
|
brewJump: function (targetPage = this.props.currentEditorCursorPageNum, smooth = true) {
|
||||||
if(!window || !this.isText() || isJumping)
|
if (!window || !this.isText() || isJumping) return;
|
||||||
return;
|
|
||||||
|
|
||||||
// Get current brewRenderer scroll position and calculate target position
|
// Get current brewRenderer scroll position and calculate target position
|
||||||
const brewRenderer = window.frames['BrewRenderer'].contentDocument.getElementsByClassName('brewRenderer')[0];
|
const brewRenderer = window.frames["BrewRenderer"].contentDocument.getElementsByClassName("brewRenderer")[0];
|
||||||
const currentPos = brewRenderer.scrollTop;
|
const currentPos = brewRenderer.scrollTop;
|
||||||
const targetPos = window.frames['BrewRenderer'].contentDocument.getElementById(`p${targetPage}`).getBoundingClientRect().top;
|
const targetPos = window.frames["BrewRenderer"].contentDocument
|
||||||
|
.getElementById(`p${targetPage}`)
|
||||||
|
.getBoundingClientRect().top;
|
||||||
|
|
||||||
let scrollingTimeout;
|
let scrollingTimeout;
|
||||||
const checkIfScrollComplete = ()=>{ // Prevent interrupting a scroll in progress if user clicks multiple times
|
const checkIfScrollComplete = () => {
|
||||||
clearTimeout(scrollingTimeout); // Reset the timer every time a scroll event occurs
|
// Prevent interrupting a scroll in progress if user clicks multiple times
|
||||||
scrollingTimeout = setTimeout(()=>{
|
clearTimeout(scrollingTimeout); // Reset the timer every time a scroll event occurs
|
||||||
|
scrollingTimeout = setTimeout(() => {
|
||||||
isJumping = false;
|
isJumping = false;
|
||||||
brewRenderer.removeEventListener('scroll', checkIfScrollComplete);
|
brewRenderer.removeEventListener("scroll", checkIfScrollComplete);
|
||||||
}, 150); // If 150 ms pass without a brewRenderer scroll event, assume scrolling is done
|
}, 150); // If 150 ms pass without a brewRenderer scroll event, assume scrolling is done
|
||||||
};
|
};
|
||||||
|
|
||||||
isJumping = true;
|
isJumping = true;
|
||||||
checkIfScrollComplete();
|
checkIfScrollComplete();
|
||||||
brewRenderer.addEventListener('scroll', checkIfScrollComplete);
|
brewRenderer.addEventListener("scroll", checkIfScrollComplete);
|
||||||
|
|
||||||
if(smooth) {
|
if (smooth) {
|
||||||
const bouncePos = targetPos >= 0 ? -30 : 30; //Do a little bounce before scrolling
|
const bouncePos = targetPos >= 0 ? -30 : 30; //Do a little bounce before scrolling
|
||||||
const bounceDelay = 100;
|
const bounceDelay = 100;
|
||||||
const scrollDelay = 500;
|
const scrollDelay = 500;
|
||||||
|
|
||||||
if(!this.throttleBrewMove) {
|
if (!this.throttleBrewMove) {
|
||||||
this.throttleBrewMove = _.throttle((currentPos, bouncePos, targetPos)=>{
|
this.throttleBrewMove = _.throttle(
|
||||||
brewRenderer.scrollTo({ top: currentPos + bouncePos, behavior: 'smooth' });
|
(currentPos, bouncePos, targetPos) => {
|
||||||
setTimeout(()=>{
|
brewRenderer.scrollTo({ top: currentPos + bouncePos, behavior: "smooth" });
|
||||||
brewRenderer.scrollTo({ top: currentPos + targetPos, behavior: 'smooth', block: 'start' });
|
setTimeout(() => {
|
||||||
}, bounceDelay);
|
brewRenderer.scrollTo({ top: currentPos + targetPos, behavior: "smooth", block: "start" });
|
||||||
}, scrollDelay, { leading: true, trailing: false });
|
}, bounceDelay);
|
||||||
};
|
},
|
||||||
|
scrollDelay,
|
||||||
|
{ leading: true, trailing: false },
|
||||||
|
);
|
||||||
|
}
|
||||||
this.throttleBrewMove(currentPos, bouncePos, targetPos);
|
this.throttleBrewMove(currentPos, bouncePos, targetPos);
|
||||||
} else {
|
} else {
|
||||||
brewRenderer.scrollTo({ top: currentPos + targetPos, behavior: 'instant', block: 'start' });
|
brewRenderer.scrollTo({ top: currentPos + targetPos, behavior: "instant", block: "start" });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
sourceJump : function(targetPage=this.props.currentBrewRendererPageNum, smooth=true){
|
sourceJump: function (targetPage = this.props.currentBrewRendererPageNum, smooth = true) {
|
||||||
if(!this.isText() || isJumping)
|
if (!this.isText() || isJumping) return;
|
||||||
return;
|
|
||||||
|
|
||||||
const textSplit = this.props.renderer == 'V3' ? PAGEBREAK_REGEX_V3 : /\\page/;
|
const textSplit = this.props.renderer == "V3" ? PAGEBREAK_REGEX_V3 : /\\page/;
|
||||||
const textString = this.props.brew.text.split(textSplit).slice(0, targetPage-1).join(textSplit);
|
const textString = this.props.brew.text
|
||||||
const targetLine = textString.match('\n') ? textString.split('\n').length - 1 : -1;
|
.split(textSplit)
|
||||||
|
.slice(0, targetPage - 1)
|
||||||
|
.join(textSplit);
|
||||||
|
const targetLine = textString.match("\n") ? textString.split("\n").length - 1 : -1;
|
||||||
|
|
||||||
let currentY = this.codeEditor.current.codeMirror?.getScrollInfo().top;
|
let currentY = this.codeEditor.current.codeMirror?.getScrollInfo().top;
|
||||||
let targetY = this.codeEditor.current.codeMirror?.heightAtLine(targetLine, 'local', true);
|
let targetY = this.codeEditor.current.codeMirror?.heightAtLine(targetLine, "local", true);
|
||||||
|
|
||||||
let scrollingTimeout;
|
let scrollingTimeout;
|
||||||
const checkIfScrollComplete = ()=>{ // Prevent interrupting a scroll in progress if user clicks multiple times
|
const checkIfScrollComplete = () => {
|
||||||
|
// Prevent interrupting a scroll in progress if user clicks multiple times
|
||||||
clearTimeout(scrollingTimeout); // Reset the timer every time a scroll event occurs
|
clearTimeout(scrollingTimeout); // Reset the timer every time a scroll event occurs
|
||||||
scrollingTimeout = setTimeout(()=>{
|
scrollingTimeout = setTimeout(() => {
|
||||||
isJumping = false;
|
isJumping = false;
|
||||||
this.codeEditor.current.codeMirror?.off('scroll', checkIfScrollComplete);
|
this.codeEditor.current.codeMirror?.off("scroll", checkIfScrollComplete);
|
||||||
}, 150); // If 150 ms pass without a scroll event, assume scrolling is done
|
}, 150); // If 150 ms pass without a scroll event, assume scrolling is done
|
||||||
};
|
};
|
||||||
|
|
||||||
isJumping = true;
|
isJumping = true;
|
||||||
checkIfScrollComplete();
|
checkIfScrollComplete();
|
||||||
if(this.codeEditor.current?.codeMirror) {
|
if (this.codeEditor.current?.codeMirror) {
|
||||||
this.codeEditor.current.codeMirror?.on('scroll', checkIfScrollComplete);
|
this.codeEditor.current.codeMirror?.on("scroll", checkIfScrollComplete);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(smooth) {
|
if (smooth) {
|
||||||
//Scroll 1/10 of the way every 10ms until 1px off.
|
//Scroll 1/10 of the way every 10ms until 1px off.
|
||||||
const incrementalScroll = setInterval(()=>{
|
const incrementalScroll = setInterval(() => {
|
||||||
currentY += (targetY - currentY) / 10;
|
currentY += (targetY - currentY) / 10;
|
||||||
this.codeEditor.current.codeMirror?.scrollTo(null, currentY);
|
this.codeEditor.current.codeMirror?.scrollTo(null, currentY);
|
||||||
|
|
||||||
// Update target: target height is not accurate until within +-10 lines of the visible window
|
// Update target: target height is not accurate until within +-10 lines of the visible window
|
||||||
if(Math.abs(targetY - currentY > 100))
|
if (Math.abs(targetY - currentY > 100))
|
||||||
targetY = this.codeEditor.current.codeMirror?.heightAtLine(targetLine, 'local', true);
|
targetY = this.codeEditor.current.codeMirror?.heightAtLine(targetLine, "local", true);
|
||||||
|
|
||||||
// End when close enough
|
// End when close enough
|
||||||
if(Math.abs(targetY - currentY) < 1) {
|
if (Math.abs(targetY - currentY) < 1) {
|
||||||
this.codeEditor.current.codeMirror?.scrollTo(null, targetY); // Scroll any remaining difference
|
this.codeEditor.current.codeMirror?.scrollTo(null, targetY); // Scroll any remaining difference
|
||||||
this.codeEditor.current.setCursorPosition({ line: targetLine + 1, ch: 0 });
|
this.codeEditor.current.setCursorPosition({ line: targetLine + 1, ch: 0 });
|
||||||
this.codeEditor.current.codeMirror?.addLineClass(targetLine + 1, 'wrap', 'sourceMoveFlash');
|
this.codeEditor.current.codeMirror?.addLineClass(targetLine + 1, "wrap", "sourceMoveFlash");
|
||||||
clearInterval(incrementalScroll);
|
clearInterval(incrementalScroll);
|
||||||
}
|
}
|
||||||
}, 10);
|
}, 10);
|
||||||
} else {
|
} else {
|
||||||
this.codeEditor.current.codeMirror?.scrollTo(null, targetY); // Scroll any remaining difference
|
this.codeEditor.current.codeMirror?.scrollTo(null, targetY); // Scroll any remaining difference
|
||||||
this.codeEditor.current.setCursorPosition({ line: targetLine + 1, ch: 0 });
|
this.codeEditor.current.setCursorPosition({ line: targetLine + 1, ch: 0 });
|
||||||
this.codeEditor.current.codeMirror?.addLineClass(targetLine + 1, 'wrap', 'sourceMoveFlash');
|
this.codeEditor.current.codeMirror?.addLineClass(targetLine + 1, "wrap", "sourceMoveFlash");
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
//Called when there are changes to the editor's dimensions
|
//Called when there are changes to the editor's dimensions
|
||||||
update : function(){},
|
update: function () {},
|
||||||
|
|
||||||
updateEditorTheme : function(newTheme){
|
updateEditorTheme: function (newTheme) {
|
||||||
window.localStorage.setItem(EDITOR_THEME_KEY, newTheme);
|
window.localStorage.setItem(EDITOR_THEME_KEY, newTheme);
|
||||||
this.setState({
|
this.setState({
|
||||||
editorTheme : newTheme
|
editorTheme: newTheme,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
//Called by CodeEditor after document switch, so Snippetbar can refresh UndoHistory
|
//Called by CodeEditor after document switch, so Snippetbar can refresh UndoHistory
|
||||||
rerenderParent : function (){
|
rerenderParent: function () {
|
||||||
this.forceUpdate();
|
this.forceUpdate();
|
||||||
},
|
},
|
||||||
|
|
||||||
renderEditor : function(){
|
renderEditor: function () {
|
||||||
if(this.isText()){
|
if (this.isText()) {
|
||||||
return <>
|
return (
|
||||||
<CodeEditor key='codeEditor'
|
<>
|
||||||
ref={this.codeEditor}
|
<CodeEditor
|
||||||
language='gfm'
|
key="codeEditor"
|
||||||
tab='brewText'
|
ref={this.codeEditor}
|
||||||
view={this.state.view}
|
language="gfm"
|
||||||
value={this.props.brew.text}
|
tab="brewText"
|
||||||
onChange={this.props.onBrewChange('text')}
|
view={this.state.view}
|
||||||
editorTheme={this.state.editorTheme}
|
value={this.props.brew.text}
|
||||||
rerenderParent={this.rerenderParent}
|
onChange={this.props.onBrewChange("text")}
|
||||||
style={{ height: `calc(100% - ${this.state.snippetBarHeight}px)` }} />
|
editorTheme={this.state.editorTheme}
|
||||||
</>;
|
rerenderParent={this.rerenderParent}
|
||||||
|
style={{ height: `calc(100% - ${this.state.snippetBarHeight}px)` }}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if(this.isStyle()){
|
if (this.isStyle()) {
|
||||||
return <>
|
return (
|
||||||
<CodeEditor key='codeEditor'
|
<>
|
||||||
ref={this.codeEditor}
|
<CodeEditor
|
||||||
language='css'
|
key="codeEditor"
|
||||||
tab='brewStyles'
|
ref={this.codeEditor}
|
||||||
view={this.state.view}
|
language="css"
|
||||||
value={this.props.brew.style ?? DEFAULT_STYLE_TEXT}
|
tab="brewStyles"
|
||||||
onChange={this.props.onBrewChange('style')}
|
view={this.state.view}
|
||||||
enableFolding={true}
|
value={this.props.brew.style ?? DEFAULT_STYLE_TEXT}
|
||||||
editorTheme={this.state.editorTheme}
|
onChange={this.props.onBrewChange("style")}
|
||||||
rerenderParent={this.rerenderParent}
|
enableFolding={true}
|
||||||
style={{ height: `calc(100% - ${this.state.snippetBarHeight}px)` }} />
|
editorTheme={this.state.editorTheme}
|
||||||
</>;
|
rerenderParent={this.rerenderParent}
|
||||||
|
style={{ height: `calc(100% - ${this.state.snippetBarHeight}px)` }}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if(this.isMeta()){
|
if (this.isMeta()) {
|
||||||
return <>
|
return (
|
||||||
<CodeEditor key='codeEditor'
|
<>
|
||||||
view={this.state.view}
|
<CodeEditor
|
||||||
style={{ display: 'none' }}
|
key="codeEditor"
|
||||||
rerenderParent={this.rerenderParent} />
|
view={this.state.view}
|
||||||
<MetadataEditor
|
style={{ display: "none" }}
|
||||||
metadata={this.props.brew}
|
rerenderParent={this.rerenderParent}
|
||||||
themeBundle={this.props.themeBundle}
|
/>
|
||||||
onChange={this.props.onBrewChange('metadata')}
|
<MetadataEditor
|
||||||
reportError={this.props.reportError}
|
metadata={this.props.brew}
|
||||||
userThemes={this.props.userThemes}/>
|
themeBundle={this.props.themeBundle}
|
||||||
</>;
|
onChange={this.props.onBrewChange("metadata")}
|
||||||
|
reportError={this.props.reportError}
|
||||||
|
userThemes={this.props.userThemes}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if(this.isSnip()){
|
if (this.isSnip()) {
|
||||||
if(!this.props.brew.snippets) { this.props.brew.snippets = DEFAULT_SNIPPET_TEXT; }
|
if (!this.props.brew.snippets) {
|
||||||
return <>
|
this.props.brew.snippets = DEFAULT_SNIPPET_TEXT;
|
||||||
<CodeEditor key='codeEditor'
|
}
|
||||||
ref={this.codeEditor}
|
return (
|
||||||
language='gfm'
|
<>
|
||||||
tab='brewSnippets'
|
<CodeEditor
|
||||||
view={this.state.view}
|
key="codeEditor"
|
||||||
value={this.props.brew.snippets}
|
ref={this.codeEditor}
|
||||||
onChange={this.props.onBrewChange('snippets')}
|
language="gfm"
|
||||||
enableFolding={true}
|
tab="brewSnippets"
|
||||||
editorTheme={this.state.editorTheme}
|
view={this.state.view}
|
||||||
rerenderParent={this.rerenderParent}
|
value={this.props.brew.snippets}
|
||||||
style={{ height: `calc(100% -${this.state.snippetBarHeight}px)` }} />
|
onChange={this.props.onBrewChange("snippets")}
|
||||||
</>;
|
enableFolding={true}
|
||||||
|
editorTheme={this.state.editorTheme}
|
||||||
|
rerenderParent={this.rerenderParent}
|
||||||
|
style={{ height: `calc(100% -${this.state.snippetBarHeight}px)` }}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
redo : function(){
|
redo: function () {
|
||||||
return this.codeEditor.current?.redo();
|
return this.codeEditor.current?.redo();
|
||||||
},
|
},
|
||||||
|
|
||||||
historySize : function(){
|
historySize: function () {
|
||||||
return this.codeEditor.current?.historySize();
|
return this.codeEditor.current?.historySize();
|
||||||
},
|
},
|
||||||
|
|
||||||
undo : function(){
|
undo: function () {
|
||||||
return this.codeEditor.current?.undo();
|
return this.codeEditor.current?.undo();
|
||||||
},
|
},
|
||||||
|
|
||||||
foldCode : function(){
|
foldCode: function () {
|
||||||
return this.codeEditor.current?.foldAllCode();
|
return this.codeEditor.current?.foldAllCode();
|
||||||
},
|
},
|
||||||
|
|
||||||
unfoldCode : function(){
|
unfoldCode: function () {
|
||||||
return this.codeEditor.current?.unfoldAllCode();
|
return this.codeEditor.current?.unfoldAllCode();
|
||||||
},
|
},
|
||||||
|
|
||||||
render : function(){
|
render: function () {
|
||||||
return (
|
return (
|
||||||
<div className='editor' ref={this.editor}>
|
<div className="editor" ref={this.editor}>
|
||||||
<SnippetBar
|
<SnippetBar
|
||||||
brew={this.props.brew}
|
brew={this.props.brew}
|
||||||
view={this.state.view}
|
view={this.state.view}
|
||||||
@@ -544,7 +625,7 @@ const Editor = createReactClass({
|
|||||||
{this.renderEditor()}
|
{this.renderEditor()}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export default Editor;
|
export default Editor;
|
||||||
|
|||||||
@@ -10,25 +10,25 @@
|
|||||||
.codeEditor {
|
.codeEditor {
|
||||||
height : calc(100% - 25px);
|
height : calc(100% - 25px);
|
||||||
.cm-editor { height : 100%; }
|
.cm-editor { height : 100%; }
|
||||||
.pageLine, .snippetLine {
|
.cm-pageLine, .cm-snippetLine {
|
||||||
background : #33333328;
|
background : #33333328;
|
||||||
border-top : #333399 solid 1px;
|
border-top : #333399 solid 1px;
|
||||||
}
|
}
|
||||||
.editor-page-count {
|
.cm-editor-page-count {
|
||||||
float : right;
|
float : right;
|
||||||
color : grey;
|
color : grey;
|
||||||
}
|
}
|
||||||
.editor-snippet-count {
|
.cm-editor-snippet-count {
|
||||||
float : right;
|
float : right;
|
||||||
color : grey;
|
color : grey;
|
||||||
}
|
}
|
||||||
.columnSplit {
|
.cm-cm-columnSplit {
|
||||||
font-style : italic;
|
font-style : italic;
|
||||||
color : grey;
|
color : grey;
|
||||||
background-color : fade(#229999, 15%);
|
background-color : fade(#229999, 15%);
|
||||||
border-bottom : #229999 solid 1px;
|
border-bottom : #229999 solid 1px;
|
||||||
}
|
}
|
||||||
.define {
|
.cm-define {
|
||||||
&:not(.term):not(.definition) {
|
&:not(.term):not(.definition) {
|
||||||
font-weight : bold;
|
font-weight : bold;
|
||||||
color : #949494;
|
color : #949494;
|
||||||
@@ -38,21 +38,21 @@
|
|||||||
&.term { color : rgb(96, 117, 143); }
|
&.term { color : rgb(96, 117, 143); }
|
||||||
&.definition { color : rgb(97, 57, 178); }
|
&.definition { color : rgb(97, 57, 178); }
|
||||||
}
|
}
|
||||||
.block:not(.cm-comment) {
|
.cm-block:not(.cm-comment) {
|
||||||
font-weight : bold;
|
font-weight : bold;
|
||||||
color : purple;
|
color : purple;
|
||||||
//font-style: italic;
|
//font-style: italic;
|
||||||
}
|
}
|
||||||
.inline-block:not(.cm-comment) {
|
.cm-inline-block:not(.cm-comment) {
|
||||||
font-weight : bold;
|
font-weight : bold;
|
||||||
color : red;
|
color : red;
|
||||||
//font-style: italic;
|
//font-style: italic;
|
||||||
}
|
}
|
||||||
.injection:not(.cm-comment) {
|
.cm-injection:not(.cm-comment) {
|
||||||
font-weight : bold;
|
font-weight : bold;
|
||||||
color : green;
|
color : green;
|
||||||
}
|
}
|
||||||
.emoji:not(.cm-comment) {
|
.cm-emoji:not(.cm-comment) {
|
||||||
padding-bottom : 1px;
|
padding-bottom : 1px;
|
||||||
margin-left : 2px;
|
margin-left : 2px;
|
||||||
font-weight : bold;
|
font-weight : bold;
|
||||||
@@ -62,19 +62,19 @@
|
|||||||
background : #FFC8FF;
|
background : #FFC8FF;
|
||||||
border-radius : 6px;
|
border-radius : 6px;
|
||||||
}
|
}
|
||||||
.superscript:not(.cm-comment) {
|
.cm-superscript:not(.cm-comment) {
|
||||||
font-size : 0.9em;
|
font-size : 0.9em;
|
||||||
font-weight : bold;
|
font-weight : bold;
|
||||||
vertical-align : super;
|
vertical-align : super;
|
||||||
color : goldenrod;
|
color : goldenrod;
|
||||||
}
|
}
|
||||||
.subscript:not(.cm-comment) {
|
.cm-subscript:not(.cm-comment) {
|
||||||
font-size : 0.9em;
|
font-size : 0.9em;
|
||||||
font-weight : bold;
|
font-weight : bold;
|
||||||
vertical-align : sub;
|
vertical-align : sub;
|
||||||
color : rgb(123, 123, 15);
|
color : rgb(123, 123, 15);
|
||||||
}
|
}
|
||||||
.dl-highlight {
|
.cm-dl-highlight {
|
||||||
&.dl-colon-highlight {
|
&.dl-colon-highlight {
|
||||||
font-weight : bold;
|
font-weight : bold;
|
||||||
color : #949494;
|
color : #949494;
|
||||||
|
|||||||
Reference in New Issue
Block a user