theme.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. '&light.cm-editor': {
  85. colorScheme: 'light',
  86. },
  87. '&dark.cm-editor': {
  88. colorScheme: 'dark',
  89. },
  90. '.cm-content': {
  91. fontSize: 'var(--font-size)',
  92. fontFamily: 'var(--source-font-family)',
  93. lineHeight: 'var(--line-height)',
  94. },
  95. '.cm-cursor-primary': {
  96. fontSize: 'var(--font-size)',
  97. fontFamily: 'var(--source-font-family)',
  98. lineHeight: 'var(--line-height)',
  99. },
  100. '.cm-gutters': {
  101. fontSize: 'var(--font-size)',
  102. lineHeight: 'var(--line-height)',
  103. },
  104. '.cm-tooltip': {
  105. // NOTE: fontFamily is not set here, as most tooltips use the UI font
  106. fontSize: 'var(--font-size)',
  107. },
  108. '.cm-panel': {
  109. fontSize: 'var(--font-size)',
  110. },
  111. '.cm-foldGutter .cm-gutterElement > span': {
  112. height: 'calc(var(--font-size) * var(--line-height))',
  113. },
  114. '.cm-lineNumbers': {
  115. fontFamily: 'var(--source-font-family)',
  116. },
  117. // double the specificity to override the underline squiggle
  118. '.cm-lintRange.cm-lintRange': {
  119. backgroundImage: 'none',
  120. },
  121. // use a background color for lint error ranges
  122. '.cm-lintRange-error': {
  123. padding: 'var(--half-leading, 0) 0',
  124. background: 'rgba(255, 0, 0, 0.2)',
  125. // avoid highlighting nested error ranges
  126. '& .cm-lintRange-error': {
  127. background: 'none',
  128. },
  129. },
  130. '.cm-specialChar': {
  131. color: 'red',
  132. backgroundColor: 'rgba(255, 0, 0, 0.1)',
  133. },
  134. '.cm-widgetBuffer': {
  135. height: '1.3em',
  136. },
  137. '.cm-snippetFieldPosition': {
  138. display: 'inline-block',
  139. height: '1.3em',
  140. },
  141. // style the gutter fold button on hover
  142. '&dark .cm-foldGutter .cm-gutterElement > span:hover': {
  143. boxShadow: '0 1px 1px rgba(255, 255, 255, 0.2)',
  144. backgroundColor: 'rgba(255, 255, 255, 0.1)',
  145. },
  146. '&light .cm-foldGutter .cm-gutterElement > span:hover': {
  147. borderColor: 'rgba(0, 0, 0, 0.3)',
  148. boxShadow: '0 1px 1px rgba(255, 255, 255, 0.7)',
  149. backgroundColor: 'rgba(255, 255, 255, 0.2)',
  150. },
  151. '.cm-diagnosticSource': {
  152. display: 'none',
  153. },
  154. '.ol-cm-diagnostic-actions': {
  155. marginTop: '4px',
  156. },
  157. '.cm-diagnostic:last-of-type .ol-cm-diagnostic-actions': {
  158. marginBottom: '4px',
  159. },
  160. '.cm-vim-panel input': {
  161. color: 'inherit',
  162. },
  163. })
  164. /**
  165. * Theme styles that don't depend on settings.
  166. */
  167. // TODO: move some/all of these into baseTheme?
  168. const staticTheme = EditorView.theme({
  169. // make the editor fill the available height
  170. '&': {
  171. height: '100%',
  172. textRendering: 'optimizeSpeed',
  173. fontVariantNumeric: 'slashed-zero',
  174. },
  175. // remove the outline from the focused editor
  176. '&.cm-editor.cm-focused:not(:focus-visible)': {
  177. outline: 'none',
  178. },
  179. // override default styles for the search panel
  180. '.cm-panel.cm-search label': {
  181. display: 'inline-flex',
  182. alignItems: 'center',
  183. fontWeight: 'normal',
  184. },
  185. '.cm-selectionLayer': {
  186. zIndex: -10,
  187. },
  188. // remove the right-hand border from the gutter
  189. // ensure the gutter doesn't shrink
  190. '.cm-gutters': {
  191. borderRight: 'none',
  192. flexShrink: 0,
  193. },
  194. // style the gutter fold button
  195. // TODO: add a class to this element for easier theming
  196. '.cm-foldGutter .cm-gutterElement > span': {
  197. border: '1px solid transparent',
  198. borderRadius: '3px',
  199. display: 'inline-flex',
  200. flexDirection: 'column',
  201. justifyContent: 'center',
  202. color: 'rgba(109, 109, 109, 0.7)',
  203. },
  204. // reduce the padding around line numbers
  205. '.cm-lineNumbers .cm-gutterElement': {
  206. padding: '0',
  207. userSelect: 'none',
  208. },
  209. // make cursor visible with reduced opacity when the editor is not focused
  210. '&:not(.cm-focused) > .cm-scroller > .cm-cursorLayer .cm-cursor': {
  211. display: 'block',
  212. opacity: 0.2,
  213. },
  214. // make the cursor wider, and use the themed color
  215. '.cm-cursor, .cm-dropCursor': {
  216. borderWidth: '2px',
  217. marginLeft: '-1px', // half the border width
  218. borderLeftColor: 'inherit',
  219. },
  220. // remove border from hover tooltips (e.g. cursor highlights)
  221. '.cm-tooltip-hover': {
  222. border: 'none',
  223. },
  224. // use the same style as Ace for snippet fields
  225. '.cm-snippetField': {
  226. background: 'rgba(194, 193, 208, 0.09)',
  227. border: '1px dotted rgba(211, 208, 235, 0.62)',
  228. },
  229. // style the fold placeholder
  230. '.cm-foldPlaceholder': {
  231. boxSizing: 'border-box',
  232. display: 'inline-block',
  233. height: '11px',
  234. width: '1.8em',
  235. marginTop: '-2px',
  236. verticalAlign: 'middle',
  237. backgroundImage:
  238. 'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII="),url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=")',
  239. backgroundRepeat: 'no-repeat, repeat-x',
  240. backgroundPosition: 'center center, top left',
  241. color: 'transparent',
  242. border: '1px solid black',
  243. borderRadius: '2px',
  244. },
  245. // align the lint icons with the line numbers
  246. '.cm-gutter-lint .cm-gutterElement': {
  247. padding: '0.3em',
  248. },
  249. // reset the default style for the lint gutter error marker, which uses :before
  250. '.cm-lint-marker-error:before': {
  251. content: 'normal',
  252. },
  253. // set a new icon for the lint gutter error marker
  254. '.cm-lint-marker-error': {
  255. content: svgUrl(
  256. `<circle cx="20" cy="20" r="15" fill="#f87" stroke="#f43" stroke-width="6"/>`
  257. ),
  258. },
  259. // set a new icon for the lint gutter warning marker
  260. '.cm-lint-marker-warning': {
  261. content: svgUrl(
  262. `<path fill="#FCC483" stroke="#DE8014" stroke-width="6" stroke-linejoin="round" d="M20 6L37 35L3 35Z"/>`
  263. ),
  264. },
  265. })
  266. const themeCache = new Map<string, any>()
  267. const loadSelectedTheme = async (editorTheme: string) => {
  268. if (!editorTheme) {
  269. editorTheme = 'textmate' // use the default theme if unset
  270. }
  271. if (!themeCache.has(editorTheme)) {
  272. const themes = getMeta('ol-editorThemes') || []
  273. const legacyThemes = getMeta('ol-legacyEditorThemes') || []
  274. const themeExists =
  275. themes.includes(editorTheme) || legacyThemes.includes(editorTheme)
  276. if (!themeExists) {
  277. editorTheme = 'textmate' // fallback to default if the theme is not found
  278. }
  279. const { theme, highlightStyle, dark } = await import(
  280. /* webpackChunkName: "cm6-theme" */ `../themes/cm6/${editorTheme}.json`
  281. )
  282. // We store these in a cache, so we'll reuse after the first load
  283. const extension = [
  284. // eslint-disable-next-line @overleaf/no-generated-editor-themes
  285. EditorView.theme(theme, { dark }),
  286. // eslint-disable-next-line @overleaf/no-generated-editor-themes
  287. EditorView.theme(highlightStyle, { dark }),
  288. ]
  289. themeCache.set(editorTheme, extension)
  290. }
  291. return themeCache.get(editorTheme)
  292. }