gitea源码

codeeditor.ts 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import tinycolor from 'tinycolor2';
  2. import {basename, extname, isObject, isDarkTheme} from '../utils.ts';
  3. import {onInputDebounce} from '../utils/dom.ts';
  4. import type MonacoNamespace from 'monaco-editor';
  5. type Monaco = typeof MonacoNamespace;
  6. type IStandaloneCodeEditor = MonacoNamespace.editor.IStandaloneCodeEditor;
  7. type IEditorOptions = MonacoNamespace.editor.IEditorOptions;
  8. type IGlobalEditorOptions = MonacoNamespace.editor.IGlobalEditorOptions;
  9. type ITextModelUpdateOptions = MonacoNamespace.editor.ITextModelUpdateOptions;
  10. type MonacoOpts = IEditorOptions & IGlobalEditorOptions & ITextModelUpdateOptions;
  11. type EditorConfig = {
  12. indent_style?: 'tab' | 'space',
  13. indent_size?: string | number, // backend emits this as string
  14. tab_width?: string | number, // backend emits this as string
  15. end_of_line?: 'lf' | 'cr' | 'crlf',
  16. charset?: 'latin1' | 'utf-8' | 'utf-8-bom' | 'utf-16be' | 'utf-16le',
  17. trim_trailing_whitespace?: boolean,
  18. insert_final_newline?: boolean,
  19. root?: boolean,
  20. };
  21. const languagesByFilename: Record<string, string> = {};
  22. const languagesByExt: Record<string, string> = {};
  23. const baseOptions: MonacoOpts = {
  24. fontFamily: 'var(--fonts-monospace)',
  25. fontSize: 14, // https://github.com/microsoft/monaco-editor/issues/2242
  26. guides: {bracketPairs: false, indentation: false},
  27. links: false,
  28. minimap: {enabled: false},
  29. occurrencesHighlight: 'off',
  30. overviewRulerLanes: 0,
  31. renderLineHighlight: 'all',
  32. renderLineHighlightOnlyWhenFocus: true,
  33. rulers: [],
  34. scrollbar: {horizontalScrollbarSize: 6, verticalScrollbarSize: 6},
  35. scrollBeyondLastLine: false,
  36. automaticLayout: true,
  37. };
  38. function getEditorconfig(input: HTMLInputElement): EditorConfig | null {
  39. const json = input.getAttribute('data-editorconfig');
  40. if (!json) return null;
  41. try {
  42. return JSON.parse(json);
  43. } catch {
  44. return null;
  45. }
  46. }
  47. function initLanguages(monaco: Monaco): void {
  48. for (const {filenames, extensions, id} of monaco.languages.getLanguages()) {
  49. for (const filename of filenames || []) {
  50. languagesByFilename[filename] = id;
  51. }
  52. for (const extension of extensions || []) {
  53. languagesByExt[extension] = id;
  54. }
  55. if (id === 'typescript') {
  56. monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
  57. // this is needed to suppress error annotations in tsx regarding missing --jsx flag.
  58. jsx: monaco.languages.typescript.JsxEmit.Preserve,
  59. });
  60. }
  61. }
  62. }
  63. function getLanguage(filename: string): string {
  64. return languagesByFilename[filename] || languagesByExt[extname(filename)] || 'plaintext';
  65. }
  66. function updateEditor(monaco: Monaco, editor: IStandaloneCodeEditor, filename: string, lineWrapExts: string[]): void {
  67. editor.updateOptions(getFileBasedOptions(filename, lineWrapExts));
  68. const model = editor.getModel();
  69. if (!model) return;
  70. const language = model.getLanguageId();
  71. const newLanguage = getLanguage(filename);
  72. if (language !== newLanguage) monaco.editor.setModelLanguage(model, newLanguage);
  73. // TODO: Need to update the model uri with the new filename, but there is no easy way currently, see
  74. // https://github.com/microsoft/monaco-editor/discussions/3751
  75. }
  76. // export editor for customization - https://github.com/go-gitea/gitea/issues/10409
  77. function exportEditor(editor: IStandaloneCodeEditor): void {
  78. if (!window.codeEditors) window.codeEditors = [];
  79. if (!window.codeEditors.includes(editor)) window.codeEditors.push(editor);
  80. }
  81. function updateTheme(monaco: Monaco): void {
  82. // https://github.com/microsoft/monaco-editor/issues/2427
  83. // also, monaco can only parse 6-digit hex colors, so we convert the colors to that format
  84. const styles = window.getComputedStyle(document.documentElement);
  85. const getColor = (name: string) => tinycolor(styles.getPropertyValue(name).trim()).toString('hex6');
  86. monaco.editor.defineTheme('gitea', {
  87. base: isDarkTheme() ? 'vs-dark' : 'vs',
  88. inherit: true,
  89. rules: [
  90. {
  91. background: getColor('--color-code-bg'),
  92. token: '',
  93. },
  94. ],
  95. colors: {
  96. 'editor.background': getColor('--color-code-bg'),
  97. 'editor.foreground': getColor('--color-text'),
  98. 'editor.inactiveSelectionBackground': getColor('--color-primary-light-4'),
  99. 'editor.lineHighlightBackground': getColor('--color-editor-line-highlight'),
  100. 'editor.selectionBackground': getColor('--color-primary-light-3'),
  101. 'editor.selectionForeground': getColor('--color-primary-light-3'),
  102. 'editorLineNumber.background': getColor('--color-code-bg'),
  103. 'editorLineNumber.foreground': getColor('--color-secondary-dark-6'),
  104. 'editorWidget.background': getColor('--color-body'),
  105. 'editorWidget.border': getColor('--color-secondary'),
  106. 'input.background': getColor('--color-input-background'),
  107. 'input.border': getColor('--color-input-border'),
  108. 'input.foreground': getColor('--color-input-text'),
  109. 'scrollbar.shadow': getColor('--color-shadow-opaque'),
  110. 'progressBar.background': getColor('--color-primary'),
  111. 'focusBorder': '#0000', // prevent blue border
  112. },
  113. });
  114. }
  115. type CreateMonacoOpts = MonacoOpts & {language?: string};
  116. export async function createMonaco(textarea: HTMLTextAreaElement, filename: string, opts: CreateMonacoOpts): Promise<{monaco: Monaco, editor: IStandaloneCodeEditor}> {
  117. const monaco = await import(/* webpackChunkName: "monaco" */'monaco-editor');
  118. initLanguages(monaco);
  119. let {language, ...other} = opts;
  120. if (!language) language = getLanguage(filename);
  121. const container = document.createElement('div');
  122. container.className = 'monaco-editor-container';
  123. if (!textarea.parentNode) throw new Error('Parent node absent');
  124. textarea.parentNode.append(container);
  125. window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
  126. updateTheme(monaco);
  127. });
  128. updateTheme(monaco);
  129. const model = monaco.editor.createModel(textarea.value, language, monaco.Uri.file(filename));
  130. const editor = monaco.editor.create(container, {
  131. model,
  132. theme: 'gitea',
  133. ...other,
  134. });
  135. monaco.editor.addKeybindingRules([
  136. {keybinding: monaco.KeyCode.Enter, command: null}, // disable enter from accepting code completion
  137. ]);
  138. model.onDidChangeContent(() => {
  139. textarea.value = editor.getValue({
  140. preserveBOM: true,
  141. lineEnding: '',
  142. });
  143. textarea.dispatchEvent(new Event('change')); // seems to be needed for jquery-are-you-sure
  144. });
  145. exportEditor(editor);
  146. const loading = document.querySelector('.editor-loading');
  147. if (loading) loading.remove();
  148. return {monaco, editor};
  149. }
  150. function getFileBasedOptions(filename: string, lineWrapExts: string[]): MonacoOpts {
  151. return {
  152. wordWrap: (lineWrapExts || []).includes(extname(filename)) ? 'on' : 'off',
  153. };
  154. }
  155. function togglePreviewDisplay(previewable: boolean): void {
  156. const previewTab = document.querySelector<HTMLElement>('a[data-tab="preview"]');
  157. if (!previewTab) return;
  158. if (previewable) {
  159. previewTab.style.display = '';
  160. } else {
  161. previewTab.style.display = 'none';
  162. // If the "preview" tab was active, user changes the filename to a non-previewable one,
  163. // then the "preview" tab becomes inactive (hidden), so the "write" tab should become active
  164. if (previewTab.classList.contains('active')) {
  165. const writeTab = document.querySelector<HTMLElement>('a[data-tab="write"]');
  166. writeTab?.click();
  167. }
  168. }
  169. }
  170. export async function createCodeEditor(textarea: HTMLTextAreaElement, filenameInput: HTMLInputElement): Promise<IStandaloneCodeEditor> {
  171. const filename = basename(filenameInput.value);
  172. const previewableExts = new Set((textarea.getAttribute('data-previewable-extensions') || '').split(','));
  173. const lineWrapExts = (textarea.getAttribute('data-line-wrap-extensions') || '').split(',');
  174. const isPreviewable = previewableExts.has(extname(filename));
  175. const editorConfig = getEditorconfig(filenameInput);
  176. togglePreviewDisplay(isPreviewable);
  177. const {monaco, editor} = await createMonaco(textarea, filename, {
  178. ...baseOptions,
  179. ...getFileBasedOptions(filenameInput.value, lineWrapExts),
  180. ...getEditorConfigOptions(editorConfig),
  181. });
  182. filenameInput.addEventListener('input', onInputDebounce(() => {
  183. const filename = filenameInput.value;
  184. const previewable = previewableExts.has(extname(filename));
  185. togglePreviewDisplay(previewable);
  186. updateEditor(monaco, editor, filename, lineWrapExts);
  187. }));
  188. return editor;
  189. }
  190. function getEditorConfigOptions(ec: EditorConfig | null): MonacoOpts {
  191. if (!ec || !isObject(ec)) return {};
  192. const opts: MonacoOpts = {};
  193. opts.detectIndentation = !('indent_style' in ec) || !('indent_size' in ec);
  194. if ('indent_size' in ec) {
  195. opts.indentSize = Number(ec.indent_size);
  196. }
  197. if ('tab_width' in ec) {
  198. opts.tabSize = Number(ec.tab_width) || Number(ec.indent_size);
  199. }
  200. if ('max_line_length' in ec) {
  201. opts.rulers = [Number(ec.max_line_length)];
  202. }
  203. opts.trimAutoWhitespace = ec.trim_trailing_whitespace === true;
  204. opts.insertSpaces = ec.indent_style === 'space';
  205. opts.useTabStops = ec.indent_style === 'tab';
  206. return opts;
  207. }