Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

181 linhas
6.3 KiB

  1. from __future__ import annotations
  2. from collections.abc import Callable, MutableMapping
  3. import dataclasses as dc
  4. from typing import Any, Literal
  5. import warnings
  6. from markdown_it._compat import DATACLASS_KWARGS
  7. def convert_attrs(value: Any) -> Any:
  8. """Convert Token.attrs set as ``None`` or ``[[key, value], ...]`` to a dict.
  9. This improves compatibility with upstream markdown-it.
  10. """
  11. if not value:
  12. return {}
  13. if isinstance(value, list):
  14. return dict(value)
  15. return value
  16. @dc.dataclass(**DATACLASS_KWARGS)
  17. class Token:
  18. type: str
  19. """Type of the token (string, e.g. "paragraph_open")"""
  20. tag: str
  21. """HTML tag name, e.g. 'p'"""
  22. nesting: Literal[-1, 0, 1]
  23. """Level change (number in {-1, 0, 1} set), where:
  24. - `1` means the tag is opening
  25. - `0` means the tag is self-closing
  26. - `-1` means the tag is closing
  27. """
  28. attrs: dict[str, str | int | float] = dc.field(default_factory=dict)
  29. """HTML attributes.
  30. Note this differs from the upstream "list of lists" format,
  31. although than an instance can still be initialised with this format.
  32. """
  33. map: list[int] | None = None
  34. """Source map info. Format: `[ line_begin, line_end ]`"""
  35. level: int = 0
  36. """Nesting level, the same as `state.level`"""
  37. children: list[Token] | None = None
  38. """Array of child nodes (inline and img tokens)."""
  39. content: str = ""
  40. """Inner content, in the case of a self-closing tag (code, html, fence, etc.),"""
  41. markup: str = ""
  42. """'*' or '_' for emphasis, fence string for fence, etc."""
  43. info: str = ""
  44. """Additional information:
  45. - Info string for "fence" tokens
  46. - The value "auto" for autolink "link_open" and "link_close" tokens
  47. - The string value of the item marker for ordered-list "list_item_open" tokens
  48. """
  49. meta: dict[Any, Any] = dc.field(default_factory=dict)
  50. """A place for plugins to store any arbitrary data"""
  51. block: bool = False
  52. """True for block-level tokens, false for inline tokens.
  53. Used in renderer to calculate line breaks
  54. """
  55. hidden: bool = False
  56. """If true, ignore this element when rendering.
  57. Used for tight lists to hide paragraphs.
  58. """
  59. def __post_init__(self) -> None:
  60. self.attrs = convert_attrs(self.attrs)
  61. def attrIndex(self, name: str) -> int:
  62. warnings.warn( # noqa: B028
  63. "Token.attrIndex should not be used, since Token.attrs is a dictionary",
  64. UserWarning,
  65. )
  66. if name not in self.attrs:
  67. return -1
  68. return list(self.attrs.keys()).index(name)
  69. def attrItems(self) -> list[tuple[str, str | int | float]]:
  70. """Get (key, value) list of attrs."""
  71. return list(self.attrs.items())
  72. def attrPush(self, attrData: tuple[str, str | int | float]) -> None:
  73. """Add `[ name, value ]` attribute to list. Init attrs if necessary."""
  74. name, value = attrData
  75. self.attrSet(name, value)
  76. def attrSet(self, name: str, value: str | int | float) -> None:
  77. """Set `name` attribute to `value`. Override old value if exists."""
  78. self.attrs[name] = value
  79. def attrGet(self, name: str) -> None | str | int | float:
  80. """Get the value of attribute `name`, or null if it does not exist."""
  81. return self.attrs.get(name, None)
  82. def attrJoin(self, name: str, value: str) -> None:
  83. """Join value to existing attribute via space.
  84. Or create new attribute if not exists.
  85. Useful to operate with token classes.
  86. """
  87. if name in self.attrs:
  88. current = self.attrs[name]
  89. if not isinstance(current, str):
  90. raise TypeError(
  91. f"existing attr 'name' is not a str: {self.attrs[name]}"
  92. )
  93. self.attrs[name] = f"{current} {value}"
  94. else:
  95. self.attrs[name] = value
  96. def copy(self, **changes: Any) -> Token:
  97. """Return a shallow copy of the instance."""
  98. return dc.replace(self, **changes)
  99. def as_dict(
  100. self,
  101. *,
  102. children: bool = True,
  103. as_upstream: bool = True,
  104. meta_serializer: Callable[[dict[Any, Any]], Any] | None = None,
  105. filter: Callable[[str, Any], bool] | None = None,
  106. dict_factory: Callable[..., MutableMapping[str, Any]] = dict,
  107. ) -> MutableMapping[str, Any]:
  108. """Return the token as a dictionary.
  109. :param children: Also convert children to dicts
  110. :param as_upstream: Ensure the output dictionary is equal to that created by markdown-it
  111. For example, attrs are converted to null or lists
  112. :param meta_serializer: hook for serializing ``Token.meta``
  113. :param filter: A callable whose return code determines whether an
  114. attribute or element is included (``True``) or dropped (``False``).
  115. Is called with the (key, value) pair.
  116. :param dict_factory: A callable to produce dictionaries from.
  117. For example, to produce ordered dictionaries instead of normal Python
  118. dictionaries, pass in ``collections.OrderedDict``.
  119. """
  120. mapping = dict_factory((f.name, getattr(self, f.name)) for f in dc.fields(self))
  121. if filter:
  122. mapping = dict_factory((k, v) for k, v in mapping.items() if filter(k, v))
  123. if as_upstream and "attrs" in mapping:
  124. mapping["attrs"] = (
  125. None
  126. if not mapping["attrs"]
  127. else [[k, v] for k, v in mapping["attrs"].items()]
  128. )
  129. if meta_serializer and "meta" in mapping:
  130. mapping["meta"] = meta_serializer(mapping["meta"])
  131. if children and mapping.get("children", None):
  132. mapping["children"] = [
  133. child.as_dict(
  134. children=children,
  135. filter=filter,
  136. dict_factory=dict_factory,
  137. as_upstream=as_upstream,
  138. meta_serializer=meta_serializer,
  139. )
  140. for child in mapping["children"]
  141. ]
  142. return mapping
  143. @classmethod
  144. def from_dict(cls, dct: MutableMapping[str, Any]) -> Token:
  145. """Convert a dict to a Token."""
  146. token = cls(**dct)
  147. if token.children:
  148. token.children = [cls.from_dict(c) for c in token.children] # type: ignore[arg-type]
  149. return token