Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 24 additions & 21 deletions examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,45 +144,48 @@ You can use Compose Wasm.
<div class="kotlin-code" data-target-platform="compose-wasm">

```kotlin
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.window.CanvasBasedWindow
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.window.ComposeViewport
import kotlinx.browser.document

//sampleStart
@OptIn(ExperimentalComposeUiApi::class)
fun main() {
CanvasBasedWindow { App() }
ComposeViewport(viewportContainer = document.body!!, content = {
App()
})
}

@Composable
fun App() {
MaterialTheme {
var greetingText by remember { mutableStateOf("Hello World!") }
var showImage by remember { mutableStateOf(false) }
var counter by remember { mutableStateOf(0) }
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
Button(onClick = {
counter++
greetingText = "Compose: ${Greeting().greet()}"
showImage = !showImage
}) {
Text(greetingText)
var showContent by remember { mutableStateOf(false) }
Column(
modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Button(onClick = { showContent = !showContent }) {
Text("Click me!")
}
AnimatedVisibility(showImage) {
Text(counter.toString())
AnimatedVisibility(showContent) {
val greeting = remember { Greeting().greet() }
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text("Compose: $greeting")
}
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "kotlin-playground",
"version": "1.31.0-alfa11",
"version": "1.32.0-alpha.3",
"description": "Self-contained component to embed in websites for running Kotlin code",
"keywords": [
"kotlin",
Expand Down Expand Up @@ -80,7 +80,7 @@
"copy-examples": "node utils/copy-examples",
"release:ci": "rm -rf dist && npm run build:all && $NPM_TOKEN=%env.NPM_TOKEN% npm publish",
"start": "webpack-dev-server --port 9002",
"start-with-local-compiler": "webpack-dev-server --port 9002 --env webDemoUrl='//localhost:8080'",
"start-with-local-compiler": "webpack-dev-server --port 9002 --env webDemoUrl='http://localhost:8080' webDemoResourcesUrl='http://localhost:8081'",
"lint": "eslint . --ext .ts",
"fix": "eslint --fix --ext .ts .",
"test": "npm run build:all && npm run test:run",
Expand Down
21 changes: 8 additions & 13 deletions src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,14 @@ export const RUNTIME_CONFIG = { ...getConfigFromElement(currentScript) };
* @type {{COMPILE: string, COMPLETE: string, VERSIONS: string, JQUERY: string, KOTLIN_JS: string}}
*/
export const API_URLS = {
server: (RUNTIME_CONFIG.server || __WEBDEMO_URL__).replace(/\/$/, ''),
composeServer: (
'https://compose.sandbox.intellij.net' || __WEBDEMO_URL__
).replace(/\/$/, ''),
server: (__WEBDEMO_URL__ || RUNTIME_CONFIG.server).replace(/\/$/, ''),
composeServer: (__WEBDEMO_URL__ || 'https://compose-stage.sandbox.intellij.net').replace(
/\/$/,
'',
),
composeResources: (__WEBDEMO_RESOURCES_URL__ || 'https://compose-stage.sandbox.intellij.net').replace(
/\/$/, ''
),

COMPILE(platform, version) {
let url;
Expand All @@ -27,9 +31,6 @@ export const API_URLS = {
url = `${this.server}/api/${version}/compiler/translate`;
break;
case TargetPlatforms.JS:
url = `${this.server}/api/${version}/compiler/translate`;
break;
case TargetPlatforms.JS_IR:
url = `${this.server}/api/${version}/compiler/translate?ir=true`;
break;
case TargetPlatforms.WASM:
Expand Down Expand Up @@ -62,12 +63,6 @@ export const API_URLS = {
get VERSIONS() {
return `${this.server}/versions`;
},
SKIKO_MJS() {
return `${this.composeServer}/api/resource/skiko.mjs`;
},
SKIKO_WASM() {
return `${this.composeServer}/api/resource/skiko.wasm`;
},
get JQUERY() {
return `https://cdn.jsdelivr.net/npm/jquery@1/dist/jquery.min.js`;
},
Expand Down
19 changes: 6 additions & 13 deletions src/executable-code/executable-fragment.js
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,8 @@ export default class ExecutableFragment extends ExecutableCodeTemplate {
}

