| 1 |
import { applyFilters } from '@wordpress/hooks'; |
| 2 |
import { __ } from '@wordpress/i18n'; |
| 3 |
import { getHighlighter, Lang, setCDN, Theme } from 'shiki'; |
| 4 |
import useSWRImmutable from 'swr/immutable'; |
| 5 |
|
| 6 |
type Params = { theme: Theme; lang: Lang; ready?: boolean }; |
| 7 |
|
| 8 |
const fetcher = ({ theme, lang, ready }: Params) => { |
| 9 |
if (!ready) throw new Error(__('Loading...', 'code-block-pro')); |
| 10 |
const themeFiltered = applyFilters( |
| 11 |
'blocks.codeBlockPro.theme', |
| 12 |
theme, |
| 13 |
) as Theme; |
| 14 |
return getHighlighter({ langs: [lang], theme: themeFiltered }); |
| 15 |
}; |
| 16 |
let once = false; |
| 17 |
|
| 18 |
export const useTheme = ({ theme, lang, ready = true }: Params) => { |
| 19 |
if (!once) { |
| 20 |
once = true; |
| 21 |
const assetDir = window.codeBlockPro?.pluginUrl + '/build/shiki/'; |
| 22 |
setCDN( |
| 23 |
applyFilters('blocks.codeBlockPro.assetDir', assetDir) as string, |
| 24 |
); |
| 25 |
} |
| 26 |
const { data: highlighter, error } = useSWRImmutable( |
| 27 |
{ theme, lang, ready }, |
| 28 |
fetcher, |
| 29 |
); |
| 30 |
|
| 31 |
return { highlighter, error, loading: !highlighter && !error }; |
| 32 |
}; |
| 33 |
|