shiki_code_block.py 23 KB

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