format.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. """Formatting operations."""
  2. from __future__ import annotations
  3. import inspect
  4. import json
  5. import os
  6. import re
  7. from typing import TYPE_CHECKING, Any, List, Optional, Union
  8. from reflex import constants
  9. from reflex.utils import exceptions, serializers, types
  10. from reflex.utils.serializers import serialize
  11. from reflex.vars import BaseVar, Var
  12. if TYPE_CHECKING:
  13. from reflex.components.component import ComponentStyle
  14. from reflex.event import EventChain, EventHandler, EventSpec
  15. WRAP_MAP = {
  16. "{": "}",
  17. "(": ")",
  18. "[": "]",
  19. "<": ">",
  20. '"': '"',
  21. "'": "'",
  22. "`": "`",
  23. }
  24. def get_close_char(open: str, close: str | None = None) -> str:
  25. """Check if the given character is a valid brace.
  26. Args:
  27. open: The open character.
  28. close: The close character if provided.
  29. Returns:
  30. The close character.
  31. Raises:
  32. ValueError: If the open character is not a valid brace.
  33. """
  34. if close is not None:
  35. return close
  36. if open not in WRAP_MAP:
  37. raise ValueError(f"Invalid wrap open: {open}, must be one of {WRAP_MAP.keys()}")
  38. return WRAP_MAP[open]
  39. def is_wrapped(text: str, open: str, close: str | None = None) -> bool:
  40. """Check if the given text is wrapped in the given open and close characters.
  41. "(a) + (b)" --> False
  42. "((abc))" --> True
  43. "(abc)" --> True
  44. Args:
  45. text: The text to check.
  46. open: The open character.
  47. close: The close character.
  48. Returns:
  49. Whether the text is wrapped.
  50. """
  51. close = get_close_char(open, close)
  52. if not (text.startswith(open) and text.endswith(close)):
  53. return False
  54. depth = 0
  55. for ch in text[:-1]:
  56. if ch == open:
  57. depth += 1
  58. if ch == close:
  59. depth -= 1
  60. if depth == 0: # it shouldn't close before the end
  61. return False
  62. return True
  63. def wrap(
  64. text: str,
  65. open: str,
  66. close: str | None = None,
  67. check_first: bool = True,
  68. num: int = 1,
  69. ) -> str:
  70. """Wrap the given text in the given open and close characters.
  71. Args:
  72. text: The text to wrap.
  73. open: The open character.
  74. close: The close character.
  75. check_first: Whether to check if the text is already wrapped.
  76. num: The number of times to wrap the text.
  77. Returns:
  78. The wrapped text.
  79. """
  80. close = get_close_char(open, close)
  81. # If desired, check if the text is already wrapped in braces.
  82. if check_first and is_wrapped(text=text, open=open, close=close):
  83. return text
  84. # Wrap the text in braces.
  85. return f"{open * num}{text}{close * num}"
  86. def indent(text: str, indent_level: int = 2) -> str:
  87. """Indent the given text by the given indent level.
  88. Args:
  89. text: The text to indent.
  90. indent_level: The indent level.
  91. Returns:
  92. The indented text.
  93. """
  94. lines = text.splitlines()
  95. if len(lines) < 2:
  96. return text
  97. return os.linesep.join(f"{' ' * indent_level}{line}" for line in lines) + os.linesep
  98. def to_snake_case(text: str) -> str:
  99. """Convert a string to snake case.
  100. The words in the text are converted to lowercase and
  101. separated by underscores.
  102. Args:
  103. text: The string to convert.
  104. Returns:
  105. The snake case string.
  106. """
  107. s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", text)
  108. return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower().replace("-", "_")
  109. def to_camel_case(text: str, allow_hyphens: bool = False) -> str:
  110. """Convert a string to camel case.
  111. The first word in the text is converted to lowercase and
  112. the rest of the words are converted to title case, removing underscores.
  113. Args:
  114. text: The string to convert.
  115. allow_hyphens: Whether to allow hyphens in the string.
  116. Returns:
  117. The camel case string.
  118. """
  119. char = "_" if allow_hyphens else "-_"
  120. words = re.split(f"[{char}]", text.lstrip(char))
  121. leading_underscores_or_hyphens = "".join(re.findall(rf"^[{char}]+", text))
  122. # Capitalize the first letter of each word except the first one
  123. converted_word = words[0] + "".join(x.capitalize() for x in words[1:])
  124. return leading_underscores_or_hyphens + converted_word
  125. def to_title_case(text: str, sep: str = "") -> str:
  126. """Convert a string from snake case to title case.
  127. Args:
  128. text: The string to convert.
  129. sep: The separator to use to join the words.
  130. Returns:
  131. The title case string.
  132. """
  133. return sep.join(word.title() for word in text.split("_"))
  134. def to_kebab_case(text: str) -> str:
  135. """Convert a string to kebab case.
  136. The words in the text are converted to lowercase and
  137. separated by hyphens.
  138. Args:
  139. text: The string to convert.
  140. Returns:
  141. The title case string.
  142. """
  143. return to_snake_case(text).replace("_", "-")
  144. def make_default_page_title(app_name: str, route: str) -> str:
  145. """Make a default page title from a route.
  146. Args:
  147. app_name: The name of the app owning the page.
  148. route: The route to make the title from.
  149. Returns:
  150. The default page title.
  151. """
  152. title = constants.DefaultPage.TITLE.format(app_name, route)
  153. return to_title_case(title, " ")
  154. def _escape_js_string(string: str) -> str:
  155. """Escape the string for use as a JS string literal.
  156. Args:
  157. string: The string to escape.
  158. Returns:
  159. The escaped string.
  160. """
  161. # Escape backticks.
  162. string = string.replace(r"\`", "`")
  163. string = string.replace("`", r"\`")
  164. return string
  165. def _wrap_js_string(string: str) -> str:
  166. """Wrap string so it looks like {`string`}.
  167. Args:
  168. string: The string to wrap.
  169. Returns:
  170. The wrapped string.
  171. """
  172. string = wrap(string, "`")
  173. string = wrap(string, "{")
  174. return string
  175. def format_string(string: str) -> str:
  176. """Format the given string as a JS string literal..
  177. Args:
  178. string: The string to format.
  179. Returns:
  180. The formatted string.
  181. """
  182. return _wrap_js_string(_escape_js_string(string))
  183. def format_f_string_prop(prop: BaseVar) -> str:
  184. """Format the string in a given prop as an f-string.
  185. Args:
  186. prop: The prop to format.
  187. Returns:
  188. The formatted string.
  189. """
  190. s = prop._var_full_name
  191. var_data = prop._var_data
  192. interps = var_data.interpolations if var_data else []
  193. parts: List[str] = []
  194. if interps:
  195. for i, (start, end) in enumerate(interps):
  196. prev_end = interps[i - 1][1] if i > 0 else 0
  197. parts.append(_escape_js_string(s[prev_end:start]))
  198. parts.append(s[start:end])
  199. parts.append(_escape_js_string(s[interps[-1][1] :]))
  200. else:
  201. parts.append(_escape_js_string(s))
  202. return _wrap_js_string("".join(parts))
  203. def format_var(var: Var) -> str:
  204. """Format the given Var as a javascript value.
  205. Args:
  206. var: The Var to format.
  207. Returns:
  208. The formatted Var.
  209. """
  210. if not var._var_is_local or var._var_is_string:
  211. return str(var)
  212. if types._issubclass(var._var_type, str):
  213. return format_string(var._var_full_name)
  214. if is_wrapped(var._var_full_name, "{"):
  215. return var._var_full_name
  216. return json_dumps(var._var_full_name)
  217. def format_route(route: str, format_case=True) -> str:
  218. """Format the given route.
  219. Args:
  220. route: The route to format.
  221. format_case: whether to format case to kebab case.
  222. Returns:
  223. The formatted route.
  224. """
  225. route = route.strip("/")
  226. # Strip the route and format casing.
  227. if format_case:
  228. route = to_kebab_case(route)
  229. # If the route is empty, return the index route.
  230. if route == "":
  231. return constants.PageNames.INDEX_ROUTE
  232. return route
  233. def format_cond(
  234. cond: str | Var,
  235. true_value: str | Var,
  236. false_value: str | Var = '""',
  237. is_prop=False,
  238. ) -> str:
  239. """Format a conditional expression.
  240. Args:
  241. cond: The cond.
  242. true_value: The value to return if the cond is true.
  243. false_value: The value to return if the cond is false.
  244. is_prop: Whether the cond is a prop
  245. Returns:
  246. The formatted conditional expression.
  247. """
  248. # Use Python truthiness.
  249. cond = f"isTrue({cond})"
  250. def create_var(cond_part):
  251. return Var.create_safe(cond_part, _var_is_string=type(cond_part) is str)
  252. # Format prop conds.
  253. if is_prop:
  254. true_value = create_var(true_value)
  255. prop1 = true_value._replace(
  256. _var_is_local=True,
  257. )
  258. false_value = create_var(false_value)
  259. prop2 = false_value._replace(_var_is_local=True)
  260. # unwrap '{}' to avoid f-string semantics for Var
  261. return f"{cond} ? {prop1._var_name_unwrapped} : {prop2._var_name_unwrapped}"
  262. # Format component conds.
  263. return wrap(f"{cond} ? {true_value} : {false_value}", "{")
  264. def format_match(cond: str | Var, match_cases: List[BaseVar], default: Var) -> str:
  265. """Format a match expression whose return type is a Var.
  266. Args:
  267. cond: The condition.
  268. match_cases: The list of cases to match.
  269. default: The default case.
  270. Returns:
  271. The formatted match expression
  272. """
  273. switch_code = f"(() => {{ switch (JSON.stringify({cond})) {{"
  274. for case in match_cases:
  275. conditions = case[:-1]
  276. return_value = case[-1]
  277. case_conditions = " ".join(
  278. [
  279. f"case JSON.stringify({condition._var_name_unwrapped}):"
  280. for condition in conditions
  281. ]
  282. )
  283. case_code = (
  284. f"{case_conditions} return ({return_value._var_name_unwrapped}); break;"
  285. )
  286. switch_code += case_code
  287. switch_code += f"default: return ({default._var_name_unwrapped}); break;"
  288. switch_code += "};})()"
  289. return switch_code
  290. def format_prop(
  291. prop: Union[Var, EventChain, ComponentStyle, str],
  292. ) -> Union[int, float, str]:
  293. """Format a prop.
  294. Args:
  295. prop: The prop to format.
  296. Returns:
  297. The formatted prop to display within a tag.
  298. Raises:
  299. exceptions.InvalidStylePropError: If the style prop value is not a valid type.
  300. TypeError: If the prop is not valid.
  301. """
  302. # import here to avoid circular import.
  303. from reflex.event import EventChain
  304. try:
  305. # Handle var props.
  306. if isinstance(prop, Var):
  307. if not prop._var_is_local or prop._var_is_string:
  308. return str(prop)
  309. if isinstance(prop, BaseVar) and types._issubclass(prop._var_type, str):
  310. if prop._var_data and prop._var_data.interpolations:
  311. return format_f_string_prop(prop)
  312. return format_string(prop._var_full_name)
  313. prop = prop._var_full_name
  314. # Handle event props.
  315. elif isinstance(prop, EventChain):
  316. sig = inspect.signature(prop.args_spec) # type: ignore
  317. if sig.parameters:
  318. arg_def = ",".join(f"_{p}" for p in sig.parameters)
  319. arg_def = f"({arg_def})"
  320. else:
  321. # add a default argument for addEvents if none were specified in prop.args_spec
  322. # used to trigger the preventDefault() on the event.
  323. arg_def = "(_e)"
  324. chain = ",".join([format_event(event) for event in prop.events])
  325. event = f"addEvents([{chain}], {arg_def}, {json_dumps(prop.event_actions)})"
  326. prop = f"{arg_def} => {event}"
  327. # Handle other types.
  328. elif isinstance(prop, str):
  329. if is_wrapped(prop, "{"):
  330. return prop
  331. return json_dumps(prop)
  332. # For dictionaries, convert any properties to strings.
  333. elif isinstance(prop, dict):
  334. prop = serializers.serialize_dict(prop) # type: ignore
  335. else:
  336. # Dump the prop as JSON.
  337. prop = json_dumps(prop)
  338. except exceptions.InvalidStylePropError:
  339. raise
  340. except TypeError as e:
  341. raise TypeError(f"Could not format prop: {prop} of type {type(prop)}") from e
  342. # Wrap the variable in braces.
  343. assert isinstance(prop, str), "The prop must be a string."
  344. return wrap(prop, "{", check_first=False)
  345. def format_props(*single_props, **key_value_props) -> list[str]:
  346. """Format the tag's props.
  347. Args:
  348. single_props: Props that are not key-value pairs.
  349. key_value_props: Props that are key-value pairs.
  350. Returns:
  351. The formatted props list.
  352. """
  353. # Format all the props.
  354. return [
  355. f"{name}={format_prop(prop)}"
  356. for name, prop in sorted(key_value_props.items())
  357. if prop is not None
  358. ] + [str(prop) for prop in single_props]
  359. def get_event_handler_parts(handler: EventHandler) -> tuple[str, str]:
  360. """Get the state and function name of an event handler.
  361. Args:
  362. handler: The event handler to get the parts of.
  363. Returns:
  364. The state and function name.
  365. """
  366. # Get the class that defines the event handler.
  367. parts = handler.fn.__qualname__.split(".")
  368. # If there's no enclosing class, just return the function name.
  369. if len(parts) == 1:
  370. return ("", parts[-1])
  371. # Get the state full name
  372. state_full_name = handler.state_full_name
  373. # Get the function name
  374. name = parts[-1]
  375. from reflex.state import State
  376. if state_full_name == "state" and name not in State.__dict__:
  377. return ("", to_snake_case(handler.fn.__qualname__))
  378. return (state_full_name, name)
  379. def format_event_handler(handler: EventHandler) -> str:
  380. """Format an event handler.
  381. Args:
  382. handler: The event handler to format.
  383. Returns:
  384. The formatted function.
  385. """
  386. state, name = get_event_handler_parts(handler)
  387. if state == "":
  388. return name
  389. return f"{state}.{name}"
  390. def format_event(event_spec: EventSpec) -> str:
  391. """Format an event.
  392. Args:
  393. event_spec: The event to format.
  394. Returns:
  395. The compiled event.
  396. """
  397. args = ",".join(
  398. [
  399. ":".join(
  400. (
  401. name._var_name,
  402. (
  403. wrap(
  404. json.dumps(val._var_name).strip('"').replace("`", "\\`"),
  405. "`",
  406. )
  407. if val._var_is_string
  408. else val._var_full_name
  409. ),
  410. )
  411. )
  412. for name, val in event_spec.args
  413. ]
  414. )
  415. event_args = [
  416. wrap(format_event_handler(event_spec.handler), '"'),
  417. ]
  418. event_args.append(wrap(args, "{"))
  419. if event_spec.client_handler_name:
  420. event_args.append(wrap(event_spec.client_handler_name, '"'))
  421. return f"Event({', '.join(event_args)})"
  422. def format_event_chain(
  423. event_chain: EventChain | Var[EventChain],
  424. event_arg: Var | None = None,
  425. ) -> str:
  426. """Format an event chain as a javascript invocation.
  427. Args:
  428. event_chain: The event chain to queue on the frontend.
  429. event_arg: The browser-native event (only used to preventDefault).
  430. Returns:
  431. Compiled javascript code to queue the given event chain on the frontend.
  432. Raises:
  433. ValueError: When the given event chain is not a valid event chain.
  434. """
  435. if isinstance(event_chain, Var):
  436. from reflex.event import EventChain
  437. if event_chain._var_type is not EventChain:
  438. raise ValueError(f"Invalid event chain: {event_chain}")
  439. return "".join(
  440. [
  441. "(() => {",
  442. format_var(event_chain),
  443. f"; preventDefault({format_var(event_arg)})" if event_arg else "",
  444. "})()",
  445. ]
  446. )
  447. chain = ",".join([format_event(event) for event in event_chain.events])
  448. return "".join(
  449. [
  450. f"addEvents([{chain}]",
  451. f", {format_var(event_arg)}" if event_arg else "",
  452. ")",
  453. ]
  454. )
  455. def format_query_params(router_data: dict[str, Any]) -> dict[str, str]:
  456. """Convert back query params name to python-friendly case.
  457. Args:
  458. router_data: the router_data dict containing the query params
  459. Returns:
  460. The reformatted query params
  461. """
  462. params = router_data[constants.RouteVar.QUERY]
  463. return {k.replace("-", "_"): v for k, v in params.items()}
  464. def format_state(value: Any, key: Optional[str] = None) -> Any:
  465. """Recursively format values in the given state.
  466. Args:
  467. value: The state to format.
  468. key: The key associated with the value (optional).
  469. Returns:
  470. The formatted state.
  471. Raises:
  472. TypeError: If the given value is not a valid state.
  473. """
  474. # Handle dicts.
  475. if isinstance(value, dict):
  476. return {k: format_state(v, k) for k, v in value.items()}
  477. # Handle lists, sets, typles.
  478. if isinstance(value, types.StateIterBases):
  479. return [format_state(v) for v in value]
  480. # Return state vars as is.
  481. if isinstance(value, types.StateBases):
  482. return value
  483. # Serialize the value.
  484. serialized = serialize(value)
  485. if serialized is not None:
  486. return serialized
  487. if key is None:
  488. raise TypeError(
  489. f"No JSON serializer found for var {value} of type {type(value)}."
  490. )
  491. else:
  492. raise TypeError(
  493. f"No JSON serializer found for State Var '{key}' of value {value} of type {type(value)}."
  494. )
  495. def format_state_name(state_name: str) -> str:
  496. """Format a state name, replacing dots with double underscore.
  497. This allows individual substates to be accessed independently as javascript vars
  498. without using dot notation.
  499. Args:
  500. state_name: The state name to format.
  501. Returns:
  502. The formatted state name.
  503. """
  504. return state_name.replace(".", "__")
  505. def format_ref(ref: str) -> str:
  506. """Format a ref.
  507. Args:
  508. ref: The ref to format.
  509. Returns:
  510. The formatted ref.
  511. """
  512. # Replace all non-word characters with underscores.
  513. clean_ref = re.sub(r"[^\w]+", "_", ref)
  514. return f"ref_{clean_ref}"
  515. def format_array_ref(refs: str, idx: Var | None) -> str:
  516. """Format a ref accessed by array.
  517. Args:
  518. refs : The ref array to access.
  519. idx : The index of the ref in the array.
  520. Returns:
  521. The formatted ref.
  522. """
  523. clean_ref = re.sub(r"[^\w]+", "_", refs)
  524. if idx is not None:
  525. idx._var_is_local = True
  526. return f"refs_{clean_ref}[{idx}]"
  527. return f"refs_{clean_ref}"
  528. def format_breadcrumbs(route: str) -> list[tuple[str, str]]:
  529. """Take a route and return a list of tuple for use in breadcrumb.
  530. Args:
  531. route: The route to transform.
  532. Returns:
  533. list[tuple[str, str]]: the list of tuples for the breadcrumb.
  534. """
  535. route_parts = route.lstrip("/").split("/")
  536. # create and return breadcrumbs
  537. return [
  538. (part, "/".join(["", *route_parts[: i + 1]]))
  539. for i, part in enumerate(route_parts)
  540. ]
  541. def format_library_name(library_fullname: str):
  542. """Format the name of a library.
  543. Args:
  544. library_fullname: The fullname of the library.
  545. Returns:
  546. The name without the @version if it was part of the name
  547. """
  548. lib, at, version = library_fullname.rpartition("@")
  549. if not lib:
  550. lib = at + version
  551. return lib
  552. def json_dumps(obj: Any) -> str:
  553. """Takes an object and returns a jsonified string.
  554. Args:
  555. obj: The object to be serialized.
  556. Returns:
  557. A string
  558. """
  559. return json.dumps(obj, ensure_ascii=False, default=serialize)
  560. def unwrap_vars(value: str) -> str:
  561. """Unwrap var values from a JSON string.
  562. For example, "{var}" will be unwrapped to "var".
  563. Args:
  564. value: The JSON string to unwrap.
  565. Returns:
  566. The unwrapped JSON string.
  567. """
  568. def unescape_double_quotes_in_var(m: re.Match) -> str:
  569. prefix = m.group(1) or ""
  570. # Since the outer quotes are removed, the inner escaped quotes must be unescaped.
  571. return prefix + re.sub('\\\\"', '"', m.group(2))
  572. # This substitution is necessary to unwrap var values.
  573. return (
  574. re.sub(
  575. pattern=r"""
  576. (?<!\\) # must NOT start with a backslash
  577. " # match opening double quote of JSON value
  578. (<reflex.Var>.*?</reflex.Var>)? # Optional encoded VarData (non-greedy)
  579. {(.*?)} # extract the value between curly braces (non-greedy)
  580. " # match must end with an unescaped double quote
  581. """,
  582. repl=unescape_double_quotes_in_var,
  583. string=value,
  584. flags=re.VERBOSE,
  585. )
  586. .replace('"`', "`")
  587. .replace('`"', "`")
  588. )
  589. def collect_form_dict_names(form_dict: dict[str, Any]) -> dict[str, Any]:
  590. """Collapse keys with consecutive suffixes into a single list value.
  591. Separators dash and underscore are removed, unless this would overwrite an existing key.
  592. Args:
  593. form_dict: The dict to collapse.
  594. Returns:
  595. The collapsed dict.
  596. """
  597. ending_digit_regex = re.compile(r"^(.*?)[_-]?(\d+)$")
  598. collapsed = {}
  599. for k in sorted(form_dict):
  600. m = ending_digit_regex.match(k)
  601. if m:
  602. collapsed.setdefault(m.group(1), []).append(form_dict[k])
  603. # collapsing never overwrites valid data from the form_dict
  604. collapsed.update(form_dict)
  605. return collapsed
  606. def format_data_editor_column(col: str | dict):
  607. """Format a given column into the proper format.
  608. Args:
  609. col: The column.
  610. Raises:
  611. ValueError: invalid type provided for column.
  612. Returns:
  613. The formatted column.
  614. """
  615. if isinstance(col, str):
  616. return {"title": col, "id": col.lower(), "type": "str"}
  617. if isinstance(col, (dict,)):
  618. if "id" not in col:
  619. col["id"] = col["title"].lower()
  620. if "type" not in col:
  621. col["type"] = "str"
  622. if "overlayIcon" not in col:
  623. col["overlayIcon"] = None
  624. return col
  625. if isinstance(col, BaseVar):
  626. return col
  627. raise ValueError(
  628. f"unexpected type ({(type(col).__name__)}: {col}) for column header in data_editor"
  629. )
  630. def format_data_editor_cell(cell: Any):
  631. """Format a given data into a renderable cell for data_editor.
  632. Args:
  633. cell: The data to format.
  634. Returns:
  635. The formatted cell.
  636. """
  637. return {"kind": Var.create(value="GridCellKind.Text"), "data": cell}