livecode-static/docs/assets/js/45901fe2.c001b3f7.js
2025-06-12 09:37:26 +08:00

71 lines
18 KiB
JavaScript

"use strict";(self.webpackChunkdocs=self.webpackChunkdocs||[]).push([["1576"],{9976:function(e,t,n){n.r(t),n.d(t,{default:()=>m,frontMatter:()=>a,metadata:()=>s,assets:()=>c,svelteSDKDemo:()=>h,toc:()=>u,contentTitle:()=>d});var s=JSON.parse('{"id":"sdk/svelte","title":"Svelte","description":"The JS/TS SDK can be used directly in Svelte components without the need for any wrappers.","source":"@site/docs/sdk/svelte.mdx","sourceDirName":"sdk","slug":"/sdk/svelte","permalink":"/docs/sdk/svelte","draft":false,"unlisted":false,"editUrl":"https://github.com/live-codes/livecodes/tree/develop/docs/docs/sdk/svelte.mdx","tags":[],"version":"current","frontMatter":{},"sidebar":"docsSidebar","previous":{"title":"Vue SDK","permalink":"/docs/sdk/vue"},"next":{"title":"Headless Mode","permalink":"/docs/sdk/headless"}}'),o=n("5893"),r=n("65"),i=n("3365"),l=n("8500");let a={},d="Svelte",c={},h={svelte:`<script>
import { onMount } from 'svelte';
import { createPlayground } from 'livecodes';
// Embed Options
const options = {
params: {
html: '<h1>Hello World!</h1>',
css: 'h1 {color: blue;}',
js: 'console.log("Hello, Svelte!")',
console: 'open',
},
};
let container;
let playground = $state(null);
onMount(() => {
createPlayground(container, options).then((p) => {
playground = p; // now the SDK is available
});
// cleanup when the component is destroyed
return () => playground?.destroy();
});
</script>
<div bind:this="{container}"></div>
`},u=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2},{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",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:"svelte",children:"Svelte"})}),"\n","\n",(0,o.jsxs)(t.p,{children:["The ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts",children:"JS/TS SDK"})," can be used directly in Svelte components without the need for any wrappers."]}),"\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.jsx)(t.p,{children:"This is an example of using the LiveCodes JS SDK in a Svelte component:"}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-html",metastring:'title="Component.svelte"',children:"<script>\n import { onMount } from 'svelte';\n import { createPlayground } from 'livecodes';\n\n // Embed Options\n const options = {\n params: {\n html: '<h1>Hello World!</h1>',\n css: 'h1 {color: blue;}',\n js: 'console.log(\"Hello, Svelte!\")',\n console: 'open',\n },\n };\n\n let container;\n let playground = $state(null);\n onMount(() => {\n createPlayground(container, options).then((p) => {\n playground = p; // now the SDK is available\n });\n // cleanup when the component is destroyed\n return () => playground?.destroy();\n });\n<\/script>\n\n<div bind:this=\"{container}\"></div>\n"})}),"\n","\n",(0,o.jsx)(l.Z,{params:h}),"\n",(0,o.jsxs)(t.p,{children:[(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#embed-options",children:"Embed options"}),", ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#sdk-methods",children:"SDK methods"})," and ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#typescript-types",children:"TypeScript types"})," are available as described in the ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts",children:"JS/TS SDK documentations"}),"."]}),"\n",(0,o.jsxs)(t.p,{children:["Alternatively, the SDK function ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#createplayground",children:(0,o.jsx)(t.code,{children:"createPlayground"})})," can be used as an ",(0,o.jsx)(t.a,{href:"https://learn.svelte.dev/tutorial/actions",children:"action"}),"."]}),"\n",(0,o.jsx)(t.p,{children:"Example:"}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-html",metastring:'title="Component.svelte"',children:"<script>\n import { createPlayground } from 'livecodes';\n let options = {\n // embed options\n };\n<\/script>\n\n<div use:createPlayground=\"{options}\"></div>\n"})}),"\n",(0,o.jsx)(t.p,{children:"However, it is recommended to cleanup when the node is unmounted, like that:"}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-html",metastring:'title="Component.svelte"',children:"<script>\n import { createPlayground } from 'livecodes';\n let options = {\n // embed options\n };\n\n const livecodes = (node, opts) => {\n let playground = $state(null);\n const ready = new Promise(async (res) => {\n playground = await createPlayground(node, opts);\n res();\n });\n return { destroy: () => ready.then(() => playground?.destroy()) };\n };\n<\/script>\n\n<div use:livecodes=\"{options}\"></div>\n"})}),"\n",(0,o.jsx)(t.h2,{id:"demo",children:"Demo"}),"\n",(0,o.jsx)(i.Z,{params:h,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/react",children:"React 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/features/embeds",children:"Embedded Playgrounds"})}),"\n"]})]})}function m(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,n){n.d(t,{Z:()=>g});var s=n("5893"),o=n("4200"),r=n("7294"),i=n("8294");function l(e){let t=(0,r.useRef)(null),[n,o]=(0,r.useState)(e.className||""),[l,a]=(0,r.useState)(e.style||{}),[d,c]=(0,r.useState)(e.height),[h,u]=(0,r.useState)(),[p,m]=(0,r.useState)(JSON.stringify(e.config||"")),[f,g]=(0,r.useState)("");return(0,r.useEffect)(()=>{if(!t.current)return;let{className:n,style:s,height:r,sdkReady:l,config:d,...v}=e;if(o(n||""),a(s||{}),c(r),h&&f===JSON.stringify(v)){if(p===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 g(JSON.stringify(v)),h?.destroy(),(0,i.T)(t.current,{config:d,...v}).then(e=>{u(e),"function"==typeof l&&l(e)})},[e]),(0,r.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"),m=n("5050");function f(e){let[t,n]=(0,r.useState)(e.js),[o,i]=(0,r.useState)(e.ts),[l,a]=(0,r.useState)(e.react),[f,g]=(0,r.useState)(e.vue),[v,y]=(0,r.useState)(e.svelte),j="3.7rem",[x,b]=(0,r.useState)(!0),[w,S]=(0,r.useState)(j),k=(0,r.useRef)(null),P=()=>{setTimeout(()=>{S(`calc(${k.current.offsetHeight}px + ${j})`)},5),setTimeout(()=>{S(`calc(${k.current.offsetHeight}px + ${j})`)},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")),a(e(l,"jsx")),g(e(f,"html")),y(e(v,"html"))}},[]),(0,s.jsxs)("details",{className:`alert alert--info ${m.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,s.jsx)("summary",{onClick:()=>{b(!x),P()},children:"show code"}),(0,s.jsx)("div",{ref:k,style:{display:"block",overflow:"hidden"},children:(0,s.jsx)("div",{className:m.Z.collapsibleContent,children:(0,s.jsxs)(u.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:l})}),(0,s.jsx)(h.Z,{value:"vue",label:"Vue",attributes:{onMouseDown:P},children:(0,s.jsx)(c.Z,{language:"html",children:f})}),(0,s.jsx)(h.Z,{value:"svelte",label:"Svelte",attributes:{onMouseDown:P},children:(0,s.jsx)(c.Z,{language:"html",children:v})})]})})})]})}function g(e){let{className:t,style:n,showCode:r,height:i,...d}=e,{colorMode:c}=(0,o.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(),m=`
import LiveCodes from 'livecodes/react';
export default function App() {
const options = ${h(d)};
return (<LiveCodes {...options}></LiveCodes>);
}
`.trimStart(),g=`
<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)(l,{className:`container_Egsj ${e.className}`,style:{height:i||"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)(f,{js:u,ts:p,react:m,vue:g,svelte:v})]})}},8500:function(e,t,n){n.d(t,{Z:()=>d});var s=n("5893");n("7294");var o=n("6735");function r(e){let{children:t,fallback:n}=e;return(0,o.Z)()?(0,s.jsx)(s.Fragment,{children:t?.()}):n??null}var i=n("1705"),l=n("8294"),a=n("1858");function d(e){let{params:t,config:n,code:o,language:d="js",codeTitle:c="",showLineNumbers:h=!1,formatCode:u=!0,linkText:p="Run in LiveCodes",style:m={},className:f=""}=e,g=(0,l.r)({appUrl:a.G,params:t,config:n});return(0,s.jsxs)("div",{style:{marginBottom:"30px",...m},className:f,children:[o&&(0,s.jsx)(r,{children:()=>(0,s.jsx)(i.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})}(o,d):o})}),(0,s.jsxs)("a",{href:g,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 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,l=s||"headless"===i,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)k(a=document.createElement("div")),document.body.appendChild(a);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",l?"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 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,m="Cannot call API methods after calling `destroy()`.",f=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",r=a.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"),l?k(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===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||a.appendChild(i)}),g=new Promise(e=>{addEventListener("message",function t(n){n.source===f.contentWindow&&n.origin===h&&n.data?.type==="livecodes-ready"&&(removeEventListener("message",t),e(),g.settled=!0)})}),v=()=>p?Promise.reject(m):new Promise(async e=>{g.settled&&e(),f.contentWindow?.postMessage({type:"livecodes-load"},h),await g,e()}),y=(e,t)=>new Promise(async(n,s)=>{if(p)return s(m);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?s(e.error):n(e)}}),f.contentWindow?.postMessage({method:e,id:o,args:t},h)}),j={},x=["load","ready","code","console","tests","destroy"],b=(e,t)=>{if(p)throw Error(m);return x.includes(e)?(y("watch",[e]),j[e]||(j[e]=[]),j[e]?.push(t),{remove:()=>{j[e]=j[e]?.filter(e=>e!==t),j[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!==f.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}),f?.remove?.(),p=!0};function k(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 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=>b("code",e),watch:b,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:()=>g.settled?y("destroy").then(S):p?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: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||i;if(a&&(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 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 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 l(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)}}}]);