Replace Monaco with CodeMirror (#36764)
- Replace monaco-editor with CodeMirror 6 - Add `--color-syntax-*` CSS variables for all syntax token types, shared by CodeMirror, Chroma and EasyMDE - Consolidate chroma CSS into a single theme-independent file (`modules/chroma.css`) - Syntax colors in the code editor now match the code view and light/dark themes - Code editor is now 12px instead of 14px font size to match code view and GitHub - Use a global style for kbd elements - When editing existing files, focus will be on codemirror instead of filename input. - Keyboard shortcuts are roughtly the same as VSCode - Add a "Find" button, useful for mobile - Add context menu similar to Monaco - Add a command palette (Ctrl/Cmd+Shift+P or F1) or via button - Add clickable URLs via Ctrl/Cmd+click - Add e2e test for the code editor - Remove `window.codeEditors` global - The main missing Monaco features are hover types and semantic rename but these were not fully working because monaco operated only on single files and only for JS/TS/HTML/CSS/JSON. | | Monaco (main) | CodeMirror (cm) | Delta | |---|---|---|---| | **Build time** | 7.8s | 5.3s | **-32%** | | **JS output** | 25 MB | 14 MB | **-44%** | | **CSS output** | 1.2 MB | 1012 KB | **-17%** | | **Total (no maps)** | 23.3 MB | 12.1 MB | **-48%** | Fixes: #36311 Fixes: #14776 Fixes: #12171 <img width="1333" height="555" alt="image" src="https://github.com/user-attachments/assets/f0fe3a28-1ed9-4f22-bf25-2b161501d7ce" /> --------- Signed-off-by: silverwind <me@silverwind.io> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: wxiaoguang <wxiaoguang@gmail.com> Co-authored-by: Giteabot <teabot@gitea.io> Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
This commit is contained in:
@@ -1,255 +0,0 @@
|
||||
import {colord} from 'colord';
|
||||
import {basename, extname, isObject, isDarkTheme} from '../utils.ts';
|
||||
import {onInputDebounce, toggleElem} from '../utils/dom.ts';
|
||||
import type MonacoNamespace from 'monaco-editor';
|
||||
|
||||
type Monaco = typeof MonacoNamespace;
|
||||
type IStandaloneCodeEditor = MonacoNamespace.editor.IStandaloneCodeEditor;
|
||||
type IEditorOptions = MonacoNamespace.editor.IEditorOptions;
|
||||
type IGlobalEditorOptions = MonacoNamespace.editor.IGlobalEditorOptions;
|
||||
type ITextModelUpdateOptions = MonacoNamespace.editor.ITextModelUpdateOptions;
|
||||
type MonacoOpts = IEditorOptions & IGlobalEditorOptions & ITextModelUpdateOptions;
|
||||
|
||||
type CodeEditorConfig = {
|
||||
indent_style?: 'tab' | 'space',
|
||||
indent_size?: number,
|
||||
tab_width?: string | number, // backend emits this as string
|
||||
trim_trailing_whitespace?: boolean,
|
||||
};
|
||||
|
||||
const languagesByFilename: Record<string, string> = {};
|
||||
const languagesByExt: Record<string, string> = {};
|
||||
|
||||
const baseOptions: MonacoOpts = {
|
||||
fontFamily: 'var(--fonts-monospace)',
|
||||
fontSize: 14, // https://github.com/microsoft/monaco-editor/issues/2242
|
||||
guides: {bracketPairs: false, indentation: false},
|
||||
links: false,
|
||||
minimap: {enabled: false},
|
||||
occurrencesHighlight: 'off',
|
||||
overviewRulerLanes: 0,
|
||||
renderLineHighlight: 'all',
|
||||
renderLineHighlightOnlyWhenFocus: true,
|
||||
rulers: [],
|
||||
scrollbar: {horizontalScrollbarSize: 6, verticalScrollbarSize: 6, alwaysConsumeMouseWheel: false},
|
||||
scrollBeyondLastLine: false,
|
||||
automaticLayout: true,
|
||||
indentSize: 'tabSize',
|
||||
wrappingIndent: 'none',
|
||||
wordWrapBreakAfterCharacters: '',
|
||||
wordWrapBreakBeforeCharacters: '',
|
||||
matchBrackets: 'never',
|
||||
editContext: false, // https://github.com/microsoft/monaco-editor/issues/5081
|
||||
};
|
||||
|
||||
function getCodeEditorConfig(input: HTMLInputElement): CodeEditorConfig | null {
|
||||
const json = input.getAttribute('data-code-editor-config');
|
||||
if (!json) return null;
|
||||
try {
|
||||
return JSON.parse(json);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function initLanguages(monaco: Monaco): void {
|
||||
for (const {filenames, extensions, id} of monaco.languages.getLanguages()) {
|
||||
for (const filename of filenames || []) {
|
||||
languagesByFilename[filename] = id;
|
||||
}
|
||||
for (const extension of extensions || []) {
|
||||
languagesByExt[extension] = id;
|
||||
}
|
||||
if (id === 'typescript') {
|
||||
monaco.typescript.typescriptDefaults.setCompilerOptions({
|
||||
// this is needed to suppress error annotations in tsx regarding missing --jsx flag.
|
||||
jsx: monaco.typescript.JsxEmit.Preserve,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getLanguage(filename: string): string {
|
||||
return languagesByFilename[filename] || languagesByExt[extname(filename)] || 'plaintext';
|
||||
}
|
||||
|
||||
function updateEditor(monaco: Monaco, editor: IStandaloneCodeEditor, filename: string, lineWrapExts: string[]): void {
|
||||
editor.updateOptions(getFileBasedOptions(filename, lineWrapExts));
|
||||
const model = editor.getModel();
|
||||
if (!model) return;
|
||||
const language = model.getLanguageId();
|
||||
const newLanguage = getLanguage(filename);
|
||||
if (language !== newLanguage) monaco.editor.setModelLanguage(model, newLanguage);
|
||||
// TODO: Need to update the model uri with the new filename, but there is no easy way currently, see
|
||||
// https://github.com/microsoft/monaco-editor/discussions/3751
|
||||
}
|
||||
|
||||
// export editor for customization - https://github.com/go-gitea/gitea/issues/10409
|
||||
function exportEditor(editor: IStandaloneCodeEditor): void {
|
||||
if (!window.codeEditors) window.codeEditors = [];
|
||||
if (!window.codeEditors.includes(editor)) window.codeEditors.push(editor);
|
||||
}
|
||||
|
||||
function updateTheme(monaco: Monaco): void {
|
||||
// https://github.com/microsoft/monaco-editor/issues/2427
|
||||
// also, monaco can only parse 6-digit hex colors, so we convert the colors to that format
|
||||
const styles = window.getComputedStyle(document.documentElement);
|
||||
const getColor = (name: string) => colord(styles.getPropertyValue(name).trim()).alpha(1).toHex();
|
||||
|
||||
monaco.editor.defineTheme('gitea', {
|
||||
base: isDarkTheme() ? 'vs-dark' : 'vs',
|
||||
inherit: true,
|
||||
rules: [
|
||||
{
|
||||
background: getColor('--color-code-bg'),
|
||||
token: '',
|
||||
},
|
||||
],
|
||||
colors: {
|
||||
'editor.background': getColor('--color-code-bg'),
|
||||
'editor.foreground': getColor('--color-text'),
|
||||
'editor.inactiveSelectionBackground': getColor('--color-primary-light-4'),
|
||||
'editor.lineHighlightBackground': getColor('--color-editor-line-highlight'),
|
||||
'editor.selectionBackground': getColor('--color-primary-light-3'),
|
||||
'editor.selectionForeground': getColor('--color-primary-light-3'),
|
||||
'editorLineNumber.background': getColor('--color-code-bg'),
|
||||
'editorLineNumber.foreground': getColor('--color-secondary-dark-6'),
|
||||
'editorWidget.background': getColor('--color-body'),
|
||||
'editorWidget.border': getColor('--color-secondary'),
|
||||
'input.background': getColor('--color-input-background'),
|
||||
'input.border': getColor('--color-input-border'),
|
||||
'input.foreground': getColor('--color-input-text'),
|
||||
'scrollbar.shadow': getColor('--color-shadow-opaque'),
|
||||
'progressBar.background': getColor('--color-primary'),
|
||||
'focusBorder': '#0000', // prevent blue border
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
type CreateMonacoOpts = MonacoOpts & {language?: string};
|
||||
|
||||
export async function createMonaco(textarea: HTMLTextAreaElement, filename: string, opts: CreateMonacoOpts): Promise<{monaco: Monaco, editor: IStandaloneCodeEditor}> {
|
||||
const monaco = await import('../modules/monaco.ts');
|
||||
|
||||
initLanguages(monaco);
|
||||
let {language, ...other} = opts;
|
||||
if (!language) language = getLanguage(filename);
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.className = 'monaco-editor-container';
|
||||
if (!textarea.parentNode) throw new Error('Parent node absent');
|
||||
textarea.parentNode.append(container);
|
||||
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
|
||||
updateTheme(monaco);
|
||||
});
|
||||
updateTheme(monaco);
|
||||
|
||||
const model = monaco.editor.createModel(textarea.value, language, monaco.Uri.file(filename));
|
||||
|
||||
const editor = monaco.editor.create(container, {
|
||||
model,
|
||||
theme: 'gitea',
|
||||
...baseOptions,
|
||||
...other,
|
||||
});
|
||||
|
||||
monaco.editor.addKeybindingRules([
|
||||
{keybinding: monaco.KeyCode.Enter, command: null}, // disable enter from accepting code completion
|
||||
]);
|
||||
|
||||
model.onDidChangeContent(() => {
|
||||
textarea.value = editor.getValue({
|
||||
preserveBOM: true,
|
||||
lineEnding: '',
|
||||
});
|
||||
textarea.dispatchEvent(new Event('change')); // seems to be needed for jquery-are-you-sure
|
||||
});
|
||||
|
||||
const elEditorOptions = textarea.closest('form')?.querySelector('.code-editor-options');
|
||||
if (elEditorOptions) {
|
||||
elEditorOptions.querySelector<HTMLSelectElement>('.js-indent-style-select')!.addEventListener('change', (e) => {
|
||||
const insertSpaces = (e.target as HTMLSelectElement).value === 'space';
|
||||
editor.updateOptions({insertSpaces, useTabStops: !insertSpaces});
|
||||
});
|
||||
elEditorOptions.querySelector<HTMLSelectElement>('.js-indent-size-select')!.addEventListener('change', (e) => {
|
||||
const tabSize = Number((e.target as HTMLSelectElement).value);
|
||||
editor.updateOptions({tabSize});
|
||||
});
|
||||
elEditorOptions.querySelector<HTMLSelectElement>('.js-line-wrap-select')!.addEventListener('change', (e) => {
|
||||
const wordWrap = (e.target as HTMLSelectElement).value as IEditorOptions['wordWrap'];
|
||||
editor.updateOptions({wordWrap});
|
||||
});
|
||||
}
|
||||
|
||||
exportEditor(editor);
|
||||
|
||||
const loading = document.querySelector('.editor-loading');
|
||||
if (loading) loading.remove();
|
||||
|
||||
return {monaco, editor};
|
||||
}
|
||||
|
||||
function getFileBasedOptions(filename: string, lineWrapExts: string[]): MonacoOpts {
|
||||
return {
|
||||
wordWrap: (lineWrapExts || []).includes(extname(filename)) ? 'on' : 'off',
|
||||
};
|
||||
}
|
||||
|
||||
function togglePreviewDisplay(previewable: boolean): void {
|
||||
// FIXME: here and below, the selector is too broad, it should only query in the editor related scope
|
||||
const previewTab = document.querySelector<HTMLElement>('a[data-tab="preview"]');
|
||||
// the "preview tab" exists for "file code editor", but doesn't exist for "git hook editor"
|
||||
if (!previewTab) return;
|
||||
|
||||
toggleElem(previewTab, previewable);
|
||||
if (previewable) return;
|
||||
|
||||
// If not previewable but the "preview" tab was active (user changes the filename to a non-previewable one),
|
||||
// then the "preview" tab becomes inactive (hidden), so the "write" tab should become active
|
||||
if (previewTab.classList.contains('active')) {
|
||||
const writeTab = document.querySelector<HTMLElement>('a[data-tab="write"]');
|
||||
writeTab?.click(); // TODO: it shouldn't need null-safe operator, writeTab must exist
|
||||
}
|
||||
}
|
||||
|
||||
export async function createCodeEditor(textarea: HTMLTextAreaElement, filenameInput: HTMLInputElement): Promise<IStandaloneCodeEditor> {
|
||||
const filename = basename(filenameInput.value);
|
||||
const previewableExts = new Set((textarea.getAttribute('data-previewable-extensions') || '').split(','));
|
||||
const lineWrapExts = (textarea.getAttribute('data-line-wrap-extensions') || '').split(',');
|
||||
const isPreviewable = previewableExts.has(extname(filename));
|
||||
const editorConfig = getCodeEditorConfig(filenameInput);
|
||||
|
||||
togglePreviewDisplay(isPreviewable);
|
||||
|
||||
const {monaco, editor} = await createMonaco(textarea, filename, {
|
||||
...getFileBasedOptions(filenameInput.value, lineWrapExts),
|
||||
...getMonacoOptsByCodeEditorConfig(editorConfig),
|
||||
});
|
||||
|
||||
filenameInput.addEventListener('input', onInputDebounce(() => {
|
||||
const filename = filenameInput.value;
|
||||
const previewable = previewableExts.has(extname(filename));
|
||||
togglePreviewDisplay(previewable);
|
||||
updateEditor(monaco, editor, filename, lineWrapExts);
|
||||
}));
|
||||
|
||||
return editor;
|
||||
}
|
||||
|
||||
function getMonacoOptsByCodeEditorConfig(ec: CodeEditorConfig | null): MonacoOpts {
|
||||
if (!ec || !isObject(ec)) return {};
|
||||
|
||||
const opts: MonacoOpts = {};
|
||||
opts.detectIndentation = !ec.indent_style || !ec.indent_size;
|
||||
|
||||
// with indentSize='tabSize', this also controls the `indentSize` option
|
||||
if (!opts.detectIndentation) {
|
||||
opts.tabSize = Number(ec.tab_width) || Number(ec.indent_size) || 4;
|
||||
}
|
||||
|
||||
opts.trimAutoWhitespace = ec.trim_trailing_whitespace === true;
|
||||
opts.insertSpaces = ec.indent_style === 'space';
|
||||
opts.useTabStops = ec.indent_style === 'tab';
|
||||
return opts;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import {html, htmlRaw} from '../utils/html.ts';
|
||||
import {createCodeEditor} from './codeeditor.ts';
|
||||
import {hideElem, queryElems, showElem, createElementFromHTML} from '../utils/dom.ts';
|
||||
import {createCodeEditor} from '../modules/codeeditor/main.ts';
|
||||
import {trimTrailingWhitespaceFromView} from '../modules/codeeditor/utils.ts';
|
||||
import {hideElem, queryElems, showElem, createElementFromHTML, onInputDebounce} from '../utils/dom.ts';
|
||||
import {POST} from '../modules/fetch.ts';
|
||||
import {initDropzone} from './dropzone.ts';
|
||||
import {confirmModal} from './comp/ConfirmModal.ts';
|
||||
@@ -50,8 +51,12 @@ export function initRepoEditor() {
|
||||
});
|
||||
}
|
||||
|
||||
// ATTENTION: two pages have this filename input
|
||||
// * new/edit file page: there is a code editor
|
||||
// * upload page: there is no code editor, but a uploader
|
||||
const filenameInput = document.querySelector<HTMLInputElement>('#file-name')!;
|
||||
if (!filenameInput) return;
|
||||
filenameInput.value = filenameInput.defaultValue; // prevent browser from restoring form values on refresh
|
||||
function joinTreePath() {
|
||||
const parts = [];
|
||||
for (const el of document.querySelectorAll('.breadcrumb span.section')) {
|
||||
@@ -143,7 +148,8 @@ export function initRepoEditor() {
|
||||
|
||||
const elForm = document.querySelector<HTMLFormElement>('.repository.editor .edit.form')!;
|
||||
|
||||
// on the upload page, there is no editor(textarea)
|
||||
// see the ATTENTION above, on the upload page, there is no editor(textarea)
|
||||
// so only the filename input above is initialized, the code below (for the code editor) will be skipped
|
||||
const editArea = document.querySelector<HTMLTextAreaElement>('.page-content.repository.editor textarea#edit_area');
|
||||
if (!editArea) return;
|
||||
|
||||
@@ -170,16 +176,22 @@ export function initRepoEditor() {
|
||||
|
||||
(async () => {
|
||||
const editor = await createCodeEditor(editArea, filenameInput);
|
||||
filenameInput.addEventListener('input', onInputDebounce(() => editor.updateFilename(filenameInput.value)));
|
||||
|
||||
// Update the editor from query params, if available,
|
||||
// only after the dirtyFileClass initialization
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const value = params.get('value');
|
||||
if (value) {
|
||||
editor.setValue(value);
|
||||
editor.view.dispatch({
|
||||
changes: {from: 0, to: editor.view.state.doc.length, insert: value},
|
||||
});
|
||||
}
|
||||
|
||||
commitButton.addEventListener('click', async (e) => {
|
||||
if (editor.trimTrailingWhitespace) {
|
||||
trimTrailingWhitespaceFromView(editor.view);
|
||||
}
|
||||
// A modal which asks if an empty file should be committed
|
||||
if (!editArea.value) {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {createMonaco} from './codeeditor.ts';
|
||||
import {createCodeEditor} from '../modules/codeeditor/main.ts';
|
||||
import {onInputDebounce, queryElems, toggleElem} from '../utils/dom.ts';
|
||||
import {POST} from '../modules/fetch.ts';
|
||||
import {initRepoSettingsBranchesDrag} from './repo-settings-branches.ts';
|
||||
@@ -72,8 +72,7 @@ function initRepoSettingsSearchTeamBox() {
|
||||
|
||||
function initRepoSettingsGitHook() {
|
||||
if (!document.querySelector('.page-content.repository.settings.edit.githook')) return;
|
||||
const filename = document.querySelector('.hook-filename')!.textContent;
|
||||
createMonaco(document.querySelector<HTMLTextAreaElement>('#content')!, filename, {language: 'shell'});
|
||||
createCodeEditor(document.querySelector<HTMLTextAreaElement>('#content')!);
|
||||
}
|
||||
|
||||
function initRepoSettingsBranches() {
|
||||
|
||||
Reference in New Issue
Block a user