UNPKG

@nguyenviet3057/react-native-code-highlighter

Version:
76 lines (75 loc) 2.58 kB
"use strict"; import React, { useMemo } from "react"; import { StyleSheet, Text, View } from "react-native"; import SyntaxHighlighter from "react-syntax-highlighter"; import { trimNewlines } from "trim-newlines"; import { getRNStylesFromHljsStyle } from "./../utils/styles"; import { jsx as _jsx } from "react/jsx-runtime"; export const CodeHighlighter = ({ children, textStyle, hljsStyle, viewProps, containerStyle, ...rest }) => { const stylesheet = useMemo(() => getRNStylesFromHljsStyle(hljsStyle), [hljsStyle]); const getStylesForNode = node => { const classes = node.properties?.className ?? []; return classes.map(c => stylesheet[c]).filter(c => !!c); }; const renderNode = (nodes, keyPrefix = "row") => nodes.reduce((acc, node, index) => { const keyPrefixWithIndex = `${keyPrefix}_${index}`; if (node.children) { const styles = StyleSheet.flatten([textStyle, { color: stylesheet.hljs?.color }, getStylesForNode(node), StyleSheet.create(node.properties?.style) // This style uses width unit by `em`, so not work ]); if (node.children.every(node => node.type === "text") && node.children.filter(node => node.value !== "").length === 0) { return acc; } acc.push(node.children.every(node => node.type === "text") ? /*#__PURE__*/_jsx(Text, { style: [styles], children: trimNewlines(node.children.map(node => node.value).join("")) }, keyPrefixWithIndex) : /*#__PURE__*/_jsx(View, { style: [{ display: "flex", flexDirection: "row", flexWrap: "wrap", alignItems: "center" }, styles], children: renderNode(node.children, `${keyPrefixWithIndex}_child`) }, keyPrefixWithIndex)); } if (node.value) { acc.push(/*#__PURE__*/_jsx(Text, { children: trimNewlines(String(node.value)) }, keyPrefixWithIndex)); } return acc; }, []); const renderer = props => { const { rows } = props; return /*#__PURE__*/_jsx(View, { ...viewProps, style: [stylesheet.hljs, viewProps?.contentContainerStyle, containerStyle], children: /*#__PURE__*/_jsx(View, { onStartShouldSetResponder: () => true, children: renderNode(rows) }) }); }; return /*#__PURE__*/_jsx(SyntaxHighlighter, { ...rest, renderer: renderer, CodeTag: View, PreTag: View, style: {}, testID: "react-native-code-highlighter", children: children }); }; export default CodeHighlighter; //# sourceMappingURL=CodeHighlighter.js.map