### Install Dependencies and Run Custom Dev Server
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/custom-components.md
Installs frontend dependencies and starts the development server with support for custom component templates. This command is used to develop custom templates locally.
```sh
cd ui
npm install
# "custom.dev" links templates in "custom_components/"
```
--------------------------------
### Run Streamsync Frontend Development Server
Source: https://github.com/ramedina86/streamsync/blob/master/CONTRIBUTING.md
Install frontend dependencies and start the Streamsync frontend in development mode. This command proxies requests to the backend running on port 5000.
```bash
npm run dev
```
--------------------------------
### Start Custom Development Server
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/custom-components.md
Starts the frontend development server for custom components. The backend is proxied to port 5000.
```bash
npm run custom.dev
```
--------------------------------
### Install Streamsync with Test or Build Extras
Source: https://github.com/ramedina86/streamsync/blob/master/CONTRIBUTING.md
Install Streamsync with the necessary extras for testing or building the project. This is a prerequisite for setting up a development environment.
```bash
pip install streamsync[test]
```
```bash
pip install streamsync[build]
```
--------------------------------
### Install Streamsync with Data Science Dependencies
Source: https://github.com/ramedina86/streamsync/blob/master/README.md
Installs Streamsync along with optional dependencies for data science tasks. This is the recommended installation command for users planning to leverage data science libraries.
```sh
pip install "streamsync[ds]"
streamsync hello
```
--------------------------------
### Create and Edit a Streamsync App for Testing
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/custom-components.md
Creates a new Streamsync application for testing custom components and starts the Streamsync server with the backend port specified.
```bash
streamsync create customtester
streamsync edit customtester --port 5000
```
--------------------------------
### Streamsync Application Structure
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/testing.md
Defines the basic structure of a Streamsync application, including initial state setup and an example event handler function.
```python
import streamsync as ss
def handle_multiplication(state):
state["n"] = state["a"]*state["b"]
ss.init_state({
"counter": 0,
"a": 0,
"b": 0
})
```
--------------------------------
### Install Streamsync in Editable Mode
Source: https://github.com/ramedina86/streamsync/blob/master/CONTRIBUTING.md
Install the Streamsync package in editable mode for convenient backend development. This allows for direct modifications to the backend code without reinstallation.
```bash
pip install -e .
```
--------------------------------
### Install StreamSync with Data Science Packages
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/index.md
Install StreamSync using pip, ensuring Python version 3.9.2 or higher. The `[ds]` extra installs common data science packages.
```sh
# Install via pip (requires Python >= 3.9.2)
pip install "streamsync[ds]"
```
--------------------------------
### Serve Multiple Streamsync Apps with FastAPI and Uvicorn
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/custom-server.md
This example demonstrates serving multiple Streamsync applications on different paths using FastAPI. It obtains individual ASGI apps for each Streamsync app and mounts them onto a main FastAPI application, which is then served by Uvicorn.
```python
import uvicorn
import streamsync.serve
from fastapi import FastAPI, Response
root_asgi_app = FastAPI()
sub_asgi_app_1 = streamsync.serve.get_asgi_app("../app1", "run")
sub_asgi_app_2 = streamsync.serve.get_asgi_app("../app2", "run")
root_asgi_app.mount("/app1", sub_asgi_app_1)
root_asgi_app.mount("/app2", sub_asgi_app_2)
@root_asgi_app.get("/")
async def init():
return Response("""
Welcome to the App Hub
""")
uvicorn.run(root_asgi_app,
host="0.0.0.0",
port=5328,
log_level="warning",
ws_max_size=streamsync.serve.MAX_WEBSOCKET_MESSAGE_SIZE)
```
--------------------------------
### Create, Edit, and Run Streamsync Application
Source: https://github.com/ramedina86/streamsync/blob/master/README.md
These commands are used to manage a Streamsync application. 'create' initializes a new app, 'edit' launches the visual editor, and 'run' starts the application.
```sh
streamsync create my_app
streamsync edit my_app
streamsync run my_app
```
--------------------------------
### Create a New StreamSync App
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/getting-started.md
Use the 'create' command to generate a new StreamSync application in a specified directory. The example shows creating an app in a folder named 'testapp'.
```sh
streamsync create [path]
# Creates a new app in folder "testapp"
streamsync create testapp
```
--------------------------------
### Implement Session Verifier Based on Headers
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/sessions.md
Use session verifiers to accept or deny a session based on request headers. This example denies sessions if the 'x-success' header is missing.
```python
import streamsync as ss
# Users without the header x-success will be denied the session
@ss.session_verifier
def check_headers(headers):
if headers.get("x-success") is None:
return False
return True
```
--------------------------------
### Dockerfile for Streamsync Application
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/deploy-with-docker.md
This Dockerfile provides a multistage build to create a lean Docker image for a Streamsync application. It installs dependencies, copies the application code, and sets up the entry point for running the application.
```docker
FROM python:3-slim AS compile-image
RUN apt-get update -y && mkdir /app && python3 -m venv /app/venv
ENV PATH="/app/venv/bin:$PATH"
COPY . /app
WORKDIR /app
RUN pip3 install streamsync && pip3 install -r requirements.txt
FROM python:3-slim AS run-image
RUN apt-get update -y && mkdir /app
COPY --from=compile-image /app /app
ENV PATH="/app/venv/bin:$PATH"
WORKDIR /app
ENTRYPOINT [ "streamsync", "run" ]
EXPOSE 5000
CMD [ ".", "--port", "5000", "--host", "0.0.0.0" ]
```
--------------------------------
### Import an ES6 Module During Initialisation
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/frontend-scripts.md
Import a frontend ES6 module when the application state is initialized. This ensures the module is available from the start.
```python
initial_state = ss.init_state({
"counter": 1
})
initial_state.import_frontend_module("my_script", "/static/mymodule.js")
```
--------------------------------
### Run Streamsync Editor on a Specific Port
Source: https://github.com/ramedina86/streamsync/blob/master/CONTRIBUTING.md
Start the Streamsync editor, specifying the port to run on. This is useful for managing multiple Streamsync instances or avoiding port conflicts.
```bash
streamsync edit hello --port 5000
```
--------------------------------
### Generate Core and Get Component Types
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/component-list.md
Initializes the StreamSync core and retrieves a list of all supported component types. This is a foundational step for accessing component definitions.
```javascript
import { generateCore } from "../../ui/src/core"
const ss = generateCore();
const types = ss.getSupportedComponentTypes();
```
--------------------------------
### Set Document Title During Loading
Source: https://github.com/ramedina86/streamsync/blob/master/ui/index.html
Sets the browser tab title to 'Loading...' when the application starts. This provides immediate feedback to the user.
```javascript
document.title = "Loading...";
```
--------------------------------
### Example ES6 Module with Exported Function
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/frontend-scripts.md
A standard ES6 module that exports a function. This function can be called from the backend after the module is imported.
```javascript
let i = 0;
export function sendAlert(personName) {
i++;
alert(`${personName}, you've been alerted. This is alert ${i}.`);
}
```
--------------------------------
### Backend-triggered Page Change
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/page-routes.md
Use the `set_page` method to change the current page from the backend based on certain conditions. This example switches pages based on the current hour.
```python
def handle_click(state):
from datetime import datetime
now = datetime.now()
if now.hour >= 18:
state.set_page("fun_work_page")
else:
state.set_page("work_work_page")
```
--------------------------------
### Set URL Route Variables from Backend
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/page-routes.md
Use the `set_route_vars` method to update URL parameters. Pass a dictionary to set values, or `None` to clear specific keys. This example sets `product_id` based on a state element.
```python
def change_route_vars(state):
state.set_route_vars({
"product_id": state["product"]
})
```
--------------------------------
### Pytest for Streamsync Application
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/testing.md
Provides example pytest test cases for a Streamsync application. It includes tests for initial state values and event handler logic using artificial states.
```python
from streamsync.core import StreamsyncState
import main
class TestApp:
initial_state = main.ss.initial_state
artificial_state = StreamsyncState({
"a": 3,
"b": 2
})
def test_counter_must_start_from_zero(self):
assert self.initial_state["counter"] == 0
def test_handle_multiplication(self):
main.handle_multiplication(self.artificial_state)
assert self.artificial_state["n"] == 6
```
--------------------------------
### Generate Core and Get Component Definitions
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/internal/internal.md
This script generates the core Streamsync instance, retrieves all supported component types, and then fetches the definition for each component. It collects details such as type, name, documentation, description, fields, events, and category.
```javascript
import { generateCore } from "../../../ui/src/core"
const ss = generateCore();
const types = ss.getSupportedComponentTypes();
const defs = types.map(type => {
const def = ss.getComponentDefinition(type);
return {
type,
name: def.name,
docs: def.docs,
description: def.description,
fields: def.fields,
events: def.events,
category: def.category
}
});
```
--------------------------------
### Target Component Types
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/stylesheets.md
Target all components of a specific type by using their root HTML element class. For example, '.CoreDataframe' targets all Dataframe components.
```css
.CoreDataframe {
line-height: 2.0;
}
```
--------------------------------
### Access Streamsync Frontend Core to Get User State
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/frontend-scripts.md
Access the Streamsync frontend core via `globalThis.core` to retrieve user state. This is an internal capability and may change.
```javascript
export function alertHueRotationValue() {
const state = globalThis.core.getUserState();
console.log("State is", state);
}
```
--------------------------------
### Retrieve Route Variables on Hash Change
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/page-routes.md
Handle the `ss-hashchange` event to monitor URL changes. The `payload` contains `route_vars`, which can be accessed to update state elements. This example retrieves `product_id`.
```python
def handle_hash_change(state, payload):
route_vars = payload.get("route_vars")
if not route_vars:
return
state["product"] = route_vars.get("product_id")
```
--------------------------------
### Initialize Nested Application State
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/application-state.md
Demonstrates how to set up nested state elements using dictionaries, allowing for hierarchical data structures within the application state.
```python
ss.init_state({
"counter": 0,
"my_app": {
"title": "Nested value"
}
})
```
--------------------------------
### Standard Output Logging
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/event-handlers.md
Shows how to use the standard 'print' function for logging messages, both on application startup and within event handlers.
```python
# Shown every time the app starts
print("Hello world")
def payload_inspector(state, payload):
# Shown every time the event handler is executed
print("Payload: " + repr(payload))
```
--------------------------------
### Import Stylesheet on Initialisation
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/stylesheets.md
Import a stylesheet for all users during initialisation by configuring the initial state. The CSS file should be placed in the /static folder.
```python
initial_state = ss.init_state({
"counter": 1
})
initial_state.import_stylesheet("theme", "/static/custom.css")
```
--------------------------------
### Pack and Initialize File and Bytes Data
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/application-state.md
Shows how to pack local files and raw bytes into data URLs for frontend use. This includes specifying MIME types for proper handling by the browser.
```python
import streamsync as ss
ss.init_state({
# Use a string to reference a filesystem path
"sales_spreadsheet": ss.pack_file("sales_spreadsheet.xlsx")
# Use any file-like object with a .read() method
"main_image": ss.pack_file(image_file, mime_type="image/jpeg"),
# Work with raw bytes
"my_bytes": ss.pack_bytes(b"\x31\x33\x33\x37", mime_type="text/plain"),
# Send raw bytes, without specifying a MIME type
"my_raw_bytes": b"\x31\x33\x33\x37"
})
```
--------------------------------
### Switch Stylesheets at Runtime
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/stylesheets.md
Implement theme logic by switching stylesheets during runtime. Specify the same 'stylesheet_key' in subsequent calls to change the applied theme.
```python
def handle_cyberpunk(state):
state.import_stylesheet("theme", "/static/cyberpunk_theme.css")
def handle_minimalist(state):
state.import_stylesheet("theme", "/static/minimalist_theme.css")
```
--------------------------------
### Build Docker Image
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/deploy-with-docker.md
Command to build a Docker image from the Dockerfile in the current directory. Replace 'my_streamsync_app' with your desired image tag.
```sh
docker build . -t my_streamsync_app
```
--------------------------------
### Initialize State and Handle Increment
Source: https://github.com/ramedina86/streamsync/blob/master/README.md
This snippet shows how to initialize the application's state with a counter and define an event handler to increment it. The UI template can then reference the state and trigger this handler.
```python
import streamsync as ss
def handle_increment(state):
state["counter"] += 1
ss.init_state({
"counter": 0
})
```
--------------------------------
### Build Custom Component Templates
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/custom-components.md
Builds only the custom component templates, generating output .js and .css files. This command is a subset of the main 'build' command.
```bash
# "build" builds the entire frontend
# "custom.build" only builds the custom templates
npm run custom.build
```
--------------------------------
### Serve a Single Streamsync App with Uvicorn
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/custom-server.md
This snippet shows how to serve a single Streamsync application using Uvicorn. It imports the necessary modules, specifies the app path and mode, retrieves the ASGI app, and configures Uvicorn with host, port, log level, and WebSocket message size.
```python
import uvicorn
import streamsync.serve
app_path = "." # . for current working directory
mode = "run" # run or edit
asgi_app = streamsync.serve.get_asgi_app(app_path, mode)
uvicorn.run(asgi_app,
host="0.0.0.0",
port=5328,
log_level="warning",
ws_max_size=streamsync.serve.MAX_WEBSOCKET_MESSAGE_SIZE)
```
--------------------------------
### Define a Simple Event Handler
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/introduction.md
This snippet shows how to define a Python function to handle UI events and initialize the application state.
```python
def handle_increment(state):
state["counter"] += 1
ss.init_state({
"counter": 0
})
```
--------------------------------
### Initialize Application State
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/application-state.md
Sets the initial application state for all sessions by copying the provided dictionary. Event handlers can then mutate this state independently for each session.
```python
import streamsync as ss
initial_state = ss.init_state({
"counter": 0,
})
# Event handler
# It receives the session state as an argument and mutates it
def increment(state):
state["counter"] += 1
```
--------------------------------
### Initialize State for Repeater
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/repeater.md
Sets up the initial state for the Repeater component, including a dictionary of articles and an empty order list. This state is used to populate the Repeater's content.
```python
ss.init_state({
"articles": {
"Banana": {
"type": "fruit",
"colour": "yellow"
},
"Lettuce": {
"type": "vegetable",
"colour": "green"
},
"Spinach": {
"type": "vegetable",
"colour": "green"
}
},
"order_list": []
})
```
--------------------------------
### Run StreamSync App with Custom Port and Host
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/getting-started.md
Specify a custom port and host when running your StreamSync application. Using '--host 0.0.0.0' allows sharing the application within your local network.
```sh
streamsync run my_app --port 5000 --host 0.0.0.0
```
--------------------------------
### Map Component Types to Definitions
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/component-list.md
Iterates through component types to fetch detailed definitions for each, including type, name, documentation, description, fields, events, and category. This prepares the data for display.
```javascript
const defs = types.map(type => {
const def = ss.getComponentDefinition(type);
return {
type,
name: def.name,
docs: def.docs,
description: def.description,
fields: def.fields,
events: def.events,
category: def.category
}
});
```
--------------------------------
### Run StreamSync as a Module
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/getting-started.md
Execute StreamSync as a module using the 'streamsync.command_line' module, which is useful for programmatic execution of StreamSync commands.
```sh
python -m streamsync.command_line run my_app
```
--------------------------------
### Run a StreamSync App
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/getting-started.md
Execute the 'run' command to make your StreamSync application available for others to use, but not edit. This command is used when your app is ready for deployment.
```sh
streamsync run my_app
```
--------------------------------
### Push Docker Image to Registry
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/deploy-with-docker.md
Commands to log in to Docker Hub and push a locally built Docker image to your Docker Hub repository. Ensure you replace 'my_streamsync_app' and 'my_user' with your specific details.
```sh
# Login to Docker Hub
docker login
# Push the image
# Replace "my_streamsync_app" for the tag you've previously chosen
# Replace "my_user" for your user on Docker Hub
docker tag my_streamsync_app:latest my_user/my_streamsync_app:latest
docker push my_user/my_streamsync_app:latest
```
--------------------------------
### Open URL
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/backend-initiated-actions.md
Open a URL in a new tab using `state.open_url`. Note that popup blockers may interfere with this action.
```python
def handle_open_streamsync_website(state):
state.open_url("https://streamsync.cloud")
```
--------------------------------
### Define Custom Component Entrypoint
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/custom-components.md
Imports and exports custom component templates from their respective files. This defines which components are available and under what identifiers.
```typescript
// Import the templates
import BubbleMessage from './BubbleMessage.vue';
import BubbleMessageAdvanced from './BubbleMessageAdvanced.vue';
// Export an object with the ids and the templates as default
export default {
"bubblemessage": BubbleMessage,
"bubblemessageadvanced": BubbleMessageAdvanced
}
```
--------------------------------
### Initialize State with Matplotlib Figure
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/application-state.md
Initializes the application state with a Matplotlib figure object. This figure will be automatically serialized to a PNG data URL for frontend display.
```python
ss.init_state({
"my_matplotlib_fig": fig,
})
```
--------------------------------
### Streamsync Loading Screen Layout
Source: https://github.com/ramedina86/streamsync/blob/master/ui/index.html
Styles the loading screen to occupy the full viewport height and centers its content. Includes font and color settings for loading text.
```css
#loading { height: 100vh; display: flex; align-items: center; justify-content: center; font-family: sans-serif; font-size: 0.9rem; flex-direction: column; color: #606060; }
```
--------------------------------
### Trigger File Download
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/backend-initiated-actions.md
Use `state.file_download` to trigger a file download in the user's browser. The data can be raw bytes or a packed file obtained using `ss.pack_file` or `ss.pack_bytes`.
```python
def handle_file_download(state):
# Pack the file as a FileWrapper object
data = ss.pack_file("assets/story.txt", "text/plain")
file_name = "thestory.txt"
state.file_download(data, file_name)
```
--------------------------------
### Import Stylesheet on Event
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/stylesheets.md
Import a stylesheet dynamically when an event is handled. The stylesheet key can be used to override it later. Ensure the CSS file is in the /static folder.
```python
def handle_click(state):
state.import_stylesheet("theme", "/static/custom.css")
```
--------------------------------
### Private Function Convention
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/event-handlers.md
Demonstrates how to define a function that should not be exposed to the frontend by prefixing its name with an underscore.
```python
# This function won't be visible in the frontend
# because its name starts with an underscore
def _reticulate(splines):
r_splines = np.random.normal(size=(splines,100))
return r_splines
```
--------------------------------
### Define Component Categories and Descriptions
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/component-list.md
An object mapping category keys to descriptive text, used to organize and explain the purpose of each component category.
```javascript
const categories = {
"Layout": "Components to organise the app's layout. Not meaningful by themselves; their objective is to enhance how other components are presented.",
"Content": "Components that present content and are meaningful by themselves. For example, charts, images or text.",
"Input": "Components whose main objective is to allow the user to input data into the app.",
"Other": "These components occupy a special role and are amongst the most powerful in the framework.",
"Root": "These components are the top-level containers."
};
```
--------------------------------
### Add Notifications
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/backend-initiated-actions.md
Display user notifications using `state.add_notification`. Supported types are 'error', 'warning', 'info', and 'success'.
```python
def notify_of_things_that_happened(state):
state.add_notification("error", "An Error", "Something bad happened.")
state.add_notification("warning", "A Warning", "Be aware that something happened.")
state.add_notification("info", "Some Info", "Something happened.")
state.add_notification("success", "A Success", "Something good happened.")
```
--------------------------------
### Run Docker Container
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/deploy-with-docker.md
Command to run a Docker container from a published image, mapping port 5000 from the container to the host machine. This allows access to the Streamsync application via localhost:5000.
```sh
docker run -p 5000:5000 my_user/my_streamsync_app
```
--------------------------------
### Using Globals for Resource-Intensive Objects
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/event-handlers.md
Demonstrates using a global variable to hold a resource-intensive object (AI model) for efficient reuse across event handler calls.
```python
my_ai = CatIdentifierAI()
def evaluate(state, payload):
result = my_ai.process(payload)
state["is_a_cat"] = result
```
--------------------------------
### Import a JavaScript Script During Initialisation
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/frontend-scripts.md
Import a standalone JavaScript script for its side effects during initialisation. This is useful for libraries not supporting ES6 modules.
```python
initial_state = ss.init_state({
"counter": 1
})
initial_state.import_script("my_script", "/static/script.js")
```
--------------------------------
### Import an ES6 Module During Event Handling
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/frontend-scripts.md
Import a frontend ES6 module using its key and path during an event. The module will be available for subsequent calls.
```python
def handle_click(state):
state.import_frontend_module("my_script", "/static/mymodule.js")
```
--------------------------------
### Call a Frontend Function from Backend
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/frontend-scripts.md
Trigger an exported function from an imported frontend module using its module key, function name, and arguments. Ensure the module is imported first.
```python
def handle_click(state):
state.call_frontend_function("mymodule", "sendAlert", ["Bob"])
```
--------------------------------
### Streamsync Loading Indicator Animations
Source: https://github.com/ramedina86/streamsync/blob/master/ui/index.html
Applies CSS animations to the top and bottom bars of the loading indicator for visual feedback during the loading process.
```css
#loading .logoTopBar { animation: logoAnimation 1s alternate infinite; }
#loading .logoBottomBar { animation: logoAnimation alternate-reverse 1s infinite; }
```
--------------------------------
### Fast Event Handler with State Mutations
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/event-handlers.md
This handler accumulates state mutations and sends them to the frontend after execution. Use for quick operations.
```python
def handle_fast(state):
state["text"] = "Hello"
state["x"] += 3
state["y"] += 2
```
--------------------------------
### Basic Python Event Handler
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/event-handlers.md
A simple Python function that can be used as an event handler. No special decorators are needed.
```python
# This event handler will add an entry to the log
def handle_click()
print("Hello")
```
--------------------------------
### Streamsync Loading Animation Keyframes
Source: https://github.com/ramedina86/streamsync/blob/master/ui/index.html
Defines the keyframes for the 'logoAnimation' used in the Streamsync loading indicator, controlling its movement and visual effect.
```css
@keyframes logoAnimation {
0% { x: 19.1875; y: 0; }
20% { x: 19.1875; y: 0; }
100% { x: 0; y: 45.3478; }
}
```
--------------------------------
### Streamsync Body and App Styles
Source: https://github.com/ramedina86/streamsync/blob/master/ui/index.html
Sets the default font for the body and defines isolation for the main application container.
```css
body { font-family: Inter, sans-serif; font-size: 13px; }
#app { isolation: isolate; }
```
--------------------------------
### Component Category Styling
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/component-list.md
CSS styles for the component list, defining the layout, appearance of category sections, component boxes, images, and text elements.
```css
.componentCategory .secondaryText {
color: #909090;
}
.componentCategory .boxContainer {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 16px;
margin-top: 16px;
}
.componentCategory .box {
border: 1px solid var(--vp-c-divider);
border-radius: 8px;
}
.componentCategory .box h3 {
margin: 16px;
font-size: 1rem;
font-weight: normal;
}
.componentCategory .box .imageContainer {
background: #E9EEF1;
border-top: 1px solid #E9EEF1;
border-bottom: 1px solid #E9EEF1;
width: 100%;
height: 160px;
overflow: hidden;
padding: 8px;
display: flex;
align-items: center;
justify-content: center;
}
.componentCategory .box .imageContainerInner {
display: flex;
align-items: flex-start;
max-height: 144px;
}
.componentCategory .box img {
max-height: 144px;
}
.componentCategory .box summary {
margin-bottom: 0;
}
.componentCategory .box .descriptionContainer {
padding: 16px;
}
```
--------------------------------
### Import a Script from a URL
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/frontend-scripts.md
Import a JavaScript script from a remote URL, such as a CDN. This is useful for including external libraries.
```python
initial_state = ss.init_state({
"my_app": {
"title": "My App"
},
})
initial_state.import_script("lodash", "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.js")
```
--------------------------------
### Edit an Existing StreamSync App
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/getting-started.md
Use the 'edit' command to open an existing StreamSync application in the visual editor. This command provides a local URL to access the editor.
```sh
streamsync edit [path]
# Edit the application in subfolder "testapp"
streamsync edit testapp
```
--------------------------------
### Streamsync Global CSS Styles
Source: https://github.com/ramedina86/streamsync/blob/master/ui/index.html
Applies global box-sizing, margin, padding, font-family, and color resets for the Streamsync UI. Ensures consistent rendering across elements.
```css
Streamsync * { box-sizing: border-box; margin: 0; padding: 0; font-family: inherit; color: currentColor; -webkit-font-smoothing: antialiased; }
```
--------------------------------
### Render Component Categories and Boxes
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/component-list.md
Vue.js template code that iterates through defined categories and component definitions to render a structured list of components, including their images and details.
```html
{{categoryKey}}
{{ categoryDesc}}
{{def.name}}
{{def.description}}
Fields
-
{{ field.name }}
: {{ field.type }}
· {{ Object.values(field.options ?? {}).join(" / ") }}
· {{ field.desc }}
Events
-
{{ eventId }} · {{ event.desc }}
```
--------------------------------
### Cleaner Mutation Detection
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/event-handlers.md
An alternative, cleaner approach to mutation detection that relies on assignment after direct mutation of a state element.
```python
def handle_click(state):
my_df = state["my_df"]
my_df.sample(frac=1, random_state=random.seed())
state["my_df"] = my_df # State assignmnet
```
--------------------------------
### Create Artificial State
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/testing.md
Use StreamsyncState to create a custom state object for testing purposes. Pass a dictionary to initialize its values.
```python
from streamsync.core import StreamsyncState
artificial_state = StreamsyncState({
"a": 3,
"b": 6
})
```
--------------------------------
### Handling Webcam Capture Payload
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/event-handlers.md
An event handler that processes the payload from a webcam capture event, saving the received image data to a file.
```python
def handle_webcam_capture(payload):
image_file = payload
with open(f"picture.png", "wb") as file_handle:
file_handle.write(image_file)
```
--------------------------------
### Apply Custom CSS Class with !important
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/stylesheets.md
Apply a custom CSS class to a component. Use the '!important' flag when targeting style attributes configurable via Builder to ensure your styles override built-in Streamsync styling.
```css
.bubblegum {
background: #ff63ca !important;
line-height: 1.5;
transform: rotate(-5deg);
}
/* Targeting an element inside the component root element */
.bubblegum > h2 {
color: #f9ff94 !important;
}
```
--------------------------------
### Mutation Detection via Assignment
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/event-handlers.md
Illustrates how Streamsync detects state mutations. Self-assignment is necessary when directly mutating an object within the state to ensure detection.
```python
def handle_click(state):
state["my_df"].sample(frac=1, random_state=random.seed())
# The self-assignment is necessary when mutating
# an existing object directly on state
state["my_df"] = state["my_df"]
```
--------------------------------
### Slow Event Handler with Periodic Updates
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/event-handlers.md
This handler performs a long-running task and provides partial updates. It includes a sleep to simulate a delay, updating the state before and after the delay.
```python
def handle_slowly(state):
state["message"] = "Loading..."
import time
time.sleep(5)
state["message"] = "Completed"
```
--------------------------------
### Python Event Handler for Input Change
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/handling-inputs.md
This Python function is designed to be used as an event handler. It takes the current application state and a payload from an input change event, then updates the 'name' element in the state with the received payload.
```python
def handle_input_change(state, payload):
state["name"] = payload
```
--------------------------------
### Identify Events Without Stubs
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/internal/internal.md
This function iterates through all component definitions and their events to identify which events are missing their corresponding stubs. It returns a list of objects, each indicating the component type, event type, and whether a stub is missing.
```javascript
function getEventsWithoutStub() {
const ews = [];
defs.filter(d => d.events).forEach(d =>
Object.entries(d.events).forEach(([eId, e]) => {
ews.push({ componentType: d.type, eventType: eId, missingStub: !e.stub });
})
);
return ews;
}
```
--------------------------------
### Access Session Information in Event Handlers
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/sessions.md
Access the session's unique ID, HTTP headers, and cookies from event handlers. The data is captured from the initial HTTP request.
```python
import streamsync as ss
# The following will output a dictionary
# with the session's id, cookies and headers.
def session_inspector(session):
print(repr(session))
```
--------------------------------
### Handling Event Payload for Text Input
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/event-handlers.md
An event handler that receives and uses the payload from a text input change event to update the application state.
```python
def handle_input_change(state, payload):
state["value"] = payload
```
--------------------------------
### Mutating Application State
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/event-handlers.md
An event handler that modifies the application state by incrementing a counter. State is accessed via the 'state' argument.
```python
def handle_click(state):
state["counter"] += 1
```
--------------------------------
### Python Recalculation Event Handler
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/handling-inputs.md
This Python function recalculates a value 'n' based on the state elements 'a', 'b', and 'c'. It's useful for triggering computations when bound input components change.
```python
def recalculate(state):
state["n"] = state["a"]*state["b"]*state["c"]
```
--------------------------------
### Repeater Event Handler to Add Item to List
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/repeater.md
An event handler function that adds the `itemId` from the Repeater's current context to the `order_list` in the state. This is typically linked to a button within the Repeater.
```python
# The event handler below adds the itemId
# of the relevant article to the order list
def handle_add_to_list(state, context):
state["order_list"] += [context["itemId"]]
```
--------------------------------
### Vue 3 Custom Component Template for Bubble Message
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/custom-components.md
Defines a 'Bubble Message' component with an editable 'text' field. This template is used to make the component available in Streamsync Builder and specifies its name, description, category, fields, and preview field.
```vue
```
--------------------------------
### Override Streamsync Style Variables
Source: https://github.com/ramedina86/streamsync/blob/master/docs/docs/stylesheets.md
Override Streamsync's style variables to customize component appearance. These variables are inherited by child components. Ensure the stylesheet is imported for immediate effect.
```css
.bubblegum {
--containerBackgroundColor: #ff63ca;
--primaryTextColor: #f9ff94;
line-height: 1.5;
transform: rotate(-5deg);
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.