Skip to content

Commit

Permalink
run before and after tokenize hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
manuelpuyol committed Feb 17, 2021
1 parent 89c194b commit 59f2ba9
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
25 changes: 24 additions & 1 deletion src/components/Highlight.js
Expand Up @@ -12,8 +12,10 @@ import type {
TokenInputProps,
TokenOutputProps,
RenderProps,
PrismGrammar,
PrismLib,
PrismTheme,
PrismToken,
} from "../types";

type Props = {
Expand Down Expand Up @@ -121,14 +123,35 @@ class Highlight extends Component<Props, *> {
return output;
};

tokenize = (
Prism: PrismLib,
code: string,
grammar: PrismGrammar,
language: Language
): Array<PrismToken> => {
const env = {
code,
grammar,
language,
};

Prism.hooks.run("before-tokenize", env);
env.tokens = Prism.tokenize(env.code, env.grammar, env.language);
Prism.hooks.run("after-tokenize", env);

return env.tokens;
};

render() {
const { Prism, language, code, children } = this.props;

const themeDict = this.getThemeDict(this.props);

const grammar = Prism.languages[language];
const mixedTokens =
grammar !== undefined ? Prism.tokenize(code, grammar, language) : [code];
grammar !== undefined
? this.tokenize(Prism, code, grammar, language)
: [code];
const tokens = normalizeTokens(mixedTokens);

return children({
Expand Down
8 changes: 7 additions & 1 deletion src/types.js
Expand Up @@ -5,7 +5,7 @@ import includedLangs from "./vendor/prism/includeLangs";

export type Language = $Keys<typeof includedLangs>;

type PrismGrammar = {
export type PrismGrammar = {
[key: string]: mixed,
};

Expand Down Expand Up @@ -37,6 +37,12 @@ export type PrismLib = {
grammar: PrismGrammar,
language: Language
) => string,
hooks: {
run: (
name: string,
env: { code: string, grammar: PrismGrammar, language: Language }
) => void,
},
};

export type StyleObj = {
Expand Down
1 change: 1 addition & 0 deletions src/vendor/prism/prism-core.js
Expand Up @@ -339,6 +339,7 @@ var Prism = (function () {

hooks: {
add: function () {},
run: function (name, env) {},
},

tokenize: function (text, grammar, language) {
Expand Down

0 comments on commit 59f2ba9

Please sign in to comment.