livecode-static/docs/assets/js/aa19e785.ae8914c1.js
2025-06-11 22:23:49 +08:00

59 lines
19 KiB
JavaScript

"use strict";(self.webpackChunkdocs=self.webpackChunkdocs||[]).push([["6465"],{1795:function(e,t,s){s.r(t),s.d(t,{default:()=>u,frontMatter:()=>a,metadata:()=>n,assets:()=>d,reactSDKDemo:()=>c,toc:()=>h,contentTitle:()=>l});var n=JSON.parse('{"id":"sdk/react","title":"React SDK","description":"The react SDK is a thin wrapper around the JavaScript SDK to provide an easy to use react component, yet retaining the full power, by having access to the SDK methods.","source":"@site/docs/sdk/react.mdx","sourceDirName":"sdk","slug":"/sdk/react","permalink":"/docs/sdk/react","draft":false,"unlisted":false,"editUrl":"https://github.com/live-codes/livecodes/tree/develop/docs/docs/sdk/react.mdx","tags":[],"version":"current","frontMatter":{},"sidebar":"docsSidebar","previous":{"title":"JS/TS SDK","permalink":"/docs/sdk/js-ts"},"next":{"title":"Vue SDK","permalink":"/docs/sdk/vue"}}'),o=s("5893"),r=s("65"),i=s("3365");let a={},l="React SDK",d={},c={jsx:`import LiveCodes from "livecodes/react";
const App = () => {
const params = {
html: "<h1>Hello World!</h1>",
css: "h1 {color: blue;}",
js: 'console.log("Hello, World!")',
console: "open",
};
return <LiveCodes params={params} />;
};
export default App;
`},h=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2},{value:"TypeScript Support",id:"typescript-support",level:3},{value:"Props",id:"props",level:3},{value:"Demo",id:"demo",level:2},{value:"Related",id:"related",level:2}];function p(e){let t={a:"a",code:"code",h1:"h1",h2:"h2",h3:"h3",header:"header",li:"li",p:"p",pre:"pre",ul:"ul",...(0,r.a)(),...e.components};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(t.header,{children:(0,o.jsx)(t.h1,{id:"react-sdk",children:"React SDK"})}),"\n","\n",(0,o.jsxs)(t.p,{children:["The react SDK is a thin wrapper around the ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts",children:"JavaScript SDK"})," to provide an easy to use react component, yet retaining the full power, by having access to the ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#sdk-methods",children:"SDK methods"}),"."]}),"\n",(0,o.jsxs)(t.p,{children:["It has a very simple ",(0,o.jsx)(t.a,{href:"https://github.com/live-codes/livecodes/blob/develop/src/sdk/react.tsx",children:"implementation"})," which you can easily modify in case you need."]}),"\n",(0,o.jsx)(t.h2,{id:"installation",children:"Installation"}),"\n",(0,o.jsxs)(t.p,{children:["Please refer to the ",(0,o.jsx)(t.a,{href:"/docs/sdk/#installation",children:"SDK installation"})," section."]}),"\n",(0,o.jsx)(t.h2,{id:"usage",children:"Usage"}),"\n",(0,o.jsxs)(t.p,{children:["The react component is provided as the default export from ",(0,o.jsx)(t.code,{children:"livecodes/react"}),"."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-jsx",metastring:'title="JSX"',children:"import LiveCodes from 'livecodes/react';\n\nexport const Playground = () => <LiveCodes />;\n"})}),"\n",(0,o.jsx)(t.h3,{id:"typescript-support",children:"TypeScript Support"}),"\n",(0,o.jsxs)(t.p,{children:["Prop types are exported as ",(0,o.jsx)(t.code,{children:"Props"})," from ",(0,o.jsx)(t.code,{children:"livecodes/react"}),"."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-tsx",metastring:'title="TSX"',children:"import LiveCodes, { type Props } from 'livecodes/react';\n\nconst options: Props = {\n // embed options\n};\nexport const Playground = () => <LiveCodes {...options} />;\n"})}),"\n",(0,o.jsxs)(t.p,{children:["TypeScript types are ",(0,o.jsx)(t.a,{href:"/docs/api/globals",children:"documented here"}),"."]}),"\n",(0,o.jsx)(t.h3,{id:"props",children:"Props"}),"\n",(0,o.jsxs)(t.p,{children:["All ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#embed-options",children:"embed options"})," are available as props with the corresponding types."]}),"\n",(0,o.jsx)(t.p,{children:"Example:"}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-jsx",metastring:'title="JSX"',children:"import LiveCodes from 'livecodes/react';\n\nconst config = {\n markup: {\n language: 'markdown',\n content: '# Hello World!',\n },\n};\nexport const Playground = () => <LiveCodes config={config} view=\"result\" />;\n"})}),"\n",(0,o.jsx)(t.p,{children:"In addition, the following props are also available:"}),"\n",(0,o.jsxs)(t.ul,{children:["\n",(0,o.jsxs)(t.li,{children:["\n",(0,o.jsx)(t.p,{children:(0,o.jsx)(t.code,{children:"className"})}),"\n",(0,o.jsxs)(t.p,{children:["Type: ",(0,o.jsx)(t.code,{children:"string"}),"."]}),"\n",(0,o.jsx)(t.p,{children:"Class name(s) to add to playground container element."}),"\n",(0,o.jsx)(t.p,{children:"Example:"}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-jsx",metastring:'title="JSX"',children:"import LiveCodes from 'livecodes/react';\n\nexport const Playground = () => <LiveCodes className=\"centered\" />;\n"})}),"\n"]}),"\n",(0,o.jsxs)(t.li,{children:["\n",(0,o.jsx)(t.p,{children:(0,o.jsx)(t.code,{children:"height"})}),"\n",(0,o.jsxs)(t.p,{children:["Type: ",(0,o.jsx)(t.code,{children:"string"}),"."]}),"\n",(0,o.jsx)(t.p,{children:"Sets the height of playground container element."}),"\n",(0,o.jsx)(t.p,{children:"Example:"}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-jsx",metastring:'title="JSX"',children:"import LiveCodes from 'livecodes/react';\n\nexport const Playground = () => <LiveCodes height=\"500px\" />;\n"})}),"\n"]}),"\n",(0,o.jsxs)(t.li,{children:["\n",(0,o.jsx)(t.p,{children:(0,o.jsx)(t.code,{children:"style"})}),"\n",(0,o.jsxs)(t.p,{children:["Type: ",(0,o.jsx)(t.code,{children:"Record<string, string>"}),"."]}),"\n",(0,o.jsxs)(t.p,{children:["Defines styles to add to playground container element. Styles set here override the ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#default-styles",children:"default styles"}),"."]}),"\n",(0,o.jsx)(t.p,{children:"Example:"}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-tsx",metastring:'title="JSX"',children:"import LiveCodes from 'livecodes/react';\n\nconst style = {\n margin: 'auto',\n width: '80%',\n};\nexport const Playground = () => <LiveCodes style={style} />;\n"})}),"\n"]}),"\n",(0,o.jsxs)(t.li,{children:["\n",(0,o.jsx)(t.p,{children:(0,o.jsx)(t.code,{children:"sdkReady"})}),"\n",(0,o.jsxs)(t.p,{children:["Type: ",(0,o.jsx)(t.code,{children:"(sdk: Playground) => void"}),"."]}),"\n",(0,o.jsxs)(t.p,{children:["A callback function, that is provided with an instance of the ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts",children:"JavaScript SDK"})," representing the current playground. This allows making use of full capability of the SDK by calling ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#sdk-methods",children:"SDK methods"}),"."]}),"\n",(0,o.jsx)(t.p,{children:"Example:"}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-tsx",metastring:'title="TSX"',children:"import { useState } from 'react';\nimport LiveCodes from 'livecodes/react';\nimport type { Playground } from 'livecodes';\n\nexport const App = () => {\n const [playground, setPlayground] = useState<Playground>();\n\n const onReady = (sdk: Playground) => {\n setPlayground(sdk);\n };\n\n const run = async () => {\n await playground?.run();\n };\n\n return (\n <>\n <LiveCodes sdkReady={onReady} />\n <button onClick={run}>Run</button>\n </>\n );\n};\n"})}),"\n"]}),"\n"]}),"\n",(0,o.jsx)(t.h2,{id:"demo",children:"Demo"}),"\n","\n",(0,o.jsx)(i.Z,{params:c,height:"80vh"}),"\n",(0,o.jsx)(t.h2,{id:"related",children:"Related"}),"\n",(0,o.jsxs)(t.ul,{children:["\n",(0,o.jsx)(t.li,{children:(0,o.jsx)(t.a,{href:"/docs/sdk/#installation",children:"SDK Installation"})}),"\n",(0,o.jsx)(t.li,{children:(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts",children:"JS/TS SDK"})}),"\n",(0,o.jsx)(t.li,{children:(0,o.jsx)(t.a,{href:"/docs/sdk/vue",children:"Vue SDK"})}),"\n",(0,o.jsx)(t.li,{children:(0,o.jsx)(t.a,{href:"/docs/sdk/svelte",children:"Using SDK in Svelte"})}),"\n",(0,o.jsx)(t.li,{children:(0,o.jsx)(t.a,{href:"/docs/features/embeds",children:"Embedded Playgrounds"})}),"\n"]})]})}function u(e={}){let{wrapper:t}={...(0,r.a)(),...e.components};return t?(0,o.jsx)(t,{...e,children:(0,o.jsx)(p,{...e})}):p(e)}},3365:function(e,t,s){s.d(t,{Z:()=>f});var n=s("5893"),o=s("4200"),r=s("7294"),i=s("8294");function a(e){let t=(0,r.useRef)(null),[s,o]=(0,r.useState)(e.className||""),[a,l]=(0,r.useState)(e.style||{}),[d,c]=(0,r.useState)(e.height),[h,p]=(0,r.useState)(),[u,m]=(0,r.useState)(JSON.stringify(e.config||"")),[g,f]=(0,r.useState)("");return(0,r.useEffect)(()=>{if(!t.current)return;let{className:s,style:n,height:r,sdkReady:a,config:d,...y}=e;if(o(s||""),l(n||{}),c(r),h&&g===JSON.stringify(y)){if(u===JSON.stringify(d))return;m(JSON.stringify(d)),"string"==typeof d?fetch(d).then(e=>e.json()).then(e=>{h?.setConfig(e)}):d&&h.setConfig(d)}else f(JSON.stringify(y)),h?.destroy(),(0,i.T)(t.current,{config:d,...y}).then(e=>{p(e),"function"==typeof a&&a(e)})},[e]),(0,r.useEffect)(()=>()=>{h?.destroy()},[]),(0,n.jsx)("div",{ref:t,className:s,style:a,"data-height":d})}var l=s("1858"),d=s("3262"),c=s("1705"),h=s("7645"),p=s("8168"),u=s("8228"),m=s("5050");function g(e){let[t,s]=(0,r.useState)(e.js),[o,i]=(0,r.useState)(e.ts),[a,l]=(0,r.useState)(e.react),[g,f]=(0,r.useState)(e.vue),[y,v]=(0,r.useState)(e.svelte),x="3.7rem",[j,b]=(0,r.useState)(!0),[w,S]=(0,r.useState)(x),k=(0,r.useRef)(null),C=()=>{setTimeout(()=>{S(`calc(${k.current.offsetHeight}px + ${x})`)},5),setTimeout(()=>{S(`calc(${k.current.offsetHeight}px + ${x})`)},255)};return(0,r.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}};s(e(t,"js")),i(e(o,"ts")),l(e(a,"jsx")),f(e(g,"html")),v(e(y,"html"))}},[]),(0,n.jsxs)("details",{className:`alert alert--info ${m.Z.details} ${u.Z.details}`,"data-collapsed":j,style:{height:j?x:w,overflow:"hidden",willChange:"height",transition:`height ${j?"250ms":"265ms"} ease-in-out 0s`,margin:"1em 0"},children:[(0,n.jsx)("summary",{onClick:()=>{b(!j),C()},children:"show code"}),(0,n.jsx)("div",{ref:k,style:{display:"block",overflow:"hidden"},children:(0,n.jsx)("div",{className:m.Z.collapsibleContent,children:(0,n.jsxs)(p.Z,{groupId:"sdk-code",children:[(0,n.jsx)(h.Z,{value:"js",label:"JS",attributes:{onMouseDown:C},children:(0,n.jsx)(c.Z,{language:"js",children:t})}),(0,n.jsx)(h.Z,{value:"ts",label:"TS",attributes:{onMouseDown:C},children:(0,n.jsx)(c.Z,{language:"ts",children:o})}),(0,n.jsx)(h.Z,{value:"react",label:"React",attributes:{onMouseDown:C},children:(0,n.jsx)(c.Z,{language:"jsx",children:a})}),(0,n.jsx)(h.Z,{value:"vue",label:"Vue",attributes:{onMouseDown:C},children:(0,n.jsx)(c.Z,{language:"html",children:g})}),(0,n.jsx)(h.Z,{value:"svelte",label:"Svelte",attributes:{onMouseDown:C},children:(0,n.jsx)(c.Z,{language:"html",children:y})})]})})})]})}function f(e){let{className:t,style:s,showCode:r,height:i,...d}=e,{colorMode:c}=(0,o.I)(),h=e=>JSON.stringify(e,null,2),p=`
import { createPlayground } from 'livecodes';
const options = ${h(d)};
createPlayground('#container', options);
`.trimStart(),u=`
import { createPlayground, type EmbedOptions } from 'livecodes';
const options: EmbedOptions = ${h(d)};
createPlayground('#container', options);
`.trimStart(),m=`
import LiveCodes from 'livecodes/react';
export default function App() {
const options = ${h(d)};
return (<LiveCodes {...options}></LiveCodes>);
}
`.trimStart(),f=`
<script setup>
import LiveCodes from "livecodes/vue";
const options = ${h(d)};
</script>
<template>
<LiveCodes v-bind="options" />
</template>
`,y=`
<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,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(a,{className:`container_Egsj ${e.className}`,style:{height:i||"50vh",...e.style},appUrl:l.G,...e,config:{theme:c,themeColor:"hsl(215, 8%, 60%)",..."object"==typeof e.config?e.config:{}}}),!1!==e.showCode&&(0,n.jsx)(g,{js:p,ts:u,react:m,vue:f,svelte:y})]})}},8294:function(e,t,s){s.d(t,{T:function(){return o},r:function(){return r}});var n=s(7728);async function o(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:s={},headless:n,loading:o="lazy",view:i}=t,a=n||"headless"===i,l=null,d=null;if("string"==typeof e)l=document.querySelector(e);else if(e instanceof HTMLElement)l=e;else if(!(a&&"object"==typeof e))throw Error("A valid container element is required.");if(!l){if(a)C(l=document.createElement("div")),document.body.appendChild(l);else throw Error(`Cannot find element: "${e}"`)}let c=new URL(r(t)),h=c.origin;c.searchParams.set("embed","true"),c.searchParams.set("loading",a?"eager":o);let p=globalThis.process;c.searchParams.set("sdkVersion",p?.env?.SDK_VERSION||"latest"),"object"==typeof s&&Object.keys(s).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 m=!1,g="Cannot call API methods after calling `destroy()`.",f=await new Promise(e=>{if(!l)return;let t=l.dataset.height||l.style.height;if(t&&!a){let e=isNaN(Number(t))?t:t+"px";l.style.height=e}"false"===l.dataset.defaultStyles||a||(l.style.backgroundColor||="#fff",l.style.border||="1px solid black",l.style.borderRadius||="8px",l.style.boxSizing||="border-box",l.style.padding||="0",l.style.width||="100%",l.style.height||=l.style.height||"300px",l.style.minHeight="200px",l.style.flexGrow="1",l.style.overflow||="hidden",l.style.resize||="vertical");let n="livecodes",r=l.querySelector(`iframe.${n}`),i=r||document.createElement("iframe");i.classList.add(n),i.setAttribute("allow","accelerometer; camera; encrypted-media; display-capture; geolocation; gyroscope; microphone; midi; clipboard-read; clipboard-write; web-share"),i.setAttribute("allowtransparency","true"),i.setAttribute("allowpaymentrequest","true"),i.setAttribute("allowfullscreen","true"),i.setAttribute("sandbox","allow-same-origin allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-presentation allow-scripts"),i.setAttribute("loading","eager"===o?"eager":"lazy"),a?C(i):(i.style.height="100%",i.style.minHeight="200px",i.style.width="100%",i.style.margin="0",i.style.border="0",i.style.borderRadius=l.style.borderRadius),addEventListener("message",function e(t){t.source===i.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===i.contentWindow&&t.origin===h&&t.data?.type==="livecodes-get-config"&&(removeEventListener("message",e),i.contentWindow?.postMessage({type:"livecodes-config",payload:s},h))}),i.onload=()=>{e(i)},i.src=c.href,r||l.appendChild(i)}),y=new Promise(e=>{addEventListener("message",function t(s){s.source===f.contentWindow&&s.origin===h&&s.data?.type==="livecodes-ready"&&(removeEventListener("message",t),e(),y.settled=!0)})}),v=()=>m?Promise.reject(g):new Promise(async e=>{y.settled&&e(),f.contentWindow?.postMessage({type:"livecodes-load"},h),await y,e()}),x=(e,t)=>new Promise(async(s,n)=>{if(m)return n(g);await v();let o=P();addEventListener("message",function t(r){if(r.source===f.contentWindow&&r.origin===h&&r.data?.type==="livecodes-api-response"&&r.data?.id===o&&r.data.method===e){removeEventListener("message",t);let e=r.data.payload;e?.error?n(e.error):s(e)}}),f.contentWindow?.postMessage({method:e,id:o,args:t},h)}),j={},b=["load","ready","code","console","tests","destroy"],w=(e,t)=>{if(m)throw Error(g);return b.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}},S=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=S(e.data?.type??"");if(e.source!==f.contentWindow||e.origin!==h||!t||!j[t])return;let s=e.data?.payload;j[t]?.forEach(e=>{e(s)})});let k=()=>{Object.values(j).forEach(e=>{e.length=0}),f?.remove?.(),m=!0};function C(e){e.style.position="absolute",e.style.top="0",e.style.visibility="hidden",e.style.opacity="0"}"lazy"===o&&"IntersectionObserver"in window&&new IntersectionObserver((e,t)=>{e.forEach(async e=>{e.isIntersecting&&(await v(),t.unobserve(l))})},{rootMargin:"150px"}).observe(l);let P=()=>(String(Math.random())+Date.now().toFixed()).replace("0.","");return{load:()=>v(),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,s=Array(t>1?t-1:0),n=1;n<t;n++)s[n-1]=arguments[n];return x("exec",[e,...s])},destroy:()=>y.settled?x("destroy").then(k):m?Promise.reject(g):(k(),Promise.resolve())}}function r(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{appUrl:s="https://livecodes.io",params:o={},config:r={},headless:i,import:a,lite:l,view:d,...c}=t;try{e=new URL(s)}catch{throw Error(`${s} is not a valid URL.`)}let h=new URLSearchParams;Object.entries(c).forEach(t=>{let[s,n]=t;void 0!==n&&e.searchParams.set(s,String(n))});let p="headless"===t.view||i;if(l&&(console.warn('Deprecation notice: "lite" option is deprecated. Use "config: { mode: \'lite\' }" instead.'),"object"==typeof r&&null==r.mode?r.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 r&&null==r.view&&"headless"!==d?r.view=d:e.searchParams.set("view",d)),"string"==typeof r)try{new URL(r),e.searchParams.set("config",encodeURIComponent(r))}catch{throw Error('"config" is not a valid URL or configuration object.')}else r&&"object"==typeof r&&Object.keys(r).length>0&&(r.title&&"Untitled Project"!==r.title&&e.searchParams.set("title",r.title),r.description&&r.description.length>0&&e.searchParams.set("description",r.description),h.set("config","code/"+(0,n.compressToEncodedURIComponent)(JSON.stringify(r))));if(o&&"object"==typeof o&&Object.keys(o).length>0)try{h.set("params",(0,n.compressToEncodedURIComponent)(JSON.stringify(o)))}catch{Object.keys(o).forEach(t=>{e.searchParams.set(t,encodeURIComponent(String(o[t])))})}return a&&e.searchParams.set("x",encodeURIComponent(a)),p&&e.searchParams.set("headless","true"),e.hash=h.toString(),e.href}},65:function(e,t,s){s.d(t,{Z:function(){return a},a:function(){return i}});var n=s(7294);let o={},r=n.createContext(o);function i(e){let t=n.useContext(r);return n.useMemo(function(){return"function"==typeof e?e(t):{...t,...e}},[t,e])}function a(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(o):e.components||o:i(e.components),n.createElement(r.Provider,{value:t},e.children)}}}]);