/** * Represents a map of configurable settings for the StringTune system. * Each key corresponds to a setting name (e.g. 'offset-top', 'parallax', etc.). * * These settings can be used as: * - Global fallbacks via `setupSettings` * - Module-specific overrides via `use(MyModule, settings)` * * The values are typically string-based, but can also be numbers or booleans. */ interface StringSettings { [key: string]: string | number | boolean; } interface ModuleLifecyclePermissionsItem { rebuild: { width: boolean; height: boolean; scrollHeight: boolean; }; } declare class ModuleLifecyclePermissions { desktop: ModuleLifecyclePermissionsItem; mobile: ModuleLifecyclePermissionsItem; } /** * Reactive cursor data for raw, target, smoothed and step deltas. */ declare class CursorState { /** * Target X position of the cursor (e.g., from `mousemove`) */ targetX: number; /** * Target Y position of the cursor. */ targetY: number; /** * Smoothed X position after applying lerp. */ smoothedX: number; /** * Smoothed Y position after applying lerp. */ smoothedY: number; /** * Delta step between current and target X (used internally for lerp). */ stepX: number; /** * Delta step between current and target Y. */ stepY: number; /** * Velocity in X direction, calculated from smoothed position. */ velocityX: number; /** * Velocity in Y direction, calculated from smoothed position. */ velocityY: number; } /** * Global Three.js or rendering context reference. */ declare class RenderState { /** Instance of Three.js or another render context */ threeInstance: any; } type ScrollDirection = 'vertical' | 'horizontal'; type BuiltInScrollMode = 'smooth' | 'disable' | 'default'; type ScrollMode = BuiltInScrollMode | string; /** * Describes current scroll-related state for all calculations and modules. */ declare class ScrollState { /** Target scroll value — where we want to scroll to (used in smooth scroll) */ target: number; /** Current scroll value (actual scroll position) */ current: number; /** Transformed current scroll value (with transform by scroll container) */ transformedCurrent: number; /** Delta between frames (used for animation / velocity) */ delta: number; /** Interpolated scroll value for smooth transitions */ lerped: number; /** Displacement value (similar to lerped, but used for other animations) */ displacement: number; /** Whether scroll direction is downward */ isScrollingDown: boolean; /** Top screen scroll position */ topPosition: number; /** Bottom screen scroll position */ bottomPosition: number; /** Scroll direction (vertical / horizontal) */ direction: ScrollDirection; /** Scroll container element */ elementContainer: HTMLElement; /** Scroll container element */ scrollContainer: HTMLElement | Window; /** Scroll container element */ container: HTMLElement; /** * Currently active scroll mode. * Can be 'smooth', 'default', or 'disable'. */ mode: ScrollMode; /** * Scroll mode to use on mobile devices. * Can be 'smooth', 'default', or 'disable'. */ modeMobile: ScrollMode; /** * Scroll mode to use on desktop devices. * Can be 'smooth', 'default', or 'disable'. */ modeDesktop: ScrollMode; /** * Base scroll speed used for calculating smooth scrolling. * Typically a small value between 0 and 1. */ speed: number; /** * Acceleration factor used for scroll easing or velocity-based animations. * Also typically a value between 0 and 1. */ speedAccelerate: number; } declare class SystemState { fpsTracker: boolean; positionTracker: boolean; suppressMasonryResize: boolean; } /** * Represents the time-related state of the current and previous animation frames. * * Useful for calculating delta time, total elapsed time, and implementing * time-based animations or physics. */ declare class TimeState { /** * Timestamp of the current animation frame in milliseconds. * This value is typically obtained via `performance.now()`. */ now: number; /** * Timestamp of the previous animation frame in milliseconds. */ previous: number; /** * Time difference between the current and previous frames in milliseconds. * Commonly used to calculate animation progress. */ delta: number; /** * Total time elapsed since the start of the animation or system in milliseconds. */ elapsed: number; } /** * Describes current viewport size and scaling. */ declare class ViewportState { /** Width of the visible window */ windowWidth: number; /** Height of the visible window */ windowHeight: number; /** Full scroll width (content width inside scroll container) */ contentWidth: number; /** Full scroll height (content height inside scroll container) */ contentHeight: number; /** Screen scale ratio for width (e.g. device pixel ratio or zoom level) */ scaleWidth: number; /** Screen scale ratio for height */ scaleHeight: number; transformScale: number; baseRem: number; } /** * Container for global dynamic state used throughout the string-tune system. * Provides access to live scroll, viewport, cursor, and render states, * which are updated each frame and shared across modules and tools. */ declare class StringData { /** * Scroll-related state object. * Contains live values like `target`, `current`, `delta`, `direction`, and more. * Used for scroll-based animations, transitions, and effects. */ scroll: ScrollState; /** * Viewport-related state object. * Holds dimensions like window size, content size, aspect ratios, and more. * Useful for layout calculations, unit parsing, and element positioning. */ viewport: ViewportState; /** * Cursor-related state object. * Tracks cursor position, velocity, movement, and derived values. * Can be used for pointer interactions, proximity effects, and hover states. */ cursor: CursorState; /** * Render-related state object. * Stores data related to rendering context (e.g. WebGL, Three.js), * such as shared materials, textures, or active render frame data. */ render: RenderState; /** * Time-related state object. * Tracks frame timings, including current timestamp, delta between frames, * and total elapsed time since animation start. * Useful for time-based animations, easing, frame consistency, and syncing logic. */ time: TimeState; system: SystemState; } /** * Base interface for scroll/interaction modules in the StringScroll system. */ interface IStringModule { permissions: ModuleLifecyclePermissions; /** Cleans up all internal state and detaches from the system. */ destroy(): void; /** Called once when the module is initialized. */ onInit(): void; /** Called once when the module is registered and can subscribe to events. */ onSubscribe(): void; /** Called once when the module is being removed and should unsubscribe. */ onUnsubscribe(): void; /** Called on each frame with current scroll and state data. */ onFrame(data: StringData): void; /** Called when the window or layout is resized. */ onResize(): void; /** Called when the layout is resize width. */ onResizeWidth(): void; /** Called when the system rebuilds the DOM (e.g. after mutations). */ onDOMRebuild(): void; /** Called when scroll position changes. */ onScroll(data: StringData): void; /** Called when scroll change direction. */ onDirectionChange(): void; /** Called when scrolling starts (user begins scroll). */ onScrollStart(): void; /** Called when scrolling ends (user stops scroll). */ onScrollStop(): void; /** Called when scroll direction changes (e.g. up → down). */ onScrollDirectionChange(): void; /** Called when overall scroll axis changes (vertical ↔ horizontal). */ onAxisChange(): void; /** Called when device type changes (e.g. desktop ↔ mobile). */ onDeviceChange(): void; /** Called when scroll-related system settings or params are updated. */ onScrollConfigChange(): void; /** * Called when global system settings are updated via `setupSettings`. * Modules can override this to re-read default values, refresh configs, * or reapply any cached parameters that depend on settings. * * This method is triggered after global fallback settings are merged into context. * * Example use cases: * - Recalculating default lerp, anchor, radius, etc. * - Updating internal thresholds or animation values. * - Reacting to system-wide design changes. */ onSettingsChange(): void; /** Called on mouse move (for interaction-based modules). */ onMouseMove(event: MouseEvent): void; /** Called on wheel scroll (separate from general scroll). */ onWheel(event: WheelEvent): void; /** * Called when the DOM mutates — useful for detecting new or removed elements. */ onDOMMutate(added: NodeList, removed: NodeList): void; /** * Triggered when an object was successfully connected. */ onObjectConnected(object: StringObject): void; /** * Called when a DOM element is detected as a potential interactive object. */ initializeObject(globalId: number, object: StringObject, element: HTMLElement, attributes: Record): void; calculatePositions(object: StringObject, windowSize: number): void; /** * Check if a module should connect to a given object. */ canConnect(object: StringObject): boolean; /** * Called to connect this module to the object. */ connectObject(object: StringObject): void; /** * Called when the cursor or interaction enters an object's area. */ enterObject(id: string, object: StringObject): void; /** * Called when the interaction leaves the object's area. */ exitObject(id: string): void; addObject(id: string, object: StringObject): void; removeObject(id: string): void; } type EventCallback = (payload: T) => void; /** * Manages custom event subscriptions and dispatching. * Allows multiple listeners per event and supports optional `id` suffixing. */ declare class EventManager { private listeners; private stateEvents; private lastPayloads; constructor(); /** * Marks an event as stateful so the last payload is cached and replayed to new listeners. * Optionally seeds the initial payload. */ registerStateEvent(eventName: string, initialPayload?: any): void; /** * Subscribes to an event. * Optionally appends an `id` to the event name for namespacing. * * @param eventName The base event name (e.g. "scroll", "update"). * @param callback The function to call when the event is emitted. * @param id Optional unique identifier to scope the event (e.g. element ID). */ on(eventName: string, callback: EventCallback, id?: string | null): void; /** * Unsubscribes from a specific event listener. * Must match the original `eventName`, `callback`, and optional `id`. * * @param eventName The base event name to unsubscribe from. * @param callback The callback function to remove. * @param id Optional identifier used when subscribing. */ off(eventName: string, callback: EventCallback, id?: string): void; /** * Emits an event with an optional payload. * All matching listeners will be called. * * @param eventName The full event name (must include `id` if used). * @param payload Optional data passed to event listeners. */ emit(eventName: string, payload?: T): void; /** * Subscribes to a per-object progress event. * @param id The object ID. * @param callback The callback to handle progress value. */ onProgress(id: string, callback: EventCallback): void; /** * Emits a per-object progress event. * @param id The object ID. * @param value The progress value. */ emitProgress(id: string, value: number): void; /** * Subscribes to a per-object in-view event. * @param id The object ID. * @param callback The callback to handle visibility. */ onInview(id: string, callback: EventCallback): void; /** * Emits a per-object in-view event. * @param id The object ID. * @param visible Whether the object is visible. */ emitInview(id: string, visible: boolean): void; /** * Subscribes to the global scroll event. * @param callback The callback to handle scroll value. */ onScroll(callback: EventCallback): void; /** * Emits the global scroll event. * @param value The scroll value. */ emitScroll(value: number): void; /** * Subscribes to the global update event. * @param callback The callback to handle update. */ onUpdate(callback: EventCallback): void; /** * Emits the global update event. */ emitUpdate(): void; /** * Clears all listeners for a specific event. * * @param eventName The full event name (including optional `id`). */ clear(eventName: string): void; /** * Clears all registered events. */ clearAll(): void; } type StringTokenModeSpec = { kind: "default"; values: []; } | { kind: "all"; values: []; } | { kind: "include"; values: ScrollMode[]; }; interface StringToken { raw: string; key: string; modeSpec: StringTokenModeSpec; } type MirrorEasingFn = (value: number) => number; /** * Lightweight wrapper that mirrors a primary StringObject while keeping * its own easing and state. Intended for elements linked via * `[string-copy-from]`. */ declare class StringMirrorObject { private parent; readonly id: string; readonly htmlElement: HTMLElement; private properties; private easingFn?; constructor(id: string, element: HTMLElement, parent: StringObject); get parentObject(): StringObject; setProperty(key: string, value: T): void; getProperty(key: string): T; setEasing(easing: MirrorEasingFn | null | undefined): void; getEasing(): MirrorEasingFn | undefined; /** * Returns eased progress using mirror easing (if set) or fallback. */ applyProgress(rawProgress: number, fallback?: MirrorEasingFn): number; } /** * Internal class representing a DOM-bound interactive object. * Connected to modules and holds its own internal state. */ declare class StringObject { /** * The DOM element this object wraps. */ htmlElement: HTMLElement; /** * Unique global ID assigned by the system. */ id: string; /** * Space-separated list of all attribute keys associated with this object. */ keys: string[]; tokens: StringToken[]; /** * Mirror objects linked via `string-copy-from`. */ private mirrors; private _cachedMirrorObjects; private _cachedConnects; private _mirrorsDirty; /** * Internal key-value store of dynamic object properties (like offsets, progress, etc.). */ private properties; /** * Modules currently connected to this object. */ private modules; /** * Manages and handles events for the object. * Provides functionality to register, trigger, and manage event listeners. */ events: EventManager; private eventNameCache; private eventNameSuffixCache; constructor(id: string, element: HTMLElement); /** * Returns a cached event name in one of these forms: * - `${prefix}:${id}` * - `${prefix}:${id}:${suffix}` */ getScopedEventName(prefix: string, suffix?: string): string; /** * Stores a property value for this object. * @param key - Property name * @param value - Value to store */ setProperty(key: string, value: T): void; /** * Retrieves a previously stored property value. * @param key - Property name * @returns The value or null if not set */ getProperty(key: string): T; /** * Marks this object as "active" (usually on intersection/scroll enter). */ enter(): void; /** * Marks this object as "inactive" (usually on intersection/scroll leave). */ leave(): void; /** * Removes the current object by iterating through all associated modules * and invoking their `removeObject` method with the object's ID. * * This method ensures that the object is properly removed from all * modules it is associated with. */ remove(): void; setInviewAutoBlocked(blocked: boolean): void; isInviewAutoBlocked(): boolean; setInviewManualActive(active: boolean): void; isInviewManualActive(): boolean; syncInviewClass(): void; /** * Shows the object, applies visual class and notifies connected modules. */ show(): void; /** * Hides the object, removes visual class (if repeat is enabled), and notifies modules. */ hide(): void; /** * Connects a module to this object if not already connected. * @param module - The module to connect */ connect(module: IStringModule): boolean; disconnect(module: IStringModule): boolean; isConnectedTo(module: IStringModule): boolean; setTokens(tokens: StringToken[]): void; getToken(key: string): StringToken | null; private updateMirrorsCache; addMirror(mirror: StringMirrorObject): void; removeMirror(id: string): void; get mirrorObjects(): StringMirrorObject[]; get connects(): HTMLElement[]; } declare class CenterCache { private map; private all; attach(obj: StringObject): void; detach(obj: StringObject): void; invalidate(id: string): void; invalidateAll(): void; getCenter(obj: StringObject): { cx: number; cy: number; }; } declare class HoverTracker { private active; private subs; track(obj: StringObject): void; untrack(obj: StringObject): void; isActive(obj: StringObject): boolean; activeObjects(): StringObject[]; } interface ISettingsChangeData { isDesktop: boolean; isForceRebuild: boolean; widthChanged: boolean; heightChanged: boolean; scrollHeightChanged: boolean; } type StyleValue = string | number; type StyleVars = Record; type StyleProps = Record; declare class StyleTxn { pendingVars: Map; pendingProps: Map; isOpen: boolean; private canUseTypedOM; private writeVar; begin(): void; setVars(el: Element, vars: StyleVars): void; setVar(el: Element, key: string, value: StyleValue): void; /** * Directly sets a CSS custom property (variable) on an element using CSS Typed OM * for improved performance. Falls back to string-based assignment if not supported. * Note: This writes immediately. Use `begin()`, `setVar()`, `commit()` for batched writes. */ setVarDirect(el: Element, key: string, value: StyleValue): void; setProps(el: Element, props: StyleProps): void; setProp(el: Element, key: string, value: StyleValue): void; run(fn: () => void): void; commit(): void; cancel(): void; } declare const styleTxn: StyleTxn; /** * Base interface for injectable core tools in the String system. * Each tool takes input and returns output (transform, extract, calculate). */ interface IStringTool { /** * Process input and return result. * Can be a transformation, extraction, interpolation, etc. * * @param input - Any input relevant to the tool. * @returns Output result from the tool. */ process(input: Input): Output; } /** * Input for `BoundingClientRectTool`. */ interface BoundingClientRectInput { /** The DOM element to retrieve bounding rect from. */ element: HTMLElement; } /** * Tool for accessing `getBoundingClientRect()` in a consistent, testable way. */ declare class BoundingClientRectTool implements IStringTool { /** * @returns The bounding client rect of the provided element. */ process({ element }: BoundingClientRectInput): DOMRect; } interface DOMAttributeInput { element: HTMLElement; key: string; fallback?: string | null; } declare class DOMAttributeTool implements IStringTool { /** * Retrieves the value of either `string-${key}` or `data-string-${key}` attribute. * * @example key = "offset-tom" → tries: * - element.getAttribute("string-offset-tom") * - element.getAttribute("data-string-offset-tom") */ process({ element, key, fallback }: DOMAttributeInput): string | null; } /** * Input for retrieving a value from a key-value object or dataset-like structure. */ interface RecordAttributeInput { /** Source object to read from (e.g. dataset or plain record). */ record: Record; /** Key to look up (without `"data-"` prefix). */ name: string; /** Fallback value if both keys are missing. */ fallback?: any; } /** * Retrieves a value from an object or dataset-like structure. * Tries `record[name]` first, then `record["data-" + name]`, or returns fallback. */ declare class RecordAttributeTool implements IStringTool { /** * @returns Value from the record or fallback. */ process({ record, name, fallback }: RecordAttributeInput): any; } /** * Input for removing transform effects from an element's bounding box. */ interface TransformNullifyInput { /** The DOM element whose CSS transform should be nullified. */ element: HTMLElement; } /** * Output with corrected bounding box values. */ interface TransformNullifyOutput { /** Top position without transform effects. */ top: number; /** Left position without transform effects. */ left: number; /** Width without transform scaling. */ width: number; /** Height without transform scaling. */ height: number; } /** * Computes the true bounding box of a DOM element, * nullifying CSS `transform: matrix(...)` effects. */ declare class TransformNullifyTool implements IStringTool { /** * @returns Element position and size without transform influence. */ process({ element }: TransformNullifyInput): TransformNullifyOutput; } /** * Input for calculating the position of an element relative to a container. */ interface RelativePositionInput { /** The DOM element whose position should be calculated. */ element: HTMLElement; /** Optional container to measure against. Defaults to `document.body`. */ container?: HTMLElement; } /** * Output: relative position in pixels. */ interface RelativePositionOutput { /** Distance from the top of the container. */ top: number; /** Distance from the left of the container. */ left: number; } /** * Calculates an element's position relative to a container. * Uses `TransformNullifyTool` to account for CSS transforms. */ declare class RelativePositionTool implements IStringTool { /** Optional tool for CSS transform-neutral measurements. */ private transformTool; constructor( /** Optional tool for CSS transform-neutral measurements. */ transformTool?: TransformNullifyTool); /** * @returns Relative top/left position of element within container. */ process({ element, container }: RelativePositionInput): RelativePositionOutput; } interface LerpInput { /** Starting value of the interpolation. */ from: number; /** Target value to interpolate towards. */ to: number; /** Interpolation progress between 0 (start) and 1 (end). */ progress: number; } declare class LerpTool implements IStringTool { /** * Calculates the linear interpolation between two values. * @returns Interpolated value. */ process({ from, to, progress }: LerpInput): number; } /** * Input for parsing unit-based strings into numeric pixel values. */ interface UnitParserInput { /** Unit string, e.g. `"20px"`, `"50%"`, `"1.5rem"`, or `"selfHeight"` */ value: string; /** DOM element used for `"selfHeight"` calculation */ element: HTMLElement; /** Viewport height in pixels (for percentage conversion) */ viewportHeight: number; /** Root font size in pixels (for rem conversion) */ baseRem: number; boundingRect: DOMRect; } /** * Converts unit-based strings to numeric pixel values. * Supports `px`, `%`, `rem`, and `"selfHeight"` keyword. Handles negatives. */ declare class UnitParserTool implements IStringTool { /** * @returns Numeric value in pixels (positive or negative). */ process({ value, element, viewportHeight, baseRem, boundingRect }: UnitParserInput): number; } /** * Input for adaptive lerp factor calculation. * Maps a speed-like value to a lerp factor, where: * - lower speed ⇒ slower smoothing (higher lerp factor) * - higher speed ⇒ faster response (lower lerp factor) */ interface AdaptiveLerpInput { /** Current value (e.g., speed or delta). */ value: number; /** Minimum input threshold (default: 0.1) */ inMin?: number; /** Maximum input threshold (default: 1.0) */ inMax?: number; /** Output when input is at minimum (default: 0.65) */ outMax?: number; /** Output when input is at maximum (default: 0.05) */ outMin?: number; } /** * Converts a numeric input (like velocity) into an adaptive lerp factor. * Useful for scroll or speed-based smoothing effects. */ declare class AdaptiveLerpTool implements IStringTool { /** * @returns A remapped lerp factor from `outMax` to `outMin`. */ process({ value, inMin, inMax, outMin, outMax }: AdaptiveLerpInput): number; } /** * Input for origin parser. * Supports static values or `random(...)` expressions. */ interface OriginInput { /** Raw origin string, e.g. `'center'` or `'random(top, bottom)'`. */ value: string; } /** * Input for parsing origin to normalized coordinates. * Supports formats like `'left top'`, `'center center'`, `'50% 50%'`, `'35% 76%'`. */ interface OriginToNormalizedInput { /** Raw origin string, e.g. `'left top'`, `'center'`, `'50% 25%'`. */ value: string; } /** * Output: normalized origin coordinates (0-1 range). */ interface NormalizedOrigin { /** Normalized X coordinate (0 = left, 0.5 = center, 1 = right). */ x: number; /** Normalized Y coordinate (0 = top, 0.5 = center, 1 = bottom). */ y: number; } /** * Tool that parses origin strings. * Allows static values like `'center'`, or expressions like `'random(...)'` to select one randomly. * Also provides `toNormalized()` method to convert origin strings to `{ x, y }` coordinates. */ declare class OriginParserTool implements IStringTool { /** * @returns Parsed string value (static or randomly chosen). */ process({ value }: OriginInput): string; /** * Parses an origin string to normalized `{ x, y }` coordinates (0-1 range). * * Supported formats: * - Single keyword: `'center'`, `'top'`, `'left'`, etc. * - Two keywords: `'left top'`, `'right bottom'`, `'center center'` * - Percentages: `'50% 50%'`, `'0% 100%'`, `'35% 76%'` * - Mixed: `'left 25%'`, `'50% top'` * * @param input - The origin string to parse. * @returns Normalized `{ x, y }` coordinates. */ toNormalized({ value }: OriginToNormalizedInput): NormalizedOrigin; /** * Parses a single value (keyword or percentage) to a normalized number. */ private parseValue; } interface StringColor { r: number; g: number; b: number; a: number; } /** * Input for parsing color strings into RGBA format. */ interface ColorParserInput { /** Color string in hex, rgb[a], or hsl[a] format. */ value: string; } /** * Parses a CSS color string (`#fff`, `rgb(...)`, `hsl(...)`, etc.) * into an object with `r`, `g`, `b`, `a` values. */ declare class ColorParserTool implements IStringTool { /** * @returns RGBA object parsed from color string. */ process({ value }: ColorParserInput): StringColor; private hslToRgb; } /** * Input parameters for EasingFunctionTool. */ interface EasingFunctionInput { /** * The easing string. * Can be: 'linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out', or 'cubic-bezier(...)' */ easing: string; } /** * Output of the easing function: receives t in [0,1] and returns eased value. */ type EasingFunctionOutput = (t: number) => number; /** * Tool for parsing easing strings into easing functions. * Supports standard keywords (`ease-in`, `ease-out`, etc.) and `cubic-bezier(...)` expressions. */ declare class EasingFunctionTool implements IStringTool { private namedCurves; /** * Parses an easing string and returns a corresponding easing function. */ process({ easing }: EasingFunctionInput): EasingFunctionOutput; /** * Generates a cubic-bezier easing function. * Ported from https://github.com/gre/bezier-easing (MIT) */ private cubicBezier; } /** * Input parameters for calculating magnetic pull factor. */ interface MagneticPullInput { /** Distance between pointer and element center (px). */ distance: number; /** Max distance within which magnetic pull is active. */ radius: number; /** Strength of the magnetic pull (0–1 recommended). */ strength: number; } /** * Output: factor to multiply by direction vector (dx/dy) to get magnetic offset. */ type MagneticPullOutput = number; /** * Tool for calculating magnetic attraction based on distance to element. * Returns a scalar value (0..strength) depending on proximity. */ declare class MagneticPullTool implements IStringTool { /** * Returns a pull factor based on distance to target within a radius. * @param input - Magnetic pull parameters. * @returns A multiplier (typically < 1) to apply to dx/dy. */ process({ distance, radius, strength }: MagneticPullInput): number; } /** * Input parameters for `LerpColorTool`. */ interface LerpColorInput { /** * Starting color as an object `{ r, g, b, a }` where each value is in the range `0–1`. */ from: StringColor; /** * Target color as an object `{ r, g, b, a }` where each value is in the range `0–1`. */ to: StringColor; /** * Interpolation progress from `0` (start) to `1` (end). */ progress: number; } /** * Tool for linearly interpolating between two RGBA colors using `StringColor` format. * Each channel (`r`, `g`, `b`, `a`) is interpolated independently. * Returns a new `StringColor` with the interpolated values. */ declare class LerpColorTool implements IStringTool { /** * Performs linear interpolation between two `StringColor` values. * * @param input.from - The starting color `{ r, g, b, a }`. * @param input.to - The target color `{ r, g, b, a }`. * @param input.progress - A number from `0` to `1` indicating interpolation progress. * @returns Interpolated color as a new `StringColor`. */ process({ from, to, progress }: LerpColorInput): StringColor; } interface StringVector { x: number; y: number; } /** * Input parameters for LerpVector2Tool. */ interface LerpVector2Input { /** * Starting vector value `{ x, y }`. */ from: StringVector; /** * Target vector value `{ x, y }`. */ to: StringVector; /** * Interpolation progress from `0` (start) to `1` (end). */ progress: number; } /** * Tool for linearly interpolating between two 2D vectors. * Useful for cursor smoothing, UI element animations, and motion blending. */ declare class LerpVector2Tool implements IStringTool { /** * Calculates the interpolated vector between `from` and `to`. * * @param input.from - The starting vector `{ x, y }`. * @param input.to - The target vector `{ x, y }`. * @param input.progress - Interpolation progress from `0` (start) to `1` (end). * @returns Interpolated vector `{ x, y }`. */ process({ from, to, progress }: LerpVector2Input): { x: number; y: number; }; } /** * Input for parsing the transform string to extract scale. */ interface TransformParserInput { /** CSS transform string (e.g., "matrix(0.5, 0, 0, 0.5, 10, 20)", "scale(0.5)", "none"). */ value: string; } /** * Parses a CSS transform string to extract the primary scale factor. * Assumes uniform scale or extracts the X-axis scale factor from matrix/scale functions. */ declare class TransformScaleParserTool implements IStringTool { /** * Processes the transform string and extracts the scale factor. * @returns Numeric scale factor (defaults to 1 if no scale transform is found or parsing fails). */ process({ value }: TransformParserInput): number; } /** * Represents a single parsed option item definition * (e.g., the result of parsing '[center]' or '[random(0,10)|abs]'). */ interface ISplitOptionItem { /** The alignment type ('start', 'center', 'end', 'random'). */ align: string; /** Optional parameters for random alignment. */ random?: { min: number; max: number; }; /** Flag indicating if the absolute value should be used. */ abs?: boolean; } /** * Represents the fully parsed options from the string-split attribute. * Holds arrays of option definitions for each split type. */ interface ISplitOptions { fit?: boolean; trimInlineGaps?: boolean; line?: ISplitOptionItem[]; word?: ISplitOptionItem[]; char?: ISplitOptionItem[]; charLine?: ISplitOptionItem[]; charWord?: ISplitOptionItem[]; wordLine?: ISplitOptionItem[]; } /** * Input interface for the SplitOptionsParserTool. */ interface SplitOptionsParserInput { /** * The raw string value from the 'string-split' attribute (or similar). * Can be null if the attribute is not present. */ attributeValue: string | null; } declare class SplitOptionsParserTool implements IStringTool { process({ attributeValue }: SplitOptionsParserInput): ISplitOptions; private toCamelCase; private parseParamsArray; } interface RuleParserInput { value: string; } interface RuleParserResult { key: string; params?: string[]; } declare class RuleParserTool implements IStringTool { process({ value }: RuleParserInput): RuleParserResult[]; } interface ValidationContext { fieldKey?: string; values?: Record; getValue?: (key: string) => any; } interface ValidateInput { rules: RuleParserResult[]; value: any; type?: "input" | "beforeinput"; context?: ValidationContext; } interface ValidationResult { valid: boolean; errors: string[]; } type ValidatorFn = (value: any, params?: string[], context?: ValidationContext) => boolean; declare class ValidationTool implements IStringTool { process({ rules, value, type, context }: ValidateInput): ValidationResult; inputValidators: Record; beforeInputValidators: Record; getErrorMessage(key: string, params?: string[]): string; private validateMimes; private validateMaxSize; private extractFiles; private isMimeAllowed; private getFileExtension; private compareDates; private resolveDateReference; private toDate; private testByRegex; private normalizeRegex; private getContextValue; private areValuesEqual; private isIPv4; private isIPv6; } /** * Container holding references to all essential tools used within the library. * Dependency injection. */ interface StringToolsContainer { /** Tool for reading DOM attributes (including data-*). */ domAttribute: DOMAttributeTool; /** Tool for reading attributes from a plain JS object or dataset. */ recordAttribute: RecordAttributeTool; /** Tool for calculating the relative position between two elements. */ relativePosition: RelativePositionTool; /** Tool that nullifies the effect of CSS transform matrix. */ transformNullify: TransformNullifyTool; /** Tool that wraps getBoundingClientRect with consistent output. */ boundingClientRect: BoundingClientRectTool; /** Tool for parsing string-based values like '50%', '2rem', 'selfHeight'. */ unitParser: UnitParserTool; /** Tool for performing linear interpolation (lerp). */ lerp: LerpTool; /** * Tool for adaptive interpolation based on dynamic input value. * Useful when smoothing cursor speed, scroll velocity, etc. */ adaptiveLerp: AdaptiveLerpTool; /** * Tool for parsing origin strings. * Supports values like `'top'`, `'center'`, or random expressions like `'random(top, bottom)'`. */ originParser: OriginParserTool; /** * Tool for parsing CSS color strings into { r, g, b, a } format. * Supports `#hex`, `rgb[a](...)`, `hsl[a](...)` inputs. */ colorParser: ColorParserTool; /** * Tool for validating strings using rules like `required`, `minLength`, `email`, etc. * Returns validation status, error code, and optional message. */ validation: ValidationTool; /** * Tool for parsing CSS-like easing strings into easing functions. * Supports keywords like `'ease'`, `'linear'`, and full `cubic-bezier(...)` expressions. */ easingFunction: EasingFunctionTool; /** * Tool for calculating magnetic offset strength based on proximity to pointer. */ magneticPull: MagneticPullTool; /** * Tool for interpolating between two RGBA colors. * Accepts `from` and `to` colors as `{ r, g, b, a }`, and a `progress` value from `0` to `1`. * Returns an interpolated `StringColor` object. */ lerpColor: LerpColorTool; /** * Tool for interpolating between two 2D vectors. * Accepts `{ x, y }` objects and a `progress` value between `0` and `1`. * Returns a new `{ x, y }` vector. */ lerpVector: LerpVector2Tool; transformScaleParser: TransformScaleParserTool; optionsParser: SplitOptionsParserTool; ruleParser: RuleParserTool; styleTxn: typeof styleTxn; } type AttributeType = "string" | "number" | "boolean" | "json" | "dimension" | "breakpoint-dimension" | "tuple" | "easing" | "color" | { type: "enum"; values: string[]; }; /** * Represents the fallback value for an attribute mapping. * It can either be a static value or a function that dynamically * computes a value based on the element, object, and its bounding rectangle. */ type AttributeFallback = any | ((context: { element: HTMLElement; object: StringObject; boundingRect: DOMRect; }) => any); /** * Describes how a specific attribute should be mapped from an HTML element * to internal module data. Each mapping defines the attribute key, its expected type, * an optional fallback value, and an optional transformation function. */ type AttributeMapping = { /** Attribute name (without `string-` prefix). */ key: string; /** The type used for parsing this attribute (e.g., 'number', 'boolean', 'tuple'). */ type: AttributeType; /** * Optional fallback value if the attribute is not present on the element. * Can be a static value or a dynamic function. */ fallback?: AttributeFallback; /** * Optional transformation function to apply to the parsed attribute value. * Useful for converting parsed data into a more usable format. */ transform?: (value: any) => any; }; interface ParseContext { element?: HTMLElement; boundingRect?: DOMRect; viewportHeight?: number; baseRem?: number; } /** * Base class for a module used in the string-tune system. * Extend this class to create custom modules that respond to scroll, resize, input, etc. */ declare class StringModule implements IStringModule { /** * List of attribute names this module should automatically read * from the DOM element and assign to the object properties. * Example: ["offset-top", "offset-bottom"] */ protected attributesToMap: AttributeMapping[]; /** * Defines CSS Custom Properties (Houdini) strictly required by this module. * ModuleManager will automatically register these properties on initialization * for Typed Object Model hardware acceleration. */ cssProperties: Array<{ name: string; syntax: string; initialValue: string; inherits: boolean; }>; /** * A map that associates string keys with `StringObject` instances. * This map is used to manage and track `StringObject` instances on a page. */ protected objectMapOnPage: Map; protected allObjectMapOnPage: Map; /** * A protected array that holds the collection of `StringObject` instances * currently present on the page. */ protected objectsOnPage: StringObject[]; protected allObjectsOnPage: StringObject[]; /** * A map of all entered objects by their unique ID. */ protected objectMap: Map; protected allObjectMap: Map; /** * A flat array of all connected objects. */ protected objects: StringObject[]; protected allObjects: StringObject[]; /** * The HTML attribute key that identifies objects this module is responsible for. */ protected htmlKey: string; protected defaultModeScope: "all" | ScrollMode[]; /** * Module type ID used internally to categorize module behavior. */ protected _type: number; /** * Returns the type of the module. * Type 1 = core module, type 2 = UI module. */ get type(): number; get key(): string; /** * Tools container providing utilities for attribute parsing, unit conversion, etc. * Acts as a dependency injection hub for core IStringTool implementations. */ protected tools: StringToolsContainer; /** * Shared global data object containing scroll state, viewport info, cursor position, etc. * Used for calculations within lifecycle hooks like `onScroll`, `onFrame`, and `onResize`. */ protected data: StringData; /** * Configuration object specific to the current module. * Passed in during module registration or initialization. */ protected settings: Record; /** * Event hub for communication between modules or systems. * Supports custom event emitting, listening, and unsubscription. */ protected events: EventManager; /** * Cache for storing and managing object centers. */ protected centers: CenterCache; /** * Tracker for managing hover states of objects. */ protected hover: HoverTracker; /** * Object manager for layout refreshes and in-view recalculation. */ protected objectManager: ObjectManager; permissions: ModuleLifecyclePermissions; constructor(context: StringContext); /** * Initializes a `StringObject` by mapping attributes from an HTML element * and applying transformations as needed. * * @param globalId - A unique identifier for the object being initialized. * @param object - The `StringObject` instance to be initialized. * @param element - The HTML element from which attributes are extracted. * @param attributes - A record of additional attributes to be used during initialization. * * The method performs the following steps: * 1. Retrieves the bounding rectangle of the provided HTML element. * 2. Iterates over a predefined list of attributes to map. * 3. Resolves fallback values for attributes, either from the provided attributes, * settings, or a fallback function. * 4. Processes and parses the raw attribute values based on their expected type. * 5. Applies optional transformations to the parsed values. * 6. Sets the processed attributes as properties on the `StringObject` instance. */ initializeObject(globalId: number, object: StringObject, element: HTMLElement, attributes: Record): void; protected cacheLayoutSnapshot(object: StringObject, element: HTMLElement): void; private getOffsetSize; private getOffsetChainPosition; /** * Calculates object-specific positions or metrics based on the current layout or scroll state. * This method is intended to be overridden in subclasses if the module needs to precompute * layout-dependent values (e.g. parallax offsets, trigger zones, distances). * * @param object The `StringObject` instance whose positions are being calculated. * @param windowSize The current window height or width (depending on scroll axis). */ calculatePositions(object: StringObject, windowSize: number): void; /** * Parses a raw DOM attribute value into the correct type based on mapping. * Handles fallback resolution, transformation, and special units. * * @param value Raw attribute string from DOM. * @param type The expected attribute type (e.g. number, boolean, dimension). * @param context Optional helper values like element or viewport size. * @returns The parsed and transformed value. */ protected parseAttribute(value: string | null, type: AttributeType, context?: ParseContext): any; /** * Determines whether the module should attach to a given object, * based on the presence of the module's `htmlKey` in the object keys. * * @param object The target object to test. * @returns `true` if the module can connect, `false` otherwise. */ canConnect(object: StringObject): boolean; protected isTokenEnabledInCurrentMode(token: StringToken): boolean; protected isObjectEnabledInCurrentMode(object: StringObject): boolean; disconnectObject(object: StringObject): void; /** * Registers the module on a given object, adds the object to internal list, * and triggers connection logic. * * @param object The object to connect to. */ connectObject(object: StringObject): void; /** * Registers the object internally when it enters the module’s scope. */ enterObject(id: string, object: StringObject): void; protected fastRemoveFromArray(array: T[], index: number): void; /** * Unregisters the object when it leaves the module’s scope. */ exitObject(id: string): void; /** * Adds a `StringObject` to the internal collections if it does not already exist. * * @param id - The unique identifier for the `StringObject`. * @param object - The `StringObject` to be added. * * @remarks * This method ensures that the object is added to both `objectMapOnPage` and * `objectsOnPage` only if the `id` is not already present in `objectMapOnPage`. */ addObject(id: string, object: StringObject): void; /** * Removes an object from the page by its unique identifier. * * This method performs the following steps: * 1. Retrieves the object associated with the given `id` from `objectMapOnPage`. * 2. If the object is not found, the method exits early. * 3. Deletes the object from `objectMapOnPage`. * 4. Finds the index of the object in the `objectsOnPage` array. * 5. If the object exists in the array, it is removed using `splice`. * * @param id - The unique identifier of the object to be removed. */ removeObject(id: string): void; /** * Called when an object is connected. Can be overridden to apply initial styles or logic. * @param object The connected object. */ onObjectConnected(object: StringObject): void; /** * Called when an object is disconnected. Can be overridden to clean up styles or logic. * @param object The disconnected object. */ onObjectDisconnected(object: StringObject): void; protected get respectSelfDisable(): boolean; protected isPrimaryElementEnabled(object: StringObject): boolean; /** * Applies a style or callback to both the main element and all its connected elements. * * @param object The object whose elements to update. * @param applyFn The function that receives an HTMLElement and performs any update. */ protected applyToElementAndConnects(object: StringObject, applyFn: (el: HTMLElement) => void, copyFn?: (el: HTMLElement, mirror?: StringMirrorObject) => void): void; /** * Directly applies a CSS variable to the object's element without closures. */ protected applyVarToElement(object: StringObject, key: string, value: string | number): void; /** * Directly applies a standard CSS property to the object's element without closures. */ protected applyPropToElement(object: StringObject, key: string, value: string | number): void; /** * Directly applies a CSS variable to all connected mirrors without closures. */ protected applyVarToConnects(object: StringObject, key: string, value: string | number): void; /** * Directly applies a standard CSS property to all connected mirrors without closures. */ protected applyPropToConnects(object: StringObject, key: string, value: string | number): void; /** * Returns a cached per-object event name to avoid building strings in hot paths. */ protected getObjectEventName(object: StringObject, prefix: string, suffix?: string): string; protected clearManagedStyles(object: StringObject): void; protected onObjectModeActivated(object: StringObject): void; protected onObjectModeDeactivated(object: StringObject): void; protected rebuildActiveObjectsForCurrentMode(): void; /** * Cleans up internal state and detaches the module from the system. */ destroy(): void; /** Called once when the module is initialized. */ onInit(): void; /** Called once when the module is registered and can subscribe to events. */ onSubscribe(): void; /** Called once when the module is being removed and should unsubscribe. */ onUnsubscribe(): void; /** Called on each frame with current scroll and state data. */ onFrame(data: StringData): void; onMutate(data: StringData): void; onScrollMeasure(data: StringData): void; onMouseMoveMeasure(data: StringData): void; /** Called when the window or layout is resized. */ onResize(): void; /** Called when the layout is resized width. */ onResizeWidth(): void; /** Called when scroll position changes. */ onScroll(data: StringData): void; /** Called when user changed scroll direction. */ onDirectionChange(): void; /** Called when user starts scrolling. */ onScrollStart(): void; /** Called when user stops scrolling. */ onScrollStop(): void; /** Called when scroll direction changes (e.g., up ↔ down). */ onScrollDirectionChange(): void; /** Called when scroll axis changes (vertical ↔ horizontal). */ onAxisChange(): void; /** Called when device type changes (e.g., desktop ↔ mobile). */ onDeviceChange(): void; /** Called when scroll-related system settings or parameters change. */ onScrollConfigChange(): void; /** Called when scroll-related system settings or parameters change. */ onSettingsChange(): void; /** Called when the DOM is rebuilt, such as after a major mutation. */ onDOMRebuild(): void; /** Called on every mouse movement. */ onMouseMove(event: MouseEvent): void; /** Called on wheel input (independent of scroll). */ onWheel(event: WheelEvent): void; /** * Called when DOM elements are added or removed. */ onDOMMutate(added: NodeList, removed: NodeList): void; } declare class ModuleManager { private data; private modules; private uiModules; private allModules; constructor(data: StringData); register(module: StringModule): void; find(type: new (...args: any[]) => T): T | undefined; onInit(): void; onFrame(): void; onMutate(): void; onScrollMeasure(): void; onMouseMoveMeasure(): void; onScroll(): void; onResizeWidth(): void; onResize(): void; onMouseMove(e: MouseEvent): void; onWheel(e: WheelEvent): void; onDirectionChange(): void; onScrollStart(): void; onScrollStop(): void; onAxisChange(): void; onDeviceChange(): void; onScrollConfigChange(): void; onSettingsChange(_data: ISettingsChangeData): void; onDOMMutate(added: NodeList, removed: NodeList): void; destroy(): void; get all(): IStringModule[]; get core(): IStringModule[]; get ui(): IStringModule[]; private callAll; private callLifecycleStrict; private rebuildAllModules; } declare class ObjectManager { private data; private modules; private events; private tools; private objects; private connectQueue; private connectableModulesBuffer; private mirrors; private mirrorId; private globalId; private domBatcher; private domBatcherEnabled; private inviewStarts; private inviewEnds; private inviewActive; private inviewStartIdx; private inviewEndIdx; private inviewIndexDirty; private lastInviewScrollPos; private intersectionObserverEnabled; private domObserver; constructor(data: StringData, modules: ModuleManager, events: EventManager, tools: StringToolsContainer); /** * Returns the object map (read-only). */ get all(): ReadonlyMap; /** * Adds a new object from an element. */ add(el: HTMLElement): void; setDOMBatcherEnabled(enabled: boolean): void; setIntersectionObserverEnabled(enabled: boolean): void; attachModule(module: StringModule): void; refreshModuleConnectionsForCurrentMode(): void; invalidateInviewIndex(): void; refreshLayoutForRoot(root: HTMLElement): void; /** * Removes an object by its id. */ remove(id: string): void; /** * Add an element that will connect later. */ enqueueConnection(id: string, element: HTMLElement): void; linkMirror(id: string, element: HTMLElement): void; private attachMirrorToObject; private detachMirrorByElement; private detachMirrorById; private getMirrorIds; private setMirrorIds; private clearMirrorIds; /** * Retrieves all attributes of a given HTML element and returns them as a record. * * @param el - The HTML element from which to extract attributes. * @returns A record where the keys are attribute names and the values are attribute values. */ private getAllAttributes; /** * Initializes IntersectionObservers for a given object and its associated HTML element. * * This method sets up observer: * - A "progress" observer to track when the object enters or leaves the viewport. * * The observers are configured with custom root margins and thresholds based on the object's properties. * Existing observers, if any, are disconnected before creating new ones. * * @param obj - The `StringObject` instance containing properties and methods for interaction. * @param el - The `HTMLElement` to observe for intersection changes. */ private initObservers; /** * Observes DOM mutations to auto-add/remove elements with [string] attribute. * Should be called once after DOM is ready. */ observeDOM(): void; /** * Removes an object and its observers. */ private handleRemoved; /** * Re-applies module initialization logic to all managed objects after settings change. * * This method should be called when `StringSettings` are updated at runtime, * especially if the new settings affect how modules calculate offsets, * easing, origins, or custom configuration. * * Internally, it re-runs `initializeObject`, `calculatePositions`, and `connectObject` * for each core module that can connect to the object. * * This is useful for supporting dynamic configuration updates without requiring * a full DOM rebuild or reinitialization. */ onSettingsChange(data: ISettingsChangeData): void; /** * Checks whether the element is marked as fixed (not managed). */ private isFixed; checkInview(): void; private checkInviewForObject; private updateInviewWindow; private rebuildInviewIndex; private upperBound; private splitPipeAndTrim; private parseStringTokens; private splitTopLevelPipe; destroy(): void; } /** * Shared context object passed to all modules and core controllers. * * Provides access to shared tools, data, settings, and event handling. */ interface StringContext { /** * Collection of utility tools (e.g. lerp, dom parser, unit converter). */ tools: StringToolsContainer; /** * Reactive state container including scroll, viewport, cursor, etc. */ data: StringData; /** * Global configuration settings for modules and system behavior. */ settings: StringSettings; /** * Centralized event emitter and listener system. */ events: EventManager; /** * Caches the center positions of string objects. */ centers: CenterCache; /** * Tracks hover states of string objects. */ hover: HoverTracker; /** * Manages all interactive objects (elements with `string-*` attributes). */ objectManager: ObjectManager; } /** * StringCursor Module * * Handles cursor tracking and hover states for StringTune objects. * * Safari Navigation Fix: * Safari has an issue where mouseleave events are not fired when navigation occurs * (especially with NuxtLink/router navigation). This module includes several * workarounds to ensure proper cleanup: * * 1. MutationObserver - detects when elements are removed from DOM * 2. beforeunload/pagehide - captures traditional navigation * 3. visibilitychange - captures modern SPA navigation * 4. DOM existence checks - prevents operations on removed elements */ declare class StringCursor extends StringModule { private cursorPrev; private cursorPortals; private hoveredObjects; private globalListenersBound; private boundBeforeUnload; private boundPageHide; private boundVisibilityChange; protected enabled: boolean; private lastFrameTime; constructor(context: StringContext); initializeObject(globalId: number, object: StringObject, element: HTMLElement, attributes: Record): void; onResize(): void; onMutate(data: StringData): void; onObjectConnected(object: StringObject): void; getCursorClass(object: StringObject): string | null; onMouseEnter(object: StringObject): void; onMouseLeave(object: StringObject): void; private onEnterObject; private onLeaveObject; private safariNavigationCleanup; private onElementRemovedFromDOM; onObjectDisconnected(object: StringObject): void; onDOMRebuild(): void; onDOMMutate(added: NodeList, removed: NodeList): void; private collectCursorPortals; private resolvePortalId; private resolvePortalLerp; private shouldRefreshPortals; private withPortalsForObject; private getPortalsForObject; private extractPortalIds; private incrementPortalHover; private decrementPortalHover; private restartPortalShowTimer; private clearPortalShowTimer; private updatePortalPosition; private handleRemovedNodes; private cleanupHoverTargets; private bindGlobalLifecycleListeners; private unbindGlobalLifecycleListeners; private setMouseCoordinates; private writePortalVars; private parseCursorVars; private getFrameAdjustedLerp; private getObjectDimensions; private calculateOffset; private reverseOffset; removeObject(id: string): void; destroy(): void; } declare class StringImpulse extends StringModule { private originObservers; constructor(context: StringContext); onObjectConnected(object: StringObject): void; onObjectDisconnected(object: StringObject): void; onMouseMove(_e?: MouseEvent): void; /** * Parses and caches the rotation origin for an object. * Called once on object connection and when attribute changes. */ private cacheRotationOrigin; /** * Observes changes to the rotation-origin attribute and re-caches when changed. */ private observeRotationOrigin; /** * Calculates the rotation origin point using cached normalized values and provided rect. * Avoids re-parsing origin string and extra getBoundingClientRect calls. */ private getRotationOriginFromRect; onFrame(_: StringData): void; onMutate(): void; } declare class StringMasonry extends StringModule { private states; constructor(context: StringContext); private parseEasing; onObjectConnected(object: StringObject): void; onFrame(data: StringData): void; onResize(): void; cleanupObject(object: StringObject): void; private createState; private handleAnimationEnd; private scheduleLayout; /** * Performs the layout calculation and application synchronously. * Optimizes for batched DOM reads and writes via `styleTxn`. */ private performSyncLayout; private getGridSettings; private attachImgLoaders; private cleanupImgListeners; } declare class StringMagnetic extends StringModule { constructor(context: StringContext); initializeObject(globalId: number, object: StringObject, element: HTMLElement, attributes: Record): void; onMouseMove(e: MouseEvent): void; onFrame(data: StringData): void; onMutate(): void; } declare abstract class CursorReactiveModule extends StringModule { protected nearOnly: boolean; protected useAllObjects: boolean; protected maxDistanceMultiplier: number; protected updateThreshold: number; protected enabled: boolean; constructor(context: StringContext); onObjectConnected(object: StringObject): void; removeObject(id: string): void; onScroll(): void; onMouseMoveMeasure(data: StringData): void; onScrollMeasure(data: StringData): void; protected getCursorTargets(allowFallback?: boolean): StringObject[]; protected refreshPointerState(target?: StringObject, allowFallback?: boolean): void; private scrollUpdateScheduled; protected scheduleCursorUpdate(): void; protected onCursorScrollUpdate(): void; } declare class StringSpotlight extends CursorReactiveModule { private readonly stepResult; constructor(context: any); initializeObject(id: number, obj: StringObject, el: HTMLElement, attrs: Record): void; onMutate(data: StringData): void; protected onCursorScrollUpdate(): void; private updateSpotlightState; private writeSpotlightVars; } declare class StringLazy extends StringModule { private isStartLoaded; private loadingCount; private imageStates; constructor(context: StringContext); onInit(): void; onObjectConnected(object: StringObject): void; onObjectDisconnected(object: StringObject): void; private ensureState; private readSource; private handleInView; private prepareAspectRatio; private maybeActivateImage; private activateImage; } /** * Represents a module responsible for handling loading-related functionality. * Extends the `StringModule` class and provides additional behavior for managing * loading states and timeouts. */ declare class StringLoading extends StringModule { loadingTimeout: number; constructor(context: StringContext); onInit(): void; } declare class StringResponsive extends StringModule { private queries; private isMobileMedia; private isTabletMedia; private isLaptopMedia; private isDesktopMedia; private matchMedias; constructor(context: StringContext); onConnect(): void; onInit(): void; onResize(): void; private updateElements; } /** * The `StringAnchor` class extends the `StringModule` class and is responsible for * managing anchor-related functionality within the string module system. * * This class maps an `anchor` attribute to a tuple containing x and y coordinates, * processes these coordinates using the `originParser` tool, and applies the resulting * values to the connected object's element as a CSS `transform-origin` style. */ declare class StringAnchor extends StringModule { constructor(context: StringContext); onObjectConnected(object: StringObject): void; } /** * The `StringGlide` class is a module that handles the glide effect for string objects * based on scroll events. It calculates displacement, acceleration, and velocity * to create a smooth scrolling effect for objects. */ declare class StringGlide extends StringModule { protected defaultModeScope: string[]; private previousLerp; private displacement; private acceleration; private velocityMultiplier; private isInitialScroll; private baseVelocityMultiplier; private reducedVelocityMultiplier; private negativeVelocityMultiplier; private maxDisplacementValue; constructor(context: StringContext); initializeObject(globalId: number, object: StringObject, element: HTMLElement, attributes: Record): void; private setupItem; private updateTransforms; private resetObjectStyles; private calcExpanderFactor; onStart(): void; onResize(): void; private resetState; onScrollStart(): void; onScrollStop(): void; onFrame(data: StringData): void; protected onObjectModeDeactivated(object: StringObject): void; onMutate(): void; private applyPendingGlideStylesForObject; private applyPendingGlideStyles; private flushPendingGlideStyles; } /** * Module that updates the `--lerp` CSS variable on elements * based on current scroll velocity. */ declare class StringLerp extends StringModule { private hasInitializedCSS; protected defaultModeScope: string[]; constructor(context: StringContext); /** * Initialize lerp value when object connects. */ onObjectConnected(object: StringObject): void; /** * Called on resize - use this to apply initial values after mirrors are created. */ onResize(): void; /** * Resets the `--lerp` value to 0 when scroll stops. */ onScrollStop(): void; /** * Updates `--lerp` value for each connected object during scroll. */ onFrame(data: StringData): void; /** * Computes the lerp value for the object. */ private recomputeLerp; /** * Applies the lerp value to the object and its mirrors. */ onMutate(): void; /** * Updates the CSS variable on the object and connected elements. */ private updateObjectLerp; /** * Cleans up the CSS variable when object is disconnected. */ onObjectDisconnected(object: StringObject): void; } declare class StringProgress extends StringModule { protected updateScheduled: boolean; private batchStarts; private batchDiffs; private batchOut; constructor(context: StringContext); initializeObject(globalId: number, object: StringObject, element: HTMLElement, attributes: Record): void; private sanitizeRawProgress; private resolveRawProgress; private applyRawProgress; private recomputeProgress; private ensureBatchCapacity; calculatePositions(object: StringObject, windowSize: number): void; onScroll(data: StringData): void; onObjectConnected(object: StringObject): void; onScrollMeasure(data: StringData): void; onMutate(): void; private updateObjectProgress; onObjectDisconnected(object: StringObject): void; } /** * The `StringParallax` class extends the `StringProgress` class to provide * functionality for handling parallax effects on scrollable elements. * It maps specific attributes related to parallax and calculates the * necessary transformations based on scroll progress and viewport size. */ declare class StringParallax extends StringProgress { protected defaultModeScope: string[]; private updateScheduledTransform; private calculateParallaxForObject; constructor(context: StringContext); /** * Called when an object is initialized. */ initializeObject(globalId: number, object: StringObject, element: HTMLElement, attributes: Record): void; calculatePositions(object: StringObject, windowSize: number): void; onScroll(data: StringData): void; onScrollMeasure(data: StringData): void; onMutate(): void; private calculateParallax; } declare class StringScrollbar extends StringModule { private scrollbar; private thumb; private scrollTimeout; private isDragging; private scrollMode; private mouseUpEventBind; private mouseDownEventBind; private mouseMoveEventBind; private scrollbarState; private scrollbarStateHorizontal; private scrollbarStateVertical; private requestScrollTo; constructor(context: StringContext); destructor(): void; onInit(): void; onScroll(data: StringData): void; onResize(): void; private addCustomStyles; private createScrollbar; private updateThumb; private mouseDownEvent; private mouseMoveEvent; private mouseUpEvent; private showScrollbar; private hideScrollbar; } /** * StringSplit module: splits text into lines, words, chars, * computes alignment/random values, and applies CSS vars. */ declare class StringSplit extends StringModule { /** Last content-width (px) at which each element was split. Keyed by element itself. */ private lastSplitWidth; constructor(context: StringContext); onInit(): void; onObjectDisconnected(object: StringObject): void; onResizeWidth(): void; onObjectConnected(object: StringObject): void; private extractTextContent; private getSplitOptions; private hasLineDrivenSplit; private needsWidthRebuild; private needsForcedRebuildOnFontLoad; private getDebugStoreKey; private writeDebugRecord; private isDebugEnabled; private getDebugLabel; private logConnectionStart; private captureBaselineSnapshot; private logSplitAnalysis; private getTokenDebugText; private logRenderedState; private applyFlexLineBreaks; private getBlockContainerContentWidth; private getElementContentWidth; split(element: HTMLElement, options: ISplitOptions, debugEnabled?: boolean): { fragment: DocumentFragment; result: DocumentFragment; extraProps: Map; }; private getFitContext; /** * Computes target font sizes to fill the container width and stores them on each line. * * With a line-level split (`line`, `wordLine`, `charLine`): sets `fitFontSize` on each * `LayoutLine` so that BuildDOMTree can expose `--fit-font-size` per `-s-line` span. * Each line may receive a different value, allowing text to fill 100% of the container * width independently per line. * * Without a line-level split: finds the widest line and returns a single * `--fit-font-size` in the extraProps map, to be applied to the container element. * * Formula: targetFontSize = currentFontSize * (contentWidth / lineWidth) */ private applyFit; private refineFitFontSize; private solveRenderedFitFontSize; private measureScopeAtFontSize; private measureCharScopeWidth; private measureContentWidth; /** * Computes the target font size to fill `contentWidth`. * * Inter-word `\u00a0` nodes in the DOM are NOT wrapped in `-s-char` spans, so they * stay at the original font size and do not scale. The formula accounts for this by * subtracting total space width (fitWidth - browserWordWidthSum) from both sides: * * targetFontSize = currentFontSize * (contentWidth - spacesWidth) / (lineWidth - spacesWidth) * * For single-word lines spacesWidth = 0 and the formula reduces to the simple ratio. */ private computeFitFontSize; /** * Computes a numeric value based on the provided split option, index, and total count. * * @param opt - The split option item containing alignment and optional random range. * @param index - The current index in the sequence. * @param total - The total number of items in the sequence. * @returns A computed numeric value based on the alignment strategy: * - "random": A random value within the specified range or default range. * - "start": The current index. * - "end": The reverse index from the end of the sequence. * - "center": The distance from the center index. * - Default: The current index. */ private computeValue; /** * Applies calculated values to the provided layout lines and their components (words and characters) * based on the given options. This method computes and assigns various calculated values * (e.g., alignment and value) to lines, words, and characters, depending on the specified options. * * @param lines - An array of `LayoutLine` objects representing the lines of text to process. * @param options - An `ISplitOptions` object specifying the calculation options for lines, words, and characters. * * The `options` parameter can include the following properties: * - `line`: An array of options for calculating values at the line level. * - `word`: An array of options for calculating values at the word level. * - `wordLine`: An array of options for calculating values at the word level relative to the line. * - `char`: An array of options for calculating values at the character level. * - `charWord`: An array of options for calculating values at the character level relative to the word. * - `charLine`: An array of options for calculating values at the character level relative to the line. * * Each calculated value is assigned to the corresponding `calculatedValues` property of the line, word, or character. * The method ensures that all specified options are processed and the calculated values are appended accordingly. */ private applyCalculatedValues; /** * Escapes the `src` attribute in a given string by removing the quotes around the URL. * * This method searches for occurrences of `src="URL"` where `URL` is an HTTP or HTTPS link, * and replaces it with `src=URL` (removing the quotes around the URL). * * @param str - The input string containing the `src` attributes to be escaped. * @returns The modified string with escaped `src` attributes. */ private escapeAttribute; } /** * Visual tracker that plots scroll displacement (velocity) in real time. * Useful for debugging and tuning smoothing behavior. */ declare class StringDelayLerpTracker extends StringModule { private canvas; private context; private history; private maxPoints; private height; private value; private target; constructor(context: StringContext); /** * Called when the module starts — sets up canvas. */ onInit(): void; /** * Called on scroll — stores current displacement and redraws. */ onScroll(data: StringData): void; /** * Draws the displacement graph to canvas. */ private draw; /** * Creates and styles the tracking canvas. */ private initCanvas; /** * Optional method to update external comparison target. */ setTarget(position: number): void; /** * Removes the canvas from DOM and resets. */ clear(): void; } /** * FPS Tracker Module. * Broadcasts frame rate to elements with `data-fps` attribute. * Also creates an optional debug display element. */ declare class StringFPSTracker extends StringModule { private displayElement; private intervalId; private frameCount; /** Cached elements with data-fps attribute */ private fpsElements; /** MutationObserver for DOM changes */ private observer; /** Last known FPS to avoid redundant updates */ private lastFps; constructor(context: StringContext); /** * Initializes the visual FPS counter, scans for elements, and starts interval. */ onInit(): void; /** * Increments the frame counter each frame. */ onFrame(_data: StringData): void; /** * Cleans up DOM, observer, and interval. */ destroy(): void; /** * Handles visibility toggle from external API. */ private onVisibilityChange; /** * Removes the display element and its styles. */ private removeDisplayElement; /** * Updates all tracked elements with current FPS. */ private updateFPS; /** * Scans document for elements with data-fps attribute. */ private scanElements; /** * Observes DOM for added/removed elements with data-fps attribute. */ private observeDOM; /** * Creates and styles the floating FPS display. */ private createDisplayElement; } /** * Visual tracker that plots lerped scroll velocity (v) in real time. * Useful for analyzing smooth scroll interpolation behavior. */ declare class StringLerpTracker extends StringModule { private canvas; private context; private history; private maxPoints; private canvasHeight; private currentValue; private targetValue; constructor(context: StringContext); /** * Called on start — sets up canvas overlay. */ onInit(): void; /** * Called on scroll — reads smoothed scroll velocity (v). */ onScroll(data: StringData): void; /** * Draws the current graph line based on v-history. */ private draw; /** * Creates the canvas overlay and applies style. */ private initCanvas; /** * Optional external target value for debugging. */ setTarget(position: number): void; /** * Removes canvas from DOM and clears history. */ clear(): void; } /** * Tracker module that broadcasts scroll position to elements with data attributes. * Elements with `data-val`, `data-val-pct`, or `data-dir` will receive updates. * Also creates an optional debug display element. */ declare class StringPositionTracker extends StringModule { private displayElement; /** Cached elements by attribute type */ private valElements; private valPctElements; private dirElements; /** MutationObserver for DOM changes */ private observer; /** Last known values to avoid redundant updates */ private lastVal; private lastValPct; private lastDir; /** Previous scroll position for direction detection */ private previousCurrent; /** Timeout for resetting direction to idle state */ private idleTimeout; constructor(context: StringContext); /** * Called on start — creates debug element and scans for tracked elements. */ onInit(): void; /** * Called on scroll — updates all tracked elements with position data. */ onScroll(data: StringData): void; /** * Updates direction on all tracked elements. */ private setDirection; /** * Cleans up DOM observer and display element. */ destroy(): void; /** * Handles visibility toggle from external API. */ private onVisibilityChange; /** * Removes the display element. */ private removeDisplayElement; /** * Scans document for elements with tracking attributes. */ private scanElements; /** * Observes DOM for added/removed elements with tracking attributes. */ private observeDOM; /** * Checks if element has any tracking attribute. */ private hasTrackingAttr; /** * Creates and styles the floating position indicator. */ private createDisplayElement; } declare class StringVideoAutoplay extends StringModule { constructor(context: StringContext); onObjectConnected(object: StringObject): void; private onEnterObject; private onLeaveObject; private tryPlay; } /** * Represents a rule for triggering actions based on scroll events. */ interface ScrollMarkRule { /** * A unique identifier for the scroll trigger rule. */ id: string; /** * The offset value (in pixels) from the top of the viewport where the rule is triggered. */ offset: number; /** * The direction of the scroll that activates the rule. * - `"forward"`: Trigger when scrolling down. * - `"backward"`: Trigger when scrolling up. * - `"any"`: Trigger regardless of scroll direction. */ direction: "forward" | "backward" | "any"; /** * Optional callback function to execute when the scroll position enters the trigger zone. */ onEnter?: () => void; /** * Optional callback function to execute when the scroll position leaves the trigger zone. */ onLeave?: () => void; /** * Optional configuration for toggling a CSS class on a target element. */ toggleClass?: { /** * The target HTML element on which the class will be toggled. */ target: HTMLElement; /** * The name of the CSS class to toggle. */ className: string; }; /** * Internal state tracking whether the rule is currently active. * prevents redundant callbacks and class toggles. */ isActive?: boolean; } declare class StringSequence extends StringModule { private activeStep; private leavingStep; private transitions; private elementIndex; private triggerElements; private globalSettings; private stateRegistered; private lastEnteredStep; private defaultDuration; private initialized; private static readonly ALL_STATES; constructor(context: StringContext); onInit(): void; private scanStandaloneTriggers; private parseGlobalSettingsFromObject; private tryParseGlobalSetting; private applyGlobalSettingsToExistingObjects; private initializeSliders; private tryApplyPendingActiveStep; canConnect(object: StringObject): boolean; onObjectConnected(object: StringObject): void; private ensureStateEventRegistered; private parseTriggerKey; private getMaxStep; private resolveDuration; private resolveDurations; private resolveEasing; private resolveEasings; onObjectDisconnected(object: StringObject): void; private parseSequenceKey; private onTriggerClick; private onSequenceEvent; private startTransition; private handleScrub; private switchInstant; private applyProgress; private setStepState; private setState; onFrame(data: StringData): void; private emitTransitionStart; private emitTransitionProgress; private emitTransitionEnd; private emitStepEnter; private emitStepLeave; private emitActiveState; } type FormField = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement; declare class StringForm extends StringModule { constructor(context: StringContext); initializeObject(globalId: number, object: StringObject, element: HTMLElement, attributes: Record): void; onObjectConnected(object: StringObject): void; onDOMMutate(added: NodeList, removed: NodeList): void; private applyValidationState; private getInteractiveFields; private getFieldRules; private registerField; private unregisterField; private collectInteractiveFieldsFromNode; private isRadioField; private handleMutationAdditions; private handleMutationRemovals; private getFormStateByContainment; private getFormStateByReference; private buildFormState; private registerFieldIndex; private getFieldIndex; private shouldValidateField; private supportsBeforeInputValidation; private requiresContext; private buildContext; private static readonly beforeInputRuleKeys; private static readonly crossFieldRuleKeys; private static readonly serviceAttributePrefixes; getInputKey(field: FormField, idx: number): string; getFieldValue(field: FormField): any; private isServiceFieldAttribute; private isFormFieldElement; private getInputEventType; } declare class StringScroller extends StringModule { constructor(context: StringContext); onObjectConnected(object: StringObject): void; onObjectDisconnected(object: StringObject): void; } /** * Module that provides smooth scrolling behavior for isolated containers. * Allows nested elements to have independent smooth scroll physics similar to the main window. * * Usage: * Add `string="scroll-container"` to any block element. * Optional: `string-lerp="0.1"` to controls the smoothing factor. */ declare class StringScrollContainer extends StringModule { /** * WeakMap storing the state for each managed HTMLElement. */ private states; /** * Initializes the StringScrollContainer module. * Registers the `lerp` attribute configuration. * * @param context The shared StringTune context. */ constructor(context: StringContext); /** * Called when a new object with `string="scroll-container"` is initialized. * Sets up initial state, event listeners, and default styles. * * @param object The StringObject instance being connected. */ onObjectConnected(object: StringObject): void; /** * Called when an object is removed from the DOM or disconnected. * Cleans up the state associated with the element. * * @param object The StringObject instance being disconnected. */ onObjectDisconnected(object: StringObject): void; /** * Main animation loop for the module. * Updates the scroll position of active containers based on their target state. * * @param data Global frame data including time deltas. */ onFrame(data: StringData): void; /** * Called when the window or layout is resized. * Recalculates scroll boundaries for all managed containers. */ onResize(): void; /** * Recalculates the maximum scrollable distance for a container. * * @param el The scroll container element. * @param state The state object associated with the element. */ private measure; /** * Handles the mouse wheel event to apply custom scroll physics. * Intercepts the event to prevent native scrolling and updates the target position. * Allows event propagation if scrolling past the boundaries (scroll chaining). * * @param e The WheelEvent triggered by the user. * @param el The target scroll container element. * @param state The state object associated with the element. */ private handleWheel; /** * Placeholder for global wheel handler if needed by generic StringModule interface. * Specific handling is done via local event listeners in `handleWheel`. * * @param e Global WheelEvent. */ onWheel(e: WheelEvent): void; /** * Handles native scroll events (dragbars, keyboard, touch). * Syncs the internal state with the native scroll position if the custom animation is not active. * * @param e The Scroll event. * @param el The target scroll container element. * @param state The state object associated with the element. */ private onNativeScroll; /** * Updates the element's scrollTop property by interpolating towards the target. * Stops the animation if the difference is negligible. * * @param el The scroll container element. * @param state The state object associated with the element. */ private updateScroll; } declare class StringProgressPart extends StringModule { constructor(context: StringContext); onObjectConnected(object: StringObject): void; onObjectDisconnected(object: StringObject): void; } type Job = () => void; declare class FrameDOM { private measureQueue; private mutateQueue; private scheduled; measure(fn: Job): void; mutate(fn: Job): void; schedule(): void; flush(): void; } declare const frameDOM: FrameDOM; declare class StringRandom extends StringModule { constructor(context: StringContext); onObjectConnected(object: StringObject): void; } declare class ScrollController { protected context: StringContext; protected document: Document; name: string; isProg: boolean; isParallaxEnabled: boolean; protected _isVertical: boolean; protected _scrollDirState: number; protected _lastAppliedDirState: number; protected isLastBottomScrollDirection: boolean; protected scrollTriggerRules: Array; protected isActive: boolean; set scrollDirection(dir: "vertical" | "horizontal"); constructor(context: StringContext); onChangeDirection: () => void; onScrollStart: () => void; onScrollStop: () => void; onCalcUpdate(): void; onFrame(): void; onWheel(e: any): void; onScroll(e: any): void; onTouchStart(e: TouchEvent): void; onTouchMove(e: TouchEvent): void; onTouchEnd(e: TouchEvent): void; disableScrollEvents(): void; enableScrollEvents(): void; activate(): void; deactivate(): void; destroy(): void; protected updateScrollDirection(isDown: boolean): void; protected clearScrollingClasses(): void; protected triggerScrollRules(): void; addScrollMark(rule: ScrollMarkRule): void; removeScrollMark(id: string): void; scrollTo(position: number, immediate?: boolean): void; } interface StringDevtoolState { active: boolean; } interface StringDevtoolHotkey { key: string; shiftKey?: boolean; ctrlKey?: boolean; altKey?: boolean; metaKey?: boolean; } interface StringDevtoolSubBadge { id: string; icon: string; label: string; /** Extra attribute used as a CSS selector hook (e.g. "data-string-grid-global-toggle"). */ selectorAttribute?: string; /** Additional data-* attributes applied to the badge button. */ attributes?: Record; onClick: (anchorElement?: HTMLElement) => void; } interface StringDevtoolDefinition { id: string; label: string; icon: string; order?: number; group?: number; hotkey?: StringDevtoolHotkey; subBadges?: StringDevtoolSubBadge[]; getState: () => StringDevtoolState; setActive: (active: boolean) => void; subscribe?: (listener: (state: StringDevtoolState) => void) => () => void; } interface StringDevtoolProvider { getDevtoolDefinition(): StringDevtoolDefinition | null; } declare class StringDevViewportLayer { private readonly id; private readonly zIndex; private screenRoot; private world; private screen; private worldHost; private hostPositionWasPatched; private hostPositionInlineValue; constructor(id: string, zIndex: number); ensure(host?: HTMLElement | null): HTMLDivElement; getElement(): HTMLDivElement | null; getWorldElement(host?: HTMLElement | null): HTMLDivElement; getScreenElement(): HTMLDivElement; destroy(): void; private attachWorldToHost; private restoreHostPosition; } declare class StringDevOverlayRegistry { private static instance; private readonly layers; static getInstance(): StringDevOverlayRegistry; acquire(id: string, zIndex: number): StringDevViewportLayer; release(id: string): void; } interface StringDevModuleDefinitionConfig { id: string; label: string; icon: string; order?: number; group?: number; hotkey?: StringDevtoolHotkey; } interface StringDevConnectsConfig { /** If true, connects to every StringObject (overlay default). If false, only explicit matches below + dev-inspect fallback. */ global?: boolean; /** Connect to objects whose string="…" token list includes any of these keys. */ keys?: string[]; /** Connect to objects whose DOM element has any of these attributes present. */ attributes?: string[]; } interface StringDevOverlayConfig { /** Unique layer name, e.g. "devtools-progress" */ layerName: string; /** Z-index for the viewport layer */ zIndex: number; /** Data-attribute added to the layer root, e.g. "data-string-progress-layer" */ layerAttribute?: string; /** Overlay ID used for the anchor/collision system. Omit if not needed. */ overlayId?: string; /** Whether the overlay starts enabled before dock preferences apply. Default: false */ defaultEnabled?: boolean; /** For badge overlay modules: data-attribute placed on each badge element */ badgeAttribute?: string; } interface StringDevModuleConfig extends StringDevModuleDefinitionConfig { /** Declare CSS styles to inject once. Can be a string or a lazy getter. */ styles?: string | (() => string); /** Overlay layer configuration. Declare for any module that uses a viewport layer. */ overlay?: StringDevOverlayConfig; /** Declare which StringObjects this module connects to. Replaces htmlKey assignment in constructor. */ connects?: StringDevConnectsConfig; } declare class StringDevModule extends StringModule implements StringDevtoolProvider { /** Declare module metadata statically. Subclasses override this. */ static devtool: StringDevModuleConfig | null; protected readonly overlayRegistry: StringDevOverlayRegistry; private readonly acquiredViewportLayers; private readonly devtoolListeners; private hotkeyHandler; protected devtoolConfig: StringDevModuleDefinitionConfig | null; constructor(context: StringContext); protected get respectSelfDisable(): boolean; protected get connectsConfig(): StringDevConnectsConfig | undefined; canConnect(object: StringObject): boolean; protected getStyleScopeId(stylesText: string): string; protected getStyles(): string | null; getDevtoolDefinition(): StringDevtoolDefinition | null; protected getDevtoolSubBadges(): StringDevtoolSubBadge[]; protected configureDevtool(config: StringDevModuleDefinitionConfig): void; protected bindDevtoolHotkey(hotkey?: StringDevtoolHotkey): void; protected emitDevtoolState(active?: boolean): void; protected acquireViewportLayer(id: string, zIndex: number): StringDevViewportLayer; protected releaseViewportLayer(id: string): void; protected ensureStyle(styleId: string, cssText: string): HTMLStyleElement; protected getWorldHost(): HTMLElement; protected getDevtoolActiveState(): boolean; protected setDevtoolActiveState(_active: boolean): void; destroy(): void; } declare function buildGridCSS(): string; /** * StringDevLayout — developer utility module for layout overlays. * * Usage: *
...
* * No configuration attributes needed. All configuration happens * through the interactive HUD panel (hover top-right corner). * * Supports multiple grid types via the adapter pattern: * - Columns, Rows, Center * - Rule of Thirds, Phi Grid, Golden Rectangle, Harmonic Armature * - Extensible via `st.use(StringDevLayout, { adapters: [MyAdapter] })` */ declare class StringDevLayout extends StringDevModule { private gridManager; private viewportLayer; private overlayLayer; private overlays; private huds; private elementMap; private triggerEntries; private triggerMeasurements; private enabled; private needsMeasure; private hasPendingMutate; private globalHost; private globalOverlay; private globalHUD; private globalSubBadge; static devtool: { id: string; label: string; icon: string; order: number; group: number; hotkey: { key: string; shiftKey: boolean; }; styles: typeof buildGridCSS; connects: { global: boolean; keys: string[]; }; }; constructor(context: StringContext); onInit(): void; protected getDevtoolSubBadges(): StringDevtoolSubBadge[]; onObjectConnected(object: StringObject): void; onObjectDisconnected(object: StringObject): void; onResize(): void; onScroll(): void; onScrollMeasure(): void; onMutate(): void; onDOMRebuild(): void; destroy(): void; setEnabled(enabled: boolean): void; isEnabled(): boolean; protected getDevtoolActiveState(): boolean; protected setDevtoolActiveState(active: boolean): void; private handleAdd; private handleRemove; private handleToggle; private handleSettingChange; private handleReorder; private handleMoveToEnd; private handleSelectLayout; private handleUpdateLayoutMinWidth; private handleAddLayout; private handleRemoveLayout; private handleRenameInstance; private handleRenamePanelTitle; private handleHUDOpen; private handleHUDClose; private handleLayoutPanelOpen; private handleLayoutPanelClose; private handleExport; private handleImport; private renderElement; private syncToResolved; private syncSelectedLayoutToViewport; private refreshHUD; private ensureGlobalGrid; private syncGlobalHostSize; private renderGlobal; private refreshGlobalHUD; private toggleGlobalPanel; private syncGlobalSubBadgeState; private positionGlobalHudAtAnchor; private destroyGlobalGrid; private destroyElement; private ensureTriggerLayer; private applyTriggerLayerState; private scheduleTriggerSync; private collectTriggerMeasurements; private measureTrigger; private applyTriggerMeasurement; protected getWorldHost(): HTMLElement; private getObjectDocY; private getViewportScrollLeft; private getViewportScrollTop; private resolveTriggerStackOffset; private registerBuiltInAdapters; private registerExternalAdapters; } /** * Discriminated union of all UI field descriptors. * Each devtool module returns an array of these to describe its settings panel. */ type StringDevUIFieldDescriptor = StringDevUIFieldNumber | StringDevUIFieldRange | StringDevUIFieldColor | StringDevUIFieldSelect | StringDevUIFieldToggle | StringDevUIFieldDivider; interface StringDevUIFieldDisabledWhen { readonly key: string; readonly equals: string | number | boolean; } interface StringDevUIFieldBase { readonly disabledWhen?: StringDevUIFieldDisabledWhen; } interface StringDevUIFieldNumber extends StringDevUIFieldBase { readonly type: "number"; readonly key: string; readonly label: string; readonly default: number; readonly min?: number; readonly max?: number; readonly step?: number; } interface StringDevUIFieldRange extends StringDevUIFieldBase { readonly type: "range"; readonly key: string; readonly label: string; readonly default: number; readonly min: number; readonly max: number; readonly step?: number; /** Multiplies the stored value for display/editing in the UI. */ readonly displayMultiplier?: number; /** Optional UI step in display-space (e.g. 10 for 0..100 opacity UX). */ readonly displayStep?: number; /** Optional display-only suffix rendered next to the numeric value. */ readonly suffix?: string; /** When provided, a compact unit dropdown is shown next to the value input. */ readonly units?: ReadonlyArray<{ value: string; label: string; }>; /** Default unit value (used when no persisted unit exists). */ readonly defaultUnit?: string; } interface StringDevUIFieldColor extends StringDevUIFieldBase { readonly type: "color"; readonly key: string; readonly label: string; readonly default: string; } interface StringDevUIFieldSelect extends StringDevUIFieldBase { readonly type: "select"; readonly key: string; readonly label: string; readonly default: string; readonly options: ReadonlyArray<{ value: string; label: string; }>; } interface StringDevUIFieldToggle extends StringDevUIFieldBase { readonly type: "toggle"; readonly key: string; readonly label: string; readonly default: boolean; } interface StringDevUIFieldDivider { readonly type: "divider"; readonly label?: string; } /** * Abstract base class for all grid adapters. * * Each adapter is a self-contained unit that: * - Declares its own default settings * - Describes its UI schema for the settings panel * - Renders itself into an SVG overlay * * To create a new grid type, extend this class and implement * all abstract members. The system handles everything else. */ declare abstract class GridAdapter { /** Unique type key used for serialization and registry lookup */ abstract readonly type: string; /** Human-readable label shown in the HUD menu */ abstract readonly label: string; /** SVG icon string (inline SVG markup) */ abstract readonly icon: string; /** * Returns the default settings for this adapter. * These are used when a new grid instance is created. */ abstract getDefaults(): Record; /** * Returns the UI field descriptors that GridUIBuilder * uses to construct the settings panel. */ abstract getUISchema(): StringDevUIFieldDescriptor[]; /** * Renders the grid into the given SVG element. * * @param svg The SVG overlay element (same size as target) * @param width Element width in px * @param height Element height in px * @param settings Current settings for this instance */ abstract render(svg: SVGSVGElement, width: number, height: number, settings: Record): void; /** * Removes all elements previously rendered by this adapter. * Default implementation clears the adapter's group element. */ clear(svg: SVGSVGElement, instanceId: string): void; /** * Creates or retrieves a group element scoped to a grid instance. * All rendering should happen inside this group for clean cleanup. */ protected getGroup(svg: SVGSVGElement, instanceId: string): SVGGElement; /** * Helper: creates an SVG line element. */ protected createLine(x1: number, y1: number, x2: number, y2: number, color: string, opacity: number, strokeWidth?: number): SVGLineElement; /** * Helper: creates an SVG rect element. */ protected createRect(x: number, y: number, width: number, height: number, fill: string, opacity: number): SVGRectElement; /** * Converts a value from the given unit to pixels. * * @param value Raw numeric value * @param unit "px" | "%" | "vw" | "vh" | "em" | "rem" * @param dimension Reference dimension (element width or height) for "%" mode */ protected resolveUnit(value: number, unit: string, dimension: number, referenceElement?: Element | null): number; /** * Helper: creates an SVG path element. */ protected createPath(d: string, stroke: string, opacity: number, strokeWidth?: number, fill?: string): SVGPathElement; } /** * StringDevRulers — developer utility module for guide-line rulers. * * Usage: * st.use(StringDevRulers) * st.use(StringDevRulers, { triggers: [...], grid: { type: "columns", count: 12, ... } }) * * Default trigger: Shift + R * * Settings: * triggers — array of trigger descriptors (keyboard / element / event) * rulers-snap — grid step in px (0 = off) * rulers-snap-elements — snap to [string] element edges (default: true) * rulers-snap-threshold — snap pull radius in px (default: 8) * rulers-snap-selector — CSS selector for snap targets * grid — RulersLayoutGrid | RulersLayoutGrid[] * * Snap visual feedback: * amber → snapping to a DOM element edge / center * green → snapping to a layout-grid line */ declare class StringDevRulers extends StringDevModule { private manager; private overlay; private visible; private dockDisabled; private currentModeId; private readonly modeStore; private readonly viewportLayer; private _kbHandlers; private _elHandlers; private _evHandlers; static devtool: { id: string; label: string; icon: string; order: number; group: number; hotkey: { key: string; shiftKey: boolean; }; styles: string; connects: { global: boolean; keys: string[]; }; }; constructor(context: StringContext); onInit(): void; onSettingsChange(): void; onSubscribe(): void; onUnsubscribe(): void; onFrame(data: StringData): void; onResize(): void; destroy(): void; toggle(): void; show(): void; hide(): void; clear(): void; isVisible(): boolean; protected getDevtoolActiveState(): boolean; protected setDevtoolActiveState(active: boolean): void; protected getDevtoolSubBadges(): StringDevtoolSubBadge[]; private _bindTriggers; private _unbindTriggers; private _applyAction; private setVisible; private setDockActive; private mountOverlay; private cycleMode; private switchMode; private applyStyleSettings; private clearStyleSettings; /** Normalises the `grid` setting to RulersLayoutGrid[] (or undefined). */ private _resolveGrids; private syncOverlayMetrics; private pushScrollToOverlay; } type StringDevtoolsOverlayId = string; interface AnchorPoint { docX: number; docY: number; } type OverlayAxis = "y" | "x"; type OverlayAnchor = "start" | "end"; interface OverlayBaseMetrics { visible: boolean; contentX: number; contentY: number; width: number; height: number; isOffscreen: boolean; baseAnchorX: number; baseAnchorY: number; collisionOffset: number; axis: OverlayAxis; primarySize: number; crossSize: number; primaryContentOffset: number; viewportPrimarySize: number; } interface OverlayObjectGeometry { contentX: number; contentY: number; width: number; height: number; } interface StringDevOverlayBadgeInit { targetId: string; selectorAttribute?: string; depth?: number; attributes?: Record; } interface StringDevOverlayBadgeState { visible?: boolean; active?: boolean; disabled?: boolean; title?: string; html?: string; label?: string; attributes?: Record; } declare abstract class StringDevOverlayModule extends StringDevModule { private _viewportLayer?; private _badgeLayer?; private _hudLayer?; protected get viewportLayer(): StringDevViewportLayer; protected get badgeLayer(): StringDevViewportLayer; protected get hudLayer(): StringDevViewportLayer; protected readonly entries: Map; protected readonly measurements: Map; protected enabled: boolean; protected needsMeasure: boolean; protected hasPendingMutate: boolean; private _rafId; private _pendingSingleIds; private readonly onOverlayLayoutChangeBind; private get _overlayConfig(); /** Override to provide the overlay ID for the anchor/collision system. */ protected get overlayId(): StringDevtoolsOverlayId | null; /** Override to declare how many badge slots this overlay occupies. */ protected get overlayBadgeCount(): number; /** Override to define your viewport layer name. Falls back to devtool.overlay.layerName. */ protected get layerName(): string; /** Override to define your viewport layer z-index. Falls back to devtool.overlay.zIndex. */ protected get layerZIndex(): number; /** Override to define the data-attribute added to the layer root. Falls back to devtool.overlay.layerAttribute. */ protected get layerAttribute(): string; /** Override when an overlay module should start enabled before dock preferences apply. Falls back to devtool.overlay.defaultEnabled. */ protected get defaultEnabled(): boolean; constructor(context: StringContext); onInit(): void; onObjectConnected(object: StringObject): void; onObjectDisconnected(object: StringObject): void; setEnabled(enabled: boolean): void; isEnabled(): boolean; protected getDevtoolActiveState(): boolean; protected setDevtoolActiveState(active: boolean): void; /** Create DOM and return state for the given element */ protected abstract createOverlayEntry(object: StringObject): TEntry | null; /** Clean up DOM and listeners for the given element */ protected abstract destroyOverlayEntry(entry: TEntry): void; /** Produce a custom measurement state utilizing the provided base metrics */ protected abstract measureEntry(entry: TEntry, baseMetrics: OverlayBaseMetrics): TMeasurement; /** Render DOM efficiently utilizing `styleTxn` */ protected abstract applyMeasurement(entry: TEntry, measurement: TMeasurement | undefined): void; /** Called when `setEnabled` state flips, allowing subclasses to show/hide specific entries */ protected onEnabledChange(_enabled: boolean): void; onScroll(): void; onScrollMeasure(): void; onMutate(): void; onResize(): void; onDOMRebuild(): void; /** * Immediate synchronous full sync — use only when instant visual response * is required (e.g. setEnabled). For everything else prefer scheduleSync(). */ protected scheduleFullSync(): void; /** * Deferred full sync — batches multiple calls within the same animation * frame into a single measure+flush pass. Use for resize, layout changes, * object connected, and any other non-immediate triggers. */ protected scheduleSync(): void; /** * Deferred single-entry sync — measures and flushes only the given entry. * Multiple calls for different entries within the same frame are batched * together into one styleTxn flush. Use for per-object events like * object:inview or slider input where only one entry changes. */ protected scheduleSingleSync(entry: TEntry): void; protected collectMeasurements(): void; protected flushMeasurements(): void; protected ensureLayer(): HTMLDivElement; protected applyEnabledState(): void; private syncSlotRegistration; protected resolveOverlayTargetId(object: StringObject): string; protected resolveOverlayObjectDepth(element: HTMLElement): number; protected createOverlayBadge(init: StringDevOverlayBadgeInit): HTMLButtonElement; protected applyOverlayBadgeState(badge: HTMLElement, state: StringDevOverlayBadgeState): void; protected applyOverlayBadgePosition(badge: HTMLElement, measurement: { visible: boolean; docX: number; docY: number; translate?: string; } | undefined): void; protected getOverlayTargetLabel(object: StringObject): string; protected getViewportAnchorOffset(anchor: OverlayAnchor, metrics: OverlayBaseMetrics): number; protected getOverlayAnchorAdjustment(_object: StringObject, _anchor: AnchorPoint, _metrics?: { contentX: number; contentY: number; width: number; height: number; }): AnchorPoint; protected resolveRulerPanelOffset(contentX: number, contentY: number): { x: number; y: number; }; protected computeBaseMetrics(entry: any): OverlayBaseMetrics; protected getHiddenMetrics(): OverlayBaseMetrics; protected getObjectDocY(object: StringObject): number; protected resolveOverlayObjectGeometry(object: StringObject, element?: HTMLElement): OverlayObjectGeometry; protected getViewportScrollLeft(): number; protected getViewportScrollTop(): number; protected resolveLiveElementMetrics(element: HTMLElement, rect: DOMRect): { docLeft?: number; docTop?: number; width: number; height: number; }; destroy(): void; } type StringDevBadgeSlot = "top-left" | "top-right" | "bottom-right" | "bottom-left"; interface StringDevBadgeSlotConfig { gap?: number; offsetX?: number; offsetY?: number; } interface StringDevBadgeDescriptor { id: string; slot?: StringDevBadgeSlot; group?: string; selectorAttribute?: string; depth?: number; attributes?: Record; gap?: number; offsetX?: number; offsetY?: number; } interface StringDevManagedBadge { id: string; descriptor: StringDevBadgeDescriptor; element: HTMLButtonElement; } interface StringDevBadgePositionMeasurement { visible: boolean; docX: number; docY: number; translate?: string; } interface StringDevBadgeMeasurement { visible: boolean; badges: Record; } interface StringDevBadgeEntry { object: StringObject; targetId: string; badge: HTMLButtonElement; depth: number; extra: TExtra; cleanup: Array<() => void>; badges: Map; groups: Map; } declare abstract class StringDevBadgeOverlayModule extends StringDevOverlayModule, TMeasurement> { protected get badgeAttribute(): string; protected createOverlayEntry(object: StringObject): StringDevBadgeEntry; protected destroyOverlayEntry(entry: StringDevBadgeEntry): void; protected measureEntry(entry: StringDevBadgeEntry, metrics: OverlayBaseMetrics): TMeasurement; protected applyMeasurement(entry: StringDevBadgeEntry, measurement: TMeasurement | undefined): void; protected onEnabledChange(_enabled: boolean): void; protected createBadgeExtra(_object: StringObject, _badge: HTMLButtonElement, _targetId: string, _depth: number): TExtra; protected destroyBadgeExtra(_entry: StringDevBadgeEntry): void; protected bindBadge(_entry: StringDevBadgeEntry): Array<() => void> | void; protected resolveBadgeDepth(object: StringObject): number; protected getBadgeSlotConfig(): Partial>; protected getBadgeDescriptors(object: StringObject, targetId: string, depth: number): Array; protected getInitialBadgeAttributes(_object: StringObject, _targetId: string, _depth: number): Record | undefined; protected applyBadgeEnabledState(entry: StringDevBadgeEntry): void; protected renderBadge(entry: StringDevBadgeEntry): void; protected afterBadgeMeasurement(_entry: StringDevBadgeEntry, _measurement: TMeasurement | undefined): void; protected abstract onBadgeClick(entry: StringDevBadgeEntry, event: MouseEvent, badge: StringDevManagedBadge): void; protected abstract getBadgeState(entry: StringDevBadgeEntry, badge?: StringDevManagedBadge): StringDevOverlayBadgeState; private resolveBadgeSlotConfig; private resolveBadgePosition; } interface InviewExtra { outline: HTMLDivElement; enterConnector: HTMLDivElement; exitConnector: HTMLDivElement; enterMarker: HTMLDivElement; exitMarker: HTMLDivElement; enterMarkerLabel: HTMLSpanElement; exitMarkerLabel: HTMLSpanElement; } interface InviewMeasurement extends StringDevBadgeMeasurement { overlayVisible: boolean; badgeVisible: boolean; markersVisible: boolean; inview: boolean; outlineDocX: number; outlineDocY: number; outlineWidth: number; outlineHeight: number; enterConnectorDocX: number; enterConnectorDocY: number; enterConnectorWidth: number; enterConnectorHeight: number; exitConnectorDocX: number; exitConnectorDocY: number; exitConnectorWidth: number; exitConnectorHeight: number; enterMarkerDocX: number; enterMarkerDocY: number; enterMarkerFlippedY: boolean; exitMarkerDocX: number; exitMarkerDocY: number; exitMarkerFlippedY: boolean; } declare class StringDevInview extends StringDevBadgeOverlayModule { static devtool: { id: string; label: string; icon: string; order: number; group: number; hotkey: { key: string; shiftKey: boolean; }; styles: string; overlay: { layerName: string; zIndex: number; layerAttribute: string; overlayId: string; defaultEnabled: boolean; }; connects: { global: boolean; }; }; protected get overlayBadgeCount(): number; protected getDevtoolSubBadges(): StringDevtoolSubBadge[]; private entryEnabled; private markerSizeCache; private readonly disabledStore; private readonly markerStore; private disabledTargetIds; private markerOffsets; private stableCoarseViewportWidth; private stableCoarseViewportHeight; protected getBadgeDescriptors(_object: StringObject, _targetId: string, _depth: number): Array; protected createBadgeExtra(object: StringObject, _badge: HTMLButtonElement, targetId: string, _depth: number): InviewExtra; protected destroyBadgeExtra(entry: StringDevBadgeEntry): void; protected bindBadge(entry: StringDevBadgeEntry): Array<() => void>; protected measureEntry(entry: StringDevBadgeEntry, metrics: OverlayBaseMetrics): InviewMeasurement; protected afterBadgeMeasurement(entry: StringDevBadgeEntry, measurement: InviewMeasurement | undefined): void; protected onBadgeClick(entry: StringDevBadgeEntry, _event: MouseEvent, badge: StringDevManagedBadge): void; protected getBadgeState(entry: StringDevBadgeEntry, badge?: StringDevManagedBadge): StringDevOverlayBadgeState; private hiddenMeasurement; private getInviewBadgeState; private toggleInview; private isInviewBadgeActive; private isEntryEnabled; private setEntryEnabled; private disableAllOffsets; private bindMarkerDrag; private getMarkerOffset; private setMarkerOffset; private syncMarkerContent; private getViewportMarkerLabel; private measureMarkerSize; private resolveLiveStickyGeometry; private clampMarkerPercentInViewport; private clampMarkerPercentInClientViewport; private syncCompactMode; private syncCompactModeForExtra; private setAttributeIfChanged; private getStableViewportHeight; } interface ProgressEntry { object: StringObject; hud: HTMLDivElement; badge: HTMLButtonElement; onBadgeClick: (event: MouseEvent) => void; } interface ProgressMeasurement { visible: boolean; docX: number; docY: number; targetId: string; progress: number; rawProgress: number; startPosition: number; endPosition: number; currentScroll: number; key: string; } declare class StringDevProgress extends StringDevOverlayModule { static devtool: { id: string; label: string; icon: string; order: number; group: number; hotkey: { key: string; shiftKey: boolean; }; styles: string; overlay: { layerName: string; zIndex: number; layerAttribute: string; overlayId: string; }; connects: { keys: string[]; }; }; private openTargetLabel; private panelRoot; private panelTitle; private panelSlider; private panelValue; private panelEasedValue; private panelPlayForwardButton; private panelPlayBackwardButton; private autoplayRaf; private autoplayDirection; private autoplayProgress; private readonly onPanelSliderInputBind; private unbindOutsideClick; constructor(context: StringContext); onInit(): void; destroy(): void; protected createOverlayEntry(object: StringObject): ProgressEntry; protected destroyOverlayEntry(entry: ProgressEntry): void; protected measureEntry(entry: ProgressEntry, metrics: OverlayBaseMetrics): ProgressMeasurement; protected applyMeasurement(entry: ProgressEntry, measurement: ProgressMeasurement | undefined): void; protected onEnabledChange(enabled: boolean): void; private applyEntryEnabledState; private openPanel; private closePanel; private closeAllPanels; private collectEntryHuds; private startAutoplay; private stopAutoplay; private syncPlayButtonState; private getEntryRange; private resolveEntryRawProgress; private resolveEasedProgress; private setEntryProgressOverride; private clearEntryProgressOverride; private clearAllProgressOverrides; private applyObjectProgress; private ensurePanel; private onPanelSliderInput; private renderPanel; private findEntryByTargetLabel; } interface DevtoolsIconDef { id: string; viewBox: string; content: string; } type DevtoolsIconSize = 12 | 16 | 20; declare class StringDevIconRegistry { private static instance; private spriteRoot; private constructor(); static getInstance(): StringDevIconRegistry; register(icon: DevtoolsIconDef): void; resolve(size: DevtoolsIconSize, name: string, ...modifiers: string[]): string; private ensureSprite; } declare function resolveDevtoolsIcon(size: DevtoolsIconSize, name: string, ...modifiers: string[]): string; type StringDevStyleTokens = Record; declare function buildDevtoolsThemeBlock(selectors: string | string[], overrides?: StringDevStyleTokens): string; declare function ensureStringDevtoolsSharedStyles(): HTMLStyleElement | null; /** * What the trigger does when activated. * Defaults to "toggle" when not specified. */ type RulersTriggerAction = "toggle" | "show" | "hide"; /** * Keyboard shortcut trigger. * * @example * { type: "keyboard", key: "R", shiftKey: true } */ interface KeyboardRulersTrigger { type: "keyboard"; /** The KeyboardEvent.key value (case-sensitive, e.g. "R", "g", "F2"). */ key: string; shiftKey?: boolean; ctrlKey?: boolean; altKey?: boolean; metaKey?: boolean; action?: RulersTriggerAction; } /** * DOM element trigger — binds to one or more elements matching a CSS selector. * The element(s) must exist in the DOM when the module subscribes (at `start()` time). * For dynamically-added controls, prefer `type: "event"` instead. * * @example * { type: "element", selector: "#rulers-toggle-btn" } * { type: "element", selector: ".dev-toolbar [data-action='rulers']", event: "pointerdown" } */ interface ElementRulersTrigger { type: "element"; /** CSS selector. All matching elements are bound. */ selector: string; /** DOM event type. Defaults to "click". */ event?: string; action?: RulersTriggerAction; } /** * StringTune event-bus trigger — reacts to a named event emitted via the event manager. * Useful for toolbar integrations, programmatic control, and cross-module communication. * * @example * { type: "event", name: "dev:rulers:toggle" } * * Activate via: * stringTune.emit("dev:rulers:toggle", null) */ interface EventRulersTrigger { type: "event"; /** Event name on the StringTune event bus. */ name: string; action?: RulersTriggerAction; } /** * Discriminated union of all supported ruler trigger descriptors. */ type StringRulersTrigger = KeyboardRulersTrigger | ElementRulersTrigger | EventRulersTrigger; /** * Column-based layout grid. * * Displays a fixed set of equally-spaced column bands across the viewport. * Column width is derived from the viewport width, margins, count, and gap. * * @example * { type: "columns", count: 12, marginLeft: 40, marginRight: 40, gap: 20 } */ interface ColumnsLayoutGrid { type: "columns"; /** Number of columns. */ count: number; /** Space reserved on the left edge of the viewport (px). Default: 0. */ marginLeft?: number; /** Space reserved on the right edge of the viewport (px). Default: 0. */ marginRight?: number; /** Gutter between columns (px). Default: 0. */ gap?: number; /** Fill color for column bands. Default: "rgba(255, 0, 80, 0.08)". */ color?: string; } /** * Row-based layout grid. * * Displays repeating horizontal stripes across the full document height. * Stripes scroll with the page content. * * @example * { type: "rows", height: 8, gap: 0 } */ interface RowsLayoutGrid { type: "rows"; /** Height of each row band (px). */ height: number; /** Gap between row bands (px). Default: 0. */ gap?: number; /** Fill color for row bands. Default: "rgba(0, 120, 255, 0.06)". */ color?: string; } type RulersLayoutGrid = ColumnsLayoutGrid | RowsLayoutGrid; interface ModuleBatchContext { module: StringModule; object: StringObject; element: HTMLElement; attributes: Record; globalId: number; windowSize: number; } declare class DOMBatcher { private readQueue; private writeQueue; private computeQueue; private isProcessing; private pendingFrame; private rectCache; private dimensionCache; scheduleRead(task: () => void, priority?: number): void; scheduleCompute(task: () => void, priority?: number): void; scheduleWrite(task: () => void, priority?: number): void; batchModuleInitialization(contexts: ModuleBatchContext[]): void; getCachedRect(element: HTMLElement): DOMRect | undefined; getCachedDimensions(element: HTMLElement): { width: number; height: number; } | undefined; private scheduleFlush; private flush; flushSync(): void; clear(): void; } declare class StringTune { private static readonly DEVTOOLS_ACCESS_URL; private static readonly DEVTOOLS_LOG_PREFIX; private static readonly DEVTOOLS_ARTIFACT_SELECTORS; /** Bound handler for the scroll start event */ private onScrollStartBind; /** Bound handler for the scroll stop event */ private onScrollStopBind; /** Bound handler for the scroll direction change event */ private onDirectionChangeBind; /** Bound handler for scroll mode/config changes */ private onScrollConfigChangeBind; /** Bound wheel event handler */ private onWheelBind; /** Bound scroll event handler */ private onScrollBind; /** Bound resize event handler */ private onResizeBind; /** Bound mouse move handler */ private onMouseMoveBind; /** Bound scroll to handler */ private onScrollToBind; private onDOMChangedBind; private onContainerTransitionEndBind; private onResizeObserverBind; private pendingScroll; private lastScrollEmitted; private observerContainerMutation; private pendingResizeRaf; private pendingResizeForce; /** Singleton instance of StringTune */ private static i; /** Root scrollable element (typically ) */ private root; /** Window object (used for event bindings and dimensions) */ private window; /** Previous window width for resize diff check */ private prevWidth; /** Previous window height for resize diff check */ private prevHeight; /** Manages all modules registered in the system */ private moduleManager; /** Manages scroll modes and active scroll engine */ private scrollManager; /** Manages all interactive objects (elements with `string-*` attributes) */ private objectManager; /** Central event manager for internal pub-sub logic */ private eventManager; /** Handles custom cursor logic (if enabled) */ private cursorController; /** Provides default utility tools (parsers, interpolation, etc.) */ private tools; /** Main loop used for frame updates (with fixed FPS) */ private loop; /** Global reactive data store (scroll, viewport, etc.) */ private data; /** Context shared across all modules (events, data, tools, settings) */ private context; /** Caches the center positions of string objects. */ private centers; /** Tracks hover states of string objects. */ private hoverManager; private devtools; private devtoolsFpsLastSampleTime; private devtoolsFpsFrameCount; private observerContainerResize; private devtoolsAccessToken; private devtoolsAccessState; private devtoolsAccessRequestId; private pendingDevtoolUses; private hasStarted; private devtoolsAccessLastMessage; canRebuild: boolean; /** * Sets the scroll position manually. * This overrides all internal scroll states including target and lerped values. * Useful for programmatic jumps or syncing scroll externally. * * @param value The new scroll position in pixels. */ set scrollPosition(value: number); set accessDevtoolToken(value: string); /** * Configures the container element(s) used for scroll tracking. * Accepts either the `Window` object or an `HTMLElement`. * Determines the appropriate internal element references based on the input type * and triggers a resize calculation. * * @param {Window | HTMLElement | any} container The target window or HTML element to associate with scrolling. * Handles `Window`, `HTMLElement`, and potentially other types via fallback. */ set scrollContainer(container: any); /** * Gets the current scroll position in pixels. * This is typically updated every frame. */ get scrollPosition(): number; get scrollHeight(): number; get containerHeight(): number; /** * Sets the base scroll speed for smooth scrolling. * Typically a value between 0 and 1. */ set speed(value: number); /** * Sets the scroll acceleration using a normalized value from 0 to 1. * Internally maps it to a real acceleration value between 0.1 and 0.5. * * @param speed A normalized acceleration factor (0 to 1). */ set speedAccelerate(speed: number); /** * Sets the scroll mode for desktop devices. * Can be 'smooth', 'default', or 'disable'. */ set scrollDesktopMode(mode: ScrollMode); /** * Sets the scroll mode for mobile devices. * Can be 'smooth', 'default', or 'disable'. */ set scrollMobileMode(mode: ScrollMode); set FPSTrackerVisible(visible: boolean); set PositionTrackerVisible(visible: boolean); set domBatcherEnabled(enabled: boolean); set intersectionObserverEnabled(enabled: boolean); private debouncedResize; private constructor(); /** * Returns the singleton instance of StringTune. * If not already created, initializes it. */ static getInstance(): StringTune; /** * Finds and returns an existing module by its class. * Useful for reusing a module instance without re-registering. * * @template T The type of the module to retrieve. * @param type The module class constructor. * @returns The module instance if found, otherwise undefined. */ reuse(type: new (...args: any[]) => T): T | undefined; /** * Instantiates and registers a new module. * Accepts optional per-instance settings that override global settings. * * @param objectClass The module class to instantiate. * @param settings Optional settings specific to this module. */ use(objectClass: typeof StringModule, settings?: any): void; private cleanupExistingDevtoolsArtifacts; private instantiateModule; private shouldDeferDevtoolModule; private validateDevtoolsAccess; private logDevtoolsAccess; private resolveDevtoolsAccessResponse; /** * Registers a new scroll mode (provider) to the system. * Allows integrating custom scroll implementations (e.g. Lenis, Locomotive). * * @param name The unique name for this scroll mode (e.g. 'smooth', 'lenis'). * @param factory A function that receives the StringContext and returns a ScrollController instance, OR a ScrollController class constructor. * * Example: * ```ts * stringTune.registerScrollMode("custom", (context) => new CustomAdapter(context)); * ``` */ registerScrollMode(name: string, factory: ((context: StringContext) => ScrollController) | (new (context: StringContext) => ScrollController)): void; /** * Subscribes to a global event within the system. * * @param eventName The name of the event to listen for. * @param callback The function to call when the event is triggered. * @param id Optional subscription ID (for easier management). */ on(eventName: string, callback: EventCallback, id?: string): void; emit(eventName: string, data: any): void; /** * Unsubscribes from a global event. * * @param eventName The name of the event. * @param callback The previously registered callback. * @param id Optional ID used during subscription. */ off(eventName: string, callback: EventCallback, id?: string): void; /** * Adds a scroll trigger rule that activates when the user scrolls past a defined offset * in a specific direction. This can be used to toggle CSS classes or execute callbacks * when elements come into view or go out of view. * * @param rule - The scroll trigger configuration object. * - `id`: A unique identifier for this rule. * - `offset`: The vertical scroll offset (in pixels) where the rule should activate. * - `direction`: Defines the scroll direction required to activate the rule. * Can be `"forward"`, `"backward"`, or `"any"`. * - `onEnter`: (Optional) A function that will be called when the scroll position enters the trigger zone * in the specified direction. * - `onLeave`: (Optional) A function that will be called when the scroll position leaves the trigger zone * or scrolls in the opposite direction. * - `toggleClass`: (Optional) An object defining a class toggle behavior. * It contains a target element and a class name to be added when the trigger is active * and removed when it's not. */ addScrollMark(rule: ScrollMarkRule): void; /** * Removes a scroll trigger by its unique identifier. * * @param id - The unique identifier of the scroll trigger to be removed. */ removeScrollMark(id: string): void; /** * Starts the scroll engine and initializes all listeners, observers, and modules. * * @param fps Desired frames per second for the update loop. */ start(fps: number): void; /** * Initializes all DOM elements with `string` or `string-copy-from` attributes. * Registers them with the object manager and triggers resize/scroll/frame hooks. */ private initObjects; /** * Sets global fallback settings for all modules. * These can be overridden by module-specific settings during `use(...)`. * * @param settings A key-value map of default settings (e.g. 'offset-top': '-10%'). */ setupSettings(settings: StringSettings): void; private onResizeObserverEvent; private onContainerTransitionEnd; private onDOMChanged; private observeContainerMutations; private queueResize; /** * Handles mouse move event and dispatches it to cursor and modules. * @param e Native mouse move event. */ private onMouseMoveEvent; /** * Handles wheel scroll event and passes it to the scroll engine and modules. * @param e Native wheel event. */ private onWheelEvent; /** * Called when scrolling begins. * Triggers module scroll start lifecycle hook. */ private onScrollStart; /** * Called when scrolling ends. * Triggers module scroll stop lifecycle hook. */ private onScrollStop; /** * Called when scrolling ends. * Triggers module scroll stop lifecycle hook. */ private onDirectionChange; private onScrollConfigChange; private syncDebugScrollState; /** * Called when global or module settings are updated. * Notifies all managers and modules to re-read new settings. */ private onSettingsChange; /** * Handles native scroll event. * Prevents default behavior and triggers internal scroll logic and event emissions. * * @param e The native scroll event. */ private onScrollEvent; /** * Called every frame by the update loop. * Triggers scroll engine, modules, and global `update` event. */ private onUpdateEvent; private updateDevtoolsFPS; /** * Handles resize events from scroll container or window. * Ignores height-only changes on mobile to prevent layout jumps. * Rebuilds layout and triggers module resize if size really changed. */ onResize(force?: boolean): void; invalidateCenter(id: string): void; scrollTo(position: number): void; scrollTo(selector: string): void; scrollTo(element: HTMLElement): void; scrollTo(options: { position: number; immediate?: boolean; offset?: number; } | { selector: string; immediate?: boolean; offset?: number; } | { element: HTMLElement; immediate?: boolean; offset?: number; }): void; private resolveScrollToValue; private resolveElementScrollPosition; destroy(): void; } export { CursorReactiveModule, DOMBatcher, GridAdapter, type RulersLayoutGrid, type RulersTriggerAction, ScrollController, type ScrollMarkRule as ScrollTriggerRule, StringAnchor, type StringContext, StringCursor, StringData, StringDelayLerpTracker, StringDevIconRegistry, StringDevInview, StringDevLayout, StringDevModule, StringDevOverlayRegistry, StringDevProgress, StringDevRulers, type StringDevStyleTokens, type StringDevtoolDefinition, type StringDevtoolProvider, type StringDevtoolState, StringFPSTracker, StringForm, StringGlide, StringImpulse, StringLazy, StringLerp, StringLerpTracker, StringLoading, StringMagnetic, StringMasonry, StringModule, StringObject, StringParallax, StringPositionTracker, StringProgress, StringProgressPart, StringRandom, StringResponsive, type StringRulersTrigger, StringScrollContainer, StringScrollbar, StringScroller, StringSequence, StringSplit, StringSpotlight, StringTune, StringVideoAutoplay, buildDevtoolsThemeBlock, StringTune as default, ensureStringDevtoolsSharedStyles, frameDOM, resolveDevtoolsIcon, styleTxn };