theme.ts 9.1 KB

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