Skip to content

Commit

Permalink
chore(js-lib): update version
Browse files Browse the repository at this point in the history
  • Loading branch information
jourdain committed Jun 5, 2024
1 parent 0a1bf78 commit 2358431
Show file tree
Hide file tree
Showing 14 changed files with 4,918 additions and 32 deletions.
130 changes: 126 additions & 4 deletions js-lib/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,132 @@

This library aims to simplify integration of any web client with a trame server.

## Examples

## Dev setup
- [CDN](./examples/cdn/)
- [Vite](./examples/vite/)

```bash
npm install
npm run build
## Usage

```js
const trame = new Trame()
await trame.connect({ application: 'trame' });

// State handing
trame.state.set("a", 5);
console.log(trame.state.get("b"));
trame.state.update({
a: 1,
b: 2,
});
trame.state.watch(["a"], (a) => {
console.log(`a changed to ${a}`);
})

// Method call on Python
const result = await trame.trigger("name", [arg_0, arg_1], { kwarg_0: 1, kwarg_1: 2 });

// Register JS object so Python can make method calls
// py => server.js_call("name", "method", arg_0, arg_1)
trame.refs["name", js_object];
```

More API examples

```js

// Connect to server and wait until connected
// - sessionURL
// - sessionManagerURL
await trame.connect({ application: "trame" });

// custom serializer registration for method/state
trame.registerDecorator()

// same as waiting on connect
await trame.ready

// Listen to connection status change
const unsubscribeOnClose = trame.onClose((info) => {
console.log("connection closed", info);
});
unsubscribeOnClose();

// Listen to connection status change
const unsubscribeOnError = trame.onError((info) => {
console.log("connection error", info);
});
unsubscribeOnError();

// Listen to connection status change
const unsubscribeOnDisconnect = trame.onDisconnect(() => {
console.log("Client is disconnecting");
});
unsubscribeOnDisconnect();

// Ask server to exit and disconnect
trame.exit(timeout);

// Disconnect from server but don't ask the server to exit
trame.disconnect();

// Try to reconnect using the same info as before after a onClose
await trame.reconnect();

// -----------------------------------
// WsClient API
// -----------------------------------
console.log(trame.client);

// -----------------------------------
// State API
// -----------------------------------
console.log(trame.state);

// set
trame.state.set("a", 2);
trame.state.set('b', 3);
trame.state.update({
a: 2.5,
b: 3.5,
c: 4.5,
})

// get
console.log(trame.state.get("c"));
console.log(trame.state.get('a'));

// force send to server
trame.state.flush('a', 'b');

// listener for state change
const unsubscribe = trame.state.onChange(({ type, keys }) => {
if (type === "dirty-state") {
console.log(`${keys} have changed`);
} else if (type === "new-keys") {
console.log(`${keys} have been added`);
} else {
console.log(`Unkown type(${type}) of message`)
}
});
unsubscribe();

// simpler api for state change
const unsubscribe2 = trame.state.watch(
["a", "b", "c"],
(a, b, c) => {
console.log(`a(${a}) or b(${b}) or c(${c}) have changed`);
}
);
unsubscribe2();

// -----------------------------------
// Method execution API
// -----------------------------------

// method execution on Python side
trame.trigger("name", ['arg_0', 'arg_1'], { kwarg_0: 1, kwarg_1: 2 });

