livecode-static/docs/assets/js/5b239f4f.7503141f.js
2025-06-11 22:23:49 +08:00

45 lines
19 KiB
JavaScript

"use strict";(self.webpackChunkdocs=self.webpackChunkdocs||[]).push([["1899"],{6373:function(e,t,n){n.r(t),n.d(t,{config:()=>c,config2:()=>u,default:()=>g,frontMatter:()=>o,metadata:()=>s,assets:()=>d,params:()=>h,toc:()=>p,contentTitle:()=>l});var s=JSON.parse('{"id":"languages/handlebars","title":"Handlebars","description":"Handlebars: Minimal templating on steroids.","source":"@site/docs/languages/handlebars.mdx","sourceDirName":"languages","slug":"/languages/handlebars","permalink":"/docs/languages/handlebars","draft":false,"unlisted":false,"editUrl":"https://github.com/live-codes/livecodes/tree/develop/docs/docs/languages/handlebars.mdx","tags":[],"version":"current","frontMatter":{},"sidebar":"docsSidebar","previous":{"title":"Haml","permalink":"/docs/languages/haml"},"next":{"title":"HTML","permalink":"/docs/languages/html"}}'),r=n("5893"),a=n("65"),i=n("3365");let o={},l="Handlebars",d={},c={markup:{language:"handlebars",content:"Hello {{name}}!"},customSettings:{template:{data:{name:"LiveCodes"}}}},h={compiled:"open"},u={markup:{language:"handlebars",content:"Hello {{name}}!"},script:{language:"javascript",content:'window.livecodes.templateData = { name: "LiveCodes" };'},customSettings:{template:{prerender:!1}},activeEditor:"script"},p=[{value:"Usage",id:"usage",level:2},{value:"Pre-rendered (Default)",id:"pre-rendered-default",level:3},{value:"Dynamic",id:"dynamic",level:3},{value:"Language Info",id:"language-info",level:2},{value:"Name",id:"name",level:3},{value:"Extensions",id:"extensions",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:"Custom Settings",id:"custom-settings",level:2},{value:"Example Usage",id:"example-usage",level:2},{value:"Pre-rendered",id:"pre-rendered",level:3},{value:"Dynamic",id:"dynamic-1",level:3},{value:"Links",id:"links",level:2}];function m(e){let t={a:"a",code:"code",h1:"h1",h2:"h2",h3:"h3",header:"header",li:"li",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,a.a)(),...e.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(t.header,{children:(0,r.jsx)(t.h1,{id:"handlebars",children:"Handlebars"})}),"\n",(0,r.jsxs)(t.p,{children:[(0,r.jsx)(t.a,{href:"https://handlebarsjs.com/",children:"Handlebars"}),": Minimal templating on steroids."]}),"\n",(0,r.jsx)(t.h2,{id:"usage",children:"Usage"}),"\n",(0,r.jsx)(t.p,{children:"There are 2 modes for rendering:"}),"\n",(0,r.jsx)(t.h3,{id:"pre-rendered-default",children:"Pre-rendered (Default)"}),"\n",(0,r.jsxs)(t.p,{children:["The values of the expressions are evaluated and added to the template during compilation of the ",(0,r.jsx)(t.a,{href:"/docs/features/result",children:"result page"}),"."]}),"\n",(0,r.jsxs)(t.p,{children:["The values of all expressions should be supplied in advance using ",(0,r.jsx)(t.a,{href:"/docs/advanced/custom-settings",children:"custom settings"})," to the property ",(0,r.jsx)(t.code,{children:"template.data"})," which accepts an object of key-value pairs."]}),"\n",(0,r.jsxs)(t.p,{children:["Example: This provides the value of the expression ",(0,r.jsx)(t.code,{children:"name"})]}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-json",metastring:'title="Custom Settings"',children:'{\n "template": {\n "data": {\n "name": "LiveCodes"\n }\n }\n}\n'})}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.a,{href:"#pre-rendered",children:"Full example below"})}),"\n",(0,r.jsx)(t.h3,{id:"dynamic",children:"Dynamic"}),"\n",(0,r.jsxs)(t.p,{children:["To use this mode, the property ",(0,r.jsx)(t.code,{children:"template.prerender"})," in ",(0,r.jsx)(t.a,{href:"/docs/advanced/custom-settings",children:"custom settings"})," should be set to ",(0,r.jsx)(t.code,{children:"false"}),"."]}),"\n",(0,r.jsx)(t.p,{children:"Example:"}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-json",metastring:'title="Custom Settings"',children:'{\n "template": {\n "prerender": false\n }\n}\n'})}),"\n",(0,r.jsxs)(t.p,{children:["In this mode, in addition to values supplied in custom settings (see above), expressions can have values that are evaluated during the ",(0,r.jsx)(t.a,{href:"/docs/features/result",children:"result page"})," runtime."]}),"\n",(0,r.jsxs)(t.p,{children:["This can be achieved in JavaScript (or any ",(0,r.jsx)(t.a,{href:"/docs/languages/",children:"language"})," that compiles to it) by assigning ",(0,r.jsx)(t.code,{children:"window.livecodes.templateData"})," to an object with the data."]}),"\n",(0,r.jsxs)(t.p,{children:["Please note that template rendering occurs on ",(0,r.jsx)(t.a,{href:"https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event",children:"page load"}),", so the assignment must occur before that."]}),"\n",(0,r.jsx)(t.p,{children:"Example:"}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-js",metastring:'title="Script Editor (JS)"',children:"window.livecodes.templateData = { name: 'LiveCodes' };\n"})}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.a,{href:"#dynamic-1",children:"Full example below"})}),"\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:"handlebars"})}),"\n",(0,r.jsx)(t.h3,{id:"extensions",children:"Extensions"}),"\n",(0,r.jsxs)(t.p,{children:[(0,r.jsx)(t.code,{children:".hbs"}),", ",(0,r.jsx)(t.code,{children:".handlebars"})]}),"\n",(0,r.jsx)(t.h3,{id:"editor",children:"Editor"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.code,{children:"markup"})}),"\n",(0,r.jsx)(t.h2,{id:"compiler",children:"Compiler"}),"\n",(0,r.jsxs)(t.p,{children:["The official ",(0,r.jsx)(t.a,{href:"https://www.npmjs.com/package/handlebars",children:"handlebars compiler"}),"."]}),"\n",(0,r.jsx)(t.h3,{id:"version",children:"Version"}),"\n",(0,r.jsxs)(t.p,{children:[(0,r.jsx)(t.code,{children:"handlebars"}),": v4.7.8"]}),"\n",(0,r.jsx)(t.h2,{id:"code-formatting",children:"Code Formatting"}),"\n",(0,r.jsxs)(t.p,{children:["Using ",(0,r.jsx)(t.a,{href:"https://prettier.io/",children:"Prettier"}),"."]}),"\n",(0,r.jsx)(t.h2,{id:"custom-settings",children:"Custom Settings"}),"\n",(0,r.jsxs)(t.p,{children:[(0,r.jsx)(t.a,{href:"/docs/advanced/custom-settings",children:"Custom settings"})," added to the property ",(0,r.jsx)(t.code,{children:"handlebars"})," are passed as a JSON object to the ",(0,r.jsx)(t.a,{href:"https://handlebarsjs.com/api-reference/compilation.html#handlebars-compile-template-options",children:(0,r.jsx)(t.code,{children:"compile"})})," method during compile. Please check the ",(0,r.jsx)(t.a,{href:"https://handlebarsjs.com/api-reference/compilation.html#handlebars-compile-template-options",children:"documentation"})," for full reference."]}),"\n",(0,r.jsx)(t.p,{children:"Please note that custom settings should be valid JSON (i.e. functions are not allowed)."}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.strong,{children:"Example:"})}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-json",metastring:'title="Custom Settings"',children:'{\n "handlebars": {\n "preventIndent": true\n }\n}\n'})}),"\n",(0,r.jsx)(t.h2,{id:"example-usage",children:"Example Usage"}),"\n","\n",(0,r.jsx)(t.h3,{id:"pre-rendered",children:"Pre-rendered"}),"\n","\n","\n",(0,r.jsx)(i.Z,{config:c,params:h}),"\n",(0,r.jsx)(t.h3,{id:"dynamic-1",children:"Dynamic"}),"\n","\n",(0,r.jsx)(i.Z,{config:u}),"\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://handlebarsjs.com/",children:"Official website"})}),"\n",(0,r.jsx)(t.li,{children:(0,r.jsx)(t.a,{href:"https://handlebarsjs.com/guide/",children:"Language guide"})}),"\n"]})]})}function g(e={}){let{wrapper:t}={...(0,a.a)(),...e.components};return t?(0,r.jsx)(t,{...e,children:(0,r.jsx)(m,{...e})}):m(e)}},3365:function(e,t,n){n.d(t,{Z:()=>f});var s=n("5893"),r=n("4200"),a=n("7294"),i=n("8294");function o(e){let t=(0,a.useRef)(null),[n,r]=(0,a.useState)(e.className||""),[o,l]=(0,a.useState)(e.style||{}),[d,c]=(0,a.useState)(e.height),[h,u]=(0,a.useState)(),[p,m]=(0,a.useState)(JSON.stringify(e.config||"")),[g,f]=(0,a.useState)("");return(0,a.useEffect)(()=>{if(!t.current)return;let{className:n,style:s,height:a,sdkReady:o,config:d,...v}=e;if(r(n||""),l(s||{}),c(a),h&&g===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 f(JSON.stringify(v)),h?.destroy(),(0,i.T)(t.current,{config:d,...v}).then(e=>{u(e),"function"==typeof o&&o(e)})},[e]),(0,a.useEffect)(()=>()=>{h?.destroy()},[]),(0,s.jsx)("div",{ref:t,className:n,style:o,"data-height":d})}var l=n("1858"),d=n("3262"),c=n("1705"),h=n("7645"),u=n("8168"),p=n("8228"),m=n("5050");function g(e){let[t,n]=(0,a.useState)(e.js),[r,i]=(0,a.useState)(e.ts),[o,l]=(0,a.useState)(e.react),[g,f]=(0,a.useState)(e.vue),[v,j]=(0,a.useState)(e.svelte),x="3.7rem",[y,b]=(0,a.useState)(!0),[w,S]=(0,a.useState)(x),C=(0,a.useRef)(null),E=()=>{setTimeout(()=>{S(`calc(${C.current.offsetHeight}px + ${x})`)},5),setTimeout(()=>{S(`calc(${C.current.offsetHeight}px + ${x})`)},255)};return(0,a.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(r,"ts")),l(e(o,"jsx")),f(e(g,"html")),j(e(v,"html"))}},[]),(0,s.jsxs)("details",{className:`alert alert--info ${m.Z.details} ${p.Z.details}`,"data-collapsed":y,style:{height:y?x:w,overflow:"hidden",willChange:"height",transition:`height ${y?"250ms":"265ms"} ease-in-out 0s`,margin:"1em 0"},children:[(0,s.jsx)("summary",{onClick:()=>{b(!y),E()},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)(u.Z,{groupId:"sdk-code",children:[(0,s.jsx)(h.Z,{value:"js",label:"JS",attributes:{onMouseDown:E},children:(0,s.jsx)(c.Z,{language:"js",children:t})}),(0,s.jsx)(h.Z,{value:"ts",label:"TS",attributes:{onMouseDown:E},children:(0,s.jsx)(c.Z,{language:"ts",children:r})}),(0,s.jsx)(h.Z,{value:"react",label:"React",attributes:{onMouseDown:E},children:(0,s.jsx)(c.Z,{language:"jsx",children:o})}),(0,s.jsx)(h.Z,{value:"vue",label:"Vue",attributes:{onMouseDown:E},children:(0,s.jsx)(c.Z,{language:"html",children:g})}),(0,s.jsx)(h.Z,{value:"svelte",label:"Svelte",attributes:{onMouseDown:E},children:(0,s.jsx)(c.Z,{language:"html",children:v})})]})})})]})}function f(e){let{className:t,style:n,showCode:a,height:i,...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(),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)(o,{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:u,ts:p,react:m,vue:f,svelte:v})]})}},8294:function(e,t,n){n.d(t,{T:function(){return r},r:function(){return a}});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:i}=t,o=s||"headless"===i,l=null,d=null;if("string"==typeof e)l=document.querySelector(e);else if(e instanceof HTMLElement)l=e;else if(!(o&&"object"==typeof e))throw Error("A valid container element is required.");if(!l){if(o)E(l=document.createElement("div")),document.body.appendChild(l);else throw Error(`Cannot find element: "${e}"`)}let c=new URL(a(t)),h=c.origin;c.searchParams.set("embed","true"),c.searchParams.set("loading",o?"eager":r);let u=globalThis.process;c.searchParams.set("sdkVersion",u?.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 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&&!o){let e=isNaN(Number(t))?t:t+"px";l.style.height=e}"false"===l.dataset.defaultStyles||o||(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",a=l.querySelector(`iframe.${s}`),i=a||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"===r?"eager":"lazy"),o?E(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,a||l.appendChild(i)}),v=new Promise(e=>{addEventListener("message",function t(n){n.source===f.contentWindow&&n.origin===h&&n.data?.type==="livecodes-ready"&&(removeEventListener("message",t),e(),v.settled=!0)})}),j=()=>m?Promise.reject(g):new Promise(async e=>{v.settled&&e(),f.contentWindow?.postMessage({type:"livecodes-load"},h),await v,e()}),x=(e,t)=>new Promise(async(n,s)=>{if(m)return s(g);await j();let r=P();addEventListener("message",function t(a){if(a.source===f.contentWindow&&a.origin===h&&a.data?.type==="livecodes-api-response"&&a.data?.id===r&&a.data.method===e){removeEventListener("message",t);let e=a.data.payload;e?.error?s(e.error):n(e)}}),f.contentWindow?.postMessage({method:e,id:r,args:t},h)}),y={},b=["load","ready","code","console","tests","destroy"],w=(e,t)=>{if(m)throw Error(g);return b.includes(e)?(x("watch",[e]),y[e]||(y[e]=[]),y[e]?.push(t),{remove:()=>{y[e]=y[e]?.filter(e=>e!==t),y[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||!y[t])return;let n=e.data?.payload;y[t]?.forEach(e=>{e(n)})});let C=()=>{Object.values(y).forEach(e=>{e.length=0}),f?.remove?.(),m=!0};function E(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 j(),t.unobserve(l))})},{rootMargin:"150px"}).observe(l);let P=()=>(String(Math.random())+Date.now().toFixed()).replace("0.","");return{load:()=>j(),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(C):m?Promise.reject(g):(C(),Promise.resolve())}}function a(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{appUrl:n="https://livecodes.io",params:r={},config:a={},headless:i,import:o,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 u="headless"===t.view||i;if(l&&(console.warn('Deprecation notice: "lite" option is deprecated. Use "config: { mode: \'lite\' }" instead.'),"object"==typeof a&&null==a.mode?a.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 a&&null==a.view&&"headless"!==d?a.view=d:e.searchParams.set("view",d)),"string"==typeof a)try{new URL(a),e.searchParams.set("config",encodeURIComponent(a))}catch{throw Error('"config" is not a valid URL or configuration object.')}else a&&"object"==typeof a&&Object.keys(a).length>0&&(a.title&&"Untitled Project"!==a.title&&e.searchParams.set("title",a.title),a.description&&a.description.length>0&&e.searchParams.set("description",a.description),h.set("config","code/"+(0,s.compressToEncodedURIComponent)(JSON.stringify(a))));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 o&&e.searchParams.set("x",encodeURIComponent(o)),u&&e.searchParams.set("headless","true"),e.hash=h.toString(),e.href}},65:function(e,t,n){n.d(t,{Z:function(){return o},a:function(){return i}});var s=n(7294);let r={},a=s.createContext(r);function i(e){let t=s.useContext(a);return s.useMemo(function(){return"function"==typeof e?e(t):{...t,...e}},[t,e])}function o(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(r):e.components||r:i(e.components),s.createElement(a.Provider,{value:t},e.children)}}}]);