theme.ts 8.6 KB

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