livecode-static/docs/assets/js/63218e6b.d8109721.js
2025-06-12 09:37:26 +08:00

84 lines
25 KiB
JavaScript

"use strict";(self.webpackChunkdocs=self.webpackChunkdocs||[]).push([["1558"],{6519:function(e,t,n){n.r(t),n.d(t,{default:()=>m,frontMatter:()=>a,metadata:()=>s,assets:()=>c,libParams:()=>h,params:()=>u,toc:()=>p,contentTitle:()=>d});var s=JSON.parse('{"id":"languages/r","title":"R","description":"LiveCodes runs R statistical programming language in the browser using WebR.","source":"@site/docs/languages/r.mdx","sourceDirName":"languages","slug":"/languages/r","permalink":"/docs/languages/r","draft":false,"unlisted":false,"editUrl":"https://github.com/live-codes/livecodes/tree/develop/docs/docs/languages/r.mdx","tags":[],"version":"current","frontMatter":{},"sidebar":"docsSidebar","previous":{"title":"Python","permalink":"/docs/languages/python"},"next":{"title":"React Native (TSX)","permalink":"/docs/languages/react-native-tsx"}}'),r=n("5893"),i=n("65"),o=n("8500"),l=n("3365");let a={},d="R",c={},h={r:`library(dplyr)
starwars %>%
filter(species == "Droid")
`,languages:"r",console:"open",compiled:"none"},u={r:`head(iris)
PW <- iris$Petal.Width
PL <- iris$Petal.Length
species <- iris$Species
speciesID <- as.numeric(species)
plot(PL, PW,
pch = speciesID,
col = speciesID,
main = "Petal Width vs Length",
xlab = "Petal Length",
ylab = "Petal Width")
legend("topleft",
levels(species),
pch = 1:3,
col = 1:3)
`,html:`<h2>Output</h2>
<div id="output"></div>
<h2>Plots</h2>
<div id="plots"></div>
<script type="module">
livecodes.r.config = {
container: null,
};
await livecodes.r.evaluated;
const pre = document.createElement('pre');
pre.innerHTML = livecodes.r.output;
document.querySelector('#output').appendChild(pre);
document.querySelector('#plots').appendChild(...livecodes.r.plots);
</script>
`,activeEditor:"script"},p=[{value:"Usage",id:"usage",level:2},{value:"Loading Packages",id:"loading-packages",level:3},{value:"Output Rendering",id:"output-rendering",level:3},{value:"Examples",id:"examples",level:3},{value:"Demo",id:"demo",level:2},{value:"Language Info",id:"language-info",level:2},{value:"Name",id:"name",level:3},{value:"Extension",id:"extension",level:3},{value:"Aliases",id:"aliases",level:3},{value:"Editor",id:"editor",level:3},{value:"Compiler",id:"compiler",level:2},{value:"Version",id:"version",level:3},{value:"Code Formatting",id:"code-formatting",level:2},{value:"Live Reload",id:"live-reload",level:2},{value:"Starter Template",id:"starter-template",level:2},{value:"Links",id:"links",level:2}];function g(e){let t={a:"a",blockquote:"blockquote",code:"code",h1:"h1",h2:"h2",h3:"h3",header:"header",li:"li",p:"p",pre:"pre",ul:"ul",...(0,i.a)(),...e.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(t.header,{children:(0,r.jsx)(t.h1,{id:"r",children:"R"})}),"\n","\n",(0,r.jsxs)(t.p,{children:["LiveCodes runs ",(0,r.jsx)(t.a,{href:"https://www.r-project.org/",children:"R"})," statistical programming language in the browser using ",(0,r.jsx)(t.a,{href:"https://docs.r-wasm.org/webr/latest/",children:"WebR"}),"."]}),"\n",(0,r.jsxs)(t.blockquote,{children:["\n",(0,r.jsxs)(t.p,{children:["WebR is a version of the statistical language ",(0,r.jsx)(t.a,{href:"https://www.r-project.org/",children:"R"})," compiled for the browser and ",(0,r.jsx)(t.a,{href:"https://nodejs.org/en/",children:"Node.js"})," using ",(0,r.jsx)(t.a,{href:"https://webassembly.org/",children:"WebAssembly"}),", via ",(0,r.jsx)(t.a,{href:"https://emscripten.org/",children:"Emscripten"}),"."]}),"\n"]}),"\n",(0,r.jsxs)(t.blockquote,{children:["\n",(0,r.jsx)(t.p,{children:"WebR makes it possible to run R code in the browser without the need for an R server to execute the code: the R interpreter runs directly on the user\u2019s machine. Several R packages have also been ported for use with webR, and can be loaded in the usual way."}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.a,{href:"https://docs.r-wasm.org/webr/",children:"https://docs.r-wasm.org/webr/"})}),"\n"]}),"\n",(0,r.jsx)(t.h2,{id:"usage",children:"Usage"}),"\n",(0,r.jsxs)(t.p,{children:["Check the ",(0,r.jsx)(t.a,{href:"#starter-template",children:"starter template"})," for an example."]}),"\n",(0,r.jsx)(t.h3,{id:"loading-packages",children:"Loading Packages"}),"\n",(0,r.jsxs)(t.p,{children:[(0,r.jsx)(t.a,{href:"https://repo.r-wasm.org/",children:"Supported packages"})," can just be loaded in code, using the ",(0,r.jsx)(t.code,{children:"library()"})," function, without the need for any explicit installs. Packages are publicly hosted via a CDN in a CRAN-like repository with URL, ",(0,r.jsx)(t.a,{href:"https://repo.r-wasm.org/",children:"https://repo.r-wasm.org/"})]}),"\n",(0,r.jsx)(t.p,{children:"Example:"}),"\n","\n",(0,r.jsx)(o.Z,{params:h,code:h.r,language:"r",formatCode:!1}),"\n",(0,r.jsx)(t.h3,{id:"output-rendering",children:"Output Rendering"}),"\n",(0,r.jsxs)(t.p,{children:["By default, the R code is evaluated and the output is rendered in the ",(0,r.jsx)(t.code,{children:"document.body"})," of the result page, followed by the plots (rendered as HTML canvas elements)."]}),"\n",(0,r.jsxs)(t.p,{children:["The evaluation and rendering behavior can be configured by adding a ",(0,r.jsx)(t.code,{children:"script"})," element in the HTML (markup editor) and setting ",(0,r.jsx)(t.code,{children:"livecodes.r.config"}),"."]}),"\n",(0,r.jsx)(t.p,{children:"Example:"}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-html",metastring:'title="HTML"',children:"<div id=\"output\"></div>\n\n<script>\n livecodes.r.config = {\n container: document.querySelector('#output'),\n // other options\n };\n<\/script>\n"})}),"\n",(0,r.jsx)(t.p,{children:"The following configurations are supported:"}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"container"}),": CSS selector of the element in which the R code is rendered. If not specified, the output is rendered in ",(0,r.jsx)(t.code,{children:"document.body"}),". If set to ",(0,r.jsx)(t.code,{children:"null"}),", the output is not rendered automatically, and can then be accessed via ",(0,r.jsx)(t.code,{children:"livecodes.r.output"})," (see below)."]}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"canvasHeight"}),": a number representing the height of the output canvas in pixels. Defaults to ",(0,r.jsx)(t.code,{children:"309"}),"."]}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"canvasWidth"}),": a number representing the width of the output canvas in pixels. Defaults to ",(0,r.jsx)(t.code,{children:"500"}),"."]}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"canvasPointSize"}),": a number representing the plots point size. Defaults to ",(0,r.jsx)(t.code,{children:"12"}),"."]}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"canvasBackground"}),": a string representing the plots background color. Defaults to ",(0,r.jsx)(t.code,{children:'"transparent"'}),"."]}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"autoEvaluate"}),": a boolean indicating whether the R code is evaluated automatically. Defaults to ",(0,r.jsx)(t.code,{children:"true"}),"."]}),"\n"]}),"\n",(0,r.jsx)(t.p,{children:"In addition, detecting and triggering evaluation can be controlled using:"}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"livecodes.r.evaluated"}),": a promise that can be awaited to denote when the R code has been evaluated when ",(0,r.jsx)(t.code,{children:"livecodes.r.config.autoEvaluate"})," is set to ",(0,r.jsx)(t.code,{children:"true"}),"."]}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"livecodes.r.run()"}),": an async method that triggers the evaluation of the R code. This is useful when ",(0,r.jsx)(t.code,{children:"livecodes.r.config.autoEvaluate"})," is set to ",(0,r.jsx)(t.code,{children:"false"}),". It may take an optional parameter representing the config object (see above)"]}),"\n"]}),"\n",(0,r.jsx)(t.p,{children:"The output and plots can be accessed via:"}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"livecodes.r.output"}),": a string representing the output of the R code."]}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"livecodes.r.plots"}),": an array of HTML canvas elements representing the plots."]}),"\n"]}),"\n",(0,r.jsxs)(t.p,{children:["These are available after the promise ",(0,r.jsx)(t.code,{children:"livecodes.r.evaluated"})," or that returned by ",(0,r.jsx)(t.code,{children:"livecodes.r.run()"})," is resolved"]}),"\n",(0,r.jsx)(t.h3,{id:"examples",children:"Examples"}),"\n",(0,r.jsx)(t.p,{children:"This example shows how to specify the container (for output and plots):"}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-html",metastring:'title="HTML"',children:"<div id=\"container\"></div>\n\n<script>\n livecodes.r.config = {\n container: document.querySelector('#container'),\n };\n<\/script>\n"})}),"\n",(0,r.jsx)(t.p,{children:"This example shows how to specify different containers for output and plots:"}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-html",metastring:'title="HTML"',children:"<h2>Output</h2>\n<div id=\"output\"></div>\n<h2>Plots</h2>\n<div id=\"plots\"></div>\n\n<script type=\"module\">\n livecodes.r.config = {\n container: null,\n };\n\n await livecodes.r.evaluated;\n\n const pre = document.createElement('pre');\n pre.innerHTML = livecodes.r.output;\n document.querySelector('#output').appendChild(pre);\n\n document.querySelector('#plots').appendChild(...livecodes.r.plots);\n<\/script>\n"})}),"\n",(0,r.jsx)(t.p,{children:"This example shows how to control when to trigger evaluation of the R code.:"}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-html",metastring:'title="HTML"',children:"<h2>Output</h2>\n<div id=\"output\"></div>\n<h2>Plots</h2>\n<div id=\"plots\"></div>\n\n<script type=\"module\">\n livecodes.r.config = {\n container: null,\n autoEvaluate: false,\n };\n\n await livecodes.r.run();\n\n const pre = document.createElement('pre');\n pre.innerHTML = livecodes.r.output;\n document.querySelector('#output').appendChild(pre);\n\n document.querySelector('#plots').appendChild(...livecodes.r.plots);\n<\/script>\n"})}),"\n",(0,r.jsx)(t.h2,{id:"demo",children:"Demo"}),"\n","\n",(0,r.jsx)(l.Z,{params:u,height:"80vh"}),"\n",(0,r.jsx)(t.h2,{id:"language-info",children:"Language Info"}),"\n",(0,r.jsx)(t.h3,{id:"name",children:"Name"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.code,{children:"r"})}),"\n",(0,r.jsx)(t.h3,{id:"extension",children:"Extension"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.code,{children:".r"})}),"\n",(0,r.jsx)(t.h3,{id:"aliases",children:"Aliases"}),"\n",(0,r.jsxs)(t.p,{children:[(0,r.jsx)(t.code,{children:"rlang"}),", ",(0,r.jsx)(t.code,{children:"rstats"}),", ",(0,r.jsx)(t.code,{children:"r-wasm"})]}),"\n",(0,r.jsx)(t.h3,{id:"editor",children:"Editor"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.code,{children:"script"})}),"\n",(0,r.jsx)(t.h2,{id:"compiler",children:"Compiler"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.a,{href:"https://docs.r-wasm.org/webr/latest/",children:"WebR"})}),"\n",(0,r.jsx)(t.h3,{id:"version",children:"Version"}),"\n",(0,r.jsx)(t.p,{children:"WebR v0.4.0, running R v4.4.1"}),"\n",(0,r.jsx)(t.h2,{id:"code-formatting",children:"Code Formatting"}),"\n",(0,r.jsx)(t.p,{children:"Not supported."}),"\n",(0,r.jsx)(t.h2,{id:"live-reload",children:"Live Reload"}),"\n",(0,r.jsx)(t.p,{children:"By default, when code is updated, the WebR environment is re-used while the global variables are reset. This behavior is used for performance reasons. However, in order to fully reload WebR and start a new environment, insert this comment in the code:"}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-r",children:"# __livecodes_reload__\n"})}),"\n",(0,r.jsx)(t.p,{children:"Think of this like restarting the kernel in Jupyter notebooks."}),"\n",(0,r.jsx)(t.h2,{id:"starter-template",children:"Starter Template"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.a,{href:"https://livecodes.io/?template=r",children:"https://livecodes.io/?template=r"})}),"\n",(0,r.jsx)(t.h2,{id:"links",children:"Links"}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsx)(t.li,{children:(0,r.jsx)(t.a,{href:"https://www.r-project.org/",children:"R"})}),"\n",(0,r.jsx)(t.li,{children:(0,r.jsx)(t.a,{href:"https://docs.r-wasm.org/webr/latest/",children:"WebR"})}),"\n",(0,r.jsx)(t.li,{children:(0,r.jsx)(t.a,{href:"https://repo.r-wasm.org/",children:"Supported packages"})}),"\n"]})]})}function m(e={}){let{wrapper:t}={...(0,i.a)(),...e.components};return t?(0,r.jsx)(t,{...e,children:(0,r.jsx)(g,{...e})}):g(e)}},3365:function(e,t,n){n.d(t,{Z:()=>v});var s=n("5893"),r=n("4200"),i=n("7294"),o=n("8294");function l(e){let t=(0,i.useRef)(null),[n,r]=(0,i.useState)(e.className||""),[l,a]=(0,i.useState)(e.style||{}),[d,c]=(0,i.useState)(e.height),[h,u]=(0,i.useState)(),[p,g]=(0,i.useState)(JSON.stringify(e.config||"")),[m,v]=(0,i.useState)("");return(0,i.useEffect)(()=>{if(!t.current)return;let{className:n,style:s,height:i,sdkReady:l,config:d,...f}=e;if(r(n||""),a(s||{}),c(i),h&&m===JSON.stringify(f)){if(p===JSON.stringify(d))return;g(JSON.stringify(d)),"string"==typeof d?fetch(d).then(e=>e.json()).then(e=>{h?.setConfig(e)}):d&&h.setConfig(d)}else v(JSON.stringify(f)),h?.destroy(),(0,o.T)(t.current,{config:d,...f}).then(e=>{u(e),"function"==typeof l&&l(e)})},[e]),(0,i.useEffect)(()=>()=>{h?.destroy()},[]),(0,s.jsx)("div",{ref:t,className:n,style:l,"data-height":d})}var a=n("1858"),d=n("3262"),c=n("1705"),h=n("7645"),u=n("8168"),p=n("8228"),g=n("5050");function m(e){let[t,n]=(0,i.useState)(e.js),[r,o]=(0,i.useState)(e.ts),[l,a]=(0,i.useState)(e.react),[m,v]=(0,i.useState)(e.vue),[f,x]=(0,i.useState)(e.svelte),j="3.7rem",[y,w]=(0,i.useState)(!0),[b,S]=(0,i.useState)(j),R=(0,i.useRef)(null),C=()=>{setTimeout(()=>{S(`calc(${R.current.offsetHeight}px + ${j})`)},5),setTimeout(()=>{S(`calc(${R.current.offsetHeight}px + ${j})`)},255)};return(0,i.useEffect)(()=>{if(d.Z.canUseDOM){let e=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"js";try{return window.prettier?.format(e,{parser:"html"===t?"html":"babel",plugins:window.prettierPlugins})}catch{return e}};n(e(t,"js")),o(e(r,"ts")),a(e(l,"jsx")),v(e(m,"html")),x(e(f,"html"))}},[]),(0,s.jsxs)("details",{className:`alert alert--info ${g.Z.details} ${p.Z.details}`,"data-collapsed":y,style:{height:y?j:b,overflow:"hidden",willChange:"height",transition:`height ${y?"250ms":"265ms"} ease-in-out 0s`,margin:"1em 0"},children:[(0,s.jsx)("summary",{onClick:()=>{w(!y),C()},children:"show code"}),(0,s.jsx)("div",{ref:R,style:{display:"block",overflow:"hidden"},children:(0,s.jsx)("div",{className:g.Z.collapsibleContent,children:(0,s.jsxs)(u.Z,{groupId:"sdk-code",children:[(0,s.jsx)(h.Z,{value:"js",label:"JS",attributes:{onMouseDown:C},children:(0,s.jsx)(c.Z,{language:"js",children:t})}),(0,s.jsx)(h.Z,{value:"ts",label:"TS",attributes:{onMouseDown:C},children:(0,s.jsx)(c.Z,{language:"ts",children:r})}),(0,s.jsx)(h.Z,{value:"react",label:"React",attributes:{onMouseDown:C},children:(0,s.jsx)(c.Z,{language:"jsx",children:l})}),(0,s.jsx)(h.Z,{value:"vue",label:"Vue",attributes:{onMouseDown:C},children:(0,s.jsx)(c.Z,{language:"html",children:m})}),(0,s.jsx)(h.Z,{value:"svelte",label:"Svelte",attributes:{onMouseDown:C},children:(0,s.jsx)(c.Z,{language:"html",children:f})})]})})})]})}function v(e){let{className:t,style:n,showCode:i,height:o,...d}=e,{colorMode:c}=(0,r.I)(),h=e=>JSON.stringify(e,null,2),u=`
import { createPlayground } from 'livecodes';
const options = ${h(d)};
createPlayground('#container', options);
`.trimStart(),p=`
import { createPlayground, type EmbedOptions } from 'livecodes';
const options: EmbedOptions = ${h(d)};
createPlayground('#container', options);
`.trimStart(),g=`
import LiveCodes from 'livecodes/react';
export default function App() {
const options = ${h(d)};
return (<LiveCodes {...options}></LiveCodes>);
}
`.trimStart(),v=`
<script setup>
import LiveCodes from "livecodes/vue";
const options = ${h(d)};
</script>
<template>
<LiveCodes v-bind="options" />
</template>
`,f=`
<script>
import { onMount } from 'svelte';
import { createPlayground } from 'livecodes';
let options = $state(${h(d)});
let container = $state(null);
onMount(() => {
createPlayground(container, options);
});
</script>
<div bind:this="{container}"></div>
`.trimStart();return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(l,{className:`container_Egsj ${e.className}`,style:{height:o||"50vh",...e.style},appUrl:a.G,...e,config:{theme:c,themeColor:"hsl(215, 8%, 60%)",..."object"==typeof e.config?e.config:{}}}),!1!==e.showCode&&(0,s.jsx)(m,{js:u,ts:p,react:g,vue:v,svelte:f})]})}},8500:function(e,t,n){n.d(t,{Z:()=>d});var s=n("5893");n("7294");var r=n("6735");function i(e){let{children:t,fallback:n}=e;return(0,r.Z)()?(0,s.jsx)(s.Fragment,{children:t?.()}):n??null}var o=n("1705"),l=n("8294"),a=n("1858");function d(e){let{params:t,config:n,code:r,language:d="js",codeTitle:c="",showLineNumbers:h=!1,formatCode:u=!0,linkText:p="Run in LiveCodes",style:g={},className:m=""}=e,v=(0,l.r)({appUrl:a.G,params:t,config:n});return(0,s.jsxs)("div",{style:{marginBottom:"30px",...g},className:m,children:[r&&(0,s.jsx)(i,{children:()=>(0,s.jsx)(o.Z,{language:d,title:c,showLineNumbers:h,children:u?function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"js";return window.prettier?.format(e,{parser:"html"===t?"html":"babel",plugins:window.prettierPlugins})}(r,d):r})}),(0,s.jsxs)("a",{href:v,target:"_blank",rel:"noreferrer",children:[p,(0,s.jsx)("svg",{width:"12",height:"12","aria-hidden":"true",viewBox:"0 0 24 24",className:"iconExternalLink_node_modules-@docusaurus-theme-classic-lib-theme-Icon-ExternalLink-styles-module",style:{marginLeft:"4px"},children:(0,s.jsx)("path",{fill:"currentColor",d:"M21 13v10h-21v-19h12v2h-10v15h17v-8h2zm3-12h-10.988l4.035 4-6.977 7.07 2.828 2.828 6.977-7.07 4.125 4.172v-11z"})})]})]})}},8294:function(e,t,n){n.d(t,{T:function(){return r},r:function(){return i}});var s=n(7728);async function r(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"object"!=typeof e||e instanceof HTMLElement||!e.headless&&"headless"!==e.view||(t=e,e=null);let{config:n={},headless:s,loading:r="lazy",view:o}=t,l=s||"headless"===o,a=null,d=null;if("string"==typeof e)a=document.querySelector(e);else if(e instanceof HTMLElement)a=e;else if(!(l&&"object"==typeof e))throw Error("A valid container element is required.");if(!a){if(l)R(a=document.createElement("div")),document.body.appendChild(a);else throw Error(`Cannot find element: "${e}"`)}let c=new URL(i(t)),h=c.origin;c.searchParams.set("embed","true"),c.searchParams.set("loading",l?"eager":r),c.searchParams.set("sdkVersion",process.env.SDK_VERSION||"latest"),"object"==typeof n&&Object.keys(n).length>0&&c.searchParams.set("config","sdk");let u=t.params;"object"==typeof u&&Object.keys(u).length>0&&JSON.stringify(u).length<1800&&Object.keys(u).forEach(e=>{c.searchParams.set(e,encodeURIComponent(String(u[e])))});let p=!1,g="Cannot call API methods after calling `destroy()`.",m=await new Promise(e=>{if(!a)return;let t=a.dataset.height||a.style.height;if(t&&!l){let e=isNaN(Number(t))?t:t+"px";a.style.height=e}"false"===a.dataset.defaultStyles||l||(a.style.backgroundColor||="#fff",a.style.border||="1px solid black",a.style.borderRadius||="8px",a.style.boxSizing||="border-box",a.style.padding||="0",a.style.width||="100%",a.style.height||=a.style.height||"300px",a.style.minHeight="200px",a.style.flexGrow="1",a.style.overflow||="hidden",a.style.resize||="vertical");let s="livecodes",i=a.querySelector(`iframe.${s}`),o=i||document.createElement("iframe");o.classList.add(s),o.setAttribute("allow","accelerometer; camera; encrypted-media; display-capture; geolocation; gyroscope; microphone; midi; clipboard-read; clipboard-write; web-share"),o.setAttribute("allowtransparency","true"),o.setAttribute("allowpaymentrequest","true"),o.setAttribute("allowfullscreen","true"),o.setAttribute("sandbox","allow-same-origin allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-presentation allow-scripts"),o.setAttribute("loading","eager"===r?"eager":"lazy"),l?R(o):(o.style.height="100%",o.style.minHeight="200px",o.style.width="100%",o.style.margin="0",o.style.border="0",o.style.borderRadius=a.style.borderRadius),addEventListener("message",function e(t){t.source===o.contentWindow&&t.origin===h&&t.data?.type==="livecodes-init"&&(removeEventListener("message",e),d=Number(t.data.payload.appVersion.replace(/^v/,"")))}),(!d||d<46)&&addEventListener("message",function e(t){t.source===o.contentWindow&&t.origin===h&&t.data?.type==="livecodes-get-config"&&(removeEventListener("message",e),o.contentWindow?.postMessage({type:"livecodes-config",payload:n},h))}),o.onload=()=>{e(o)},o.src=c.href,i||a.appendChild(o)}),v=new Promise(e=>{addEventListener("message",function t(n){n.source===m.contentWindow&&n.origin===h&&n.data?.type==="livecodes-ready"&&(removeEventListener("message",t),e(),v.settled=!0)})}),f=()=>p?Promise.reject(g):new Promise(async e=>{v.settled&&e(),m.contentWindow?.postMessage({type:"livecodes-load"},h),await v,e()}),x=(e,t)=>new Promise(async(n,s)=>{if(p)return s(g);await f();let r=C();addEventListener("message",function t(i){if(i.source===m.contentWindow&&i.origin===h&&i.data?.type==="livecodes-api-response"&&i.data?.id===r&&i.data.method===e){removeEventListener("message",t);let e=i.data.payload;e?.error?s(e.error):n(e)}}),m.contentWindow?.postMessage({method:e,id:r,args:t},h)}),j={},y=["load","ready","code","console","tests","destroy"],w=(e,t)=>{if(p)throw Error(g);return y.includes(e)?(x("watch",[e]),j[e]||(j[e]=[]),j[e]?.push(t),{remove:()=>{j[e]=j[e]?.filter(e=>e!==t),j[e]?.length===0&&x("watch",[e,"unsubscribe"])}}):{remove:()=>void 0}},b=e=>({"livecodes-app-loaded":"load","livecodes-ready":"ready","livecodes-change":"code","livecodes-console":"console","livecodes-test-results":"tests","livecodes-destroy":"destroy"})[e];addEventListener("message",async e=>{let t=b(e.data?.type??"");if(e.source!==m.contentWindow||e.origin!==h||!t||!j[t])return;let n=e.data?.payload;j[t]?.forEach(e=>{e(n)})});let S=()=>{Object.values(j).forEach(e=>{e.length=0}),m?.remove?.(),p=!0};function R(e){e.style.position="absolute",e.style.top="0",e.style.visibility="hidden",e.style.opacity="0"}"lazy"===r&&"IntersectionObserver"in window&&new IntersectionObserver((e,t)=>{e.forEach(async e=>{e.isIntersecting&&(await f(),t.unobserve(a))})},{rootMargin:"150px"}).observe(a);let C=()=>(String(Math.random())+Date.now().toFixed()).replace("0.","");return{load:()=>f(),run:()=>x("run"),format:e=>x("format",[e]),getShareUrl:e=>x("getShareUrl",[e]),getConfig:e=>x("getConfig",[e]),setConfig:e=>x("setConfig",[e]),getCode:()=>x("getCode"),show:(e,t)=>x("show",[e,t]),runTests:()=>x("runTests"),onChange:e=>w("code",e),watch:w,exec:function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return x("exec",[e,...n])},destroy:()=>v.settled?x("destroy").then(S):p?Promise.reject(g):(S(),Promise.resolve())}}function i(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{appUrl:n="https://livecodes.io",params:r={},config:i={},headless:o,import:l,lite:a,view:d,...c}=t;try{e=new URL(n)}catch{throw Error(`${n} is not a valid URL.`)}let h=new URLSearchParams;Object.entries(c).forEach(t=>{let[n,s]=t;void 0!==s&&e.searchParams.set(n,String(s))});let u="headless"===t.view||o;if(a&&(console.warn('Deprecation notice: "lite" option is deprecated. Use "config: { mode: \'lite\' }" instead.'),"object"==typeof i&&null==i.mode?i.mode="lite":e.searchParams.set("lite","true")),d&&(console.warn('Deprecation notice: The "view" option has been moved to "config.view". For headless mode use "headless: true".'),"object"==typeof i&&null==i.view&&"headless"!==d?i.view=d:e.searchParams.set("view",d)),"string"==typeof i)try{new URL(i),e.searchParams.set("config",encodeURIComponent(i))}catch{throw Error('"config" is not a valid URL or configuration object.')}else i&&"object"==typeof i&&Object.keys(i).length>0&&(i.title&&"Untitled Project"!==i.title&&e.searchParams.set("title",i.title),i.description&&i.description.length>0&&e.searchParams.set("description",i.description),h.set("config","code/"+(0,s.compressToEncodedURIComponent)(JSON.stringify(i))));if(r&&"object"==typeof r&&Object.keys(r).length>0)try{h.set("params",(0,s.compressToEncodedURIComponent)(JSON.stringify(r)))}catch{Object.keys(r).forEach(t=>{e.searchParams.set(t,encodeURIComponent(String(r[t])))})}return l&&e.searchParams.set("x",encodeURIComponent(l)),u&&e.searchParams.set("headless","true"),e.hash=h.toString(),e.href}},65:function(e,t,n){n.d(t,{Z:function(){return l},a:function(){return o}});var s=n(7294);let r={},i=s.createContext(r);function o(e){let t=s.useContext(i);return s.useMemo(function(){return"function"==typeof e?e(t):{...t,...e}},[t,e])}function l(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(r):e.components||r:o(e.components),s.createElement(i.Provider,{value:t},e.children)}}}]);