livecode-static/docs/assets/js/3021cf83.46361c6a.js
2025-06-12 09:37:26 +08:00

62 lines
19 KiB
JavaScript

"use strict";(self.webpackChunkdocs=self.webpackChunkdocs||[]).push([["804"],{4791:function(e,t,n){n.r(t),n.d(t,{config:()=>f,UMDCode:()=>g,default:()=>b,frontMatter:()=>h,metadata:()=>s,assets:()=>u,ESMCode:()=>m,toc:()=>v,contentTitle:()=>p});var s=JSON.parse('{"id":"getting-started","title":"Getting Started","description":"There are multiple options:","source":"@site/docs/getting-started.mdx","sourceDirName":".","slug":"/getting-started","permalink":"/docs/getting-started","draft":false,"unlisted":false,"editUrl":"https://github.com/live-codes/livecodes/tree/develop/docs/docs/getting-started.mdx","tags":[],"version":"current","frontMatter":{},"sidebar":"docsSidebar","previous":{"title":"Why Another Playground?","permalink":"/docs/why"},"next":{"title":"Features","permalink":"/docs/features/"}}'),o=n("5893"),r=n("65"),i=n("8168"),a=n("7645"),l=n("3365"),d=n("7262"),c=n("1705");let h={},p="Getting Started",u={},m=()=>{let{siteConfig:e}=(0,d.Z)();return(0,o.jsx)(c.Z,{title:"index.html",language:"html",children:`<div id="container"></div>
<script type="module">
import { createPlayground } from 'https://cdn.jsdelivr.net/npm/livecodes@${e.customFields.sdkVersion}';
createPlayground('#container', {
template: 'react',
// other embed options
});
</script>`})},g=()=>{let{siteConfig:e}=(0,d.Z)();return(0,o.jsx)(c.Z,{title:"index.html",language:"html",children:`<div id="container"></div>
<script src="https://cdn.jsdelivr.net/npm/livecodes@${e.customFields.sdkVersion}/livecodes.umd.js"></script>
<script>
// the UMD version provides the global object \`livecodes\`
livecodes.createPlayground('#container', {
${" ".repeat(4)}template: 'react',
// other embed options
});
</script>
`})},f={markup:{language:"markdown",content:"# Hello LiveCodes!"},style:{language:"css",content:"body { color: blue; }"},script:{language:"javascript",content:'console.log("hello from JavaScript!");'},activeEditor:"script"},v=[{value:"Standalone App",id:"standalone-app",level:2},{value:"Embedded Playgrounds",id:"embedded-playgrounds",level:2},{value:"App Embed Screen",id:"app-embed-screen",level:3},{value:"SDK",id:"sdk",level:3},{value:"Option 1: Using a bundler",id:"option-1-using-a-bundler",level:4},{value:"Option 2: Load from CDN",id:"option-2-load-from-cdn",level:4},{value:"Add your own content",id:"add-your-own-content",level:4},{value:"Self-Hosting",id:"self-hosting",level:2}];function y(e){let t={a:"a",code:"code",h1:"h1",h2:"h2",h3:"h3",h4:"h4",header:"header",p:"p",pre:"pre",...(0,r.a)(),...e.components};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(t.header,{children:(0,o.jsx)(t.h1,{id:"getting-started",children:"Getting Started"})}),"\n","\n",(0,o.jsx)(t.p,{children:"There are multiple options:"}),"\n",(0,o.jsx)(t.h2,{id:"standalone-app",children:"Standalone App"}),"\n",(0,o.jsxs)(t.p,{children:["The easiest way to get started with LiveCodes is to just use the app (",(0,o.jsx)(t.a,{href:"https://livecodes.io",children:"https://livecodes.io"}),")."]}),"\n",(0,o.jsxs)(t.p,{children:["It is packed with ",(0,o.jsx)(t.a,{href:"/docs/features/",children:"features"})," and offers various ways to ",(0,o.jsx)(t.a,{href:"/docs/features/import",children:"import code"}),"."]}),"\n",(0,o.jsx)(t.h2,{id:"embedded-playgrounds",children:"Embedded Playgrounds"}),"\n",(0,o.jsxs)(t.p,{children:["LiveCodes playgrounds can be easily ",(0,o.jsx)(t.a,{href:"/docs/features/embeds",children:"embedded"})," into any web page. This can be achieved using:"]}),"\n",(0,o.jsx)(t.h3,{id:"app-embed-screen",children:"App Embed Screen"}),"\n",(0,o.jsxs)(t.p,{children:["The ",(0,o.jsx)(t.a,{href:"#standalone-app",children:"standalone app"})," allows you to embed any project from the ",(0,o.jsx)(t.a,{href:"/docs/features/embeds",children:"embed screen"}),". The UI allows setting embed options and shows a preview of the embedded playground.\nCopy the generated code snippet (at the bottom of the screen) and add it to the web page that you want to embed the playground in."]}),"\n",(0,o.jsx)(t.h3,{id:"sdk",children:"SDK"}),"\n",(0,o.jsxs)(t.p,{children:["LiveCodes ",(0,o.jsx)(t.a,{href:"/docs/sdk/",children:(0,o.jsx)("abbr",{title:"Software Development Kit",children:"SDK"})})," is available as ",(0,o.jsx)(t.a,{href:"https://www.npmjs.com/package/livecodes",children:"npm package"})," to allow easy embedding and communication with playgrounds."]}),"\n",(0,o.jsx)(t.h4,{id:"option-1-using-a-bundler",children:"Option 1: Using a bundler"}),"\n",(0,o.jsx)(t.p,{children:"Install from npm."}),"\n",(0,o.jsxs)(i.Z,{groupId:"npm2yarn",children:[(0,o.jsx)(a.Z,{value:"npm",children:(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-bash",children:"npm install livecodes\n"})})}),(0,o.jsx)(a.Z,{value:"yarn",label:"Yarn",children:(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-bash",children:"yarn add livecodes\n"})})}),(0,o.jsx)(a.Z,{value:"pnpm",label:"pnpm",children:(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-bash",children:"pnpm add livecodes\n"})})}),(0,o.jsx)(a.Z,{value:"bun",label:"Bun",children:(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-bash",children:"bun add livecodes\n"})})})]}),"\n",(0,o.jsx)(t.p,{children:"then you can use it like that:"}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-js",metastring:'title="index.js"',children:"import { createPlayground } from 'livecodes';\n\ncreatePlayground('#container', {\n template: 'react',\n // other embed options\n});\n"})}),"\n",(0,o.jsx)(t.h4,{id:"option-2-load-from-cdn",children:"Option 2: Load from CDN"}),"\n",(0,o.jsx)(t.p,{children:"ESM:"}),"\n","\n","\n",(0,o.jsx)(m,{}),"\n",(0,o.jsx)(t.p,{children:"UMD:"}),"\n","\n",(0,o.jsx)(g,{}),"\n",(0,o.jsx)(t.h4,{id:"add-your-own-content",children:"Add your own content"}),"\n",(0,o.jsxs)(t.p,{children:["You may use any of the methods to ",(0,o.jsx)(t.a,{href:"/docs/features/code-prefill",children:"prefill the playground"})," with your own code."]}),"\n",(0,o.jsx)(t.p,{children:"Example:"}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-js",metastring:'title="index.js"',children:"import { createPlayground } from 'livecodes';\n\nconst config = {\n markup: {\n language: 'markdown',\n content: '# Hello LiveCodes!',\n },\n style: {\n language: 'css',\n content: 'body { color: blue; }',\n },\n script: {\n language: 'javascript',\n content: 'console.log(\"hello from JavaScript!\");',\n },\n activeEditor: 'script',\n};\n\ncreatePlayground('#container', { config, params: { console: 'open' } });\n"})}),"\n","\n",(0,o.jsx)(t.p,{children:"Live demo:\n(this is an interactive playground - try editing the code!)"}),"\n",(0,o.jsx)(l.Z,{config:f,params:{console:"open"}}),"\n",(0,o.jsxs)(t.p,{children:["Please refer to the section on ",(0,o.jsx)(t.a,{href:"/docs/features/embeds",children:"Embedded Playgrounds"})," for more details."]}),"\n",(0,o.jsx)(t.h2,{id:"self-hosting",children:"Self-Hosting"}),"\n",(0,o.jsx)(t.p,{children:"LiveCodes can be hosted on any static file server or CDN."}),"\n",(0,o.jsxs)(t.p,{children:["The easiest way is to download the app from ",(0,o.jsx)(t.a,{href:"https://github.com/live-codes/livecodes/releases",children:"releases"}),", extract the folder and add it to your website."]}),"\n",(0,o.jsxs)(t.p,{children:["Please check the section on ",(0,o.jsx)(t.a,{href:"/docs/features/self-hosting",children:"self-hosting"})," for other methods of self-hosting, including the built-in setup to deploy to GitHub pages and how to use the SDK with the self-hosted app."]})]})}function b(e={}){let{wrapper:t}={...(0,r.a)(),...e.components};return t?(0,o.jsx)(t,{...e,children:(0,o.jsx)(y,{...e})}):y(e)}},3365:function(e,t,n){n.d(t,{Z:()=>f});var s=n("5893"),o=n("4200"),r=n("7294"),i=n("8294");function a(e){let t=(0,r.useRef)(null),[n,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:n,style:s,height:r,sdkReady:a,config:d,...v}=e;if(o(n||""),l(s||{}),c(r),h&&g===JSON.stringify(v)){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(v)),h?.destroy(),(0,i.T)(t.current,{config:d,...v}).then(e=>{p(e),"function"==typeof a&&a(e)})},[e]),(0,r.useEffect)(()=>()=>{h?.destroy()},[]),(0,s.jsx)("div",{ref:t,className:n,style:a,"data-height":d})}var l=n("1858"),d=n("3262"),c=n("1705"),h=n("7645"),p=n("8168"),u=n("8228"),m=n("5050");function g(e){let[t,n]=(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),[v,y]=(0,r.useState)(e.svelte),b="3.7rem",[j,x]=(0,r.useState)(!0),[w,S]=(0,r.useState)(b),C=(0,r.useRef)(null),P=()=>{setTimeout(()=>{S(`calc(${C.current.offsetHeight}px + ${b})`)},5),setTimeout(()=>{S(`calc(${C.current.offsetHeight}px + ${b})`)},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}};n(e(t,"js")),i(e(o,"ts")),l(e(a,"jsx")),f(e(g,"html")),y(e(v,"html"))}},[]),(0,s.jsxs)("details",{className:`alert alert--info ${m.Z.details} ${u.Z.details}`,"data-collapsed":j,style:{height:j?b:w,overflow:"hidden",willChange:"height",transition:`height ${j?"250ms":"265ms"} ease-in-out 0s`,margin:"1em 0"},children:[(0,s.jsx)("summary",{onClick:()=>{x(!j),P()},children:"show code"}),(0,s.jsx)("div",{ref:C,style:{display:"block",overflow:"hidden"},children:(0,s.jsx)("div",{className:m.Z.collapsibleContent,children:(0,s.jsxs)(p.Z,{groupId:"sdk-code",children:[(0,s.jsx)(h.Z,{value:"js",label:"JS",attributes:{onMouseDown:P},children:(0,s.jsx)(c.Z,{language:"js",children:t})}),(0,s.jsx)(h.Z,{value:"ts",label:"TS",attributes:{onMouseDown:P},children:(0,s.jsx)(c.Z,{language:"ts",children:o})}),(0,s.jsx)(h.Z,{value:"react",label:"React",attributes:{onMouseDown:P},children:(0,s.jsx)(c.Z,{language:"jsx",children:a})}),(0,s.jsx)(h.Z,{value:"vue",label:"Vue",attributes:{onMouseDown:P},children:(0,s.jsx)(c.Z,{language:"html",children:g})}),(0,s.jsx)(h.Z,{value:"svelte",label:"Svelte",attributes:{onMouseDown:P},children:(0,s.jsx)(c.Z,{language:"html",children:v})})]})})})]})}function f(e){let{className:t,style:n,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>
`,v=`
<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)(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,s.jsx)(g,{js:p,ts:u,react:m,vue:f,svelte:v})]})}},8294:function(e,t,n){n.d(t,{T:function(){return o},r:function(){return r}});var s=n(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:n={},headless:s,loading:o="lazy",view:i}=t,a=s||"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),c.searchParams.set("sdkVersion",process.env.SDK_VERSION||"latest"),"object"==typeof n&&Object.keys(n).length>0&&c.searchParams.set("config","sdk");let p=t.params;"object"==typeof p&&Object.keys(p).length>0&&JSON.stringify(p).length<1800&&Object.keys(p).forEach(e=>{c.searchParams.set(e,encodeURIComponent(String(p[e])))});let u=!1,m="Cannot call API methods after calling `destroy()`.",g=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 s="livecodes",r=l.querySelector(`iframe.${s}`),i=r||document.createElement("iframe");i.classList.add(s),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:n},h))}),i.onload=()=>{e(i)},i.src=c.href,r||l.appendChild(i)}),f=new Promise(e=>{addEventListener("message",function t(n){n.source===g.contentWindow&&n.origin===h&&n.data?.type==="livecodes-ready"&&(removeEventListener("message",t),e(),f.settled=!0)})}),v=()=>u?Promise.reject(m):new Promise(async e=>{f.settled&&e(),g.contentWindow?.postMessage({type:"livecodes-load"},h),await f,e()}),y=(e,t)=>new Promise(async(n,s)=>{if(u)return s(m);await v();let o=P();addEventListener("message",function t(r){if(r.source===g.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?s(e.error):n(e)}}),g.contentWindow?.postMessage({method:e,id:o,args:t},h)}),b={},j=["load","ready","code","console","tests","destroy"],x=(e,t)=>{if(u)throw Error(m);return j.includes(e)?(y("watch",[e]),b[e]||(b[e]=[]),b[e]?.push(t),{remove:()=>{b[e]=b[e]?.filter(e=>e!==t),b[e]?.length===0&&y("watch",[e,"unsubscribe"])}}):{remove:()=>void 0}},w=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=w(e.data?.type??"");if(e.source!==g.contentWindow||e.origin!==h||!t||!b[t])return;let n=e.data?.payload;b[t]?.forEach(e=>{e(n)})});let S=()=>{Object.values(b).forEach(e=>{e.length=0}),g?.remove?.(),u=!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:()=>y("run"),format:e=>y("format",[e]),getShareUrl:e=>y("getShareUrl",[e]),getConfig:e=>y("getConfig",[e]),setConfig:e=>y("setConfig",[e]),getCode:()=>y("getCode"),show:(e,t)=>y("show",[e,t]),runTests:()=>y("runTests"),onChange:e=>x("code",e),watch:x,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 y("exec",[e,...n])},destroy:()=>f.settled?y("destroy").then(S):u?Promise.reject(m):(S(),Promise.resolve())}}function r(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{appUrl:n="https://livecodes.io",params:o={},config:r={},headless:i,import:a,lite:l,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 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,s.compressToEncodedURIComponent)(JSON.stringify(r))));if(o&&"object"==typeof o&&Object.keys(o).length>0)try{h.set("params",(0,s.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,n){n.d(t,{Z:function(){return a},a:function(){return i}});var s=n(7294);let o={},r=s.createContext(o);function i(e){let t=s.useContext(r);return s.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),s.createElement(r.Provider,{value:t},e.children)}}}]);