onConsoleCloseButtonEnter() {
const { jsLibs, onCloseConsole, targetPlatform, compilerVersion } = this.state;
const { jsLibs, onCloseConsole, targetPlatform, compilerVersion } =
this.state;
// creates a new iframe and removes the old one, thereby stops execution of any running script
if (isJsRelated(targetPlatform) || isWasmRelated(targetPlatform))
this.jsExecutor.reloadIframeScripts(
Expand Down Expand Up @@ -411,24 +412,15 @@ export default class ExecutableFragment extends ExecutableCodeTemplate {
targetPlatform,
compilerVersion,
);
const additionalRequests = [];
if (targetPlatform === TargetPlatforms.COMPOSE_WASM) {
if (!this.jsExecutor.skikoImport) {
additionalRequests.push(this.jsExecutor.skikoImport);
}
}

Promise.all([
WebDemoApi.translateKotlinToJs(
WebDemoApi.translateKotlinToJs(
this.getCode(),
compilerVersion,
targetPlatform,
args,
hiddenDependencies,
),
...additionalRequests,
]).then(
([state]) => {
).then(
(state) => {
state.waitingForOutput = false;
const jsCode = state.jsCode;
const wasm = state.wasm;
Expand All @@ -453,6 +445,7 @@ export default class ExecutableFragment extends ExecutableCodeTemplate {
outputHeight,
theme,
onError,
compilerVersion,
)
.then((output) => {
const originState = state.openConsole;
Expand Down
25 changes: 14 additions & 11 deletions src/js-executor/execute-es-module.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
import {API_URLS} from "../config";

export async function executeWasmCode(container, jsCode, wasmCode) {
const newCode = prepareJsCode(jsCode);
return execute(container, newCode, wasmCode);
}

export async function executeWasmCodeWithSkiko(container, jsCode, wasmCode) {
const newCode = prepareJsCode(jsCode)
.replaceAll(
"imports['./skiko.mjs']",
"window.skikoImports"
);
return execute(container, newCode, wasmCode);
}

function execute(container, jsCode, wasmCode) {
container.wasmCode = Uint8Array.from(atob(wasmCode), c => c.charCodeAt(0));
return executeJs(container, jsCode);
}

export function executeJs(container, jsCode) {
function executeJs(container, jsCode) {
return container.eval(`import(/* webpackIgnore: true */ '${'data:text/javascript;base64,' + btoa(jsCode)}');`)
}

function prepareJsCode(jsCode) {
const re = /instantiateStreaming\(fetch\(new URL\('([^']*)',\s*import\.meta\.url\)\.href\),\s*importObject\s*,\s*\{\s*builtins\s*:\s*\[''\]\s*\}\s*\)\)\.instance;/g;

return `
class BufferedOutput {
constructor() {
Expand All @@ -31,12 +26,20 @@ function prepareJsCode(jsCode) {
export const bufferedOutput = new BufferedOutput()
` +
jsCode
.replaceAll(
"await import('./",
"await import('" + API_URLS.composeResources + "/"
)
.replaceAll(
"%3",
"%253"
)
.replace(
"instantiateStreaming(fetch(wasmFilePath), importObject)).instance;",
"instantiate(window.wasmCode, importObject)).instance;\nwindow.wasmCode = undefined;"
)
.replace(
"instantiateStreaming(fetch(new URL('./playground.wasm',import.meta.url).href), importObject)).instance;",
re,
"instantiate(window.wasmCode, importObject)).instance;\nwindow.wasmCode = undefined;"
)
.replace(
Expand Down
Loading