PluginProbe
Code Block Pro – Beautiful Syntax Highlighting / 1.13.0
Code Block Pro – Beautiful Syntax Highlighting v1.13.0
1.27.1 1.27.2 1.27.3 1.27.4 1.27.5 1.27.6 1.27.7 1.28.0 1.3.0 1.4.0 1.5.0 1.5.1 1.5.2 1.6.0 1.7.0 1.8.0 1.9.0 1.9.1 1.9.2 1.9.3 trunk 1.1.0 1.10.0 1.11.0 1.11.1 All 63 releases
← All changes | src/hooks/useTheme.ts +36 -8 1.8.01.13.0 View file →
@@ -1,32 +1,60 @@
1 +import { useEffect, useState } from '@wordpress/element';
1 2 import { applyFilters } from '@wordpress/hooks';
2 -import { __ } from '@wordpress/i18n';
3 -import { getHighlighter, Lang, setCDN, Theme } from 'shiki';
3 +import { getHighlighter, Lang, setCDN, Theme, setWasm } from 'shiki';
4 4 import useSWRImmutable from 'swr/immutable';
5 +import defaultThemes from '../defaultThemes.json';
6 +import { getEditorLanguage } from '../util/languages';
5 7
6 -type Params = { theme: Theme; lang: Lang; ready?: boolean };
8 +type Params = { theme: Theme; lang: Lang | 'ansi'; ready?: boolean };
7 9
8 10 const fetcher = ({ theme, lang, ready }: Params) => {
9 - if (!ready) throw new Error(__('Loading...', 'code-block-pro'));
11 + if (!ready) throw new Error();
10 12 const themeFiltered = applyFilters(
11 13 'blocks.codeBlockPro.theme',
12 14 theme,
13 15 ) as Theme;
14 - return getHighlighter({ langs: [lang], theme: themeFiltered });
16 + // If the theme has an alias, use that instead
17 + // i.e. it was renamed upstream
18 + const themeAlias = (
19 + defaultThemes as Record<
20 + string,
21 + { name: string; priority?: boolean; alias?: string }
22 + >
23 + )?.[themeFiltered]?.['alias'] as Theme;
24 +
25 + return getHighlighter({
26 + langs: [getEditorLanguage(lang)],
27 + theme: themeAlias ?? themeFiltered,
28 + });
15 29 };
16 30 let once = false;
17 31
18 32 export const useTheme = ({ theme, lang, ready = true }: Params) => {
33 + const [wasmLoaded, setWasmFileLoaded] = useState(false);
19 34 if (!once) {
20 35 once = true;
21 - const assetDir = window.codeBlockPro?.pluginUrl + '/build/shiki/';
36 + const assetDir = window.codeBlockPro?.pluginUrl + 'build/shiki/';
22 37 setCDN(
23 38 applyFilters('blocks.codeBlockPro.assetDir', assetDir) as string,
24 39 );
25 40 }
26 41 const { data: highlighter, error } = useSWRImmutable(
27 - { theme, lang, ready },
42 + { theme, lang, ready: ready && wasmLoaded },
28 43 fetcher,
29 44 );
45 + useEffect(() => {
46 + const assetDir = window.codeBlockPro?.pluginUrl + 'build/shiki/';
47 + fetch(assetDir + 'dist/onig.wasm')
48 + .then((res) => res.arrayBuffer())
49 + .then((wasmBuffer) => {
50 + setWasm(wasmBuffer);
51 + setWasmFileLoaded(true);
52 + });
53 + }, []);
30 54
31 - return { highlighter, error, loading: !highlighter && !error };
55 + return {
56 + highlighter,
57 + error,
58 + loading: (!highlighter && !error) || !wasmLoaded,
59 + };
32 60 };