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

Mobile: Syntax highlighting for TeX, code blocks #6607

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
15 changes: 15 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -859,6 +859,21 @@ packages/app-mobile/components/NoteEditor/CodeMirror.js.map
packages/app-mobile/components/NoteEditor/NoteEditor.d.ts
packages/app-mobile/components/NoteEditor/NoteEditor.js
packages/app-mobile/components/NoteEditor/NoteEditor.js.map
packages/app-mobile/components/NoteEditor/codeMirrorDecorators.d.ts
packages/app-mobile/components/NoteEditor/codeMirrorDecorators.js
packages/app-mobile/components/NoteEditor/codeMirrorDecorators.js.map
packages/app-mobile/components/NoteEditor/codeMirrorLanguages.d.ts
packages/app-mobile/components/NoteEditor/codeMirrorLanguages.js
packages/app-mobile/components/NoteEditor/codeMirrorLanguages.js.map
packages/app-mobile/components/NoteEditor/codeMirrorTheme.d.ts
packages/app-mobile/components/NoteEditor/codeMirrorTheme.js
packages/app-mobile/components/NoteEditor/codeMirrorTheme.js.map
packages/app-mobile/components/NoteEditor/markdownMathParser.d.ts
packages/app-mobile/components/NoteEditor/markdownMathParser.js
packages/app-mobile/components/NoteEditor/markdownMathParser.js.map
packages/app-mobile/components/NoteEditor/types.d.ts
packages/app-mobile/components/NoteEditor/types.js
packages/app-mobile/components/NoteEditor/types.js.map
packages/app-mobile/components/SelectDateTimeDialog.d.ts
packages/app-mobile/components/SelectDateTimeDialog.js
packages/app-mobile/components/SelectDateTimeDialog.js.map
Expand Down
15 changes: 15 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,21 @@ packages/app-mobile/components/NoteEditor/CodeMirror.js.map
packages/app-mobile/components/NoteEditor/NoteEditor.d.ts
packages/app-mobile/components/NoteEditor/NoteEditor.js
packages/app-mobile/components/NoteEditor/NoteEditor.js.map
packages/app-mobile/components/NoteEditor/codeMirrorDecorators.d.ts
packages/app-mobile/components/NoteEditor/codeMirrorDecorators.js
packages/app-mobile/components/NoteEditor/codeMirrorDecorators.js.map
packages/app-mobile/components/NoteEditor/codeMirrorLanguages.d.ts
packages/app-mobile/components/NoteEditor/codeMirrorLanguages.js
packages/app-mobile/components/NoteEditor/codeMirrorLanguages.js.map
packages/app-mobile/components/NoteEditor/codeMirrorTheme.d.ts
packages/app-mobile/components/NoteEditor/codeMirrorTheme.js
packages/app-mobile/components/NoteEditor/codeMirrorTheme.js.map
packages/app-mobile/components/NoteEditor/markdownMathParser.d.ts
packages/app-mobile/components/NoteEditor/markdownMathParser.js
packages/app-mobile/components/NoteEditor/markdownMathParser.js.map
packages/app-mobile/components/NoteEditor/types.d.ts
packages/app-mobile/components/NoteEditor/types.js
packages/app-mobile/components/NoteEditor/types.js.map
packages/app-mobile/components/SelectDateTimeDialog.d.ts
packages/app-mobile/components/SelectDateTimeDialog.js
packages/app-mobile/components/SelectDateTimeDialog.js.map
Expand Down
207 changes: 63 additions & 144 deletions packages/app-mobile/components/NoteEditor/CodeMirror.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,26 @@
// wrapper to access CodeMirror functionalities. Anything else should be done
// from NoteEditor.tsx.

import { EditorState, Extension } from '@codemirror/state';
import { MarkdownMathExtension } from './markdownMathParser';
import codeMirrorDecorator from './codeMirrorDecorators';
import createTheme from './codeMirrorTheme';
import syntaxHighlightingLanguages from './codeMirrorLanguages';

