feat(ui): replace Monaco with CodeMirror (#10559)

- Replace the [Monaco Editor](https://microsoft.github.io/monaco-editor/)
with [CodeMirror 6](https://codemirror.net/). This editor is used to
facilitate the 'Add file' and 'Edit file' functionality.
- Rationale:
  - Monaco editor is a great and powerful editor, however for Forgejo's
  purpose it acts more like a small IDE than a code editor and is doing
  too much. In my limited user research the usage of editing files via
  the web UI is largely for small changes that does not need the
  features that Monaco editor provides.
  - Monaco editor has no mobile support, Codemirror is very usable on mobile.
  - Monaco editor pulls in large dependencies (for language support) and
  by replacing it with Codemirror the amount of time that webpack needs
  to build the frontend is reduced by 50% (~30s -> ~15s).
  - The binary of Forgejo (build with `bindata` tag) is reduced by 2MiB.
  - Codemirror is much more lightweight and should be more usable on
  less powerful hardware, most notably the lazy loading is much faster
  as codemirror uses less javascript.
  - Because Codemirror is modular it is much easier to change the
  behavior of the code editor if we wish to.
- Drawbacks:
  - Codemirror is quite modular and as seen in `package.json` and in
  `codeeditor.ts` we have to supply a lot more of its features to have
  feature parity with Monaco editor.
  - Monaco editor has great integrated language support (features that
  an lsp would provide), Codemirror only has such language support to an
  extend.
  - Monaco editor has its famous command palette (known by many as its
  also available in VSCode), this is not available in code mirror.
- Good to note:
  - All features that was added on top of the monaco editor (such as
  dynamically changing language  support depending on the filename)
  still works and the theme is based on the VSCode colors which largely
  resembles the monaco editor.
  - The code editor is still lazy-loaded (this is painfully clear by
  reading how imports are passed around in `codeeditor.ts`).
  - This change was privately tested by a few people, a few bugs were
  found (and fixed) but no major drawbacks were noted for their usage of
  the web editor.
  - There's a "search" button in the top bar, so that search can be used
  on mobile. It is otherwise only accessible via
  <kbd>Ctrl</kbd>+<kbd>f</kbd>.

Co-authored-by: Beowulf <beowulf@beocode.eu>

Co-authored-by: Gusted <postmaster@gusted.xyz>
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/10559
Reviewed-by: Gusted <gusted@noreply.codeberg.org>
Reviewed-by: 0ko <0ko@noreply.codeberg.org>
Co-committed-by: Beowulf <beowulf@beocode.eu>
This commit is contained in:
Beowulf 2026-01-04 23:52:33 +01:00 committed by Gusted
parent 1cecec6536
commit 28e0af23fa
31 changed files with 1665 additions and 325 deletions

View file

@ -1,48 +1,103 @@
.monaco-editor-container,
.editor-loading.is-loading {
width: 100%;
min-height: 200px;
height: 90vh;
height: 200px;
}
.edit.githook .monaco-editor-container {
.edit.githook .codemirror-container {
border: 1px solid var(--color-secondary);
height: 70vh;
}
/* overwrite conflicting styles from fomantic */
.monaco-editor-container .inputarea {
min-height: 0 !important;
margin: 0 !important;
padding: 0 !important;
resize: none !important;
border: none !important;
color: transparent !important;
background-color: transparent !important;
#editor-bar {
display: flex;
justify-content: space-between;
margin-bottom: 1rem;
}
/* these seem unthemeable */
.monaco-scrollable-element > .scrollbar > .slider {
background: var(--color-primary) !important;
}
.monaco-scrollable-element > .scrollbar > .slider:hover {
background: var(--color-primary-dark-1) !important;
}
.monaco-scrollable-element > .scrollbar > .slider:active {
background: var(--color-primary-dark-2) !important;
@media (max-width: 768px) {
#editor-bar {
gap: var(--button-spacing);
.switch {
overflow-x: scroll;
}
}
}
/* fomantic styles destroy this element only visible on IOS, restore it */
.monaco-editor .iPadShowKeyboard {
border: none !important;
width: 58px !important;
min-width: 0 !important;
height: 36px !important;
min-height: 0 !important;
margin: 0 !important;
padding: 0 !important;
position: absolute !important;
resize: none !important;
overflow: hidden !important;
border-radius: var(--border-radius-medium) !important;
.cm-panel.fj-search {
position: absolute;
top: 0;
right: 0;
background-color: var(--color-body);
box-shadow: 0 6px 18px var(--color-shadow);
border-radius: 0.3rem;
display: flex;
flex-direction: column;
gap: 1rem;
.search-input-group {
align-items: center;
background: var(--color-input-background);
border: 1px solid var(--color-input-border);
border-radius: 0.3rem;
display: inline-flex;
width: 100%;
&:focus-within {
border-color: var(--color-primary);
}
input {
background: none !important;
box-shadow: none !important;
border-color: transparent !important;
}
label {
display: inline-flex;
align-items: center;
justify-content: center;
background-color: var(--color-secondary-bg);
border-radius: 50%;
padding: 6px 12px;
height: 2em;
width: 2em;
font-size: 80%;
white-space: pre;
user-select: none;
&:hover {
background-color: var(--color-label-hover-bg);
}
&.focused {
box-shadow:
inset 0 1px 1px rgb(0 0 0 / 8%),
0 0 8px var(--color-accent);
}
&.active {
background-color: var(--color-accent);
}
}
}
.search-hidden-inputs {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
overflow: hidden;
clip-path: inset(50%);
}
.search-section,
.replace-section {
display: flex;
gap: var(--button-spacing);
}
}
@media screen and (max-width: 786px) {
.cm-panel.fj-search {
position: sticky;
box-shadow: none;
}
}

View file

@ -14,28 +14,13 @@ function shouldIgnoreError(err) {
// If the error stack trace does not include the base URL of our script assets, it likely came
// from a browser extension or inline script. Ignore these errors.
if (!err.stack?.includes(assetBaseUrl)) return true;
// Ignore some known internal errors that we are unable to currently fix (eg via Monaco).
const ignorePatterns = [
'/assets/js/monaco.', // https://codeberg.org/forgejo/forgejo/issues/3638 , https://github.com/go-gitea/gitea/issues/30861 , https://github.com/microsoft/monaco-editor/issues/4496
];
for (const pattern of ignorePatterns) {
if (err.stack?.includes(pattern)) return true;
}
return false;
}
const filteredErrors = new Set([
'getModifierState is not a function', // https://github.com/microsoft/monaco-editor/issues/4325
]);
export function showGlobalErrorMessage(msg) {
const pageContent = document.querySelector('.page-content');
if (!pageContent) return;
for (const filteredError of filteredErrors) {
if (msg.includes(filteredError)) return;
}
// compact the message to a data attribute to avoid too many duplicated messages
const msgCompact = msg.replace(/\W/g, '').trim();
let msgDiv = pageContent.querySelector(`.js-global-error[data-global-error-msg-compact="${msgCompact}"]`);

View file

@ -1,191 +0,0 @@
import tinycolor from 'tinycolor2';
import {basename, extname, isObject, isDarkTheme} from '../utils.js';
import {onInputDebounce} from '../utils/dom.js';
const languagesByFilename = {};
const languagesByExt = {};
const baseOptions = {
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: false,
scrollbar: {horizontalScrollbarSize: 6, verticalScrollbarSize: 6},
scrollBeyondLastLine: false,
automaticLayout: true,
};
function getEditorconfig(input) {
try {
return JSON.parse(input.getAttribute('data-editorconfig'));
} catch {
return null;
}
}
function initLanguages(monaco) {
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;
}
}
}
function getLanguage(filename) {
return languagesByFilename[filename] || languagesByExt[extname(filename)] || 'plaintext';
}
function updateEditor(monaco, editor, filename, lineWrapExts) {
editor.updateOptions(getFileBasedOptions(filename, lineWrapExts));
const model = editor.getModel();
const language = model.getLanguageId();
const newLanguage = getLanguage(filename);
if (language !== newLanguage) monaco.editor.setModelLanguage(model, newLanguage);
}
// export editor for customization - https://github.com/go-gitea/gitea/issues/10409
function exportEditor(editor) {
if (!window.codeEditors) window.codeEditors = [];
if (!window.codeEditors.includes(editor)) window.codeEditors.push(editor);
}
export async function createMonaco(textarea, filename, editorOpts) {
const monaco = await import(/* webpackChunkName: "monaco" */'monaco-editor');
initLanguages(monaco);
let {language, ...other} = editorOpts;
if (!language) language = getLanguage(filename);
const container = document.createElement('div');
container.className = 'monaco-editor-container';
textarea.parentNode.append(container);
// 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) => tinycolor(styles.getPropertyValue(name).trim()).toString('hex6');
monaco.editor.defineTheme('gitea', {
base: isDarkTheme() ? 'vs-dark' : 'vs',
inherit: true,
rules: [
{
background: getColor('--color-code-bg'),
},
],
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'),
'progressBar.background': getColor('--color-primary'),
},
});
const editor = monaco.editor.create(container, {
value: textarea.value,
theme: 'gitea',
language,
...other,
});
monaco.editor.addKeybindingRules([
{keybinding: monaco.KeyCode.Enter, command: null}, // disable enter from accepting code completion
]);
const model = editor.getModel();
model.onDidChangeContent(() => {
textarea.value = editor.getValue({preserveBOM: true});
textarea.dispatchEvent(new Event('change')); // seems to be needed for jquery-are-you-sure
});
exportEditor(editor);
const loading = document.querySelector('.editor-loading');
if (loading) loading.remove();
return {monaco, editor};
}
function getFileBasedOptions(filename, lineWrapExts) {
return {
wordWrap: (lineWrapExts || []).includes(extname(filename)) ? 'on' : 'off',
};
}
function togglePreviewDisplay(previewable) {
const previewTab = document.querySelector('a[data-tab="preview"]');
if (!previewTab) return;
if (previewable) {
const newUrl = (previewTab.getAttribute('data-url') || '').replace(/(.*)\/.*/, `$1/markup`);
previewTab.setAttribute('data-url', newUrl);
previewTab.style.display = '';
} else {
previewTab.style.display = 'none';
// If 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('a[data-tab="write"]');
writeTab.click();
}
}
}
export async function createCodeEditor(textarea, filenameInput) {
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 previewable = previewableExts.has(extname(filename));
const editorConfig = getEditorconfig(filenameInput);
togglePreviewDisplay(previewable);
const {monaco, editor} = await createMonaco(textarea, filename, {
...baseOptions,
...getFileBasedOptions(filenameInput.value, lineWrapExts),
...getEditorConfigOptions(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 getEditorConfigOptions(ec) {
if (!isObject(ec)) return {};
const opts = {};
opts.detectIndentation = !('indent_style' in ec) || !('indent_size' in ec);
if ('indent_size' in ec) opts.indentSize = Number(ec.indent_size);
if ('tab_width' in ec) opts.tabSize = Number(ec.tab_width) || opts.indentSize;
if ('max_line_length' in ec) opts.rulers = [Number(ec.max_line_length)];
opts.trimAutoWhitespace = ec.trim_trailing_whitespace === true;
opts.insertSpaces = ec.indent_style === 'space';
opts.useTabStops = ec.indent_style === 'tab';
return opts;
}

View file

@ -0,0 +1,124 @@
import {basename, extname} from '../utils.js';
import {hideElem, onInputDebounce, showElem} from '../utils/dom.js';
import {createCodemirror, type CodemirrorEditor, type EditorOptions} from './codemirror.ts';
import {EditorView} from '@codemirror/view';
import type {LanguageSupport} from '@codemirror/language';
interface EditorConfig {
indent_style: string;
indent_size: string;
}
export class SettableEditorView extends EditorView {
public setValue(value: string) {
// Replace \n with the actual newline character and unescape escaped \n
value = value.replaceAll(/(?<!\\)\\n/g, '\n').replaceAll(/\\\\n/g, '\\n');
this.dispatch({changes: {from: 0, to: this.state.doc.length, insert: value}});
}
}
function getEditorconfig(input: HTMLInputElement): null | EditorConfig {
try {
return JSON.parse(input.getAttribute('data-editorconfig'));
} catch {
return null;
}
}
async function updateEditor(editor: CodemirrorEditor, filename: string, lineWrapExts: string[]) {
const fileOption = getFileBasedOptions(filename, lineWrapExts);
editor.view.dispatch({
effects: editor.compartments.wordWrap.reconfigure(fileOption.wordWrap ? editor.codemirrorView.EditorView.lineWrapping : []),
});
const currentLanguage = editor.compartments.language.get(editor.view.state) as Array<unknown> | LanguageSupport;
const newLanguage = editor.codemirrorLanguage.LanguageDescription.matchFilename(editor.languages, filename);
if (!currentLanguage || (currentLanguage as Array<unknown>).length === 0 || !newLanguage || (currentLanguage as LanguageSupport).language.name.toLowerCase() !== newLanguage.name.toLowerCase()) {
editor.view.dispatch({
effects: editor.compartments.language.reconfigure(newLanguage ? await newLanguage.load() : []),
});
}
}
function getFileBasedOptions(filename: string, lineWrapExts: string[]): Pick<EditorOptions, 'wordWrap'> {
return {
wordWrap: (lineWrapExts || []).includes(extname(filename)),
};
}
function togglePreviewDisplay(previewable: boolean) {
const previewTab = document.querySelector('.item[data-tab="preview"]') as HTMLAnchorElement;
if (!previewTab) return;
if (previewable) {
const newUrl = (previewTab.getAttribute('data-url') || '').replace(/(.*)\/.*/, `$1/markup`);
previewTab.setAttribute('data-url', newUrl);
previewTab.style.display = '';
} else {
previewTab.style.display = 'none';
// If 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('.item[data-tab="write"]') as HTMLAnchorElement;
writeTab.click();
}
}
}
export async function createCodeEditor(textarea: HTMLTextAreaElement, filenameInput: HTMLInputElement): Promise<SettableEditorView> {
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 previewable = previewableExts.has(extname(filename));
const editorConfig = getEditorconfig(filenameInput);
togglePreviewDisplay(previewable);
const editor = await createCodemirror(textarea, filename, {
...getFileBasedOptions(filenameInput.value, lineWrapExts),
...getEditorConfigOptions(editorConfig),
});
filenameInput.addEventListener('input', onInputDebounce(async () => {
const filename = filenameInput.value;
const previewable = previewableExts.has(extname(filename));
togglePreviewDisplay(previewable);
await updateEditor(editor, filename, lineWrapExts);
}));
const searchButton = document.querySelector('#editor-find');
searchButton.addEventListener('click', () => {
const search = editor.codemirrorSearch;
const view = editor.view;
if (search.searchPanelOpen(view.state)) {
search.closeSearchPanel(view);
} else {
search.openSearchPanel(view);
}
});
const writeTab = document.querySelector('#editor-bar .switch .item[data-tab="write"]');
document.querySelector('#editor-bar .switch').addEventListener('click', () => {
if (writeTab.classList.contains('active')) {
showElem(searchButton);
} else {
hideElem(searchButton);
}
});
return Object.setPrototypeOf(editor.view, SettableEditorView.prototype);
}
function getEditorConfigOptions(ec: null | EditorConfig): Pick<EditorOptions, 'indentSize' | 'tabSize' | 'indentStyle'> {
if (ec === null) {
return {indentStyle: 'space'};
}
const opts: ReturnType<typeof getEditorConfigOptions> = {
indentStyle: ec.indent_style,
};
if ('indent_size' in ec) opts.indentSize = Number(ec.indent_size);
if ('tab_width' in ec) opts.tabSize = Number(ec.tab_width) || opts.indentSize;
return opts;
}

View file

@ -0,0 +1,161 @@
import type {LanguageDescription} from '@codemirror/language';
export function languages(codemirrorLanguage: CodeMirrorLanguage): LanguageDescription[] {
return [
codemirrorLanguage.LanguageDescription.of({
name: 'C',
extensions: ['c', 'h', 'ino'],
async load() {
return (await import('@codemirror/lang-cpp')).cpp();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'C++',
alias: ['cpp'],
extensions: ['cpp', 'c++', 'cc', 'cxx', 'hpp', 'h++', 'hh', 'hxx'],
async load() {
return (await import('@codemirror/lang-cpp')).cpp();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'CSS',
extensions: ['css'],
async load() {
return (await import('@codemirror/lang-css')).css();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'Go',
extensions: ['go'],
async load() {
return (await import('@codemirror/lang-go')).go();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'HTML',
alias: ['xhtml'],
extensions: ['html', 'htm', 'handlebars', 'hbs'],
async load() {
return (await import('@codemirror/lang-html')).html();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'Java',
extensions: ['java'],
async load() {
return (await import('@codemirror/lang-java')).java();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'JavaScript',
alias: ['ecmascript', 'js', 'node'],
extensions: ['js', 'mjs', 'cjs'],
async load() {
return (await import('@codemirror/lang-javascript')).javascript();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'JSON',
alias: ['json5'],
extensions: ['json', 'map'],
async load() {
return (await import('@codemirror/lang-json')).json();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'JSX',
extensions: ['jsx'],
async load() {
return (await import('@codemirror/lang-javascript')).javascript({jsx: true});
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'LESS',
extensions: ['less'],
async load() {
return (await import('@codemirror/lang-less')).less();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'Liquid',
extensions: ['liquid'],
async load() {
return (await import('@codemirror/lang-liquid')).liquid();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'Markdown',
extensions: ['md', 'markdown', 'mkd'],
async load() {
return (await import('@codemirror/lang-markdown')).markdown();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'PHP',
extensions: ['php', 'php3', 'php4', 'php5', 'php7', 'phtml'],
async load() {
return (await import('@codemirror/lang-php')).php();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'Python',
extensions: ['BUILD', 'bzl', 'py', 'pyw'],
filename: /^(BUCK|BUILD)$/,
async load() {
return (await import('@codemirror/lang-python')).python();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'Rust',
extensions: ['rs'],
async load() {
return (await import('@codemirror/lang-rust')).rust();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'Sass',
extensions: ['sass'],
async load() {
return (await import('@codemirror/lang-sass')).sass({indented: true});
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'SCSS',
extensions: ['scss'],
async load() {
return (await import('@codemirror/lang-sass')).sass();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'TSX',
extensions: ['tsx'],
async load() {
return (await import('@codemirror/lang-javascript')).javascript({jsx: true, typescript: true});
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'TypeScript',
alias: ['ts'],
extensions: ['ts', 'mts', 'cts'],
async load() {
return (await import('@codemirror/lang-javascript')).javascript({typescript: true});
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'XML',
alias: ['rss', 'wsdl', 'xsd'],
extensions: ['xml', 'xsl', 'xsd', 'svg'],
async load() {
return (await import('@codemirror/lang-xml')).xml();
},
}),
codemirrorLanguage.LanguageDescription.of({
name: 'YAML',
alias: ['yml'],
extensions: ['yaml', 'yml'],
async load() {
return (await import('@codemirror/lang-yaml')).yaml();
},
}),
];
}

View file

@ -0,0 +1,240 @@
// Copyright 2025 The Forgejo Authors. All rights reserved.
// SPDX-License-Identifier: GPL-3.0-or-later
import type {SearchQuery} from '@codemirror/search';
import type {EditorView, Panel, ViewUpdate} from '@codemirror/view';
import {svg} from '../svg.js';
class SearchPanel implements Panel {
searchField: HTMLInputElement;
replaceField: HTMLInputElement;
caseField: HTMLInputElement;
caseLabel: HTMLLabelElement;
reField: HTMLInputElement;
reLabel: HTMLLabelElement;
wordField: HTMLInputElement;
wordLabel: HTMLLabelElement;
dom: HTMLElement;
query: SearchQuery;
search: CodeMirrorSearch;
constructor(readonly codemirrorSearch: CodeMirrorSearch, readonly view: EditorView) {
this.search = codemirrorSearch;
const container = view.dom.parentElement;
const query = (this.query = this.search.getSearchQuery(view.state));
this.commit = this.commit.bind(this);
this.searchField = document.createElement('input');
this.searchField.value = query.search;
this.searchField.name = 'search';
const searchText = container.getAttribute('data-search-text');
this.searchField.placeholder = searchText;
this.searchField.ariaLabel = searchText;
this.searchField.classList.add('cm-textfield');
this.searchField.setAttribute('main-field', 'true');
this.searchField.addEventListener('keyup', this.commit);
this.searchField.addEventListener('change', this.commit);
this.caseField = document.createElement('input');
this.caseField.checked = query.caseSensitive;
this.caseField.type = 'checkbox';
this.caseField.name = 'case_sensitive';
this.caseField.id = 'search_case_sensitive';
this.caseField.addEventListener('change', this.commit);
this.caseField.addEventListener('focus', () => this.updateLabels());
this.caseField.addEventListener('blur', () => this.updateLabels());
this.caseLabel = document.createElement('label');
this.caseLabel.setAttribute('for', 'search_case_sensitive');
const caseText = container.getAttribute('data-toggle-case-text');
this.caseLabel.ariaLabel = caseText;
this.caseLabel.setAttribute('data-tooltip-content', caseText);
this.caseLabel.textContent = 'aA';
this.reField = document.createElement('input');
this.reField.checked = query.regexp;
this.reField.type = 'checkbox';
this.reField.name = 'regexp';
this.reField.id = 'search_regexp';
this.reField.addEventListener('change', this.commit);
this.reField.addEventListener('focus', () => this.updateLabels());
this.reField.addEventListener('blur', () => this.updateLabels());
this.reLabel = document.createElement('label');
this.reLabel.setAttribute('for', 'search_regexp');
const reText = container.getAttribute('data-toggle-regex-text');
this.reLabel.ariaLabel = reText;
this.reLabel.setAttribute('data-tooltip-content', reText);
this.reLabel.textContent = '[.+]';
this.wordField = document.createElement('input');
this.wordField.checked = query.wholeWord;
this.wordField.type = 'checkbox';
this.wordField.name = 'by_word';
this.wordField.id = 'search_by_word';
this.wordField.addEventListener('change', this.commit);
this.wordField.addEventListener('focus', () => this.updateLabels());
this.wordField.addEventListener('blur', () => this.updateLabels());
this.wordLabel = document.createElement('label');
this.wordLabel.setAttribute('for', 'search_by_word');
const wholeWordText = container.getAttribute('data-toggle-whole-word-text');
this.wordLabel.ariaLabel = wholeWordText;
this.wordLabel.setAttribute('data-tooltip-content', wholeWordText);
this.wordLabel.textContent = 'W';
this.updateLabels();
const searchFieldContainer = document.createElement('span');
searchFieldContainer.classList.add('search-input-group');
searchFieldContainer.replaceChildren(this.searchField, this.caseLabel, this.reLabel, this.wordLabel);
const hiddenInputs = document.createElement('div');
hiddenInputs.classList.add('search-hidden-inputs');
hiddenInputs.replaceChildren(this.caseField, this.reField, this.wordField);
const prevSearch = document.createElement('button');
prevSearch.classList.add('secondary', 'button');
prevSearch.type = 'button';
const findPrevText = container.getAttribute('data-find-prev-text');
prevSearch.ariaLabel = findPrevText;
prevSearch.addEventListener('click', () => {
this.search.findPrevious(view);
});
prevSearch.innerHTML = svg('octicon-arrow-up');
const nextSearch = document.createElement('button');
nextSearch.classList.add('secondary', 'button');
nextSearch.type = 'button';
const findNextText = container.getAttribute('data-find-next-text');
nextSearch.ariaLabel = findNextText;
nextSearch.addEventListener('click', () => {
this.search.findNext(view);
});
nextSearch.innerHTML = svg('octicon-arrow-down');
const searchSection = document.createElement('div');
searchSection.classList.add('search-section');
searchSection.replaceChildren(searchFieldContainer, hiddenInputs, prevSearch, nextSearch);
this.replaceField = document.createElement('input');
this.replaceField.value = query.replace;
this.replaceField.name = 'replace';
const replaceText = container.getAttribute('data-replace-text');
this.replaceField.placeholder = replaceText;
this.replaceField.ariaLabel = replaceText;
this.replaceField.classList.add('cm-textfield');
this.replaceField.addEventListener('keyup', this.commit);
this.replaceField.addEventListener('change', this.commit);
const replaceButton = document.createElement('button');
replaceButton.classList.add('secondary', 'button');
replaceButton.type = 'button';
replaceButton.addEventListener('click', () => {
this.search.replaceNext(view);
});
replaceButton.textContent = replaceText;
const replaceAllButton = document.createElement('button');
replaceAllButton.classList.add('secondary', 'button');
replaceAllButton.type = 'button';
replaceAllButton.addEventListener('click', () => {
this.search.replaceAll(view);
});
const replaceAllText = container.getAttribute('data-replace-all-text');
replaceAllButton.textContent = replaceAllText;
const replaceSection = document.createElement('div');
replaceSection.classList.add('replace-section');
replaceSection.replaceChildren(this.replaceField, replaceButton, replaceAllButton);
this.dom = document.createElement('div');
this.dom.classList.add('fj-search');
this.dom.addEventListener('keydown', (e: KeyboardEvent) => this.keydown(e));
this.dom.replaceChildren(searchSection, replaceSection);
}
commit() {
this.updateLabels();
const query = new this.search.SearchQuery({
search: this.searchField.value,
caseSensitive: this.caseField.checked,
regexp: this.reField.checked,
wholeWord: this.wordField.checked,
replace: this.replaceField.value,
});
if (!query.eq(this.query)) {
this.query = query;
this.view.dispatch({effects: this.search.setSearchQuery.of(query)});
// Set the new search query and reset the selection
const anchor = this.view.state.selection.main.anchor;
this.view.dispatch({
selection: {anchor},
effects: this.search.setSearchQuery.of(query),
});
}
}
keydown(e: KeyboardEvent) {
if (e.key === 'Enter' && e.target === this.searchField) {
e.preventDefault();
if (e.shiftKey) {
this.search.findPrevious(this.view);
} else {
this.search.findNext(this.view);
}
} else if (e.key === 'Enter' && e.target === this.replaceField) {
e.preventDefault();
this.search.replaceNext(this.view);
}
}
update(update: ViewUpdate) {
for (const tr of update.transactions) for (const effect of tr.effects) {
if (effect.is(this.search.setSearchQuery) && !effect.value.eq(this.query)) {
this.setQuery(effect.value);
}
}
}
setQuery(query: SearchQuery) {
this.query = query;
this.searchField.value = query.search;
this.replaceField.value = query.replace;
this.caseField.checked = query.caseSensitive;
this.reField.checked = query.regexp;
this.wordField.checked = query.wholeWord;
this.updateLabels();
}
updateLabels() {
this.caseLabel.classList.toggle('active', this.caseField.checked);
this.caseLabel.classList.toggle('focused', this.caseField === document.activeElement);
this.reLabel.classList.toggle('active', this.reField.checked);
this.reLabel.classList.toggle('focused', this.reField === document.activeElement);
this.wordLabel.classList.toggle('active', this.wordField.checked);
this.wordLabel.classList.toggle('focused', this.wordField === document.activeElement);
}
mount() {
this.searchField.select();
}
get pos() {
return 80;
}
get top() {
return true;
}
}
export function searchPanel(
codemirrorSearch: CodeMirrorSearch,
): (view: EditorView) => Panel {
return (view) => {
return new SearchPanel(codemirrorSearch, view);
};
}

View file

@ -0,0 +1,218 @@
import {isDarkTheme} from '../utils.js';
import {languages} from './codemirror-lang.ts';
import type {LanguageDescription} from '@codemirror/language';
import type {Compartment} from '@codemirror/state';
import type {EditorView, ViewUpdate} from '@codemirror/view';
import {searchPanel} from './codemirror-search.ts';
// Export editor for customization - https://github.com/go-gitea/gitea/issues/10409
function exportEditor(editor: EditorView) {
if (!window.codeEditors) window.codeEditors = new Set<EditorView>();
window.codeEditors.add(editor);
}
export interface EditorOptions {
indentSize?: number;
tabSize?: number;
wordWrap: boolean;
indentStyle: string;
onContentChange?: (update: ViewUpdate) => void;
}
export interface CodemirrorEditor {
codemirrorView: CodeMirrorView;
codemirrorLanguage: CodeMirrorLanguage;
codemirrorState: CodeMirrorState;
codemirrorSearch: CodeMirrorSearch;
view: EditorView;
languages: LanguageDescription[];
compartments: {
wordWrap: Compartment;
language: Compartment;
tabSize: Compartment;
};
}
export async function createCodemirror(
textarea: HTMLTextAreaElement,
filename: string,
editorOpts: EditorOptions,
): Promise<CodemirrorEditor> {
const codemirrorView = await import(/* webpackChunkName: "codemirror" */ '@codemirror/view');
const codemirrorCommands = await import(/* webpackChunkName: "codemirror" */ '@codemirror/commands');
const codemirrorState = await import(/* webpackChunkName: "codemirror" */ '@codemirror/state');
const codemirrorSearch = await import(/* webpackChunkName: "codemirror" */ '@codemirror/search');
const codemirrorLanguage = await import(/* webpackChunkName: "codemirror" */ '@codemirror/language');
const codemirrorAutocomplete = await import(/* webpackChunkName: "codemirror" */ '@codemirror/autocomplete');
const {tags: t} = await import(/* webpackChunkName: "codemirror" */ '@lezer/highlight');
const languageDescriptions = languages(codemirrorLanguage);
const code = codemirrorLanguage.LanguageDescription.matchFilename(
languageDescriptions,
filename,
);
const onContentChange = editorOpts.onContentChange || ((update) => {
if (update.docChanged) {
textarea.value = update.state.doc.toString();
// Make jquery-are-you-sure happy.
textarea.dispatchEvent(new Event('change'));
}
});
const darkTheme = isDarkTheme();
const theme = codemirrorView.EditorView.theme(
{
'&': {
color: 'var(--color-text)',
backgroundColor: 'var(--color-code-bg)',
maxHeight: '90vh',
},
'.cm-content, .cm-gutter': {
minHeight: '200px',
},
'.cm-scroller': {
overflow: 'auto',
},
'.cm-content': {
caretColor: 'var(--color-caret)',
fontFamily: 'var(--fonts-monospace)',
fontSize: '14px',
},
'.cm-cursor, .cm-dropCursor': {
borederLeftCursor: 'var(--color-caret)',
},
'&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground':
{
backgroundColor: 'var(--color-primary-light-3)',
},
'.cm-panels': {
backgroundColor: 'var(--color-body)',
borderColor: 'var(--color-secondary)',
},
'.cm-activeLine, .cm-activeLineGutter': {
backgroundColor: '#6699ff0b',
},
'.cm-gutters': {
backgroundColor: 'var(--color-code-bg)',
color: 'var(--color-secondary-dark-6)',
},
'.cm-line ::selection, .cm-line::selection': {
color: 'inherit !important',
},
'.cm-searchMatch': {
backgroundColor: '#72a1ff59',
outline: `1px solid #ffffff0f`,
},
'.cm-tooltip.cm-tooltip-autocomplete > ul > li': {
padding: '0.5em 0.5em',
},
},
{dark: isDarkTheme()},
);
const highlightStyle = codemirrorLanguage.HighlightStyle.define([
{
tag: [t.keyword, t.operatorKeyword, t.modifier, t.color, t.constant(t.name), t.standard(t.name), t.standard(t.tagName), t.special(t.brace), t.atom, t.bool, t.special(t.variableName)],
color: darkTheme ? '#569cd6' : '#0064ff',
},
{tag: [t.controlKeyword, t.moduleKeyword], color: darkTheme ? '#c586c0' : '#af00db'},
{
tag: [t.name, t.deleted, t.character, t.macroName, t.propertyName, t.variableName, t.labelName, t.definition(t.name)],
color: darkTheme ? '#9cdcfe' : '#383a42',
},
{
tag: [t.typeName, t.className, t.tagName, t.number, t.changed, t.annotation, t.self, t.namespace],
color: darkTheme ? '#4ec9b0' : '#267f99',
},
{
tag: [t.function(t.variableName), t.function(t.propertyName)],
color: darkTheme ? '#dcdcaa' : '#795e26',
},
{tag: [t.number], color: darkTheme ? '#b5cea8' : '#098658'},
{
tag: [t.operator, t.punctuation, t.separator, t.url, t.escape, t.regexp],
color: darkTheme ? '#d4d4d4' : '#383a42',
},
{tag: [t.regexp], color: darkTheme ? '#d16969' : '#af00db'},
{
tag: [t.special(t.string), t.processingInstruction, t.string, t.inserted],
color: darkTheme ? '#ce9178' : '#a31515',
},
{tag: [t.meta, t.comment], color: darkTheme ? '#6a9955' : '#6b6b6b'},
{tag: t.invalid, color: darkTheme ? '#ff0000' : '#e51400'},
{tag: t.strong, fontWeight: 'bold'},
{tag: t.emphasis, fontStyle: 'italic'},
{tag: t.strikethrough, textDecoration: 'line-through'},
{tag: t.link, color: darkTheme ? '#6a9955' : '#006ab1', textDecoration: 'underline'},
]);
const container = textarea.parentNode.querySelector('.codemirror-container');
const wordWrap = new codemirrorState.Compartment();
const language = new codemirrorState.Compartment();
const tabSize = new codemirrorState.Compartment();
const view = new codemirrorView.EditorView({
doc: textarea.value,
parent: container,
extensions: [
codemirrorView.lineNumbers(),
codemirrorLanguage.foldGutter(),
codemirrorView.highlightActiveLineGutter(),
codemirrorView.highlightSpecialChars(),
codemirrorView.highlightActiveLine(),
codemirrorView.drawSelection(),
codemirrorView.dropCursor(),
codemirrorSearch.search({createPanel: searchPanel(codemirrorSearch)}),
codemirrorView.keymap.of([
...codemirrorAutocomplete.closeBracketsKeymap,
...codemirrorCommands.defaultKeymap,
...codemirrorCommands.historyKeymap,
// If no search panel, then disable the search keymap
...(document.getElementById('editor-find') ? codemirrorSearch.searchKeymap : []),
...codemirrorLanguage.foldKeymap,
...codemirrorAutocomplete.completionKeymap,
codemirrorCommands.indentWithTab,
]),
codemirrorState.EditorState.allowMultipleSelections.of(true),
codemirrorLanguage.indentOnInput(),
codemirrorLanguage.syntaxHighlighting(highlightStyle),
codemirrorLanguage.bracketMatching(),
codemirrorLanguage.indentUnit.of(
editorOpts.indentStyle === 'tab' ?
'\t' :
' '.repeat(editorOpts.indentSize || 2),
),
codemirrorAutocomplete.closeBrackets(),
codemirrorAutocomplete.autocompletion(),
codemirrorCommands.history(),
tabSize.of(
codemirrorState.EditorState.tabSize.of(editorOpts.tabSize || 4),
),
wordWrap.of(
editorOpts.wordWrap ? codemirrorView.EditorView.lineWrapping : [],
),
language.of(code ? await code.load() : []),
codemirrorView.EditorView.updateListener.of(onContentChange),
theme,
],
});
exportEditor(view);
container.querySelector('.editor-loading')?.remove();
return {
codemirrorView,
codemirrorState,
codemirrorLanguage,
codemirrorSearch,
view,
languages: languageDescriptions,
compartments: {
tabSize,
wordWrap,
language,
},
};
}

View file

@ -1,6 +1,6 @@
import $ from 'jquery';
import {htmlEscape} from 'escape-goat';
import {createCodeEditor} from './codeeditor.js';
import {createCodeEditor} from './codeeditor.ts';
import {hideElem, showElem, createElementFromHTML} from '../utils/dom.js';
import {initMarkupContent} from '../markup/content.js';
import {attachRefIssueContextPopup} from './contextpopup.js';
@ -9,7 +9,7 @@ import {initTab} from '../modules/tab.ts';
import {showModal} from '../modules/modal.ts';
function initEditPreviewTab($form) {
const $tabMenu = $form.find('.tabular.menu');
const $tabMenu = $form.find('.switch');
initTab($tabMenu[0]);
const $previewTab = $tabMenu.find(
`.item[data-tab="${$tabMenu.data('preview')}"]`,

View file

@ -2,7 +2,6 @@ import {vi} from 'vitest';
import {issueTitleHTML} from './repo-issue.js';
// monaco-editor does not have any exports fields, which trips up vitest
vi.mock('./comp/ComboMarkdownEditor.js', () => ({}));
// jQuery is missing
vi.mock('./common-global.js', () => ({}));

View file

@ -1,8 +1,8 @@
import $ from 'jquery';
import {minimatch} from 'minimatch';
import {createMonaco} from './codeeditor.js';
import {onInputDebounce, toggleElem} from '../utils/dom.js';
import {POST} from '../modules/fetch.js';
import {createCodemirror} from './codemirror.ts';
const {appSubUrl} = window.config;
@ -71,7 +71,7 @@ export function initRepoSettingSearchTeamBox() {
export function initRepoSettingGitHook() {
if (!$('.edit.githook').length) return;
const filename = document.querySelector('.hook-filename').textContent;
const _promise = createMonaco($('#content')[0], filename, {language: 'shell'});
const _promise = createCodemirror($('#content')[0], filename, {language: 'shell'});
}
export function initRepoSettingBranches() {

3
web_src/js/globals.d.ts vendored Normal file
View file

@ -0,0 +1,3 @@
interface Window {
codeEditors: Set<import('codemirror').EditorView>;
}

View file

@ -5,6 +5,8 @@ import giteaDoubleChevronRight from '../../public/assets/img/svg/gitea-double-ch
import giteaEmptyCheckbox from '../../public/assets/img/svg/gitea-empty-checkbox.svg';
import giteaExclamation from '../../public/assets/img/svg/gitea-exclamation.svg';
import octiconArchive from '../../public/assets/img/svg/octicon-archive.svg';
import octiconArrowDown from '../../public/assets/img/svg/octicon-arrow-down.svg';
import octiconArrowUp from '../../public/assets/img/svg/octicon-arrow-up.svg';
import octiconArrowSwitch from '../../public/assets/img/svg/octicon-arrow-switch.svg';
import octiconBlocked from '../../public/assets/img/svg/octicon-blocked.svg';
import octiconBold from '../../public/assets/img/svg/octicon-bold.svg';
@ -81,7 +83,9 @@ const svgs = {
'gitea-empty-checkbox': giteaEmptyCheckbox,
'gitea-exclamation': giteaExclamation,
'octicon-archive': octiconArchive,
'octicon-arrow-down': octiconArrowDown,
'octicon-arrow-switch': octiconArrowSwitch,
'octicon-arrow-up': octiconArrowUp,
'octicon-blocked': octiconBlocked,
'octicon-bold': octiconBold,
'octicon-check': octiconCheck,

View file

@ -8,3 +8,8 @@ declare module '*.vue' {
import Vue from 'vue';
export default Vue;
}
type CodeMirrorLanguage = typeof import('@codemirror/language');
type CodeMirrorSearch = typeof import('@codemirror/search');
type CodeMirrorState = typeof import('@codemirror/state');
type CodeMirrorView = typeof import('@codemirror/view');