### Minimal Hello World example Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/guide/introduction/installation.md A basic HTML and JavaScript example to verify that js-toolkit is installed and working correctly. This includes setting up a component with a reference and an event handler. ```html
``` ```javascript // main.js import { Base, registerComponent } from '@studiometa/js-toolkit'; class Hello extends Base { static config = { name: 'Hello', refs: ['btn'], }; onBtnClick() { alert('Hello, world!'); } } registerComponent(Hello); ``` -------------------------------- ### Initialize JS Toolkit App Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/helpers/createApp.md Import and use the createApp helper to initialize your application. This example shows the basic setup for creating and mounting your root App class. ```javascript import { createApp } from '@studiometa/js-toolkit'; import App from './App.js'; const useApp = createApp(App); useApp().then((app) => console.log(app)); ``` -------------------------------- ### Basic App Setup with SyncedInput Component Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/decorators/withGroup.md This snippet shows a basic application setup using the Studiometa JS Toolkit, importing and registering the SyncedInput component. It demonstrates how to initialize the application with components. ```javascript import { Base, createApp } from '@studiometa/js-toolkit'; import { SyncedInput } from './SyncedInput.js'; class App extends Base { static config = { name: 'App', components: { SyncedInput, }, }; } export default createApp(App); ``` -------------------------------- ### Cookie Storage Provider Example Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/storage/providers.md This example demonstrates how to create a custom storage provider using cookies. It includes methods for getting, setting, removing, checking existence, listing keys, and clearing all cookies. ```typescript import { createStorage } from '@studiometa/js-toolkit/utils'; import type { StorageProvider } from '@studiometa/js-toolkit/utils'; const cookieProvider: StorageProvider = { // Optional: DOM event name for external sync syncEvent: undefined, get(key: string): string | null { const match = document.cookie.match(new RegExp(`(?:^|; )${key}=([^;]*)`)); return match ? decodeURIComponent(match[1]) : null; }, set(key: string, value: string): void { document.cookie = `${key}=${encodeURIComponent(value)}; path=/`; }, remove(key: string): void { document.cookie = `${key}=; path=/; max-age=0`; }, has(key: string): boolean { return this.get(key) !== null; }, keys(): string[] { return document.cookie .split('; ') .filter(Boolean) .map((c) => c.split('=')[0]); }, clear(): void { for (const key of this.keys()) { this.remove(key); } }, }; const storage = createStorage({ provider: cookieProvider }); ``` -------------------------------- ### Install js-toolkit via NPM Source: https://github.com/studiometa/js-toolkit/blob/main/README.md Install the latest version of the js-toolkit package using NPM. This is the standard method for adding the framework to your project. ```bash npm install @studiometa/js-toolkit ``` -------------------------------- ### Get First and All Component Instances Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/helpers/queryComponent.md Use queryComponent to retrieve the first matching component instance and queryComponentAll to get all matching instances. Both functions accept the component's configuration name as an argument. ```javascript import { queryComponent, queryComponentAll } from '@studiometa/js-toolkit'; // Get the first instance of component with `config.name === 'Foo'` const foo = queryComponent('Foo'); // Get all instances of component with `config.name === 'Foo'` const allFoos = queryComponentAll('Foo'); ``` -------------------------------- ### Getting a list of available hooks Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/methods-hooks-events.md Provides an example of how to retrieve an array of all available hook names using the `hooks` getter. This helps in understanding the extension points of the API. ```javascript const availableHooks = api.hooks; console.log('Available hooks:', availableHooks); ``` -------------------------------- ### Install ESLint Plugin Source: https://github.com/studiometa/js-toolkit/blob/main/README.md Install the ESLint plugin for JS Toolkit to enforce best practices. This command should be run in your project's development environment. ```bash npm install --save-dev @studiometa/eslint-plugin-js-toolkit ``` -------------------------------- ### Basic CSS Transition Example Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/css/transition.md Demonstrates how to apply a CSS transition to an element. Ensure the element has a transition property defined in its CSS. ```javascript import { transition } from "@studiometa/js-toolkit/utils"; const element = document.querySelector('.my-element'); transition(element, { duration: 300, delay: 100, easing: 'ease-in-out', css: true, enter: true, leave: true, }); ``` -------------------------------- ### EaseInCirc Example Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/math/ease.md Demonstrates the usage of the easeInCirc function with various progress values. ```javascript easeInCirc(0); // 0 easeInCirc(0.25); // 0.031754163448145745 easeInCirc(0.5); // 0.1339745962155614 easeInCirc(0.55); // 0.16483534557549673 easeInCirc(0.9); // 0.5641101056459328 easeInCirc(0.95); // 0.6877501000800801 easeInCirc(0.99); // 0.858932640203341 easeInCirc(1); // 1 ``` -------------------------------- ### Basic damping example Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/math/smoothTo.md Demonstrates how to use smoothTo to animate a value and subscribe to its updates. The transition starts from 0 and moves towards 300, with a damping factor of 0.1. The subscribe callback updates an element's transform style. ```javascript import { smoothTo } from '@studiometa/js-toolkit/utils'; const position = smoothTo(0, { damping: 0.1 }); position.subscribe((value) => { // Called on each frame during the transition element.style.transform = `translateX(${value}px)`; }); // Start transition to 300 position(300); ``` -------------------------------- ### Basic useScheduler Example Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/useScheduler.md Demonstrates how to use useScheduler to define 'before' and 'after' steps and schedule tasks. Tasks within the same step are executed in the order they are added. ```javascript import { useScheduler } from '@studiometa/js-toolkit/utils'; const { before, after } = useScheduler(['before', 'after']); after(() => console.log('after')); before(() => console.log('before')); before(() => console.log('before')); after(() => console.log('after')); // Will output: // before // before // after // after ``` -------------------------------- ### Debounce Function Example Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/debounce.md This example demonstrates how to use the debounce utility to limit the execution of a function. The function 'Hello 👋' will only be logged after 500ms of inactivity. ```javascript import { debounce } from '@studiometa/js-toolkit/utils'; const debouncedFn = debounce(() => { console.log('Hello 👋'); }, 500); debouncedFn(); // Hello 👋 ``` -------------------------------- ### App Setup for Modal Component Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/examples/modal/index.md Registers the Modal component with the @studiometa/js-toolkit application, making it available for use in the DOM. ```javascript import { registerComponent } from '@studiometa/js-toolkit'; import Modal from './Modal.js'; registerComponent(Modal); ``` -------------------------------- ### Using createUrlSearchParamsStorage Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/storage/createUrlSearchParamsStorage.md Demonstrates how to initialize and use the createUrlSearchParamsStorage to set, get, and subscribe to URL search parameters. This is useful for managing state that should be reflected in the URL. ```javascript import { createUrlSearchParamsStorage } from '@studiometa/js-toolkit/utils'; const storage = createUrlSearchParamsStorage(); // URL: /products storage.set('page', 2); // URL: /products?page=2 storage.set('sort', 'price'); // URL: /products?page=2&sort=%22price%22 storage.get('page'); // 2 // React to back/forward navigation storage.subscribe('page', (value) => { console.log('Page changed:', value); }); ``` -------------------------------- ### Add new refs Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/decorators/withExtraConfig.md Example of using withExtraConfig to add a new ref to an existing component, demonstrated with the Modal component. ```APIDOC ## Add new refs This decorator can be used to easily add a new ref to an existing component. ```js import { Modal } from '@studiometa/ui/Modal'; import { withExtraConfig } from '@studiometa/js-toolkit'; export default withExtraConfig(Modal, { refs: ['toggle'] }); ``` ``` -------------------------------- ### Configure Components with Direct References, Async Loading, and Custom Selectors Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/configuration.md This example demonstrates how to configure components using various methods: direct references for immediate mounting, asynchronous loading for on-demand mounting, and custom selectors for targeting specific elements. It shows how to import components and define their mounting logic within the `App` class. ```javascript import { Base } from '@studiometa/js-toolkit'; import { Figure, PrefetchWhenOver } from '@studiometa/ui'; class App extends Base { static config = { name: 'App', components: { // Direct reference, Figure instances will be mounted // on every `[data-component="Figure"]` elements. Figure, // Async loading, the Slider component will be loaded only if there // is one or more `[data-component="Slider"]` element in the DOM. Slider: () => import('@studiometa/ui').then(({ Slider }) => Slider), // Custom selector, ComponentThree instances will be mounted // on every `a[href]` elements. 'a[href]': PrefetchWhenOver, // Custom selector with async loading, the Component component will be loaded // only if there is one or more `.other-custom-selector` element in the DOM. '.other-custom-selector': () => import('./Component.js'), }, }; } ``` -------------------------------- ### smoothTo Function Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/math/smoothTo.md Call the function with a new value to start transitioning to it, or without arguments to get the current smoothed value. ```APIDOC ## `smoothTo(initialValue)` ### Description Initializes the smoothTo utility with an initial value. ### Parameters #### Path Parameters - **initialValue** (number) - Required - The starting value for the smoothing. ### `smooth(newValue)` ### Description Call the function with a new value to start transitioning to it, or without arguments to get the current smoothed value. ### Parameters #### Path Parameters - **newValue** (number) - Optional - The target value to transition to. ### Request Example ```js import { smoothTo } from '@studiometa/js-toolkit/utils'; const smooth = smoothTo(0); smooth(100); // Start transition to 100 console.log(smooth()); // Get current smoothed value ``` ``` -------------------------------- ### Smooth Interpolation Example Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/math/smoothTo.md Demonstrates how to use the smoothTo function to interpolate between a start and end value over a specified duration. This is commonly used for animations. ```javascript import { smoothTo } from "@studiometa/js-toolkit/utils/math"; const startValue = 0; const endValue = 100; const duration = 1000; // milliseconds // This is a conceptual example, actual usage might involve requestAnimationFrame // For demonstration, we'll just show the function call. // To get the value at a specific time 't' (0 to duration): // const currentValue = smoothTo(startValue, endValue, t / duration); console.log("smoothTo function is available for use in animations."); console.log("Example usage: smoothTo(0, 100, 0.5) would return 50."); ``` -------------------------------- ### Creating Storage Provider Instances Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/storage/providers.md Demonstrates how to create instances of various storage providers using their factory functions. Includes default singletons and custom instances with specific options. ```javascript import { createLocalStorageProvider, createMemoryStorageProvider, createNoopProvider, createSessionStorageProvider, createUrlSearchParamsProvider, createUrlSearchParamsInHashProvider, } from '@studiometa/js-toolkit/utils'; const noopProvider = createNoopProvider(); const localProvider = createLocalStorageProvider(); const memoryProvider = createMemoryStorageProvider(); const sessionProvider = createSessionStorageProvider(); // Uses pushState instead of the default replaceState const pushProvider = createUrlSearchParamsProvider({ push: true }); const pushHashProvider = createUrlSearchParamsInHashProvider({ push: true }); ``` -------------------------------- ### createApp Usage Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/helpers/createApp.md Demonstrates how to use the createApp helper to initialize your application. It imports the createApp function and your root App class, then uses createApp to create an app instance and logs it to the console upon successful mounting. ```APIDOC ## createApp ### Description Initializes and mounts your application. ### Method `createApp(App)` ### Parameters #### Path Parameters - **App** (`typeof Base`) - Required - The root class for your app. ### Request Example ```js import { createApp } from '@studiometa/js-toolkit'; import App from './App.js'; const useApp = createApp(App); useApp().then((app) => console.log(app)); ``` ``` -------------------------------- ### Instantiate and Use Queue Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/Queue.md Demonstrates how to create a new Queue instance and add functions to it for sequential dispatch. Ensure the Queue class is imported before use. ```javascript import { Queue } from "@studiometa/js-toolkit/utils"; const queue = new Queue(); queue.add(() => { console.log('Task 1 executed'); }); queue.add(() => { console.log('Task 2 executed'); }); queue.dispatch(); ``` -------------------------------- ### Calculate Damped Value Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/math/damp.md Demonstrates how to use the `damp` function to get the next interpolated value. Initialize with a starting value and repeatedly call `damp` with the target and a damping factor. ```javascript import { damp } from '@studiometa/js-toolkit/utils'; const targetValue = 10; const factor = 0.5; const precision = 0.1; let currentValue = 5; // In a loop or animation frame: currentValue = damp(currentValue, targetValue, factor); if (Math.abs(targetValue - currentValue) < precision) { currentValue = targetValue; } ``` -------------------------------- ### Basic Usage of createStorage Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/storage/createStorage.md Demonstrates how to create a storage instance with a specific provider and prefix, and how to set, get, and subscribe to values. Remember to unsubscribe and destroy the storage instance when no longer needed. ```javascript import { createStorage, localStorageProvider, } from '@studiometa/js-toolkit/utils'; const storage = createStorage({ provider: localStorageProvider, prefix: 'myapp:', }); // Set and get values storage.set('theme', 'dark'); storage.get('theme'); // 'dark' // Get with default value storage.get('lang', 'en'); // 'en' (key not set yet) // Subscribe to changes const unsubscribe = storage.subscribe('theme', (value) => { console.log('Theme changed:', value); }); // Clean up unsubscribe(); storage.destroy(); ``` -------------------------------- ### Basic useScroll Hook Usage Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/services/useScroll.md Import and use the useScroll hook in your React component to get scroll position data. No additional setup is required beyond importing the hook. ```javascript import { useScroll } from "@studiometa/js-toolkit/services/scroll"; function MyComponent() { const { x, y } = useScroll(); return (
Scroll Position: X={x}, Y={y}
); } ``` -------------------------------- ### Component Instantiation Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/instantiation.md Demonstrates how to create a new instance of a component class, extending the base `Base` class from `@studiometa/js-toolkit`. The instance is created with a root element and is ready to be mounted. ```APIDOC ## new Component(element) ### Description Instantiates a new component. ### Method `new` (constructor) ### Parameters #### Path Parameters - `element` (HTMLElement) - The root element of the component/application. ### Return value Returns an instance of the class not yet mounted. ``` -------------------------------- ### JavaScript for Hello World component Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/guide/index.md Create a 'Hello' component extending Base, registering a click handler for the button. ```js // main.js import { Base, registerComponent } from '@studiometa/js-toolkit'; class Hello extends Base { static config = { name: 'Hello', refs: ['btn'], }; onBtnClick() { alert('Hello, world!'); } } registerComponent(Hello); ``` -------------------------------- ### Create and Use Session Storage Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/storage/createSessionStorage.md Demonstrates how to create a session storage instance with a prefix and set/get values. The storage is lazily resolved, allowing import before a browser-like global exists. ```javascript import { createSessionStorage } from '@studiometa/js-toolkit/utils'; const storage = createSessionStorage({ prefix: 'session:' }); storage.set('token', 'abc123'); storage.set('expires', 3600); storage.get('token'); // 'abc123' ``` -------------------------------- ### Get Random Item from Array or String Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/randomItem.md Use this function to get a random element from an array or a random character from a string. It returns undefined if the input array or string is empty. ```javascript import { randomItem } from '@studiometa/js-toolkit/utils'; const items = ['a', 'b', 'c', 'd', 'e', 'f']; randomItem(items); // one of the value in `items` const string = 'abcdef'; randomItem(string); // one of the letter in `string` ``` -------------------------------- ### Replace 'get:...' Event Handlers with Getters Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/guide/migration/v1-to-v2.md Legacy events like `get:refs` are removed in v2. Use getters within child classes to achieve similar functionality. ```js class Foo extends Base { mounted() { this.$on('get:refs', (refs) => { refs.body = document.body; }); } ``` ```js class Foo extends Base { get $refs() { const $refs = super.$refs; $refs.body = document.body; return $refs; } } ``` -------------------------------- ### Component with Responsive Options Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/decorators/withResponsiveOptions.md This example shows a basic component that utilizes `withResponsiveOptions`. The `label` option is set to be responsive, allowing its value to change based on the breakpoint. The `resized` method logs the current breakpoint and the option's value. ```javascript import { Base, withResponsiveOptions } from '@studiometa/js-toolkit'; export default class Component extends withResponsiveOptions(Base) { static config = { name: 'Component', options: { label: { type: String, responsive: true, }, }, }; resized(props) { console.log(props.breakpoint, this.$options.label); } } ``` -------------------------------- ### Instantiate App with Components Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/instantiation.md Use `createApp` to create a new app instance. This is useful for configuring global features or accessing the root app instance. Components can be registered within the app's configuration. ```javascript import { Base, createApp } from '@studiometa/js-toolkit'; import Component from './Component.js'; class App extends Base { static config = { name: 'App', components: { Component, }, }; } export default createApp(App); ``` -------------------------------- ### Initialize useDrag and Listen for START Mode Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/services/useDrag.md This snippet shows how to initialize the useDrag service on a target element and add a listener for the 'START' mode. The listener receives properties related to the drag event. ```javascript import { useDrag } from '@studiometa/js-toolkit'; useDrag(target).add('key', (props) => { if (props.mode === props.MODES.START) { console.log('drag is starting'); } }); ``` -------------------------------- ### Custom Service with Init and Kill Lifecycle Methods Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/guide/going-further/registering-new-services.md Extends `AbstractService` to include custom initialization and teardown logic. The `init()` method establishes a WebSocket connection, and `kill()` closes it. ```javascript class WebSocketService extends AbstractService { ws = null; init() { this.ws = new WebSocket('wss://example.com'); this.ws.addEventListener('message', (event) => { this.trigger({ data: JSON.parse(event.data) }); }); } kill() { this.ws?.close(); this.ws = null; } } ``` -------------------------------- ### Basic Usage of smoothTo Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/math/smoothTo.md Demonstrates how to use `smoothTo` to create a smooth transition from an initial value to a target value. Subscribe to the returned function to receive updated values during the transition. ```javascript const x = smoothTo(0); x.subscribe((value) => console.log(value)); x(100); // Smoothly transition from 0 to 100 ``` -------------------------------- ### Controlling CSS Animation Progress Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/css/animate.md Demonstrates how to use the `animate` utility to get and set the progress of a CSS animation. The `progress()` method can be called with or without an argument to get or set the animation's current state, respectively. ```javascript import { animate } from '@studiometa/js-toolkit/utils'; const animation = animate(document.body, [{ opacity: 1 }, { opacity: 0 }]); console.log(animation.progress()); // 0 animation.progress(1); console.log(animation.progress()); // 1 console.log(document.body.style.opacity); // '0' ``` -------------------------------- ### HTML structure for Hello World component Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/guide/index.md Define the HTML structure for the 'Hello' component with a button referenced by data-ref. ```html
``` -------------------------------- ### withoutLeadingSlash Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/string/withoutLeadingSlash.md Removes the leading slash from a given string. If the string does not start with a slash, it is returned as is. ```APIDOC ## withoutLeadingSlash ### Description Removes the leading slash from a given string. If the string does not start with a slash, it is returned as is. ### Parameters - `string` (string): The string to modify. ### Return value - `string`: The modified string. ### Usage Example ```js import { withoutLeadingSlash } from '@studiometa/js-toolkit/utils'; withoutLeadingSlash('/string'); // "string" withoutLeadingSlash('string'); // "string" ``` ``` -------------------------------- ### App Setup for ScrollLinkedAnimation Component Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/examples/scroll-linked-animation/index.md Registers the ScrollLinkedAnimation component with the StudioMeta JS-Toolkit application. ```javascript import { registerComponent } from '@studiometa/js-toolkit'; import ScrollLinkedAnimation from './ScrollLinkedAnimation.js'; registerComponent(ScrollLinkedAnimation); ``` -------------------------------- ### Basic withMountWhenInView Usage Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/decorators/withMountWhenInView.md This example shows a simple component that logs messages when it becomes visible or is destroyed. Ensure the component is a child of a `Base` class and is configured correctly. ```javascript import { Base, withMountWhenInView } from '@studiometa/js-toolkit'; export default class Component extends withMountWhenInView(Base) { static config = { name: 'Component', log: true, }; mounted() { this.$log('I am visible!'); } destroyed() { this.$log('I am no longer visible.'); } } ``` -------------------------------- ### Importing and Using the App Instance Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/helpers/createApp.md Import the created app instance in other files to access its methods and properties once it's mounted. The useApp function returns a promise that resolves to the app instance. ```javascript import useApp from './app.js'; (async () => { const app = await useApp(); console.log(app.$el); // document.body })(); ``` -------------------------------- ### App Setup for Component Registration Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/examples/form-validation/index.md Registers the FormValidation component with the StudioMeta JS-Toolkit application. ```javascript import { registerComponent } from '@studiometa/js-toolkit'; import FormValidation from './FormValidation.js'; registerComponent(FormValidation); ``` -------------------------------- ### Tween Usage Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/tween.md This example demonstrates how to use the tween utility to animate a value and control its progress. ```APIDOC ## tween ### Description Creates a tween instance that can be used to animate a value over time. The `callback` function is called on each animation frame with the current progress. ### Parameters #### callback - **callback** (function) - Required - A function that will be called on each animation frame with the current progress (a value between 0 and 1). #### options - **options** (object) - Optional - Configuration options for the tween. - **duration** (number) - The duration of the tween in milliseconds. Defaults to 0. - **delay** (number) - The delay before the tween starts in milliseconds. Defaults to 0. - **smooth** (boolean | number) - Enables smooth animation. If a number, it specifies the smoothing factor. Defaults to false. - **spring** (boolean | number) - Enables spring physics for animation. If a number, it specifies the spring tension. Defaults to false. - **mass** (number) - The mass of the spring. Defaults to 1. - **precision** (number) - The precision of the animation. Defaults to 0.001. - **easing** (EasingFunction | BezierCurve) - An easing function or a Bezier curve to control the animation's acceleration. - **onStart** (function) - A callback function that is called when the tween starts. - **onProgress** (function) - A callback function that is called on each animation frame. - **onFinish** (function) - A callback function that is called when the tween finishes. ### Methods - **start()**: Starts the tween animation. - **pause()**: Pauses the tween animation. - **play()**: Resumes the tween animation if it was paused. - **finish()**: Immediately finishes the tween animation. - **progress(value?: number)**: Gets or sets the current progress of the tween. Returns the current progress if no value is provided. Sets the progress to the provided value if a number is given. ### Example ```javascript import { tween } from '@studiometa/js-toolkit/utils'; const tw = tween((progress) => { document.body.innerHTML = progress; }); console.log(tw.progress()); // 0 tw.progress(1); console.log(tw.progress()); // 1 console.log(document.body.innerHTML); // '1' ``` ### Types ```ts type EasingFunction = (value: number) => number; type BezierCurve = [number, number, number, number]; interface Options { duration?: number; delay?: number; smooth?: true | number; spring?: true | number; mass?: number; precision?: number; easing?: EasingFunction | BezierCurve; onStart?: (progress: number) => void; onProgress?: (progress: number) => void; onFinish?: (progress: number) => void; } interface Tween { start: () => void; pause: () => void; play: () => void; finish: () => void; progress: (value?: number) => number; } function tween( callback: (progress: number) => void, options?: Options, ): Tween; ``` ``` -------------------------------- ### Initialize and Add Tasks to SmartQueue Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/SmartQueue.md Demonstrates how to create a new SmartQueue instance and add tasks to it. Tasks are functions that will be executed in the order they are added. ```javascript import { SmartQueue } from '@studiometa/js-toolkit/utils'; const queue = new SmartQueue(); queue.add(() => console.log('1')); queue.add(() => console.log('2')); ``` -------------------------------- ### Remove Callback Example Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/services/useDrag.md Demonstrates how to remove a callback using the remove function with a custom ID. ```javascript // Remove the callback remove('custom-id'); ``` -------------------------------- ### withMountOnMediaQuery Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/decorators/withMountOnMediaQuery.md Creates a component that mounts and destroys itself based on a specified media query. ```APIDOC ## withMountOnMediaQuery ### Description Use this decorator to create a component which will mount and destroy itself based on a specified media query. ### Usage ```js import { Base, withMountOnMediaQuery } from '@studiometa/js-toolkit'; import Component from './Component.js'; export default withMountOnMediaQuery( Component, 'not (prefers-reduced-motion)', ); ``` ### Parameters - `Base` (`BaseConstructor`): The `Base` class or a class extending it. - `media` (`string`): a [media query](https://developer.mozilla.org/en-US/docs/Web/CSS/@media#media_features) ### Return value - `BaseConstructor`: A child class of the given class which will be mounted when the media query matches. ``` -------------------------------- ### spring Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/math/smoothTo.md Gets or sets the spring behavior for the animation. When enabled, the animation will have a spring-like overshoot and oscillation. ```APIDOC ## spring(value?) ### Description Gets or sets the spring option. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **value** (boolean) - Optional - The new spring value to set (true to enable, false to disable). ### Returns - **boolean** - The current spring setting. ``` -------------------------------- ### Configure ESLint (Recommended) Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/guide/going-further/linting.md Apply the recommended configuration for the StudioMeta ESLint plugin in your ESLint v9 flat config file. ```javascript import { jsToolkit } from '@studiometa/eslint-plugin-js-toolkit'; export default [ jsToolkit.configs.recommended, // ...your other config ]; ``` -------------------------------- ### Component with Mutation Dependencies Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/decorators/withMutation.md An example of a component that uses `withMutation` and declares its dependencies, including the mutation configuration. ```javascript import { withMutation } from "@studiometa/js-toolkit/decorators"; export default withMutation(class extends Component { static dependencies = [ { path: ".user-form", mutate: { updateUser: { method: "put", path: "/users/:id" } } } ]; updateName() { const { updateUser} = this.props; updateUser({ id: this.id, name: "New Name" }); } }); ``` -------------------------------- ### Handling Mutation Responses Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/decorators/withMutation.md Provides an example of how to handle the response from a mutation, including success and error states. ```javascript async updateUser() { try { const response = await this.props.updateUser({ id: this.id, name: "New Name" }); console.log("User updated successfully:", response); } catch (error) { console.error("Failed to update user:", error); } } ``` -------------------------------- ### Configure Blocking Behavior Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/helpers/defineFeatures.md Set `blocking` to `true` to mount the app immediately. The default is `false`, which waits for `document.readyState === 'complete'`. ```javascript import { defineFeatures } from '@studiometa/js-toolkit'; defineFeatures({ blocking: true }); ``` -------------------------------- ### importWhenPrefersMotion Usage Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/helpers/importWhenPrefersMotion.md This example demonstrates how to use the `importWhenPrefersMotion` function to dynamically import a component. The component will only be imported if the user's system preferences indicate that they accept motion. ```APIDOC ## importWhenPrefersMotion Use this function to import components when the user accepts motion. ### Description Conditionally imports a component based on the user's system preference for motion. If the user prefers reduced motion, the import will not occur. ### Parameters - `importFn` (`() => Promise`): A function that returns a Promise resolving to the component's class. This function is only executed if the user accepts motion. ### Returns - `Promise`: A Promise that resolves to the imported component's class if the user accepts motion, otherwise it might resolve to undefined or an empty promise depending on the implementation details not fully specified. ### Usage Example ```js import { importWhenPrefersMotion } from '@studiometa/js-toolkit'; // Import Component.js only if the user accepts motion. importWhenPrefersMotion(() => import('./components/Component.js')); ``` ### Example within a Component Configuration ```js import { Base, importWhenPrefersMotion } from '@studiometa/js-toolkit'; class App extends Base { static config = { name: 'App', components: { Component: () => importWhenPrefersMotion(() => import('./components/Component.js')), }, }; } ``` ``` -------------------------------- ### stiffness Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/math/smoothTo.md Gets or sets the stiffness factor for the animation. Higher stiffness leads to a faster, more responsive animation. ```APIDOC ## stiffness(value?) ### Description Gets or sets the stiffness factor. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **value** (number) - Optional - The new stiffness value to set. ### Returns - **number** - The current stiffness value. ``` -------------------------------- ### damping Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/math/smoothTo.md Gets or sets the damping factor for the animation. A higher damping factor results in a slower transition. ```APIDOC ## damping(value?) ### Description Gets or sets the damping factor. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **value** (number) - Optional - The new damping factor to set. ### Returns - **number** - The current damping factor. ``` -------------------------------- ### Instantiate a Component Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/instantiation.md Instantiate a new component with a specific root element. The component is created but not yet mounted. ```javascript import { Base } from '@studiometa/js-toolkit'; class Component extends Base { static config = { name: 'Component', }; } const component = new Component(document.querySelector('.component')); component.$mount(); ``` -------------------------------- ### Basic Pointer Usage Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/services/usePointer.md Demonstrates how to use the usePointer hook to track cursor position relative to the viewport. ```javascript import { usePointer } from "@studiometa/js-toolkit/services/pointer"; const { x, y, event } = usePointer(); console.log(x, y, event); ``` -------------------------------- ### Basic Usage Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/helpers/closestComponent.md Find the closest parent 'Parent' instance starting from the current component's element. ```APIDOC ## closestComponent(query, options) ### Description Finds the closest ancestor component instance that matches the provided query. ### Method `closestComponent` ### Parameters #### Path Parameters - **query** (string) - Required - A query string in the format `ComponentName(.cssSelector):state`. - **options** ({ from: HTMLElement }) - Optional - An object containing the element from which to start traversing up the DOM. Defaults to the current component's `$el`. ### Return value - `Base | undefined` - The closest matching ancestor instance, or `undefined` if none found. ### Example ```js import { Base, closestComponent } from '@studiometa/js-toolkit'; class Child extends Base { static config = { name: 'Child', }; mounted() { // Get the closest parent 'Parent' instance const parent = closestComponent('Parent', { from: this.$el }); if (parent) { // Do something with the parent instance } } } ``` ``` -------------------------------- ### Create localStorage Instance Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/storage/createStorage.md Initializes a localStorage instance with a specific key prefix. This is useful for namespacing your storage keys to avoid conflicts. ```javascript import { createStorage } from "@studiometa/js-toolkit/utils/storage"; const localStorage = createStorage('my-app'); ``` -------------------------------- ### App Setup for Lazy Image Component Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/examples/lazy-image/index.md Registers the `LazyImage` component with the Studiometa JS Toolkit application. ```js import { registerComponent } from '@studiometa/js-toolkit'; import LazyImage from './LazyImage.js'; registerComponent(LazyImage); ``` -------------------------------- ### Get All Mounted Instances Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/helpers/getInstances.md Retrieves all mounted instances of every component. This is useful for global component management or debugging. ```javascript import { Base, getInstances } from '@studiometa/js-toolkit'; import Component from './Component.js'; // Get all mounted instances of all components const instances = getInstances(); // Set ``` -------------------------------- ### withoutLeadingCharacters Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/string/withoutLeadingCharacters.md Removes a specified set of characters from the beginning of a string. If the string does not start with any of the specified characters, it is returned unchanged. ```APIDOC ## withoutLeadingCharacters ### Description Removes a specified set of characters from the beginning of a string. If the string does not start with any of the specified characters, it is returned unchanged. ### Method `withoutLeadingCharacters(string, characters)` ### Parameters #### Path Parameters - `string` (string): The string to modify. - `characters` (string): The characters to remove from the start of the string. ### Return value - `string`: The modified string. ### Usage Example ```js import { withoutLeadingCharacters } from '@studiometa/js-toolkit/utils'; withoutLeadingCharacters('__string', '__'); // "string" withoutLeadingCharacters('string', '__'); // "string" ``` ``` -------------------------------- ### nextMicrotask Usage Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/nextMicrotask.md Demonstrates how to use the nextMicrotask utility function both as a callback API and a Promise API. ```APIDOC ## nextMicrotask ### Description Schedules a function to be executed in the next microtask or returns a Promise that resolves in the next microtask. ### Method `nextMicrotask(fn?: () => T): Promise | void` ### Parameters - `fn` (`() => T`): Optional. The function to execute in the next microtask. If not provided, a Promise is returned. ### Return value - If `fn` is provided, returns `void`. - If `fn` is not provided, returns a `Promise` that resolves on the next microtask. ### Examples #### Callback API ```javascript import { nextMicrotask } from '@studiometa/js-toolkit/utils'; nextMicrotask(() => { console.log('I will be executed in the next microtask!'); }); ``` #### Promise API ```javascript import { nextMicrotask } from '@studiometa/js-toolkit/utils'; await nextMicrotask(); console.log('I will be executed in the next microtask!'); ``` ``` -------------------------------- ### Accessing Responsive Options with a Function Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/decorators/withResponsiveOptions.md Illustrates how to use a function to define responsive options, allowing for dynamic option generation based on the current breakpoint. ```javascript import React from 'react'; import { withResponsiveOptions } from '@studiometa/js-toolkit/decorators'; @withResponsiveOptions({ breakpoints: { mobile: 320, tablet: 768, desktop: 1024, }, options: ({ current }) => { if (current === 'mobile') { return { size: 'small' }; } else if (current === 'tablet') { return { size: 'medium' }; } return { size: 'large' }; }, }) class MyDynamicComponent extends React.Component { render() { const { responsive } = this.props; return (

