Skip to content

Commit

Permalink
docs(api): Update client side API
Browse files Browse the repository at this point in the history
  • Loading branch information
jourdain committed Aug 17, 2022
1 parent 1877a46 commit 738565f
Show file tree
Hide file tree
Showing 3 changed files with 287 additions and 0 deletions.
182 changes: 182 additions & 0 deletions docs/api/source/client.intro.rst
@@ -0,0 +1,182 @@
Introduction
===================================================

Trame is driven by Python but sometime, JavaScript expression needs to be written.
This document aims to gather tools and utilities available on the "client side" for you to use.

State variables
---------------------------------------------------

The first thing you have access is obviously the various state variables that you've defined.

.. code-block:: python
from trame.app import get_server
server = get_server()
state = server.state
state.welcome = "hello"
state.name = "seb"
# ...
with layout:
vuetify.VTextField(v_model=("welcome",)) # welcome is a reactive variable that is linked to state.welcome from Python
vuetify.VTextField(v_model=("name",)) # name is a reactive variable that is linked to state.name from Python
Methods available
---------------------------------------------------

On top of the state variables, a couple of methods are also available for you to use when needed.


.. function:: set(key, value)

Given a variable name as a string you can set its value to something new like shown in the example below.

:param key: The name of the state variable to set
:type key: str


:param value: The value to set that variable to


.. code-block:: python
vuetify.VTextField(v_model=("var_name", "a"))
vuetify.VTextField(v_model=("var_value", "value"))
vuetify.VBtn("Set value", click="set(var_name, var_value)")
.. function:: get(key=null)

Given a variable name, its value will be returned. If nothing is provided, the full state will be returned as a dictionary.

:param key: The name of the state variable to retrieve
:type key: str

:return: Return the value stored within that state variable

.. function:: setAll(obj={})

Given an object, set all key/value pair into the state before flushing it.

:param obj: Map gathering the set of key/value pair to update
:type obj: {}


.. code-block:: python
vuetify.VBtn("Reset many vars", click="setAll({ a: 1, b: true, c: 'hello' })")
.. function:: flushState(...keys)

Force push one or many local state variables to the server. This is especially useful when dynamically editing nested content.

:param ...keys: Names of all the variables that needs to be push back to Python
:type ...keys: str


.. code-block:: python
# ...
state.slider_values = [1, 2, 3, 4]
with layout:
vuetify.VSlider(
v_for="v, index in slider_values",
key="index",
v_model="slider_values[index]",
change="flushState('slider_values')"
)
.. function:: registerDecorator(...args)

Used internally to register special serializers for exchanging data between Python and JS.

.. function:: trigger(name, args=[], kwargs={})

Call a method from JavaScript to Python.

:param name: Name of the trigger to execute
:type name: str

:param args: List of arguments to provide to the method call
:type args: []

:param kwargs: List of keyword arguments to provide to the method call
:type kwargs: {}

:returns: A promise matching the return value of the Python method.

.. code-block:: python
@ctrl.trigger("exec_prog")
def exec_function(*args, **kwargs):
print("exec_function", args, kwargs)
# ...
with layout:
vuetify.VBtn("Exec", click="trigger('exec_prog', [1, 2, 3], { b: 2 })")
or you can do

.. code-block:: python
def exec_function(*args, **kwargs):
print("exec_function", args, kwargs)
# ...
with layout:
vuetify.VBtn("Exec", click=(exec_function, "[1, 2, 3]", "{ b: 2 }"))
and even


.. code-block:: python
def exec_function(*args, **kwargs):
print("exec_function", args, kwargs)
# ...
with layout:
vuetify.VBtn("Exec", click=f"trigger('{ctrl.trigger_name(exec_function)}', [1, 2, 3], { b: 2 })")
.. function:: getRef(name)

Lookup a Vue.js reference within your template.

:param name: Name of the ref to lookup
:type name: str

