2.1 KB63 lines
Blame
1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8import type {TextMateGrammar} from 'shared/textmate-lib/types';
9import type {IGrammar, Registry} from 'vscode-textmate';
10import type {ThemeColor} from '../../theme';
11
12import createTextMateRegistry from 'shared/textmate-lib/createTextMateRegistry';
13import {nullthrows} from 'shared/utils';
14import {grammars} from '../../generated/textmate/TextMateGrammarManifest';
15import VSCodeDarkPlusTheme from './VSCodeDarkPlusTheme';
16import VSCodeLightPlusTheme from './VSCodeLightPlusTheme';
17
18const grammarCache: Map<string, Promise<IGrammar | null>> = new Map();
19export function getGrammar(store: Registry, scopeName: string): Promise<IGrammar | null> {
20 if (grammarCache.has(scopeName)) {
21 return nullthrows(grammarCache.get(scopeName));
22 }
23 const grammarPromise = store.loadGrammar(scopeName);
24 grammarCache.set(scopeName, grammarPromise);
25 return grammarPromise;
26}
27
28async function fetchGrammar(
29 moduleName: string,
30 type: 'json' | 'plist',
31 base: string,
32): Promise<TextMateGrammar> {
33 const uri = new URL(`./generated/textmate/${moduleName}.${type}`, base);
34 const response = await fetch(uri);
35 const grammar = await response.text();
36 return {type, grammar};
37}
38
39let cachedGrammarStore: {value: Registry; theme: ThemeColor} | null = null;
40export function getGrammarStore(
41 theme: ThemeColor,
42 base: string,
43 onNewColors?: (colorMap: string[]) => void,
44) {
45 const found = cachedGrammarStore;
46 if (found != null && found.theme === theme) {
47 return found.value;
48 }
49
50 // Grammars were cached according to the store, but the theme may have changed. Just bust the cache
51 // to force grammars to reload.
52 grammarCache.clear();
53
54 const themeValues = theme === 'light' ? VSCodeLightPlusTheme : VSCodeDarkPlusTheme;
55
56 const registry = createTextMateRegistry(themeValues, grammars, fetchGrammar, base);
57
58 onNewColors?.(registry.getColorMap());
59
60 cachedGrammarStore = {value: registry, theme};
61 return registry;
62}
63