addons/isl/src/ComparisonView/SplitDiffView/grammar.tsxblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318import type {TextMateGrammar} from 'shared/textmate-lib/types';
b69ab319import type {IGrammar, Registry} from 'vscode-textmate';
b69ab3110import type {ThemeColor} from '../../theme';
b69ab3111
b69ab3112import createTextMateRegistry from 'shared/textmate-lib/createTextMateRegistry';
b69ab3113import {nullthrows} from 'shared/utils';
b69ab3114import {grammars} from '../../generated/textmate/TextMateGrammarManifest';
b69ab3115import VSCodeDarkPlusTheme from './VSCodeDarkPlusTheme';
b69ab3116import VSCodeLightPlusTheme from './VSCodeLightPlusTheme';
b69ab3117
b69ab3118const grammarCache: Map<string, Promise<IGrammar | null>> = new Map();
b69ab3119export function getGrammar(store: Registry, scopeName: string): Promise<IGrammar | null> {
b69ab3120 if (grammarCache.has(scopeName)) {
b69ab3121 return nullthrows(grammarCache.get(scopeName));
b69ab3122 }
b69ab3123 const grammarPromise = store.loadGrammar(scopeName);
b69ab3124 grammarCache.set(scopeName, grammarPromise);
b69ab3125 return grammarPromise;
b69ab3126}
b69ab3127
b69ab3128async function fetchGrammar(
b69ab3129 moduleName: string,
b69ab3130 type: 'json' | 'plist',
b69ab3131 base: string,
b69ab3132): Promise<TextMateGrammar> {
b69ab3133 const uri = new URL(`./generated/textmate/${moduleName}.${type}`, base);
b69ab3134 const response = await fetch(uri);
b69ab3135 const grammar = await response.text();
b69ab3136 return {type, grammar};
b69ab3137}
b69ab3138
b69ab3139let cachedGrammarStore: {value: Registry; theme: ThemeColor} | null = null;
b69ab3140export function getGrammarStore(
b69ab3141 theme: ThemeColor,
b69ab3142 base: string,
b69ab3143 onNewColors?: (colorMap: string[]) => void,
b69ab3144) {
b69ab3145 const found = cachedGrammarStore;
b69ab3146 if (found != null && found.theme === theme) {
b69ab3147 return found.value;
b69ab3148 }
b69ab3149
b69ab3150 // Grammars were cached according to the store, but the theme may have changed. Just bust the cache
b69ab3151 // to force grammars to reload.
b69ab3152 grammarCache.clear();
b69ab3153
b69ab3154 const themeValues = theme === 'light' ? VSCodeLightPlusTheme : VSCodeDarkPlusTheme;
b69ab3155
b69ab3156 const registry = createTextMateRegistry(themeValues, grammars, fetchGrammar, base);
b69ab3157
b69ab3158 onNewColors?.(registry.getColorMap());
b69ab3159
b69ab3160 cachedGrammarStore = {value: registry, theme};
b69ab3161 return registry;
b69ab3162}