react-live
Advanced tools
Comparing version 3.2.0 to 4.0.0
@@ -5,2 +5,3 @@ 'use strict'; | ||
var jsxRuntime = require('react/jsx-runtime'); | ||
var Highlight = require('prism-react-renderer'); | ||
@@ -15,17 +16,2 @@ var React = require('react'); | ||
function _defineProperty(obj, key, value) { | ||
if (key in obj) { | ||
Object.defineProperty(obj, key, { | ||
value: value, | ||
enumerable: true, | ||
configurable: true, | ||
writable: true | ||
}); | ||
} else { | ||
obj[key] = value; | ||
} | ||
return obj; | ||
} | ||
var m = { | ||
@@ -362,474 +348,327 @@ characterData: !0, | ||
var theme = { | ||
plain: { | ||
color: "#C5C8C6", | ||
backgroundColor: "#1D1F21" | ||
}, | ||
styles: [{ | ||
types: ["prolog", "comment", "doctype", "cdata"], | ||
style: { | ||
color: "hsl(30, 20%, 50%)" | ||
} | ||
}, { | ||
types: ["property", "tag", "boolean", "number", "constant", "symbol"], | ||
style: { | ||
color: "hsl(350, 40%, 70%)" | ||
} | ||
}, { | ||
types: ["attr-name", "string", "char", "builtin", "insterted"], | ||
style: { | ||
color: "hsl(75, 70%, 60%)" | ||
} | ||
}, { | ||
types: ["operator", "entity", "url", "string", "variable", "language-css"], | ||
style: { | ||
color: "hsl(40, 90%, 60%)" | ||
} | ||
}, { | ||
types: ["deleted"], | ||
style: { | ||
color: "rgb(255, 85, 85)" | ||
} | ||
}, { | ||
types: ["italic"], | ||
style: { | ||
fontStyle: "italic" | ||
} | ||
}, { | ||
types: ["important", "bold"], | ||
style: { | ||
fontWeight: "bold" | ||
} | ||
}, { | ||
types: ["regex", "important"], | ||
style: { | ||
color: "#e90" | ||
} | ||
}, { | ||
types: ["atrule", "attr-value", "keyword"], | ||
style: { | ||
color: "hsl(350, 40%, 70%)" | ||
} | ||
}, { | ||
types: ["punctuation", "symbol"], | ||
style: { | ||
opacity: "0.7" | ||
} | ||
}] | ||
const theme = { | ||
plain: { | ||
color: "#C5C8C6", | ||
backgroundColor: "#1D1F21", | ||
}, | ||
styles: [ | ||
{ | ||
types: ["prolog", "comment", "doctype", "cdata"], | ||
style: { | ||
color: "hsl(30, 20%, 50%)", | ||
}, | ||
}, | ||
{ | ||
types: ["property", "tag", "boolean", "number", "constant", "symbol"], | ||
style: { color: "hsl(350, 40%, 70%)" }, | ||
}, | ||
{ | ||
types: ["attr-name", "string", "char", "builtin", "insterted"], | ||
style: { | ||
color: "hsl(75, 70%, 60%)", | ||
}, | ||
}, | ||
{ | ||
types: [ | ||
"operator", | ||
"entity", | ||
"url", | ||
"string", | ||
"variable", | ||
"language-css", | ||
], | ||
style: { | ||
color: "hsl(40, 90%, 60%)", | ||
}, | ||
}, | ||
{ | ||
types: ["deleted"], | ||
style: { | ||
color: "rgb(255, 85, 85)", | ||
}, | ||
}, | ||
{ | ||
types: ["italic"], | ||
style: { | ||
fontStyle: "italic", | ||
}, | ||
}, | ||
{ | ||
types: ["important", "bold"], | ||
style: { | ||
fontWeight: "bold", | ||
}, | ||
}, | ||
{ | ||
types: ["regex", "important"], | ||
style: { | ||
color: "#e90", | ||
}, | ||
}, | ||
{ | ||
types: ["atrule", "attr-value", "keyword"], | ||
style: { | ||
color: "hsl(350, 40%, 70%)", | ||
}, | ||
}, | ||
{ | ||
types: ["punctuation", "symbol"], | ||
style: { | ||
opacity: 0.7, | ||
}, | ||
}, | ||
], | ||
}; | ||
function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
var CodeEditor = function CodeEditor(props) { | ||
var editorRef = React.useRef(null); | ||
var _useState = React.useState(props.code || ""), | ||
code = _useState[0], | ||
setCode = _useState[1]; | ||
React.useEffect(function () { | ||
setCode(props.code); | ||
}, [props.code]); | ||
var onEditableChange = React.useCallback(function (_code) { | ||
setCode(_code.slice(0, -1)); | ||
}, []); | ||
useEditable(editorRef, onEditableChange, { | ||
disabled: props.disabled, | ||
indentation: props.tabMode === "indentation" ? 2 : undefined | ||
}); | ||
React.useEffect(function () { | ||
if (props.onChange) { | ||
props.onChange(code); | ||
} | ||
}, [code]); | ||
return /*#__PURE__*/React__default['default'].createElement("div", { | ||
className: props.className, | ||
style: props.style | ||
}, /*#__PURE__*/React__default['default'].createElement(Highlight__default['default'], { | ||
Prism: props.prism || Highlight.Prism, | ||
code: code, | ||
theme: props.theme || theme, | ||
language: props.language | ||
}, function (_ref) { | ||
var _className = _ref.className, | ||
tokens = _ref.tokens, | ||
getLineProps = _ref.getLineProps, | ||
getTokenProps = _ref.getTokenProps, | ||
_style = _ref.style, | ||
_theme = _ref.theme; | ||
return /*#__PURE__*/React__default['default'].createElement("pre", { | ||
className: _className, | ||
style: _objectSpread$2(_objectSpread$2({ | ||
margin: 0, | ||
outline: "none", | ||
padding: 10, | ||
fontFamily: "inherit" | ||
}, _theme && typeof _theme.plain === "object" ? _theme.plain : {}), _style), | ||
ref: editorRef, | ||
spellCheck: "false" | ||
}, tokens.map(function (line, lineIndex) { | ||
return ( | ||
/*#__PURE__*/ | ||
// eslint-disable-next-line react/jsx-key | ||
React__default['default'].createElement("div", getLineProps({ | ||
line: line, | ||
key: "line-" + lineIndex | ||
}), line.filter(function (token) { | ||
return !token.empty; | ||
}).map(function (token, tokenIndex) { | ||
return ( | ||
/*#__PURE__*/ | ||
// eslint-disable-next-line react/jsx-key | ||
React__default['default'].createElement("span", getTokenProps({ | ||
token: token, | ||
key: "token-" + tokenIndex | ||
})) | ||
); | ||
}), "\n") | ||
); | ||
})); | ||
})); | ||
const CodeEditor = (props) => { | ||
const editorRef = React.useRef(null); | ||
const [code, setCode] = React.useState(props.code || ""); | ||
React.useEffect(() => { | ||
setCode(props.code); | ||
}, [props.code]); | ||
const onEditableChange = React.useCallback((_code) => { | ||
setCode(_code.slice(0, -1)); | ||
}, []); | ||
useEditable(editorRef, onEditableChange, { | ||
disabled: props.disabled, | ||
indentation: props.tabMode === "indentation" ? 2 : undefined, | ||
}); | ||
React.useEffect(() => { | ||
if (props.onChange) { | ||
props.onChange(code); | ||
} | ||
}, [code]); | ||
return (jsxRuntime.jsx("div", Object.assign({ className: props.className, style: props.style }, { children: jsxRuntime.jsx(Highlight__default['default'], Object.assign({ Prism: props.prism || Highlight.Prism, code: code, theme: props.theme || theme, language: props.language }, { children: ({ className: _className, tokens, getLineProps, getTokenProps, style: _style, | ||
/* @ts-ignore — this property exists but the lib's types are incorrect */ | ||
theme: _theme, }) => (jsxRuntime.jsx("pre", Object.assign({ className: _className, style: Object.assign(Object.assign({ margin: 0, outline: "none", padding: 10, fontFamily: "inherit" }, (_theme && typeof _theme.plain === "object" | ||
? _theme.plain | ||
: {})), _style), ref: editorRef, spellCheck: "false" }, { children: tokens.map((line, lineIndex) => ( | ||
// eslint-disable-next-line react/jsx-key | ||
jsxRuntime.jsxs("div", Object.assign({}, getLineProps({ line, key: `line-${lineIndex}` }), { children: [line | ||
.filter((token) => !token.empty) | ||
.map((token, tokenIndex) => ( | ||
// eslint-disable-next-line react/jsx-key | ||
jsxRuntime.jsx("span", Object.assign({}, getTokenProps({ token, key: `token-${tokenIndex}` }))))), "\n"] })))) }))) })) }))); | ||
}; | ||
CodeEditor.defaultProps = { | ||
tabMode: "indentation" | ||
tabMode: "indentation", | ||
}; | ||
var Editor = CodeEditor; | ||
var LiveContext = /*#__PURE__*/React.createContext({}); | ||
var LiveContext$1 = LiveContext; | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
var opts = { | ||
transforms: ["jsx", "imports"] | ||
}; | ||
var transform = (function (code) { | ||
return sucrase.transform(code, opts).code; | ||
}); | ||
Permission to use, copy, modify, and/or distribute this software for any | ||
purpose with or without fee is hereby granted. | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | ||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | ||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | ||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | ||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | ||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */ | ||
function __rest(s, e) { | ||
var t = {}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
for (var p in s) { | ||
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; | ||
} | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
_setPrototypeOf(subClass, superClass); | ||
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { | ||
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; | ||
} | ||
return t; | ||
} | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
function adopt(value) { | ||
return value instanceof P ? value : new P(function (resolve) { | ||
resolve(value); | ||
}); | ||
} | ||
var errorBoundary = function errorBoundary(Element, errorCallback) { | ||
return /*#__PURE__*/function (_Component) { | ||
_inheritsLoose(ErrorBoundary, _Component); | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { | ||
try { | ||
step(generator.next(value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
function ErrorBoundary() { | ||
return _Component.apply(this, arguments) || this; | ||
function rejected(value) { | ||
try { | ||
step(generator["throw"](value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
var _proto = ErrorBoundary.prototype; | ||
function step(result) { | ||
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); | ||
} | ||
_proto.componentDidCatch = function componentDidCatch(error) { | ||
errorCallback(error); | ||
}; | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
} | ||
_proto.render = function render() { | ||
return typeof Element === "function" ? /*#__PURE__*/React__default['default'].createElement(Element, null) : /*#__PURE__*/React__default['default'].isValidElement(Element) ? Element : null; | ||
}; | ||
const LiveContext = React.createContext({}); | ||
return ErrorBoundary; | ||
}(React.Component); | ||
}; | ||
var errorBoundary$1 = errorBoundary; | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
try { | ||
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
const defaultTransforms = ["jsx", "imports"]; | ||
function transform(opts = {}) { | ||
const transforms = (Array.isArray(opts.transforms) | ||
? opts.transforms.filter(Boolean) | ||
: defaultTransforms); | ||
return (code) => sucrase.transform(code, { transforms }).code; | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct; | ||
} else { | ||
_construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) _setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
const errorBoundary = (Element, errorCallback) => { | ||
return class ErrorBoundary extends React.Component { | ||
componentDidCatch(error) { | ||
errorCallback(error); | ||
} | ||
render() { | ||
return typeof Element === "function" ? (jsxRuntime.jsx(Element, {})) : React__default['default'].isValidElement(Element) ? (Element) : null; | ||
} | ||
}; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
var evalCode = function evalCode(code, scope) { | ||
var scopeKeys = Object.keys(scope); | ||
var scopeValues = scopeKeys.map(function (key) { | ||
return scope[key]; | ||
}); | ||
return _construct(Function, scopeKeys.concat([code])).apply(void 0, scopeValues); | ||
}; | ||
var evalCode$1 = evalCode; | ||
function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
var generateElement = function generateElement(_ref, errorCallback) { | ||
var _ref$code = _ref.code, | ||
code = _ref$code === void 0 ? "" : _ref$code, | ||
_ref$scope = _ref.scope, | ||
scope = _ref$scope === void 0 ? {} : _ref$scope; | ||
// NOTE: Remove trailing semicolon to get an actual expression. | ||
var codeTrimmed = code.trim().replace(/;$/, ""); // NOTE: Workaround for classes and arrow functions. | ||
var transformed = transform("return (" + codeTrimmed + ")").trim(); | ||
return errorBoundary$1(evalCode$1(transformed, _objectSpread$1({ | ||
React: React__default['default'] | ||
}, scope)), errorCallback); | ||
const evalCode = (code, scope) => { | ||
const scopeKeys = Object.keys(scope); | ||
const scopeValues = scopeKeys.map((key) => scope[key]); | ||
return new Function(...scopeKeys, code)(...scopeValues); | ||
}; | ||
var renderElementAsync = function renderElementAsync(_ref2, resultCallback, errorCallback // eslint-disable-next-line consistent-return | ||
) { | ||
var _ref2$code = _ref2.code, | ||
code = _ref2$code === void 0 ? "" : _ref2$code, | ||
_ref2$scope = _ref2.scope, | ||
scope = _ref2$scope === void 0 ? {} : _ref2$scope; | ||
var render = function render(element) { | ||
if (typeof element === "undefined") { | ||
errorCallback(new SyntaxError("`render` must be called with valid JSX.")); | ||
} else { | ||
resultCallback(errorBoundary$1(element, errorCallback)); | ||
} | ||
}; | ||
/** | ||
* Creates a new composite function that invokes the functions from right to left | ||
*/ | ||
function compose(...functions) { | ||
return functions.reduce((acc, currentFn) => (...args) => acc(currentFn(...args))); | ||
} | ||
if (!/render\s*\(/.test(code)) { | ||
return errorCallback(new SyntaxError("No-Inline evaluations must call `render`.")); | ||
} | ||
evalCode$1(transform(code), _objectSpread$1(_objectSpread$1({ | ||
React: React__default['default'] | ||
}, scope), {}, { | ||
render: render | ||
})); | ||
const jsxConst = 'const _jsxFileName = "";'; | ||
const trimCode = (code) => code.trim().replace(/;$/, ""); | ||
const spliceJsxConst = (code) => code.replace(jsxConst, "").trim(); | ||
const addJsxConst = (code) => jsxConst + code; | ||
const wrapReturn = (code) => `return (${code})`; | ||
const generateElement = ({ code = "", scope = {}, enableTypeScript = true }, errorCallback) => { | ||
/** | ||
* To enable TypeScript we need to transform the TS to JS code first, | ||
* splice off the JSX const, wrap the eval in a return statement, then | ||
* transform any imports. The two-phase approach is required to do | ||
* the implicit evaluation and not wrap leading Interface or Type | ||
* statements in the return. | ||
*/ | ||
const firstPassTransforms = ["jsx"]; | ||
enableTypeScript && firstPassTransforms.push("typescript"); | ||
const transformed = compose(addJsxConst, transform({ transforms: ["imports"] }), wrapReturn, spliceJsxConst, trimCode, transform({ transforms: firstPassTransforms }), trimCode)(code); | ||
return errorBoundary(evalCode(transformed, Object.assign({ React: React__default['default'] }, scope)), errorCallback); | ||
}; | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
function LiveProvider(_ref) { | ||
var children = _ref.children, | ||
code = _ref.code, | ||
language = _ref.language, | ||
theme = _ref.theme, | ||
disabled = _ref.disabled, | ||
scope = _ref.scope, | ||
transformCode = _ref.transformCode, | ||
_ref$noInline = _ref.noInline, | ||
noInline = _ref$noInline === void 0 ? false : _ref$noInline; | ||
var _useState = React.useState({ | ||
error: undefined, | ||
element: undefined | ||
}), | ||
state = _useState[0], | ||
setState = _useState[1]; | ||
function transpileAsync(newCode) { | ||
var errorCallback = function errorCallback(error) { | ||
setState({ | ||
error: error.toString(), | ||
element: undefined | ||
}); | ||
}; // - transformCode may be synchronous or asynchronous. | ||
// - transformCode may throw an exception or return a rejected promise, e.g. | ||
// if newCode is invalid and cannot be transformed. | ||
// - Not using async-await to since it requires targeting ES 2017 or | ||
// importing regenerator-runtime... in the next major version of | ||
// react-live, should target ES 2017+ | ||
try { | ||
var transformResult = transformCode ? transformCode(newCode) : newCode; | ||
return Promise.resolve(transformResult).then(function (transformedCode) { | ||
var renderElement = function renderElement(element) { | ||
return setState({ | ||
error: undefined, | ||
element: element | ||
}); | ||
}; // Transpilation arguments | ||
var input = { | ||
code: transformedCode, | ||
scope: scope | ||
}; | ||
if (noInline) { | ||
setState({ | ||
error: undefined, | ||
element: null | ||
}); // Reset output for async (no inline) evaluation | ||
renderElementAsync(input, renderElement, errorCallback); | ||
} else { | ||
renderElement(generateElement(input, errorCallback)); | ||
const renderElementAsync = ({ code = "", scope = {}, enableTypeScript = true }, resultCallback, errorCallback | ||
// eslint-disable-next-line consistent-return | ||
) => { | ||
const render = (element) => { | ||
if (typeof element === "undefined") { | ||
errorCallback(new SyntaxError("`render` must be called with valid JSX.")); | ||
} | ||
})["catch"](errorCallback); | ||
} catch (e) { | ||
errorCallback(e); | ||
return Promise.resolve(); | ||
else { | ||
resultCallback(errorBoundary(element, errorCallback)); | ||
} | ||
}; | ||
if (!/render\s*\(/.test(code)) { | ||
return errorCallback(new SyntaxError("No-Inline evaluations must call `render`.")); | ||
} | ||
} | ||
const transforms = ["jsx", "imports"]; | ||
enableTypeScript && transforms.splice(1, 0, "typescript"); | ||
evalCode(transform({ transforms })(code), Object.assign(Object.assign({ React: React__default['default'] }, scope), { render })); | ||
}; | ||
var onError = function onError(error) { | ||
return setState({ | ||
error: error.toString() | ||
function LiveProvider({ children, code = "", language = "tsx", theme, enableTypeScript = true, disabled = false, scope, transformCode, noInline = false, }) { | ||
const [state, setState] = React.useState({ | ||
error: undefined, | ||
element: undefined, | ||
}); | ||
}; | ||
React.useEffect(function () { | ||
transpileAsync(code)["catch"](onError); | ||
}, [code, scope, noInline, transformCode]); | ||
var onChange = function onChange(newCode) { | ||
transpileAsync(newCode)["catch"](onError); | ||
}; | ||
return /*#__PURE__*/React__default['default'].createElement(LiveContext$1.Provider, { | ||
value: _objectSpread(_objectSpread({}, state), {}, { | ||
code: code, | ||
language: language, | ||
theme: theme, | ||
disabled: disabled, | ||
onError: onError, | ||
onChange: onChange | ||
}) | ||
}, children); | ||
} | ||
LiveProvider.defaultProps = { | ||
code: "", | ||
noInline: false, | ||
language: "jsx", | ||
disabled: false | ||
}; | ||
function _extends() { | ||
_extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
function transpileAsync(newCode) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const errorCallback = (error) => { | ||
setState({ error: error.toString(), element: undefined }); | ||
}; | ||
// - transformCode may be synchronous or asynchronous. | ||
// - transformCode may throw an exception or return a rejected promise, e.g. | ||
// if newCode is invalid and cannot be transformed. | ||
// - Not using async-await to since it requires targeting ES 2017 or | ||
// importing regenerator-runtime... in the next major version of | ||
// react-live, should target ES 2017+ | ||
try { | ||
const transformResult = transformCode ? transformCode(newCode) : newCode; | ||
try { | ||
const transformedCode = yield Promise.resolve(transformResult); | ||
const renderElement = (element) => setState({ error: undefined, element }); | ||
if (typeof transformedCode !== "string") { | ||
throw new Error("Code failed to transform"); | ||
} | ||
// Transpilation arguments | ||
const input = { | ||
code: transformedCode, | ||
scope, | ||
enableTypeScript, | ||
}; | ||
if (noInline) { | ||
setState({ error: undefined, element: null }); // Reset output for async (no inline) evaluation | ||
renderElementAsync(input, renderElement, errorCallback); | ||
} | ||
else { | ||
renderElement(generateElement(input, errorCallback)); | ||
} | ||
} | ||
catch (error) { | ||
return errorCallback(error); | ||
} | ||
} | ||
catch (e) { | ||
errorCallback(e); | ||
return Promise.resolve(); | ||
} | ||
}); | ||
} | ||
return target; | ||
}; | ||
return _extends.apply(this, arguments); | ||
const onError = (error) => setState({ error: error.toString() }); | ||
React.useEffect(() => { | ||
transpileAsync(code).catch(onError); | ||
}, [code, scope, noInline, transformCode]); | ||
const onChange = (newCode) => { | ||
transpileAsync(newCode).catch(onError); | ||
}; | ||
return (jsxRuntime.jsx(LiveContext.Provider, Object.assign({ value: Object.assign(Object.assign({}, state), { code, | ||
language, | ||
theme, | ||
disabled, | ||
onError, | ||
onChange }) }, { children: children }))); | ||
} | ||
function LiveEditor(props) { | ||
var _useContext = React.useContext(LiveContext$1), | ||
code = _useContext.code, | ||
language = _useContext.language, | ||
theme = _useContext.theme, | ||
disabled = _useContext.disabled, | ||
onChange = _useContext.onChange; | ||
return /*#__PURE__*/React__default['default'].createElement(Editor, _extends({ | ||
theme: theme, | ||
code: code, | ||
language: language, | ||
disabled: disabled, | ||
onChange: onChange | ||
}, props)); | ||
const { code, language, theme, disabled, onChange } = React.useContext(LiveContext); | ||
return (jsxRuntime.jsx(CodeEditor, Object.assign({ theme: theme, code: code, language: language, disabled: disabled, onChange: onChange }, props))); | ||
} | ||
function LiveError(props) { | ||
var _useContext = React.useContext(LiveContext$1), | ||
error = _useContext.error; | ||
return error ? /*#__PURE__*/React__default['default'].createElement("pre", props, error) : null; | ||
const { error } = React.useContext(LiveContext); | ||
return error ? jsxRuntime.jsx("pre", Object.assign({}, props, { children: error })) : null; | ||
} | ||
function _objectWithoutPropertiesLoose(source, excluded) { | ||
if (source == null) return {}; | ||
var target = {}; | ||
var sourceKeys = Object.keys(source); | ||
var key, i; | ||
for (i = 0; i < sourceKeys.length; i++) { | ||
key = sourceKeys[i]; | ||
if (excluded.indexOf(key) >= 0) continue; | ||
target[key] = source[key]; | ||
} | ||
return target; | ||
const fallbackComponent = (props) => jsxRuntime.jsx("div", Object.assign({}, props)); | ||
function LivePreview(_a) { | ||
var { Component = fallbackComponent } = _a, rest = __rest(_a, ["Component"]); | ||
const { element: Element } = React.useContext(LiveContext); | ||
return jsxRuntime.jsx(Component, Object.assign({}, rest, { children: Element ? jsxRuntime.jsx(Element, {}) : null })); | ||
} | ||
var _excluded = ["Component"]; | ||
function LivePreview(_ref) { | ||
var Component = _ref.Component, | ||
rest = _objectWithoutPropertiesLoose(_ref, _excluded); | ||
var _useContext = React.useContext(LiveContext$1), | ||
Element = _useContext.element; | ||
return /*#__PURE__*/React__default['default'].createElement(Component, rest, Element ? /*#__PURE__*/React__default['default'].createElement(Element, null) : null); | ||
} | ||
LivePreview.defaultProps = { | ||
Component: "div" | ||
}; | ||
function withLive(WrappedComponent) { | ||
var WithLive = /*#__PURE__*/function (_Component) { | ||
_inheritsLoose(WithLive, _Component); | ||
function WithLive() { | ||
return _Component.apply(this, arguments) || this; | ||
} | ||
var _proto = WithLive.prototype; | ||
_proto.render = function render() { | ||
var _this = this; | ||
return /*#__PURE__*/React__default['default'].createElement(LiveContext$1.Consumer, null, function (live) { | ||
return /*#__PURE__*/React__default['default'].createElement(WrappedComponent, _extends({ | ||
live: live | ||
}, _this.props)); | ||
}); | ||
}; | ||
const WithLive = (props) => (jsxRuntime.jsx(LiveContext.Consumer, { children: (live) => jsxRuntime.jsx(WrappedComponent, Object.assign({ live: live }, props)) })); | ||
WithLive.displayName = "WithLive"; | ||
return WithLive; | ||
}(React.Component); | ||
return WithLive; | ||
} | ||
exports.Editor = Editor; | ||
exports.LiveContext = LiveContext$1; | ||
exports.Editor = CodeEditor; | ||
exports.LiveContext = LiveContext; | ||
exports.LiveEditor = LiveEditor; | ||
@@ -836,0 +675,0 @@ exports.LiveError = LiveError; |
@@ -0,1 +1,2 @@ | ||
import { jsx, jsxs } from 'react/jsx-runtime'; | ||
import Highlight, { Prism } from 'prism-react-renderer'; | ||
@@ -5,17 +6,2 @@ import React, { useState, useMemo, useLayoutEffect, useRef, useEffect, useCallback, createContext, Component, useContext } from 'react'; | ||
function _defineProperty(obj, key, value) { | ||
if (key in obj) { | ||
Object.defineProperty(obj, key, { | ||
value: value, | ||
enumerable: true, | ||
configurable: true, | ||
writable: true | ||
}); | ||
} else { | ||
obj[key] = value; | ||
} | ||
return obj; | ||
} | ||
var m = { | ||
@@ -352,472 +338,325 @@ characterData: !0, | ||
var theme = { | ||
plain: { | ||
color: "#C5C8C6", | ||
backgroundColor: "#1D1F21" | ||
}, | ||
styles: [{ | ||
types: ["prolog", "comment", "doctype", "cdata"], | ||
style: { | ||
color: "hsl(30, 20%, 50%)" | ||
} | ||
}, { | ||
types: ["property", "tag", "boolean", "number", "constant", "symbol"], | ||
style: { | ||
color: "hsl(350, 40%, 70%)" | ||
} | ||
}, { | ||
types: ["attr-name", "string", "char", "builtin", "insterted"], | ||
style: { | ||
color: "hsl(75, 70%, 60%)" | ||
} | ||
}, { | ||
types: ["operator", "entity", "url", "string", "variable", "language-css"], | ||
style: { | ||
color: "hsl(40, 90%, 60%)" | ||
} | ||
}, { | ||
types: ["deleted"], | ||
style: { | ||
color: "rgb(255, 85, 85)" | ||
} | ||
}, { | ||
types: ["italic"], | ||
style: { | ||
fontStyle: "italic" | ||
} | ||
}, { | ||
types: ["important", "bold"], | ||
style: { | ||
fontWeight: "bold" | ||
} | ||
}, { | ||
types: ["regex", "important"], | ||
style: { | ||
color: "#e90" | ||
} | ||
}, { | ||
types: ["atrule", "attr-value", "keyword"], | ||
style: { | ||
color: "hsl(350, 40%, 70%)" | ||
} | ||
}, { | ||
types: ["punctuation", "symbol"], | ||
style: { | ||
opacity: "0.7" | ||
} | ||
}] | ||
const theme = { | ||
plain: { | ||
color: "#C5C8C6", | ||
backgroundColor: "#1D1F21", | ||
}, | ||
styles: [ | ||
{ | ||
types: ["prolog", "comment", "doctype", "cdata"], | ||
style: { | ||
color: "hsl(30, 20%, 50%)", | ||
}, | ||
}, | ||
{ | ||
types: ["property", "tag", "boolean", "number", "constant", "symbol"], | ||
style: { color: "hsl(350, 40%, 70%)" }, | ||
}, | ||
{ | ||
types: ["attr-name", "string", "char", "builtin", "insterted"], | ||
style: { | ||
color: "hsl(75, 70%, 60%)", | ||
}, | ||
}, | ||
{ | ||
types: [ | ||
"operator", | ||
"entity", | ||
"url", | ||
"string", | ||
"variable", | ||
"language-css", | ||
], | ||
style: { | ||
color: "hsl(40, 90%, 60%)", | ||
}, | ||
}, | ||
{ | ||
types: ["deleted"], | ||
style: { | ||
color: "rgb(255, 85, 85)", | ||
}, | ||
}, | ||
{ | ||
types: ["italic"], | ||
style: { | ||
fontStyle: "italic", | ||
}, | ||
}, | ||
{ | ||
types: ["important", "bold"], | ||
style: { | ||
fontWeight: "bold", | ||
}, | ||
}, | ||
{ | ||
types: ["regex", "important"], | ||
style: { | ||
color: "#e90", | ||
}, | ||
}, | ||
{ | ||
types: ["atrule", "attr-value", "keyword"], | ||
style: { | ||
color: "hsl(350, 40%, 70%)", | ||
}, | ||
}, | ||
{ | ||
types: ["punctuation", "symbol"], | ||
style: { | ||
opacity: 0.7, | ||
}, | ||
}, | ||
], | ||
}; | ||
function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
var CodeEditor = function CodeEditor(props) { | ||
var editorRef = useRef(null); | ||
var _useState = useState(props.code || ""), | ||
code = _useState[0], | ||
setCode = _useState[1]; | ||
useEffect(function () { | ||
setCode(props.code); | ||
}, [props.code]); | ||
var onEditableChange = useCallback(function (_code) { | ||
setCode(_code.slice(0, -1)); | ||
}, []); | ||
useEditable(editorRef, onEditableChange, { | ||
disabled: props.disabled, | ||
indentation: props.tabMode === "indentation" ? 2 : undefined | ||
}); | ||
useEffect(function () { | ||
if (props.onChange) { | ||
props.onChange(code); | ||
} | ||
}, [code]); | ||
return /*#__PURE__*/React.createElement("div", { | ||
className: props.className, | ||
style: props.style | ||
}, /*#__PURE__*/React.createElement(Highlight, { | ||
Prism: props.prism || Prism, | ||
code: code, | ||
theme: props.theme || theme, | ||
language: props.language | ||
}, function (_ref) { | ||
var _className = _ref.className, | ||
tokens = _ref.tokens, | ||
getLineProps = _ref.getLineProps, | ||
getTokenProps = _ref.getTokenProps, | ||
_style = _ref.style, | ||
_theme = _ref.theme; | ||
return /*#__PURE__*/React.createElement("pre", { | ||
className: _className, | ||
style: _objectSpread$2(_objectSpread$2({ | ||
margin: 0, | ||
outline: "none", | ||
padding: 10, | ||
fontFamily: "inherit" | ||
}, _theme && typeof _theme.plain === "object" ? _theme.plain : {}), _style), | ||
ref: editorRef, | ||
spellCheck: "false" | ||
}, tokens.map(function (line, lineIndex) { | ||
return ( | ||
/*#__PURE__*/ | ||
// eslint-disable-next-line react/jsx-key | ||
React.createElement("div", getLineProps({ | ||
line: line, | ||
key: "line-" + lineIndex | ||
}), line.filter(function (token) { | ||
return !token.empty; | ||
}).map(function (token, tokenIndex) { | ||
return ( | ||
/*#__PURE__*/ | ||
// eslint-disable-next-line react/jsx-key | ||
React.createElement("span", getTokenProps({ | ||
token: token, | ||
key: "token-" + tokenIndex | ||
})) | ||
); | ||
}), "\n") | ||
); | ||
})); | ||
})); | ||
const CodeEditor = (props) => { | ||
const editorRef = useRef(null); | ||
const [code, setCode] = useState(props.code || ""); | ||
useEffect(() => { | ||
setCode(props.code); | ||
}, [props.code]); | ||
const onEditableChange = useCallback((_code) => { | ||
setCode(_code.slice(0, -1)); | ||
}, []); | ||
useEditable(editorRef, onEditableChange, { | ||
disabled: props.disabled, | ||
indentation: props.tabMode === "indentation" ? 2 : undefined, | ||
}); | ||
useEffect(() => { | ||
if (props.onChange) { | ||
props.onChange(code); | ||
} | ||
}, [code]); | ||
return (jsx("div", Object.assign({ className: props.className, style: props.style }, { children: jsx(Highlight, Object.assign({ Prism: props.prism || Prism, code: code, theme: props.theme || theme, language: props.language }, { children: ({ className: _className, tokens, getLineProps, getTokenProps, style: _style, | ||
/* @ts-ignore — this property exists but the lib's types are incorrect */ | ||
theme: _theme, }) => (jsx("pre", Object.assign({ className: _className, style: Object.assign(Object.assign({ margin: 0, outline: "none", padding: 10, fontFamily: "inherit" }, (_theme && typeof _theme.plain === "object" | ||
? _theme.plain | ||
: {})), _style), ref: editorRef, spellCheck: "false" }, { children: tokens.map((line, lineIndex) => ( | ||
// eslint-disable-next-line react/jsx-key | ||
jsxs("div", Object.assign({}, getLineProps({ line, key: `line-${lineIndex}` }), { children: [line | ||
.filter((token) => !token.empty) | ||
.map((token, tokenIndex) => ( | ||
// eslint-disable-next-line react/jsx-key | ||
jsx("span", Object.assign({}, getTokenProps({ token, key: `token-${tokenIndex}` }))))), "\n"] })))) }))) })) }))); | ||
}; | ||
CodeEditor.defaultProps = { | ||
tabMode: "indentation" | ||
tabMode: "indentation", | ||
}; | ||
var Editor = CodeEditor; | ||
var LiveContext = /*#__PURE__*/createContext({}); | ||
var LiveContext$1 = LiveContext; | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
var opts = { | ||
transforms: ["jsx", "imports"] | ||
}; | ||
var transform = (function (code) { | ||
return transform$1(code, opts).code; | ||
}); | ||
Permission to use, copy, modify, and/or distribute this software for any | ||
purpose with or without fee is hereby granted. | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | ||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | ||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | ||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | ||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | ||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */ | ||
function __rest(s, e) { | ||
var t = {}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
for (var p in s) { | ||
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; | ||
} | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
_setPrototypeOf(subClass, superClass); | ||
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { | ||
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; | ||
} | ||
return t; | ||
} | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
function adopt(value) { | ||
return value instanceof P ? value : new P(function (resolve) { | ||
resolve(value); | ||
}); | ||
} | ||
var errorBoundary = function errorBoundary(Element, errorCallback) { | ||
return /*#__PURE__*/function (_Component) { | ||
_inheritsLoose(ErrorBoundary, _Component); | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { | ||
try { | ||
step(generator.next(value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
function ErrorBoundary() { | ||
return _Component.apply(this, arguments) || this; | ||
function rejected(value) { | ||
try { | ||
step(generator["throw"](value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
var _proto = ErrorBoundary.prototype; | ||
function step(result) { | ||
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); | ||
} | ||
_proto.componentDidCatch = function componentDidCatch(error) { | ||
errorCallback(error); | ||
}; | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
} | ||
_proto.render = function render() { | ||
return typeof Element === "function" ? /*#__PURE__*/React.createElement(Element, null) : /*#__PURE__*/React.isValidElement(Element) ? Element : null; | ||
}; | ||
const LiveContext = createContext({}); | ||
return ErrorBoundary; | ||
}(Component); | ||
}; | ||
var errorBoundary$1 = errorBoundary; | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
try { | ||
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
const defaultTransforms = ["jsx", "imports"]; | ||
function transform(opts = {}) { | ||
const transforms = (Array.isArray(opts.transforms) | ||
? opts.transforms.filter(Boolean) | ||
: defaultTransforms); | ||
return (code) => transform$1(code, { transforms }).code; | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct; | ||
} else { | ||
_construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) _setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
const errorBoundary = (Element, errorCallback) => { | ||
return class ErrorBoundary extends Component { | ||
componentDidCatch(error) { | ||
errorCallback(error); | ||
} | ||
render() { | ||
return typeof Element === "function" ? (jsx(Element, {})) : React.isValidElement(Element) ? (Element) : null; | ||
} | ||
}; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
var evalCode = function evalCode(code, scope) { | ||
var scopeKeys = Object.keys(scope); | ||
var scopeValues = scopeKeys.map(function (key) { | ||
return scope[key]; | ||
}); | ||
return _construct(Function, scopeKeys.concat([code])).apply(void 0, scopeValues); | ||
}; | ||
var evalCode$1 = evalCode; | ||
function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
var generateElement = function generateElement(_ref, errorCallback) { | ||
var _ref$code = _ref.code, | ||
code = _ref$code === void 0 ? "" : _ref$code, | ||
_ref$scope = _ref.scope, | ||
scope = _ref$scope === void 0 ? {} : _ref$scope; | ||
// NOTE: Remove trailing semicolon to get an actual expression. | ||
var codeTrimmed = code.trim().replace(/;$/, ""); // NOTE: Workaround for classes and arrow functions. | ||
var transformed = transform("return (" + codeTrimmed + ")").trim(); | ||
return errorBoundary$1(evalCode$1(transformed, _objectSpread$1({ | ||
React: React | ||
}, scope)), errorCallback); | ||
const evalCode = (code, scope) => { | ||
const scopeKeys = Object.keys(scope); | ||
const scopeValues = scopeKeys.map((key) => scope[key]); | ||
return new Function(...scopeKeys, code)(...scopeValues); | ||
}; | ||
var renderElementAsync = function renderElementAsync(_ref2, resultCallback, errorCallback // eslint-disable-next-line consistent-return | ||
) { | ||
var _ref2$code = _ref2.code, | ||
code = _ref2$code === void 0 ? "" : _ref2$code, | ||
_ref2$scope = _ref2.scope, | ||
scope = _ref2$scope === void 0 ? {} : _ref2$scope; | ||
var render = function render(element) { | ||
if (typeof element === "undefined") { | ||
errorCallback(new SyntaxError("`render` must be called with valid JSX.")); | ||
} else { | ||
resultCallback(errorBoundary$1(element, errorCallback)); | ||
} | ||
}; | ||
/** | ||
* Creates a new composite function that invokes the functions from right to left | ||
*/ | ||
function compose(...functions) { | ||
return functions.reduce((acc, currentFn) => (...args) => acc(currentFn(...args))); | ||
} | ||
if (!/render\s*\(/.test(code)) { | ||
return errorCallback(new SyntaxError("No-Inline evaluations must call `render`.")); | ||
} | ||
evalCode$1(transform(code), _objectSpread$1(_objectSpread$1({ | ||
React: React | ||
}, scope), {}, { | ||
render: render | ||
})); | ||
const jsxConst = 'const _jsxFileName = "";'; | ||
const trimCode = (code) => code.trim().replace(/;$/, ""); | ||
const spliceJsxConst = (code) => code.replace(jsxConst, "").trim(); | ||
const addJsxConst = (code) => jsxConst + code; | ||
const wrapReturn = (code) => `return (${code})`; | ||
const generateElement = ({ code = "", scope = {}, enableTypeScript = true }, errorCallback) => { | ||
/** | ||
* To enable TypeScript we need to transform the TS to JS code first, | ||
* splice off the JSX const, wrap the eval in a return statement, then | ||
* transform any imports. The two-phase approach is required to do | ||
* the implicit evaluation and not wrap leading Interface or Type | ||
* statements in the return. | ||
*/ | ||
const firstPassTransforms = ["jsx"]; | ||
enableTypeScript && firstPassTransforms.push("typescript"); | ||
const transformed = compose(addJsxConst, transform({ transforms: ["imports"] }), wrapReturn, spliceJsxConst, trimCode, transform({ transforms: firstPassTransforms }), trimCode)(code); | ||
return errorBoundary(evalCode(transformed, Object.assign({ React }, scope)), errorCallback); | ||
}; | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
function LiveProvider(_ref) { | ||
var children = _ref.children, | ||
code = _ref.code, | ||
language = _ref.language, | ||
theme = _ref.theme, | ||
disabled = _ref.disabled, | ||
scope = _ref.scope, | ||
transformCode = _ref.transformCode, | ||
_ref$noInline = _ref.noInline, | ||
noInline = _ref$noInline === void 0 ? false : _ref$noInline; | ||
var _useState = useState({ | ||
error: undefined, | ||
element: undefined | ||
}), | ||
state = _useState[0], | ||
setState = _useState[1]; | ||
function transpileAsync(newCode) { | ||
var errorCallback = function errorCallback(error) { | ||
setState({ | ||
error: error.toString(), | ||
element: undefined | ||
}); | ||
}; // - transformCode may be synchronous or asynchronous. | ||
// - transformCode may throw an exception or return a rejected promise, e.g. | ||
// if newCode is invalid and cannot be transformed. | ||
// - Not using async-await to since it requires targeting ES 2017 or | ||
// importing regenerator-runtime... in the next major version of | ||
// react-live, should target ES 2017+ | ||
try { | ||
var transformResult = transformCode ? transformCode(newCode) : newCode; | ||
return Promise.resolve(transformResult).then(function (transformedCode) { | ||
var renderElement = function renderElement(element) { | ||
return setState({ | ||
error: undefined, | ||
element: element | ||
}); | ||
}; // Transpilation arguments | ||
var input = { | ||
code: transformedCode, | ||
scope: scope | ||
}; | ||
if (noInline) { | ||
setState({ | ||
error: undefined, | ||
element: null | ||
}); // Reset output for async (no inline) evaluation | ||
renderElementAsync(input, renderElement, errorCallback); | ||
} else { | ||
renderElement(generateElement(input, errorCallback)); | ||
const renderElementAsync = ({ code = "", scope = {}, enableTypeScript = true }, resultCallback, errorCallback | ||
// eslint-disable-next-line consistent-return | ||
) => { | ||
const render = (element) => { | ||
if (typeof element === "undefined") { | ||
errorCallback(new SyntaxError("`render` must be called with valid JSX.")); | ||
} | ||
})["catch"](errorCallback); | ||
} catch (e) { | ||
errorCallback(e); | ||
return Promise.resolve(); | ||
else { | ||
resultCallback(errorBoundary(element, errorCallback)); | ||
} | ||
}; | ||
if (!/render\s*\(/.test(code)) { | ||
return errorCallback(new SyntaxError("No-Inline evaluations must call `render`.")); | ||
} | ||
} | ||
const transforms = ["jsx", "imports"]; | ||
enableTypeScript && transforms.splice(1, 0, "typescript"); | ||
evalCode(transform({ transforms })(code), Object.assign(Object.assign({ React }, scope), { render })); | ||
}; | ||
var onError = function onError(error) { | ||
return setState({ | ||
error: error.toString() | ||
function LiveProvider({ children, code = "", language = "tsx", theme, enableTypeScript = true, disabled = false, scope, transformCode, noInline = false, }) { | ||
const [state, setState] = useState({ | ||
error: undefined, | ||
element: undefined, | ||
}); | ||
}; | ||
useEffect(function () { | ||
transpileAsync(code)["catch"](onError); | ||
}, [code, scope, noInline, transformCode]); | ||
var onChange = function onChange(newCode) { | ||
transpileAsync(newCode)["catch"](onError); | ||
}; | ||
return /*#__PURE__*/React.createElement(LiveContext$1.Provider, { | ||
value: _objectSpread(_objectSpread({}, state), {}, { | ||
code: code, | ||
language: language, | ||
theme: theme, | ||
disabled: disabled, | ||
onError: onError, | ||
onChange: onChange | ||
}) | ||
}, children); | ||
} | ||
LiveProvider.defaultProps = { | ||
code: "", | ||
noInline: false, | ||
language: "jsx", | ||
disabled: false | ||
}; | ||
function _extends() { | ||
_extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
function transpileAsync(newCode) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const errorCallback = (error) => { | ||
setState({ error: error.toString(), element: undefined }); | ||
}; | ||
// - transformCode may be synchronous or asynchronous. | ||
// - transformCode may throw an exception or return a rejected promise, e.g. | ||
// if newCode is invalid and cannot be transformed. | ||
// - Not using async-await to since it requires targeting ES 2017 or | ||
// importing regenerator-runtime... in the next major version of | ||
// react-live, should target ES 2017+ | ||
try { | ||
const transformResult = transformCode ? transformCode(newCode) : newCode; | ||
try { | ||
const transformedCode = yield Promise.resolve(transformResult); | ||
const renderElement = (element) => setState({ error: undefined, element }); | ||
if (typeof transformedCode !== "string") { | ||
throw new Error("Code failed to transform"); | ||
} | ||
// Transpilation arguments | ||
const input = { | ||
code: transformedCode, | ||
scope, | ||
enableTypeScript, | ||
}; | ||
if (noInline) { | ||
setState({ error: undefined, element: null }); // Reset output for async (no inline) evaluation | ||
renderElementAsync(input, renderElement, errorCallback); | ||
} | ||
else { | ||
renderElement(generateElement(input, errorCallback)); | ||
} | ||
} | ||
catch (error) { | ||
return errorCallback(error); | ||
} | ||
} | ||
catch (e) { | ||
errorCallback(e); | ||
return Promise.resolve(); | ||
} | ||
}); | ||
} | ||
return target; | ||
}; | ||
return _extends.apply(this, arguments); | ||
const onError = (error) => setState({ error: error.toString() }); | ||
useEffect(() => { | ||
transpileAsync(code).catch(onError); | ||
}, [code, scope, noInline, transformCode]); | ||
const onChange = (newCode) => { | ||
transpileAsync(newCode).catch(onError); | ||
}; | ||
return (jsx(LiveContext.Provider, Object.assign({ value: Object.assign(Object.assign({}, state), { code, | ||
language, | ||
theme, | ||
disabled, | ||
onError, | ||
onChange }) }, { children: children }))); | ||
} | ||
function LiveEditor(props) { | ||
var _useContext = useContext(LiveContext$1), | ||
code = _useContext.code, | ||
language = _useContext.language, | ||
theme = _useContext.theme, | ||
disabled = _useContext.disabled, | ||
onChange = _useContext.onChange; | ||
return /*#__PURE__*/React.createElement(Editor, _extends({ | ||
theme: theme, | ||
code: code, | ||
language: language, | ||
disabled: disabled, | ||
onChange: onChange | ||
}, props)); | ||
const { code, language, theme, disabled, onChange } = useContext(LiveContext); | ||
return (jsx(CodeEditor, Object.assign({ theme: theme, code: code, language: language, disabled: disabled, onChange: onChange }, props))); | ||
} | ||
function LiveError(props) { | ||
var _useContext = useContext(LiveContext$1), | ||
error = _useContext.error; | ||
return error ? /*#__PURE__*/React.createElement("pre", props, error) : null; | ||
const { error } = useContext(LiveContext); | ||
return error ? jsx("pre", Object.assign({}, props, { children: error })) : null; | ||
} | ||
function _objectWithoutPropertiesLoose(source, excluded) { | ||
if (source == null) return {}; | ||
var target = {}; | ||
var sourceKeys = Object.keys(source); | ||
var key, i; | ||
for (i = 0; i < sourceKeys.length; i++) { | ||
key = sourceKeys[i]; | ||
if (excluded.indexOf(key) >= 0) continue; | ||
target[key] = source[key]; | ||
} | ||
return target; | ||
const fallbackComponent = (props) => jsx("div", Object.assign({}, props)); | ||
function LivePreview(_a) { | ||
var { Component = fallbackComponent } = _a, rest = __rest(_a, ["Component"]); | ||
const { element: Element } = useContext(LiveContext); | ||
return jsx(Component, Object.assign({}, rest, { children: Element ? jsx(Element, {}) : null })); | ||
} | ||
var _excluded = ["Component"]; | ||
function LivePreview(_ref) { | ||
var Component = _ref.Component, | ||
rest = _objectWithoutPropertiesLoose(_ref, _excluded); | ||
var _useContext = useContext(LiveContext$1), | ||
Element = _useContext.element; | ||
return /*#__PURE__*/React.createElement(Component, rest, Element ? /*#__PURE__*/React.createElement(Element, null) : null); | ||
} | ||
LivePreview.defaultProps = { | ||
Component: "div" | ||
}; | ||
function withLive(WrappedComponent) { | ||
var WithLive = /*#__PURE__*/function (_Component) { | ||
_inheritsLoose(WithLive, _Component); | ||
function WithLive() { | ||
return _Component.apply(this, arguments) || this; | ||
} | ||
var _proto = WithLive.prototype; | ||
_proto.render = function render() { | ||
var _this = this; | ||
return /*#__PURE__*/React.createElement(LiveContext$1.Consumer, null, function (live) { | ||
return /*#__PURE__*/React.createElement(WrappedComponent, _extends({ | ||
live: live | ||
}, _this.props)); | ||
}); | ||
}; | ||
const WithLive = (props) => (jsx(LiveContext.Consumer, { children: (live) => jsx(WrappedComponent, Object.assign({ live: live }, props)) })); | ||
WithLive.displayName = "WithLive"; | ||
return WithLive; | ||
}(Component); | ||
return WithLive; | ||
} | ||
export { Editor, LiveContext$1 as LiveContext, LiveEditor, LiveError, LivePreview, LiveProvider, generateElement, renderElementAsync, withLive }; | ||
export { CodeEditor as Editor, LiveContext, LiveEditor, LiveError, LivePreview, LiveProvider, generateElement, renderElementAsync, withLive }; |
(function (global, factory) { | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('prism-react-renderer'), require('react'), require('sucrase')) : | ||
typeof define === 'function' && define.amd ? define(['exports', 'prism-react-renderer', 'react', 'sucrase'], factory) : | ||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactLive = {}, global.Prism, global.React, global.Sucrase)); | ||
}(this, (function (exports, Highlight, React, sucrase) { 'use strict'; | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react/jsx-runtime'), require('prism-react-renderer'), require('react'), require('sucrase')) : | ||
typeof define === 'function' && define.amd ? define(['exports', 'react/jsx-runtime', 'prism-react-renderer', 'react', 'sucrase'], factory) : | ||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactLive = {}, global['jsx-runtime'], global.Prism, global.React, global.Sucrase)); | ||
}(this, (function (exports, jsxRuntime, Highlight, React, sucrase) { 'use strict'; | ||
@@ -12,17 +12,2 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } | ||
function _defineProperty(obj, key, value) { | ||
if (key in obj) { | ||
Object.defineProperty(obj, key, { | ||
value: value, | ||
enumerable: true, | ||
configurable: true, | ||
writable: true | ||
}); | ||
} else { | ||
obj[key] = value; | ||
} | ||
return obj; | ||
} | ||
var m = { | ||
@@ -359,474 +344,327 @@ characterData: !0, | ||
var theme = { | ||
plain: { | ||
color: "#C5C8C6", | ||
backgroundColor: "#1D1F21" | ||
}, | ||
styles: [{ | ||
types: ["prolog", "comment", "doctype", "cdata"], | ||
style: { | ||
color: "hsl(30, 20%, 50%)" | ||
} | ||
}, { | ||
types: ["property", "tag", "boolean", "number", "constant", "symbol"], | ||
style: { | ||
color: "hsl(350, 40%, 70%)" | ||
} | ||
}, { | ||
types: ["attr-name", "string", "char", "builtin", "insterted"], | ||
style: { | ||
color: "hsl(75, 70%, 60%)" | ||
} | ||
}, { | ||
types: ["operator", "entity", "url", "string", "variable", "language-css"], | ||
style: { | ||
color: "hsl(40, 90%, 60%)" | ||
} | ||
}, { | ||
types: ["deleted"], | ||
style: { | ||
color: "rgb(255, 85, 85)" | ||
} | ||
}, { | ||
types: ["italic"], | ||
style: { | ||
fontStyle: "italic" | ||
} | ||
}, { | ||
types: ["important", "bold"], | ||
style: { | ||
fontWeight: "bold" | ||
} | ||
}, { | ||
types: ["regex", "important"], | ||
style: { | ||
color: "#e90" | ||
} | ||
}, { | ||
types: ["atrule", "attr-value", "keyword"], | ||
style: { | ||
color: "hsl(350, 40%, 70%)" | ||
} | ||
}, { | ||
types: ["punctuation", "symbol"], | ||
style: { | ||
opacity: "0.7" | ||
} | ||
}] | ||
const theme = { | ||
plain: { | ||
color: "#C5C8C6", | ||
backgroundColor: "#1D1F21", | ||
}, | ||
styles: [ | ||
{ | ||
types: ["prolog", "comment", "doctype", "cdata"], | ||
style: { | ||
color: "hsl(30, 20%, 50%)", | ||
}, | ||
}, | ||
{ | ||
types: ["property", "tag", "boolean", "number", "constant", "symbol"], | ||
style: { color: "hsl(350, 40%, 70%)" }, | ||
}, | ||
{ | ||
types: ["attr-name", "string", "char", "builtin", "insterted"], | ||
style: { | ||
color: "hsl(75, 70%, 60%)", | ||
}, | ||
}, | ||
{ | ||
types: [ | ||
"operator", | ||
"entity", | ||
"url", | ||
"string", | ||
"variable", | ||
"language-css", | ||
], | ||
style: { | ||
color: "hsl(40, 90%, 60%)", | ||
}, | ||
}, | ||
{ | ||
types: ["deleted"], | ||
style: { | ||
color: "rgb(255, 85, 85)", | ||
}, | ||
}, | ||
{ | ||
types: ["italic"], | ||
style: { | ||
fontStyle: "italic", | ||
}, | ||
}, | ||
{ | ||
types: ["important", "bold"], | ||
style: { | ||
fontWeight: "bold", | ||
}, | ||
}, | ||
{ | ||
types: ["regex", "important"], | ||
style: { | ||
color: "#e90", | ||
}, | ||
}, | ||
{ | ||
types: ["atrule", "attr-value", "keyword"], | ||
style: { | ||
color: "hsl(350, 40%, 70%)", | ||
}, | ||
}, | ||
{ | ||
types: ["punctuation", "symbol"], | ||
style: { | ||
opacity: 0.7, | ||
}, | ||
}, | ||
], | ||
}; | ||
function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
var CodeEditor = function CodeEditor(props) { | ||
var editorRef = React.useRef(null); | ||
var _useState = React.useState(props.code || ""), | ||
code = _useState[0], | ||
setCode = _useState[1]; | ||
React.useEffect(function () { | ||
setCode(props.code); | ||
}, [props.code]); | ||
var onEditableChange = React.useCallback(function (_code) { | ||
setCode(_code.slice(0, -1)); | ||
}, []); | ||
useEditable(editorRef, onEditableChange, { | ||
disabled: props.disabled, | ||
indentation: props.tabMode === "indentation" ? 2 : undefined | ||
}); | ||
React.useEffect(function () { | ||
if (props.onChange) { | ||
props.onChange(code); | ||
} | ||
}, [code]); | ||
return /*#__PURE__*/React__default['default'].createElement("div", { | ||
className: props.className, | ||
style: props.style | ||
}, /*#__PURE__*/React__default['default'].createElement(Highlight__default['default'], { | ||
Prism: props.prism || Highlight.Prism, | ||
code: code, | ||
theme: props.theme || theme, | ||
language: props.language | ||
}, function (_ref) { | ||
var _className = _ref.className, | ||
tokens = _ref.tokens, | ||
getLineProps = _ref.getLineProps, | ||
getTokenProps = _ref.getTokenProps, | ||
_style = _ref.style, | ||
_theme = _ref.theme; | ||
return /*#__PURE__*/React__default['default'].createElement("pre", { | ||
className: _className, | ||
style: _objectSpread$2(_objectSpread$2({ | ||
margin: 0, | ||
outline: "none", | ||
padding: 10, | ||
fontFamily: "inherit" | ||
}, _theme && typeof _theme.plain === "object" ? _theme.plain : {}), _style), | ||
ref: editorRef, | ||
spellCheck: "false" | ||
}, tokens.map(function (line, lineIndex) { | ||
return ( | ||
/*#__PURE__*/ | ||
// eslint-disable-next-line react/jsx-key | ||
React__default['default'].createElement("div", getLineProps({ | ||
line: line, | ||
key: "line-" + lineIndex | ||
}), line.filter(function (token) { | ||
return !token.empty; | ||
}).map(function (token, tokenIndex) { | ||
return ( | ||
/*#__PURE__*/ | ||
// eslint-disable-next-line react/jsx-key | ||
React__default['default'].createElement("span", getTokenProps({ | ||
token: token, | ||
key: "token-" + tokenIndex | ||
})) | ||
); | ||
}), "\n") | ||
); | ||
})); | ||
})); | ||
const CodeEditor = (props) => { | ||
const editorRef = React.useRef(null); | ||
const [code, setCode] = React.useState(props.code || ""); | ||
React.useEffect(() => { | ||
setCode(props.code); | ||
}, [props.code]); | ||
const onEditableChange = React.useCallback((_code) => { | ||
setCode(_code.slice(0, -1)); | ||
}, []); | ||
useEditable(editorRef, onEditableChange, { | ||
disabled: props.disabled, | ||
indentation: props.tabMode === "indentation" ? 2 : undefined, | ||
}); | ||
React.useEffect(() => { | ||
if (props.onChange) { | ||
props.onChange(code); | ||
} | ||
}, [code]); | ||
return (jsxRuntime.jsx("div", Object.assign({ className: props.className, style: props.style }, { children: jsxRuntime.jsx(Highlight__default['default'], Object.assign({ Prism: props.prism || Highlight.Prism, code: code, theme: props.theme || theme, language: props.language }, { children: ({ className: _className, tokens, getLineProps, getTokenProps, style: _style, | ||
/* @ts-ignore — this property exists but the lib's types are incorrect */ | ||
theme: _theme, }) => (jsxRuntime.jsx("pre", Object.assign({ className: _className, style: Object.assign(Object.assign({ margin: 0, outline: "none", padding: 10, fontFamily: "inherit" }, (_theme && typeof _theme.plain === "object" | ||
? _theme.plain | ||
: {})), _style), ref: editorRef, spellCheck: "false" }, { children: tokens.map((line, lineIndex) => ( | ||
// eslint-disable-next-line react/jsx-key | ||
jsxRuntime.jsxs("div", Object.assign({}, getLineProps({ line, key: `line-${lineIndex}` }), { children: [line | ||
.filter((token) => !token.empty) | ||
.map((token, tokenIndex) => ( | ||
// eslint-disable-next-line react/jsx-key | ||
jsxRuntime.jsx("span", Object.assign({}, getTokenProps({ token, key: `token-${tokenIndex}` }))))), "\n"] })))) }))) })) }))); | ||
}; | ||
CodeEditor.defaultProps = { | ||
tabMode: "indentation" | ||
tabMode: "indentation", | ||
}; | ||
var Editor = CodeEditor; | ||
var LiveContext = /*#__PURE__*/React.createContext({}); | ||
var LiveContext$1 = LiveContext; | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
var opts = { | ||
transforms: ["jsx", "imports"] | ||
}; | ||
var transform = (function (code) { | ||
return sucrase.transform(code, opts).code; | ||
}); | ||
Permission to use, copy, modify, and/or distribute this software for any | ||
purpose with or without fee is hereby granted. | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | ||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | ||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | ||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | ||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | ||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */ | ||
function __rest(s, e) { | ||
var t = {}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
for (var p in s) { | ||
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; | ||
} | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
_setPrototypeOf(subClass, superClass); | ||
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { | ||
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; | ||
} | ||
return t; | ||
} | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
function adopt(value) { | ||
return value instanceof P ? value : new P(function (resolve) { | ||
resolve(value); | ||
}); | ||
} | ||
var errorBoundary = function errorBoundary(Element, errorCallback) { | ||
return /*#__PURE__*/function (_Component) { | ||
_inheritsLoose(ErrorBoundary, _Component); | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { | ||
try { | ||
step(generator.next(value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
function ErrorBoundary() { | ||
return _Component.apply(this, arguments) || this; | ||
function rejected(value) { | ||
try { | ||
step(generator["throw"](value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
var _proto = ErrorBoundary.prototype; | ||
function step(result) { | ||
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); | ||
} | ||
_proto.componentDidCatch = function componentDidCatch(error) { | ||
errorCallback(error); | ||
}; | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
} | ||
_proto.render = function render() { | ||
return typeof Element === "function" ? /*#__PURE__*/React__default['default'].createElement(Element, null) : /*#__PURE__*/React__default['default'].isValidElement(Element) ? Element : null; | ||
}; | ||
const LiveContext = React.createContext({}); | ||
return ErrorBoundary; | ||
}(React.Component); | ||
}; | ||
var errorBoundary$1 = errorBoundary; | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
try { | ||
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
const defaultTransforms = ["jsx", "imports"]; | ||
function transform(opts = {}) { | ||
const transforms = (Array.isArray(opts.transforms) | ||
? opts.transforms.filter(Boolean) | ||
: defaultTransforms); | ||
return (code) => sucrase.transform(code, { transforms }).code; | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct; | ||
} else { | ||
_construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) _setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
const errorBoundary = (Element, errorCallback) => { | ||
return class ErrorBoundary extends React.Component { | ||
componentDidCatch(error) { | ||
errorCallback(error); | ||
} | ||
render() { | ||
return typeof Element === "function" ? (jsxRuntime.jsx(Element, {})) : React__default['default'].isValidElement(Element) ? (Element) : null; | ||
} | ||
}; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
var evalCode = function evalCode(code, scope) { | ||
var scopeKeys = Object.keys(scope); | ||
var scopeValues = scopeKeys.map(function (key) { | ||
return scope[key]; | ||
}); | ||
return _construct(Function, scopeKeys.concat([code])).apply(void 0, scopeValues); | ||
}; | ||
var evalCode$1 = evalCode; | ||
function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
var generateElement = function generateElement(_ref, errorCallback) { | ||
var _ref$code = _ref.code, | ||
code = _ref$code === void 0 ? "" : _ref$code, | ||
_ref$scope = _ref.scope, | ||
scope = _ref$scope === void 0 ? {} : _ref$scope; | ||
// NOTE: Remove trailing semicolon to get an actual expression. | ||
var codeTrimmed = code.trim().replace(/;$/, ""); // NOTE: Workaround for classes and arrow functions. | ||
var transformed = transform("return (" + codeTrimmed + ")").trim(); | ||
return errorBoundary$1(evalCode$1(transformed, _objectSpread$1({ | ||
React: React__default['default'] | ||
}, scope)), errorCallback); | ||
const evalCode = (code, scope) => { | ||
const scopeKeys = Object.keys(scope); | ||
const scopeValues = scopeKeys.map((key) => scope[key]); | ||
return new Function(...scopeKeys, code)(...scopeValues); | ||
}; | ||
var renderElementAsync = function renderElementAsync(_ref2, resultCallback, errorCallback // eslint-disable-next-line consistent-return | ||
) { | ||
var _ref2$code = _ref2.code, | ||
code = _ref2$code === void 0 ? "" : _ref2$code, | ||
_ref2$scope = _ref2.scope, | ||
scope = _ref2$scope === void 0 ? {} : _ref2$scope; | ||
var render = function render(element) { | ||
if (typeof element === "undefined") { | ||
errorCallback(new SyntaxError("`render` must be called with valid JSX.")); | ||
} else { | ||
resultCallback(errorBoundary$1(element, errorCallback)); | ||
} | ||
}; | ||
/** | ||
* Creates a new composite function that invokes the functions from right to left | ||
*/ | ||
function compose(...functions) { | ||
return functions.reduce((acc, currentFn) => (...args) => acc(currentFn(...args))); | ||
} | ||
if (!/render\s*\(/.test(code)) { | ||
return errorCallback(new SyntaxError("No-Inline evaluations must call `render`.")); | ||
} | ||
evalCode$1(transform(code), _objectSpread$1(_objectSpread$1({ | ||
React: React__default['default'] | ||
}, scope), {}, { | ||
render: render | ||
})); | ||
const jsxConst = 'const _jsxFileName = "";'; | ||
const trimCode = (code) => code.trim().replace(/;$/, ""); | ||
const spliceJsxConst = (code) => code.replace(jsxConst, "").trim(); | ||
const addJsxConst = (code) => jsxConst + code; | ||
const wrapReturn = (code) => `return (${code})`; | ||
const generateElement = ({ code = "", scope = {}, enableTypeScript = true }, errorCallback) => { | ||
/** | ||
* To enable TypeScript we need to transform the TS to JS code first, | ||
* splice off the JSX const, wrap the eval in a return statement, then | ||
* transform any imports. The two-phase approach is required to do | ||
* the implicit evaluation and not wrap leading Interface or Type | ||
* statements in the return. | ||
*/ | ||
const firstPassTransforms = ["jsx"]; | ||
enableTypeScript && firstPassTransforms.push("typescript"); | ||
const transformed = compose(addJsxConst, transform({ transforms: ["imports"] }), wrapReturn, spliceJsxConst, trimCode, transform({ transforms: firstPassTransforms }), trimCode)(code); | ||
return errorBoundary(evalCode(transformed, Object.assign({ React: React__default['default'] }, scope)), errorCallback); | ||
}; | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
function LiveProvider(_ref) { | ||
var children = _ref.children, | ||
code = _ref.code, | ||
language = _ref.language, | ||
theme = _ref.theme, | ||
disabled = _ref.disabled, | ||
scope = _ref.scope, | ||
transformCode = _ref.transformCode, | ||
_ref$noInline = _ref.noInline, | ||
noInline = _ref$noInline === void 0 ? false : _ref$noInline; | ||
var _useState = React.useState({ | ||
error: undefined, | ||
element: undefined | ||
}), | ||
state = _useState[0], | ||
setState = _useState[1]; | ||
function transpileAsync(newCode) { | ||
var errorCallback = function errorCallback(error) { | ||
setState({ | ||
error: error.toString(), | ||
element: undefined | ||
}); | ||
}; // - transformCode may be synchronous or asynchronous. | ||
// - transformCode may throw an exception or return a rejected promise, e.g. | ||
// if newCode is invalid and cannot be transformed. | ||
// - Not using async-await to since it requires targeting ES 2017 or | ||
// importing regenerator-runtime... in the next major version of | ||
// react-live, should target ES 2017+ | ||
try { | ||
var transformResult = transformCode ? transformCode(newCode) : newCode; | ||
return Promise.resolve(transformResult).then(function (transformedCode) { | ||
var renderElement = function renderElement(element) { | ||
return setState({ | ||
error: undefined, | ||
element: element | ||
}); | ||
}; // Transpilation arguments | ||
var input = { | ||
code: transformedCode, | ||
scope: scope | ||
}; | ||
if (noInline) { | ||
setState({ | ||
error: undefined, | ||
element: null | ||
}); // Reset output for async (no inline) evaluation | ||
renderElementAsync(input, renderElement, errorCallback); | ||
} else { | ||
renderElement(generateElement(input, errorCallback)); | ||
const renderElementAsync = ({ code = "", scope = {}, enableTypeScript = true }, resultCallback, errorCallback | ||
// eslint-disable-next-line consistent-return | ||
) => { | ||
const render = (element) => { | ||
if (typeof element === "undefined") { | ||
errorCallback(new SyntaxError("`render` must be called with valid JSX.")); | ||
} | ||
})["catch"](errorCallback); | ||
} catch (e) { | ||
errorCallback(e); | ||
return Promise.resolve(); | ||
else { | ||
resultCallback(errorBoundary(element, errorCallback)); | ||
} | ||
}; | ||
if (!/render\s*\(/.test(code)) { | ||
return errorCallback(new SyntaxError("No-Inline evaluations must call `render`.")); | ||
} | ||
} | ||
const transforms = ["jsx", "imports"]; | ||
enableTypeScript && transforms.splice(1, 0, "typescript"); | ||
evalCode(transform({ transforms })(code), Object.assign(Object.assign({ React: React__default['default'] }, scope), { render })); | ||
}; | ||
var onError = function onError(error) { | ||
return setState({ | ||
error: error.toString() | ||
function LiveProvider({ children, code = "", language = "tsx", theme, enableTypeScript = true, disabled = false, scope, transformCode, noInline = false, }) { | ||
const [state, setState] = React.useState({ | ||
error: undefined, | ||
element: undefined, | ||
}); | ||
}; | ||
React.useEffect(function () { | ||
transpileAsync(code)["catch"](onError); | ||
}, [code, scope, noInline, transformCode]); | ||
var onChange = function onChange(newCode) { | ||
transpileAsync(newCode)["catch"](onError); | ||
}; | ||
return /*#__PURE__*/React__default['default'].createElement(LiveContext$1.Provider, { | ||
value: _objectSpread(_objectSpread({}, state), {}, { | ||
code: code, | ||
language: language, | ||
theme: theme, | ||
disabled: disabled, | ||
onError: onError, | ||
onChange: onChange | ||
}) | ||
}, children); | ||
} | ||
LiveProvider.defaultProps = { | ||
code: "", | ||
noInline: false, | ||
language: "jsx", | ||
disabled: false | ||
}; | ||
function _extends() { | ||
_extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
function transpileAsync(newCode) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const errorCallback = (error) => { | ||
setState({ error: error.toString(), element: undefined }); | ||
}; | ||
// - transformCode may be synchronous or asynchronous. | ||
// - transformCode may throw an exception or return a rejected promise, e.g. | ||
// if newCode is invalid and cannot be transformed. | ||
// - Not using async-await to since it requires targeting ES 2017 or | ||
// importing regenerator-runtime... in the next major version of | ||
// react-live, should target ES 2017+ | ||
try { | ||
const transformResult = transformCode ? transformCode(newCode) : newCode; | ||
try { | ||
const transformedCode = yield Promise.resolve(transformResult); | ||
const renderElement = (element) => setState({ error: undefined, element }); | ||
if (typeof transformedCode !== "string") { | ||
throw new Error("Code failed to transform"); | ||
} | ||
// Transpilation arguments | ||
const input = { | ||
code: transformedCode, | ||
scope, | ||
enableTypeScript, | ||
}; | ||
if (noInline) { | ||
setState({ error: undefined, element: null }); // Reset output for async (no inline) evaluation | ||
renderElementAsync(input, renderElement, errorCallback); | ||
} | ||
else { | ||
renderElement(generateElement(input, errorCallback)); | ||
} | ||
} | ||
catch (error) { | ||
return errorCallback(error); | ||
} | ||
} | ||
catch (e) { | ||
errorCallback(e); | ||
return Promise.resolve(); | ||
} | ||
}); | ||
} | ||
return target; | ||
}; | ||
return _extends.apply(this, arguments); | ||
const onError = (error) => setState({ error: error.toString() }); | ||
React.useEffect(() => { | ||
transpileAsync(code).catch(onError); | ||
}, [code, scope, noInline, transformCode]); | ||
const onChange = (newCode) => { | ||
transpileAsync(newCode).catch(onError); | ||
}; | ||
return (jsxRuntime.jsx(LiveContext.Provider, Object.assign({ value: Object.assign(Object.assign({}, state), { code, | ||
language, | ||
theme, | ||
disabled, | ||
onError, | ||
onChange }) }, { children: children }))); | ||
} | ||
function LiveEditor(props) { | ||
var _useContext = React.useContext(LiveContext$1), | ||
code = _useContext.code, | ||
language = _useContext.language, | ||
theme = _useContext.theme, | ||
disabled = _useContext.disabled, | ||
onChange = _useContext.onChange; | ||
return /*#__PURE__*/React__default['default'].createElement(Editor, _extends({ | ||
theme: theme, | ||
code: code, | ||
language: language, | ||
disabled: disabled, | ||
onChange: onChange | ||
}, props)); | ||
const { code, language, theme, disabled, onChange } = React.useContext(LiveContext); | ||
return (jsxRuntime.jsx(CodeEditor, Object.assign({ theme: theme, code: code, language: language, disabled: disabled, onChange: onChange }, props))); | ||
} | ||
function LiveError(props) { | ||
var _useContext = React.useContext(LiveContext$1), | ||
error = _useContext.error; | ||
return error ? /*#__PURE__*/React__default['default'].createElement("pre", props, error) : null; | ||
const { error } = React.useContext(LiveContext); | ||
return error ? jsxRuntime.jsx("pre", Object.assign({}, props, { children: error })) : null; | ||
} | ||
function _objectWithoutPropertiesLoose(source, excluded) { | ||
if (source == null) return {}; | ||
var target = {}; | ||
var sourceKeys = Object.keys(source); | ||
var key, i; | ||
for (i = 0; i < sourceKeys.length; i++) { | ||
key = sourceKeys[i]; | ||
if (excluded.indexOf(key) >= 0) continue; | ||
target[key] = source[key]; | ||
} | ||
return target; | ||
const fallbackComponent = (props) => jsxRuntime.jsx("div", Object.assign({}, props)); | ||
function LivePreview(_a) { | ||
var { Component = fallbackComponent } = _a, rest = __rest(_a, ["Component"]); | ||
const { element: Element } = React.useContext(LiveContext); | ||
return jsxRuntime.jsx(Component, Object.assign({}, rest, { children: Element ? jsxRuntime.jsx(Element, {}) : null })); | ||
} | ||
var _excluded = ["Component"]; | ||
function LivePreview(_ref) { | ||
var Component = _ref.Component, | ||
rest = _objectWithoutPropertiesLoose(_ref, _excluded); | ||
var _useContext = React.useContext(LiveContext$1), | ||
Element = _useContext.element; | ||
return /*#__PURE__*/React__default['default'].createElement(Component, rest, Element ? /*#__PURE__*/React__default['default'].createElement(Element, null) : null); | ||
} | ||
LivePreview.defaultProps = { | ||
Component: "div" | ||
}; | ||
function withLive(WrappedComponent) { | ||
var WithLive = /*#__PURE__*/function (_Component) { | ||
_inheritsLoose(WithLive, _Component); | ||
function WithLive() { | ||
return _Component.apply(this, arguments) || this; | ||
} | ||
var _proto = WithLive.prototype; | ||
_proto.render = function render() { | ||
var _this = this; | ||
return /*#__PURE__*/React__default['default'].createElement(LiveContext$1.Consumer, null, function (live) { | ||
return /*#__PURE__*/React__default['default'].createElement(WrappedComponent, _extends({ | ||
live: live | ||
}, _this.props)); | ||
}); | ||
}; | ||
const WithLive = (props) => (jsxRuntime.jsx(LiveContext.Consumer, { children: (live) => jsxRuntime.jsx(WrappedComponent, Object.assign({ live: live }, props)) })); | ||
WithLive.displayName = "WithLive"; | ||
return WithLive; | ||
}(React.Component); | ||
return WithLive; | ||
} | ||
exports.Editor = Editor; | ||
exports.LiveContext = LiveContext$1; | ||
exports.Editor = CodeEditor; | ||
exports.LiveContext = LiveContext; | ||
exports.LiveEditor = LiveEditor; | ||
@@ -833,0 +671,0 @@ exports.LiveError = LiveError; |
@@ -1,1 +0,16 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("prism-react-renderer"),require("react"),require("sucrase")):"function"==typeof define&&define.amd?define(["exports","prism-react-renderer","react","sucrase"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactLive={},e.Prism,e.React,e.Sucrase)}(this,(function(e,t,n,r){"use strict";function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=o(t),a=o(n);function c(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var l={characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0};function u(e){var t=window.getSelection();t.empty(),t.addRange(e)}function s(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&"KeyZ"===e.code}function f(e){e=[e.firstChild];for(var t,n="";t=e.pop();)t.nodeType===Node.TEXT_NODE?n+=t.textContent:t.nodeType===Node.ELEMENT_NODE&&"BR"===t.nodeName&&(n+="\n"),t.nextSibling&&e.push(t.nextSibling),t.firstChild&&e.push(t.firstChild);return"\n"!==n[n.length-1]&&(n+="\n"),n}function d(e){var t=window.getSelection().getRangeAt(0),n=t.collapsed?0:t.toString().length,r=document.createRange();return r.setStart(e,0),r.setEnd(t.startContainer,t.startOffset),{position:e=(r=r.toString()).length,extent:n,content:r=(r=r.split("\n"))[t=r.length-1],line:t}}function p(e,t,n){0>=t&&(t=0),(!n||0>n)&&(n=t);var r=document.createRange();e=[e.firstChild];for(var o,i=0,a=t;o=e[e.length-1];){if(o.nodeType===Node.TEXT_NODE){if(i+o.textContent.length>=a){var c=a-i;if(a===t){if(a=r,c<o.textContent.length?a.setStart(o,c):a.setStartAfter(o),n!==t){a=n;continue}break}t=r,c<(n=o).textContent.length?t.setEnd(n,c):t.setEndAfter(n);break}i+=o.textContent.length}else if(o.nodeType===Node.ELEMENT_NODE&&"BR"===o.nodeName){if(i+1>=a){if(a===t){if(c=r,0<o.textContent.length?c.setStart(o,0):c.setStartAfter(o),n!==t){a=n;continue}break}t=r,0<(n=o).textContent.length?t.setEnd(n,0):t.setEndAfter(n);break}i++}e.pop(),o.nextSibling&&e.push(o.nextSibling),o.firstChild&&e.push(o.firstChild)}return r}var y={plain:{color:"#C5C8C6",backgroundColor:"#1D1F21"},styles:[{types:["prolog","comment","doctype","cdata"],style:{color:"hsl(30, 20%, 50%)"}},{types:["property","tag","boolean","number","constant","symbol"],style:{color:"hsl(350, 40%, 70%)"}},{types:["attr-name","string","char","builtin","insterted"],style:{color:"hsl(75, 70%, 60%)"}},{types:["operator","entity","url","string","variable","language-css"],style:{color:"hsl(40, 90%, 60%)"}},{types:["deleted"],style:{color:"rgb(255, 85, 85)"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["important","bold"],style:{fontWeight:"bold"}},{types:["regex","important"],style:{color:"#e90"}},{types:["atrule","attr-value","keyword"],style:{color:"hsl(350, 40%, 70%)"}},{types:["punctuation","symbol"],style:{opacity:"0.7"}}]};function v(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function h(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?v(Object(n),!0).forEach((function(t){c(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):v(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var g=function(e){var r=n.useRef(null),o=n.useState(e.code||""),c=o[0],v=o[1];n.useEffect((function(){v(e.code)}),[e.code]);var g=n.useCallback((function(e){v(e.slice(0,-1))}),[]);return function(e,t,r){function o(t){var n=e.current;if(n){var r=d(n);n=f(n),r.position+=t.length-n.length,h.position=r,h.onChange(t,r)}}function i(t,n){var r=e.current;if(r){var o=window.getSelection().getRangeAt(0);o.deleteContents(),o.collapse();var i=n||0;(o=p(r,n=(o=d(r)).position+(0>i?i:0),o.position+(0<i?i:0))).deleteContents(),t&&o.insertNode(document.createTextNode(t)),u(p(r,n+t.length))}}function a(t){var n=e.current;if(n){n.focus();var r=0;if("number"==typeof t)r=t;else{var o=f(n).split("\n").slice(0,t.row);t.row&&(r+=o.join("\n").length+1),r+=t.column}u(p(n,r))}}function c(){var t=e.current;return{text:f(t),position:t=d(t)}}function y(){h.observer.disconnect()}r||(r={});var v=n.useState([])[1],h=n.useState((function(){var e={observer:null,disconnected:!1,onChange:t,queue:[],history:[],historyAt:-1,position:null};return"undefined"!=typeof MutationObserver&&(e.observer=new MutationObserver((function(t){var n;(n=e.queue).push.apply(n,t)}))),e}))[0],g=n.useMemo((function(){return{update:o,insert:i,move:a,getState:c}}),[]);"object"!=typeof navigator||(n.useLayoutEffect((function(){if(h.onChange=t,e.current&&!r.disabled){if(h.disconnected=!1,h.observer.observe(e.current,l),h.position){var n=h.position,o=n.position;u(p(e.current,o,o+n.extent))}return y}})),n.useLayoutEffect((function(){if(e.current&&!r.disabled){var t=e.current;if(h.position){t.focus();var n=h.position,o=n.position;u(p(t,o,o+n.extent))}var i=t.style.whiteSpace,a=t.contentEditable,c=!0;try{t.contentEditable="plaintext-only"}catch(e){t.contentEditable="true",c=!1}"pre"!==i&&(t.style.whiteSpace="pre-wrap"),r.indentation&&(t.style.tabSize=t.style.MozTabSize=""+r.indentation),n=""+" ".repeat(r.indentation||0);var l,y=new RegExp("^(?:"+n+")"),b=new RegExp("^(?:"+n+")*("+n+")$"),m=function(n){if(e.current&&h.position){var r=f(t),o=d(t),i=(new Date).valueOf(),a=h.history[h.historyAt];!n&&500>i-l||a&&a[1]===r?l=i:(n=++h.historyAt,h.history[n]=[o,r],h.history.splice(n+1),500<n&&(h.historyAt--,h.history.shift()))}},O=function(){var e;if((e=h.queue).push.apply(e,h.observer.takeRecords()),e=d(t),h.queue.length){h.observer.disconnect(),h.disconnected=!0;var n,r,o=f(t);for(h.position=e;n=h.queue.pop();){for(null!==n.oldValue&&(n.target.textContent=n.oldValue),r=n.removedNodes.length-1;0<=r;r--)n.target.insertBefore(n.removedNodes[r],n.nextSibling);for(r=n.addedNodes.length-1;0<=r;r--)n.addedNodes[r].parentNode&&n.target.removeChild(n.addedNodes[r])}h.onChange(o,e)}},E=function(e){if(!e.defaultPrevented&&e.target===t){if(h.disconnected)return e.preventDefault(),v([]);if(s(e))e.preventDefault(),e.shiftKey?(e=++h.historyAt,(e=h.history[e])||(h.historyAt=h.history.length-1)):(e=--h.historyAt,(e=h.history[e])||(h.historyAt=0)),e&&(h.observer.disconnect(),h.disconnected=!0,h.position=e[0],h.onChange(e[1],e[0]));else{if(m(),"Enter"===e.key){e.preventDefault();var n=d(t),o=/\S/g.exec(n.content);n="\n"+n.content.slice(0,o?o.index:n.content.length),g.insert(n)}else if(c&&!r.indentation||"Backspace"!==e.key){if(r.indentation&&"Tab"===e.key){e.preventDefault(),o=(n=d(t)).position-n.content.length;var i=f(t);n=e.shiftKey?i.slice(0,o)+n.content.replace(y,"")+i.slice(o+n.content.length):i.slice(0,o)+(r.indentation?" ".repeat(r.indentation):"\t")+i.slice(o),g.update(n)}}else e.preventDefault(),window.getSelection().getRangeAt(0).collapsed?(n=d(t),n=b.exec(n.content),g.insert("",n?-n[1].length:-1)):g.insert("",0);e.repeat&&O()}}},w=function(e){e.defaultPrevented||e.isComposing||(s(e)||m(),O(),t.focus())},C=function(e){h.position=window.getSelection().rangeCount&&e.target===t?d(t):null},j=function(e){e.preventDefault(),m(!0),g.insert(e.clipboardData.getData("text/plain")),m(!0),O()};return document.addEventListener("selectstart",C),window.addEventListener("keydown",E),t.addEventListener("paste",j),t.addEventListener("keyup",w),function(){document.removeEventListener("selectstart",C),window.removeEventListener("keydown",E),t.removeEventListener("paste",j),t.removeEventListener("keyup",w),t.style.whiteSpace=i,t.contentEditable=a}}h.history.length=0,h.historyAt=-1}),[e.current,r.disabled,r.indentation]))}(r,g,{disabled:e.disabled,indentation:"indentation"===e.tabMode?2:void 0}),n.useEffect((function(){e.onChange&&e.onChange(c)}),[c]),a.default.createElement("div",{className:e.className,style:e.style},a.default.createElement(i.default,{Prism:e.prism||t.Prism,code:c,theme:e.theme||y,language:e.language},(function(e){var t=e.className,n=e.tokens,o=e.getLineProps,i=e.getTokenProps,c=e.style,l=e.theme;return a.default.createElement("pre",{className:t,style:h(h({margin:0,outline:"none",padding:10,fontFamily:"inherit"},l&&"object"==typeof l.plain?l.plain:{}),c),ref:r,spellCheck:"false"},n.map((function(e,t){return a.default.createElement("div",o({line:e,key:"line-"+t}),e.filter((function(e){return!e.empty})).map((function(e,t){return a.default.createElement("span",i({token:e,key:"token-"+t}))})),"\n")})))})))};g.defaultProps={tabMode:"indentation"};var b=g,m=n.createContext({}),O={transforms:["jsx","imports"]},E=function(e){return r.transform(e,O).code};function w(e,t){return(w=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function C(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,w(e,t)}var j=function(e,t){return function(n){function r(){return n.apply(this,arguments)||this}C(r,n);var o=r.prototype;return o.componentDidCatch=function(e){t(e)},o.render=function(){return"function"==typeof e?a.default.createElement(e,null):a.default.isValidElement(e)?e:null},r}(n.Component)};function P(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function S(e,t,n){return(S=P()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&w(o,n.prototype),o}).apply(null,arguments)}var x=function(e,t){var n=Object.keys(t),r=n.map((function(e){return t[e]}));return S(Function,n.concat([e])).apply(void 0,r)};function D(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function k(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?D(Object(n),!0).forEach((function(t){c(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):D(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var N=function(e,t){var n=e.code,r=void 0===n?"":n,o=e.scope,i=void 0===o?{}:o,c=r.trim().replace(/;$/,""),l=E("return ("+c+")").trim();return j(x(l,k({React:a.default},i)),t)},L=function(e,t,n){var r=e.code,o=void 0===r?"":r,i=e.scope,c=void 0===i?{}:i;if(!/render\s*\(/.test(o))return n(new SyntaxError("No-Inline evaluations must call `render`."));x(E(o),k(k({React:a.default},c),{},{render:function(e){void 0===e?n(new SyntaxError("`render` must be called with valid JSX.")):t(j(e,n))}}))};function R(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function A(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?R(Object(n),!0).forEach((function(t){c(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):R(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function T(e){var t=e.children,r=e.code,o=e.language,i=e.theme,c=e.disabled,l=e.scope,u=e.transformCode,s=e.noInline,f=void 0!==s&&s,d=n.useState({error:void 0,element:void 0}),p=d[0],y=d[1];function v(e){var t=function(e){y({error:e.toString(),element:void 0})};try{var n=u?u(e):e;return Promise.resolve(n).then((function(e){var n=function(e){return y({error:void 0,element:e})},r={code:e,scope:l};f?(y({error:void 0,element:null}),L(r,n,t)):n(N(r,t))})).catch(t)}catch(e){return t(e),Promise.resolve()}}var h=function(e){return y({error:e.toString()})};n.useEffect((function(){v(r).catch(h)}),[r,l,f,u]);return a.default.createElement(m.Provider,{value:A(A({},p),{},{code:r,language:o,theme:i,disabled:c,onError:h,onChange:function(e){v(e).catch(h)}})},t)}function _(){return(_=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}T.defaultProps={code:"",noInline:!1,language:"jsx",disabled:!1};var M=["Component"];function q(e){var t=e.Component,r=function(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,M),o=n.useContext(m).element;return a.default.createElement(t,r,o?a.default.createElement(o,null):null)}q.defaultProps={Component:"div"},e.Editor=b,e.LiveContext=m,e.LiveEditor=function(e){var t=n.useContext(m),r=t.code,o=t.language,i=t.theme,c=t.disabled,l=t.onChange;return a.default.createElement(b,_({theme:i,code:r,language:o,disabled:c,onChange:l},e))},e.LiveError=function(e){var t=n.useContext(m).error;return t?a.default.createElement("pre",e,t):null},e.LivePreview=q,e.LiveProvider=T,e.generateElement=N,e.renderElementAsync=L,e.withLive=function(e){return function(t){function n(){return t.apply(this,arguments)||this}return C(n,t),n.prototype.render=function(){var t=this;return a.default.createElement(m.Consumer,null,(function(n){return a.default.createElement(e,_({live:n},t.props))}))},n}(n.Component)},Object.defineProperty(e,"__esModule",{value:!0})})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react/jsx-runtime"),require("prism-react-renderer"),require("react"),require("sucrase")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","prism-react-renderer","react","sucrase"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactLive={},e["jsx-runtime"],e.Prism,e.React,e.Sucrase)}(this,(function(e,t,n,r,o){"use strict";function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=i(n),a=i(r),c={characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0};function l(e){var t=window.getSelection();t.empty(),t.addRange(e)}function d(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&"KeyZ"===e.code}function u(e){e=[e.firstChild];for(var t,n="";t=e.pop();)t.nodeType===Node.TEXT_NODE?n+=t.textContent:t.nodeType===Node.ELEMENT_NODE&&"BR"===t.nodeName&&(n+="\n"),t.nextSibling&&e.push(t.nextSibling),t.firstChild&&e.push(t.firstChild);return"\n"!==n[n.length-1]&&(n+="\n"),n}function p(e){var t=window.getSelection().getRangeAt(0),n=t.collapsed?0:t.toString().length,r=document.createRange();return r.setStart(e,0),r.setEnd(t.startContainer,t.startOffset),{position:e=(r=r.toString()).length,extent:n,content:r=(r=r.split("\n"))[t=r.length-1],line:t}}function f(e,t,n){0>=t&&(t=0),(!n||0>n)&&(n=t);var r=document.createRange();e=[e.firstChild];for(var o,i=0,s=t;o=e[e.length-1];){if(o.nodeType===Node.TEXT_NODE){if(i+o.textContent.length>=s){var a=s-i;if(s===t){if(s=r,a<o.textContent.length?s.setStart(o,a):s.setStartAfter(o),n!==t){s=n;continue}break}t=r,a<(n=o).textContent.length?t.setEnd(n,a):t.setEndAfter(n);break}i+=o.textContent.length}else if(o.nodeType===Node.ELEMENT_NODE&&"BR"===o.nodeName){if(i+1>=s){if(s===t){if(a=r,0<o.textContent.length?a.setStart(o,0):a.setStartAfter(o),n!==t){s=n;continue}break}t=r,0<(n=o).textContent.length?t.setEnd(n,0):t.setEndAfter(n);break}i++}e.pop(),o.nextSibling&&e.push(o.nextSibling),o.firstChild&&e.push(o.firstChild)}return r}const y={plain:{color:"#C5C8C6",backgroundColor:"#1D1F21"},styles:[{types:["prolog","comment","doctype","cdata"],style:{color:"hsl(30, 20%, 50%)"}},{types:["property","tag","boolean","number","constant","symbol"],style:{color:"hsl(350, 40%, 70%)"}},{types:["attr-name","string","char","builtin","insterted"],style:{color:"hsl(75, 70%, 60%)"}},{types:["operator","entity","url","string","variable","language-css"],style:{color:"hsl(40, 90%, 60%)"}},{types:["deleted"],style:{color:"rgb(255, 85, 85)"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["important","bold"],style:{fontWeight:"bold"}},{types:["regex","important"],style:{color:"#e90"}},{types:["atrule","attr-value","keyword"],style:{color:"hsl(350, 40%, 70%)"}},{types:["punctuation","symbol"],style:{opacity:.7}}]},g=e=>{const o=r.useRef(null),[i,a]=r.useState(e.code||"");r.useEffect((()=>{a(e.code)}),[e.code]);const g=r.useCallback((e=>{a(e.slice(0,-1))}),[]);return function(e,t,n){function o(t){var n=e.current;if(n){var r=p(n);n=u(n),r.position+=t.length-n.length,h.position=r,h.onChange(t,r)}}function i(t,n){var r=e.current;if(r){var o=window.getSelection().getRangeAt(0);o.deleteContents(),o.collapse();var i=n||0;(o=f(r,n=(o=p(r)).position+(0>i?i:0),o.position+(0<i?i:0))).deleteContents(),t&&o.insertNode(document.createTextNode(t)),l(f(r,n+t.length))}}function s(t){var n=e.current;if(n){n.focus();var r=0;if("number"==typeof t)r=t;else{var o=u(n).split("\n").slice(0,t.row);t.row&&(r+=o.join("\n").length+1),r+=t.column}l(f(n,r))}}function a(){var t=e.current;return{text:u(t),position:t=p(t)}}function y(){h.observer.disconnect()}n||(n={});var g=r.useState([])[1],h=r.useState((function(){var e={observer:null,disconnected:!1,onChange:t,queue:[],history:[],historyAt:-1,position:null};return"undefined"!=typeof MutationObserver&&(e.observer=new MutationObserver((function(t){var n;(n=e.queue).push.apply(n,t)}))),e}))[0],v=r.useMemo((function(){return{update:o,insert:i,move:s,getState:a}}),[]);"object"!=typeof navigator||(r.useLayoutEffect((function(){if(h.onChange=t,e.current&&!n.disabled){if(h.disconnected=!1,h.observer.observe(e.current,c),h.position){var r=h.position,o=r.position;l(f(e.current,o,o+r.extent))}return y}})),r.useLayoutEffect((function(){if(e.current&&!n.disabled){var t=e.current;if(h.position){t.focus();var r=h.position,o=r.position;l(f(t,o,o+r.extent))}var i=t.style.whiteSpace,s=t.contentEditable,a=!0;try{t.contentEditable="plaintext-only"}catch(e){t.contentEditable="true",a=!1}"pre"!==i&&(t.style.whiteSpace="pre-wrap"),n.indentation&&(t.style.tabSize=t.style.MozTabSize=""+n.indentation),r=""+" ".repeat(n.indentation||0);var c,y=new RegExp("^(?:"+r+")"),m=new RegExp("^(?:"+r+")*("+r+")$"),b=function(n){if(e.current&&h.position){var r=u(t),o=p(t),i=(new Date).valueOf(),s=h.history[h.historyAt];!n&&500>i-c||s&&s[1]===r?c=i:(n=++h.historyAt,h.history[n]=[o,r],h.history.splice(n+1),500<n&&(h.historyAt--,h.history.shift()))}},x=function(){var e;if((e=h.queue).push.apply(e,h.observer.takeRecords()),e=p(t),h.queue.length){h.observer.disconnect(),h.disconnected=!0;var n,r,o=u(t);for(h.position=e;n=h.queue.pop();){for(null!==n.oldValue&&(n.target.textContent=n.oldValue),r=n.removedNodes.length-1;0<=r;r--)n.target.insertBefore(n.removedNodes[r],n.nextSibling);for(r=n.addedNodes.length-1;0<=r;r--)n.addedNodes[r].parentNode&&n.target.removeChild(n.addedNodes[r])}h.onChange(o,e)}},j=function(e){if(!e.defaultPrevented&&e.target===t){if(h.disconnected)return e.preventDefault(),g([]);if(d(e))e.preventDefault(),e.shiftKey?(e=++h.historyAt,(e=h.history[e])||(h.historyAt=h.history.length-1)):(e=--h.historyAt,(e=h.history[e])||(h.historyAt=0)),e&&(h.observer.disconnect(),h.disconnected=!0,h.position=e[0],h.onChange(e[1],e[0]));else{if(b(),"Enter"===e.key){e.preventDefault();var r=p(t),o=/\S/g.exec(r.content);r="\n"+r.content.slice(0,o?o.index:r.content.length),v.insert(r)}else if(a&&!n.indentation||"Backspace"!==e.key){if(n.indentation&&"Tab"===e.key){e.preventDefault(),o=(r=p(t)).position-r.content.length;var i=u(t);r=e.shiftKey?i.slice(0,o)+r.content.replace(y,"")+i.slice(o+r.content.length):i.slice(0,o)+(n.indentation?" ".repeat(n.indentation):"\t")+i.slice(o),v.update(r)}}else e.preventDefault(),window.getSelection().getRangeAt(0).collapsed?(r=p(t),r=m.exec(r.content),v.insert("",r?-r[1].length:-1)):v.insert("",0);e.repeat&&x()}}},C=function(e){e.defaultPrevented||e.isComposing||(d(e)||b(),x(),t.focus())},E=function(e){h.position=window.getSelection().rangeCount&&e.target===t?p(t):null},w=function(e){e.preventDefault(),b(!0),v.insert(e.clipboardData.getData("text/plain")),b(!0),x()};return document.addEventListener("selectstart",E),window.addEventListener("keydown",j),t.addEventListener("paste",w),t.addEventListener("keyup",C),function(){document.removeEventListener("selectstart",E),window.removeEventListener("keydown",j),t.removeEventListener("paste",w),t.removeEventListener("keyup",C),t.style.whiteSpace=i,t.contentEditable=s}}h.history.length=0,h.historyAt=-1}),[e.current,n.disabled,n.indentation]))}(o,g,{disabled:e.disabled,indentation:"indentation"===e.tabMode?2:void 0}),r.useEffect((()=>{e.onChange&&e.onChange(i)}),[i]),t.jsx("div",Object.assign({className:e.className,style:e.style},{children:t.jsx(s.default,Object.assign({Prism:e.prism||n.Prism,code:i,theme:e.theme||y,language:e.language},{children:({className:e,tokens:n,getLineProps:r,getTokenProps:i,style:s,theme:a})=>t.jsx("pre",Object.assign({className:e,style:Object.assign(Object.assign({margin:0,outline:"none",padding:10,fontFamily:"inherit"},a&&"object"==typeof a.plain?a.plain:{}),s),ref:o,spellCheck:"false"},{children:n.map(((e,n)=>t.jsxs("div",Object.assign({},r({line:e,key:`line-${n}`}),{children:[e.filter((e=>!e.empty)).map(((e,n)=>t.jsx("span",Object.assign({},i({token:e,key:`token-${n}`}))))),"\n"]}))))}))}))}))};function h(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))}g.defaultProps={tabMode:"indentation"};const v=r.createContext({}),m=["jsx","imports"];function b(e={}){const t=Array.isArray(e.transforms)?e.transforms.filter(Boolean):m;return e=>o.transform(e,{transforms:t}).code}const x=(e,n)=>class extends r.Component{componentDidCatch(e){n(e)}render(){return"function"==typeof e?t.jsx(e,{}):a.default.isValidElement(e)?e:null}},j=(e,t)=>{const n=Object.keys(t),r=n.map((e=>t[e]));return new Function(...n,e)(...r)};const C='const _jsxFileName = "";',E=e=>e.trim().replace(/;$/,""),w=e=>e.replace(C,"").trim(),S=e=>C+e,O=e=>`return (${e})`,N=({code:e="",scope:t={},enableTypeScript:n=!0},r)=>{const o=["jsx"];n&&o.push("typescript");const i=function(...e){return e.reduce(((e,t)=>(...n)=>e(t(...n))))}(S,b({transforms:["imports"]}),O,w,E,b({transforms:o}),E)(e);return x(j(i,Object.assign({React:a.default},t)),r)},k=({code:e="",scope:t={},enableTypeScript:n=!0},r,o)=>{if(!/render\s*\(/.test(e))return o(new SyntaxError("No-Inline evaluations must call `render`."));const i=["jsx","imports"];n&&i.splice(1,0,"typescript"),j(b({transforms:i})(e),Object.assign(Object.assign({React:a.default},t),{render:e=>{void 0===e?o(new SyntaxError("`render` must be called with valid JSX.")):r(x(e,o))}}))};const L=e=>t.jsx("div",Object.assign({},e));e.Editor=g,e.LiveContext=v,e.LiveEditor=function(e){const{code:n,language:o,theme:i,disabled:s,onChange:a}=r.useContext(v);return t.jsx(g,Object.assign({theme:i,code:n,language:o,disabled:s,onChange:a},e))},e.LiveError=function(e){const{error:n}=r.useContext(v);return n?t.jsx("pre",Object.assign({},e,{children:n})):null},e.LivePreview=function(e){var{Component:n=L}=e,o= | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
Permission to use, copy, modify, and/or distribute this software for any | ||
purpose with or without fee is hereby granted. | ||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | ||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | ||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | ||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | ||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | ||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */ | ||
function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}(e,["Component"]);const{element:i}=r.useContext(v);return t.jsx(n,Object.assign({},o,{children:i?t.jsx(i,{}):null}))},e.LiveProvider=function({children:e,code:n="",language:o="tsx",theme:i,enableTypeScript:s=!0,disabled:a=!1,scope:c,transformCode:l,noInline:d=!1}){const[u,p]=r.useState({error:void 0,element:void 0});function f(e){return h(this,void 0,void 0,(function*(){const t=e=>{p({error:e.toString(),element:void 0})};try{const n=l?l(e):e;try{const e=yield Promise.resolve(n),r=e=>p({error:void 0,element:e});if("string"!=typeof e)throw new Error("Code failed to transform");const o={code:e,scope:c,enableTypeScript:s};d?(p({error:void 0,element:null}),k(o,r,t)):r(N(o,t))}catch(e){return t(e)}}catch(e){return t(e),Promise.resolve()}}))}const y=e=>p({error:e.toString()});return r.useEffect((()=>{f(n).catch(y)}),[n,c,d,l]),t.jsx(v.Provider,Object.assign({value:Object.assign(Object.assign({},u),{code:n,language:o,theme:i,disabled:a,onError:y,onChange:e=>{f(e).catch(y)}})},{children:e}))},e.generateElement=N,e.renderElementAsync=k,e.withLive=function(e){const n=n=>t.jsx(v.Consumer,{children:r=>t.jsx(e,Object.assign({live:r},n))});return n.displayName="WithLive",n},Object.defineProperty(e,"__esModule",{value:!0})})); |
{ | ||
"name": "react-live", | ||
"version": "3.2.0", | ||
"version": "4.0.0", | ||
"description": "A production-focused playground for live editing React code", | ||
"main": "dist/react-live.cjs.js", | ||
"typings": "./typings/react-live.d.ts", | ||
"types": "dist/index.d.ts", | ||
"jsnext:main": "dist/react-live.es.js", | ||
@@ -19,7 +19,14 @@ "module": "dist/react-live.es.js", | ||
"test:typings": "typings-tester --dir typings", | ||
"lint": "eslint --config .eslintrc \"./**/*.js\"" | ||
"typecheck": "tsc --noEmit", | ||
"lint": "eslint --config .eslintrc \"./src/**/*.js\"", | ||
"install:docs": "yarn --cwd website install", | ||
"start:docs": "yarn --cwd website start", | ||
"build:docs": "yarn --cwd website build", | ||
"format:docs": "prettier --write docs", | ||
"changeset": "changeset", | ||
"version": "yarn changeset version" | ||
}, | ||
"dependencies": { | ||
"prism-react-renderer": "^1.3.1", | ||
"sucrase": "^3.21.0", | ||
"sucrase": "^3.31.0", | ||
"use-editable": "^2.3.3" | ||
@@ -35,2 +42,4 @@ }, | ||
"@babel/preset-react": "^7.14.5", | ||
"@babel/preset-typescript": "^7.21.0", | ||
"@changesets/cli": "^2.26.1", | ||
"@rollup/plugin-babel": "^5.3.0", | ||
@@ -40,5 +49,13 @@ "@rollup/plugin-commonjs": "^20.0.0", | ||
"@rollup/plugin-replace": "^3.0.0", | ||
"@rollup/plugin-typescript": "^11.0.0", | ||
"@storybook/addon-controls": "^6.4.13", | ||
"@storybook/builder-webpack5": "^6.5.16", | ||
"@storybook/manager-webpack5": "^6.5.16", | ||
"@storybook/react": "^6.4.13", | ||
"@types/react": "^17.0.38", | ||
"@svitejs/changesets-changelog-github-compact": "^1.1.0", | ||
"@types/prismjs": "^1.26.0", | ||
"@types/react": "^18.0.31", | ||
"@types/styled-components": "^5.1.26", | ||
"@typescript-eslint/eslint-plugin": "^5.57.0", | ||
"@typescript-eslint/parser": "^5.57.0", | ||
"babel-jest": "^27.0.6", | ||
@@ -57,4 +74,5 @@ "babel-loader": "^8.2.2", | ||
"prop-types": "^15.7.2", | ||
"react": "^17.0.2", | ||
"react-dom": "^17.0.2", | ||
"react": "^18.2.0", | ||
"react-docgen-typescript": "^2.2.2", | ||
"react-dom": "^18.2.0", | ||
"react-test-renderer": "^17.0.2", | ||
@@ -66,4 +84,5 @@ "rollup": "^2.55.1", | ||
"styled-components": "^4.0.0-beta.8", | ||
"typescript": "^2.9.2", | ||
"typings-tester": "^0.3.1" | ||
"typescript": "^4.9", | ||
"typings-tester": "^0.3.1", | ||
"webpack": "^5.76.3" | ||
}, | ||
@@ -70,0 +89,0 @@ "files": [ |
232
README.md
@@ -25,235 +25,19 @@ <p align="center"> | ||
## Usage | ||
Come learn more at our [docs site](https://formidable-react-live-docs.vercel.app)! | ||
Install it with `npm install react-live` or `yarn add react-live` and try out this piece of JSX: | ||
## Support | ||
```js | ||
import { LiveProvider, LiveEditor, LiveError, LivePreview } from "react-live"; | ||
Have a question about react-live? Submit an issue in this repository using the | ||
["Question" template](https://github.com/FormidableLabs/react-live/issues/new?template=question.md). | ||
<LiveProvider code="<strong>Hello World!</strong>"> | ||
<LiveEditor /> | ||
<LiveError /> | ||
<LivePreview /> | ||
</LiveProvider>; | ||
``` | ||
Notice something inaccurate or confusing? Feel free to [open an issue](https://github.com/FormidableLabs/react-live/issues/new/choose) or [make a pull request](https://github.com/FormidableLabs/react-live/pulls) to help improve the documentation for everyone! | ||
## Demo | ||
The source for our docs site lives in this repo in the [`docs`](https://github.com/FormidableLabs/react-live/blob/main/docs) folder. | ||
[https://react-live.netlify.com/](https://react-live.netlify.com/) | ||
## Contributing | ||
## FAQ | ||
Please see our [contributing guide](CONTRIBUTING.md). | ||
### How does it work? | ||
It takes your code and transpiles it with [Sucrase](https://github.com/alangpierce/sucrase), while the code is displayed using [`use-editable`](https://github.com/FormidableLabs/use-editable) and the code is highlighted using [`prism-react-renderer`](https://github.com/FormidableLabs/prism-react-renderer). | ||
The transpiled code is then rendered in the preview component (`LivePreview`), which does a fake mount if the code | ||
is a React component. | ||
Prior to `v3.0.0`, earlier versions of the library used different internals. We recommend using the latest version you can. | ||
| Version | Supported React version | Editor | Transpiler | | ||
| ------- | ----------------------- | -------------------------- | ---------- | | ||
| v3.x.x | v17.x.x | `use-editable` | `Sucrase` | | ||
| v2.x.x | v16.x.x | `react-simple-code-editor` | `Bublé` | | ||
Please see also the related Formidable libraries:- | ||
- [https://github.com/FormidableLabs/prism-react-renderer](https://github.com/FormidableLabs/prism-react-renderer) | ||
- [https://github.com/FormidableLabs/use-editable](https://github.com/FormidableLabs/use-editable) | ||
### What code can I use? | ||
The code can be one of the following things: | ||
- React elements, e.g. `<strong>Hello World!</strong>` | ||
- React pure functional components, e.g. `() => <strong>Hello World!</strong>` | ||
- React functional components with Hooks | ||
- React component classes | ||
If you enable the `noInline` prop on your `LiveProvider`, you’ll be able to write imperative code, | ||
and render one of the above things by calling `render`. | ||
### How does the scope work? | ||
The `scope` prop on the `LiveProvider` accepts additional globals. By default it injects `React` only, which | ||
means that the user can use it in their code like this: | ||
```js | ||
// ↓↓↓↓↓ | ||
class Example extends React.Component { | ||
render() { | ||
return <strong>Hello World!</strong>; | ||
} | ||
} | ||
``` | ||
But you can of course pass more things to the scope. They will be available as variables in the code. Here's an example using [styled components](https://github.com/styled-components/styled-components): | ||
```js | ||
import styled from 'styled-components'; | ||
const headerProps = { text: 'I\'m styled!' }; | ||
const scope = {styled, headerProps}; | ||
const code = ` | ||
const Header = styled.div\` | ||
color: palevioletred; | ||
font-size: 18px; | ||
\` | ||
render(<Header>{headerProps.text}</Header>) | ||
` | ||
<LiveProvider code={code} scope={scope} noInline={true}> | ||
<LiveEditor /> | ||
<LiveError /> | ||
<LivePreview /> | ||
</LiveProvider> | ||
``` | ||
Here's an example using a custom component `<MyButton />`. This component lives in a different directory. It gets passed into the scope wrapped in an Object. Note that since we are not using `render()` in the code snippet we let `noInline` stay equal to the default of `false`: | ||
```js | ||
import { MyButton } from './components/MyButton'; | ||
const scope = { MyButton }; | ||
const code = ` | ||
<MyButton /> | ||
` | ||
<LiveProvider code={code} scope={scope}> | ||
<LiveEditor /> | ||
<LiveError /> | ||
<LivePreview /> | ||
</LiveProvider> | ||
``` | ||
### Using Hooks | ||
React Live supports using Hooks, but you may need to be mindful of the scope. As mentioned above, only React is injected into scope by default. | ||
This means that while you may be used to destructuring `useState` when importing React, to use hooks provided by React in React Live you will either need to stick to using `React.useState` or alternately you can set the scope up so that `useState` is provided separately. | ||
```js | ||
() => { | ||
const [likes, increaseLikes] = React.useState(0); | ||
return ( | ||
<> | ||
<p>{`${likes} likes`}</p> | ||
<button onClick={() => increaseLikes(likes + 1)}>Like</button> | ||
</> | ||
); | ||
}; | ||
``` | ||
### What bundle size can I expect? | ||
Our reported bundle size badges don't give you the full picture of | ||
the kind of sizes you will get in a production app. The minified | ||
bundles we publish _exclude_ some dependencies that we depend | ||
on. | ||
<img src="https://img.badgesize.io/https://unpkg.com/react-live/dist/react-live.min.js?compression=gzip&label=gzip%20size"> | ||
In an actual app when you use `react-live` you will also be bundling | ||
Sucrase for transpilation. | ||
## API | ||
### <LiveProvider /> | ||
This component provides the `context` for all the other ones. It also transpiles the user’s code! | ||
It supports these props, while passing any others through to the `children`: | ||
| Name | PropType | Description | | ||
| ------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| code | PropTypes.string | The code that should be rendered, apart from the user’s edits | | ||
| scope | PropTypes.object | Accepts custom globals that the `code` can use | | ||
| noInline | PropTypes.bool | Doesn’t evaluate and mount the inline code (Default: `false`). Note: when using `noInline` whatever code you write must be a single expression (function, class component or some `jsx`) that can be returned immediately. If you'd like to render multiple components, use `noInline={true}` | | ||
| transformCode | PropTypes.func | Accepts and returns the code to be transpiled, affording an opportunity to first transform it | | ||
| language | PropTypes.string | What language you're writing for correct syntax highlighting. (Default: `jsx`) | | ||
| disabled | PropTypes.bool | Disable editing on the `<LiveEditor />` (Default: `false`) | | ||
| theme | PropTypes.object | A `prism-react-renderer` theme object. See more [here](https://github.com/FormidableLabs/prism-react-renderer#theming) | | ||
All subsequent components must be rendered inside a provider, since they communicate | ||
using one. | ||
The `noInline` option kicks the Provider into a different mode, where you can write imperative-style | ||
code and nothing gets evaluated and mounted automatically. Your example will need to call `render` | ||
with valid JSX elements. | ||
### <LiveEditor /> | ||
This component renders the editor that displays the code. It is a wrapper around [`react-simple-code-editor`](https://github.com/satya164/react-simple-code-editor) and the code highlighted using [`prism-react-renderer`](https://github.com/FormidableLabs/prism-react-renderer). | ||
| Name | PropType | Description | | ||
| ------- | ----------------------------------------- | ----------------------------------------------------------------- | | ||
| style | PropTypes.object | Allows overriding default styles on the `LiveEditor` component. | | ||
| tabMode | PropTypes.oneOf(["indentation", "focus"]) | Sets how you want the tab key to work. (Default: `"indentation"`) | | ||
### <LiveError /> | ||
This component renders any error that occur while executing the code, or transpiling it. | ||
It passes through any props to a `pre`. | ||
> Note: Right now when the component unmounts, when there’s no error to be shown. | ||
### <LivePreview /> | ||
This component renders the actual component that the code generates inside an error boundary. | ||
| Name | PropType | Description | | ||
| --------- | -------------- | ------------------------------------------------------- | | ||
| Component | PropTypes.node | Element that wraps the generated code. (Default: `div`) | | ||
### withLive | ||
The `withLive` method creates a higher-order component, that injects the live-editing props provided | ||
by `LiveProvider` into a component. | ||
Using this HOC allows you to add new components to react-live, or replace the default ones, with a new | ||
desired behavior. | ||
The component wrapped with `withLive` gets injected the following props: | ||
| Name | PropType | Description | | ||
| -------- | ---------------- | -------------------------------------------------------------------------------------- | | ||
| code | PropTypes.string | Reflects the code that is passed in as the `code` prop | | ||
| error | PropTypes.string | An error that the code has thrown when it was previewed | | ||
| onError | PropTypes.func | A callback that, when called, changes the error to what's passed as the first argument | | ||
| onChange | PropTypes.func | A callback that accepts new code and transpiles it | | ||
| element | React.Element | The result of the transpiled code that is previewed | | ||
> Note: The code prop doesn't reflect the up-to-date code, but the `code` prop, that is passed to the `LiveProvider`. | ||
## FAQ | ||
> **I want to use experimental feature x but Sucrase doesn't support it! Can I use babel instead?** | ||
`react-live` doesn't currently support configuring the transpiler and it ships with Sucrase. The current workaround for using some experimental features `Sucrase` doesn't support would be to use the `transformCode` prop on `LiveProvider` to transform your code with `babel` alongside `Sucrase`. | ||
## Comparison to [component-playground](https://github.com/FormidableLabs/component-playground) | ||
There are multiple options when it comes to live, editable React component environments. Formidable actually has **two** first class projects to help you out: [`component-playground`](https://github.com/FormidableLabs/component-playground) and [`react-live`](https://github.com/FormidableLabs/react-live). Let's briefly look at the libraries, use cases, and factors that might help in deciding which is right for you. | ||
Here's a high-level decision tree: | ||
- If you want **fast and easy** setup and integration, then `component-playground` may be the ticket! | ||
- If you want **a smaller bundle**, **SSR**, and **more flexibility**, then `react-live` is for you! | ||
Here are the various factors at play: | ||
- **Build**: `component-playground` uses `babel-standalone`, `react-live` uses `Sucrase`. | ||
- **Bundle size**: `component-playground` has a larger bundle, but uses a more familiar editor setup. `react-live` is smaller, but more customized editor around `prism`. | ||
- **Ease vs. flexibility**: `react-live` is more modular/customizable, while `component-playground` is easier/faster to set up. | ||
- **Extra features**: `component-playground` supports raw evaluation and pretty-printed output out-of-the-box, while `react-live` does not. | ||
- **Error handling**: `component-playground` might have more predictable error handling than `react-live` in some cases (due to `react-dom`). | ||
## Maintenance Status | ||
**Active:** Formidable is actively working on this project, and we expect to continue for work for the foreseeable future. Bug reports, feature requests and pull requests are welcome. |
import React, { useContext } from "react"; | ||
import { act } from "react-dom/test-utils"; | ||
import { renderElementAsync } from "../../utils/transpile"; | ||
import { renderElementAsync } from "../../utils/transpile/index.ts"; | ||
import { render } from "../../utils/test/renderer"; | ||
import LiveProvider from "./LiveProvider"; | ||
import LiveContext from "./LiveContext"; | ||
import LiveProvider from "./LiveProvider.tsx"; | ||
import LiveContext from "./LiveContext.ts"; | ||
@@ -8,0 +8,0 @@ jest.mock("../../utils/transpile"); |
import React from "react"; | ||
import errorBoundary from "../transpile/errorBoundary"; | ||
import errorBoundary from "../transpile/errorBoundary.tsx"; | ||
import { render } from "./renderer"; | ||
@@ -4,0 +4,0 @@ |
import React from "react"; | ||
import { generateElement, renderElementAsync } from "../transpile"; | ||
import { generateElement, renderElementAsync } from "../transpile/index.ts"; | ||
import { shallow } from "./renderer"; | ||
@@ -4,0 +4,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
127994
44
3127
49
43
6
Updatedsucrase@^3.31.0