shiki_code_block.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. """Shiki syntax hghlighter component."""
  2. from __future__ import annotations
  3. import re
  4. from collections import defaultdict
  5. from typing import Any, Literal, Optional, Union
  6. from reflex.base import Base
  7. from reflex.components.component import Component, ComponentNamespace
  8. from reflex.components.core.colors import color
  9. from reflex.components.core.cond import color_mode_cond
  10. from reflex.components.el.elements.forms import Button
  11. from reflex.components.lucide.icon import Icon
  12. from reflex.components.props import NoExtrasAllowedProps
  13. from reflex.components.radix.themes.layout.box import Box
  14. from reflex.event import run_script, set_clipboard
  15. from reflex.style import Style
  16. from reflex.utils.exceptions import VarTypeError
  17. from reflex.utils.imports import ImportVar
  18. from reflex.vars.base import LiteralVar, Var
  19. from reflex.vars.function import FunctionStringVar
  20. from reflex.vars.sequence import StringVar, string_replace_operation
  21. def copy_script() -> Any:
  22. """Copy script for the code block and modify the child SVG element.
  23. Returns:
  24. Any: The result of calling the script.
  25. """
  26. return run_script(
  27. f"""
  28. // Event listener for the parent click
  29. document.addEventListener('click', function(event) {{
  30. // Find the closest button (parent element)
  31. const parent = event.target.closest('button');
  32. // If the parent is found
  33. if (parent) {{
  34. // Find the SVG element within the parent
  35. const svgIcon = parent.querySelector('svg');
  36. // If the SVG exists, proceed with the script
  37. if (svgIcon) {{
  38. const originalPath = svgIcon.innerHTML;
  39. const checkmarkPath = '<polyline points="20 6 9 17 4 12"></polyline>'; // Checkmark SVG path
  40. function transition(element, scale, opacity) {{
  41. element.style.transform = `scale(${{scale}})`;
  42. element.style.opacity = opacity;
  43. }}
  44. // Animate the SVG
  45. transition(svgIcon, 0, '0');
  46. setTimeout(() => {{
  47. svgIcon.innerHTML = checkmarkPath; // Replace content with checkmark
  48. svgIcon.setAttribute('viewBox', '0 0 24 24'); // Adjust viewBox if necessary
  49. transition(svgIcon, 1, '1');
  50. setTimeout(() => {{
  51. transition(svgIcon, 0, '0');
  52. setTimeout(() => {{
  53. svgIcon.innerHTML = originalPath; // Restore original SVG content
  54. transition(svgIcon, 1, '1');
  55. }}, 125);
  56. }}, 600);
  57. }}, 125);
  58. }} else {{
  59. // console.error('SVG element not found within the parent.');
  60. }}
  61. }} else {{
  62. // console.error('Parent element not found.');
  63. }}
  64. }})
  65. """
  66. )
  67. SHIKIJS_TRANSFORMER_FNS = {
  68. "transformerNotationDiff",
  69. "transformerNotationHighlight",
  70. "transformerNotationWordHighlight",
  71. "transformerNotationFocus",
  72. "transformerNotationErrorLevel",
  73. "transformerRenderWhitespace",
  74. "transformerMetaHighlight",
  75. "transformerMetaWordHighlight",
  76. "transformerCompactLineOptions",
  77. # TODO: this transformer when included adds a weird behavior which removes other code lines. Need to figure out why.
  78. # "transformerRemoveLineBreak",
  79. "transformerRemoveNotationEscape",
  80. }
  81. LINE_NUMBER_STYLING = {
  82. "code": {
  83. "counter-reset": "step",
  84. "counter-increment": "step 0",
  85. "display": "grid",
  86. "line-height": "1.7",
  87. "font-size": "0.875em",
  88. },
  89. "code .line::before": {
  90. "content": "counter(step)",
  91. "counter-increment": "step",
  92. "width": "1rem",
  93. "margin-right": "1.5rem",
  94. "display": "inline-block",
  95. "text-align": "right",
  96. "color": "rgba(115,138,148,.4)",
  97. },
  98. }
  99. BOX_PARENT_STYLING = {
  100. "pre": {
  101. "margin": "0",
  102. "padding": "24px",
  103. "background": "transparent",
  104. "overflow-x": "auto",
  105. "border-radius": "6px",
  106. },
  107. }
  108. THEME_MAPPING = {
  109. "light": "one-light",
  110. "dark": "one-dark-pro",
  111. "a11y-dark": "github-dark",
  112. }
  113. LANGUAGE_MAPPING = {"bash": "shellscript"}
  114. LiteralCodeLanguage = Literal[
  115. "abap",
  116. "actionscript-3",
  117. "ada",
  118. "angular-html",
  119. "angular-ts",
  120. "apache",
  121. "apex",
  122. "apl",
  123. "applescript",
  124. "ara",
  125. "asciidoc",
  126. "asm",
  127. "astro",
  128. "awk",
  129. "ballerina",
  130. "bat",
  131. "beancount",
  132. "berry",
  133. "bibtex",
  134. "bicep",
  135. "blade",
  136. "c",
  137. "cadence",
  138. "clarity",
  139. "clojure",
  140. "cmake",
  141. "cobol",
  142. "codeowners",
  143. "codeql",
  144. "coffee",
  145. "common-lisp",
  146. "coq",
  147. "cpp",
  148. "crystal",
  149. "csharp",
  150. "css",
  151. "csv",
  152. "cue",
  153. "cypher",
  154. "d",
  155. "dart",
  156. "dax",
  157. "desktop",
  158. "diff",
  159. "docker",
  160. "dotenv",
  161. "dream-maker",
  162. "edge",
  163. "elixir",
  164. "elm",
  165. "emacs-lisp",
  166. "erb",
  167. "erlang",
  168. "fennel",
  169. "fish",
  170. "fluent",
  171. "fortran-fixed-form",
  172. "fortran-free-form",
  173. "fsharp",
  174. "gdresource",
  175. "gdscript",
  176. "gdshader",
  177. "genie",
  178. "gherkin",
  179. "git-commit",
  180. "git-rebase",
  181. "gleam",
  182. "glimmer-js",
  183. "glimmer-ts",
  184. "glsl",
  185. "gnuplot",
  186. "go",
  187. "graphql",
  188. "groovy",
  189. "hack",
  190. "haml",
  191. "handlebars",
  192. "haskell",
  193. "haxe",
  194. "hcl",
  195. "hjson",
  196. "hlsl",
  197. "html",
  198. "html-derivative",
  199. "http",
  200. "hxml",
  201. "hy",
  202. "imba",
  203. "ini",
  204. "java",
  205. "javascript",
  206. "jinja",
  207. "jison",
  208. "json",
  209. "json5",
  210. "jsonc",
  211. "jsonl",
  212. "jsonnet",
  213. "jssm",
  214. "jsx",
  215. "julia",
  216. "kotlin",
  217. "kusto",
  218. "latex",
  219. "lean",
  220. "less",
  221. "liquid",
  222. "log",
  223. "logo",
  224. "lua",
  225. "luau",
  226. "make",
  227. "markdown",
  228. "marko",
  229. "matlab",
  230. "mdc",
  231. "mdx",
  232. "mermaid",
  233. "mojo",
  234. "move",
  235. "narrat",
  236. "nextflow",
  237. "nginx",
  238. "nim",
  239. "nix",
  240. "nushell",
  241. "objective-c",
  242. "objective-cpp",
  243. "ocaml",
  244. "pascal",
  245. "perl",
  246. "php",
  247. "plain",
  248. "plsql",
  249. "po",
  250. "postcss",
  251. "powerquery",
  252. "powershell",
  253. "prisma",
  254. "prolog",
  255. "proto",
  256. "pug",
  257. "puppet",
  258. "purescript",
  259. "python",
  260. "qml",
  261. "qmldir",
  262. "qss",
  263. "r",
  264. "racket",
  265. "raku",
  266. "razor",
  267. "reg",
  268. "regexp",
  269. "rel",
  270. "riscv",
  271. "rst",
  272. "ruby",
  273. "rust",
  274. "sas",
  275. "sass",
  276. "scala",
  277. "scheme",
  278. "scss",
  279. "shaderlab",
  280. "shellscript",
  281. "shellsession",
  282. "smalltalk",
  283. "solidity",
  284. "soy",
  285. "sparql",
  286. "splunk",
  287. "sql",
  288. "ssh-config",
  289. "stata",
  290. "stylus",
  291. "svelte",
  292. "swift",
  293. "system-verilog",
  294. "systemd",
  295. "tasl",
  296. "tcl",
  297. "templ",
  298. "terraform",
  299. "tex",
  300. "toml",
  301. "ts-tags",
  302. "tsv",
  303. "tsx",
  304. "turtle",
  305. "twig",
  306. "typescript",
  307. "typespec",
  308. "typst",
  309. "v",
  310. "vala",
  311. "vb",
  312. "verilog",
  313. "vhdl",
  314. "viml",
  315. "vue",
  316. "vue-html",
  317. "vyper",
  318. "wasm",
  319. "wenyan",
  320. "wgsl",
  321. "wikitext",
  322. "wolfram",
  323. "xml",
  324. "xsl",
  325. "yaml",
  326. "zenscript",
  327. "zig",
  328. ]
  329. LiteralCodeTheme = Literal[
  330. "andromeeda",
  331. "aurora-x",
  332. "ayu-dark",
  333. "catppuccin-frappe",
  334. "catppuccin-latte",
  335. "catppuccin-macchiato",
  336. "catppuccin-mocha",
  337. "dark-plus",
  338. "dracula",
  339. "dracula-soft",
  340. "everforest-dark",
  341. "everforest-light",
  342. "github-dark",
  343. "github-dark-default",
  344. "github-dark-dimmed",
  345. "github-dark-high-contrast",
  346. "github-light",
  347. "github-light-default",
  348. "github-light-high-contrast",
  349. "houston",
  350. "laserwave",
  351. "light-plus",
  352. "material-theme",
  353. "material-theme-darker",
  354. "material-theme-lighter",
  355. "material-theme-ocean",
  356. "material-theme-palenight",
  357. "min-dark",
  358. "min-light",
  359. "monokai",
  360. "night-owl",
  361. "nord",
  362. "one-dark-pro",
  363. "one-light",
  364. "plastic",
  365. "poimandres",
  366. "red",
  367. # rose-pine themes dont work with the current version of shikijs transformers
  368. # https://github.com/shikijs/shiki/issues/730
  369. "rose-pine",
  370. "rose-pine-dawn",
  371. "rose-pine-moon",
  372. "slack-dark",
  373. "slack-ochin",
  374. "snazzy-light",
  375. "solarized-dark",
  376. "solarized-light",
  377. "synthwave-84",
  378. "tokyo-night",
  379. "vesper",
  380. "vitesse-black",
  381. "vitesse-dark",
  382. "vitesse-light",
  383. ]
  384. class Position(NoExtrasAllowedProps):
  385. """Position of the decoration."""
  386. line: int
  387. character: int
  388. class ShikiDecorations(NoExtrasAllowedProps):
  389. """Decorations for the code block."""
  390. start: Union[int, Position]
  391. end: Union[int, Position]
  392. tag_name: str = "span"
  393. properties: dict[str, Any] = {}
  394. always_wrap: bool = False
  395. class ShikiBaseTransformers(Base):
  396. """Base for creating transformers."""
  397. library: str
  398. fns: list[FunctionStringVar]
  399. style: Optional[Style]
  400. class ShikiJsTransformer(ShikiBaseTransformers):
  401. """A Wrapped shikijs transformer."""
  402. library: str = "@shikijs/transformers"
  403. fns: list[FunctionStringVar] = [
  404. FunctionStringVar.create(fn) for fn in SHIKIJS_TRANSFORMER_FNS
  405. ]
  406. style: Optional[Style] = Style(
  407. {
  408. "code": {"line-height": "1.7", "font-size": "0.875em", "display": "grid"},
  409. # Diffs
  410. ".diff": {
  411. "margin": "0 -24px",
  412. "padding": "0 24px",
  413. "width": "calc(100% + 48px)",
  414. "display": "inline-block",
  415. },
  416. ".diff.add": {
  417. "background-color": "rgba(16, 185, 129, .14)",
  418. "position": "relative",
  419. },
  420. ".diff.remove": {
  421. "background-color": "rgba(244, 63, 94, .14)",
  422. "opacity": "0.7",
  423. "position": "relative",
  424. },
  425. ".diff.remove:after": {
  426. "position": "absolute",
  427. "left": "10px",
  428. "content": "'-'",
  429. "color": "#b34e52",
  430. },
  431. ".diff.add:after": {
  432. "position": "absolute",
  433. "left": "10px",
  434. "content": "'+'",
  435. "color": "#18794e",
  436. },
  437. # Highlight
  438. ".highlighted": {
  439. "background-color": "rgba(142, 150, 170, .14)",
  440. "margin": "0 -24px",
  441. "padding": "0 24px",
  442. "width": "calc(100% + 48px)",
  443. "display": "inline-block",
  444. },
  445. ".highlighted.error": {
  446. "background-color": "rgba(244, 63, 94, .14)",
  447. },
  448. ".highlighted.warning": {
  449. "background-color": "rgba(234, 179, 8, .14)",
  450. },
  451. # Highlighted Word
  452. ".highlighted-word": {
  453. "background-color": color("gray", 2),
  454. "border": f"1px solid {color('gray', 5)}",
  455. "padding": "1px 3px",
  456. "margin": "-1px -3px",
  457. "border-radius": "4px",
  458. },
  459. # Focused Lines
  460. ".has-focused .line:not(.focused)": {
  461. "opacity": "0.7",
  462. "filter": "blur(0.095rem)",
  463. "transition": "filter .35s, opacity .35s",
  464. },
  465. ".has-focused:hover .line:not(.focused)": {
  466. "opacity": "1",
  467. "filter": "none",
  468. },
  469. # White Space
  470. # ".tab, .space": {
  471. # "position": "relative",
  472. # },
  473. # ".tab::before": {
  474. # "content": "'⇥'",
  475. # "position": "absolute",
  476. # "opacity": "0.3",
  477. # },
  478. # ".space::before": {
  479. # "content": "'·'",
  480. # "position": "absolute",
  481. # "opacity": "0.3",
  482. # },
  483. }
  484. )
  485. def __init__(self, **kwargs):
  486. """Initialize the transformer.
  487. Args:
  488. kwargs: Kwargs to initialize the props.
  489. """
  490. fns = kwargs.pop("fns", None)
  491. style = kwargs.pop("style", None)
  492. if fns:
  493. kwargs["fns"] = [
  494. (
  495. FunctionStringVar.create(x)
  496. if not isinstance(x, FunctionStringVar)
  497. else x
  498. )
  499. for x in fns
  500. ]
  501. if style:
  502. kwargs["style"] = Style(style)
  503. super().__init__(**kwargs)
  504. class ShikiCodeBlock(Component):
  505. """A Code block."""
  506. library = "/components/shiki/code"
  507. tag = "Code"
  508. alias = "ShikiCode"
  509. lib_dependencies: list[str] = ["shiki"]
  510. # The language to use.
  511. language: Var[LiteralCodeLanguage] = Var.create("python")
  512. # The theme to use ("light" or "dark").
  513. theme: Var[LiteralCodeTheme] = Var.create("one-light")
  514. # The set of themes to use for different modes.
  515. themes: Var[Union[list[dict[str, Any]], dict[str, str]]]
  516. # The code to display.
  517. code: Var[str]
  518. # The transformers to use for the syntax highlighter.
  519. transformers: Var[list[Union[ShikiBaseTransformers, dict[str, Any]]]] = Var.create(
  520. []
  521. )
  522. # The decorations to use for the syntax highlighter.
  523. decorations: Var[list[ShikiDecorations]] = Var.create([])
  524. @classmethod
  525. def create(
  526. cls,
  527. *children,
  528. **props,
  529. ) -> Component:
  530. """Create a code block component using [shiki syntax highlighter](https://shiki.matsu.io/).
  531. Args:
  532. *children: The children of the component.
  533. **props: The props to pass to the component.
  534. Returns:
  535. The code block component.
  536. """
  537. # Separate props for the code block and the wrapper
  538. code_block_props = {}
  539. code_wrapper_props = {}
  540. decorations = props.pop("decorations", [])
  541. class_props = cls.get_props()
  542. # Distribute props between the code block and wrapper
  543. for key, value in props.items():
  544. (code_block_props if key in class_props else code_wrapper_props)[key] = (
  545. value
  546. )
  547. # cast decorations into ShikiDecorations.
  548. decorations = [
  549. ShikiDecorations(**decoration)
  550. if not isinstance(decoration, ShikiDecorations)
  551. else decoration
  552. for decoration in decorations
  553. ]
  554. code_block_props["decorations"] = decorations
  555. code_block_props["code"] = children[0]
  556. code_block = super().create(**code_block_props)
  557. transformer_styles = {}
  558. # Collect styles from transformers and wrapper
  559. for transformer in code_block.transformers._var_value: # type: ignore
  560. if isinstance(transformer, ShikiBaseTransformers) and transformer.style:
  561. transformer_styles.update(transformer.style)
  562. transformer_styles.update(code_wrapper_props.pop("style", {}))
  563. return Box.create(
  564. code_block,
  565. *children[1:],
  566. style=Style({**transformer_styles, **BOX_PARENT_STYLING}),
  567. **code_wrapper_props,
  568. )
  569. def add_imports(self) -> dict[str, list[str]]:
  570. """Add the necessary imports.
  571. We add all referenced transformer functions as imports from their corresponding
  572. libraries.
  573. Returns:
  574. Imports for the component.
  575. """
  576. imports = defaultdict(list)
  577. for transformer in self.transformers._var_value:
  578. if isinstance(transformer, ShikiBaseTransformers):
  579. imports[transformer.library].extend(
  580. [ImportVar(tag=str(fn)) for fn in transformer.fns]
  581. )
  582. (
  583. self.lib_dependencies.append(transformer.library)
  584. if transformer.library not in self.lib_dependencies
  585. else None
  586. )
  587. return imports
  588. @classmethod
  589. def create_transformer(cls, library: str, fns: list[str]) -> ShikiBaseTransformers:
  590. """Create a transformer from a third party library.
  591. Args:
  592. library: The name of the library.
  593. fns: The str names of the functions/callables to invoke from the library.
  594. Returns:
  595. A transformer for the specified library.
  596. Raises:
  597. ValueError: If a supplied function name is not valid str.
  598. """
  599. if any(not isinstance(fn_name, str) for fn_name in fns):
  600. raise ValueError(
  601. f"the function names should be str names of functions in the specified transformer: {library!r}"
  602. )
  603. return ShikiBaseTransformers( # type: ignore
  604. library=library, fns=[FunctionStringVar.create(fn) for fn in fns]
  605. )
  606. def _render(self, props: dict[str, Any] | None = None):
  607. """Renders the component with the given properties, processing transformers if present.
  608. Args:
  609. props: Optional properties to pass to the render function.
  610. Returns:
  611. Rendered component output.
  612. """
  613. # Ensure props is initialized from class attributes if not provided
  614. props = props or {
  615. attr.rstrip("_"): getattr(self, attr) for attr in self.get_props()
  616. }
  617. # Extract transformers and apply transformations
  618. transformers = props.get("transformers")
  619. if transformers is not None:
  620. transformed_values = self._process_transformers(transformers._var_value)
  621. props["transformers"] = LiteralVar.create(transformed_values)
  622. return super()._render(props)
  623. def _process_transformers(self, transformer_list: list) -> list:
  624. """Processes a list of transformers, applying transformations where necessary.
  625. Args:
  626. transformer_list: List of transformer objects or values.
  627. Returns:
  628. list: A list of transformed values.
  629. """
  630. processed = []
  631. for transformer in transformer_list:
  632. if isinstance(transformer, ShikiBaseTransformers):
  633. processed.extend(fn.call() for fn in transformer.fns)
  634. else:
  635. processed.append(transformer)
  636. return processed
  637. class ShikiHighLevelCodeBlock(ShikiCodeBlock):
  638. """High level component for the shiki syntax highlighter."""
  639. # If this is enabled, the default transformers(shikijs transformer) will be used.
  640. use_transformers: Var[bool]
  641. # If this is enabled line numbers will be shown next to the code block.
  642. show_line_numbers: Var[bool]
  643. # Whether a copy button should appear.
  644. can_copy: bool = False
  645. # copy_button: A custom copy button to override the default one.
  646. copy_button: Optional[Union[Component, bool]] = None
  647. @classmethod
  648. def create(
  649. cls,
  650. *children,
  651. **props,
  652. ) -> Component:
  653. """Create a code block component using [shiki syntax highlighter](https://shiki.matsu.io/).
  654. Args:
  655. *children: The children of the component.
  656. **props: The props to pass to the component.
  657. Returns:
  658. The code block component.
  659. """
  660. use_transformers = props.pop("use_transformers", False)
  661. show_line_numbers = props.pop("show_line_numbers", False)
  662. language = props.pop("language", None)
  663. can_copy = props.pop("can_copy", False)
  664. copy_button = props.pop("copy_button", None)
  665. if use_transformers:
  666. props["transformers"] = [ShikiJsTransformer()]
  667. if language is not None:
  668. props["language"] = cls._map_languages(language)
  669. # line numbers are generated via css
  670. if show_line_numbers:
  671. props["style"] = {**LINE_NUMBER_STYLING, **props.get("style", {})}
  672. theme = props.pop("theme", None)
  673. props["theme"] = props["theme"] = (
  674. cls._map_themes(theme)
  675. if theme is not None
  676. else color_mode_cond( # Default color scheme responds to global color mode.
  677. light="one-light",
  678. dark="one-dark-pro",
  679. )
  680. )
  681. if can_copy:
  682. code = children[0]
  683. copy_button = ( # type: ignore
  684. copy_button
  685. if copy_button is not None
  686. else Button.create(
  687. Icon.create(tag="copy", size=16, color=color("gray", 11)),
  688. on_click=[
  689. set_clipboard(cls._strip_transformer_triggers(code)), # type: ignore
  690. copy_script(),
  691. ],
  692. style=Style(
  693. {
  694. "position": "absolute",
  695. "top": "4px",
  696. "right": "4px",
  697. "background": color("gray", 3),
  698. "border": "1px solid",
  699. "border-color": color("gray", 5),
  700. "border-radius": "6px",
  701. "padding": "5px",
  702. "opacity": "1",
  703. "cursor": "pointer",
  704. "_hover": {
  705. "background": color("gray", 4),
  706. },
  707. "transition": "background 0.250s ease-out",
  708. "&>svg": {
  709. "transition": "transform 0.250s ease-out, opacity 0.250s ease-out",
  710. },
  711. "_active": {
  712. "background": color("gray", 5),
  713. },
  714. }
  715. ),
  716. )
  717. )
  718. if copy_button:
  719. return ShikiCodeBlock.create(
  720. children[0], copy_button, position="relative", **props
  721. )
  722. else:
  723. return ShikiCodeBlock.create(children[0], **props)
  724. @staticmethod
  725. def _map_themes(theme: str) -> str:
  726. if isinstance(theme, str) and theme in THEME_MAPPING:
  727. return THEME_MAPPING[theme]
  728. return theme
  729. @staticmethod
  730. def _map_languages(language: str) -> str:
  731. if isinstance(language, str) and language in LANGUAGE_MAPPING:
  732. return LANGUAGE_MAPPING[language]
  733. return language
  734. @staticmethod
  735. def _strip_transformer_triggers(code: str | StringVar) -> StringVar | str:
  736. if not isinstance(code, (StringVar, str)):
  737. raise VarTypeError(
  738. f"code should be string literal or a StringVar type. Got {type(code)} instead."
  739. )
  740. regex_pattern = r"[\/#]+ *\[!code.*?\]"
  741. if isinstance(code, Var):
  742. return string_replace_operation(
  743. code, StringVar(_js_expr=f"/{regex_pattern}/g", _var_type=str), ""
  744. )
  745. if isinstance(code, str):
  746. return re.sub(regex_pattern, "", code)
  747. class TransformerNamespace(ComponentNamespace):
  748. """Namespace for the Transformers."""
  749. shikijs = ShikiJsTransformer
  750. class CodeblockNamespace(ComponentNamespace):
  751. """Namespace for the CodeBlock component."""
  752. root = staticmethod(ShikiCodeBlock.create)
  753. create_transformer = staticmethod(ShikiCodeBlock.create_transformer)
  754. transformers = TransformerNamespace()
  755. __call__ = staticmethod(ShikiHighLevelCodeBlock.create)
  756. code_block = CodeblockNamespace()