react-live
Advanced tools
Comparing version 3.0.0-rc1 to 3.0.0
@@ -431,2 +431,5 @@ 'use strict'; | ||
React.useEffect(function () { | ||
setCode(props.code); | ||
}, [props.code]); | ||
var onEditableChange = React.useCallback(function (_code) { | ||
@@ -445,5 +448,6 @@ setCode(_code.slice(0, -1)); | ||
return /*#__PURE__*/React__default['default'].createElement("div", { | ||
className: props.className | ||
className: props.className, | ||
style: props.style | ||
}, /*#__PURE__*/React__default['default'].createElement(Highlight__default['default'], { | ||
Prism: Highlight.Prism, | ||
Prism: props.prism || Highlight.Prism, | ||
code: code, | ||
@@ -463,3 +467,4 @@ theme: props.theme || theme, | ||
outline: "none", | ||
padding: 10 | ||
padding: 10, | ||
fontFamily: "inherit" | ||
}, !props.className || !props.theme ? {} : _style), | ||
@@ -649,53 +654,63 @@ ref: editorRef | ||
function transpile(newCode) { | ||
// Transpilation arguments | ||
var input = { | ||
code: transformCode ? transformCode(newCode) : newCode, | ||
scope: scope | ||
}; | ||
function transpileAsync(newCode) { | ||
var errorCallback = function errorCallback(error) { | ||
return setState({ | ||
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+ | ||
var renderElement = function renderElement(element) { | ||
return setState({ | ||
error: undefined, | ||
element: element | ||
}); | ||
}; | ||
try { | ||
if (noInline) { | ||
setState({ | ||
error: undefined, | ||
element: null | ||
}); // Reset output for async (no inline) evaluation | ||
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 | ||
renderElementAsync(input, renderElement, errorCallback); | ||
} else { | ||
renderElement(generateElement(input, errorCallback)); | ||
} | ||
} catch (error) { | ||
errorCallback(error); | ||
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)); | ||
} | ||
})["catch"](errorCallback); | ||
} catch (e) { | ||
errorCallback(e); | ||
return Promise.resolve(); | ||
} | ||
} | ||
var onError = function onError(error) { | ||
return setState({ | ||
error: error.toString() | ||
}); | ||
}; | ||
React.useEffect(function () { | ||
transpile(code); | ||
transpileAsync(code)["catch"](onError); | ||
}, [code, scope, noInline, transformCode]); | ||
var onChange = function onChange(newCode) { | ||
return transpile(newCode); | ||
transpileAsync(newCode)["catch"](onError); | ||
}; | ||
var onError = function onError(error) { | ||
return setState({ | ||
error: error.toString() | ||
}); | ||
}; | ||
return /*#__PURE__*/React__default['default'].createElement(LiveContext$1.Provider, { | ||
@@ -702,0 +717,0 @@ value: _objectSpread(_objectSpread({}, state), {}, { |
@@ -1,2 +0,2 @@ | ||
import React, { useState, useMemo, useLayoutEffect, useRef, useCallback, useEffect, createContext, Component, useContext } from 'react'; | ||
import React, { useState, useMemo, useLayoutEffect, useRef, useEffect, useCallback, createContext, Component, useContext } from 'react'; | ||
import Highlight, { Prism } from 'prism-react-renderer'; | ||
@@ -421,2 +421,5 @@ import { transform as transform$1 } from 'sucrase'; | ||
useEffect(function () { | ||
setCode(props.code); | ||
}, [props.code]); | ||
var onEditableChange = useCallback(function (_code) { | ||
@@ -435,5 +438,6 @@ setCode(_code.slice(0, -1)); | ||
return /*#__PURE__*/React.createElement("div", { | ||
className: props.className | ||
className: props.className, | ||
style: props.style | ||
}, /*#__PURE__*/React.createElement(Highlight, { | ||
Prism: Prism, | ||
Prism: props.prism || Prism, | ||
code: code, | ||
@@ -453,3 +457,4 @@ theme: props.theme || theme, | ||
outline: "none", | ||
padding: 10 | ||
padding: 10, | ||
fontFamily: "inherit" | ||
}, !props.className || !props.theme ? {} : _style), | ||
@@ -639,53 +644,63 @@ ref: editorRef | ||
function transpile(newCode) { | ||
// Transpilation arguments | ||
var input = { | ||
code: transformCode ? transformCode(newCode) : newCode, | ||
scope: scope | ||
}; | ||
function transpileAsync(newCode) { | ||
var errorCallback = function errorCallback(error) { | ||
return setState({ | ||
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+ | ||
var renderElement = function renderElement(element) { | ||
return setState({ | ||
error: undefined, | ||
element: element | ||
}); | ||
}; | ||
try { | ||
if (noInline) { | ||
setState({ | ||
error: undefined, | ||
element: null | ||
}); // Reset output for async (no inline) evaluation | ||
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 | ||
renderElementAsync(input, renderElement, errorCallback); | ||
} else { | ||
renderElement(generateElement(input, errorCallback)); | ||
} | ||
} catch (error) { | ||
errorCallback(error); | ||
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)); | ||
} | ||
})["catch"](errorCallback); | ||
} catch (e) { | ||
errorCallback(e); | ||
return Promise.resolve(); | ||
} | ||
} | ||
var onError = function onError(error) { | ||
return setState({ | ||
error: error.toString() | ||
}); | ||
}; | ||
useEffect(function () { | ||
transpile(code); | ||
transpileAsync(code)["catch"](onError); | ||
}, [code, scope, noInline, transformCode]); | ||
var onChange = function onChange(newCode) { | ||
return transpile(newCode); | ||
transpileAsync(newCode)["catch"](onError); | ||
}; | ||
var onError = function onError(error) { | ||
return setState({ | ||
error: error.toString() | ||
}); | ||
}; | ||
return /*#__PURE__*/React.createElement(LiveContext$1.Provider, { | ||
@@ -692,0 +707,0 @@ value: _objectSpread(_objectSpread({}, state), {}, { |
@@ -428,2 +428,5 @@ (function (global, factory) { | ||
React.useEffect(function () { | ||
setCode(props.code); | ||
}, [props.code]); | ||
var onEditableChange = React.useCallback(function (_code) { | ||
@@ -442,5 +445,6 @@ setCode(_code.slice(0, -1)); | ||
return /*#__PURE__*/React__default['default'].createElement("div", { | ||
className: props.className | ||
className: props.className, | ||
style: props.style | ||
}, /*#__PURE__*/React__default['default'].createElement(Highlight__default['default'], { | ||
Prism: Highlight.Prism, | ||
Prism: props.prism || Highlight.Prism, | ||
code: code, | ||
@@ -460,3 +464,4 @@ theme: props.theme || theme, | ||
outline: "none", | ||
padding: 10 | ||
padding: 10, | ||
fontFamily: "inherit" | ||
}, !props.className || !props.theme ? {} : _style), | ||
@@ -646,53 +651,63 @@ ref: editorRef | ||
function transpile(newCode) { | ||
// Transpilation arguments | ||
var input = { | ||
code: transformCode ? transformCode(newCode) : newCode, | ||
scope: scope | ||
}; | ||
function transpileAsync(newCode) { | ||
var errorCallback = function errorCallback(error) { | ||
return setState({ | ||
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+ | ||
var renderElement = function renderElement(element) { | ||
return setState({ | ||
error: undefined, | ||
element: element | ||
}); | ||
}; | ||
try { | ||
if (noInline) { | ||
setState({ | ||
error: undefined, | ||
element: null | ||
}); // Reset output for async (no inline) evaluation | ||
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 | ||
renderElementAsync(input, renderElement, errorCallback); | ||
} else { | ||
renderElement(generateElement(input, errorCallback)); | ||
} | ||
} catch (error) { | ||
errorCallback(error); | ||
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)); | ||
} | ||
})["catch"](errorCallback); | ||
} catch (e) { | ||
errorCallback(e); | ||
return Promise.resolve(); | ||
} | ||
} | ||
var onError = function onError(error) { | ||
return setState({ | ||
error: error.toString() | ||
}); | ||
}; | ||
React.useEffect(function () { | ||
transpile(code); | ||
transpileAsync(code)["catch"](onError); | ||
}, [code, scope, noInline, transformCode]); | ||
var onChange = function onChange(newCode) { | ||
return transpile(newCode); | ||
transpileAsync(newCode)["catch"](onError); | ||
}; | ||
var onError = function onError(error) { | ||
return setState({ | ||
error: error.toString() | ||
}); | ||
}; | ||
return /*#__PURE__*/React__default['default'].createElement(LiveContext$1.Provider, { | ||
@@ -699,0 +714,0 @@ value: _objectSpread(_objectSpread({}, state), {}, { |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("prism-react-renderer"),require("sucrase"),require("core-js/features/object/assign")):"function"==typeof define&&define.amd?define(["exports","react","prism-react-renderer","sucrase","core-js/features/object/assign"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactLive={},e.React,e.Prism,e.Sucrase,e.assign)}(this,(function(e,t,n,r,o){"use strict";function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=i(t),c=i(n),s=i(o);function u(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 f(e){var t=window.getSelection();t.empty(),t.addRange(e)}function d(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&"KeyZ"===e.code}function p(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 y(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 v(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 g={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 h(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 b(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?h(Object(n),!0).forEach((function(t){u(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):h(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var m=function(e){var r=t.useRef(null),o=t.useState(e.code||""),i=o[0],s=o[1],u=t.useCallback((function(e){s(e.slice(0,-1))}),[]);return function(e,n,r){function o(t){var n=e.current;if(n){var r=y(n);n=p(n),r.position+=t.length-n.length,g.position=r,g.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=v(r,n=(o=y(r)).position+(0>i?i:0),o.position+(0<i?i:0))).deleteContents(),t&&o.insertNode(document.createTextNode(t)),f(v(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=p(n).split("\n").slice(0,t.row);t.row&&(r+=o.join("\n").length+1),r+=t.column}f(v(n,r))}}function c(){var t=e.current;return{text:p(t),position:t=y(t)}}function s(){g.observer.disconnect()}r||(r={});var u=t.useState([])[1],g=t.useState((function(){var e={observer:null,disconnected:!1,onChange:n,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],h=t.useMemo((function(){return{update:o,insert:i,move:a,getState:c}}),[]);"object"!=typeof navigator||(t.useLayoutEffect((function(){if(g.onChange=n,e.current&&!r.disabled){if(g.disconnected=!1,g.observer.observe(e.current,l),g.position){var t=g.position,o=t.position;f(v(e.current,o,o+t.extent))}return s}})),t.useLayoutEffect((function(){if(e.current&&!r.disabled){var t=e.current;if(g.position){t.focus();var n=g.position,o=n.position;f(v(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 s,l=new RegExp("^(?:"+n+")"),b=new RegExp("^(?:"+n+")*("+n+")$"),m=function(n){if(e.current&&g.position){var r=p(t),o=y(t),i=(new Date).valueOf(),a=g.history[g.historyAt];!n&&500>i-s||a&&a[1]===r?s=i:(n=++g.historyAt,g.history[n]=[o,r],g.history.splice(n+1),500<n&&(g.historyAt--,g.history.shift()))}},O=function(){var e;if((e=g.queue).push.apply(e,g.observer.takeRecords()),e=y(t),g.queue.length){g.observer.disconnect(),g.disconnected=!0;var n,r,o=p(t);for(g.position=e;n=g.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])}g.onChange(o,e)}},E=function(e){if(!e.defaultPrevented&&e.target===t){if(g.disconnected)return e.preventDefault(),u([]);if(d(e))e.preventDefault(),e.shiftKey?(e=++g.historyAt,(e=g.history[e])||(g.historyAt=g.history.length-1)):(e=--g.historyAt,(e=g.history[e])||(g.historyAt=0)),e&&(g.observer.disconnect(),g.disconnected=!0,g.position=e[0],g.onChange(e[1],e[0]));else{if(m(),"Enter"===e.key){e.preventDefault();var n=y(t),o=/\S/g.exec(n.content);n="\n"+n.content.slice(0,o?o.index:n.content.length),h.insert(n)}else if(c&&!r.indentation||"Backspace"!==e.key){if(r.indentation&&"Tab"===e.key){e.preventDefault(),o=(n=y(t)).position-n.content.length;var i=p(t);n=e.shiftKey?i.slice(0,o)+n.content.replace(l,"")+i.slice(o+n.content.length):i.slice(0,o)+(r.indentation?" ".repeat(r.indentation):"\t")+i.slice(o),h.update(n)}}else e.preventDefault(),window.getSelection().getRangeAt(0).collapsed?(n=y(t),n=b.exec(n.content),h.insert("",n?-n[1].length:-1)):h.insert("",0);e.repeat&&O()}}},w=function(e){e.defaultPrevented||e.isComposing||(d(e)||m(),O(),t.focus())},j=function(e){g.position=window.getSelection().rangeCount&&e.target===t?y(t):null},C=function(e){e.preventDefault(),m(!0),h.insert(e.clipboardData.getData("text/plain")),m(!0),O()};return document.addEventListener("selectstart",j),window.addEventListener("keydown",E),t.addEventListener("paste",C),t.addEventListener("keyup",w),function(){document.removeEventListener("selectstart",j),window.removeEventListener("keydown",E),t.removeEventListener("paste",C),t.removeEventListener("keyup",w),t.style.whiteSpace=i,t.contentEditable=a}}g.history.length=0,g.historyAt=-1}),[e.current,r.disabled,r.indentation]))}(r,u,{disabled:e.disabled,indentation:2}),t.useEffect((function(){e.onChange&&e.onChange(i)}),[i]),a.default.createElement("div",{className:e.className},a.default.createElement(c.default,{Prism:n.Prism,code:i,theme:e.theme||g,language:e.language},(function(t){var n=t.className,o=t.tokens,i=t.getLineProps,c=t.getTokenProps,s=t.style;return a.default.createElement("pre",{className:n,style:b({margin:0,outline:"none",padding:10},e.className&&e.theme?s:{}),ref:r},o.map((function(e,t){return a.default.createElement("div",i({line:e,key:"line-"+t}),e.filter((function(e){return!e.empty})).map((function(e,t){return a.default.createElement("span",c({token:e,key:"token-"+t}))})),"\n")})))})))},O=t.createContext({}),E={transforms:["jsx","imports"]},w=function(e){return r.transform(e,E).code};function j(e,t){return(j=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,j(e,t)}var P=function(e,n){return function(t){function r(){return t.apply(this,arguments)||this}C(r,t);var o=r.prototype;return o.componentDidCatch=function(e){n(e)},o.render=function(){return"function"==typeof e?a.default.createElement(e,null):a.default.isValidElement(e)?e:null},r}(t.Component)};function S(){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 x(e,t,n){return(x=S()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&j(o,n.prototype),o}).apply(null,arguments)}var D={assign:s.default},k=function(e,t){var n=Object.keys(t),r=n.map((function(e){return t[e]}));return x(Function,["_poly","React"].concat(n,[e])).apply(void 0,[D,a.default].concat(r))};function N(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 L(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?N(Object(n),!0).forEach((function(t){u(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):N(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var R=function(e,t){var n=e.code,r=void 0===n?"":n,o=e.scope,i=void 0===o?{}:o,a=r.trim().replace(/;$/,""),c=w("return ("+a+")").trim();return P(k(c,i),t)},A=function(e,t,n){var r=e.code,o=void 0===r?"":r,i=e.scope,a=void 0===i?{}:i;if(!/render\s*\(/.test(o))return n(new SyntaxError("No-Inline evaluations must call `render`."));k(w(o),L(L({},a),{},{render:function(e){void 0===e?n(new SyntaxError("`render` must be called with valid JSX.")):t(P(e,n))}}))};function T(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 _(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?T(Object(n),!0).forEach((function(t){u(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):T(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function q(e){var n=e.children,r=e.code,o=e.language,i=e.theme,c=e.disabled,s=e.scope,u=e.transformCode,l=e.noInline,f=void 0!==l&&l,d=t.useState({error:void 0,element:void 0}),p=d[0],y=d[1];function v(e){var t={code:u?u(e):e,scope:s},n=function(e){return y({error:e.toString(),element:void 0})},r=function(e){return y({error:void 0,element:e})};try{f?(y({error:void 0,element:null}),A(t,r,n)):r(R(t,n))}catch(e){n(e)}}t.useEffect((function(){v(r)}),[r,s,f,u]);return a.default.createElement(O.Provider,{value:_(_({},p),{},{code:r,language:o,theme:i,disabled:c,onError:function(e){return y({error:e.toString()})},onChange:function(e){return v(e)}})},n)}function M(){return(M=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)}q.defaultProps={code:"",noInline:!1,language:"jsx",disabled:!1};var B=["Component"];function K(e){var n=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,B),o=t.useContext(O).element;return a.default.createElement(n,r,o?a.default.createElement(o,null):null)}K.defaultProps={Component:"div"},e.Editor=m,e.LiveContext=O,e.LiveEditor=function(e){var n=t.useContext(O),r=n.code,o=n.language,i=n.theme,c=n.disabled,s=n.onChange;return a.default.createElement(m,M({theme:i,code:r,language:o,disabled:c,onChange:s},e))},e.LiveError=function(e){var n=t.useContext(O).error;return n?a.default.createElement("pre",e,n):null},e.LivePreview=K,e.LiveProvider=q,e.generateElement=R,e.renderElementAsync=A,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(O.Consumer,null,(function(n){return a.default.createElement(e,M({live:n},t.props))}))},n}(t.Component)},Object.defineProperty(e,"__esModule",{value:!0})})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("prism-react-renderer"),require("sucrase"),require("core-js/features/object/assign")):"function"==typeof define&&define.amd?define(["exports","react","prism-react-renderer","sucrase","core-js/features/object/assign"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactLive={},e.React,e.Prism,e.Sucrase,e.assign)}(this,(function(e,t,n,r,o){"use strict";function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=i(t),c=i(n),s=i(o);function u(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 f(e){var t=window.getSelection();t.empty(),t.addRange(e)}function d(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&"KeyZ"===e.code}function p(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 y(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 v(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 g={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 h(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 b(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?h(Object(n),!0).forEach((function(t){u(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):h(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var m=function(e){var r=t.useRef(null),o=t.useState(e.code||""),i=o[0],s=o[1];t.useEffect((function(){s(e.code)}),[e.code]);var u=t.useCallback((function(e){s(e.slice(0,-1))}),[]);return function(e,n,r){function o(t){var n=e.current;if(n){var r=y(n);n=p(n),r.position+=t.length-n.length,g.position=r,g.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=v(r,n=(o=y(r)).position+(0>i?i:0),o.position+(0<i?i:0))).deleteContents(),t&&o.insertNode(document.createTextNode(t)),f(v(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=p(n).split("\n").slice(0,t.row);t.row&&(r+=o.join("\n").length+1),r+=t.column}f(v(n,r))}}function c(){var t=e.current;return{text:p(t),position:t=y(t)}}function s(){g.observer.disconnect()}r||(r={});var u=t.useState([])[1],g=t.useState((function(){var e={observer:null,disconnected:!1,onChange:n,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],h=t.useMemo((function(){return{update:o,insert:i,move:a,getState:c}}),[]);"object"!=typeof navigator||(t.useLayoutEffect((function(){if(g.onChange=n,e.current&&!r.disabled){if(g.disconnected=!1,g.observer.observe(e.current,l),g.position){var t=g.position,o=t.position;f(v(e.current,o,o+t.extent))}return s}})),t.useLayoutEffect((function(){if(e.current&&!r.disabled){var t=e.current;if(g.position){t.focus();var n=g.position,o=n.position;f(v(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 s,l=new RegExp("^(?:"+n+")"),b=new RegExp("^(?:"+n+")*("+n+")$"),m=function(n){if(e.current&&g.position){var r=p(t),o=y(t),i=(new Date).valueOf(),a=g.history[g.historyAt];!n&&500>i-s||a&&a[1]===r?s=i:(n=++g.historyAt,g.history[n]=[o,r],g.history.splice(n+1),500<n&&(g.historyAt--,g.history.shift()))}},O=function(){var e;if((e=g.queue).push.apply(e,g.observer.takeRecords()),e=y(t),g.queue.length){g.observer.disconnect(),g.disconnected=!0;var n,r,o=p(t);for(g.position=e;n=g.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])}g.onChange(o,e)}},E=function(e){if(!e.defaultPrevented&&e.target===t){if(g.disconnected)return e.preventDefault(),u([]);if(d(e))e.preventDefault(),e.shiftKey?(e=++g.historyAt,(e=g.history[e])||(g.historyAt=g.history.length-1)):(e=--g.historyAt,(e=g.history[e])||(g.historyAt=0)),e&&(g.observer.disconnect(),g.disconnected=!0,g.position=e[0],g.onChange(e[1],e[0]));else{if(m(),"Enter"===e.key){e.preventDefault();var n=y(t),o=/\S/g.exec(n.content);n="\n"+n.content.slice(0,o?o.index:n.content.length),h.insert(n)}else if(c&&!r.indentation||"Backspace"!==e.key){if(r.indentation&&"Tab"===e.key){e.preventDefault(),o=(n=y(t)).position-n.content.length;var i=p(t);n=e.shiftKey?i.slice(0,o)+n.content.replace(l,"")+i.slice(o+n.content.length):i.slice(0,o)+(r.indentation?" ".repeat(r.indentation):"\t")+i.slice(o),h.update(n)}}else e.preventDefault(),window.getSelection().getRangeAt(0).collapsed?(n=y(t),n=b.exec(n.content),h.insert("",n?-n[1].length:-1)):h.insert("",0);e.repeat&&O()}}},w=function(e){e.defaultPrevented||e.isComposing||(d(e)||m(),O(),t.focus())},j=function(e){g.position=window.getSelection().rangeCount&&e.target===t?y(t):null},C=function(e){e.preventDefault(),m(!0),h.insert(e.clipboardData.getData("text/plain")),m(!0),O()};return document.addEventListener("selectstart",j),window.addEventListener("keydown",E),t.addEventListener("paste",C),t.addEventListener("keyup",w),function(){document.removeEventListener("selectstart",j),window.removeEventListener("keydown",E),t.removeEventListener("paste",C),t.removeEventListener("keyup",w),t.style.whiteSpace=i,t.contentEditable=a}}g.history.length=0,g.historyAt=-1}),[e.current,r.disabled,r.indentation]))}(r,u,{disabled:e.disabled,indentation:2}),t.useEffect((function(){e.onChange&&e.onChange(i)}),[i]),a.default.createElement("div",{className:e.className,style:e.style},a.default.createElement(c.default,{Prism:e.prism||n.Prism,code:i,theme:e.theme||g,language:e.language},(function(t){var n=t.className,o=t.tokens,i=t.getLineProps,c=t.getTokenProps,s=t.style;return a.default.createElement("pre",{className:n,style:b({margin:0,outline:"none",padding:10,fontFamily:"inherit"},e.className&&e.theme?s:{}),ref:r},o.map((function(e,t){return a.default.createElement("div",i({line:e,key:"line-"+t}),e.filter((function(e){return!e.empty})).map((function(e,t){return a.default.createElement("span",c({token:e,key:"token-"+t}))})),"\n")})))})))},O=t.createContext({}),E={transforms:["jsx","imports"]},w=function(e){return r.transform(e,E).code};function j(e,t){return(j=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,j(e,t)}var P=function(e,n){return function(t){function r(){return t.apply(this,arguments)||this}C(r,t);var o=r.prototype;return o.componentDidCatch=function(e){n(e)},o.render=function(){return"function"==typeof e?a.default.createElement(e,null):a.default.isValidElement(e)?e:null},r}(t.Component)};function S(){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 x(e,t,n){return(x=S()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&j(o,n.prototype),o}).apply(null,arguments)}var D={assign:s.default},k=function(e,t){var n=Object.keys(t),r=n.map((function(e){return t[e]}));return x(Function,["_poly","React"].concat(n,[e])).apply(void 0,[D,a.default].concat(r))};function N(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 L(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?N(Object(n),!0).forEach((function(t){u(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):N(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var R=function(e,t){var n=e.code,r=void 0===n?"":n,o=e.scope,i=void 0===o?{}:o,a=r.trim().replace(/;$/,""),c=w("return ("+a+")").trim();return P(k(c,i),t)},A=function(e,t,n){var r=e.code,o=void 0===r?"":r,i=e.scope,a=void 0===i?{}:i;if(!/render\s*\(/.test(o))return n(new SyntaxError("No-Inline evaluations must call `render`."));k(w(o),L(L({},a),{},{render:function(e){void 0===e?n(new SyntaxError("`render` must be called with valid JSX.")):t(P(e,n))}}))};function T(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 _(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?T(Object(n),!0).forEach((function(t){u(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):T(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function q(e){var n=e.children,r=e.code,o=e.language,i=e.theme,c=e.disabled,s=e.scope,u=e.transformCode,l=e.noInline,f=void 0!==l&&l,d=t.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:s};f?(y({error:void 0,element:null}),A(r,n,t)):n(R(r,t))})).catch(t)}catch(e){return t(e),Promise.resolve()}}var g=function(e){return y({error:e.toString()})};t.useEffect((function(){v(r).catch(g)}),[r,s,f,u]);return a.default.createElement(O.Provider,{value:_(_({},p),{},{code:r,language:o,theme:i,disabled:c,onError:g,onChange:function(e){v(e).catch(g)}})},n)}function M(){return(M=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)}q.defaultProps={code:"",noInline:!1,language:"jsx",disabled:!1};var B=["Component"];function K(e){var n=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,B),o=t.useContext(O).element;return a.default.createElement(n,r,o?a.default.createElement(o,null):null)}K.defaultProps={Component:"div"},e.Editor=m,e.LiveContext=O,e.LiveEditor=function(e){var n=t.useContext(O),r=n.code,o=n.language,i=n.theme,c=n.disabled,s=n.onChange;return a.default.createElement(m,M({theme:i,code:r,language:o,disabled:c,onChange:s},e))},e.LiveError=function(e){var n=t.useContext(O).error;return n?a.default.createElement("pre",e,n):null},e.LivePreview=K,e.LiveProvider=q,e.generateElement=R,e.renderElementAsync=A,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(O.Consumer,null,(function(n){return a.default.createElement(e,M({live:n},t.props))}))},n}(t.Component)},Object.defineProperty(e,"__esModule",{value:!0})})); |
{ | ||
"name": "react-live", | ||
"version": "3.0.0-rc1", | ||
"version": "3.0.0", | ||
"description": "A production-focused playground for live editing React code", | ||
@@ -53,2 +53,3 @@ "main": "dist/react-live.cjs.js", | ||
"prettier": "^2.5.1", | ||
"prismjs": "^1.26.0", | ||
"prop-types": "^15.7.2", | ||
@@ -93,2 +94,4 @@ "react": "^17.0.2", | ||
"jest": { | ||
"testEnvironment": "jsdom", | ||
"resetMocks": true, | ||
"rootDir": "./src", | ||
@@ -95,0 +98,0 @@ "testURL": "http://localhost/" |
@@ -17,3 +17,2 @@ <p align="center"><img src="https://user-images.githubusercontent.com/17658189/63178611-4e90d580-c042-11e9-875f-f2455148b9ae.png" width=250></p> | ||
**React Live** brings you the ability to render React components with editable source code and live preview. | ||
It supports server-side rendering and comes in a tiny bundle. | ||
@@ -52,3 +51,3 @@ The library is structured modularly and lets you style and compose its components freely. | ||
It takes your code and transpiles it with [Bublé](https://github.com/bublejs/buble), while the code is displayed using [`react-simple-code-editor`](https://github.com/satya164/react-simple-code-editor) and the code is highlighted using [`prism-react-renderer`](https://github.com/FormidableLabs/prism-react-renderer). | ||
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). | ||
@@ -58,2 +57,14 @@ The transpiled code is then rendered in the preview component (`LivePreview`), which does a fake mount if the code | ||
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? | ||
@@ -65,2 +76,3 @@ | ||
- React pure functional components, e.g. `() => <strong>Hello World!</strong>` | ||
- React functional components with Hooks | ||
- React component classes | ||
@@ -129,2 +141,24 @@ | ||
### 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? | ||
@@ -140,13 +174,4 @@ | ||
In an actual app when you use `react-live` you will also be bundling | ||
Buble for transpilation, which adds `~135kB` to your bundle. This also | ||
includes their dependency on `regenerate-unicode-properties`, which | ||
is rather large as well. | ||
Sucrase for transpilation. | ||
We maintain a fork of Buble which excludes the ESnext Regular Expression | ||
transpilation with removes Buble's large dependency and weighs in at | ||
a smaller size of `~51kB`, which you can find published at [`@philpl/buble`](https://npm.im/@philpl/buble). | ||
You can alias this in Webpack or the build tool of your choice, which | ||
will reduce the overall bundle size of `react-live` to about `83kB`. | ||
## API | ||
@@ -225,13 +250,8 @@ | ||
## FAQ | ||
> **I want to use experimental feature x but Bublé doesn't support it! Can I use babel instead?** | ||
> **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 Bublé. The current workaround for using some experimental features `bublé` doesn't support would be to use the `transformCode` prop on `LiveProvider` to transform your code with `babel` alongside `bublé`. | ||
`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`. | ||
Here is a minimal example on how you could use `babel` to support class-properties in `react-live`: | ||
[![Edit 7ml9mjw766](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/7ml9mjw766?fontsize=14) | ||
## Comparison to [component-playground](https://github.com/FormidableLabs/component-playground) | ||
@@ -248,8 +268,7 @@ | ||
- **Build**: `component-playground` uses `babel-standalone`, `react-live` uses `bublé`. (_Note_: `react-live` might make transpiler customizable in the future). | ||
- **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. | ||
- **SSR**: `component-playground` is not server-side renderable, `react-live` is. | ||
- **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`, although this might change with React 16). | ||
- **Error handling**: `component-playground` might have more predictable error handling than `react-live` in some cases (due to `react-dom`). | ||
@@ -256,0 +275,0 @@ ## Maintenance Status |
@@ -11,2 +11,6 @@ import React, { useEffect, useState, useRef, useCallback } from "react"; | ||
useEffect(() => { | ||
setCode(props.code); | ||
}, [props.code]); | ||
const onEditableChange = useCallback((_code) => { | ||
@@ -28,5 +32,5 @@ setCode(_code.slice(0, -1)); | ||
return ( | ||
<div className={props.className}> | ||
<div className={props.className} style={props.style}> | ||
<Highlight | ||
Prism={Prism} | ||
Prism={props.prism || Prism} | ||
code={code} | ||
@@ -49,2 +53,3 @@ theme={props.theme || liveTheme} | ||
padding: 10, | ||
fontFamily: "inherit", | ||
...(!props.className || !props.theme ? {} : _style), | ||
@@ -81,2 +86,3 @@ }} | ||
onChange: PropTypes.func, | ||
prism: PropTypes.object, | ||
style: PropTypes.object, | ||
@@ -83,0 +89,0 @@ theme: PropTypes.object, |
@@ -22,34 +22,51 @@ import React, { useEffect, useState } from "react"; | ||
function transpile(newCode) { | ||
// Transpilation arguments | ||
const input = { | ||
code: transformCode ? transformCode(newCode) : newCode, | ||
scope, | ||
function transpileAsync(newCode) { | ||
const errorCallback = (error) => { | ||
setState({ error: error.toString(), element: undefined }); | ||
}; | ||
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; | ||
const renderElement = (element) => setState({ error: undefined, element }); | ||
return Promise.resolve(transformResult) | ||
.then((transformedCode) => { | ||
const renderElement = (element) => | ||
setState({ error: undefined, element }); | ||
try { | ||
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) { | ||
errorCallback(error); | ||
// Transpilation arguments | ||
const input = { | ||
code: transformedCode, | ||
scope, | ||
}; | ||
if (noInline) { | ||
setState({ error: undefined, element: null }); // Reset output for async (no inline) evaluation | ||
renderElementAsync(input, renderElement, errorCallback); | ||
} else { | ||
renderElement(generateElement(input, errorCallback)); | ||
} | ||
}) | ||
.catch(errorCallback); | ||
} catch (e) { | ||
errorCallback(e); | ||
return Promise.resolve(); | ||
} | ||
} | ||
const onError = (error) => setState({ error: error.toString() }); | ||
useEffect(() => { | ||
transpile(code); | ||
transpileAsync(code).catch(onError); | ||
}, [code, scope, noInline, transformCode]); | ||
const onChange = (newCode) => transpile(newCode); | ||
const onChange = (newCode) => { | ||
transpileAsync(newCode).catch(onError); | ||
}; | ||
const onError = (error) => setState({ error: error.toString() }); | ||
return ( | ||
@@ -80,3 +97,3 @@ <LiveContext.Provider | ||
theme: PropTypes.object, | ||
transformCode: PropTypes.node, | ||
transformCode: PropTypes.func, | ||
}; | ||
@@ -83,0 +100,0 @@ |
@@ -16,3 +16,3 @@ import { ComponentClass, HTMLProps, ComponentType, Context } from 'react' | ||
noInline?: boolean; | ||
transformCode?: (code: string) => string; | ||
transformCode?: (code: string) => (string | Promise<string>); | ||
language?: Language; | ||
@@ -32,2 +32,3 @@ disabled?: boolean; | ||
theme?: PrismTheme; | ||
prism?: unknown | ||
} | ||
@@ -34,0 +35,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
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
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
124047
25
2805
2
271
37