:returns: The reference to vue component with that ref

.. function:: execAction(action)

This allow to call method or update a property on a given vue component using its ref.

The action object can only be one of the two structures:

.. code-block:: javascript
action = {ref, type: 'method', method, args}
action = {ref, type: 'property', property, value}
Variables available
---------------------------------------------------


.. js:data:: tts

tts stands for "Template Time Stamp" which represent an integer that will only change when a trame layout is getting updated.

.. js:data:: utils

This object aims to be editable by the user so custom helper functions could be used.
By default, we currently `the following content <client.utils.html>`_.
98 changes: 98 additions & 0 deletions docs/api/source/client.utils.rst
@@ -0,0 +1,98 @@
utils
===================================================

The **utils** namespace is aiming to gather user friendly methods. Trame by default provide a couple of useful ones listed below.

.. function:: utils.download(filename, contentOrPromise, type = 'application/octet-stream')

Trigger a file download within the browser.

:param filename: Name that the file should have on your disk once downloaded
:param contentOrPromise: File content or a promise which will return such content
:param type: Mime type of the file which may affect how your browser will deal with it.


.. code-block:: python
import time
from trame.app import get_server
from trame.ui.vuetify import SinglePageLayout
from trame.widgets import vuetify
# -----------------------------------------------------------------------------
# Trame setup
# -----------------------------------------------------------------------------
server = get_server()
state, ctrl = server.state, server.controller
@ctrl.trigger("generate_content")
def generate_content():
return f"Hello on the server is {time.time()}"
# -----------------------------------------------------------------------------
# UI setup
# -----------------------------------------------------------------------------
layout = SinglePageLayout(server)
with layout:
with layout.toolbar as toolbar:
toolbar.clear()
vuetify.VSpacer()
vuetify.VBtn(
"Download",
click="utils.download('hello.txt', trigger('generate_content'), 'text/plain')",
)
# -----------------------------------------------------------------------------
# start server
# -----------------------------------------------------------------------------
if __name__ == "__main__":
server.start()
.. function:: utils.get(path, obj = window)

This allow to lookup window nested JS path.

.. code-block:: python
# ...
with layout:
vuetify.VBtn("Print", click="utils.get('console.log')('hello')")
.. function:: utils.safe(obj)

Sometime JavaScript object don't preoperly serialize due to circular references or else.
That **safe** method will strip down anything that does not serialize in a transparent manner.
This method is mainly meant for debugging or exploration as ideally you should only try to exchange between the server and the client only what is really required.

.. function:: utils.vtk.event(event)

This decorator is to handle meaningful data extraction from an event of trame.widgets.vtk.Vtk{...}View into something that can be processed on the server side.

.. function:: utils.fmt.number(value, units=[], steps=1000, fixed=2)

This formatter helper let you reduce a number based on some more appropriate unit for human readability.

.. code-block:: javascript
console.log(utils.fmt.number(5.234, ['B1', 'B2', 'B3'], 123, 2))
// 5.23 B1
console.log(utils.fmt.number(5.234 * 123, ['B1', 'B2', 'B3'], 123, 2))
// 5.23 B2
console.log(utils.fmt.number(5.234 * 123 * 123, ['B1', 'B2', 'B3'], 123, 4))
// 5.2340 B3
.. function:: utils.fmt.bytes(value, fixed=2)

Convert the provided value into a string with Bytes units while keeping 2 fixed number behind the comma by default.

.. code-block:: javascript
console.log(utils.fmt.bytes(5.234 * 1024))
// 5.23 KB
7 changes: 7 additions & 0 deletions docs/api/source/index.rst
Expand Up @@ -19,6 +19,13 @@ Welcome to Trame's documentation!
trame.assets
trame.env

.. toctree::
:hidden:
:caption: Client API

client.intro
client.utils

.. toctree::
:hidden:
:caption: Core Classes
Expand Down

0 comments on commit 738565f

Please sign in to comment.