|
| 1 | +import { ExpressiveCodeEngine, ExpressiveCodeTheme } from '@expressive-code/core'; |
| 2 | +import type ShikiPlugin from 'src/main'; |
| 3 | +import { LoadedLanguage } from 'src/LoadedLanguage'; |
| 4 | +import { bundledLanguages, createHighlighter, type Highlighter } from 'shiki/index.mjs'; |
| 5 | +import { ThemeMapper } from 'src/themes/ThemeMapper'; |
| 6 | +import { pluginShiki } from '@expressive-code/plugin-shiki'; |
| 7 | +import { pluginCollapsibleSections } from '@expressive-code/plugin-collapsible-sections'; |
| 8 | +import { pluginTextMarkers } from '@expressive-code/plugin-text-markers'; |
| 9 | +import { pluginLineNumbers } from '@expressive-code/plugin-line-numbers'; |
| 10 | +import { pluginFrames } from '@expressive-code/plugin-frames'; |
| 11 | +import { getECTheme } from 'src/themes/ECTheme'; |
| 12 | +import { normalizePath, Notice } from 'obsidian'; |
| 13 | +import { DEFAULT_SETTINGS } from 'src/settings/Settings'; |
| 14 | +import { toHtml } from '@expressive-code/core/hast'; |
| 15 | + |
| 16 | +interface CustomTheme { |
| 17 | + name: string; |
| 18 | + displayName: string; |
| 19 | + type: string; |
| 20 | + colors?: Record<string, unknown>[]; |
| 21 | + tokenColors?: Record<string, unknown>[]; |
| 22 | +} |
| 23 | + |
| 24 | +// some languages break obsidian's `registerMarkdownCodeBlockProcessor`, so we blacklist them |
| 25 | +const languageNameBlacklist = new Set(['c++', 'c#', 'f#', 'mermaid']); |
| 26 | + |
| 27 | +export class CodeHighlighter { |
| 28 | + plugin: ShikiPlugin; |
| 29 | + themeMapper: ThemeMapper; |
| 30 | + |
| 31 | + ec!: ExpressiveCodeEngine; |
| 32 | + ecElements!: HTMLElement[]; |
| 33 | + loadedLanguages!: Map<string, LoadedLanguage>; |
| 34 | + shiki!: Highlighter; |
| 35 | + customThemes!: CustomTheme[]; |
| 36 | + |
| 37 | + constructor(plugin: ShikiPlugin) { |
| 38 | + this.plugin = plugin; |
| 39 | + this.themeMapper = new ThemeMapper(this.plugin); |
| 40 | + } |
| 41 | + |
| 42 | + async load(): Promise<void> { |
| 43 | + await this.loadCustomThemes(); |
| 44 | + |
| 45 | + await this.loadLanguages(); |
| 46 | + |
| 47 | + await this.loadEC(); |
| 48 | + await this.loadShiki(); |
| 49 | + } |
| 50 | + |
| 51 | + async unload(): Promise<void> { |
| 52 | + this.unloadEC(); |
| 53 | + } |
| 54 | + |
| 55 | + async loadLanguages(): Promise<void> { |
| 56 | + this.loadedLanguages = new Map(); |
| 57 | + |
| 58 | + for (const [shikiLanguage, registration] of Object.entries(bundledLanguages)) { |
| 59 | + // the last element of the array is seemingly the most recent version of the language |
| 60 | + const language = (await registration()).default.at(-1); |
| 61 | + const shikiLanguageName = shikiLanguage as keyof typeof bundledLanguages; |
| 62 | + |
| 63 | + if (language === undefined) { |
| 64 | + continue; |
| 65 | + } |
| 66 | + |
| 67 | + for (const alias of [language.name, ...(language.aliases ?? [])]) { |
| 68 | + if (languageNameBlacklist.has(alias)) { |
| 69 | + continue; |
| 70 | + } |
| 71 | + |
| 72 | + if (!this.loadedLanguages.has(alias)) { |
| 73 | + const newLanguage = new LoadedLanguage(alias); |
| 74 | + newLanguage.addLanguage(shikiLanguageName); |
| 75 | + |
| 76 | + this.loadedLanguages.set(alias, newLanguage); |
| 77 | + } |
| 78 | + |
| 79 | + this.loadedLanguages.get(alias)!.addLanguage(shikiLanguageName); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + for (const [alias, language] of this.loadedLanguages) { |
| 84 | + if (language.languages.length === 1) { |
| 85 | + language.setDefaultLanguage(language.languages[0]); |
| 86 | + } else { |
| 87 | + const defaultLanguage = language.languages.find(lang => lang === alias); |
| 88 | + if (defaultLanguage !== undefined) { |
| 89 | + language.setDefaultLanguage(defaultLanguage); |
| 90 | + } else { |
| 91 | + console.warn(`No default language found for ${alias}, using the first language in the list`); |
| 92 | + language.setDefaultLanguage(language.languages[0]); |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + for (const disabledLanguage of this.plugin.loadedSettings.disabledLanguages) { |
| 98 | + this.loadedLanguages.delete(disabledLanguage); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + async loadCustomThemes(): Promise<void> { |
| 103 | + this.customThemes = []; |
| 104 | + |
| 105 | + // custom themes are disabled unless users specify a folder for them in plugin settings |
| 106 | + if (!this.plugin.loadedSettings.customThemeFolder) return; |
| 107 | + |
| 108 | + const themeFolder = normalizePath(this.plugin.loadedSettings.customThemeFolder); |
| 109 | + if (!(await this.plugin.app.vault.adapter.exists(themeFolder))) { |
| 110 | + new Notice(`${this.plugin.manifest.name}\nUnable to open custom themes folder: ${themeFolder}`, 5000); |
| 111 | + return; |
| 112 | + } |
| 113 | + |
| 114 | + const themeList = await this.plugin.app.vault.adapter.list(themeFolder); |
| 115 | + const themeFiles = themeList.files.filter(f => f.toLowerCase().endsWith('.json')); |
| 116 | + |
| 117 | + for (const themeFile of themeFiles) { |
| 118 | + const baseName = themeFile.substring(`${themeFolder}/`.length); |
| 119 | + try { |
| 120 | + const theme = JSON.parse(await this.plugin.app.vault.adapter.read(themeFile)) as CustomTheme; |
| 121 | + // validate that theme file JSON can be parsed and contains colors at a minimum |
| 122 | + if (!theme.colors && !theme.tokenColors) { |
| 123 | + throw Error('Invalid JSON theme file.'); |
| 124 | + } |
| 125 | + // what metadata is available in the theme file depends on how it was created |
| 126 | + theme.displayName = theme.displayName ?? theme.name ?? baseName; |
| 127 | + theme.name = baseName.toLowerCase(); |
| 128 | + theme.type = theme.type ?? 'both'; |
| 129 | + |
| 130 | + this.customThemes.push(theme); |
| 131 | + } catch (e) { |
| 132 | + new Notice(`${this.plugin.manifest.name}\nUnable to load custom theme: ${themeFile}`, 5000); |
| 133 | + console.warn(`Unable to load custom theme: ${themeFile}`, e); |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + // if the user's set theme cannot be loaded (e.g. it was deleted), fall back to default theme |
| 138 | + if (this.usesCustomTheme() && !this.customThemes.find(theme => theme.name === this.plugin.loadedSettings.theme)) { |
| 139 | + this.plugin.settings.theme = DEFAULT_SETTINGS.theme; |
| 140 | + this.plugin.loadedSettings.theme = DEFAULT_SETTINGS.theme; |
| 141 | + |
| 142 | + await this.plugin.saveSettings(); |
| 143 | + } |
| 144 | + |
| 145 | + this.customThemes.sort((a, b) => a.displayName.localeCompare(b.displayName)); |
| 146 | + } |
| 147 | + |
| 148 | + async loadEC(): Promise<void> { |
| 149 | + this.ec = new ExpressiveCodeEngine({ |
| 150 | + themes: [new ExpressiveCodeTheme(await this.themeMapper.getThemeForEC())], |
| 151 | + plugins: [ |
| 152 | + pluginShiki({ |
| 153 | + langs: Object.values(bundledLanguages), |
| 154 | + }), |
| 155 | + pluginCollapsibleSections(), |
| 156 | + pluginTextMarkers(), |
| 157 | + pluginLineNumbers(), |
| 158 | + pluginFrames(), |
| 159 | + ], |
| 160 | + styleOverrides: getECTheme(this.plugin.loadedSettings), |
| 161 | + minSyntaxHighlightingColorContrast: 0, |
| 162 | + themeCssRoot: 'div.expressive-code', |
| 163 | + defaultProps: { |
| 164 | + showLineNumbers: false, |
| 165 | + }, |
| 166 | + }); |
| 167 | + |
| 168 | + this.ecElements = []; |
| 169 | + |
| 170 | + const styles = (await this.ec.getBaseStyles()) + (await this.ec.getThemeStyles()); |
| 171 | + this.ecElements.push(document.head.createEl('style', { text: styles })); |
| 172 | + |
| 173 | + const jsModules = await this.ec.getJsModules(); |
| 174 | + for (const jsModule of jsModules) { |
| 175 | + this.ecElements.push(document.head.createEl('script', { attr: { type: 'module' }, text: jsModule })); |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + unloadEC(): void { |
| 180 | + for (const el of this.ecElements) { |
| 181 | + el.remove(); |
| 182 | + } |
| 183 | + this.ecElements = []; |
| 184 | + } |
| 185 | + |
| 186 | + async loadShiki(): Promise<void> { |
| 187 | + this.shiki = await createHighlighter({ |
| 188 | + themes: [await this.themeMapper.getTheme()], |
| 189 | + langs: Object.keys(bundledLanguages), |
| 190 | + }); |
| 191 | + } |
| 192 | + |
| 193 | + usesCustomTheme(): boolean { |
| 194 | + return this.plugin.loadedSettings.theme.endsWith('.json'); |
| 195 | + } |
| 196 | + |
| 197 | + /** |
| 198 | + * Highlights code with EC and renders it to the passed container element. |
| 199 | + */ |
| 200 | + async renderWithEc(code: string, language: string, meta: string, container: HTMLElement): Promise<void> { |
| 201 | + const result = await this.ec.render({ |
| 202 | + code, |
| 203 | + language, |
| 204 | + meta, |
| 205 | + }); |
| 206 | + |
| 207 | + container.innerHTML = toHtml(this.themeMapper.fixAST(result.renderedGroupAst)); |
| 208 | + } |
| 209 | +} |
0 commit comments