### Initialize Multisynq Session with Multisynq.Session.join Source: https://multisynq.io/docs/client/tutorial-1_1_hello_world.html Illustrates how to launch a Multisynq application by joining a session using `Multisynq.Session.join`. It provides a JavaScript example for session initialization and details the required parameters, along with a step-by-step explanation of the session startup process. ```javascript Multisynq.Session.join({ apiKey: "your_api_key", appId: "io.codepen.multisynq.hello", name: "public", password: "none", model: MyModel, view: MyView }); ``` ```APIDOC Multisynq.Session.join({ apiKey, appId, name, password, model, view, options }) Description: This method is where the Multisynq application is actually launched. Parameters: apiKey: Your API key (required). appId: The application ID (e.g., "io.codepen.multisynq.hello"). name: The session name (e.g., "public"). password: The session password (e.g., "none"). model: The MyModel class reference. view: The MyView class reference. options: Any additional configuration options. Session Startup Process: 1. Connect to a nearby public synchronizer using the provided API key. 2. Instantiate the model. 3. a) Run the initialization code in the model's init routine, OR b) Initialize the model from a saved snapshot. 4. Instantiate the view, passing the view constructor a reference to the model. 5. Create a main event loop and begin executing. ``` -------------------------------- ### Create Multisynq Model Instance Source: https://multisynq.io/docs/client/Model.html Example demonstrating how to create a new instance of a Multisynq Model using the static `create()` method. This is the recommended way to instantiate models, rather than using `new`. ```JavaScript this.foo = FooModel.create({answer: 123}); ``` -------------------------------- ### JavaScript Examples for Basic Event Publishing Source: https://multisynq.io/docs/client/Model.html Provides basic JavaScript examples for publishing events with and without data using the `this.publish` method in a Multisynq model. ```JavaScript this.publish("something", "changed"); this.publish(this.id, "moved", this.pos); ``` -------------------------------- ### JavaScript Example for persistSession Method Source: https://multisynq.io/docs/client/Model.html Illustrates how to implement `persistSession` within a `SimpleAppRootModel` class, showing the `init` method for loading persisted data and the `save` method for calling `persistSession` with a versioned data structure for future migrations. ```JavaScript class SimpleAppRootModel { init(options, persisted) { ... // regular setup if (persisted) { if (persisted.version === 1) { ... // init from persisted data } } } save() { this.persistSession(() => { const data = { version: 1, // for future migrations ... // data to persist }; return data; }); } } ``` -------------------------------- ### Initialize Model Instance with init(options, persistentData) Source: https://multisynq.io/docs/client/Model.html Called during model instance creation to perform initial setup, such as subscribing to events or starting future message chains. Receives optional configuration `options` and `persistentData` from previous sessions, allowing for state restoration. ```APIDOC init(optionsopt, persistentDataopt) This is called by [create()](Model.html#.create) to initialize a model instance. Parameters: Name Type Attributes Description `options` Object if passed to [Session.join](Session.html#.join) `persistentData` Object data previously stored by [persistSession](Model.html#persistSession) ``` -------------------------------- ### JavaScript Example for Asynchronous Event Publishing Source: https://multisynq.io/docs/client/Model.html Demonstrates how to publish an event asynchronously using `this.future(0).publish` within a Multisynq model, ensuring the handler is called in a future message cycle. ```JavaScript this.future(0).publish("scope", "event", data); ``` -------------------------------- ### Integrate Multisynq Client Library Source: https://multisynq.io/docs/client/index.html This snippet demonstrates various methods to include the Multisynq client library into a web project. It covers direct CDN inclusion via HTML script tags for quick setup, ES module imports for modern JavaScript environments, and npm-based installations for bundler workflows, providing flexibility for different development setups. ```HTML ``` ```JavaScript import * as Multisynq from "https://cdn.jsdelivr.net/npm/@multisynq/client@1.0.4/bundled/multisynq-client.esm.js"; ``` ```Bash npm install @multisynq/client ``` ```JavaScript import * as Multisynq from "@multisynq/client" ``` -------------------------------- ### Join Multisynq Session with Auto Configuration Source: https://multisynq.io/docs/client/Session.html Example demonstrating how to join a Multisynq session using automatically generated session name and password (via URL arguments), and configuring a root model and view with basic session debugging enabled. ```JavaScript Multisynq.Session.join({ apiKey: "your_api_key", // paste from multisynq.io/coder appId: "com.example.myapp", // namespace for session names name: Multisynq.App.autoSession(), // session via URL arg password: Multisynq.App.autoPassword(), // password via URL arg model: MyRootModel, view: MyRootView, debug: ["session"] }); ``` -------------------------------- ### JavaScript Example: Registering a Multisynq Model Source: https://multisynq.io/docs/client/Model.html This JavaScript code snippet demonstrates how to define a new class that extends `Multisynq.Model` and then register it using the static `register` method. This registration is crucial for the Multisynq framework to properly manage and serialize model instances. ```JavaScript class MyModel extends Multisynq.Model { ... } MyModel.register("MyModel") ``` -------------------------------- ### MyView Constructor: Initial display update Source: https://multisynq.io/docs/client/tutorial-1_1_hello_world.html This call to `counterChanged()` immediately after subscription ensures that the displayed value matches the model's current count at the start of the session. Without it, the display would be incorrect until the first 'changed' event is received. ```JavaScript this.counterChanged(); ``` -------------------------------- ### JavaScript Example: Multisynq Model and View for User Presence Source: https://multisynq.io/docs/client/global.html Illustrates how to implement user presence tracking in a Multisynq application using `MyModel` and `MyView` classes. The model subscribes to 'view-join' and 'view-exit' events to manage user data, while the view handles custom 'user-added' and 'user-deleted' events for UI updates, demonstrating inter-component communication. ```JavaScript class MyModel extends Multisynq.Model { init() { this.userData = {}; this.subscribe(this.sessionId, "view-join", this.addUser); this.subscribe(this.sessionId, "view-exit", this.deleteUser); } addUser(viewId) { this.userData[viewId] = { start: this.now() }; this.publish(this.sessionId, "user-added", viewId); } deleteUser(viewId) { const time = this.now() - this.userData[viewId].start; delete this.userData[viewId]; this.publish(this.sessionId, "user-deleted", {viewId, time}); } } MyModel.register("MyModel"); class MyView extends Multisynq.View { constructor(model) { super(model); for (const viewId of Object.keys(model.userData)) this.userAdded(viewId); this.subscribe(this.sessionId, "user-added", this.userAdded); this.subscribe(this.sessionId, "user-deleted", this.userDeleted); } userAdded(viewId) { console.log(`${ this.viewId === viewId ? "local" : "remote"} user ${viewId} came in`); } userDeleted({viewId, time}) { console.log(`${ this.viewId === viewId ? "local" : "remote"} user ${viewId} left after ${time / 1000} seconds`); } } ``` -------------------------------- ### Join a Multisynq Session Source: https://multisynq.io/docs/client/index.html Demonstrates how to join a Multisynq session using `Multisynq.Session.join()`. This method automatically connects to a reflector, synchronizes the model, and starts execution. It requires session metadata such as an API key, application ID, session name, and password, along with the defined model and view classes. ```JavaScript const apiKey = "your_api_key"; // paste from multisynq.io/coder const appId = "com.example.myapp"; const name = Multisynq.App.autoSession(); const password = Multisynq.App.autoPassword(); Multisynq.Session.join({apiKey, appId, name, password, model: MyModel, view: MyView}); ``` -------------------------------- ### Define a Multisynq Model Class Source: https://multisynq.io/docs/client/index.html Illustrates the basic structure for defining a Multisynq application's model class, inheriting from `Multisynq.Model`. It uses an `init()` method instead of a constructor for initial setup, which executes only on the very first instantiation. The static `register()` method is mandatory for internal class registration. ```JavaScript class MyModel extends Multisynq.Model { init() { ... } } MyModel.register("MyModel"); ``` -------------------------------- ### Override Model Initialization Method Source: https://multisynq.io/docs/client/Model.html Illustrates how to override the `init()` method in a custom Multisynq Model class. This method is called only once when the model is first created in a session, allowing for initial property setup based on provided options. ```JavaScript class FooModel extends Multisynq.Model { init(options={}) { this.answer = options.answer || 42; } } ``` -------------------------------- ### Highlight Code with Prism.js on DOM Load Source: https://multisynq.io/docs/multisynq-react/index.html This JavaScript code ensures that all code blocks on the page are highlighted using the Prism.js library once the DOM content is fully loaded. This improves readability and presentation of code examples within the documentation. ```JavaScript document.addEventListener("DOMContentLoaded",(e=>{Prism.highlightAll()})) ``` -------------------------------- ### Log Events from Active Subscription Source: https://multisynq.io/docs/client/View.html An example method demonstrating how to access `scope`, `event`, and `source` from `this.activeSubscription` within a view's event handler. This allows logging detailed information about incoming events, useful for debugging and understanding event flow. ```JavaScript // this.subscribe("*", "*", this.logEvents) logEvents(data) { const {scope, event, source} = this.activeSubscription; console.log(`Event in view from ${source} ${scope}:${event} with`, data); } ``` -------------------------------- ### InMultisynqSession() API Reference Source: https://multisynq.io/docs/multisynq-react/global.html API documentation for the `InMultisynqSession` component, a wrapper that starts and manages a Multisynq session. It accepts parameters similar to `Session.join` and enables child elements to use Multisynq hooks. This component is deprecated; `MultisynqRoot` should be used instead. ```APIDOC InMultisynqSession(): Description: Main wrapper component that starts and manages a Multisynq session, enabling child elements to use the hooks described above. Parameters: Same as [Session.join](../client/Session.html#.join) (e.g., apiKey, appId, name, password, model). Deprecated: Use [MultisynqRoot](global.html#MultisynqRoot) instead. ``` -------------------------------- ### JavaScript: Lazy Initialization with wellKnownModel Source: https://multisynq.io/docs/client/Model.html This JavaScript example demonstrates how to use `wellKnownModel` within a static getter named `Default` for lazy initialization. It checks if a model named 'DefaultModel' already exists; if not, it creates a new `MyModel` instance, registers it with `beWellKnownAs`, and then returns it, ensuring a singleton-like pattern for the default model. ```JavaScript static get Default() { let default = this.wellKnownModel("DefaultModel"); if (!default) { console.log("Creating default") default = MyModel.create(); default.beWellKnownAs("DefaultModel"); } return default; } ``` -------------------------------- ### Wrap Application with InMultisynqSession Component Source: https://multisynq.io/docs/multisynq-react/global.html Example of using the `InMultisynqSession` React component as a wrapper to initiate and manage a Multisynq session for child elements. It accepts session parameters such as `apiKey`, `appId`, `name`, `password`, and a `model` for session configuration. Note: This component is deprecated in favor of `MultisynqRoot`. ```JavaScript function MyApp() { return ( // child elements that use hooks go here... ); } ``` -------------------------------- ### Define Custom Serialization for Non-Model Classes Source: https://multisynq.io/docs/client/Model.html This example demonstrates how to implement custom `write` and `read` functions for non-model classes, allowing fine-grained control over their serialization and deserialization process. It also shows how to handle static properties using `writeStatic` and `readStatic`. This is useful for optimizing serialization size (e.g., converting a Vector3 to an array) or handling complex object structures that require specific conversion logic. ```javascript class MyModel extends Multisynq.Model { static types() { return { "SomeUniqueName": { cls: MyNonModelClass, write: obj => obj.serialize(), // answer a serializable type, see above read: state => MyNonModelClass.deserialize(state), // answer a new instance writeStatic: () => ({foo: MyNonModelClass.foo}), readStatic: state => MyNonModelClass.foo = state.foo }, "THREE.Vector3": { cls: THREE.Vector3, write: v => [v.x, v.y, v.z], // serialized as '[...,...,...]' which is shorter than the default above read: v => new THREE.Vector3(v[0], v[1], v[2]) }, "THREE.Color": { cls: THREE.Color, write: color => '#' + color.getHexString(), read: state => new THREE.Color(state) } }; } } ``` -------------------------------- ### Multisynq Client Library API Overview Source: https://multisynq.io/docs/client/tutorial-1_1_hello_world.html This section outlines the main components of the Multisynq client library's API, including core classes for model, session, and view management, key events for synchronization, and global constants. It serves as a high-level index to the library's capabilities. ```APIDOC Classes: - Model - Session - View Events: - synced - view-exit - view-join Global: - Constants ``` -------------------------------- ### Include Multisynq Client Library in HTML Source: https://multisynq.io/docs/client/tutorial-1_1_hello_world.html This HTML script tag demonstrates how to asynchronously load the Multisynq client library into a web application. It specifies the CDN URL for version 1.0.4 of the library, making its functionalities available globally in the JavaScript environment. ```HTML ``` -------------------------------- ### APIDOC: viewId Property and Subscription Example Source: https://multisynq.io/docs/client/View.html Defines the `viewId` property, which uniquely identifies the current user's View and their connection to the server. It scopes local events like 'synced' and is distinct from `this.id`. The accompanying JavaScript example demonstrates how to subscribe to a 'synced' event using `this.viewId`. ```APIDOC viewId: String ``` ```JavaScript this.subscribe(this.viewId, "synced", this.handleSynced); ``` -------------------------------- ### Multisynq Model Core API Concepts Source: https://multisynq.io/docs/client/tutorial-1_1_hello_world.html This section details key API concepts for developing Multisynq models, including the base `Multisynq.Model` class, the `init()` lifecycle method, the `subscribe()` method for inter-component communication, the `future()` method for time-based event scheduling, and the `publish()` method for sending messages. It also covers model registration. ```APIDOC Multisynq.Model: Base class for all Multisynq application models. Provides core functionality for state replication and synchronization. MyModel.init(): Purpose: Initializes the model's state. Called automatically once when a session first begins. Parameters: None Behavior: - Sets initial property values (e.g., this.count = 0). - Establishes subscriptions to view events (e.g., this.subscribe("scope", "event", handler)). - Schedules initial time-based events (e.g., this.future(delay).method()). this.subscribe(scope: string, event: string, handler: function): Purpose: Subscribes the model to specific events published by the view or other model components. Parameters: - scope (string): The category or context of the event. - event (string): The specific event name. - handler (function): The model method to execute when the event is received. Example: this.subscribe("counter", "reset", this.resetCounter); this.future(delay_ms: number).method(): Purpose: Schedules a model method to be executed after a specified delay in milliseconds. Parameters: - delay_ms (number): The delay in milliseconds before the method is called. Returns: A proxy object allowing chaining to the method to be called. Example: this.future(1000).tick(); this.publish(scope: string, event: string): Purpose: Publishes an event from the model, typically to notify the view of state changes. Parameters: - scope (string): The category or context of the event. - event (string): The specific event name. Example: this.publish("counter", "changed"); MyModel.register(model_name: string): Purpose: Registers the model class with the Multisynq system, making it available for instantiation. Parameters: - model_name (string): The string name by which the model will be identified. Example: MyModel.register("MyModel"); ``` -------------------------------- ### Multisynq Counter Application Model (JavaScript) Source: https://multisynq.io/docs/client/tutorial-1_1_hello_world.html This JavaScript class defines the model for a simple 'Hello World' counter application. It extends `Multisynq.Model` to leverage Multisynq's replication capabilities. The model manages a `count` property, subscribes to 'reset' events from the view, and uses `future` calls to increment the counter every second, publishing 'changed' events to notify the view. ```JavaScript class MyModel extends Multisynq.Model { init() { this.count = 0; this.subscribe("counter", "reset", this.resetCounter); this.future(1000).tick(); } resetCounter() { this.count = 0; this.publish("counter", "changed"); } tick() { this.count++; this.publish("counter", "changed"); this.future(1000).tick(); } } MyModel.register("MyModel"); ``` -------------------------------- ### Multisynq: Registering a new Model subclass Source: https://multisynq.io/docs/client/tutorial-1_1_hello_world.html Every new model subclass defined within Multisynq must be registered. This step is crucial for the framework to recognize the model and properly manage its instances and synchronization across users. ```JavaScript MyModel.register("MyModel"); ``` -------------------------------- ### useSessionId Hook for Current Session ID Source: https://multisynq.io/docs/multisynq-react/global.html Hook that returns the ID of the current Multisynq session. It provides a quick way to get the unique identifier for the active session, returning null if no session is active. ```APIDOC useSessionId() → string | null Description: Hook that returns the ID of the current Multisynq session. Returns: string | null - The ID of the current session, or null if not in a session. ``` ```typescript const sessionId = useSessionId(); console.log(sessionId ? `Current session: ${sessionId}` : 'Not in a session'); ``` -------------------------------- ### Multisynq API Reference: Classes, Events, and Tutorials Source: https://multisynq.io/docs/client/Session.html This section provides an overview of the Multisynq API, detailing key classes such as Model, Session, and View, along with important events like 'synced', 'view-exit', and 'view-join'. It also lists available tutorials covering various aspects of Multisynq application development, from basic 'Hello World' to advanced topics like 'Simulation Time' and 'Persistence API'. ```APIDOC Classes Model Session View Events synced view-exit view-join Tutorials đŸ’ģ Hello World đŸ’ģ Simple Animation đŸ’ģ Multiuser Chat đŸ’ģ View Smoothing đŸ’ģ 3D Animation đŸ•šī¸ Multiblaster 💡 Model-View-Synchronizer 💡 Writing a Multisynq Application 💡 Writing a Multisynq View 💡 Writing a Multisynq Model 💡 Simulation Time and Future Sends 💡 Events & Publish/Subscribe 💡 Snapshots 💡 Randomness & Determinism 💡 Data API 💡 Persistence API Global Constants ``` -------------------------------- ### MyView: Multisynq View Class Definition Source: https://multisynq.io/docs/client/tutorial-1_1_hello_world.html This is the complete implementation of the `MyView` class, which extends `Multisynq.View`. It's responsible for rendering the model's state to the user interface and capturing user input to publish events back to the model. It handles subscriptions to model changes and updates the display accordingly. ```JavaScript class MyView extends Multisynq.View { constructor(model) { super(model); this.model = model; countDisplay.onclick = event => this.counterReset(); this.subscribe("counter", "changed", this.counterChanged); this.counterChanged(); } counterReset() { this.publish("counter", "reset"); } counterChanged() { countDisplay.textContent = this.model.count; } } ``` -------------------------------- ### Hook to Get Joined View Information Source: https://multisynq.io/docs/multisynq-react/global.html Provides an object containing comprehensive information about all views currently joined to the Multisynq session. This includes view IDs, detailed view information, and the total count of joined views. ```javascript const { viewIds, viewCount } = useJoinedViews(); console.log(`There are ${viewCount} views joined to the session.`); console.log('View IDs:', views.join(", ")); ``` ```APIDOC useJoinedViews(): Object Returns: An object containing information about joined views. viewIds: string[] - An array of all the joined view ids. viewInfos: { [viewId: string]: ViewInfo} - An object with the joined view ids as keys and the ViewInfo objects as values. viewCount: number - The total number of views currently joined to the session. views: string[] - Deprecated. An alias for viewIds. This property will be removed in the next major release. ``` -------------------------------- ### Join Multisynq Session and Integrate with XR Animation Frame Source: https://multisynq.io/docs/client/Session.html This JavaScript snippet demonstrates how to initialize a Multisynq session using `Multisynq.Session.join` with various configuration options like API key, app ID, and model/view references. It then integrates the session's `step` method into an `xrSession.requestAnimationFrame` loop, essential for real-time updates in XR environments. The `...` indicates omitted code for brevity. ```JavaScript Multisynq.Session.join({ apiKey: "your_api_key", appId: "com.example.myapp", name: "abc", password: "password", model: MyRootModel, view: MyRootView, step: "manual"}).then(session => { function xrAnimFrame(time, xrFrame) { session.step(time); ... xrSession.requestAnimationFrame(xrAnimFrame); } xrSession.requestAnimationFrame(xrAnimFrame); }); ``` -------------------------------- ### Import React and Multisynq Dependencies Source: https://multisynq.io/docs/multisynq-react/tutorial-1_React_Simple_Counter.html Imports necessary modules for a React application using Multisynq. This includes `ReactDOM` for rendering the React application, `React` itself, and specific components/hooks from the `@multisynq/react` package such as `useReactModelRoot`, `MultisynqRoot`, and `ReactModel`. ```JavaScript import ReactDOM from "react-dom/client"; import React from "react"; import { useReactModelRoot, MultisynqRoot, ReactModel, } from "@multisynq/react"; ``` -------------------------------- ### Publish Event Using Model ID as Scope Source: https://multisynq.io/docs/client/Model.html Example showing how to use the `id` property of a Multisynq Model as the scope when publishing an event. The `id` is unique within a session and ensures events are scoped to a specific model instance. ```JavaScript this.publish(this.id, "changed"); ``` -------------------------------- ### Define CounterApp React Component Source: https://multisynq.io/docs/multisynq-react/tutorial-1_React_Simple_Counter.html Defines the main `CounterApp` React component, serving as the top-level application entry point. It wraps the application logic within `MultisynqRoot`, configuring the Multisynq session with necessary parameters like API key, app ID, password, name, and the `CounterModel` itself. It then renders a `CounterDisplay` component as its child. ```JavaScript function CounterApp() { return ( ); } ``` -------------------------------- ### Hook to Get Root Model Instance Source: https://multisynq.io/docs/multisynq-react/global.html Returns a reference to the root Model instance of the current Multisynq session. Similar to `useModelById`, this hook does not cause re-renders on model data changes; `useReactModelRoot` or `useModelSelector` should be used for reactive updates. ```javascript const rootModel = useModelRoot(); if (rootModel) { console.log(rootModel.gameState); } ``` ```APIDOC useModelRoot(): M | null Returns: The root Model instance if available, or null if not. ``` -------------------------------- ### MyView: Publish 'reset' event from user input Source: https://multisynq.io/docs/client/tutorial-1_1_hello_world.html In response to user interaction (e.g., a click), the view publishes a 'reset' event in the 'counter' scope. This event is then subscribed to by the model, allowing the view to influence the model's behavior in a synchronized and deterministic manner across all Multisynq instances. ```JavaScript this.publish("counter", "reset"); ``` -------------------------------- ### MyView Constructor: Call base class constructor Source: https://multisynq.io/docs/client/tutorial-1_1_hello_world.html Within the `MyView` constructor, `super(model)` ensures that the constructor of the base class, `Multisynq.View`, is properly executed. This is a standard practice for subclassing in JavaScript. ```JavaScript super(model); ``` -------------------------------- ### Multisynq View Class API Reference Source: https://multisynq.io/docs/client/View.html Comprehensive API documentation for the `Multisynq.View` class, detailing its constructor, properties, and their usage within a Multisynq application. This section outlines how to instantiate a View, its key attributes, and their purpose. ```APIDOC Class: View Description: Views are the local, non-synchronized part of a Multisynq Application. Each device and browser window creates its own independent local view. The view subscribes to events published by the synchronized model, so it stays up to date in real time. Constructor: new View(model, viewOptionsnullable) Description: A View instance is created in Session.join, and the root model is passed into its constructor. This inherited constructor does not use the model in any way. Your constructor should recreate the view state to exactly match what is in the model. It should also subscribe to any changes published by the model. Typically, a view would also subscribe to the browser's or framework's input events, and in response publish events for the model to consume. The constructor will, however, register the view and assign it an id. Parameters: model: Type: Model Description: the view's model viewOptions: Type: Object Attributes: nullable Description: if viewOptions where given in Session.join Members: activeSubscription: Type: Object Description: Scope, event, and source of the currently executing subscription handler. Since: 2.0 id: Type: String Description: Each view has an id which can be used to scope events between views. It is unique within the session for each user. The id is NOT currently guaranteed to be unique for different users. Views on multiple devices may or may not be given the same id. This property is read-only. It is assigned in the view's constructor. There will be an error if you try to assign to it. session: Type: Object | undefined Description: The session object. Same as returned by Session.join. WILL BE UNDEFINED WHEN DISCONNECTED! In callbacks that can still be executed after a disconnect, you should check if (!this.session) return to avoid errors. ``` -------------------------------- ### MyView Constructor: Handle click event Source: https://multisynq.io/docs/client/tutorial-1_1_hello_world.html This line attaches an `onclick` event listener to the `countDisplay` HTML element. When the element is clicked, it triggers the `counterReset()` method of the view, initiating a reset action. ```JavaScript countDisplay.onclick = event => this.counterReset(); ``` -------------------------------- ### Hook to Get Model Instance by ID Source: https://multisynq.io/docs/multisynq-react/global.html Returns a reference to a specific Model instance identified by its ID. It's important to note that this hook does not trigger React re-renders when the model's data changes; for reactive behavior, use `useReactModelRoot` or `useModelSelector`. ```javascript const userModel = useModelById('user-123'); if (userModel) { console.log(userModel.name); } ``` ```APIDOC useModelById(id: string): M | null Parameters: id: The id of the Model to retrieve. Returns: The model instance with the given id. Returns null if not currently joined to any session, or if an image with the given id was not found ``` -------------------------------- ### Get Current Model Time with now() Source: https://multisynq.io/docs/client/Model.html Returns the model's current virtual time in milliseconds. Time in Multisynq is discrete and advances in steps, ensuring synchronized computation across devices. The value is a floating-point number representing milliseconds since the session's creation. ```APIDOC now() → {Number} The model's current time Returns: the model's time in milliseconds since the first user created the session. Type: Number ``` -------------------------------- ### Multisynq.App.join Method Documentation Source: https://multisynq.io/docs/client/Session.html Documents the `join` method for Multisynq sessions, including its purpose, detailed parameter descriptions, session ID generation logic, and the three phases of the Multisynq main loop. ```APIDOC Method: (async, static) join(parameters) → {Promise} Description: Join a Multisynq session. Joins a session by instantiating the root model (for a new session) or resuming from a snapshot, then constructs the view root instance. Parameters: parameters: Object Detailed Parameter Descriptions: appId: string Description: Identifies each Multisynq app. It must be a globally unique identifier following the Android convention, e.g. "com.example.myapp". Each dot-separated segment must start with a letter, and only letters, digits, and underscores are allowed. name: string Description: Identifies individual sessions within an app. You can use it for example to create different sessions for different users. One simple way to create unique sessions is via `Multisynq.App.autoSession()` which will use or generate a random name in the query part (`?...`) of the current url. password: string Description: Used for end-to-end encryption of all data leaving the client. If your app does not need to protect user data, you will still have to provide a constant dummy password. One simple way to have individual passwords is via `Multisynq.App.autoPassword()` which will use or generate a random password in the hash part (`#...`) of the current url. Session ID and Model Initialization: A session id is created from the given session `name` and `options`, and a hash of all the registered Model classes and Constants. This ensures that only users running the exact same source code end up in the same session, which is a prerequisite for perfectly synchronized computation. The session id is used to connect to a reflector. If there is no ongoing session, an instance of the `model` class is created (which in turn typically creates a number of submodels). Otherwise, the previously stored `modelRoot` is deserialized from the snapshot, along with all additional models. That root model instance is passed to the constructor of your root `view` class. The root view should set up the input and output operations of your application, and create any additional views as to match the application state as found in the models. Multisynq Main Loop: The Multisynq main loop is started (unless you pass in a `step: "manual"` parameter). This uses `requestAnimationFrame()` for continuous updating. Each step of the main loop executes in three phases: 1. Simulation: The models execute the events received via the reflector, and the future messages up to the latest time stamp received from the reflector. The events generated in this phase are put in a queue for the views to consume. 2. Event Processing: The queued events are processed by calling the view's event handlers. The views typically use these events to modify some view state, e.g. moving a DOM element or setting some attribute of a Three.js object. 3. Updating/Rendering: The view root's update() method is called after all the queued events have been processed. In some applications, the update method will do nothing (e.g. DOM elements are rendered after returning control to the browser). When using other UI frameworks (e.g. Three.js), this is the place to perform the actual rendering. Also, polling input and other tasks that should happen in every frame should be placed here. ``` -------------------------------- ### Declare Non-Model Class Types with Default Serialization Source: https://multisynq.io/docs/client/Model.html This example shows how to register non-model classes for serialization using the default serializer. By simply providing the class reference, Multisynq will automatically handle the serialization of its fields. This is suitable for classes where a direct field-to-JSON conversion is sufficient, such as simple data structures or third-party library objects like `THREE.Vector3`. ```javascript class MyModel extends Multisynq.Model { static types() { return { "SomeUniqueName": MyNonModelClass, "THREE.Vector3": THREE.Vector3, // serialized as '{"x":...,"y":...,"z":...}' "THREE.Quaternion": THREE.Quaternion }; } } ``` -------------------------------- ### Initialize SimplePageView Component with API Key Source: https://multisynq.io/scroll This JavaScript snippet demonstrates how to initialize the `SimplePageView` component. It requires an `apiKey` to authenticate and connect to the Multisynq service, enabling tracking or interaction functionalities within a web application. ```JavaScript SimplePageView.start({ apiKey: "2d0fPrsWoWQFrelRWB1TftMoNJLfOk4Ni6XkQvswX3", }); ``` -------------------------------- ### Initialize Tocbot and Prism.js for Page Content Source: https://multisynq.io/docs/client/Session.html This JavaScript snippet initializes `tocbot` for generating a table of contents based on heading elements within the `.main-content` area. It configures `tocbot` with specific selectors and offsets. Additionally, it ensures that `Prism.highlightAll()` is called once the DOM content is fully loaded, enabling syntax highlighting for all code blocks on the page. ```JavaScript var tocbotInstance=tocbot.init({tocSelector:"#eed4d2a0bfd64539bb9df78095dec881",contentSelector:".main-content",headingSelector:"h1, h2, h3",hasInnerContainers:!0,scrollContainer:".main-content",headingsOffset:130,onClick:bringLinkToView})var tocbotInstance=tocbot.init({tocSelector:"#eed4d2a0bfd64539bb9df78095dec881",contentSelector:".main-content",headingSelector:"h1, h2, h3",hasInnerContainers:!0,scrollContainer:".main-content",headingsOffset:130,onClick:bringLinkToView})document.addEventListener("DOMContentLoaded",(e=>{Prism.highlightAll()})) ``` -------------------------------- ### Multisynq Global Hooks and Functions Reference Source: https://multisynq.io/docs/multisynq-react/tutorial-1_React_Simple_Counter.html A comprehensive list of global hooks and functions provided by the Multisynq library, designed for managing sessions, models, and views in collaborative React applications. ```APIDOC function InMultisynqSession() function MultisynqContext() function MultisynqRoot() function createMultisynqSession() function useConnectedViews() function useDetachCallback() function useIsJoined() function useJoinedViews() function useLeaveSession() function useModelById() function useModelRoot() function useModelSelector() function useMultisynqSession() function useMultisynqView() function usePublish() function useReactModelRoot() function useSession() function useSessionId() function useSessionParams() function useSetSession() function useSubscribe() function useSyncedCallback() function useUpdateCallback() function useView() function useViewId() ``` -------------------------------- ### Multisynq Global API Reference Source: https://multisynq.io/docs/multisynq-react/tutorial-1_React_Simple_Counter.html This section provides a reference to global functions, components, and hooks exposed by the Multisynq library, primarily for React integration. These elements facilitate session management, model interaction, and view synchronization within Multisynq applications. ```APIDOC Classes: ReactModel Global: InMultisynqSession MultisynqContext MultisynqRoot createMultisynqSession useConnectedViews useDetachCallback useIsJoined useJoinedViews useLeaveSession useModelById useModelRoot useModelSelector useMultisynqSession useMultisynqView usePublish useReactModelRoot useSession useSessionId useSessionParams useSetSession useSubscribe useSyncedCallback useUpdateCallback useView useViewId ``` -------------------------------- ### Multisynq Core API Components Overview Source: https://multisynq.io/docs/client/index.html This section provides an overview of the main programmatic interfaces available in the Multisynq library. It lists key classes, events, and global constants that form the foundation for building synchronized real-time applications, serving as a quick reference to the library's core API elements. ```APIDOC Classes: - Model - Session - View Events: - synced - view-exit - view-join Global: - Constants ``` -------------------------------- ### Multisynq Model Class API Reference Source: https://multisynq.io/docs/client/Model.html Comprehensive API documentation for the Multisynq `Model` class, detailing its purpose as a synchronized object, instance creation guidelines, available members, and key methods for managing state and events across a session. ```APIDOC Class: Model Description: Models are synchronized objects in Multisynq. They are automatically kept in sync for each user in the same session. Models receive input by subscribing to events published in a View. Their output is handled by views subscribing to events published by a model. Models advance time by sending messages into their future. Instance Creation and Initialization: - Do NOT create a Model instance using `new` and do NOT override the `constructor`. - To create a new instance, use `Model.create()`. - To initialize an instance, override `init()`. Members: - activeSubscription: object Description: Scope, event, and source of the currently executing subscription handler. The `source` is either "model" or "view". Type: {scope: string, event: string, source: "model" | "view"} Since: 2.0 - id: String (read-only) Description: Unique identifier for the model within the session, used for event scoping. Assigned in `Model.create()` before `init()`. - sessionId: String Description: Identifies the shared session of all users. Used as a global scope for events like "view-join". - viewCount: Number Description: The number of users currently in this session (number of views sharing this model). Increased before "view-join" and decreased before "view-exit" events. Methods: - create(): Model Description: Static method to create a new Model instance. (e.g., `FooModel.create({answer: 123})`) - init(options: object): void Description: Method to override for instance initialization. Called only once when the object first comes into existence in the session. (e.g., `init(options={}) { this.answer = options.answer || 42; }`) - publish(scope: string, event: string, data: any): void Description: Publishes an event from the model. - subscribe(scope: string, event: string, handler: Function): void Description: Subscribes the model to events. - future(delay: number, callback: Function): void Description: Advances time by sending messages into the model's future. ```