Current size option: {responsive.option('size')}

); } } export default MyDynamicComponent; ``` -------------------------------- ### Create and use localStorage instance Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/storage/createLocalStorage.md Instantiate a localStorage-backed storage object with a custom prefix. You can then use its methods to set, get, and subscribe to changes in storage values. Values persist across page reloads and are synced across tabs. ```javascript import { createLocalStorage } from '@studiometa/js-toolkit/utils'; const storage = createLocalStorage({ prefix: 'myapp:' }); storage.set('theme', 'dark'); storage.get('theme'); // 'dark' storage.get('lang', 'en'); // 'en' (default) // React to changes (including from other tabs) const unsubscribe = storage.subscribe('theme', (value) => { document.documentElement.dataset.theme = value; }); ``` -------------------------------- ### precision Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/utils/math/smoothTo.md Gets or sets the precision for the animation. This determines how close the smoothed value needs to be to the target value to be considered reached. ```APIDOC ## precision(value?) ### Description Gets or sets the precision factor. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **value** (number) - Optional - The new precision value to set. ### Returns - **number** - The current precision value. ``` -------------------------------- ### Import and Use withExtraConfig Decorator Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/decorators/withExtraConfig.md Demonstrates how to import and use the withExtraConfig decorator to create a new component class with added configuration. This is the basic usage pattern for the decorator. ```javascript import { withExtraConfig } from '@studiometa/js-toolkit'; import Component from './Component.js'; export default withExtraConfig(Component, { log: true }); ``` -------------------------------- ### Pointer Usage Relative to an Element Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/services/usePointer.md Shows how to use the usePointer hook with an HTMLElement to get cursor position relative to that element. ```javascript import { usePointer } from "@studiometa/js-toolkit/services/pointer"; const element = document.querySelector('.my-element'); const { x, y, event } = usePointer(element); console.log(x, y, event); ``` -------------------------------- ### Basic App Creation Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/helpers/createApp.md Define your main application class and export it using createApp. This is the primary way to initialize your JS Toolkit application. ```javascript import { Base, createApp } from '@studiometa/js-toolkit'; class App extends Base { static config = { name: 'App', }; } export default createApp(App); ``` -------------------------------- ### v2 Ref Handling Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/guide/migration/v1-to-v2.md v2 is stricter and only registers refs defined in `config.refs`. Extra refs like 'two' in this example are ignored. ```javascript class Foo extends Base { static config = { name: 'Foo', refs: ['one'], }; mounted() { console.log(this.$refs); // Before: { one: HTMLElement } } } ``` -------------------------------- ### Configuring Responsive Options Source: https://github.com/studiometa/js-toolkit/blob/main/packages/docs/api/decorators/withResponsiveOptions.md Shows how to configure the responsive options for the withResponsiveOptions decorator. This allows you to define custom breakpoints and their corresponding options. ```javascript import React from 'react'; import { withResponsiveOptions } from '@studiometa/js-toolkit/decorators'; @withResponsiveOptions({ breakpoints: { mobile: 320, tablet: 768, desktop: 1024, }, options: { mobile: { theme: 'light' }, tablet: { theme: 'dark' }, desktop: { theme: 'dark' }, }, }) class MyConfigurableComponent extends React.Component { render() { const { responsive } = this.props; return (

Current theme: {responsive.option('theme')}

); } } export default MyConfigurableComponent; ```