livecode-static/docs/assets/js/4738667a.62f39206.js
2025-06-12 09:37:26 +08:00

83 lines
18 KiB
JavaScript

"use strict";(self.webpackChunkdocs=self.webpackChunkdocs||[]).push([["9826"],{6183:function(e,t,n){n.r(t),n.d(t,{default:()=>p,frontMatter:()=>o,javaConfig:()=>c,assets:()=>d,metadata:()=>i,toc:()=>h,contentTitle:()=>l});var i=JSON.parse('{"id":"languages/java","title":"Java","description":"Java is a high-level, general-purpose, memory-safe, object-oriented programming language.","source":"@site/docs/languages/java.mdx","sourceDirName":"languages","slug":"/languages/java","permalink":"/docs/languages/java","draft":false,"unlisted":false,"editUrl":"https://github.com/live-codes/livecodes/tree/develop/docs/docs/languages/java.mdx","tags":[],"version":"current","frontMatter":{},"sidebar":"docsSidebar","previous":{"title":"Imba","permalink":"/docs/languages/imba"},"next":{"title":"JavaScript","permalink":"/docs/languages/javascript"}}'),r=n("5893"),s=n("65"),a=n("3365");let o={},l="Java",d={},c={activeEditor:"script",script:{language:"java",content:`public class BinarySearchSnippet {
/**
* Search an item with binarySearch algorithm.
*
* @param arr sorted array to search
* @param item an item to search
* @return if item is found, return the index position of the array item otherwise return -1
*/
public static int binarySearch(int[] arr, int left, int right, int item) {
if (right >= left) {
int mid = left + (right - left) / 2;
if (arr[mid] == item) {
return mid;
}
if (arr[mid] > item) {
return binarySearch(arr, left, mid - 1, item);
}
return binarySearch(arr, mid + 1, right, item);
}
return -1;
}
public static void main(String[] args) {
int[] sortedArray = {1, 3, 5, 7, 9, 11, 13, 15};
int itemToSearch = 7;
int result = binarySearch(sortedArray, 0, sortedArray.length - 1, itemToSearch);
if (result == -1) {
System.out.println("Result: Item not found in the array.");
} else {
System.out.println("Result: Item found at index -> " + result);
}
}
}
`},mode:"simple",editor:"auto",tools:{status:"full"}},h=[{value:"Usage",id:"usage",level:2},{value:"Communication with JavaScript",id:"communication-with-javascript",level:3},{value:"Language Info",id:"language-info",level:2},{value:"Name",id:"name",level:3},{value:"Extension",id:"extension",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:"Live Reload",id:"live-reload",level:2},{value:"Starter Template",id:"starter-template",level:2},{value:"Links",id:"links",level:2}];function u(e){let t={a:"a",code:"code",h1:"h1",h2:"h2",h3:"h3",header:"header",li:"li",p:"p",ul:"ul",...(0,s.a)(),...e.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(t.header,{children:(0,r.jsx)(t.h1,{id:"java",children:"Java"})}),"\n",(0,r.jsx)(t.p,{children:"Java is a high-level, general-purpose, memory-safe, object-oriented programming language."}),"\n",(0,r.jsxs)(t.p,{children:["In LiveCodes, Java runs in the browser using ",(0,r.jsx)(t.a,{href:"https://github.com/plasma-umass/doppio",children:"DoppioJVM"}),"."]}),"\n",(0,r.jsx)(t.h2,{id:"usage",children:"Usage"}),"\n",(0,r.jsx)(t.p,{children:"Demo:"}),"\n","\n","\n",(0,r.jsx)(a.Z,{config:c}),"\n",(0,r.jsx)(t.h3,{id:"communication-with-javascript",children:"Communication with JavaScript"}),"\n",(0,r.jsxs)(t.p,{children:["The Java code runs in the context of the ",(0,r.jsx)(t.a,{href:"/docs/features/result",children:"result page"}),".\nA few helper properties and methods are available in the browser global ",(0,r.jsx)(t.code,{children:"livecodes.java"})," object:"]}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"livecodes.java.input"}),": the initial standard input that is passed to the Java code."]}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"livecodes.java.loaded"}),": A promise that resolves when the Java environment is loaded. Any other helpers should be used after this promise resolves."]}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"livecodes.java.output"}),": the standard output."]}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"livecodes.java.error"}),": the standard error."]}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"livecodes.java.exitCode"}),": the exit code."]}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.code,{children:"livecodes.java.run"}),": a function that runs the Java code with new input. This function takes a string as input and returns a promise that resolves when the Java code is done running. The promise resolves with an object containing the ",(0,r.jsx)(t.code,{children:"input"}),", ",(0,r.jsx)(t.code,{children:"output"}),", ",(0,r.jsx)(t.code,{children:"error"}),", and ",(0,r.jsx)(t.code,{children:"exitCode"})," properties."]}),"\n"]}),"\n",(0,r.jsx)(t.p,{children:"Example:"}),"\n",(0,r.jsx)(a.Z,{template:"java",params:{activeEditor:"markup"},height:"80vh"}),"\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:"java"})}),"\n",(0,r.jsx)(t.h3,{id:"extension",children:"Extension"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.code,{children:".java"})}),"\n",(0,r.jsx)(t.h3,{id:"editor",children:"Editor"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.code,{children:"script"})}),"\n",(0,r.jsx)(t.h2,{id:"compiler",children:"Compiler"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.a,{href:"https://github.com/plasma-umass/doppio",children:"DoppioJVM"})}),"\n",(0,r.jsx)(t.h3,{id:"version",children:"Version"}),"\n",(0,r.jsxs)(t.p,{children:[(0,r.jsx)(t.code,{children:"DoppioJVM"}),": v0.5.0, which runs Java 8 JDK."]}),"\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"})," with the ",(0,r.jsx)(t.a,{href:"https://github.com/jhipster/prettier-java",children:"Prettier Java plugin"}),"."]}),"\n",(0,r.jsx)(t.h2,{id:"live-reload",children:"Live Reload"}),"\n",(0,r.jsx)(t.p,{children:"By default, new code changes are sent to the result page for re-evaluation without a full page reload, to avoid the need to reload the Java environment."}),"\n",(0,r.jsxs)(t.p,{children:["This behavior can be disabled by adding the code comment ",(0,r.jsx)(t.code,{children:"// __livecodes_reload__"})," to the code, which will force a full page reload.\nThis comment can be added in the ",(0,r.jsxs)(t.a,{href:"/docs/configuration/configuration-object#markup",children:[(0,r.jsx)(t.code,{children:"hiddenContent"})," property of the editor"]})," for embedded playgrounds."]}),"\n",(0,r.jsx)(t.h2,{id:"starter-template",children:"Starter Template"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.a,{href:"https://livecodes.io/?template=java",children:"https://livecodes.io/?template=java"})}),"\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://www.java.com/",children:"Java"})}),"\n",(0,r.jsx)(t.li,{children:(0,r.jsx)(t.a,{href:"https://github.com/plasma-umass/doppio",children:"DoppioJVM"})}),"\n"]})]})}function p(e={}){let{wrapper:t}={...(0,s.a)(),...e.components};return t?(0,r.jsx)(t,{...e,children:(0,r.jsx)(u,{...e})}):u(e)}},3365:function(e,t,n){n.d(t,{Z:()=>v});var i=n("5893"),r=n("4200"),s=n("7294"),a=n("8294");function o(e){let t=(0,s.useRef)(null),[n,r]=(0,s.useState)(e.className||""),[o,l]=(0,s.useState)(e.style||{}),[d,c]=(0,s.useState)(e.height),[h,u]=(0,s.useState)(),[p,m]=(0,s.useState)(JSON.stringify(e.config||"")),[g,v]=(0,s.useState)("");return(0,s.useEffect)(()=>{if(!t.current)return;let{className:n,style:i,height:s,sdkReady:o,config:d,...f}=e;if(r(n||""),l(i||{}),c(s),h&&g===JSON.stringify(f)){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 v(JSON.stringify(f)),h?.destroy(),(0,a.T)(t.current,{config:d,...f}).then(e=>{u(e),"function"==typeof o&&o(e)})},[e]),(0,s.useEffect)(()=>()=>{h?.destroy()},[]),(0,i.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,s.useState)(e.js),[r,a]=(0,s.useState)(e.ts),[o,l]=(0,s.useState)(e.react),[g,v]=(0,s.useState)(e.vue),[f,j]=(0,s.useState)(e.svelte),y="3.7rem",[x,b]=(0,s.useState)(!0),[w,S]=(0,s.useState)(y),C=(0,s.useRef)(null),E=()=>{setTimeout(()=>{S(`calc(${C.current.offsetHeight}px + ${y})`)},5),setTimeout(()=>{S(`calc(${C.current.offsetHeight}px + ${y})`)},255)};return(0,s.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")),a(e(r,"ts")),l(e(o,"jsx")),v(e(g,"html")),j(e(f,"html"))}},[]),(0,i.jsxs)("details",{className:`alert alert--info ${m.Z.details} ${p.Z.details}`,"data-collapsed":x,style:{height:x?y:w,overflow:"hidden",willChange:"height",transition:`height ${x?"250ms":"265ms"} ease-in-out 0s`,margin:"1em 0"},children:[(0,i.jsx)("summary",{onClick:()=>{b(!x),E()},children:"show code"}),(0,i.jsx)("div",{ref:C,style:{display:"block",overflow:"hidden"},children:(0,i.jsx)("div",{className:m.Z.collapsibleContent,children:(0,i.jsxs)(u.Z,{groupId:"sdk-code",children:[(0,i.jsx)(h.Z,{value:"js",label:"JS",attributes:{onMouseDown:E},children:(0,i.jsx)(c.Z,{language:"js",children:t})}),(0,i.jsx)(h.Z,{value:"ts",label:"TS",attributes:{onMouseDown:E},children:(0,i.jsx)(c.Z,{language:"ts",children:r})}),(0,i.jsx)(h.Z,{value:"react",label:"React",attributes:{onMouseDown:E},children:(0,i.jsx)(c.Z,{language:"jsx",children:o})}),(0,i.jsx)(h.Z,{value:"vue",label:"Vue",attributes:{onMouseDown:E},children:(0,i.jsx)(c.Z,{language:"html",children:g})}),(0,i.jsx)(h.Z,{value:"svelte",label:"Svelte",attributes:{onMouseDown:E},children:(0,i.jsx)(c.Z,{language:"html",children:f})})]})})})]})}function v(e){let{className:t,style:n,showCode:s,height:a,...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(),v=`
<script setup>
import LiveCodes from "livecodes/vue";
const options = ${h(d)};
</script>
<template>
<LiveCodes v-bind="options" />
</template>
`,f=`
<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,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(o,{className:`container_Egsj ${e.className}`,style:{height:a||"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,i.jsx)(g,{js:u,ts:p,react:m,vue:v,svelte:f})]})}},8294:function(e,t,n){n.d(t,{T:function(){return r},r:function(){return s}});var i=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:i,loading:r="lazy",view:a}=t,o=i||"headless"===a,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)C(l=document.createElement("div")),document.body.appendChild(l);else throw Error(`Cannot find element: "${e}"`)}let c=new URL(s(t)),h=c.origin;c.searchParams.set("embed","true"),c.searchParams.set("loading",o?"eager":r),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()`.",g=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 i="livecodes",s=l.querySelector(`iframe.${i}`),a=s||document.createElement("iframe");a.classList.add(i),a.setAttribute("allow","accelerometer; camera; encrypted-media; display-capture; geolocation; gyroscope; microphone; midi; clipboard-read; clipboard-write; web-share"),a.setAttribute("allowtransparency","true"),a.setAttribute("allowpaymentrequest","true"),a.setAttribute("allowfullscreen","true"),a.setAttribute("sandbox","allow-same-origin allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-presentation allow-scripts"),a.setAttribute("loading","eager"===r?"eager":"lazy"),o?C(a):(a.style.height="100%",a.style.minHeight="200px",a.style.width="100%",a.style.margin="0",a.style.border="0",a.style.borderRadius=l.style.borderRadius),addEventListener("message",function e(t){t.source===a.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===a.contentWindow&&t.origin===h&&t.data?.type==="livecodes-get-config"&&(removeEventListener("message",e),a.contentWindow?.postMessage({type:"livecodes-config",payload:n},h))}),a.onload=()=>{e(a)},a.src=c.href,s||l.appendChild(a)}),v=new Promise(e=>{addEventListener("message",function t(n){n.source===g.contentWindow&&n.origin===h&&n.data?.type==="livecodes-ready"&&(removeEventListener("message",t),e(),v.settled=!0)})}),f=()=>p?Promise.reject(m):new Promise(async e=>{v.settled&&e(),g.contentWindow?.postMessage({type:"livecodes-load"},h),await v,e()}),j=(e,t)=>new Promise(async(n,i)=>{if(p)return i(m);await f();let r=E();addEventListener("message",function t(s){if(s.source===g.contentWindow&&s.origin===h&&s.data?.type==="livecodes-api-response"&&s.data?.id===r&&s.data.method===e){removeEventListener("message",t);let e=s.data.payload;e?.error?i(e.error):n(e)}}),g.contentWindow?.postMessage({method:e,id:r,args:t},h)}),y={},x=["load","ready","code","console","tests","destroy"],b=(e,t)=>{if(p)throw Error(m);return x.includes(e)?(j("watch",[e]),y[e]||(y[e]=[]),y[e]?.push(t),{remove:()=>{y[e]=y[e]?.filter(e=>e!==t),y[e]?.length===0&&j("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||!y[t])return;let n=e.data?.payload;y[t]?.forEach(e=>{e(n)})});let S=()=>{Object.values(y).forEach(e=>{e.length=0}),g?.remove?.(),p=!0};function C(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 f(),t.unobserve(l))})},{rootMargin:"150px"}).observe(l);let E=()=>(String(Math.random())+Date.now().toFixed()).replace("0.","");return{load:()=>f(),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=>b("code",e),watch:b,exec:function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return j("exec",[e,...n])},destroy:()=>v.settled?j("destroy").then(S):p?Promise.reject(m):(S(),Promise.resolve())}}function s(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{appUrl:n="https://livecodes.io",params:r={},config:s={},headless:a,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,i]=t;void 0!==i&&e.searchParams.set(n,String(i))});let u="headless"===t.view||a;if(l&&(console.warn('Deprecation notice: "lite" option is deprecated. Use "config: { mode: \'lite\' }" instead.'),"object"==typeof s&&null==s.mode?s.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 s&&null==s.view&&"headless"!==d?s.view=d:e.searchParams.set("view",d)),"string"==typeof s)try{new URL(s),e.searchParams.set("config",encodeURIComponent(s))}catch{throw Error('"config" is not a valid URL or configuration object.')}else s&&"object"==typeof s&&Object.keys(s).length>0&&(s.title&&"Untitled Project"!==s.title&&e.searchParams.set("title",s.title),s.description&&s.description.length>0&&e.searchParams.set("description",s.description),h.set("config","code/"+(0,i.compressToEncodedURIComponent)(JSON.stringify(s))));if(r&&"object"==typeof r&&Object.keys(r).length>0)try{h.set("params",(0,i.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 a}});var i=n(7294);let r={},s=i.createContext(r);function a(e){let t=i.useContext(s);return i.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:a(e.components),i.createElement(s.Provider,{value:t},e.children)}}}]);