livecode-static/docs/assets/js/403159e4.8887f14b.js
2025-06-11 22:23:49 +08:00

45 lines
16 KiB
JavaScript

"use strict";(self.webpackChunkdocs=self.webpackChunkdocs||[]).push([["1197"],{6807:function(e,t,s){s.r(t),s.d(t,{default:()=>h,frontMatter:()=>l,metadata:()=>r,assets:()=>c,toc:()=>d,contentTitle:()=>a});var r=JSON.parse('{"id":"features/code-prefill","title":"Code Prefill","description":"There are many ways to pre-fill code into playgrounds. This is generally achieved either by the SDK or using query params.","source":"@site/docs/features/code-prefill.mdx","sourceDirName":"features","slug":"/features/code-prefill","permalink":"/docs/features/code-prefill","draft":false,"unlisted":false,"editUrl":"https://github.com/live-codes/livecodes/tree/develop/docs/docs/features/code-prefill.mdx","tags":[],"version":"current","frontMatter":{},"sidebar":"docsSidebar","previous":{"title":"Permanent URL","permalink":"/docs/features/permanent-url"},"next":{"title":"Data URLs","permalink":"/docs/features/data-urls"}}'),o=s("5893"),n=s("65"),i=s("3365");let l={},a="Code Prefill",c={},d=[{value:"Prefill using SDK",id:"prefill-using-sdk",level:2},{value:"config",id:"config",level:3},{value:"import",id:"import",level:3},{value:"template",id:"template",level:3},{value:"Prefill using query params",id:"prefill-using-query-params",level:2},{value:"Auto-Prefill from page DOM",id:"auto-prefill-from-page-dom",level:2},{value:"Related",id:"related",level:2}];function u(e){let t={a:"a",h1:"h1",h2:"h2",h3:"h3",header:"header",li:"li",p:"p",ul:"ul",...(0,n.a)(),...e.components};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(t.header,{children:(0,o.jsx)(t.h1,{id:"code-prefill",children:"Code Prefill"})}),"\n","\n",(0,o.jsxs)(t.p,{children:["There are many ways to pre-fill code into playgrounds. This is generally achieved either by the ",(0,o.jsx)(t.a,{href:"/docs/sdk/",children:"SDK"})," or using ",(0,o.jsx)(t.a,{href:"/docs/configuration/query-params",children:"query params"}),"."]}),"\n",(0,o.jsx)(t.h2,{id:"prefill-using-sdk",children:"Prefill using SDK"}),"\n",(0,o.jsxs)(t.p,{children:["When creating an embedded playground, the following ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#embed-options",children:"embed options"})," allow prefill with code:"]}),"\n",(0,o.jsx)(t.h3,{id:"config",children:"config"}),"\n",(0,o.jsx)(t.p,{children:(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#config",children:"EmbedOptions.config"})}),"\n",(0,o.jsxs)(t.p,{children:["loads a ",(0,o.jsx)(t.a,{href:"/docs/configuration/configuration-object",children:"configuration object"})," (or a URL to JSON file representing the configuration object)"]}),"\n",(0,o.jsx)(i.Z,{config:{markup:{language:"html",content:"<h1>Hello World!</h1>"},style:{language:"css",content:"h1 { color: blue; }"}}}),"\n",(0,o.jsx)(t.h3,{id:"import",children:"import"}),"\n",(0,o.jsx)(t.p,{children:(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#import",children:"EmbedOptions.import"})}),"\n",(0,o.jsxs)(t.p,{children:["allows ",(0,o.jsx)(t.a,{href:"/docs/features/import",children:"importing"})," from many sources."]}),"\n",(0,o.jsx)(t.p,{children:"Examples:"}),"\n",(0,o.jsx)(t.p,{children:"Import GitHub directory:"}),"\n",(0,o.jsx)(i.Z,{import:"https://github.com/bradtraversy/50projects50days/tree/master/progress-steps"}),"\n",(0,o.jsx)(t.p,{children:"Import shared project:"}),"\n",(0,o.jsx)(i.Z,{import:"id/6ys2b8txf33"}),"\n",(0,o.jsx)(t.h3,{id:"template",children:"template"}),"\n",(0,o.jsx)(t.p,{children:(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#template",children:"EmbedOptions.template"})}),"\n",(0,o.jsxs)(t.p,{children:["loads one of the ",(0,o.jsx)(t.a,{href:"/docs/features/templates",children:"starter templates"}),"."]}),"\n",(0,o.jsx)(i.Z,{template:"react"}),"\n",(0,o.jsx)(t.h2,{id:"prefill-using-query-params",children:"Prefill using query params"}),"\n",(0,o.jsxs)(t.p,{children:[(0,o.jsx)(t.a,{href:"/docs/configuration/query-params",children:"Query parameters"})," can provide easy and powerful ways for configuring the playground."]}),"\n",(0,o.jsx)(t.p,{children:"Example:"}),"\n",(0,o.jsx)("a",{href:"https://livecodes.io/?md=**Hello World!**",target:"_blank",children:"https://livecodes.io/?md=**Hello World!**"}),"\n",(0,o.jsx)("br",{}),"\n",(0,o.jsx)("br",{}),"\n",(0,o.jsx)(i.Z,{params:{md:"**Hello World!**"}}),"\n",(0,o.jsx)(t.h2,{id:"auto-prefill-from-page-dom",children:"Auto-Prefill from page DOM"}),"\n",(0,o.jsx)(t.p,{children:"TODO..."}),"\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/features/import",children:"Import"})}),"\n",(0,o.jsx)(t.li,{children:(0,o.jsx)(t.a,{href:"/docs/features/templates",children:"Templates"})}),"\n",(0,o.jsx)(t.li,{children:(0,o.jsx)(t.a,{href:"/docs/configuration/",children:"Configuration"})}),"\n",(0,o.jsx)(t.li,{children:(0,o.jsx)(t.a,{href:"/docs/sdk/",children:"SDK"})}),"\n"]})]})}function h(e={}){let{wrapper:t}={...(0,n.a)(),...e.components};return t?(0,o.jsx)(t,{...e,children:(0,o.jsx)(u,{...e})}):u(e)}},3365:function(e,t,s){s.d(t,{Z:()=>g});var r=s("5893"),o=s("4200"),n=s("7294"),i=s("8294");function l(e){let t=(0,n.useRef)(null),[s,o]=(0,n.useState)(e.className||""),[l,a]=(0,n.useState)(e.style||{}),[c,d]=(0,n.useState)(e.height),[u,h]=(0,n.useState)(),[p,f]=(0,n.useState)(JSON.stringify(e.config||"")),[m,g]=(0,n.useState)("");return(0,n.useEffect)(()=>{if(!t.current)return;let{className:s,style:r,height:n,sdkReady:l,config:c,...y}=e;if(o(s||""),a(r||{}),d(n),u&&m===JSON.stringify(y)){if(p===JSON.stringify(c))return;f(JSON.stringify(c)),"string"==typeof c?fetch(c).then(e=>e.json()).then(e=>{u?.setConfig(e)}):c&&u.setConfig(c)}else g(JSON.stringify(y)),u?.destroy(),(0,i.T)(t.current,{config:c,...y}).then(e=>{h(e),"function"==typeof l&&l(e)})},[e]),(0,n.useEffect)(()=>()=>{u?.destroy()},[]),(0,r.jsx)("div",{ref:t,className:s,style:l,"data-height":c})}var a=s("1858"),c=s("3262"),d=s("1705"),u=s("7645"),h=s("8168"),p=s("8228"),f=s("5050");function m(e){let[t,s]=(0,n.useState)(e.js),[o,i]=(0,n.useState)(e.ts),[l,a]=(0,n.useState)(e.react),[m,g]=(0,n.useState)(e.vue),[y,v]=(0,n.useState)(e.svelte),j="3.7rem",[x,b]=(0,n.useState)(!0),[w,S]=(0,n.useState)(j),P=(0,n.useRef)(null),C=()=>{setTimeout(()=>{S(`calc(${P.current.offsetHeight}px + ${j})`)},5),setTimeout(()=>{S(`calc(${P.current.offsetHeight}px + ${j})`)},255)};return(0,n.useEffect)(()=>{if(c.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")),a(e(l,"jsx")),g(e(m,"html")),v(e(y,"html"))}},[]),(0,r.jsxs)("details",{className:`alert alert--info ${f.Z.details} ${p.Z.details}`,"data-collapsed":x,style:{height:x?j:w,overflow:"hidden",willChange:"height",transition:`height ${x?"250ms":"265ms"} ease-in-out 0s`,margin:"1em 0"},children:[(0,r.jsx)("summary",{onClick:()=>{b(!x),C()},children:"show code"}),(0,r.jsx)("div",{ref:P,style:{display:"block",overflow:"hidden"},children:(0,r.jsx)("div",{className:f.Z.collapsibleContent,children:(0,r.jsxs)(h.Z,{groupId:"sdk-code",children:[(0,r.jsx)(u.Z,{value:"js",label:"JS",attributes:{onMouseDown:C},children:(0,r.jsx)(d.Z,{language:"js",children:t})}),(0,r.jsx)(u.Z,{value:"ts",label:"TS",attributes:{onMouseDown:C},children:(0,r.jsx)(d.Z,{language:"ts",children:o})}),(0,r.jsx)(u.Z,{value:"react",label:"React",attributes:{onMouseDown:C},children:(0,r.jsx)(d.Z,{language:"jsx",children:l})}),(0,r.jsx)(u.Z,{value:"vue",label:"Vue",attributes:{onMouseDown:C},children:(0,r.jsx)(d.Z,{language:"html",children:m})}),(0,r.jsx)(u.Z,{value:"svelte",label:"Svelte",attributes:{onMouseDown:C},children:(0,r.jsx)(d.Z,{language:"html",children:y})})]})})})]})}function g(e){let{className:t,style:s,showCode:n,height:i,...c}=e,{colorMode:d}=(0,o.I)(),u=e=>JSON.stringify(e,null,2),h=`
import { createPlayground } from 'livecodes';
const options = ${u(c)};
createPlayground('#container', options);
`.trimStart(),p=`
import { createPlayground, type EmbedOptions } from 'livecodes';
const options: EmbedOptions = ${u(c)};
createPlayground('#container', options);
`.trimStart(),f=`
import LiveCodes from 'livecodes/react';
export default function App() {
const options = ${u(c)};
return (<LiveCodes {...options}></LiveCodes>);
}
`.trimStart(),g=`
<script setup>
import LiveCodes from "livecodes/vue";
const options = ${u(c)};
</script>
<template>
<LiveCodes v-bind="options" />
</template>
`,y=`
<script>
import { onMount } from 'svelte';
import { createPlayground } from 'livecodes';
let options = $state(${u(c)});
let container = $state(null);
onMount(() => {
createPlayground(container, options);
});
</script>
<div bind:this="{container}"></div>
`.trimStart();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(l,{className:`container_Egsj ${e.className}`,style:{height:i||"50vh",...e.style},appUrl:a.G,...e,config:{theme:d,themeColor:"hsl(215, 8%, 60%)",..."object"==typeof e.config?e.config:{}}}),!1!==e.showCode&&(0,r.jsx)(m,{js:h,ts:p,react:f,vue:g,svelte:y})]})}},8294:function(e,t,s){s.d(t,{T:function(){return o},r:function(){return n}});var r=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:r,loading:o="lazy",view:i}=t,l=r||"headless"===i,a=null,c=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)C(a=document.createElement("div")),document.body.appendChild(a);else throw Error(`Cannot find element: "${e}"`)}let d=new URL(n(t)),u=d.origin;d.searchParams.set("embed","true"),d.searchParams.set("loading",l?"eager":o);let h=globalThis.process;d.searchParams.set("sdkVersion",h?.env?.SDK_VERSION||"latest"),"object"==typeof s&&Object.keys(s).length>0&&d.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=>{d.searchParams.set(e,encodeURIComponent(String(p[e])))});let f=!1,m="Cannot call API methods after calling `destroy()`.",g=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 r="livecodes",n=a.querySelector(`iframe.${r}`),i=n||document.createElement("iframe");i.classList.add(r),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"),l?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=a.style.borderRadius),addEventListener("message",function e(t){t.source===i.contentWindow&&t.origin===u&&t.data?.type==="livecodes-init"&&(removeEventListener("message",e),c=Number(t.data.payload.appVersion.replace(/^v/,"")))}),(!c||c<46)&&addEventListener("message",function e(t){t.source===i.contentWindow&&t.origin===u&&t.data?.type==="livecodes-get-config"&&(removeEventListener("message",e),i.contentWindow?.postMessage({type:"livecodes-config",payload:s},u))}),i.onload=()=>{e(i)},i.src=d.href,n||a.appendChild(i)}),y=new Promise(e=>{addEventListener("message",function t(s){s.source===g.contentWindow&&s.origin===u&&s.data?.type==="livecodes-ready"&&(removeEventListener("message",t),e(),y.settled=!0)})}),v=()=>f?Promise.reject(m):new Promise(async e=>{y.settled&&e(),g.contentWindow?.postMessage({type:"livecodes-load"},u),await y,e()}),j=(e,t)=>new Promise(async(s,r)=>{if(f)return r(m);await v();let o=E();addEventListener("message",function t(n){if(n.source===g.contentWindow&&n.origin===u&&n.data?.type==="livecodes-api-response"&&n.data?.id===o&&n.data.method===e){removeEventListener("message",t);let e=n.data.payload;e?.error?r(e.error):s(e)}}),g.contentWindow?.postMessage({method:e,id:o,args:t},u)}),x={},b=["load","ready","code","console","tests","destroy"],w=(e,t)=>{if(f)throw Error(m);return b.includes(e)?(j("watch",[e]),x[e]||(x[e]=[]),x[e]?.push(t),{remove:()=>{x[e]=x[e]?.filter(e=>e!==t),x[e]?.length===0&&j("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!==g.contentWindow||e.origin!==u||!t||!x[t])return;let s=e.data?.payload;x[t]?.forEach(e=>{e(s)})});let P=()=>{Object.values(x).forEach(e=>{e.length=0}),g?.remove?.(),f=!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(a))})},{rootMargin:"150px"}).observe(a);let E=()=>(String(Math.random())+Date.now().toFixed()).replace("0.","");return{load:()=>v(),run:()=>j("run"),format:e=>j("format",[e]),getShareUrl:e=>j("getShareUrl",[e]),getConfig:e=>j("getConfig",[e]),setConfig:e=>j("setConfig",[e]),getCode:()=>j("getCode"),show:(e,t)=>j("show",[e,t]),runTests:()=>j("runTests"),onChange:e=>w("code",e),watch:w,exec:function(e){for(var t=arguments.length,s=Array(t>1?t-1:0),r=1;r<t;r++)s[r-1]=arguments[r];return j("exec",[e,...s])},destroy:()=>y.settled?j("destroy").then(P):f?Promise.reject(m):(P(),Promise.resolve())}}function n(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{appUrl:s="https://livecodes.io",params:o={},config:n={},headless:i,import:l,lite:a,view:c,...d}=t;try{e=new URL(s)}catch{throw Error(`${s} is not a valid URL.`)}let u=new URLSearchParams;Object.entries(d).forEach(t=>{let[s,r]=t;void 0!==r&&e.searchParams.set(s,String(r))});let h="headless"===t.view||i;if(a&&(console.warn('Deprecation notice: "lite" option is deprecated. Use "config: { mode: \'lite\' }" instead.'),"object"==typeof n&&null==n.mode?n.mode="lite":e.searchParams.set("lite","true")),c&&(console.warn('Deprecation notice: The "view" option has been moved to "config.view". For headless mode use "headless: true".'),"object"==typeof n&&null==n.view&&"headless"!==c?n.view=c:e.searchParams.set("view",c)),"string"==typeof n)try{new URL(n),e.searchParams.set("config",encodeURIComponent(n))}catch{throw Error('"config" is not a valid URL or configuration object.')}else n&&"object"==typeof n&&Object.keys(n).length>0&&(n.title&&"Untitled Project"!==n.title&&e.searchParams.set("title",n.title),n.description&&n.description.length>0&&e.searchParams.set("description",n.description),u.set("config","code/"+(0,r.compressToEncodedURIComponent)(JSON.stringify(n))));if(o&&"object"==typeof o&&Object.keys(o).length>0)try{u.set("params",(0,r.compressToEncodedURIComponent)(JSON.stringify(o)))}catch{Object.keys(o).forEach(t=>{e.searchParams.set(t,encodeURIComponent(String(o[t])))})}return l&&e.searchParams.set("x",encodeURIComponent(l)),h&&e.searchParams.set("headless","true"),e.hash=u.toString(),e.href}},65:function(e,t,s){s.d(t,{Z:function(){return l},a:function(){return i}});var r=s(7294);let o={},n=r.createContext(o);function i(e){let t=r.useContext(n);return r.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(o):e.components||o:i(e.components),r.createElement(n.Provider,{value:t},e.children)}}}]);