import { EditorState } from '@codemirror/state';
import { markdown } from '@codemirror/lang-markdown';
import { GFM } from '@lezer/markdown';
import { indentOnInput, indentUnit } from '@codemirror/language';
import { highlightSelectionMatches, search } from '@codemirror/search';
import { defaultHighlightStyle, syntaxHighlighting, HighlightStyle } from '@codemirror/language';
import { tags } from '@lezer/highlight';
import { EditorView, drawSelection, highlightSpecialChars, ViewUpdate } from '@codemirror/view';
import { undo, redo, history, undoDepth, redoDepth } from '@codemirror/commands';

import { keymap } from '@codemirror/view';
import { indentOnInput } from '@codemirror/language';
import { searchKeymap } from '@codemirror/search';
import { historyKeymap, defaultKeymap } from '@codemirror/commands';

interface CodeMirrorResult {
editor: EditorView;
undo: Function;
redo: Function;
select(anchor: number, head: number): void;
scrollSelectionIntoView(): void;
insertText(text: string): void;
}
import { historyKeymap, defaultKeymap, indentWithTab } from '@codemirror/commands';

import { EditorControl, EditorSettings } from './types';
import { ChangeEvent, SelectionChangeEvent, Selection } from './types';


function postMessage(name: string, data: any) {
(window as any).ReactNativeWebView.postMessage(JSON.stringify({
Expand All @@ -42,125 +41,14 @@ function logMessage(...msg: any[]) {
postMessage('onLog', { value: msg });
}

// For an example on how to customize the theme, see:
//
// https://github.com/codemirror/theme-one-dark/blob/main/src/one-dark.ts
//
// For a tutorial, see:
//
// https://codemirror.net/6/examples/styling/#themes
//
// Use Safari developer tools to view the content of the CodeMirror iframe while
// the app is running. It seems that what appears as ".ͼ1" in the CSS is the
// equivalent of "&" in the theme object. So to target ".ͼ1.cm-focused", you'd
// use '&.cm-focused' in the theme.
const createTheme = (theme: any): Extension[] => {
const isDarkTheme = theme.appearance === 'dark';

const baseGlobalStyle: Record<string, string> = {
color: theme.color,
backgroundColor: theme.backgroundColor,
fontFamily: theme.fontFamily,
fontSize: `${theme.fontSize}px`,
};
const baseCursorStyle: Record<string, string> = { };
const baseContentStyle: Record<string, string> = { };
const baseSelectionStyle: Record<string, string> = { };

// If we're in dark mode, the caret and selection are difficult to see.
// Adjust them appropriately
if (isDarkTheme) {
// Styling the caret requires styling both the caret itself
// and the CodeMirror caret.
// See https://codemirror.net/6/examples/styling/#themes
baseContentStyle.caretColor = 'white';
baseCursorStyle.borderLeftColor = 'white';

baseSelectionStyle.backgroundColor = '#6b6b6b';
}

const baseTheme = EditorView.baseTheme({
'&': baseGlobalStyle,

// These must be !important or more specific than CodeMirror's built-ins
'.cm-content': baseContentStyle,
'&.cm-focused .cm-cursor': baseCursorStyle,
'&.cm-focused .cm-selectionBackground, ::selection': baseSelectionStyle,

'&.cm-focused': {
outline: 'none',
},
});

const appearanceTheme = EditorView.theme({}, { dark: isDarkTheme });

const baseHeadingStyle = {
fontWeight: 'bold',
fontFamily: theme.fontFamily,
};

const highlightingStyle = HighlightStyle.define([
{
tag: tags.strong,
fontWeight: 'bold',
},
{
tag: tags.emphasis,
fontStyle: 'italic',
},
{
...baseHeadingStyle,
tag: tags.heading1,
fontSize: '1.6em',
borderBottom: `1px solid ${theme.dividerColor}`,
},
{
...baseHeadingStyle,
tag: tags.heading2,
fontSize: '1.4em',
},
{
...baseHeadingStyle,
tag: tags.heading3,
fontSize: '1.3em',
},
{
...baseHeadingStyle,
tag: tags.heading4,
fontSize: '1.2em',
},
{
...baseHeadingStyle,
tag: tags.heading5,
fontSize: '1.1em',
},
{
...baseHeadingStyle,
tag: tags.heading6,
fontSize: '1.0em',
},
{
tag: tags.list,
fontFamily: theme.fontFamily,
},
]);

return [
baseTheme,
appearanceTheme,
syntaxHighlighting(highlightingStyle),

// If we haven't defined highlighting for tags, fall back
// to the default.
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
];
};

export function initCodeMirror(parentElement: any, initialText: string, theme: any): CodeMirrorResult {
export function initCodeMirror(
parentElement: any, initialText: string, settings: EditorSettings
): EditorControl {
logMessage('Initializing CodeMirror...');
const theme = settings.themeData;

let schedulePostUndoRedoDepthChangeId_: any = 0;
function schedulePostUndoRedoDepthChange(editor: EditorView, doItNow: boolean = false) {
const schedulePostUndoRedoDepthChange = (editor: EditorView, doItNow: boolean = false) => {
if (schedulePostUndoRedoDepthChangeId_) {
if (doItNow) {
clearTimeout(schedulePostUndoRedoDepthChangeId_);
Expand All @@ -176,14 +64,47 @@ export function initCodeMirror(parentElement: any, initialText: string, theme: a
redoDepth: redoDepth(editor.state),
});
}, doItNow ? 0 : 1000);
}
};

const notifyDocChanged = (viewUpdate: ViewUpdate) => {
if (viewUpdate.docChanged) {
const event: ChangeEvent = {
value: editor.state.doc.toString(),
};

postMessage('onChange', event);
schedulePostUndoRedoDepthChange(editor);
}
};

const notifySelectionChange = (viewUpdate: ViewUpdate) => {
if (!viewUpdate.state.selection.eq(viewUpdate.startState.selection)) {
const mainRange = viewUpdate.state.selection.main;
const selection: Selection = {
start: mainRange.from,
end: mainRange.to,
};
const event: SelectionChangeEvent = {
selection,
};
postMessage('onSelectionChange', event);
}
};

const editor = new EditorView({
state: EditorState.create({
// See https://github.com/codemirror/basic-setup/blob/main/src/codemirror.ts
// for a sample configuration.
extensions: [
markdown(),
markdown({
extensions: [
GFM,

// Don't highlight KaTeX if the user disabled it
settings.katexEnabled ? MarkdownMathExtension : [],
],
codeLanguages: syntaxHighlightingLanguages,
}),
...createTheme(theme),
history(),
search(),
Expand All @@ -192,23 +113,20 @@ export function initCodeMirror(parentElement: any, initialText: string, theme: a
highlightSelectionMatches(),
indentOnInput(),

// By default, indent with a tab
indentUnit.of('\t'),

// Full-line styling
codeMirrorDecorator,

EditorView.lineWrapping,
EditorView.contentAttributes.of({ autocapitalize: 'sentence' }),
EditorView.updateListener.of((viewUpdate: ViewUpdate) => {
if (viewUpdate.docChanged) {
postMessage('onChange', { value: editor.state.doc.toString() });
schedulePostUndoRedoDepthChange(editor);
}

if (!viewUpdate.state.selection.eq(viewUpdate.startState.selection)) {
const mainRange = viewUpdate.state.selection.main;
const selStart = mainRange.from;
const selEnd = mainRange.to;
postMessage('onSelectionChange', { selection: { start: selStart, end: selEnd } });
}
notifyDocChanged(viewUpdate);
notifySelectionChange(viewUpdate);
}),
keymap.of([
...defaultKeymap, ...historyKeymap, ...searchKeymap,
...defaultKeymap, ...historyKeymap, indentWithTab, ...searchKeymap,
]),
],
doc: initialText,
Expand All @@ -218,6 +136,7 @@ export function initCodeMirror(parentElement: any, initialText: string, theme: a

return {
editor,

undo: () => {
undo(editor);
schedulePostUndoRedoDepthChange(editor, true);
Expand Down
Loading