theme.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import { EditorView } from '@codemirror/view'
  2. import { Annotation, Compartment, TransactionSpec } from '@codemirror/state'
  3. import { syntaxHighlighting } from '@codemirror/language'
  4. import { classHighlighter } from './class-highlighter'
  5. import classNames from 'classnames'
  6. import { FontFamily, LineHeight, userStyles } from '@/shared/utils/styles'
  7. import { ActiveOverallTheme } from '@/shared/hooks/use-active-overall-theme'
  8. import { ThemeCache } from '../utils/theme-cache'
  9. import getMeta from '@/utils/meta'
  10. const optionsThemeConf = new Compartment()
  11. const selectedThemeConf = new Compartment()
  12. export const themeOptionsChange = Annotation.define<boolean>()
  13. type Options = {
  14. fontSize: number
  15. fontFamily: FontFamily
  16. lineHeight: LineHeight
  17. activeOverallTheme: ActiveOverallTheme
  18. }
  19. export const theme = (options: Options) => [
  20. baseTheme,
  21. staticTheme,
  22. /**
  23. * Syntax highlighting, using a highlighter which maps tags to class names.
  24. */
  25. syntaxHighlighting(classHighlighter),
  26. optionsThemeConf.of(createThemeFromOptions(options)),
  27. selectedThemeConf.of([]),
  28. ]
  29. export const setOptionsTheme = (options: Options): TransactionSpec => {
  30. return {
  31. effects: optionsThemeConf.reconfigure(createThemeFromOptions(options)),
  32. annotations: themeOptionsChange.of(true),
  33. }
  34. }
  35. export const setEditorTheme = async (
  36. editorTheme: string
  37. ): Promise<TransactionSpec> => {
  38. const theme = await loadSelectedTheme(editorTheme)
  39. return {
  40. effects: selectedThemeConf.reconfigure(theme),
  41. }
  42. }
  43. const svgUrl = (content: string) =>
  44. `url('data:image/svg+xml,${encodeURIComponent(
  45. `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">${content}</svg>`
  46. )}')`
  47. const tooltipThemeCache = new ThemeCache()
  48. const createThemeFromOptions = ({
  49. fontSize = 12,
  50. fontFamily = 'monaco',
  51. lineHeight = 'normal',
  52. activeOverallTheme = 'dark',
  53. }: Options) => {
  54. // Theme styles that depend on settings.
  55. const styles = userStyles({ fontSize, fontFamily, lineHeight })
  56. return [
  57. EditorView.editorAttributes.of({
  58. class: classNames(
  59. activeOverallTheme === 'dark'
  60. ? 'overall-theme-dark'
  61. : 'overall-theme-light'
  62. ),
  63. style: Object.entries({
  64. '--font-size': styles.fontSize,
  65. '--source-font-family': styles.fontFamily,
  66. '--line-height': styles.lineHeight,
  67. })
  68. .map(([key, value]) => `${key}: ${value}`)
  69. .join(';'),
  70. }),
  71. tooltipThemeCache.get({
  72. '.cm-tooltip': {
  73. '--font-size': styles.fontSize,
  74. '--source-font-family': styles.fontFamily,
  75. '--line-height': styles.lineHeight,
  76. },
  77. }),
  78. ]
  79. }
  80. /**
  81. * Base styles that can have &dark and &light variants
  82. */
  83. const baseTheme = EditorView.baseTheme({
  84. '.cm-content': {
  85. fontSize: 'var(--font-size)',
  86. fontFamily: 'var(--source-font-family)',
  87. lineHeight: 'var(--line-height)',
  88. },
  89. '.cm-cursor-primary': {
  90. fontSize: 'var(--font-size)',
  91. fontFamily: 'var(--source-font-family)',
  92. lineHeight: 'var(--line-height)',
  93. },
  94. '.cm-gutters': {
  95. fontSize: 'var(--font-size)',
  96. lineHeight: 'var(--line-height)',
  97. },
  98. '.cm-tooltip': {
  99. // NOTE: fontFamily is not set here, as most tooltips use the UI font
  100. fontSize: 'var(--font-size)',
  101. },
  102. '.cm-panel': {
  103. fontSize: 'var(--font-size)',
  104. },
  105. '.cm-foldGutter .cm-gutterElement > span': {
  106. height: 'calc(var(--font-size) * var(--line-height))',
  107. },
  108. '.cm-lineNumbers': {
  109. fontFamily: 'var(--source-font-family)',
  110. },
  111. // double the specificity to override the underline squiggle
  112. '.cm-lintRange.cm-lintRange': {
  113. backgroundImage: 'none',
  114. },
  115. // use a background color for lint error ranges
  116. '.cm-lintRange-error': {
  117. padding: 'var(--half-leading, 0) 0',
  118. background: 'rgba(255, 0, 0, 0.2)',
  119. // avoid highlighting nested error ranges
  120. '& .cm-lintRange-error': {
  121. background: 'none',
  122. },
  123. },
  124. '.cm-specialChar': {
  125. color: 'red',
  126. backgroundColor: 'rgba(255, 0, 0, 0.1)',
  127. },
  128. '.cm-widgetBuffer': {
  129. height: '1.3em',
  130. },
  131. '.cm-snippetFieldPosition': {
  132. display: 'inline-block',
  133. height: '1.3em',
  134. },
  135. // style the gutter fold button on hover
  136. '&dark .cm-foldGutter .cm-gutterElement > span:hover': {
  137. boxShadow: '0 1px 1px rgba(255, 255, 255, 0.2)',
  138. backgroundColor: 'rgba(255, 255, 255, 0.1)',
  139. },
  140. '&light .cm-foldGutter .cm-gutterElement > span:hover': {
  141. borderColor: 'rgba(0, 0, 0, 0.3)',
  142. boxShadow: '0 1px 1px rgba(255, 255, 255, 0.7)',
  143. backgroundColor: 'rgba(255, 255, 255, 0.2)',
  144. },
  145. '.cm-diagnosticSource': {
  146. display: 'none',
  147. },
  148. '.ol-cm-diagnostic-actions': {
  149. marginTop: '4px',
  150. },
  151. '.cm-diagnostic:last-of-type .ol-cm-diagnostic-actions': {
  152. marginBottom: '4px',
  153. },
  154. '.cm-vim-panel input': {
  155. color: 'inherit',
  156. },
  157. })
  158. /**
  159. * Theme styles that don't depend on settings.
  160. */
  161. // TODO: move some/all of these into baseTheme?
  162. const staticTheme = EditorView.theme({
  163. // make the editor fill the available height
  164. '&': {
  165. height: '100%',
  166. textRendering: 'optimizeSpeed',
  167. fontVariantNumeric: 'slashed-zero',
  168. },
  169. // remove the outline from the focused editor
  170. '&.cm-editor.cm-focused:not(:focus-visible)': {
  171. outline: 'none',
  172. },
  173. // override default styles for the search panel
  174. '.cm-panel.cm-search label': {
  175. display: 'inline-flex',
  176. alignItems: 'center',
  177. fontWeight: 'normal',
  178. },
  179. '.cm-selectionLayer': {
  180. zIndex: -10,
  181. },
  182. // remove the right-hand border from the gutter
  183. // ensure the gutter doesn't shrink
  184. '.cm-gutters': {
  185. borderRight: 'none',
  186. flexShrink: 0,
  187. },
  188. // style the gutter fold button
  189. // TODO: add a class to this element for easier theming
  190. '.cm-foldGutter .cm-gutterElement > span': {
  191. border: '1px solid transparent',
  192. borderRadius: '3px',
  193. display: 'inline-flex',
  194. flexDirection: 'column',
  195. justifyContent: 'center',
  196. color: 'rgba(109, 109, 109, 0.7)',
  197. },
  198. // reduce the padding around line numbers
  199. '.cm-lineNumbers .cm-gutterElement': {
  200. padding: '0',
  201. userSelect: 'none',
  202. },
  203. // make cursor visible with reduced opacity when the editor is not focused
  204. '&:not(.cm-focused) > .cm-scroller > .cm-cursorLayer .cm-cursor': {
  205. display: 'block',
  206. opacity: 0.2,
  207. },
  208. // make the cursor wider, and use the themed color
  209. '.cm-cursor, .cm-dropCursor': {
  210. borderWidth: '2px',
  211. marginLeft: '-1px', // half the border width
  212. borderLeftColor: 'inherit',
  213. },
  214. // remove border from hover tooltips (e.g. cursor highlights)
  215. '.cm-tooltip-hover': {
  216. border: 'none',
  217. },
  218. // use the same style as Ace for snippet fields
  219. '.cm-snippetField': {
  220. background: 'rgba(194, 193, 208, 0.09)',
  221. border: '1px dotted rgba(211, 208, 235, 0.62)',
  222. },
  223. // style the fold placeholder
  224. '.cm-foldPlaceholder': {
  225. boxSizing: 'border-box',
  226. display: 'inline-block',
  227. height: '11px',
  228. width: '1.8em',
  229. marginTop: '-2px',
  230. verticalAlign: 'middle',
  231. backgroundImage:
  232. 'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII="),url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=")',
  233. backgroundRepeat: 'no-repeat, repeat-x',
  234. backgroundPosition: 'center center, top left',
  235. color: 'transparent',
  236. border: '1px solid black',
  237. borderRadius: '2px',
  238. },
  239. // align the lint icons with the line numbers
  240. '.cm-gutter-lint .cm-gutterElement': {
  241. padding: '0.3em',
  242. },
  243. // reset the default style for the lint gutter error marker, which uses :before
  244. '.cm-lint-marker-error:before': {
  245. content: 'normal',
  246. },
  247. // set a new icon for the lint gutter error marker
  248. '.cm-lint-marker-error': {
  249. content: svgUrl(
  250. `<circle cx="20" cy="20" r="15" fill="#f87" stroke="#f43" stroke-width="6"/>`
  251. ),
  252. },
  253. // set a new icon for the lint gutter warning marker
  254. '.cm-lint-marker-warning': {
  255. content: svgUrl(
  256. `<path fill="#FCC483" stroke="#DE8014" stroke-width="6" stroke-linejoin="round" d="M20 6L37 35L3 35Z"/>`
  257. ),
  258. },
  259. })
  260. const themeCache = new Map<string, any>()
  261. const loadSelectedTheme = async (editorTheme: string) => {
  262. if (!editorTheme) {
  263. editorTheme = 'textmate' // use the default theme if unset
  264. }
  265. if (!themeCache.has(editorTheme)) {
  266. const themes = getMeta('ol-editorThemes') || []
  267. const legacyThemes = getMeta('ol-legacyEditorThemes') || []
  268. const themeExists =
  269. themes.includes(editorTheme) || legacyThemes.includes(editorTheme)
  270. if (!themeExists) {
  271. editorTheme = 'textmate' // fallback to default if the theme is not found
  272. }
  273. const { theme, highlightStyle, dark } = await import(
  274. /* webpackChunkName: "cm6-theme" */ `../themes/cm6/${editorTheme}.json`
  275. )
  276. // We store these in a cache, so we'll reuse after the first load
  277. const extension = [
  278. // eslint-disable-next-line @overleaf/no-generated-editor-themes
  279. EditorView.theme(theme, { dark }),
  280. // eslint-disable-next-line @overleaf/no-generated-editor-themes
  281. EditorView.theme(highlightStyle, { dark }),
  282. ]
  283. themeCache.set(editorTheme, extension)
  284. }
  285. return themeCache.get(editorTheme)
  286. }