theme.ts 8.8 KB

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