UNPKG

shark-mvc

Version:

Shark-MVC is a small MVC framework born to make our small JS apps easier to build.

1,176 lines (996 loc) 48.8 kB
/** * The class to extend to create Component classes. * Components are sub-parts of a View, used to render and manage portions of the UI. */ export declare class Component extends RenderableJaw { /** * The type identifier for this class. * Always `"component"` — non-writable and non-configurable. */ readonly type: "component"; /** * Creates a new Component instance and registers it with Shark via `Shark.registerComponent()`. * * @param jawId - The identifier for this Component. If omitted/null/empty, defaults to the * camelCase class name of the subclass. */ constructor(jawId?: string | null); /** * @deprecated Pass only `jawId`. The `jawDefinition` parameter will be removed in a future version. */ // eslint-disable-next-line @typescript-eslint/unified-signatures constructor(jawId: string | null | undefined, jawDefinition: object); } /** * The class to extend to create Controller classes. * Controllers manage application logic and are registered globally with Shark. */ export declare class Controller extends Jaw { /** * The type identifier for this class. * Always `"controller"` — non-writable and non-configurable. */ readonly type: "controller"; /** * Creates a new Controller instance and registers it with Shark via `Shark.registerController()`. * * @param jawId - The identifier for this Controller. If omitted/null/empty, defaults to the * camelCase class name of the subclass. */ constructor(jawId?: string | null); /** * @deprecated Pass only `jawId`. The `jawDefinition` parameter will be removed in a future version. */ // eslint-disable-next-line @typescript-eslint/unified-signatures constructor(jawId: string | null | undefined, jawDefinition: object); } /** Describes a single auto-listener entry stored in `__listeners`. */ interface JawListenerEntry { context?: string; handler: ((...args: any[]) => any) | string; originalHandler?: string; target: "DOM" | "controller" | "component"; type: "autoListener"; smartUnlisten?: boolean; } /** Describes an item used in array-form calls to `set()`. */ interface JawSetItem { name: string; value: any; } /** Describes an entry in the `__validMethodList` built by `_extractValidMethodList`. */ interface JawValidMethod { handlerName: string; handlerHolder: Jaw; _from?: string; depthList?: number[]; minDepth?: number; targetType?: "singleNode" | "multiNode" | "manager"; } /** * Represents an element of the MVC model (View or Controller). * Extends the native `EventTarget` and adds Shark-specific methods. * * @version 1.2.1.19, 2019.05.05 */ export declare class Jaw extends EventTarget { /** Read-only identifier for this Jaw instance. Set from `jawId` in the constructor. */ readonly className: string; /** Read-only identifier alias for `className`. */ readonly id: string; /** If the routing method is set to "url", this will be the URL displayed when this Jaw is active. */ route: string | null; /** Whether this Jaw has been initialized via `init()`. */ isInitialized: boolean; /** The options object used in the most recent open operation. */ currentOpenOptions: Record<string, any>; /** * Reactive proxy over `__store`. Properties defined here trigger auto-render when changed, * if `Shark.settings.enableJawStoreAutoRender` is enabled. */ $store: Record<string, any>; /** @internal Internal data store, backing `$store` and `get()`/`set()`. */ protected __store: Record<string, any>; /** @internal Fields registered for auto-rendering. */ protected __renderFields: string[]; /** @internal Map of child templates used during rendering. */ protected __childTemplates: Record<string, string>; /** @internal Map of dynamic data bindings. */ protected __dynamicDataBindings: Record<string, any>; /** @internal Registry of event listeners assigned by `smartListen`. */ protected __listeners: Record<string, Record<string, JawListenerEntry>>; /** @internal Named methods added to this Jaw. */ protected __methods: Record<string, any>; /** @internal View binding map (primary). */ protected __viewBinds: Record<string, any>; /** @internal View binding map (secondary). */ protected __viewBinds2: Record<string, any>; /** @internal Hash map used for change-detection in `__singleSet`. */ protected __storeHashMap: Map<string, any>; /** @internal List of valid handler methods built by `smartListen`. */ protected __validMethodList?: JawValidMethod[]; /** * The list of Components currently active on this Jaw. * Backed by a private field; use `addComponent`/`addComponents` to modify it. */ readonly activeComponents: Jaw[]; /** * Creates a new Jaw instance. * * @param jawId - The identifier for this Jaw. If omitted/null/empty, defaults to the * camelCase class name of the subclass. */ constructor(jawId?: string | null); /** * @deprecated Pass only `jawId`. The `jawDefinition` parameter will be removed in a future version. */ // eslint-disable-next-line @typescript-eslint/unified-signatures constructor(jawId: string | null | undefined, jawDefinition: object); /** * Add a single Component to this Jaw. * * @param component - The Component to add, either as a string ID or a Component instance. * Passing a string is deprecated; prefer passing the instance directly. * @returns The updated list of active Components. */ addComponent(component: Jaw | string): Jaw[]; /** * Add multiple Components to this Jaw. * * @param components - Array of Components to add (as instances or string IDs). * @returns The updated list of active Components. */ addComponents(components: (Jaw | string)[]): Jaw[]; /** * Retrieve one or more values from the internal data store. * * - Called with no arguments: returns the entire `__store` object. * - Called with a string: returns the value for that key. * - Called with an array of strings: returns an array of the corresponding values. * * @param itemName - Key name, array of key names, or `undefined` for full store. */ get(itemName?: string): any; get(itemName: string[]): any[]; get(itemName: undefined): Record<string, any>; /** * Called when this Jaw is used for the first time. Should be overridden by subclasses. */ init(): void; /** @internal Extracts valid `*Handler` methods from a list of Components, recursively. */ protected _extractComponentsValidMethodList( componentList: Jaw[], processedComponentList: string[], notProcessedComponentList: string[] ): JawValidMethod[]; /** @internal Extracts valid `*Handler` methods from a target object and its prototype chain. */ protected _extractValidMethodList(targetObject: Jaw): JawValidMethod[]; /** @internal Initialises Components, calling `init()` on each if not already done. */ protected _initComponents(componentList?: Jaw[] | null, processedComponentList?: string[]): void; /** * Store one or more values in this Jaw's internal data store. * If `Shark.settings.enableJawStoreAutoRender` is enabled and a value changed, triggers a render. * * Accepted signatures: * - `set(name, value)` — set a single named value. * - `set(object)` — merge all properties of the object into the store. * - `set(array)` — each item must have `{ name, value }`. * * @param nameOrItems - Property name, plain object, or array of `{ name, value }` items. * @param value - The value to store (only used when `nameOrItems` is a string). */ set(nameOrItems: string, value: any): void; set(nameOrItems: Record<string, any>): void; set(nameOrItems: JawSetItem[]): void; /** @internal Sets a single key on the store, returns `1` if the value changed, `0` otherwise. */ protected __singleSet(name: string, value: any): 0 | 1; // ── Methods added via prototype ─────────────────────────────────────────── /** * Dispatch an event from this Jaw using jQuery's `.trigger()`. * * @param eventName - Name of the event to dispatch. * @param eventData - Optional data passed to listeners. */ emit(eventName: string, eventData?: any): JQuery; /** * Remove an event listener from this Jaw using jQuery's `.off()`. * * @param eventName - Name of the event. * @param eventHandler - The handler function to remove. */ off(eventName: string, eventHandler: (...args: any[]) => any): JQuery; /** * Attach an event listener to this Jaw using jQuery's `.on()`. * * @param eventName - Name of the event. * @param eventHandler - The handler function to attach. */ on(eventName: string, eventHandler: (...args: any[]) => any): JQuery; /** * Automatically match and assign DOM and controller event listeners based on the * naming convention `selectorOrControllerName_eventNameHandler`. * * @param container - Optional CSS selector or jQuery selection to restrict parsing scope. * @param selfAssign - If `true`, the container itself is treated as a potential target. */ smartListen(container?: string | JQuery, selfAssign?: boolean): void; /** @internal Experimental v2 of `smartListen`. Work in progress. */ smartListen2(container?: string | JQuery, selfAssign?: boolean): void; /** * Remove all listeners previously assigned by `smartListen`. * * @param container - Optional container to restrict the unlisten scope. */ smartUnlisten(container?: string | JQuery): void; /** * Internal tracing utility. Delegates to `Shark.trace` if available. * * @param message - The message or object to trace. * @param level - The trace level/type string. */ trace(message: any, level?: string): void; /** * Update the DOM portions bound to a reference model path after the model's dirty * properties have changed. * * @param referenceModelPath - Dot-notation path to the reference model (e.g. `"user.profile"`). * @param sourceEvent - The original event that triggered the update. */ updateDisplay(referenceModelPath: string, sourceEvent?: Event): void; /** @internal Utility to compute the DOM depth of a node (distance from BODY). */ static __getNodeDepth(node: Node): number; } /** * The base Class for View and Component classes. It implements methods for template management. */ export declare class RenderableJaw extends Jaw { /** The default template HTML content. */ templateContent: string; /** The type identifier for this class. */ type: string; /** The parsed default template string, or null if not yet parsed. */ protected __parsedTemplate: string | null; /** * A map of parsed templates keyed by name, or null before `parseTemplates()` runs. * Note: initialized as `null` in the constructor — always check before accessing. */ protected __parsedTemplates: Record<string, string> | null; /** A map of raw template content keyed by name. */ protected __templates: Record<string, string>; /** Set to `true` after `parseTemplates()` completes; prevents re-parsing. */ protected __templatesParsed?: boolean; /** * Creates an instance of RenderableJaw. * * @param jawId - The identifier for this Jaw. If omitted/null/empty, defaults to the * camelCase class name of the subclass (inherited from `Jaw`). */ constructor(jawId?: string | null); /** * @deprecated Pass only `jawId`. The `jawDefinition` parameter will be removed in a future version. */ // eslint-disable-next-line @typescript-eslint/unified-signatures constructor(jawId: string | null | undefined, jawDefinition: object); /** * Internal implementation for adding a template. * Called by both `addTemplate()` and `setTemplate()`. * * @param name - The template name. Empty string registers the default template. * Cannot contain spaces or equal "__default__" (reserved). * @param content - The template HTML content. * @returns The updated template map, or `undefined` if validation failed. */ protected _addTemplate(name: string, content: string): Record<string, string> | undefined; /** * Add a named HTML template to this RenderableJaw. * * @param name - The name used in container templates to reference this template. * Pass an empty string to register the default template (only one allowed). * Cannot be `"__default__"` (reserved) or contain spaces. * @param content - The template HTML content. * @returns The updated template map, or `undefined` if validation failed. * @version 1.0.0, 2020.09.08 */ addTemplate(name: string, content: string): Record<string, string> | undefined; /** * Parse all registered templates, resolving embedded component references. * * Supports two component-embedding syntaxes: * - Mustache-style: `{{=>ComponentName}}` / `{{=>ComponentName.templateName}}` * - Custom HTML: `<shark-component-name />` with optional `template="templateName"` attribute * * Populates `__parsedTemplate` and `__parsedTemplates`. * Guarded by `__templatesParsed`: subsequent calls are no-ops. */ parseTemplates(): void; /** * Set the default HTML template for this RenderableJaw. * Shorthand for `addTemplate("", content)`. * * @param content - The template HTML content. * @returns The updated template map, or `undefined` if validation failed. * @version 1.0.0, 2020.12.03 */ setTemplate(content: string): Record<string, string> | undefined; } export declare class Shark { constructor (); static $store: any; /** * Retrieve values from the main store. It supports object deconstruction * * @param {string|array} itemName - */ static get (itemName?: string): any; /** * Return an instance of the requested model, filled with the passed data if present. * * @return {object} * @static * @version 1.1.0.10 - 2017.07.28 * * @param {string} modelNameOrClass - The name of the model to instantiate. It must exist: prior of this call you must have called the [createModel method]{@link Shark#createModel} withe the same model name and a model definition. * @param {object} [modelData = undefined] - An object containing the data to use to fill the new instance. (it just call the instance.parse method) */ static getInstance (modelNameOrClass: any, modelData: object): object; static getInstanceList (modelNameOrClass: any, dataList: array): array; /** * @param {object} [options] - An object containing the options for initializing. * @param {object} [options.commonEndPointsBase = ""] - DEPRECATED and REMOVED The "base" parte of the URL for the remote request. Use this value only if you have common destination for all your API call. * Otehrwise you can set different URL for each call. * @param {object} [options.labels = []] - An array of objects containing a list of labels to be used in conjunction with localization features. * @param {integer} [options.remoteCallTimeOutDuration = 15000] - The number of millisecods that Shark should wait befor abort remote call. * @param {object} [options.dataManager = DataManager] - DEPRECATED and REMOVED The Class to be used to manage the remote request. Not yet fully implemented. * @param {object} [options.templates = {}] - An object containing html templates as strings. (documentation has to be written about creating templates object) * @param {object} [options.templateRenderer = MustacheRenderer] - The Class responsible for rendering Views on screen. Must be a SharRenderer sub-class. Not yet fully implemented. * @param {boolean} [forceReinit = false] - If true process initialize step even if the initialization phase has alredy been completed. */ static init (options: object, forceReinit: boolean): undefined; /** * Open the requested View showing it on the screen * * @param {(string|Jaw)} pageIdOrJaw - The view to register. */ static openPage (pageIdOrJaw: string | object, options: object): boolean; static registerComponent (jaw: object): undefined; static registerController (jaw: object): undefined; static registerModel (modelName: string, modelClass: object): undefined; /** * Register a view that can be used withe the openPage method. * * @param {Jaw} jaw - The view to register. */ static registerView (jaw: object): undefined; static render (currJaw?: object, options?: object): boolean; static set (nameOrObject: any, value?: any): any; } /** Describes a single dirty property entry, tracking the original value before changes. */ interface SmartModelDirtyEntry { property: string; originalValue: any; } /** Options accepted by `__export` / `export`. */ interface SmartModelExportOptions { /** If provided, only the listed property names will be exported. */ fields?: string[]; } /** Options accepted by `__import` / `import`. */ interface SmartModelImportOptions { /** If `true`, properties present in `data` but missing on the model will be created. Default: `false`. */ createMissingProperties?: boolean; /** If `true`, empty/falsy values in `data` are still matched onto the model. Default: `true`. */ matchEmptyParameters?: boolean; } /** Options accepted by `importField`. */ interface SmartModelImportFieldOptions { /** If `true`, `undefined` / `null` values are accepted and not short-circuited. Default: `false`. */ acceptUndefined?: boolean; /** Explicit data type for parsing. `"auto"` performs no conversion. Default: `"auto"`. */ dataType?: "auto" | "boolean" | "date" | "number"; /** Fallback value used when the parsed number is `NaN`. Only relevant for `dataType: "number"`. */ defaultValue?: number; /** If `true`, date values are parsed as UTC and converted to local time. Default: `true`. */ useUTC?: boolean; } /** * Payload dispatched with `"dataChanged"` and `"<propertyName>Changed"` events, * and passed to `onDataChanged` / `on<PropertyName>Changed` hooks. */ interface SmartModelChangeEventData { /** The `__modelName` of the model that triggered the change. */ modelName: string | undefined; /** The new value assigned to the property. */ newValue: any; /** The previous value of the property before the change. */ oldValue: any; /** The dot-notation path of the property that changed. */ property: string; } /** Describes an item used in array-form calls to `set()`. */ interface SmartModelSetItem { name: string; value: any; } /** Inferred type map produced by `SmartModel.inferTypes()`. */ type SmartModelInferredTypes = Record<string, "number" | "datetime" | "boolean" | "string" | "array" | "object" | typeof SmartModel>; /** * Base class for reactive data models in the Shark MVC framework. * * Extends `EventTarget` and provides: * - Dirty tracking (`isDirty`, `clean`, `restore`) * - Typed import/export helpers for boolean, date, number, array, object fields * - Auto-casting and toggle logic in `set()` * - jQuery-based event emission via `emit`, `on`, `off` * - Experimental screen-sync via `updateScreenWithModelValue` * * @version 1.0.0.3, 2019.03.03 * * @fires SmartModel#dataChanged - Emitted whenever a property changes value. * @fires SmartModel#<propertyName>Changed - Emitted for the specific changed property. */ export declare class SmartModel extends EventTarget { /** Unique GUID assigned at construction. Non-writable. */ readonly __shguid: string; /** Whether any property of this model differs from its original/cleaned value. */ __isDirty: boolean; /** List of properties that have changed since the last `clean()` call. */ __dirtyProperties: SmartModelDirtyEntry[]; /** Auto-bound property names (reserved for internal use). */ __boundProperties: string[]; /** The model structure passed at construction, if any. */ __modelStructure: object | undefined; /** The renderer instance associated with this model. */ __renderer: any; // ── Private methods exposed via Object.defineProperty ──────────────────── /** * Clear dirty state for all or specific properties. * @see `clean()` for the public API. */ protected readonly __clean: (properties?: string[]) => SmartModelDirtyEntry[]; /** * Export model data to a plain object. * @see `export()` for the public API. */ protected readonly __export: (options?: SmartModelExportOptions) => Record<string, any>; /** * Import data from a plain object onto this model. * @see `import()` for the public API. */ protected readonly __import: (data: object, options?: SmartModelImportOptions) => any; /** * Restore all dirty properties to their original values. * @see `restore()` for the public API. */ protected readonly __restore: (properties?: string[]) => void; /** * Update the dirty-property registry for a single property after a value change. * @internal */ protected readonly __setPropertyDirtiness: (propertyName: string, eventData: SmartModelChangeEventData) => void; /** * Serialize this model to a plain object, optionally including private (`__`) properties. * @see `toJSON()` for the public API. */ protected readonly __toJSON: (forcePrivateProperties?: boolean) => Record<string, any>; /** * Creates a new SmartModel instance. * * @param data - If provided, its properties are matched onto the model via `import()`. * Note: due to how `super()` works, this is not automatically applied * in the base constructor — subclasses should call `this.import(data)` manually. * @param options - Options controlling how `data` is matched onto the model. * @param modelStructure - A structural template used to pre-populate model properties * via `Utils.matchProperties`. */ constructor(data?: object, options?: SmartModelImportOptions, modelStructure?: object); /** * Replace the renderer instance for this model. * * @param renderer - The new renderer. Must expose a `setModel(model)` method. */ addRenderer(renderer: { setModel(model: SmartModel): void; [key: string]: any }): void; /** * Clear dirty state for all properties, or only for the specified ones. * After this call, `__isDirty` is recomputed. * * @param properties - Optional array of property path strings to clean selectively. * @returns The remaining dirty-property entries after cleaning. */ clean(properties?: string[]): SmartModelDirtyEntry[]; /** * Dispatch an event from this model using jQuery's `.trigger()`. * * @param eventName - Name of the event to dispatch. * @param eventData - Optional data passed to listeners. */ emit(eventName: string, eventData?: any): JQuery; /** * Export all public, non-function properties to a plain object. * Properties whose names start with `__` or `jQuery` are excluded by default. * Override to customise export behaviour; call `__export()` for the default logic. * * @param options - Pass `{ fields: [...] }` to export only specific properties. * @returns A plain object with the exported data. */ export(options?: SmartModelExportOptions): Record<string, any>; /** * Export an array field as a JSON string (or other formats in the future). * * @param field - Dot-notation path to the array property. * @param format - Export format. Currently only `"JSON"` is supported. Default: `"JSON"`. */ exportArrayField(field: string, format?: "JSON"): string; /** @internal Implementation of `exportArrayField`. */ protected __exportArrayField(field: string, format?: "JSON"): string; /** * Export a boolean field as a number (`1`/`0`) or string. * * @param field - Dot-notation path to the boolean property. * @param format - `"number"` (default) returns `1` or `0`; `"string"` returns `"true"`/`"false"`. */ exportBooleanField(field: string, format?: "number" | "string"): number | string; /** @internal Implementation of `exportBooleanField`. */ protected __exportBooleanField(field: string, format?: "number" | "string"): number | string; /** * Export a date field as a formatted string. * * @param field - Dot-notation path to the date/moment property. * @param format - Export format. Currently only `"ISO"` is supported (outputs `"YYYY-MM-DD HH:mm:ss"`). Default: `"ISO"`. * @param useUTC - If `true`, the date is converted to UTC before formatting. Default: `true`. * @returns The formatted date string, or `"0000-00-00 00:00:00"` if the value is invalid. */ exportDateField(field: string, format?: "ISO", useUTC?: boolean): string; /** @internal Implementation of `exportDateField`. */ protected __exportDateField(field: string, format?: "ISO", useUTC?: boolean): string; /** * Export a numeric field, parsing strings to floats if necessary. * * @param field - Dot-notation path to the numeric property. * @param format - Reserved for future use. */ exportNumberField(field: string, format?: string): number; /** @internal Implementation of `exportNumberField`. */ protected __exportNumberField(field: string, format?: string): number; /** * Export an object field as a JSON string (or other formats in the future). * * @param field - Dot-notation path to the object property. * @param format - Export format. Currently only `"JSON"` is supported. Default: `"JSON"`. */ exportObjectField(field: string, format?: "JSON"): string; /** @internal Implementation of `exportObjectField`. */ protected __exportObjectField(field: string, format?: "JSON"): string; /** * Import data from a plain object onto this model. * Override to add custom parsing; call `__import()` for the default logic. * * @param data - Source data object. * @param options - Import options. */ import(data: object, options?: SmartModelImportOptions): any; /** * Import and parse a boolean field from an external raw value. * Accepts `number` (`1`/`0`), `string` (`"true"`/`"false"`/`"1"`/`"0"`), or `boolean`. * * @param field - Dot-notation path to the target property. * @param value - Raw value to parse. * @returns `true` if the value was successfully parsed and set; `false` otherwise. */ importBooleanField(field: string, value: any): boolean; /** @internal Implementation of `importBooleanField`. */ protected __importBooleanField(field: string, value: any): boolean; /** * Import and parse a date field, converting it to a `moment` object. * * @param field - Dot-notation path to the target property. * @param value - Raw date value (string, number, Date, or moment). * @param useUTC - If `true`, parses as UTC and converts to local. Default: `true`. * @returns `true` if the resulting moment is valid; `false` otherwise. */ importDateField(field: string, value: any, useUTC?: boolean): boolean; /** @internal Implementation of `importDateField`. */ protected __importDateField(field: string, value: any, useUTC?: boolean): boolean; /** * Import and parse a numeric field, converting strings via `parseFloat`. * * @param field - Dot-notation path to the target property. * @param value - Raw value to parse. * @param defaultValue - Fallback number used if parsing yields `NaN`. * @returns `true` if the value was successfully set; `false` if the value was `undefined`/`null` or parsing failed without a default. */ importNumberField(field: string, value: any, defaultValue?: number): boolean; /** @internal Implementation of `importNumberField`. */ protected __importNumberField(field: string, value: any, defaultValue?: number): boolean; /** * Unified import helper that dispatches to the correct typed import method based on `options.dataType`. * When `dataType` is `"auto"`, no conversion is performed and the method always returns `true` * (provided the value is not `undefined`/`null`, unless `acceptUndefined` is set). * * @param field - Dot-notation path to the target property. * @param value - Raw value to import. * @param options - Import options including type, default value, UTC flag, etc. * @returns `true` if the field was set; `false` if it was skipped. */ importField(field: string, value: any, options?: SmartModelImportFieldOptions): boolean; /** * Inspect an instance of this model class and infer the data type of each public property * based on its default value. * * Assigns the resulting type map to `this.inferTypes` (overwriting the method on the class). * Results are also logged to the console. * * @static */ static inferTypes(): void; /** * Check whether this model has unsaved/unclean property changes. * * - Called with no arguments: returns the overall `__isDirty` flag. * - Called with `properties`: checks whether any (`"any"`) or all (`"all"`) of those * properties are currently dirty. * * @param properties - A single property path string or an array of paths to check. * If `null` or omitted, the overall dirty state is returned. * @param mode - `"any"` (default): returns `true` if at least one listed property is dirty. * `"all"`: returns `true` only if every listed property is dirty. */ isDirty(properties?: string | string[] | null, mode?: "any" | "all"): boolean; /** * Remove an event listener from this model using jQuery's `.off()`. * * @param eventName - Name of the event. * @param eventHandler - The handler function to remove. */ off(eventName: string, eventHandler: (...args: any[]) => any): JQuery; /** * Attach an event listener to this model using jQuery's `.on()`. * * @param eventName - Name of the event. * @param eventHandler - The handler function to attach. */ on(eventName: string, eventHandler: (...args: any[]) => any): JQuery; /** * Restore dirty properties to their original values and reset `__isDirty` to `false`. * Currently only supports restoring all properties at once (the `properties` parameter * is accepted but not yet implemented in the internal `__restore`). * * @param properties - Reserved. Passing a value has no effect in the current implementation. */ restore(properties?: string[]): void; /** * @internal * Core implementation of `set()` for a single property. * Handles auto-casting, array toggle logic, dirty tracking, event dispatch, * and optional screen sync. * * @param name - Dot-notation property path. * @param value - New value to assign. * @param eventTargetNode - The DOM node that triggered the change, if any (used to avoid * updating the source element during `updateScreenWithModelValue`). */ protected __singleSet(name: string, value: any, eventTargetNode?: Element | null): void; /** * Assign a value to one or more model properties. * * Accepted signatures: * - `set(name, value)` — set a single named property. * - `set(object)` — set multiple properties from a plain object. * - `set(array)` — each item must have `{ name, value }`. * * Auto-casting rules (based on the current property type): * - `number`: value is parsed with `parseFloat`. * - `string`: value is converted with `.toString()`. * - `array` + scalar value: the value is toggled (added if absent, removed if present). * - `moment` object: value is wrapped with `moment(value)`. * * On change, dispatches `"dataChanged"` and `"<propertyName>Changed"` events, * and calls `onDataChanged` / `on<PropertyName>Changed` hooks if defined on the model. * * @param name - Property name, plain object, or array of `{ name, value }` items. * @param value - The value to assign (used only when `name` is a string). * @param eventTargetNode - Optional source DOM node, forwarded to `updateScreenWithModelValue`. * * @fires SmartModel#dataChanged * @fires SmartModel#<propertyName>Changed */ set(name: string, value: any, eventTargetNode?: Element | null): void; set(name: Record<string, any>, eventTargetNode?: Element | null): void; set(name: SmartModelSetItem[], eventTargetNode?: Element | null): void; /** * Serialize this model to a plain object. * Excludes functions, `Element` instances, and properties starting with `__` * (unless `forcePrivateProperties` is `true`) and those starting with `jQuery`. * * @param forcePrivateProperties - If `true`, `__`-prefixed properties are included. */ toJSON(forcePrivateProperties?: boolean): Record<string, any>; /** * Serialize this model to a JSON string. * * @param forcePrivateProperties - Forwarded to `toJSON()`. */ toString(forcePrivateProperties?: boolean): string; /** * @experimental * Sync a single property value to all matching `[data-sh-prop]` DOM elements, * skipping the element that triggered the change. * * @param name - The property name used to query `[data-sh-prop="name"]`. * @param eventTargetNode - The DOM node to skip during update. * @param value - The new value to apply. * @param eventData - The change event data (used for tracing). */ updateScreenWithModelValue(name: string, eventTargetNode: Element | null, value: any, eventData: SmartModelChangeEventData | string): void; /** * @experimental @dangerous * Sync all public properties to their matching `[data-sh-prop]` DOM elements. * Does not check which model owns a given DOM node. */ updateScreenWithModelValues(): void; // ── Optional lifecycle hooks (to be defined on subclasses) ─────────────── /** * Called whenever any property changes value. Override in subclasses to react to changes. * * @param eventData - Details about the property change. */ onDataChanged?(eventData: SmartModelChangeEventData): void; /** * Dynamically typed hook: `on<PropertyName>Changed` is called when the property named * `propertyName` changes. E.g. `onUsernameChanged(eventData)`. * TypeScript cannot statically verify these; they are captured by the index signature below. */ [key: string]: any; } /** Data object accepted by the `SwimRoute` constructor. */ interface SwimRouteData { /** The route pattern, optionally containing dynamic segments prefixed with `:` (e.g. `"/user/:id/orders/:orderId"`). */ route: string; /** The View instance or class associated with this route. */ view: any; } /** * Represents a single application route, pairing a URL pattern with a View * and providing dynamic parameter extraction. */ export declare class SwimRoute { /** The route pattern string (e.g. `"/user/:id/orders/:orderId"`). */ route: string; /** The View instance or class associated with this route. */ view: any; /** * The last matched URL for this route. * Populated externally; used as fallback in `extractRouteParams()` when no URL is passed. */ url: string; /** * The dynamic parameters extracted from the last successful `extractRouteParams()` call. * Backed by a private field; read-only from outside the class. */ readonly params: Record<string, string>; /** * Creates a new SwimRoute instance. * * @param data - Object containing the `route` pattern and the associated `view`. */ constructor(data: SwimRouteData); /** * Match a URL against this route's pattern and extract any dynamic segment values. * * Dynamic segments are defined with a `:` prefix in the route pattern * (e.g. `"/user/:id"` matches `"/user/42"` and extracts `{ id: "42" }`). * * Trailing slashes and query strings are stripped from both the pattern and the URL * before matching. The number of path segments must match exactly. * * On a successful match the extracted parameters are stored in `this.params` as a side-effect. * On failure (segment count mismatch or static segment mismatch) the method returns early * and `this.params` is left unchanged. * * @param url - The actual URL to match (e.g. `"/user/abc/orders/123"`). * If omitted or falsy, `this.url` is used as fallback. */ extractRouteParams(url?: string): void; } export declare class SwimWay { /** * This is the basic router for the Shark environment. * <br>Fun Fuct: SwimWay is a name given by some researcher to a sort of route followd in the ocean by a great amount of Sharks. * @constructor * @param {string} [routingMethod=pathname] - The routing method used for this router: value could be one of pathname, url or hash. */ constructor (routingMethod: string); addRoute (route: object): number addRoutes (routes: Array): number navigateTo (route: string | object): boolean /** * Parse the document.location properties and return the requested View in the URL. * * @returns {string} requestedView - The name of the View extracted from the current URL. */ getRequestedViewFromLocation (): string; /** * Set current URLSearchParams without creating a new state in browser's history. * * @param {string|object|URLSearchParams} urlSearchParams - Could be a string, an object or a URLSearchParams instance. */ setURLSearchParams (urlSearchParams: string | object | URLSearchParams): undefined; } export declare class Utils { constructor (); // greeting: string; // showGreeting(): void; /** * Return a random number between 0 and a max value ora between two values. * @static * @version 0.1.0.1 * @param {number} minOrMax If this is the only passed parameter thant it will be used as "max", and the return number will be between 0 and this number. If the max parameter is passed, then this parameter will be as lower limit. * @param {number} [max] The higher limit for the generate number. * @returns {number} The random number generated. */ static betterRandom (minOrMax: number, max: number): number; /** * Return a random integer number between 0 and a max value ora between two values. If not integer numbers are passed in, the result will be anyway an integer. * @static * @version 0.1.0.1 * @param {number} minOrMax If this is the only passed parameter thant it will be used as "max", and the return number will be between 0 and this number. If the max parameter is passed, then this parameter will be as lower limit. * @param {number} [max] The higher limit for the generate number. */ static betterRandomInt (minOrMax: number, max: number): number; /** * Convert a string with camel-cased text to a dash separated words. Each uppercase character will be considered as the word starter and lower-cased. * @static * @version 0.1.0.1 * @param {string} inputString The camelCased string. * @returns {string} The dash-converted string. */ static camelToDashed (inputString: string): string; static computeHash (value: any): string; /** * Convert a string with dash as word separator to a camel-cased text. The first letter after each dash is upper-cased and joined with previous word. * @static * @version 0.1.0.1 * @param {string} inputString - The camelCased string. * @returns {string} - The camel-cased string. */ static dashedToCamel (inputString: string): string; static extractDifferentProperties (firstObject: object, secondObject: object): object; static flatten (objectToFlatten: object): object; /** * Generate a random GUID * @static * @version 0.1.0.1 * @param {string} [prefix] - * @param {string} [suffix] - */ static generateGUID(prefix?: string, suffix?: string): string; /** * Get a property value from an object. The property can be a sub-property of any property of the object. If the path identificates an unexisting property, this function returns undefined. * @static * @version 0.1.0.1 * @param {object} object - The object to read from the property value. * @param {string} path - The dot-separated path that identify the route to follow to get to the property to read the value. * @returns {boolean|object|string|array|number|null|undefined} - The value of the property. */ static getDeepProperty (object:object, path:string): any; static matchLists (sourceList: Array, matchLists: object, options: object): Array; /** * Replicate the property from the sourceObject into targetObject, with various options. * @static * @version 0.1.2.36 - 2017.06.05 * * @param {object} targetObject - The object that the properties will be copied onto. * @param {object} sourceObject - The object that cointains properties and values to be copied. * @param {object} [options] - An object containing the options. * @param {boolean} [options.createMissingProperties = false] - If true properties that are in the soruceObject but not in the targetObject are created in the targetObject and assigned the value they have in the sourceObject; if false, only properties alredy in the targetObject takes the value they have in the sourceObject. * @param {boolean} [options.matchEmptyParameters = true] - If true a property that is empty in the sourceObject are copied into the targetObject, even if the value in the targetObject is not empty; if false, an empty property in sourceObject will not overwrite any content present in the targetObject. */ static matchProperties(targetObject: object, sourceObject: object, options: object); static moveCaretToEnd(target: Element): undefined; static parseJSON (data: string, expectedType: string): any; /** * Takes an array and (usign <code>forEach</code> method) add two "hidden" property: _index and _displayIndex. * * @returns {array} * @static * @version 1.0.0, 2022-07-05 * * @param {array} list - The array to cycle. * */ static reindexList (list: Array): Array; static replaceNullValue (objectToParse, replaceVal): any; static safeStringify (sourceValue: any): string; /** * Shorthand for the searchArrayForProperty method. * Search an array for an object that has the requested property with the given value. By default if a result is found it stops the loop and returns that item. *<br />If no object matches the requested filter this method returns null. *<br />Since the version 2.0.6 this method uses the faster Array.prototype.find method if is available and the parameters are compatible. * * @static * @version 2.0.6, 2018.05.31 * @param {array} list - The array of objects to search into. * @param {string} property - The name of the property to search in each object of the array. If a dot separated list (eg. "childs.name") is passed, the value param is compared to the last property of the <i>path</i>; for example if the "property" param is "childs.name", then the value param will compared to the "name" property of the "childs" property of each element in the array. * @param {any} value - The value that will be used to check the given property. It must have same value and same type, since a comparison of type === is made. * @param {boolean|string} [searchType = "first"] - This can be one of "first", "all" or "index". * <br />For compatibilty with previous version of this method, a boolean can be passed and if the value is true the method stops and return on the first occourence and therefore return a single object (like it was "first"), if is false, the method will return an array of object that match the filter (like it was "all"). * <br />If searchType is set to "all" or false, the method will return an array even if it matches only one object. */ static safp (list: array, string: property, value: any, searchType?: boolean | string): object | array | number | null; /** * Search an array for an object that has the requested property with the given value. By default if a result is found it stops the loop and returns that item. *<br />If no object matches the requested filter this method returns null. *<br />Since the version 2.0.6 this method uses the faster Array.prototype.find method if is available and the parameters are compatible. * * @static * @version 2.0.6, 2018.05.31 * @param {array} list - The array of objects to search into. * @param {string} property - The name of the property to search in each object of the array. If a dot separated list (eg. "childs.name") is passed, the value param is compared to the last property of the <i>path</i>; for example if the "property" param is "childs.name", then the value param will compared to the "name" property of the "childs" property of each element in the array. * @param {any} value - The value that will be used to check the given property. It must have same value and same type, since a comparison of type === is made. * @param {boolean|string} [searchType = "first"] - This can be one of "first", "all" or "index". * <br />For compatibilty with previous version of this method, a boolean can be passed and if the value is true the method stops and return on the first occourence and therefore return a single object (like it was "first"), if is false, the method will return an array of object that match the filter (like it was "all"). * <br />If searchType is set to "all" or false, the method will return an array even if it matches only one object. */ static searchArrayForProperty (list: array, string: property, value: any, searchType: boolean | string): object | array | number | null; /** * Assign a property to an object. The property can be a sub-property of any property of the object. If the path parameters indicates a sub-property of a property that does not exists, the property and the sub-property will be both created. * @static * @version 0.1.0.1 * @param {object} object - The object on whom the property will be created or assigned a value. * @param {string} path - */ static setDeepProperty (object: object, path: string, value: any, depth: number): any; static trace (content: string): undefined; static toCamelCase (value: string): string; static toTitleCase (value: string, forceLowerCase: boolean): string; /** * Return a string of <code>length</code> characters representing the given number with leading zeros. * @static * @version 1.0.2 - 2019.04.23 * @param {number} number - * @param {number} length - * @returns {string} - The string representing the passed number with leading zeros. */ static zeroFill (number: number, length: number): string; } /** * The base Class for View and Component classes. It implements methods for template management. */ /** * The class to extend to create View classes. * A View can only have a single template; use `setTemplate()` to set it. */ export declare class View extends RenderableJaw { /** * The main route associated with this View. * Writable, but not reconfigurable. */ $mainRoute: string; /** * The type identifier for this class. * Always `"view"` — non-writable and non-configurable. */ readonly type: "view"; /** * Creates a new View instance and registers it with Shark via `Shark.registerView()`. * * @param jawId - The identifier for this View. If omitted/null/empty, defaults to the * camelCase class name of the subclass. */ constructor(jawId?: string | null); /** * @deprecated Pass only `jawId`. The `jawDefinition` parameter will be removed in a future version. */ // eslint-disable-next-line @typescript-eslint/unified-signatures constructor(jawId: string | null | undefined, jawDefinition: object); /** * @deprecated Views can only have one template. Use `setTemplate()` instead. * * This override ignores `name` and delegates to `setTemplate(content)`. * Will be removed in a future version. * * @param name - Ignored. Views support a single template only. * @param content - The template HTML content. * @returns The updated template map, or `undefined` if validation failed. */ addTemplate(name: string, content: string): Record<string, string> | undefined; }