// object registration on JS side so Python can execute methods on them
trame.refs["ref_name"] = console;
```
36 changes: 29 additions & 7 deletions js-lib/examples/cdn/server.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import asyncio
import random
from trame.app import get_server

server = get_server()
state, ctrl = server.state, server.controller

state.list = [
"a",
"b",
"c",
]

state.count = 1
state.play = False


@state.change("count")
def count_change(count, **_):
print(f"count={count}")


@ctrl.trigger("add")
Expand All @@ -19,7 +21,27 @@ def add_to_count():

@ctrl.trigger("subtract")
def subtract_to_count():
state.count += 1
state.count -= 1


@ctrl.trigger("toggle_play")
def toggle_play():
state.play = not state.play


@ctrl.trigger("random")
def random_count():
server.js_call("counter", "reset", random.random())


async def animate(**kwargs):
while True:
await asyncio.sleep(0.5)
if state.play:
with state:
state.count += 1


ctrl.on_server_ready.add_task(animate)

server.start()
59 changes: 40 additions & 19 deletions js-lib/examples/cdn/www/index.html
Original file line number Diff line number Diff line change
@@ -1,29 +1,50 @@
<!DOCTYPE html><html lang="en">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>My Trame Client</title>
</head>
<body>
<main>
<h1>Welcome to My Trame Client</h1>
<button class="add">Add</button>
<button class="subtract">Subtract</button>
<div class="count">from HTML</div>
<div>
<h1>Hello Trame !</h1>
<div class="card">
<button id="counter" type="button"></button>
<button id="play" type="button">Auto update</button>
<button id="subtract" type="button">-1</button>
<button id="random" type="button">Random</button>
</div>
</div>
</main>
<script crossorigin="anonymous" src="https://www.unpkg.com/@kitware/trame/dist/trame.umd.js"></script>
<script
crossorigin="anonymous"
src="https://www.unpkg.com/@kitware/trame/dist/trame.umd.js"
></script>
<script>
const trame = new Trame();
trame.connect().then((config) => {
console.log(config);

trame.state.watch(["count"], (count) => {
document.querySelector(".count").innerHTML = count;
});
document.querySelector(".add").addEventListener("click", () => trame.trigger("add"));
document.querySelector(".subtract").addEventListener("click", () => trame.trigger("subtract"));
const trame = new Trame();
trame.connect().then((config) => {
trame.refs["counter"] = {
reset(value) {
trame.state.set("count", value);
},
};
const element = document.querySelector("#counter");
trame.state.watch(["count"], (count) => {
element.innerHTML = `count is ${count}`;
});
element.addEventListener("click", () => trame.trigger("add"));
document
.querySelector("#play")
.addEventListener("click", () => trame.trigger("toggle_play"));
document
.querySelector("#subtract")
.addEventListener("click", () => trame.trigger("subtract"));
document
.querySelector("#random")
.addEventListener("click", () => trame.trigger("random"));
});
</script>
</body>
</html>
</html>
25 changes: 25 additions & 0 deletions js-lib/examples/vite/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Vite project

This example use npm package to illustrate how to use the trame client.

## Trame setup

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install trame
```

## Build the client

```bash
cd client
npm i
npm run build
```

## Running example

```bash
python ./server.py --content ./client/dist
```
24 changes: 24 additions & 0 deletions js-lib/examples/vite/client/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
6 changes: 6 additions & 0 deletions js-lib/examples/vite/client/counter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export function setupCounter(element, trame) {
trame.state.watch(["count"], (count) => {
element.innerHTML = `count is ${count}`;
});
element.addEventListener("click", () => trame.trigger("add"));
}
12 changes: 12 additions & 0 deletions js-lib/examples/vite/client/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/main.js"></script>
</body>
</html>
35 changes: 35 additions & 0 deletions js-lib/examples/vite/client/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import "./style.css";
// import Trame from "@kitware/trame";
import Trame from "../../../dist/trame.mjs";
import { setupCounter } from "./counter.js";

document.querySelector("#app").innerHTML = `
<div>
<h1>Hello Trame !</h1>
<div class="card">
<button id="counter" type="button"></button>
<button id="play" type="button">Auto update</button>
<button id="subtract" type="button">-1</button>
<button id="random" type="button">Random</button>
</div>
</div>
`;

const trame = new Trame();
trame.connect().then(() => {
setupCounter(document.querySelector("#counter"), trame);
trame.refs["counter"] = {
reset(value) {
trame.state.set("count", value);
},
};
document
.querySelector("#play")
.addEventListener("click", () => trame.trigger("toggle_play"));
document
.querySelector("#subtract")
.addEventListener("click", () => trame.trigger("subtract"));
document
.querySelector("#random")
.addEventListener("click", () => trame.trigger("random"));
});
Loading

0 comments on commit 2358431

Please sign in to comment.