( node: HastNode | HastTextNode, key: string, links?: Links, indent = '' )
| 276 | // Renders a Hast Node to a list of tokens. A token is either a string, a React element, or a token type (number) + string. |
| 277 | // These are flattened into an array that gets sent to the client. This format significantly reduces the payload size vs JSX. |
| 278 | function renderHast( |
| 279 | node: HastNode | HastTextNode, |
| 280 | key: string, |
| 281 | links?: Links, |
| 282 | indent = '' |
| 283 | ): Token | Token[] { |
| 284 | if (node.type === 'element' && 'children' in node) { |
| 285 | let childArray: Token[] = renderChildren(node.children, key, links); |
| 286 | if (node.tagName === 'div') { |
| 287 | if (typeof childArray.at(-1) === 'string' && typeof childArray.at(-2) !== 'number') { |
| 288 | childArray[childArray.length - 1] += '\n'; |
| 289 | } else { |
| 290 | childArray.push('\n'); |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | let tokenType = |
| 295 | node.properties?.className |
| 296 | .split(' ') |
| 297 | .map(c => TokenType[c]) |
| 298 | .filter(v => v != null) || []; |
| 299 | if (node.properties?.className === 'comment' && text(node) === '/* PROPS */') { |
| 300 | return <CodeProps key={key} indent={indent} />; |
| 301 | } |
| 302 | |
| 303 | // CodeProps includes the indent and newlines in case there are no props to show. |
| 304 | if ( |
| 305 | node.tagName === 'div' && |
| 306 | typeof childArray[0] === 'string' && |
| 307 | /^\s+$/.test(childArray[0]) && |
| 308 | React.isValidElement(childArray[1]) && |
| 309 | childArray[1].type === CodeProps |
| 310 | ) { |
| 311 | // If the only thing after CodeProps is the newline from div processing, exclude it (CodeProps handles its own newlines). |
| 312 | // Otherwise, include all trailing content. |
| 313 | childArray = |
| 314 | childArray.length === 3 && childArray[2] === '\n' |
| 315 | ? childArray.slice(1, 2) |
| 316 | : childArray.slice(1); |
| 317 | } |
| 318 | |
| 319 | let children = childArray.length === 1 ? childArray[0] : childArray; |
| 320 | let tagName: any = node.tagName; |
| 321 | let properties: any = node.properties; |
| 322 | if (links && typeof children === 'string' && links[children]) { |
| 323 | let link = links[children]; |
| 324 | return ( |
| 325 | <CodeLink key={key} className={styles[properties?.className]} href={link}> |
| 326 | {children} |
| 327 | </CodeLink> |
| 328 | ); |
| 329 | } |
| 330 | |
| 331 | // Link to imported files. |
| 332 | if ( |
| 333 | properties?.className === 'string' && |
| 334 | typeof children === 'string' && |
| 335 | /^['"]\.\//.test(children) |
no test coverage detected