react-native-code-edit
Version:
A lightweight code editor for React Native
49 lines (48 loc) • 1.81 kB
JavaScript
import React, { useEffect, useState } from "react";
import { ScrollView, StyleSheet, TextInput } from "react-native";
import ParsedText from "react-native-parsed-text";
const CodeEditor = (props) => {
const [code, setCode] = useState(props.initialValue || "");
useEffect(() => {
if (props.onChange) {
props.onChange(code);
}
}, [code]);
function onChange(text) {
setCode(text);
}
function highlightSyntax() {
if (!props.language) {
return code;
}
const langs = {
java: require("./langs/java"),
javascript: require("./langs/javascript")
};
const { keywords, singleLineComments } = langs[props.language];
const patterns = [];
if (singleLineComments) {
patterns.push({ pattern: new RegExp(`(${singleLineComments.join("|")})(.*)$`, "gm"), style: { color: "grey" } });
}
if (keywords) {
patterns.push({ pattern: new RegExp(keywords.join("|"), "g"), style: { color: "#7796CB" } });
}
return (React.createElement(ParsedText, { parse: patterns, style: styles.syntax }, code));
}
return (React.createElement(ScrollView, { alwaysBounceVertical: false, style: styles.scrollView },
highlightSyntax(),
React.createElement(TextInput, { autoCapitalize: "none", autoCorrect: false, autoFocus: true, multiline: true, onChangeText: onChange, returnKeyType: "next", spellCheck: false, style: styles.input, textAlignVertical: "top", textContentType: "none", value: code })));
};
const styles = StyleSheet.create({
input: {
color: "transparent",
},
scrollView: {
flex: 1
},
syntax: {
position: "absolute",
top: 0
}
});
export default CodeEditor;