import Backbone from 'backbone'; import { ModelDestroyOptions, _StringKey } from 'backbone'; export interface DomComponentsConfig { stylePrefix?: string; /** * Could be used for default components. */ components?: Record[]; /** * If the component is draggable you can drag the component itself (not only from the toolbar). * @default true */ draggableComponents?: boolean; /** * Experimental: Disable text inner components. * With this option, you're able to decide which inner component inside text should be * disabled (eg. no select, no hover, no layer visibility) once edited. * @default false * @example * // disable all inner childs * disableTextInnerChilds: true, * // disable all except link components * disableTextInnerChilds: (child) => !child.is('link'), */ disableTextInnerChilds?: boolean | ((cmp: Component) => boolean | void); /** * You can setup a custom component definition processor before adding it into the editor. * It might be useful to transform custom objects (es. some framework specific JSX) to GrapesJS component one. * This custom function will be executed on ANY new added component to the editor so make smart checks/conditions * to avoid doing useless executions * By default, GrapesJS supports already elements generated from React JSX preset * @example * processor: (obj) => { * if (obj.$$typeof) { // eg. this is a React Element * const gjsComponent = { * type: obj.type, * components: obj.props.children, * ... * }; * ... * return gjsComponent; * } * } */ processor?: (obj: any) => Record | undefined; /** * List of HTML void elements. * https://www.w3.org/TR/2011/WD-html-markup-20110113/syntax.html#void-elements */ voidElements?: string[]; /** * Experimental: Use the frame document for DOM element creation. * This option might be useful when elements require the local document context to * work properly (eg. Web Components). */ useFrameDoc?: boolean; } declare const DataVariableType: "data-variable"; export interface DataVariableProps { type?: typeof DataVariableType; path?: string; defaultValue?: string; collectionId?: string; variableType?: DataCollectionStateType; } declare class DataVariable extends Model { private em; private collectionsStateMap; defaults(): DataVariableProps; constructor(props: DataVariableProps, options: { em: EditorModel; collectionsStateMap: DataCollectionStateMap; }); get path(): string; get defaultValue(): string; get collectionId(): string | undefined; get variableType(): DataCollectionStateType | undefined; getDataValue(): any; resolvesFromCollection(): boolean; updateCollectionsStateMap(collectionsStateMap: DataCollectionStateMap): void; getResolverPath(): string | false; toJSON(options?: any): DataVariableProps & { type: typeof DataVariableType; }; private resolveDataSourcePath; private resolveCollectionVariable; private resolveCurrentItem; } declare enum DataCollectionStateType { currentIndex = "currentIndex", startIndex = "startIndex", currentItem = "currentItem", endIndex = "endIndex", collectionId = "collectionId", totalItems = "totalItems", remainingItems = "remainingItems" } export interface DataCollectionState { [DataCollectionStateType.currentIndex]: number; [DataCollectionStateType.startIndex]: number; [DataCollectionStateType.currentItem]: DataVariableProps; [DataCollectionStateType.endIndex]: number; [DataCollectionStateType.collectionId]: string; [DataCollectionStateType.totalItems]: number; [DataCollectionStateType.remainingItems]: number; } export interface DataCollectionStateMap { [key: string]: DataCollectionState; } export interface DynamicWatchersOptions { skipWatcherUpdates?: boolean; fromDataSource?: boolean; } export interface ComponentResolverWatcherOptions { em: EditorModel; collectionsStateMap?: DataCollectionStateMap; } declare class ModuleModel = Module, T extends ObjectHash = any, S = SetOptions, E = any> extends Model { private _module; constructor(module: TModule, attributes?: T, options?: CombinedModelConstructorOptions); get module(): TModule; get config(): TModule extends IBaseModule ? C : unknown; get em(): EditorModel; } export type ModuleExt = TModel extends ModuleModel ? M : unknown; export type ModelConstructor = { new (mod: ModuleExt, attr: any): TModel; }; declare class ModuleCollection extends Collection { module: ModuleExt; private newModel; add(model: Array> | TModel, options?: AddOptions): TModel; add(models: Array> | TModel>, options?: AddOptions): TModel[]; constructor(module: ModuleExt, models: TModel[] | Array>, modelConstructor: ModelConstructor); preinitialize(models?: TModel[] | Array>, options?: any): void; } export type ModuleFromModel = TModel extends ModuleModel ? M : unknown; export type ModuleModelExt = TItem extends ModuleCollection ? ModuleFromModel : TItem extends ModuleModel ? M : unknown; declare class ModuleView extends View { protected get pfx(): string; protected get ppfx(): string; collection: TModel extends ModuleModel ? ModuleCollection : TModel; protected get module(): ModuleModelExt; protected get em(): EditorModel; protected get config(): ModuleModelExt extends IBaseModule ? C : unknown; className: string; preinitialize(options?: any): void; } export type ContentElement = string | ComponentDefinition; export type ContentType = ContentElement | ContentElement[]; export interface DraggableContent { /** * Determines if a block can be moved inside a given component when the content is a function. * * This property is used to determine the validity of the drag operation. * @type {ComponentDefinition | undefined} */ dragDef?: ComponentDefinition; /** * The content being dragged. Might be an HTML string or a [Component Defintion](/modules/Components.html#component-definition) */ content?: ContentType | (() => ContentType); } export type DragSource = DraggableContent & { model?: T; }; export type Placement = "inside" | "before" | "after"; export type DroppableZoneConfig = { ratio: number; minUndroppableDimension: number; maxUndroppableDimension: number; }; declare enum DragDirection { Vertical = "Vertical", Horizontal = "Horizontal", BothDirections = "BothDirections" } export type CustomTarget = ({ event }: { event: MouseEvent; }) => HTMLElement | null; export interface SorterContainerContext { container: HTMLElement; containerSel: string; itemSel: string; pfx: string; document: Document; placeholderElement: HTMLElement; customTarget?: CustomTarget; } export interface PositionOptions { windowMargin?: number; borderOffset?: number; offsetTop?: number; offsetLeft?: number; canvasRelative?: boolean; relative?: boolean; } /** * Represents an event handler for the `onStartSort` event. * * @param sourceNodes The source nodes being sorted. * @param container The container element where the sorting is taking place. */ export type OnStartSortHandler = (sourceNodes: NodeType[], container?: HTMLElement) => void; /** * Represents an event handler for the `onDragStart` event. * * @param mouseEvent The mouse event associated with the drag start. */ export type OnDragStartHandler = (mouseEvent: MouseEvent) => void; export type OnMouseMoveHandler = (mouseEvent: MouseEvent) => void; export type OnDropHandler = (targetNode: NodeType | undefined, sourceNodes: NodeType[], index: number | undefined) => void; export type OnTargetChangeHandler = (oldTargetNode: NodeType | undefined, newTargetNode: NodeType | undefined) => void; export type OnPlaceholderPositionChangeHandler = (targetDimension: Dimension, placement: Placement) => void; export type OnEndHandler = () => void; /** * Represents a collection of event handlers for sortable tree node events. */ export interface SorterEventHandlers { onStartSort?: OnStartSortHandler; onDragStart?: OnDragStartHandler; onMouseMove?: OnMouseMoveHandler; onDrop?: OnDropHandler; onTargetChange?: OnTargetChangeHandler; onPlaceholderPositionChange?: OnPlaceholderPositionChangeHandler; onEnd?: OnEndHandler; legacyOnMoveClb?: Function; legacyOnStartSort?: Function; legacyOnEndMove?: Function; legacyOnEnd?: Function; } export interface SorterDragBehaviorOptions { dragDirection: DragDirection; nested?: boolean; selectOnEnd?: boolean; } export interface SorterOptions> { em: EditorModel; treeClass: new (model: T, dragSource?: DragSource) => NodeType; containerContext: SorterContainerContext; positionOptions: PositionOptions; dragBehavior: SorterDragBehaviorOptions; eventHandlers: SorterEventHandlers; } declare class Dimension { top: number; left: number; height: number; width: number; offsets: ReturnType; dir?: boolean; /** * Initializes the DimensionCalculator with the given initial dimensions. * * @param initialDimensions - The initial dimensions containing `top`, `left`, `height`, `width`, and other properties. */ constructor(initialDimensions: { top: number; left: number; height: number; width: number; offsets: ReturnType; dir?: boolean; el?: HTMLElement; indexEl?: number; }); /** * Calculates the difference between the current and previous dimensions. * If there are no previous dimensions, it will return zero differences. * * @returns An object containing the differences in `top` and `left` positions. */ calculateDimensionDifference(dimension: Dimension): { topDifference: number; leftDifference: number; }; /** * Updates the current dimensions by adding the given differences to the `top` and `left` values. * * @param topDifference - The difference to add to the current `top` value. * @param leftDifference - The difference to add to the current `left` value. */ adjustDimensions(difference: { topDifference: number; leftDifference: number; }): Dimension; /** * Determines the placement ('before' or 'after') based on the X and Y coordinates and center points. * * @param {number} mouseX X coordinate of the mouse * @param {number} mouseY Y coordinate of the mouse * @return {Placement} 'before' or 'after' */ determinePlacement(mouseX: number, mouseY: number): Placement; /** * Compares the current dimension object with another dimension to check equality. * * @param {Dimension} dimension - The dimension to compare against. * @returns {boolean} True if the dimensions are equal, otherwise false. */ equals(dimension: Dimension | undefined): boolean; /** * Creates a clone of the current Dimension object. * * @returns {Dimension} A new Dimension object with the same properties. */ clone(): Dimension; getDropArea(config: DroppableZoneConfig): Dimension; private adjustDropDimension; /** * Checks if the given coordinates are within the bounds of this dimension instance. * * @param {number} x - The X coordinate to check. * @param {number} y - The Y coordinate to check. * @returns {boolean} - True if the coordinates are within bounds, otherwise false. */ isWithinBounds(x: number, y: number): boolean; } declare abstract class SortableTreeNode { protected _model: T; protected _dragSource: DragSource; protected _dropAreaConfig: DroppableZoneConfig; /** The dimensions of the node. */ nodeDimensions?: Dimension; /** The dimensions of the child elements within the target node. */ childrenDimensions?: Dimension[]; constructor(model: T, dragSource?: DragSource); /** * Get the list of children of this node. * * @returns {SortableTreeNode[] | null} - List of children or null if no children exist. */ abstract getChildren(): SortableTreeNode[] | null; /** * Get the parent node of this node, or null if it has no parent. * * @returns {SortableTreeNode | null} - Parent node or null if it has no parent. */ abstract getParent(): SortableTreeNode | null; /** * Add a child node at a particular index. * * @param {SortableTreeNode} node - The node to add. * @param {number} index - The position to insert the child node at. * @returns {SortableTreeNode} - The added node. */ abstract addChildAt(node: SortableTreeNode, index: number): SortableTreeNode; /** * Remove a child node at a particular index. * * @param {number} index - The index to remove the child node from. */ abstract removeChildAt(index: number): void; /** * Get the index of a child node in the current node's list of children. * * @param {SortableTreeNode} node - The node whose index is to be found. * @returns {number} - The index of the node, or -1 if the node is not a child. */ abstract indexOfChild(node: SortableTreeNode): number; /** * Determine if a node can be moved to a specific index in another node's children list. * * @param {SortableTreeNode} source - The node to be moved. * @param {number} index - The index at which the node will be inserted. * @returns {boolean} - True if the move is allowed, false otherwise. */ abstract canMove(source: SortableTreeNode, index: number): boolean; /** * Get the view associated with this node, if any. * * @returns {View | undefined} - The view associated with this node, or undefined if none. */ abstract get view(): View | undefined; /** * Get the HTML element associated with this node. * * @returns {HTMLElement} - The associated HTML element. */ abstract get element(): HTMLElement | undefined; /** * Get the model associated with this node. * * @returns {T} - The associated model. */ get model(): T; get dragSource(): DragSource; get dropArea(): Dimension | undefined; /** * Checks if the given coordinates are within the bounds of this node. * * @param {number} x - The X coordinate to check. * @param {number} y - The Y coordinate to check. * @returns {boolean} - True if the coordinates are within bounds, otherwise false. */ isWithinDropBounds(x: number, y: number): boolean; equals(node?: SortableTreeNode): node is SortableTreeNode; adjustDimensions(diff: { topDifference: number; leftDifference: number; }): void; } declare abstract class BaseComponentNode extends SortableTreeNode { private displayCache; /** * Get the list of child components. * @returns {BaseComponentNode[] | null} - The list of children wrapped in * BaseComponentNode, or null if there are no children. */ getChildren(): BaseComponentNode[] | null; /** * Get the list of displayed children, i.e., components that have a valid HTML element. * Cached values are used to avoid recalculating the display status unnecessarily. * @returns {BaseComponentNode[] | null} - The list of displayed children wrapped in * BaseComponentNode, or null if there are no displayed children. */ private getDisplayedChildren; /** * Check if a child is displayed, using cached value if available. * @param {Component} child - The child component to check. * @returns {boolean} - Whether the child is displayed. */ private isChildDisplayed; /** * Get the parent component of this node. * @returns {BaseComponentNode | null} - The parent wrapped in BaseComponentNode, * or null if no parent exists. */ getParent(): BaseComponentNode | null; /** * Add a child component to this node at the specified index. * @param {BaseComponentNode} node - The child node to add. * @param {number} displayIndex - The visual index at which to insert the child. * @param {{ action: string }} options - Options for the operation, with the default action being 'add-component'. * @returns {BaseComponentNode} - The newly added child node wrapped in BaseComponentNode. */ addChildAt(node: BaseComponentNode, displayIndex: number, options?: { action: string; }): BaseComponentNode; /** * Remove a child component at the specified index. * @param {number} displayIndex - The visual index of the child to remove. * @param {{ temporary: boolean }} options - Whether to temporarily remove the child. */ removeChildAt(displayIndex: number, options?: { temporary: boolean; }): void; /** * Get the visual index of a child node within the displayed children. * @param {BaseComponentNode} node - The child node to locate. * @returns {number} - The index of the child node, or -1 if not found. */ indexOfChild(node: BaseComponentNode): number; /** * Get the index of the given node within the displayed children. * @param {BaseComponentNode} node - The node to find. * @returns {number} - The display index of the node, or -1 if not found. */ private getDisplayIndex; /** * Convert a display index to the actual index within the component's children array. * @param {number} index - The display index to convert. * @returns {number} - The corresponding real index, or -1 if not found. */ getRealIndex(index: number): number; /** * Check if a source node can be moved to a specified index within this component. * @param {BaseComponentNode} source - The source node to move. * @param {number} index - The display index to move the source to. * @returns {boolean} - True if the move is allowed, false otherwise. */ canMove(source: BaseComponentNode, index: number): boolean; /** * Abstract method to get the view associated with this component. * Subclasses must implement this method. * @abstract */ abstract get view(): any; /** * Abstract method to get the DOM element associated with this component. * Subclasses must implement this method. * @abstract */ abstract get element(): HTMLElement | undefined; /** * Reset the state of the node by clearing its status and disabling editing. */ restNodeState(): void; /** * Set the contentEditable property of the node's DOM element. * @param {boolean} value - True to make the content editable, false to disable editing. */ setContentEditable(value: boolean): void; /** * Disable editing capabilities for the component's view. * This method depends on the presence of the `disableEditing` method in the view. */ private disableEditing; /** * Clear the current state of the node by resetting its status. */ private clearState; /** * Set the state of the node to 'selected-parent'. */ setSelectedParentState(): void; /** * Determine if the component is a text node. * @returns {boolean} - True if the component is a text node, false otherwise. */ isTextNode(): boolean; /** * Determine if the component is textable. * @returns {boolean} - True if the component is textable, false otherwise. */ isTextable(): boolean; } declare class CanvasComponentNode extends BaseComponentNode { protected _dropAreaConfig: { ratio: number; minUndroppableDimension: number; maxUndroppableDimension: number; }; /** * Get the associated view of this component. * @returns The view associated with the component, or undefined if none. */ get view(): ComponentView | undefined; /** * Get the associated element of this component. * @returns The Element associated with the component, or undefined if none. */ get element(): HTMLElement | undefined; } declare class CanvasNewComponentNode extends CanvasComponentNode { canMove(source: CanvasNewComponentNode, index: number): boolean; private canMoveSingleContent; addChildAt(node: CanvasNewComponentNode, index: number): CanvasNewComponentNode; /** * Adds a single content item to the current node. * @param {ContentType} content - The content to add. * @param {number} index - The index where the content is to be added. * @param {boolean} insertingTextableIntoText - Whether the operation involves textable content. * @returns {CanvasNewComponentNode} - The newly added node. */ private addSingleChild; /** * Adds multiple content items as children, looping through the array. * @param {any[]} contentArray - Array of content items * @param {number} index - Index to start adding children * @param {boolean} insertingTextableIntoText - Whether inserting textable content * @returns {CanvasNewComponentNode} The last added node */ private addMultipleChildren; /** * Checks if the source component belongs to the same symbol model as the current component. * @param {Component | undefined} symbolModel - Symbol model to compare * @returns {boolean} Whether the source is the same symbol */ private isSourceSameSymbol; set content(content: ContentType | (() => ContentType)); } export type ContainerContext = { container: HTMLElement; itemSel: string; customTarget?: CustomTarget; document: Document; }; export interface DropLocationDeterminerOptions> { em: EditorModel; treeClass: new (model: T, dragSource?: DragSource) => NodeType; containerContext: ContainerContext; positionOptions: PositionOptions; dragDirection: DragDirection; eventHandlers: SorterEventHandlers; } /** * Represents the data related to the last move event during drag-and-drop sorting. * This type is discriminated by the presence or absence of a valid target node. */ export type lastMoveData = { /** The target node under the mouse pointer during the last move. */ targetNode?: NodeType; /** The node under the mouse pointer during this move*/ hoveredNode?: NodeType; /** The index where the placeholder or dragged element should be inserted. */ index?: number; /** Placement relative to the target ('before' or 'after'). */ placement?: Placement; /** The mouse event, used if we want to move placeholder with scrolling. */ mouseEvent?: MouseEvent; placeholderDimensions?: Dimension; }; declare class DropLocationDeterminer> extends View { em: EditorModel; treeClass: new (model: any, dragSource?: DragSource) => NodeType; positionOptions: PositionOptions; containerContext: ContainerContext; dragDirection: DragDirection; eventHandlers: SorterEventHandlers; sourceNodes: NodeType[]; lastMoveData: lastMoveData; containerOffset: { top: number; left: number; }; private moveThreshold; private rateLimiter; constructor(options: DropLocationDeterminerOptions); /** * Picking components to move * @param {HTMLElement[]} sourceElements * */ startSort(sourceNodes: NodeType[]): void; private bindDragEventHandlers; /** * Triggers the `onMove` event. * * This method is should be called when the user scrolls within the container, using the last recorded mouse event * to determine the new target. */ recalculateTargetOnScroll(): void; private onMove; private handleMove; private adjustForScroll; private restLastMoveData; private triggerLegacyOnMoveCallback; private triggerMoveEvent; /** * Handles the movement of the dragged element over a target node. * Updates the placeholder position and triggers relevant events when necessary. * * @param node - The node currently being hovered over. * @param mouseX - The x-coordinate of the mouse relative to the container. * @param mouseY - The y-coordinate of the mouse relative to the container. */ private getDropPosition; /** * Retrieves the target node based on the mouse event. * Determines the element being hovered, its corresponding model, and * calculates the valid parent node to use as the target node. * * @param mouseEvent - The mouse event containing the cursor position and target element. * @returns The target node if a valid one is found, otherwise undefined. */ private getTargetNode; /** * Creates a new hovered node or reuses the last hovered node if it is the same. * * @param hoveredModel - The model corresponding to the hovered element. * @returns The new or reused hovered node. */ private getOrCreateHoveredNode; /** * Checks if the target node has changed and returns the last one if they are identical. * * @param targetNode - The newly calculated target node. * @returns The new or reused target node. */ private getOrReuseTargetNode; private getMouseTargetElement; private onDragStart; endDrag(): void; cancelDrag(): void; private finalizeMove; private dropDragged; private triggerOnDragEndEvent; /** * Retrieves the first element that has a data model associated with it. * Traverses up the DOM tree from the given element until it reaches the container * or an element with a data model. * * @param mouseTargetEl - The element to start searching from. * @returns The first element with a data model, or null if not found. */ private getFirstElementWithAModel; private getValidParent; private handleParentTraversal; private getIndexInParent; private triggerDragValidation; /** * Clean up event listeners that were attached during the move. * * @param {HTMLElement} container - The container element. * @param {Document[]} docs - List of documents. * @private */ private cleanupEventListeners; /** * Determines if an element is in the normal flow of the document. * This checks whether the element is not floated or positioned in a way that removes it from the flow. * * @param {HTMLElement} el - The element to check. * @param {HTMLElement} [parent=document.body] - The parent element for additional checks (defaults to `document.body`). * @return {boolean} Returns `true` if the element is in flow, otherwise `false`. * @private */ private getDirection; /** * Get children dimensions * @param {NodeType} el Element root * @return {Array} * */ private getChildrenDim; /** * Gets the mouse position relative to the container, adjusting for scroll and canvas relative options. * * @return {{ mouseXRelativeToContainer: number, mouseYRelativeToContainer: number }} - The mouse X and Y positions relative to the container. * @private */ private getMousePositionRelativeToContainer; /** * Caches the container position and updates relevant variables for position calculation. * * @private */ private cacheContainerPosition; /** * Returns dimensions and positions about the element * @param {HTMLElement} el * @return {Dimension} */ private getDim; } declare class PlaceholderClass extends View { pfx: string; allowNesting: boolean; container: HTMLElement; el: HTMLElement; offset: { top: number; left: number; }; private moveLimiter; constructor(options: { container: HTMLElement; pfx?: string; allowNesting?: boolean; el: HTMLElement; offset: { top: number; left: number; }; }); show(): void; hide(): void; /** * Updates the position of the placeholder with a movement threshold. * @param {Dimension} elementDimension element dimensions. * @param {Placement} placement either before or after the target. */ move(elementDimension: Dimension, placement: Placement): void; private _move; /** * Sets the orientation of the placeholder based on the element dimensions. * @param {Dimension} elementDimension Dimensions of the element at the index. */ private setOrientationForDimension; /** * Sets the placeholder's class to vertical. */ private setOrientation; /** * Updates the CSS styles of the placeholder element. * @param {number} top Top position of the placeholder. * @param {number} left Left position of the placeholder. * @param {string} width Width of the placeholder. * @param {string} height Height of the placeholder. */ private updateStyles; private adjustOffset; } declare class Sorter> { em: EditorModel; treeClass: new (model: T, dragSource?: DragSource) => NodeType; placeholder: PlaceholderClass; dropLocationDeterminer: DropLocationDeterminer; positionOptions: PositionOptions; containerContext: SorterContainerContext; dragBehavior: SorterDragBehaviorOptions; eventHandlers: SorterEventHandlers; sourceNodes?: NodeType[]; constructor(sorterOptions: SorterOptions); /** * Picking components to move * @param {HTMLElement[]} sources[] * */ startSort(sources: { element?: HTMLElement; dragSource?: DragSource; }[]): void; validTarget(targetEl: HTMLElement | undefined, sources: { element?: HTMLElement; dragSource?: DragSource; }[], index: number): boolean; private getSourceNodes; /** * This method is should be called when the user scrolls within the container. */ protected recalculateTargetOnScroll(): void; /** * Called when the drag operation should be cancelled */ cancelDrag(): void; /** * Called to drop an item onto a valid target. */ endDrag(): void; private handlePlaceholderMove; /** * Creates a new placeholder element for the drag-and-drop operation. * * @returns {PlaceholderClass} The newly created placeholder instance. */ private createPlaceholder; private ensurePlaceholderElement; /** * Triggered when the offset of the editor is changed */ private updateOffset; /** * Finds the closest valid source element within the container context. * @param sourceElement - The initial source element to check. * @returns The closest valid source element, or null if none is found. */ private findValidSourceElement; protected bindDragEventHandlers(): void; private updatePlaceholderPosition; /** * Clean up event listeners that were attached during the move. * * @private */ protected cleanupEventListeners(): void; /** * Finalize the move. * * @private */ protected finalizeMove(): void; /** * Cancels the drag on Escape press ( nothing is dropped or moved ) * @param {KeyboardEvent} e - The keyboard event object. */ private rollback; protected triggerNullOnEndMove(dragIsCancelled: boolean): void; } export interface CategoryViewConfig { em: EditorModel; pStylePrefix?: string; stylePrefix?: string; } declare class CategoryView extends View { em: EditorModel; config: CategoryViewConfig; pfx: string; caretR: string; caretD: string; iconClass: string; activeClass: string; iconEl?: HTMLElement; typeEl?: HTMLElement; catName: string; events(): { "click [data-title]": string; }; template({ pfx, label, catName }: { pfx: string; label: string; catName: string; }): string; /** @ts-ignore */ attributes(): Record; constructor(o: any, config: CategoryViewConfig, catName: string); updateVisibility(): void; open(): void; close(): void; toggle(): void; getIconEl(): HTMLElement; getTypeEl(): HTMLElement; append(el: HTMLElement): void; render(): this; } interface CategoryProperties { /** * Category id. */ id: string; /** * Category label. */ label: string; /** * Category open state. * @default true */ open?: boolean; /** * Category order. */ order?: string | number; /** * Category attributes. * @default {} */ attributes?: Record; } export interface ItemsByCategory { category?: Category; items: T[]; } export declare class Category extends Model { view?: CategoryView; defaults(): { id: string; label: string; open: boolean; attributes: {}; }; getId(): string; getLabel(): string; } export type CategoryCollectionParams = ConstructorParameters>; export interface CategoryOptions { events?: { update?: string; }; em?: EditorModel; } export declare class Categories extends Collection { constructor(models?: CategoryCollectionParams[0], opts?: CategoryOptions); /** @ts-ignore */ add(model: (CategoryProperties | Category)[] | CategoryProperties | Category, opts?: AddOptions): Category; get(id: string | Category): Category; } export interface ModelWithCategoryProps { category?: string | CategoryProperties; } declare abstract class CollectionWithCategories> extends Collection { abstract getCategories(): Categories; initCategory(model: T): Category | undefined; } export declare class Blocks extends CollectionWithCategories { em: EditorModel; constructor(coll: any[], options: { em: EditorModel; }); getCategories(): Categories; handleAdd(model: Block): void; } /** @private */ export interface BlockProperties extends DraggableContent { /** * Block label, eg. `My block` */ label: string; /** * HTML string for the media/icon of the block, eg. ` editor.getWrapper().append(block.get('content')) */ onClick?: (block: Block, editor: Editor) => void; /** * Block attributes */ attributes?: Record; id?: string; /** * @deprecated */ activeOnRender?: boolean; } /** * @property {String} label Block label, eg. `My block` * @property {String|Object} content The content of the block. Might be an HTML string or a [Component Definition](/modules/Components.html#component-definition) * @property {String} [media=''] HTML string for the media/icon of the block, eg. ` editor.getWrapper().append(block.get('content'))` * @property {Object} [attributes={}] Block attributes to apply in the view element * * @module docsjs.Block */ export declare class Block extends Model { defaults(): { label: string; content: string; media: string; category: string; activate: boolean; select: undefined; resetId: boolean; disable: boolean; onClick: undefined; attributes: {}; dragDef: {}; }; get category(): Category | undefined; get parent(): Blocks; /** * Get block id * @returns {String} */ getId(): string; /** * Get block label * @returns {String} */ getLabel(): string; /** * Get block media * @returns {String} */ getMedia(): string | undefined; /** * Get block content * @returns {Object|String|Array} */ getContent(): ContentType | (() => ContentType) | undefined; /** * Get block component dragDef * @returns {ComponentDefinition} */ getDragDef(): ComponentDefinition | undefined; /** * Get block category label * @returns {String} */ getCategoryLabel(): string; } declare class ComponentSorter extends Sorter { targetIsText: boolean; __currentBlock?: Block; constructor({ em, treeClass, containerContext, dragBehavior, positionOptions, eventHandlers, }: { em: EditorModel; treeClass: new (model: Component, dragSource?: DragSource) => NodeType; containerContext: SorterContainerContext; dragBehavior: SorterDragBehaviorOptions; positionOptions?: PositionOptions; eventHandlers?: SorterEventHandlers; }); private onStartSort; protected bindDragEventHandlers(): void; protected cleanupEventListeners(): void; handleScrollEvent(...agrs: any[]): void; private onMouseMove; /** * Handles the drop action by moving the source nodes to the target node. * Calls appropriate handlers based on whether the move was successful or not. * * @param targetNode - The node where the source nodes will be dropped. * @param sourceNodes - The nodes being dropped. * @param index - The index at which to drop the source nodes. */ private onDrop; /** * Handles the addition of multiple source nodes to the target node. * If the move is valid, adds the nodes at the specified index and increments the index. * * @param targetNode - The target node where source nodes will be added. * @param sourceNodes - The nodes being added. * @param index - The initial index at which to add the source nodes. * @returns The list of successfully added nodes. */ private handleNodeAddition; /** * Determines if a source node position has changed. * * @param targetNode - The node where the source node will be moved. * @param sourceNode - The node being moved. * @param index - The index at which to move the source node. * @returns Whether the node can be moved. */ private isPositionChanged; /** * Moves a source node to the target node at the specified index, handling edge cases. * * @param targetNode - The node where the source node will be moved. * @param sourceNode - The node being moved. * @param index - The index at which to move the source node. * @returns An object containing the added node and its new index, or null if it couldn't be moved. */ private moveNode; /** * Triggers the end move event for a node that was added to the target. * * @param addedNode - The node that was moved and added to the target. */ private triggerEndMoveEvent; /** * Finalize the move by removing any helpers and selecting the target model. * * @private */ protected finalizeMove(): void; private onTargetChange; private updateTextViewCursorPosition; /** * Change Autoscroll while sorting * @param {Boolean} active */ private setAutoCanvasScroll; } export type DragStop = (cancel?: boolean) => void; declare class Droppable { em: EditorModel; canvas: CanvasModule; el: HTMLElement; counter: number; getSorterOptions?: (sorter: any) => Record | null; over?: boolean; dragStop?: DragStop; draggedNode?: CanvasNewComponentNode; sorter: ComponentSorter; setAbsoluteDragContent?: (cnt: any) => any; constructor(em: EditorModel, rootEl?: HTMLElement); toggleEffects(el: HTMLElement, enable: boolean): void; __customTglEff(enable: boolean): void; startCustom(): void; endCustom(cancel?: boolean): void; /** * This function is expected to be always executed at the end of d&d. */ endDrop(cancel?: boolean, ev?: Event): void; handleDragLeave(ev: Event): void; updateCounter(value: number, ev: Event): void; handleDragEnter(ev: DragEvent | Event): void; /** * Generates a temporary model of the content being dragged for use with the sorter. * @returns The temporary model representing the dragged content. */ private getTempDropModel; handleDragEnd(model: any, dt: any): void; /** * Always need to have this handler active for enabling the drop * @param {Event} ev */ handleDragOver(ev: Event): void; /** * WARNING: This function might fail to run on drop, for example, when the * drop, accidentally, happens on some external element (DOM not inside the iframe) */ handleDrop(ev: Event | DragEvent): void; getContentByData(dt: any): { content: any; }; } export interface PageManagerConfig extends ModuleConfig { /** * Default pages. */ pages?: PageProperties[]; /** * ID of the page to select on editor load. */ selected?: string; } export interface SelectableOption { /** * Select the page. */ select?: boolean; } export interface AbortOption { abort?: boolean; } declare enum PagesEvents { /** * @event `page:add` Added new page. The page is passed as an argument to the callback. * @example * editor.on('page:add', (page) => { ... }); */ add = "page:add", addBefore = "page:add:before", /** * @event `page:remove` Page removed. The page is passed as an argument to the callback. * @example * editor.on('page:remove', (page) => { ... }); */ remove = "page:remove", removeBefore = "page:remove:before", /** * @event `page:select` New page selected. The newly selected page and the previous one, are passed as arguments to the callback. * @example * editor.on('page:select', (page, previousPage) => { ... }); */ select = "page:select", selectBefore = "page:select:before", /** * @event `page:update` Page updated. The updated page and the object containing changes are passed as arguments to the callback. * @example * editor.on('page:update', (page, changes) => { ... }); */ update = "page:update", /** * @event `page` Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback. * @example * editor.on('page', ({ event, model, ... }) => { ... }); */ all = "page" } export declare class Frames extends ModuleCollection` content of the frame */ updateHead(): void; getEl(): HTMLIFrameElement; getCanvasModel(): Canvas; getWindow(): Window; getDoc(): Document; getHead(): HTMLHeadElement; getBody(): HTMLBodyElement; getWrapper(): HTMLElement; getJsContainer(): HTMLElement; getToolsEl(): HTMLElement; getGlobalToolsEl(): HTMLElement; getHighlighter(): HTMLElement; getBadgeEl(): HTMLElement; getOffsetViewerEl(): HTMLElement; getRect(): DOMRect; /** * Get rect data, not affected by the canvas zoom */ getOffsetRect(): { top: number; left: number; height: number; width: number; scrollTop: number; scrollLeft: number; scrollBottom: number; scrollRight: number; }; _getTool(name: string): HTMLElement; remove(...args: any): this; startAutoscroll(): void; stopAutoscroll(): void; showGlobalTools(): void; render(): this; renderScripts(): void; renderStyles(opts?: any): void; renderHead(): void; renderBody(): void; _toggleEffects(enable: boolean): void; _emitUpdate(): void; } export interface CssComposerConfig { /** * Style prefix. * @default 'css-' */ stylePrefix?: string; /** * Default CSS style rules */ rules?: Array; } export declare class CssRules extends Collection { editor: EditorModel; constructor(props: any, opt: any); toJSON(opts?: any): any; onAdd(model: CssRule, c: CssRules, o: any): void; onRemove(removed: CssRule): void; /** @ts-ignore */ add(models: any, opt?: any): any[]; } declare class CssRulesView extends View { atRules: Record; config: Record; em: EditorModel; pfx: string; renderStarted?: boolean; constructor(o: any); /** * Add to collection * @param {Object} model * @private * */ addTo(model: CssRule): void; /** * Add new object to collection * @param {Object} model * @param {Object} fragmentEl * @return {Object} * @private * */ addToCollection(model: CssRule, fragmentEl?: DocumentFragment): HTMLElement | undefined; getMediaWidth(mediaText: string): string; sortRules(a: number, b: number): number; render(): this; } /** @private */ export interface RuleOptions { /** * At-rule type, eg. `media` */ atRuleType?: string; /** * At-rule parameters, eg. `(min-width: 500px)` */ atRuleParams?: string; } /** @private */ export interface SetRuleOptions extends RuleOptions, UpdateStyleOptions { /** * If the rule exists already, merge passed styles instead of replacing them. */ addStyles?: boolean; } /** @private */ export interface GetSetRuleOptions extends UpdateStyleOptions { state?: string; mediaText?: string; addOpts?: ObjectAny; current?: boolean; } export type CssRuleStyle = Required["style"]; declare class CssComposer extends ItemManagerModule { rules: CssRules; rulesView?: CssRulesView; Selectors: typeof Selectors; storageKey: string; /** * Initializes module. Automatically called with a new instance of the editor * @param {Object} config Configurations * @private */ constructor(em: EditorModel); /** * On load callback * @private */ onLoad(): void; /** * Do stuff after load * @param {Editor} em * @private */ postLoad(): void; store(): any; load(data: any): any; /** * Add new rule to the collection, if not yet exists with the same selectors * @param {Array} selectors Array of selectors * @param {String} state Css rule state * @param {String} width For which device this style is oriented * @param {Object} props Other props for the rule * @param {Object} opts Options for the add of new rule * @return {Model} * @private * @example * var sm = editor.SelectorManager; * var sel1 = sm.add('myClass1'); * var sel2 = sm.add('myClass2'); * var rule = cssComposer.add([sel1, sel2], 'hover'); * rule.set('style', { * width: '100px', * color: '#fff', * }); * */ add(selectors: any, state?: string, width?: string, opts?: {}, addOpts?: {}): CssRule; /** * Get the rule * @param {String|Array} selectors Array of selectors or selector string, eg `.myClass1.myClass2` * @param {String} state Css rule state, eg. 'hover' * @param {String} width Media rule value, eg. '(max-width: 992px)' * @param {Object} ruleProps Other rule props * @return {Model|null} * @private * @example * const sm = editor.SelectorManager; * const sel1 = sm.add('myClass1'); * const sel2 = sm.add('myClass2'); * const rule = cssComposer.get([sel1, sel2], 'hover', '(max-width: 992px)'); * // Update the style * rule.set('style', { * width: '300px', * color: '#000', * }); * */ get(selectors: any, state?: string, width?: string, ruleProps?: Omit): CssRule | undefined; getAll(): CssRules; /** * Add a raw collection of rule objects * This method overrides styles, in case, of already defined rule * @param {String|Array} data CSS string or an array of rule objects, eg. [{selectors: ['class1'], style: {....}}, ..] * @param {Object} opts Options * @param {Object} props Additional properties to add on rules * @return {Array} * @private */ addCollection(data: string | CssRuleJSON[], opts?: Record, props?: {}): CssRule[]; /** * Add CssRules via CSS string. * @param {String} css CSS string of rules to add. * @returns {Array<[CssRule]>} Array of rules * @example * const addedRules = css.addRules('.my-cls{ color: red } @media (max-width: 992px) { .my-cls{ color: darkred } }'); * // Check rules * console.log(addedRules.map(rule => rule.toCSS())); */ addRules(css: string): CssRule[]; /** * Add/update the CssRule. * @param {String} selectors Selector string, eg. `.myclass` * @param {Object} style Style properties and values. If the rule exists, styles will be replaced unless `addStyles` option is used. * @param {Object} [opts={}] Additional properties. * @param {String} [opts.atRuleType=''] At-rule type, eg. `media`. * @param {String} [opts.atRuleParams=''] At-rule parameters, eg. `(min-width: 500px)`. * @param {Boolean} [opts.addStyles=false] If the rule exists already, merge passed styles instead of replacing them. * @returns {[CssRule]} The new/updated CssRule. * @example * // Simple class-based rule * const rule = css.setRule('.class1.class2', { color: 'red' }); * console.log(rule.toCSS()) // output: .class1.class2 { color: red } * // With state and other mixed selector * const rule = css.setRule('.class1.class2:hover, div#myid', { color: 'red' }); * // output: .class1.class2:hover, div#myid { color: red } * // With media * const rule = css.setRule('.class1:hover', { color: 'red' }, { * atRuleType: 'media', * atRuleParams: '(min-width: 500px)', * }); * // output: `@media (min-width: 500px) { .class1:hover { color: red } }` * * // Update styles of existent rule * css.setRule('.class1', { color: 'red', background: 'red' }); * css.setRule('.class1', { color: 'blue' }, { addStyles: true }); * // output: .class1 { color: blue; background: red } */ setRule(selectors: any, style?: CssRuleProperties["style"], opts?: SetRuleOptions): CssRule; /** * Get the CssRule. * @param {String} selectors Selector string, eg. `.myclass:hover` * @param {Object} [opts={}] Additional properties * @param {String} [opts.atRuleType=''] At-rule type, eg. `media` * @param {String} [opts.atRuleParams=''] At-rule parameters, eg. '(min-width: 500px)' * @returns {[CssRule]} * @example * const rule = css.getRule('.myclass1:hover'); * const rule2 = css.getRule('.myclass1:hover, div#myid'); * const rule3 = css.getRule('.myclass1', { * atRuleType: 'media', * atRuleParams: '(min-width: 500px)', * }); */ getRule(selectors: any, opts?: RuleOptions): CssRule | undefined; /** * Get all rules or filtered by a matching selector. * @param {String} [selector=''] Selector, eg. `.myclass` * @returns {Array<[CssRule]>} * @example * // Take all the component specific rules * const id = someComponent.getId(); * const rules = css.getRules(`#${id}`); * console.log(rules.map(rule => rule.toCSS())) * // All rules in the project * console.log(css.getRules()) */ getRules(selector?: string): CssRule[]; /** * Add/update the CSS rule with id selector * @param {string} name Id selector name, eg. 'my-id' * @param {Object} style Style properties and values * @param {Object} [opts={}] Custom options, like `state` and `mediaText` * @return {CssRule} The new/updated rule * @private * @example * const rule = css.setIdRule('myid', { color: 'red' }); * const ruleHover = css.setIdRule('myid', { color: 'blue' }, { state: 'hover' }); * // This will add current CSS: * // #myid { color: red } * // #myid:hover { color: blue } */ setIdRule(name: string, style?: CssRuleStyle, opts?: GetSetRuleOptions): CssRule; /** * Get the CSS rule by id selector * @param {string} name Id selector name, eg. 'my-id' * @param {Object} [opts={}] Custom options, like `state` and `mediaText` * @return {CssRule} * @private * @example * const rule = css.getIdRule('myid'); * const ruleHover = css.setIdRule('myid', { state: 'hover' }); */ getIdRule(name: string, opts?: GetSetRuleOptions): CssRule | undefined; /** * Add/update the CSS rule with class selector * @param {string} name Class selector name, eg. 'my-class' * @param {Object} style Style properties and values * @param {Object} [opts={}] Custom options, like `state` and `mediaText` * @return {CssRule} The new/updated rule * @private * @example * const rule = css.setClassRule('myclass', { color: 'red' }); * const ruleHover = css.setClassRule('myclass', { color: 'blue' }, { state: 'hover' }); * // This will add current CSS: * // .myclass { color: red } * // .myclass:hover { color: blue } */ setClassRule(name: string, style?: CssRuleStyle, opts?: GetSetRuleOptions): CssRule; /** * Get the CSS rule by class selector * @param {string} name Class selector name, eg. 'my-class' * @param {Object} [opts={}] Custom options, like `state` and `mediaText` * @return {CssRule} * @private * @example * const rule = css.getClassRule('myclass'); * const ruleHover = css.getClassRule('myclass', { state: 'hover' }); */ getClassRule(name: string, opts?: GetSetRuleOptions): CssRule | undefined; /** * Remove rule, by CssRule or matching selector (eg. the selector will match also at-rules like `@media`) * @param {String|[CssRule]|Array<[CssRule]>} rule CssRule or matching selector. * @return {Array<[CssRule]>} Removed rules * @example * // Remove by CssRule * const toRemove = css.getRules('.my-cls'); * css.remove(toRemove); * // Remove by selector * css.remove('.my-cls-2'); */ remove(rule: string | CssRule, opts?: any): CssRule[] | (CssRule & any[]); /** * Remove all rules * @return {this} */ clear(opts?: {}): this; getComponentRules(cmp: Component, opts?: GetSetRuleOptions): CssRule[]; /** * Render the block of CSS rules * @return {HTMLElement} * @private */ render(): HTMLElement; checkId(rule: CssRuleJSON | CssRuleJSON[], opts?: { idMap?: PrevToNewIdMap; }): CssRuleJSON[]; destroy(): void; } declare class ComponentsView extends View { opts: any; config: DomComponentsConfig & { frameView?: FrameView; }; em: EditorModel; parentEl?: HTMLElement; compView: typeof ComponentView; initialize(o: any): void; removeChildren(removed: Component, coll: any, opts?: {}): void; /** * Add to collection * @param {Model} model * @param {Collection} coll * @param {Object} opts * @private * */ addTo(model: Component): void; /** * Add new object to collection * @param {Object} Model * @param {Object} Fragment collection * @param {Integer} Index of append * * @return {Object} Object rendered * @private * */ addToCollection(model: Component, fragment?: DocumentFragment | null, index?: number): HTMLElement | Text; resetChildren(models: Components, opts?: ResetComponentsOptions): void; render(parent?: HTMLElement): this; } export type ClbObj = ReturnType; export interface IComponentView extends ExtractMethods { } export declare class ComponentView extends View { /** @ts-ignore */ model: TComp; /** @ts-ignore */ className(): any; /** @ts-ignore */ tagName(): string; modelOpt: ComponentOptions; em: EditorModel; opts?: any; pfx?: string; ppfx?: string; attr?: Record; classe?: string; config: DomComponentsConfig; childrenView?: ComponentsView; getChildrenSelector?: Function; getTemplate?: Function; scriptContainer?: HTMLElement; preinitialize(opt?: any): void; initialize(opt?: any): void; get __cmpStyleOpts(): GetSetRuleOptions; get frameView(): FrameView; get createDoc(): Document; __isDraggable(): string | boolean | DraggableDroppableFn | undefined; _clbObj(): { editor: Editor; model: TComp; el: HTMLElement; }; /** * Initialize callback */ init(opts: ClbObj): void; /** * Remove callback */ removed(opts: ClbObj): void; /** * On render callback */ onRender(opts: ClbObj): void; /** * Callback executed when the `active` event is triggered on component */ onActive(ev: Event): void; /** * Callback executed when the `disable` event is triggered on component */ onDisable(opts?: DisableOptions): void; remove(): this; handleDragStart(event: Event): false | undefined; initClasses(): void; initComponents(opts?: { avoidRender?: boolean; }): void; /** * Handle any property change * @private */ handleChange(): void; /** * Import, if possible, classes inside main container * @private * */ importClasses(): void; /** * Update item on status change * @param {Event} e * @private * */ updateStatus(opts?: { noExtHl?: boolean; avoidHover?: boolean; }): void; /** * Update highlight attribute * @private * */ updateHighlight(): void; /** * Update style attribute * @private * */ updateStyle(m?: any, v?: any, opts?: ObjectAny): void; updateStyles(): void; /** * Update classe attribute * @private * */ updateClasses(): void; /** * Update single attribute * @param {[type]} name [description] * @param {[type]} value [description] */ setAttribute(name: string, value: any): void; /** * Get classes from attributes. * This method is called before initialize * * @return {Array}|null * @private * */ getClasses(): any; /** * Update attributes * @private * */ updateAttributes(): void; /** * Update component content * @private * */ updateContent(): void; /** * Prevent default helper * @param {Event} e * @private */ prevDef(e: Event): void; /** * Render component's script * @private */ updateScript(): void; /** * Return children container * Differently from a simple component where children container is the * component itself * * * * You could have the children container more deeper * *
*
*
*
* *
*
*
* @return HTMLElement * @private */ getChildrenContainer(): HTMLElement; /** * This returns rect informations not affected by the canvas zoom. * The method `getBoundingClientRect` doesn't work here and we * have to take in account offsetParent */ getOffsetRect(): { top: number; left: number; bottom: number; right: number; }; isInViewport(): boolean; scrollIntoView(opts?: { force?: boolean; } & ScrollIntoViewOptions): void; /** * Recreate the element of the view */ reset(): void; _setData(): void; _createElement(tagName: string): Node; /** * Render children components * @private */ renderChildren(): void; renderAttributes(): void; onAttrUpdate(): void; render(): this; postRender(): void; static getEvents(): any; } declare enum CanvasSpotBuiltInTypes { Select = "select", Hover = "hover", Spacing = "spacing", Target = "target", Resize = "resize" } export type CanvasSpotBuiltInType = `${CanvasSpotBuiltInTypes}`; export type CanvasSpotType = LiteralUnion; /** @private */ export interface CanvasSpotBase { /** * Spot type, eg. `select`. */ type: T; /** * Spot ID. */ id: string; /** * Fixed box rect of the spot, eg. `{ width: 100, height: 100, x: 0, y: 0 }`. */ boxRect?: BoxRect; /** * Component to which the spot will be attached. */ component?: Component; /** * ComponentView to which the spot will be attached. */ componentView?: ComponentView; frame?: Frame; } export interface CanvasSpotProps extends CanvasSpotBase { } /** * Canvas spots are elements drawn on top of the canvas. They can be used to represent anything you * might need but the most common use case of canvas spots is rendering information and managing * components rendered in the canvas. * Read here for more information about [Canvas Spots](https://grapesjs.com/docs/modules/Canvas.html#canvas-spots) * * [Component]: component.html * * @property {String} id Spot ID. * @property {String} type Spot type. * @property {[Component]} [component] Component to which the spot will be attached. * @property {ComponentView} [componentView] ComponentView to which the spot will be attached. * @property {Object} [boxRect] Fixed box rect of the spot, eg. `{ width: 100, height: 100, x: 0, y: 0 }`. * */ export declare class CanvasSpot extends ModuleModel { defaults(): T; get type(): "" | T["type"]; get component(): Component | undefined; get componentView(): ComponentView | undefined; get el(): HTMLElement | undefined; /** * Get the box rect of the spot. * @param {Object} [opts={}] * @returns {Object} The box rect object * @example * canvasSpot.getBoxRect(); * // { width: 100, height: 50, x: 0, y: 0 } */ getBoxRect(opts?: GetBoxRectOptions): BoxRect; /** * Get the style object of the spot. * @param {Object} [opts={}] * @returns {CSSStyleDeclaration} [opts] * @example * canvasSpot.getStyle(); * // { width: '100px', height: '...', ... } */ getStyle(opts?: { boxRect?: BoxRect; } & GetBoxRectOptions): Partial; /** * Check the spot type. * @param {String} type * @returns {Boolean} * @example * canvasSpot.isType('select'); */ isType(type: E["type"]): this is CanvasSpot; } export interface CanvasConfig { stylePrefix?: string; /** * Append external scripts to the `` of the iframe. * Be aware that these scripts will not be printed in the export code. * @default [] * @example * scripts: [ 'https://...1.js', 'https://...2.js' ] * // or passing objects as attributes * scripts: [ { src: '/file.js', someattr: 'value' }, ... ] */ scripts?: (string | Record)[]; /** * Append external styles to the `` of the iframe. * Be aware that these scripts will not be printed in the export code. * @default [] * @example * styles: [ 'https://...1.css', 'https://...2.css' ] * // or passing objects as attributes * styles: [ { href: '/style.css', someattr: 'value' }, ... ] */ styles?: (string | Record)[]; /** * Add custom badge naming strategy. * @example * customBadgeLabel: component => component.getName(), */ customBadgeLabel?: (component: Component) => string; /** * Indicate when to start the autoscroll of the canvas on component/block dragging (value in px). * @default 50 */ autoscrollLimit?: number; /** * Experimental: external highlighter box */ extHl?: boolean; /** * Initial content to load in all frames. * The default value enables the standard mode for the iframe. * @default '' */ frameContent?: string; /** * Initial style to load in all frames. */ frameStyle?: string; /** * When some textable component is selected and focused (eg. input or text component), the editor * stops some commands (eg. disables the copy/paste of components with CTRL+C/V to allow the copy/paste of the text). * This option allows to customize, by a selector, which element should not be considered textable. */ notTextable?: string[]; /** * By default, the editor allows to drop external elements by relying on the native HTML5 * drag & drop API (eg. like a D&D of an image file from your desktop). * If you want to customize how external elements are interpreted by the editor, you can rely * on `canvas:dragdata` event, eg. https://github.com/GrapesJS/grapesjs/discussions/3849 * @default true */ allowExternalDrop?: boolean; /** * Disable the rendering of built-in canvas spots. * * Read here for more information about [Canvas Spots](https://grapesjs.com/docs/modules/Canvas.html#canvas-spots). * @example * // Disable only the hover type spot * customSpots: { hover: true }, * * // Disable all built-in spots * customSpots: true, */ customSpots?: boolean | Partial>; /** * Experimental: enable infinite canvas. */ infiniteCanvas?: boolean; /** * Enables the scrollable canvas feature. * * When this feature flag is set to `true`, the canvas element * will have its `overflow` style set to `auto`, allowing users to scroll * the canvas content if it exceeds the visible area. This is useful for * handling large diagrams or zoomed-in views where parts of the content * are initially hidden. If `false`, the canvas will use default overflow (typically hidden). * * @default false */ scrollableCanvas?: boolean; } export declare class CanvasSpots extends ModuleCollection { refreshDbn: Debounced; constructor(module: CanvasModule, models?: CanvasSpot[] | CanvasSpotProps[]); get em(): EditorModel; get events(): typeof CanvasEvents; refresh(): void; onAdd(spot: CanvasSpot): void; onChange(spot: CanvasSpot): void; onRemove(spot: CanvasSpot): void; __trgEvent(event: string, props: ObjectAny): void; } declare class AutoScroller { private eventEl?; private scrollEl?; private dragging; private lastClientY?; private lastMaxHeight; private onScroll?; private autoscrollLimit; private zoom; /** * When an element is inside an iframe, its `getBoundingClientRect()` values * are relative to the iframe's document, not the main window's. */ private rectIsInScrollIframe; constructor(autoscrollLimit?: number, opts?: { lastMaxHeight?: number; onScroll?: () => void; rectIsInScrollIframe?: boolean; }); start(eventEl: HTMLElement, scrollEl: HTMLElement | Window, opts?: { lastMaxHeight?: number; zoom?: number; }): void; private autoscroll; private getEventElHeight; private updateClientY; private getElScrollTop; private toggleAutoscrollFx; stop(): void; } export type CanvasEvent = `${CanvasEvents}`; declare class CanvasModule extends Module { autoScroller: AutoScroller; /** * Get configuration object * @name getConfig * @function * @return {Object} */ /** * Used inside RTE * @private */ getCanvasView(): CanvasView; canvas: Canvas; model: Canvas; spots: CanvasSpots; events: typeof CanvasEvents; framesById: Record; private canvasView?; /** * Initialize module. Automatically called with a new instance of the editor * @param {Object} config Configurations * @private */ constructor(em: EditorModel); postLoad(): void; getModel(): Canvas; /** * Get the canvas element * @returns {HTMLElement} */ getElement(): HTMLElement; getFrame(index?: number): Frame; /** * Get the main frame element of the canvas * @returns {HTMLIFrameElement} */ getFrameEl(): HTMLIFrameElement; getFramesEl(): HTMLElement; /** * Get the main frame window instance * @returns {Window} */ getWindow(): Window; /** * Get the main frame document element * @returns {HTMLDocument} */ getDocument(): Document; /** * Get the main frame body element * @return {HTMLBodyElement} */ getBody(): HTMLBodyElement; _getLocalEl(globalEl: any, compView: ComponentView, method: keyof FrameView): any; /** * Returns element containing all global canvas tools * @returns {HTMLElement} * @private */ getGlobalToolsEl(): HTMLElement | undefined; /** * Returns element containing all canvas tools * @returns {HTMLElement} * @private */ getToolsEl(compView?: any): any; /** * Returns highlighter element * @returns {HTMLElement} * @private */ getHighlighter(compView?: any): any; /** * Returns badge element * @returns {HTMLElement} * @private */ getBadgeEl(compView: any): any; /** * Returns placer element * @returns {HTMLElement} * @private */ getPlacerEl(): HTMLElement | undefined; /** * Returns ghost element * @returns {HTMLElement} * @private */ getGhostEl(): HTMLElement | undefined; /** * Returns toolbar element * @returns {HTMLElement} * @private */ getToolbarEl(): HTMLElement | undefined; /** * Returns resizer element * @returns {HTMLElement} * @private */ getResizerEl(): HTMLElement | undefined; /** * Returns offset viewer element * @returns {HTMLElement} * @private */ getOffsetViewerEl(compView: any): any; /** * Returns fixed offset viewer element * @returns {HTMLElement} * @private */ getFixedOffsetViewerEl(): HTMLElement | undefined; getSpotsEl(): HTMLElement | undefined; render(): HTMLElement; /** * Get frame position * @returns {Object} * @private */ getOffset(): { top: number; left: number; }; /** * Get the offset of the passed component element * @param {HTMLElement} el * @returns {Object} * @private */ offset(el: HTMLElement): { top: number; left: number; width: number; height: number; }; /** * Set custom badge naming strategy * @param {Function} f * @example * canvas.setCustomBadgeLabel(function(component){ * return component.getName(); * }); */ setCustomBadgeLabel(f: Function): void; /** * Get element position relative to the canvas * @param {HTMLElement} el * @returns {Object} * @private */ getElementPos(el: HTMLElement, opts?: any): { top: number; left: number; height: number; width: number; zoom: number; rect: { top: number; left: number; width: number; height: number; }; }; /** * Returns element's offsets like margins and paddings * @param {HTMLElement} el * @returns {Object} * @private */ getElementOffsets(el: HTMLElement): MarginPaddingOffsets; /** * Get canvas rectangular data * @returns {Object} */ getRect(): { topScroll: number; leftScroll: number; top: number; left: number; width: number; height: number; }; /** * This method comes handy when you need to attach something like toolbars * to elements inside the canvas, dealing with all relative position, * offsets, etc. and returning as result the object with positions which are * viewable by the user (when the canvas is scrolled the top edge of the element * is not viewable by the user anymore so the new top edge is the one of the canvas) * * The target should be visible before being passed here as invisible elements * return empty string as width * @param {HTMLElement} target The target in this case could be the toolbar * @param {HTMLElement} element The element on which I'd attach the toolbar * @param {Object} options Custom options * @param {Boolean} options.toRight Set to true if you want the toolbar attached to the right * @return {Object} * @private */ getTargetToElementDim(target: HTMLElement, element: HTMLElement, options?: any): { top: number; left: any; elementTop: any; elementLeft: any; elementWidth: any; elementHeight: any; targetWidth: number; targetHeight: number; canvasTop: number; canvasLeft: number; canvasWidth: number; canvasHeight: number; } | undefined; canvasRectOffset(el: HTMLElement, pos: { top: number; left: number; }, opts?: any): { top: number; left: number; }; /** * * @param {HTMLElement} el The component element in the canvas * @param {HTMLElement} targetEl The target element to position (eg. toolbar) * @param {Object} opts * @private */ getTargetToElementFixed(el: HTMLElement, targetEl: HTMLElement, opts?: any): { top: number; left: any; canvasOffsetTop: any; canvasOffsetLeft: any; elRect: any; canvasOffset: any; canvasRect: ElementRect; targetWidth: number; targetHeight: number; }; /** * Instead of simply returning e.clientX and e.clientY this function * calculates also the offset based on the canvas. This is helpful when you * need to get X and Y position while moving between the editor area and * canvas area, which is in the iframe * @param {Event} e * @return {Object} * @private */ getMouseRelativePos(e: any, opts?: any): { y: number; x: number; }; /** * X and Y mouse position relative to the canvas * @param {Event} ev * @return {Object} * @private */ getMouseRelativeCanvas(ev: MouseEvent | { clientX: number; clientY: number; }, opts?: Record): { y: number; x: number; }; /** * Start custom drag-and-drop process. * * @param {DragSource} dragSource - The source object for the drag operation, containing the component being dragged. * @example * // as component definition * canvas.startDrag({ * content: { type: 'my-component' } * }); * // as HTML * canvas.startDrag({ * content: '
...
' * }); */ startDrag(dragSource: DragSource): void; /** * Ends the drag-and-drop process, resetting the drag source and clearing any drag results. * This method can be used to finalize custom drag-and-drop content operations. * @example * canvas.startDrag({...}); * // ... drag finished ... * canvas.endDrag(); */ endDrag(): void; /** * Check if the canvas is focused * @returns {Boolean} */ hasFocus(): boolean; /** * Detects if some input is focused (input elements, text components, etc.) * @return {Boolean} * @private */ isInputFocused(): boolean | null; /** * Scroll canvas to the element if it's not visible. The scrolling is * executed via `scrollIntoView` API and options of this method are * passed to it. For instance, you can scroll smoothly by using * `{ behavior: 'smooth' }`. * @param {HTMLElement|[Component]} el * @param {Object} [opts={}] Options, same as options for `scrollIntoView` * @param {Boolean} [opts.force=false] Force the scroll, even if the element is already visible * @example * const selected = editor.getSelected(); * // Scroll smoothly (this behavior can be polyfilled) * canvas.scrollTo(selected, { behavior: 'smooth' }); * // Force the scroll, even if the element is already visible * canvas.scrollTo(selected, { force: true }); */ scrollTo(el: any, opts?: {}): void; /** * Start autoscroll * @private */ startAutoscroll(frame?: Frame): void; /** * Stop autoscroll * @private */ stopAutoscroll(frame?: Frame): void; /** * Set canvas zoom value * @param {Number} value The zoom value, from 0 to 100 * @returns {this} * @example * canvas.setZoom(50); // set zoom to 50% */ setZoom(value: number | string, opts?: SetZoomOptions): this; /** * Get canvas zoom value * @returns {Number} * @example * canvas.setZoom(50); // set zoom to 50% * const zoom = canvas.getZoom(); // 50 */ getZoom(): number; /** * Set canvas position coordinates * @param {Number} x Horizontal position * @param {Number} y Vertical position * @returns {this} * @example * canvas.setCoords(100, 100); */ setCoords(x?: string | number, y?: string | number, opts?: ToWorldOption): this; /** * Get canvas position coordinates * @returns {Object} Object containing coordinates * @example * canvas.setCoords(100, 100); * const coords = canvas.getCoords(); * // { x: 100, y: 100 } */ getCoords(): Coordinates; /** * Get canvas pointer position coordinates. * @returns {Object} Object containing pointer coordinates * @private * @example * const worldPointer = canvas.getPointer(); * const screenPointer = canvas.getPointer(true); */ getPointer(screen?: boolean): Coordinates; getZoomDecimal(): number; getZoomMultiplier(): number; fitViewport(opts?: FitViewportOptions): void; toggleFramesEvents(on: boolean): void; getFrames(): Frame[]; /** * Add new frame to the canvas * @param {Object} props Frame properties * @returns {[Frame]} * @private * @example * canvas.addFrame({ * name: 'Mobile home page', * x: 100, // Position in canvas * y: 100, * width: 500, // Frame dimensions * height: 600, * // device: 'DEVICE-ID', * components: [ * '

Title frame

', * '

Paragraph frame

', * ], * styles: ` * .testh { color: red; } * .testp { color: blue; } * `, * }); */ addFrame(props?: {}, opts?: {}): Frame; /** * Get the last created Component from a drag & drop to the canvas. * @returns {[Component]|undefined} */ getLastDragResult(): Component | undefined; /** * Add or update canvas spot. * @param {Object} props Canvas spot properties. * @param opts * @returns {[CanvasSpot]} * @example * // Add new canvas spot * const spot = canvas.addSpot({ * type: 'select', // 'select' is one of the built-in spots * component: editor.getSelected(), * }); * * // Add custom canvas spot * const spot = canvas.addSpot({ * type: 'my-custom-spot', * component: editor.getSelected(), * }); * // Update the same spot by reusing its ID * canvas.addSpot({ * id: spot.id, * component: anotherComponent, * }); */ addSpot(props: Omit & { id?: string; }, opts?: AddOptions): CanvasSpot; /** * Get canvas spots. * @param {Object} [spotProps] Canvas spot properties for filtering the result. With no properties, all available spots will be returned. * @returns {[CanvasSpot][]} * @example * canvas.addSpot({ type: 'select', component: cmp1 }); * canvas.addSpot({ type: 'select', component: cmp2 }); * canvas.addSpot({ type: 'target', component: cmp3 }); * * // Get all spots * const allSpots = canvas.getSpots(); * allSpots.length; // 3 * * // Get all 'select' spots * const allSelectSpots = canvas.getSpots({ type: 'select' }); * allSelectSpots.length; // 2 */ getSpots(spotProps?: Partial): CanvasSpot[]; /** * Remove canvas spots. * @param {Object|[CanvasSpot][]} [spotProps] Canvas spot properties for filtering spots to remove or an array of spots to remove. With no properties, all available spots will be removed. * @returns {[CanvasSpot][]} * @example * canvas.addSpot({ type: 'select', component: cmp1 }); * canvas.addSpot({ type: 'select', component: cmp2 }); * canvas.addSpot({ type: 'target', component: cmp3 }); * * // Remove all 'select' spots * canvas.removeSpots({ type: 'select' }); * * // Remove spots by an array of canvas spots * const filteredSpots = canvas.getSpots().filter(spot => myCustomCondition); * canvas.removeSpots(filteredSpots); * * // Remove all spots * canvas.removeSpots(); */ removeSpots(spotProps?: Partial | CanvasSpot[]): CanvasSpot[]; /** * Check if the built-in canvas spot has a declared custom rendering. * @param {String} type Built-in canvas spot type * @returns {Boolean} * @example * grapesjs.init({ * // ... * canvas: { * // avoid rendering the built-in 'target' canvas spot * customSpots: { target: true } * } * }); * // ... * canvas.hasCustomSpot('select'); // false * canvas.hasCustomSpot('target'); // true */ hasCustomSpot(type?: CanvasSpotBuiltInTypes): boolean; /** * Transform a box rect from the world coordinate system to the screen one. * @param {Object} boxRect * @returns {Object} */ getWorldRectToScreen(boxRect: Parameters[0]): BoxRect | undefined; /** * Update canvas for spots/tools positioning. * @param {Object} [opts] Options. * @param {Object} [opts.spots=false] Update the position of spots. */ refresh(opts?: CanvasRefreshOptions): void; refreshSpots(): void; destroy(): void; } /** * @property {Object|String} component Wrapper component definition. You can also pass an HTML string as components of the default wrapper component. * @property {String} [width=''] Width of the frame. By default, the canvas width will be taken. * @property {String} [height=''] Height of the frame. By default, the canvas height will be taken. * @property {Number} [x=0] Horizontal position of the frame in the canvas. * @property {Number} [y=0] Vertical position of the frame in the canvas. * */ export declare class Frame extends ModuleModel { defaults(): { x: number; y: number; changesCount: number; attributes: {}; width: null; height: null; head: never[]; component: string; styles: string; refFrame: null; _undo: boolean; _undoexc: string[]; }; view?: FrameView; /** * @hideconstructor */ constructor(module: CanvasModule, attr: any); get width(): number; get height(): number; get head(): { tag: string; attributes: any; }[]; get refFrame(): Frame | undefined; get root(): ComponentWrapper; initRefs(): void; getBoxRect(): BoxRect; onRemove(): void; changesUp(opt?: any): void; getComponent(): ComponentWrapper; getStyles(): any; disable(): void; remove(): this; getHead(): { tag: string; attributes: any; }[]; setHead(value: { tag: string; attributes: any; }[]): this; addHeadItem(item: { tag: string; attributes: any; }): void; getHeadByAttr(attr: string, value: any, tag: string): { tag: string; attributes: any; }; removeHeadByAttr(attr: string, value: any, tag: string): void; addLink(href: string): void; removeLink(href: string): void; addScript(src: string): void; removeScript(src: string): void; getPage(): Page | undefined; _emitUpdated(data?: {}): void; hasAutoHeight(): boolean; toJSON(opts?: any): any; } export interface TraitManagerConfig { /** * Style prefix. * @default 'trt-' */ stylePrefix?: string; /** * Specify the element to use as a container, string (query) or HTMLElement. * With the empty value, nothing will be rendered. * @default '' */ appendTo?: string | HTMLElement; /** * Avoid rendering the default Trait Manager UI. * More about it here: [Custom Trait Manager](https://grapesjs.com/docs/modules/Traits.html#custom-trait-manager). * @default false */ custom?: boolean; optionsTarget?: Record[]; } declare class TraitView extends View { pfx: string; ppfx: string; config: any; clsField: string; elInput: HTMLInputElement; input?: HTMLInputElement; $input?: JQuery; eventCapture: string[]; noLabel?: boolean; em: EditorModel; target: Component; createLabel?: (data: { label: string; component: Component; trait: TraitView; }) => string | HTMLElement; createInput?: (data: ReturnType) => string | HTMLElement; events: any; appendInput: boolean; /** @ts-ignore */ attributes(): Record; templateLabel(cmp?: Component): string; templateInput(data: ReturnType): string; constructor(o?: any); getClbOpts(): { component: Component; trait: Trait; elInput: HTMLInputElement; }; removeView(): void; init(): void; removed(): void; onRender(props: ReturnType): void; onUpdate(props: ReturnType): void; onEvent(props: ReturnType & { event: Event; }): void; /** * Fires when the input is changed * @private */ onChange(event: Event): void; getValueForTarget(): any; setInputValue(value: string): void; /** * On change callback * @private */ onValueChange(_m: Trait, _v: string, opts?: SetOptions & { fromTarget?: boolean; }): void; /** * Render label * @private */ renderLabel(): void; /** * Returns label for the input * @return {string} * @private */ getLabel(): any; /** * Returns current target component */ getComponent(): Component; /** * Returns input element * @return {HTMLElement} * @private */ getInputEl(): HTMLInputElement | undefined; getInputElem(): HTMLInputElement; getModelValue(): any; getElInput(): HTMLInputElement; /** * Renders input * @private * */ renderField(): void; hasLabel(): boolean; rerender(): void; postUpdate(): void; render(): this; } declare class DomainViews extends View { config?: any; items: any[]; ns?: string; itemView?: any; itemsView: any; itemType: string; reuseView: boolean; constructor(opts?: any, config?: any, autoAdd?: boolean); /** * Add new model to the collection * @param {Model} model * @private * */ addTo(model: any): void; itemViewNotFound(type: string): void; /** * Render new model inside the view * @param {Model} model * @param {Object} fragment Fragment collection * @private * */ add(model: any, fragment?: DocumentFragment): void; render(): this; onRender(): void; onRemoveBefore(items?: any, opts?: any): void; onRemove(items?: any, opts?: any): void; remove(opts?: {}): this; clearItems(): void; } export interface TraitsViewProps { el?: HTMLElement; collection: any[]; editor: EditorModel; config: TraitManagerConfigModule; } declare class TraitsView extends DomainViews { reuseView: boolean; em: EditorModel; pfx: string; ppfx: string; renderedCategories: Map; config: TraitManagerConfigModule; traitContClass: string; catsClass: string; classNoCat: string; catsEl?: HTMLElement; traitsEl?: HTMLElement; rendered?: boolean; itemsView: TraitManager["types"]; collection: Traits; constructor(props: TraitsViewProps, itemsView: TraitManager["types"]); /** * Update view collection * @private */ updatedCollection(): void; /** * Render new model inside the view * @param {Model} model * @param {Object} fragment Fragment collection * @private * */ add(model: Trait, fragment?: DocumentFragment): void; getCategoriesEl(): HTMLElement; getTraitsEl(): HTMLElement; append(el: HTMLElement | DocumentFragment): void; render(): this; } declare class TraitManager extends Module { __ctn?: HTMLElement; view?: TraitsView; TraitsView: typeof TraitsView; events: typeof TraitsEvents; state: Model; types: TraitViewTypes; /** * Get configuration object * @name getConfig * @function * @returns {Object} */ /** * Initialize module * @private */ constructor(em: EditorModel); /** * Select traits from a component. * @param {[Component]} component * @example * tm.select(someComponent); */ select(component?: Component): void; /** * Get trait categories from the currently selected component. * @returns {Array} * @example * const traitCategories: Category[] = tm.getCategories(); * */ getCategories(): Category[]; /** * Get traits from the currently selected component. * @returns {Array<[Trait]>} * @example * const currentTraits: Trait[] = tm.getTraits(); */ getTraits(): Trait[]; /** * Get traits by category from the currently selected component. * @example * tm.getTraitsByCategory(); * // Returns an array of items of this type * // > { category?: Category; items: Trait[] } * * // NOTE: The item without category is the one containing traits without category. * * // You can also get the same output format by passing your own array of Traits * const myFilteredTraits: Trait[] = [...]; * tm.getTraitsByCategory(myFilteredTraits); */ getTraitsByCategory(traits?: Trait[]): TraitsByCategory[]; /** * Get component from the currently selected traits. * @example * tm.getComponent(); * // Component {} */ getComponent(): Component | undefined; /** * Add new trait type. * More about it here: [Define new Trait type](https://grapesjs.com/docs/modules/Traits.html#define-new-trait-type). * @param {string} name Type name. * @param {Object} methods Object representing the trait. */ addType(name: string, methods: CustomTrait): void; /** * Get trait type * @param {string} name Type name * @returns {Object} * @private * const traitView = tm.getType('text'); */ getType(name: string): new (o: any) => TraitView; /** * Get all trait types * @returns {Object} * @private */ getTypes(): TraitViewTypes; /** * * Get Traits viewer * @private */ getTraitsViewer(): TraitsView | undefined; getCurrent(): Trait[]; render(): HTMLElement; postRender(): void; __onSelect(): void; __trgCustom(opts?: TraitCustomData): void; __customData(): TraitCustomData; __upSel(): void; __onUp(): void; } declare class TraitFactory { config: Partial; constructor(config?: Partial); /** * Build props object by their name */ build(prop: string | TraitProperties, em: EditorModel): Trait; private buildFromString; } export declare class Traits extends CollectionWithCategories { em: EditorModel; target: Component; tf: TraitFactory; categories: Categories; constructor(coll: TraitProperties[], options: { em: EditorModel; }); get module(): TraitManager; getCategories(): Categories; handleReset(coll: TraitProperties[], { previousModels }?: { previousModels?: Trait[]; }): void; handleAdd(model: Trait): void; setTarget(target: Component): void; add(model: string | TraitProperties | Trait, options?: AddOptions): Trait; add(models: Array, options?: AddOptions): Trait[]; } /** * @property {String} id Trait id, eg. `my-trait-id`. * @property {String} type Trait type, defines how the trait should be rendered. Possible values: `text` (default), `number`, `select`, `checkbox`, `color`, `button` * @property {String} label The trait label to show for the rendered trait. * @property {String} name The name of the trait used as a key for the attribute/property. By default, the name is used as attribute name or property in case `changeProp` in enabled. * @property {String} default Default value to use in case the value is not defined on the component. * @property {String} placeholder Placeholder to show inside the default input (if the UI type allows it). * @property {String} [category=''] Trait category. * @property {Boolean} changeProp If `true`, the trait value is applied on the component property, otherwise, on component attributes. * * @module docsjs.Trait * */ export declare class Trait extends Model { target: Component; em: EditorModel; view?: TraitView; el?: HTMLElement; defaults(): { type: string; label: string; name: string; unit: string; step: number; value: string; default: string; placeholder: string; category: string; changeProp: boolean; options: never[]; }; constructor(prop: TraitProperties, em: EditorModel); get parent(): Traits; get category(): Category | undefined; get component(): Component; get changeProp(): boolean; setTarget(component: Component): void; /** * Get the trait id. * @returns {String} */ getId(): string | number; /** * Get the trait type. * @returns {String} */ getType(): string; /** * Get the trait name. * @returns {String} */ getName(): string; /** * Get the trait label. * @param {Object} [opts={}] Options. * @param {Boolean} [opts.locale=true] Use the locale string from i18n module. * @returns {String} */ getLabel(opts?: { locale?: boolean; }): any; /** * Get the trait value. * The value is taken from component attributes by default or from properties if the trait has the `changeProp` enabled. * @param {Object} [opts={}] Options. * @param {Boolean} [opts.useType=false] Get the value based on type (eg. the checkbox will always return a boolean). * @returns {any} */ getValue(opts?: TraitGetValueOptions): any; /** * Update the trait value. * The value is applied on component attributes by default or on properties if the trait has the `changeProp` enabled. * @param {any} value Value of the trait. * @param {Object} [opts={}] Options. * @param {Boolean} [opts.partial] If `true` the update won't be considered complete (not stored in UndoManager). */ setValue(value: any, opts?: TraitSetValueOptions): void; /** * Get default value. */ getDefault(): any; /** * Get trait options. */ getOptions(): TraitOption[]; /** * Get current selected option or by id. * @param {String} [id] Option id. * @returns {Object | null} */ getOption(id?: string): TraitOption | undefined; /** * Get the option id from the option object. * @param {Object} option Option object * @returns {String} Option id */ getOptionId(option: TraitOption): string; /** * Get option label. * @param {String|Object} id Option id or the option object * @param {Object} [opts={}] Options * @param {Boolean} [opts.locale=true] Use the locale string from i18n module * @returns {String} Option label */ getOptionLabel(id: string | TraitOption, opts?: LocaleOptions): string; /** * Get category label. * @param {Object} [opts={}] Options. * @param {Boolean} [opts.locale=true] Use the locale string from i18n module. * @returns {String} */ getCategoryLabel(opts?: LocaleOptions): string; /** * Run the trait command (used on the button trait type). */ runCommand(): any; props(): Partial; targetUpdated(): void; getTargetValue(opts?: TraitGetValueOptions): any; setTargetValue(value: any, opts?: SetOptions): void; setValueFromInput(value: any, final?: boolean, opts?: SetOptions): void; getInitValue(): any; } export interface TraitViewTypes { [id: string]: { new (o: any): TraitView; }; } export interface ITraitView { noLabel?: TraitView["noLabel"]; eventCapture?: TraitView["eventCapture"]; templateInput?: TraitView["templateInput"]; onEvent?: TraitView["onEvent"]; onUpdate?: TraitView["onUpdate"]; createInput?: TraitView["createInput"]; createLabel?: TraitView["createLabel"]; } export type CustomTrait = ITraitView & T & ThisType; export interface TraitModuleStateProps { component?: Component; traits: Trait[]; } export interface TraitsByCategory extends ItemsByCategory { } export interface TraitManagerConfigModule extends TraitManagerConfig { pStylePrefix?: string; em: EditorModel; } export interface TraitCustomData { container?: HTMLElement; } export interface TraitProperties { /** * Trait type, defines how the trait should be rendered. * Possible values: `text` (default), `number`, `select`, `checkbox`, `color`, `button` */ type?: string; /** * The name of the trait used as a key for the attribute/property. * By default, the name is used as attribute name or property in case `changeProp` in enabled. */ name?: string; /** * Trait id, eg. `my-trait-id`. * If not specified, the `name` will be used as id. */ id?: string | number; /** * Trait category. * @default '' */ category?: string | CategoryProperties; /** * The trait label to show for the rendered trait. */ label?: string | false; /** * If `true`, the trait value is applied on the component property, otherwise, on component attributes. * @default false */ changeProp?: boolean; /** * Instead of relying on component props/attributes, define your own * logic on how to get the trait value. */ getValue?: (props: { editor: Editor; trait: Trait; component: Component; }) => any; /** * In conjunction with the `getValue`, define your own logic for updating the trait value. */ setValue?: (props: { value: any; editor: Editor; trait: Trait; component: Component; partial: boolean; options: TraitSetValueOptions; emitUpdate: () => void; }) => void; /** * Custom true value for checkbox type. * @default 'true' */ valueTrue?: string; /** * Custom false value for checkbox type. * * @default 'false' */ valueFalse?: string; /** * Minimum number value for number type. */ min?: number; /** * Maximum number value for number type. */ max?: number; unit?: string; /** * Number of steps for number type. */ step?: number; value?: any; target?: Component; default?: any; /** * Placeholder to show inside the default input (if the UI type allows it). */ placeholder?: string; /** * Array of options for the select type. */ options?: TraitOption[]; /** * Label text to use for the button type. */ text?: string; labelButton?: string; /** * Command to use for the button type. */ command?: string | ((editor: Editor, trait: Trait) => any); full?: boolean; attributes?: Record; } export interface TraitSetValueOptions { partial?: boolean; [key: string]: unknown; } export interface TraitGetValueOptions { /** * Get the value based on type. * With this option enabled, the returned value is normalized based on the * trait type (eg. the checkbox will always return a boolean). * @default false */ useType?: boolean; } export interface TraitOption { id: string; label?: string; [key: string]: unknown; } declare enum TraitsEvents { /** * @event `trait:select` New traits selected (eg. by changing a component). * @example * editor.on('trait:select', ({ traits, component }) => { ... }); */ select = "trait:select", /** * @event `trait:value` Trait value updated. * @example * editor.on('trait:value', ({ trait, component, value }) => { ... }); */ value = "trait:value", /** * @event `trait:category:update` Trait category updated. * @example * editor.on('trait:category:update', ({ category, changes }) => { ... }); */ categoryUpdate = "trait:category:update", /** * @event `trait:custom` Event to use in case of [custom Trait Manager UI](https://grapesjs.com/docs/modules/Traits.html#custom-trait-manager). * @example * editor.on('trait:custom', ({ container }) => { ... }); */ custom = "trait:custom", /** * @event `trait` Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback. * @example * editor.on('trait', ({ event, model, ... }) => { ... }); */ all = "trait" } export type RectDim = { t: number; l: number; w: number; h: number; }; export type BoundingRect = { left: number; top: number; width: number; height: number; }; export type CallbackOptions = { docs: any; config: any; el: HTMLElement; resizer: Resizer; }; export interface ResizerUpdateTargetOptions { store: boolean; selectedHandler?: string; resizer: Resizer; config: ResizerOptions; } export interface ResizerOnUpdateContainerOptions { el: HTMLElement; resizer: Resizer; opts: ResizerOptions; } export interface ResizerOptions { /** * Function which returns custom X and Y coordinates of the mouse. */ mousePosFetcher?: (ev: Event) => Position; /** * Indicates custom target updating strategy. */ updateTarget?: (el: HTMLElement, rect: RectDim, opts: ResizerUpdateTargetOptions) => void; /** * Function which gets HTMLElement as an arg and returns it relative position */ posFetcher?: (el: HTMLElement, opts: ElementPosOpts) => BoundingRect; /** * Indicate if the resizer should keep the default ratio. * @default false */ ratioDefault?: boolean; /** * On resize start callback. */ onStart?: (ev: Event, opts: CallbackOptions) => void; /** * On resize move callback. */ onMove?: (ev: Event) => void; /** * On resize end callback. */ onEnd?: (ev: Event, opts: CallbackOptions) => void; /** * On container update callback. */ onUpdateContainer?: (opts: ResizerOnUpdateContainerOptions) => void; /** * Resize unit step. * @default 1 */ step?: number; /** * Minimum dimension. * @default 10 */ minDim?: number; /** * Maximum dimension. * @default Infinity */ maxDim?: number; /** * Unit used for height resizing. * @default 'px' */ unitHeight?: string; /** * Unit used for width resizing. * @default 'px' */ unitWidth?: string; /** * The key used for height resizing. * @default 'height' */ keyHeight?: string; /** * The key used for width resizing. * @default 'width' */ keyWidth?: string; /** * If true, will override unitHeight and unitWidth, on start, with units * from the current focused element (currently used only in SelectComponent). * @default true */ currentUnit?: boolean; /** * With this option enabled the mousemove event won't be altered when the pointer comes over iframes. * @default false */ silentFrames?: boolean; /** * If true the container of handlers won't be updated. * @default false */ avoidContainerUpdate?: boolean; /** * If height is 'auto', this setting will preserve it and only update the width. * @default false */ keepAutoHeight?: boolean; /** * If width is 'auto', this setting will preserve it and only update the height. * @default false */ keepAutoWidth?: boolean; /** * When keepAutoHeight is true and the height has the value 'auto', this is set to true and height isn't updated. * @default false */ autoHeight?: boolean; /** * When keepAutoWidth is true and the width has the value 'auto', this is set to true and width isn't updated. * @default false */ autoWidth?: boolean; /** * Enable top left handler. * @default true */ tl?: boolean; /** * Enable top center handler. * @default true */ tc?: boolean; /** * Enable top right handler. * @default true */ tr?: boolean; /** * Enable center left handler. * @default true */ cl?: boolean; /** * Enable center right handler. * @default true */ cr?: boolean; /** * Enable bottom left handler. * @default true */ bl?: boolean; /** * Enable bottom center handler. * @default true */ bc?: boolean; /** * Enable bottom right handler. * @default true */ br?: boolean; /** * Class prefix. */ prefix?: string; /** * Where to append resize container (default body element). */ appendTo?: HTMLElement; /** * Drag mode */ dragMode?: "absolute" | "relative"; } export type Handlers = Record; declare class Resizer { defOpts: ResizerOptions; opts: ResizerOptions; container?: HTMLElement; handlers?: Handlers; el?: HTMLElement; clickedHandler?: HTMLElement; selectedHandler?: HTMLElement; handlerAttr?: string; startDim?: RectDim; rectDim?: RectDim; parentDim?: RectDim; startPos?: Position; delta?: Position; currentPos?: Position; docs?: Document[]; keys?: { shift: boolean; ctrl: boolean; alt: boolean; }; mousePosFetcher?: ResizerOptions["mousePosFetcher"]; updateTarget?: ResizerOptions["updateTarget"]; posFetcher?: ResizerOptions["posFetcher"]; onStart?: ResizerOptions["onStart"]; onMove?: ResizerOptions["onMove"]; onEnd?: ResizerOptions["onEnd"]; onUpdateContainer?: ResizerOptions["onUpdateContainer"]; /** * Init the Resizer with options * @param {Object} options */ constructor(opts?: ResizerOptions); /** * Get current connfiguration options * @return {Object} */ getConfig(): ResizerOptions; /** * Setup options * @param {Object} options */ setOptions(options?: Partial, reset?: boolean): void; /** * Setup resizer */ setup(): void; /** * Toggle iframes pointer event * @param {Boolean} silent If true, iframes will be silented */ toggleFrames(silent?: boolean): void; /** * Detects if the passed element is a resize handler * @param {HTMLElement} el * @return {Boolean} */ isHandler(el: HTMLElement): boolean; /** * Returns the focused element * @return {HTMLElement} */ getFocusedEl(): HTMLElement | undefined; /** * Returns the parent of the focused element * @return {HTMLElement} */ getParentEl(): HTMLElement | null | undefined; /** * Returns documents */ getDocumentEl(): Document[]; /** * Return element position * @param {HTMLElement} el * @param {Object} opts Custom options * @return {Object} */ getElementPos(el: HTMLElement, opts?: ElementPosOpts): BoundingRect; /** * Focus resizer on the element, attaches handlers to it * @param {HTMLElement} el */ focus(el: HTMLElement): void; /** * Blur from element */ blur(): void; /** * Start resizing * @param {Event} e */ start(ev: Event): void; /** * While resizing * @param {Event} e */ move(ev: PointerEvent | Event): void; /** * Stop resizing * @param {Event} e */ stop(e: Event): void; /** * Update rect */ updateRect(store: boolean): void; updateContainer(opt?: { forceShow?: boolean; }): void; /** * Get selected handler name * @return {string} */ getSelectedHandler(): string | undefined; /** * Handle ESC key * @param {Event} e */ handleKeyDown(e: Event): void; /** * Handle mousedown to check if it's possible to start resizing * @param {Event} e */ handleMouseDown(e: Event): void; /** * All positioning logic * @return {Object} */ calc(data: Resizer): RectDim | undefined; getParentRect(): BoundingRect; } export interface ICommand { run?: CommandAbstract["run"]; stop?: CommandAbstract["stop"]; id?: string; [key: string]: unknown; } export type CommandFunction = CommandAbstract["run"]; export type Command = CommandObject | CommandFunction; export type CommandOptions = Record; export type CommandObject = ICommand & T & ThisType>; declare class CommandAbstract extends Model { config: any; em: EditorModel; pfx: string; ppfx: string; hoverClass: string; badgeClass: string; plhClass: string; freezClass: string; canvas: CanvasModule; noStop?: boolean; constructor(o: any); /** * On frame scroll callback * @param {[type]} e [description] * @return {[type]} [description] */ onFrameScroll(e: any): void; /** * Returns canval element * @return {HTMLElement} */ getCanvas(): HTMLElement; /** * Get canvas body element * @return {HTMLElement} */ getCanvasBody(): HTMLBodyElement; /** * Get canvas wrapper element * @return {HTMLElement} */ getCanvasTools(): any; /** * Get the offset of the element * @param {HTMLElement} el * @return {Object} */ offset(el: HTMLElement): { top: number; left: number; }; /** * Callback triggered after initialize * @param {Object} o Options * @private * */ init(o: any): void; /** * Method that run command * @param {Object} editor Editor instance * @param {Object} [options={}] Options * @private * */ callRun(editor: Editor, options?: any): void; /** * Method that run command * @param {Object} editor Editor instance * @param {Object} [options={}] Options * @private * */ callStop(editor: Editor, options?: any): void; /** * Stop current command */ stopCommand(opts?: any): void; /** * Method that run command * @param {Object} em Editor model * @param {Object} sender Button sender * @private * */ run(em: Editor, sender: any, options: O): void; /** * Method that stop command * @param {Object} em Editor model * @param {Object} sender Button sender * @private * */ stop(em: Editor, sender: any, options: O): void; } export interface ToolbarButtonProps { /** * Command name. */ command: CommandFunction | string; /** * Button label. */ label?: string; id?: string; attributes?: ObjectAny; events?: ObjectAny; } export type DragMode = "translate" | "absolute" | ""; export type DraggableDroppableFn = (source: Component, target: Component, index?: number) => boolean | void; export interface AddComponentsOption extends AddOptions, OptionAsDocument { } export interface ResetComponentsOptions extends AddComponentsOption { previousModels?: Component[]; keepIds?: string[]; skipDomReset?: boolean; } export interface ComponentWithCheck { new (props: any, opt: ComponentOptions): C; isComponent(node: HTMLElement, opts?: ParseNodeOptions): ComponentDefinitionDefined | undefined | boolean; } export interface ComponentStackItem = ComponentView> { id: string; model: ComponentWithCheck; view: new (opt: any) => CV; } /** * Delegate commands to other components. */ export interface ComponentDelegateProps { /** * Delegate remove command to another component. * @example * delegate: { * remove: (cmp) => cmp.closestType('other-type'), * } */ remove?: (cmp: Component) => Component | Nullable; /** * Delegate move command to another component. * @example * delegate: { * move: (cmp) => cmp.closestType('other-type'), * } */ move?: (cmp: Component) => Component | Nullable; /** * Delegate copy command to another component. * @example * delegate: { * copy: (cmp) => cmp.closestType('other-type'), * } */ copy?: (cmp: Component) => Component | Nullable; /** * Delegate select command to another component. * @example * delegate: { * select: (cmp) => cmp.findType('other-type')[0], * } */ select?: (cmp: Component) => Component | Nullable; /** * Delegate another component as a layer in the LayerManager. * @example * delegate: { * layer: (cmp) => cmp.findType('other-type')[0], * } */ layer?: (cmp: Component) => Component | Nullable; } export interface ComponentProperties { /** * Component type, eg. `text`, `image`, `video`, etc. * @default '' */ type?: string; /** * HTML tag of the component, eg. `span`. Default: `div` * @default 'div' */ tagName?: string; /** * Key-value object of the component's attributes, eg. `{ title: 'Hello' }` Default: `{}` * @default {} */ attributes?: Record; /** * Name of the component. Will be used, for example, in Layers and badges * @default '' */ name?: string; /** * When `true` the component is removable from the canvas, default: `true` * @default true */ removable?: boolean; /** * Indicates if it's possible to drag the component inside others. You can also specify a query string to indentify elements, eg. `'.some-class[title=Hello], [data-gjs-type=column]'` means you can drag the component only inside elements containing `some-class` class and `Hello` title, and `column` components. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drag is possible. Default: `true` * @default true */ draggable?: boolean | string | DraggableDroppableFn; /** * Indicates if it's possible to drop other components inside. You can use a query string as with `draggable`. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drop is possible. Default: `true` * @default true */ droppable?: boolean | string | DraggableDroppableFn; /** * Set to false if you don't want to see the badge (with the name) over the component. Default: `true` * @default true */ badgable?: boolean; /** * True if it's possible to style the component. You can also indicate an array of CSS properties which is possible to style, eg. `['color', 'width']`, all other properties will be hidden from the style manager. Default: `true` * @default true */ stylable?: boolean | String[]; /** * Indicate an array of style properties which should be hidden from the style manager. Default: `[]` * @default [] */ unstylable?: String[]; /** * It can be highlighted with 'dotted' borders if true. Default: `true` * @default true */ highlightable?: boolean; /** * True if it's possible to clone the component. Default: `true` * @default true */ copyable?: boolean; /** * Indicates if it's possible to resize the component. It's also possible to pass an object as [options for the Resizer](https://github.com/GrapesJS/grapesjs/blob/master/src/utils/Resizer.ts). Default: `false` */ resizable?: boolean | ResizerOptions; /** * Allow to edit the content of the component (used on Text components). Default: `false` */ editable?: boolean; /** * Set to `false` if you need to hide the component inside Layers. Default: `true` * @default true */ layerable?: boolean; /** * Allow component to be selected when clicked. Default: `true` * @default true */ selectable?: boolean; /** * Shows a highlight outline when hovering on the element if `true`. Default: `true` * @default true */ hoverable?: boolean; /** * Disable the selection of the component and its children in the canvas. * @default false */ locked?: boolean; /** * This property is used by the HTML exporter as void elements don't have closing tags, eg. `
`, `
`, etc. Default: `false` */ void?: boolean; /** * Component default style, eg. `{ width: '100px', height: '100px', 'background-color': 'red' }` * @default {} */ style?: string | Record; /** * Component related styles, eg. `.my-component-class { color: red }` * @default '' */ styles?: string; /** * Content of the component (not escaped) which will be appended before children rendering. Default: `''` * @default '' */ content?: string; /** * Component's icon, this string will be inserted before the name (in Layers and badge), eg. it can be an HTML string ''. Default: `''` * @default '' */ icon?: string; /** * Component's javascript. More about it [here](/modules/Components-js.html). Default: `''` * @default '' */ script?: string | ((...params: any[]) => any); /** * Component's traits. More about it [here](/modules/Traits.html). Default: `['id', 'title']` * @default '' */ traits?: Traits; /** * Indicates an array of properties which will be inhereted by all NEW appended children. For example if you create a component likes this: `{ removable: false, draggable: false, propagate: ['removable', 'draggable'] }` and append some new component inside, the new added component will get the exact same properties indicated in the `propagate` array (and the `propagate` property itself). Default: `[]` * @default [] */ propagate?: (keyof ComponentProperties)[]; /** * Set an array of items to show up inside the toolbar when the component is selected (move, clone, delete). * Eg. `toolbar: [ { attributes: {class: 'fa fa-arrows'}, command: 'tlb-move' }, ... ]`. * By default, when `toolbar` property is falsy the editor will add automatically commands `core:component-exit` (select parent component, added if there is one), `tlb-move` (added if `draggable`) , `tlb-clone` (added if `copyable`), `tlb-delete` (added if `removable`). */ toolbar?: ToolbarButtonProps[]; /** * Delegate commands to other components. */ delegate?: ComponentDelegateProps; components?: Components; classes?: Selectors; dmode?: DragMode; "script-props"?: string[]; [key: string]: any; } export interface SymbolToUpOptions extends DynamicWatchersOptions { changed?: string; fromInstance?: boolean; noPropagate?: boolean; fromUndo?: boolean; } export interface ComponentDefinition extends Omit { /** * Children components. */ components?: string | ComponentDefinition | (string | ComponentDefinition)[]; traits?: (Partial | string)[]; attributes?: Record; [key: string]: unknown; } export interface ComponentDefinitionDefined extends Omit { /** * Children components. */ components?: ComponentDefinitionDefined[] | ComponentDefinitionDefined; traits?: (Partial | string)[]; [key: string]: any; } export type ComponentAddType = Component | ComponentDefinition | ComponentDefinitionDefined | string; export type ComponentAdd = ComponentAddType | ComponentAddType[]; export interface ToHTMLOptions extends OptionAsDocument { /** * Custom tagName. */ tag?: string; /** * Include component properties as `data-gjs-*` attributes. This allows you to have re-importable HTML. */ withProps?: boolean; /** * In case the attribute value contains a `"` char, instead of escaping it (`attr="value ""`), the attribute will be quoted using single quotes (`attr='value "'`). */ altQuoteAttr?: boolean; /** * Keep inline style set intentionally by users with `setStyle({}, { inline: true })` */ keepInlineStyle?: boolean; /** * You can pass an object of custom attributes to replace with the current ones * or you can even pass a function to generate attributes dynamically. */ attributes?: Record | ((component: Component, attr: Record) => Record); } export interface ComponentOptions { em: EditorModel; config: DomComponentsConfig; frame?: Frame; temporary?: boolean; avoidChildren?: boolean; forCloning?: boolean; } declare class ComponentHead extends Component { get defaults(): { type: string; tagName: string; draggable: boolean; highlightable: boolean; droppable: DraggableDroppableFn; components?: ComponentDefinitionDefined[] | ComponentDefinitionDefined; traits?: (Partial | string)[]; }; static isComponent(el: HTMLElement): boolean; } declare class ComponentWrapper extends Component { get defaults(): { tagName: string; removable: boolean; copyable: boolean; draggable: boolean; components: never[]; traits: never[]; doctype: string; head: null; docEl: null; stylable: string[]; }; preInit(): void; get head(): ComponentHead; get docEl(): Component; get doctype(): string; clone(opt?: { symbol?: boolean | undefined; symbolInv?: boolean | undefined; }): this; toHTML(opts?: ToHTMLOptions): string; __postAdd(): void; __postRemove(): void; static isComponent(): boolean; } declare class ComponentWrapperView extends ComponentView { tagName(): string; } export interface SymbolInfo { isSymbol: boolean; isMain: boolean; isInstance: boolean; isRoot: boolean; main?: Component; instances: Component[]; relatives: Component[]; } export interface ParseStringOptions extends AddOptions, OptionAsDocument, WithHTMLParserOptions { keepIds?: string[]; } declare enum ComponentsEvents { /** * @event `component:add` New component added. * @example * editor.on('component:add', (component) => { ... }); */ add = "component:add", /** * @event `component:remove` Component removed. * @example * editor.on('component:remove', (component) => { ... }); */ remove = "component:remove", removeBefore = "component:remove:before", removed = "component:removed", /** * @event `component:create` Component created. * @example * editor.on('component:create', (component) => { ... }); */ create = "component:create", /** * @event `component:update` Component is updated, the component is passed as an argument to the callback. * @example * editor.on('component:update', (component) => { ... }); */ update = "component:update", updateInside = "component:update-inside", /** * @event `component:select` Component selected. * @example * editor.on('component:select', (component) => { ... }); */ select = "component:select", selectBefore = "component:select:before", /** * @event `component:script:mount` Component with script is mounted. * @example * editor.on('component:script:mount', ({ component, view, el }) => { ... }); */ scriptMount = "component:script:mount", scriptMountBefore = "component:script:mount:before", /** * @event `component:script:unmount` Component with script is unmounted. This is triggered when the component is removed or the script execution has to be refreshed. This event might be useful to clean up resources. * @example * editor.on('component:script:unmount', ({ component, view, el }) => { ... }); */ scriptUnmount = "component:script:unmount", /** * @event `component:render` Component rendered in the canvas. This event could be triggered multiple times for the same component (eg. undo/redo, explicit rerender). * @example * editor.on('component:render', ({ component, view, el }) => { ... }); */ render = "component:render", /** * @event `symbol:main:add` Added new main symbol. * @example * editor.on('symbol:main:add', ({ component }) => { ... }); */ symbolMainAdd = "symbol:main:add", /** * @event `symbol:main:update` Main symbol updated. * @example * editor.on('symbol:main:update', ({ component }) => { ... }); */ symbolMainUpdate = "symbol:main:update", symbolMainUpdateDeep = "symbol:main:update-deep", /** * @event `symbol:main:remove` Main symbol removed. * @example * editor.on('symbol:main:remove', ({ component }) => { ... }); */ symbolMainRemove = "symbol:main:remove", /** * @event `symbol:main` Catch-all event related to main symbol updates. * @example * editor.on('symbol:main', ({ event, component }) => { ... }); */ symbolMain = "symbol:main", /** * @event `symbol:instance:add` Added new root instance symbol. * @example * editor.on('symbol:instance:add', ({ component }) => { ... }); */ symbolInstanceAdd = "symbol:instance:add", /** * @event `symbol:instance:remove` Root instance symbol removed. * @example * editor.on('symbol:instance:remove', ({ component }) => { ... }); */ symbolInstanceRemove = "symbol:instance:remove", /** * @event `symbol:instance` Catch-all event related to instance symbol updates. * @example * editor.on('symbol:instance', ({ event, component }) => { ... }); */ symbolInstance = "symbol:instance", /** * @event `symbol` Catch-all event for any symbol update (main or instance). * @example * editor.on('symbol', () => { ... }); */ symbol = "symbol" } export interface PropsComponentUpdate { component: Component; changed: ObjectAny; options: ObjectAny; } declare class Symbols extends Components { refreshDbn: Debounced; constructor(...args: ConstructorParameters); removeChildren(component: Component, coll?: Components, opts?: any): void; onAdd(...args: Parameters): void; onUpdate(props: PropsComponentUpdate): void; onUpdateDeep(props: PropsComponentUpdate): void; refresh(): void; __trgEvent(event: string, props: ObjectAny, isInstance?: boolean): void; } export type ComponentEvent = "component:create" | "component:mount" | "component:add" | "component:remove" | "component:remove:before" | "component:clone" | "component:update" | "component:styleUpdate" | "component:selected" | "component:deselected" | "component:toggled" | "component:type:add" | "component:type:update" | "component:drag:start" | "component:drag" | "component:drag:end" | "component:resize"; export interface ComponentModelDefinition extends IComponent { defaults?: ComponentDefinition | (() => ComponentDefinition); [key: string]: any; } export interface ComponentViewDefinition extends IComponentView { [key: string]: any; } export interface AddComponentTypeOptions { isComponent?: (el: HTMLElement) => boolean | ComponentDefinitionDefined | undefined; model?: Partial & ThisType; view?: Partial & ThisType; block?: boolean | Partial; extend?: string; extendView?: string; extendFn?: string[]; extendFnView?: string[]; } declare enum CanMoveReason { /** * Invalid source. This is a default value and should be ignored in case the `result` is true */ InvalidSource = 0, /** * Source doesn't accept target as destination. */ SourceReject = 1, /** * Target doesn't accept source. */ TargetReject = 2 } export interface CanMoveResult { result: boolean; reason: CanMoveReason; target: Component; source?: Component | null; } export declare class ComponentManager extends ItemManagerModule { componentTypes: ComponentStackItem[]; componentsById: { [id: string]: Component; }; componentView?: ComponentWrapperView; Component: typeof Component; Components: typeof Components; ComponentView: typeof ComponentView; ComponentsView: typeof ComponentsView; /** * Name of the module * @type {String} * @private */ storageKey: string; keySymbols: string; shallow?: Component; symbols: Symbols; events: typeof ComponentsEvents; /** * Initialize module. Called on a new instance of the editor with configurations passed * inside 'domComponents' field * @param {Object} config Configurations * @private */ constructor(em: EditorModel); postLoad(): void; load(data: any): any; store(): { [x: string]: Symbols; }; /** * Returns the main wrapper. * @return {Object} * @private */ getComponent(): ComponentWrapper | undefined; /** * Returns root component inside the canvas. Something like `` inside HTML page * The wrapper doesn't differ from the original Component Model * @return {[Component]} Root Component * @example * // Change background of the wrapper and set some attribute * var wrapper = cmp.getWrapper(); * wrapper.set('style', {'background-color': 'red'}); * wrapper.set('attributes', {'title': 'Hello!'}); */ getWrapper(): ComponentWrapper | undefined; /** * Returns wrapper's children collection. Once you have the collection you can * add other Components(Models) inside. Each component can have several nested * components inside and you can nest them as more as you wish. * @return {Components} Collection of components * @example * // Let's add some component * var wrapperChildren = cmp.getComponents(); * var comp1 = wrapperChildren.add({ * style: { 'background-color': 'red'} * }); * var comp2 = wrapperChildren.add({ * tagName: 'span', * attributes: { title: 'Hello!'} * }); * // Now let's add an other one inside first component * // First we have to get the collection inside. Each * // component has 'components' property * var comp1Children = comp1.get('components'); * // Procede as before. You could also add multiple objects * comp1Children.add([ * { style: { 'background-color': 'blue'}}, * { style: { height: '100px', width: '100px'}} * ]); * // Remove comp2 * wrapperChildren.remove(comp2); */ getComponents(): Components; /** * Add new components to the wrapper's children. It's the same * as 'cmp.getComponents().add(...)' * @param {Object|[Component]|Array} component Component/s to add * @param {string} [component.tagName='div'] Tag name * @param {string} [component.type=''] Type of the component. Available: ''(default), 'text', 'image' * @param {boolean} [component.removable=true] If component is removable * @param {boolean} [component.draggable=true] If is possible to move the component around the structure * @param {boolean} [component.droppable=true] If is possible to drop inside other components * @param {boolean} [component.badgable=true] If the badge is visible when the component is selected * @param {boolean} [component.stylable=true] If is possible to style component * @param {boolean} [component.copyable=true] If is possible to copy&paste the component * @param {string} [component.content=''] String inside component * @param {Object} [component.style={}] Style object * @param {Object} [component.attributes={}] Attribute object * @param {Object} opt the options object to be used by the [Components.add]{@link getComponents} method * @return {[Component]|Array<[Component]>} Component/s added * @example * // Example of a new component with some extra property * var comp1 = cmp.addComponent({ * tagName: 'div', * removable: true, // Can't remove it * draggable: true, // Can't move it * copyable: true, // Disable copy/past * content: 'Content text', // Text inside component * style: { color: 'red'}, * attributes: { title: 'here' } * }); */ addComponent(component: ComponentAdd, opt?: AddComponentsOption): Component | Component[]; /** * Render and returns wrapper element with all components inside. * Once the wrapper is rendered, and it's what happens when you init the editor, * the all new components will be added automatically and property changes are all * updated immediately * @return {HTMLElement} * @private */ render(): HTMLElement | undefined; /** * Remove all components * @return {this} */ clear(opts?: {}): this; /** * Set components * @param {Object|string} components HTML string or components model * @param {Object} opt the options object to be used by the {@link addComponent} method * @return {this} * @private */ setComponents(components: ComponentAdd, opt?: AddComponentsOption): void; /** * Add new component type. * Read more about this in [Define New Component](https://grapesjs.com/docs/modules/Components.html#define-new-component) * @param {string} type Component ID * @param {Object} methods Component methods * @return {this} */ addType(type: string, methods: AddComponentTypeOptions): this; /** * Get component type. * Read more about this in [Define New Component](https://grapesjs.com/docs/modules/Components.html#define-new-component) * @param {string} type Component ID * @return {Object} Component type definition, eg. `{ model: ..., view: ... }` */ getType(type: "default"): { id: string; model: any; view: any; }; getType(type: string): { id: string; model: any; view: any; } | undefined; /** * Remove component type * @param {string} type Component ID * @returns {Object|undefined} Removed component type, undefined otherwise */ removeType(id: string): { id: string; model: any; view: any; } | undefined; /** * Return the array of all types * @return {Array} */ getTypes(): ComponentStackItem>[]; selectAdd(component: Component, opts?: {}): void; selectRemove(component: Component, opts?: {}): void; /** * Triggered when the component is hovered * @private */ componentHovered(): void; getShallowWrapper(): Component | undefined; /** * Check if the object is a [Component]. * @param {Object} obj * @returns {Boolean} * @example * cmp.isComponent(editor.getSelected()); // true * cmp.isComponent({}); // false */ isComponent(obj?: ObjectAny): obj is Component; /** * Add a new symbol from a component. * If the passed component is not a symbol, it will be converted to an instance and will return the main symbol. * If the passed component is already an instance, a new instance will be created and returned. * If the passed component is the main symbol, a new instance will be created and returned. * @param {[Component]} component Component from which create a symbol. * @returns {[Component]} * @example * const symbol = cmp.addSymbol(editor.getSelected()); * // cmp.getSymbolInfo(symbol).isSymbol === true; */ addSymbol(component: Component): Component | undefined; /** * Get the array of main symbols. * @returns {Array<[Component]>} * @example * const symbols = cmp.getSymbols(); * // [Component, Component, ...] * // Removing the main symbol will detach all the relative instances. * symbols[0].remove(); */ getSymbols(): Component[]; /** * Detach symbol instance from the main one. * The passed symbol instance will become a regular component. * @param {[Component]} component The component symbol to detach. * @example * const cmpInstance = editor.getSelected(); * // cmp.getSymbolInfo(cmpInstance).isInstance === true; * cmp.detachSymbol(cmpInstance); * // cmp.getSymbolInfo(cmpInstance).isInstance === false; */ detachSymbol(component: Component): void; /** * Get info about the symbol. * @param {[Component]} component Component symbol from which to get the info. * @returns {Object} Object containing symbol info. * @example * cmp.getSymbolInfo(editor.getSelected()); * // > { isSymbol: true, isMain: false, isInstance: true, ... } */ getSymbolInfo(component: Component, opts?: { withChanges?: string; }): SymbolInfo; /** * Check if a component can be moved inside another one. * @param {[Component]} target The target component is the one that is supposed to receive the source one. * @param {[Component]|String} source The source can be another component, a component definition or an HTML string. * @param {Number} [index] Index position, if not specified, the check will be performed against appending the source to the target. * @returns {Object} Object containing the `result` (Boolean), `source`, `target` (as Components), and a `reason` (Number) with these meanings: * * `0` - Invalid source. This is a default value and should be ignored in case the `result` is true. * * `1` - Source doesn't accept target as destination. * * `2` - Target doesn't accept source. * @example * const rootComponent = editor.getWrapper(); * const someComponent = editor.getSelected(); * * // Check with two components * editor.Components.canMove(rootComponent, someComponent); * * // Check with component definition * editor.Components.canMove(rootComponent, { tagName: 'a', draggable: false }); * * // Check with HTML string * editor.Components.canMove(rootComponent, '
...
'); */ canMove(target: Component, source?: Component | ComponentDefinition | string, index?: number): CanMoveResult; allById(): { [id: string]: Component; }; getById(id: string): Component; destroy(): void; } export interface ComponentsOptions { em: EditorModel; config?: DomComponentsConfig; domc?: ComponentManager; } export interface AddComponentOptions extends AddOptions { previousModels?: Component[]; keepIds?: string[]; } export declare class Components extends Collection { opt: ComponentsOptions; config?: DomComponentsConfig; em: EditorModel; domc?: ComponentManager; parent?: Component; constructor(models: any, opt: ComponentsOptions); get events(): typeof ComponentsEvents; resetChildren(models: Components, opts?: { previousModels?: Component[]; keepIds?: string[]; }): void; resetFromString(input?: string, opts?: { visitedCmps?: Record; keepIds?: string[]; }): void; removeChildren(removed: Component, coll?: Components, opts?: any): void; /** @ts-ignore */ model(attrs: Partial, options: any): Component; parseString(value: string, opt?: ParseStringOptions): ComponentDefinitionDefined | ComponentDefinitionDefined[]; add(model: Exclude, opt?: AddComponentOptions): Component; add(models: ComponentAddType[], opt?: AddComponentOptions): Component[]; add(models: ComponentAdd, opt?: AddComponentOptions): Component | Component[]; /** * Process component definition. */ processDef(mdl: Component | ComponentDefinition | ComponentDefinitionDefined): Component | ComponentDefinitionDefined | ComponentDefinition; onAdd(model: Component, c?: any, opts?: { temporary?: boolean; }): void; } export interface LayerManagerConfig { stylePrefix?: string; /** * Specify the element to use as a container, string (query) or HTMLElement. * With the empty value, nothing will be rendered. * @default '' */ appendTo?: string | HTMLElement; /** * Enable/Disable globally the possibility to sort layers. * @default true */ sortable?: boolean; /** * Enable/Disable globally the possibility to hide layers. * @default true */ hidable?: boolean; /** * Hide textnodes. * @default true */ hideTextnode?: boolean; /** * Indicate a query string of the element to be selected as the root of layers. * By default the root is the wrapper. * @default '' */ root?: string; /** * Indicates if the wrapper is visible in layers. * @default true */ showWrapper?: boolean; /** * Show hovered components in canvas. * @default true */ showHover?: boolean; /** * Scroll to selected component in Canvas when it's selected in Layers. * true, false or `scrollIntoView`-like options, * `block: 'nearest'` avoids the issue of window scrolling. * @default { behavior: 'smooth', block: 'nearest' } */ scrollCanvas?: boolean | ScrollIntoViewOptions; /** * Scroll to selected component in Layers when it's selected in Canvas. * @default { behavior: 'auto', block: 'nearest' } */ scrollLayers?: boolean | ScrollIntoViewOptions; /** * Highlight when a layer component is hovered. * @default true */ highlightHover?: boolean; /** * Avoid rendering the default layer manager. * @default false */ custom?: boolean; /** * WARNING: Experimental option. * A callback triggered once the component layer is initialized. * Useful to trigger updates on some component prop change. * @example * onInit({ component, render, listenTo }) { * listenTo(component, 'change:some-prop', render); * }; */ onInit?: () => void; /** * WARNING: Experimental option. * A callback triggered once the component layer is rendered. * A callback useful to update the layer DOM on some component change * @example * onRender({ component, el }) { // el is the DOM of the layer * if (component.get('some-prop')) { * // do changes using the `el` DOM * } * } */ onRender?: () => void; /** * Extend Layer view object (view/ItemView.js) * @example * extend: { * setName(name) { * // this.model is the component of the layer * this.model.set('another-prop-for-name', name); * }, * }, */ extend?: Record; } export interface LayerData { name: string; open: boolean; selected: boolean; hovered: boolean; visible: boolean; locked: boolean; components: Component[]; } declare class LayerManager extends Module { model: ModuleModel; __ctn?: HTMLElement; view?: View; events: { all: string; root: string; component: string; custom: string; }; constructor(em: EditorModel); onLoad(): void; /** * Update the root layer with another component. * @param {[Component]|String} component Component to be set as root * @return {[Component]} * @example * const component = editor.getSelected(); * layers.setRoot(component); */ setRoot(component: Component | string): Component; /** * Get the current root layer. * @return {[Component]} * @example * const layerRoot = layers.getRoot(); */ getRoot(): Component; /** * Get valid layer child components (eg. excludes non layerable components). * @param {[Component]} component Component from which you want to get child components * @returns {Array<[Component]>} * @example * const component = editor.getSelected(); * const components = layers.getComponents(component); * console.log(components); */ getComponents(component: Component): Component[]; /** * Update the layer open state of the component. * @param {[Component]} component Component to update * @param {Boolean} value */ setOpen(component: Component, value: boolean): void; /** * Check the layer open state of the component. * @param {[Component]} component * @returns {Boolean} */ isOpen(component: Component): boolean; /** * Update the layer visibility state of the component. * @param {[Component]} component Component to update * @param {Boolean} value */ setVisible(component: Component, value: boolean): void; /** * Check the layer visibility state of the component. * @param {[Component]} component * @returns {Boolean} */ isVisible(component: Component): boolean; /** * Update the layer locked state of the component. * @param {[Component]} component Component to update * @param {Boolean} value */ setLocked(component: Component, value: boolean): void; /** * Check the layer locked state of the component. * @param {[Component]} component * @returns {Boolean} */ isLocked(component: Component): boolean; /** * Update the layer name of the component. * @param {[Component]} component Component to update * @param {String} value New name */ setName(component: Component, value: string): void; /** * Get the layer name of the component. * @param {[Component]} component * @returns {String} Component layer name */ getName(component: Component): any; /** * Get layer data from a component. * @param {[Component]} component Component from which you want to read layer data. * @returns {Object} Object containing the layer data. * @example * const component = editor.getSelected(); * const layerData = layers.getLayerData(component); * console.log(layerData); */ getLayerData(component: Component): LayerData; setLayerData(component: Component, data: Partial>, opts?: {}): void; /** * Triggered when the selected component is changed * @private */ componentChanged(sel?: Component, opts?: {}): void; getAll(): View | undefined; render(): HTMLElement; destroy(): void; __onRootChange(): void; __getLayerFromComponent(cmp: Component): Component; __onComponent(component: Component): void; __isLayerable(cmp: Component): boolean; __trgCustom(opts?: any): void; updateLayer(component: Component, opts?: any): void; } declare class LayersComponentNode extends BaseComponentNode { protected _dropAreaConfig: { ratio: number; minUndroppableDimension: number; maxUndroppableDimension: number; }; /** * Get the associated view of this component. * @returns The view associated with the component, or undefined if none. */ get view(): any; /** * Get the associated element of this component. * @returns The Element associated with the component, or undefined if none. */ get element(): HTMLElement | undefined; } declare class ItemsView extends View { items: ItemView[]; opt: { sorter: ComponentSorter; [k: string]: any; }; config: any; parentView: ItemView; module: LayerManager; /** @ts-ignore */ collection: Components; constructor(opt?: any); /** * Create placeholder * @return {HTMLElement} */ private createPlaceholder; removeChildren(removed: Component): void; /** * Add to collection * @param Object Model * * @return Object * */ addTo(model: Component): void; /** * Add new object to collection * @param Object Model * @param Object Fragment collection * @param integer Index of append * * @return Object Object created * */ addToCollection(model: Component, fragment: DocumentFragment | null, index?: number): HTMLElement; remove(...args: [ ]): this; render(): this; } export type ItemViewProps = ViewOptions & { ItemView: ItemView; level: number; config: any; opened: {}; model: Component; module: LayerManager; sorter: any; parentView: ItemView; }; declare class ItemView extends View { events(): { "mousedown [data-toggle-move]": string; "touchstart [data-toggle-move]": string; "click [data-toggle-visible]": string; "click [data-toggle-open]": string; "click [data-toggle-select]": string; "mouseover [data-toggle-select]": string; "mouseout [data-toggle-select]": string; "dblclick [data-name]": string; "keydown [data-name]": string; "focusout [data-name]": string; }; template(model: Component): string; get em(): EditorModel; get ppfx(): string; get pfx(): string; opt: ItemViewProps; module: LayerManager; config: any; sorter: Sorter; /** @ts-ignore */ model: Component; parentView: ItemView; items?: ItemsView; inputNameCls: string; clsTitleC: string; clsTitle: string; clsCaret: string; clsCount: string; clsMove: string; clsChildren: string; clsNoChild: string; clsEdit: string; clsNoEdit: string; _rendered?: boolean; caret?: JQuery; inputName?: HTMLElement; constructor(opt: ItemViewProps); initComponent(): void; updateName(): void; getVisibilityEl(): JQuery; updateVisibility(): void; updateMove(): void; /** * Toggle visibility * @param Event * * @return void * */ toggleVisibility(ev?: MouseEvent): void; /** * Handle the edit of the component name */ handleEdit(ev?: MouseEvent): void; handleEditKey(ev: KeyboardEvent): void; /** * Handle with the end of editing of the component name */ handleEditEnd(ev?: KeyboardEvent): void; /** * Get the input containing the name of the component * @return {HTMLElement} */ getInputName(): HTMLElement; /** * Update item opening * * @return void * */ updateOpening(): void; /** * Toggle item opening * @param {Object} e * * @return void * */ toggleOpening(ev?: MouseEvent): void; /** * Handle component selection */ handleSelect(event?: MouseEvent): void; /** * Handle component selection */ handleHover(ev?: MouseEvent): void; handleHoverOut(ev?: MouseEvent): void; /** * Delegate to sorter * @param Event * */ startSort(ev: MouseEvent): void; /** * Update item on status change * @param Event * */ updateStatus(): void; getItemContainer(): JQuery; /** * Update item aspect after children changes * * @return void * */ checkChildren(): void; getCaret(): JQuery; setRoot(cmp: Component | string): void; updateLayerable(): void; __clearItems(): void; remove(...args: [ ]): this; render(): this; __render(): void; } declare class ComponentDataResolverWatchers { private component; private propertyWatcher; private attributeWatcher; constructor(component: Component | undefined, options: ComponentResolverWatcherOptions); private onPropertyUpdate; private onAttributeUpdate; bindComponent(component: Component): void; updateCollectionStateMap(collectionsStateMap: DataCollectionStateMap): void; addProps(props: ObjectAny, options?: DynamicWatchersOptions): { [k: string]: any; }; removeAttributes(attributes: string[]): void; private updateSymbolOverride; getDynamicPropsDefs(): ObjectAny; getDynamicAttributesDefs(): ObjectAny; getPropsDefsOrValues(props: ObjectAny): { [x: string]: any; }; getAttributesDefsOrValues(attributes: ObjectAny): { [x: string]: any; }; destroy(): void; } export interface IComponent extends ExtractMethods { } export interface SetAttrOptions extends SetOptions, UpdateStyleOptions, DynamicWatchersOptions { } export interface ComponentSetOptions extends SetOptions, DynamicWatchersOptions { } /** * The Component object represents a single node of our template structure, so when you update its properties the changes are * immediately reflected on the canvas and in the code to export (indeed, when you ask to export the code we just go through all * the tree of nodes). * An example on how to update properties: * ```js * component.set({ * tagName: 'span', * attributes: { ... }, * removable: false, * }); * component.get('tagName'); * // -> 'span' * ``` * * [Component]: component.html * * @property {String} [type=''] Component type, eg. `text`, `image`, `video`, etc. * @property {String} [tagName='div'] HTML tag of the component, eg. `span`. Default: `div` * @property {Object} [attributes={}] Key-value object of the component's attributes, eg. `{ title: 'Hello' }` Default: `{}` * @property {String} [name=''] Name of the component. Will be used, for example, in Layers and badges * @property {Boolean} [removable=true] When `true` the component is removable from the canvas, default: `true` * @property {Boolean|String|Function} [draggable=true] Indicates if it's possible to drag the component inside others. * You can also specify a query string to identify elements, * eg. `'.some-class[title=Hello], [data-gjs-type=column]'` means you can drag the component only inside elements * containing `some-class` class and `Hello` title, and `column` components. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drag is possible. Default: `true` * @property {Boolean|String|Function} [droppable=true] Indicates if it's possible to drop other components inside. You can use * a query string as with `draggable`. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drop is possible. Default: `true` * @property {Boolean} [badgable=true] Set to false if you don't want to see the badge (with the name) over the component. Default: `true` * @property {Boolean|Array} [stylable=true] True if it's possible to style the component. * You can also indicate an array of CSS properties which is possible to style, eg. `['color', 'width']`, all other properties * will be hidden from the style manager. Default: `true` * @property {Array} [stylable-require=[]] Indicate an array of style properties to show up which has been marked as `toRequire`. Default: `[]` * @property {Array} [unstylable=[]] Indicate an array of style properties which should be hidden from the style manager. Default: `[]` * @property {Boolean} [highlightable=true] It can be highlighted with 'dotted' borders if true. Default: `true` * @property {Boolean} [copyable=true] True if it's possible to clone the component. Default: `true` * @property {Boolean} [resizable=false] Indicates if it's possible to resize the component. It's also possible to pass an object as [options for the Resizer](https://github.com/GrapesJS/grapesjs/blob/master/src/utils/Resizer.ts). Default: `false` * @property {Boolean} [editable=false] Allow to edit the content of the component (used on Text components). Default: `false` * @property {Boolean} [layerable=true] Set to `false` if you need to hide the component inside Layers. Default: `true` * @property {Boolean} [selectable=true] Allow component to be selected when clicked. Default: `true` * @property {Boolean} [hoverable=true] Shows a highlight outline when hovering on the element if `true`. Default: `true` * @property {Boolean} [locked] Disable the selection of the component and its children in the canvas. You can unlock a children by setting its locked property to `false`. Default: `undefined` * @property {Boolean} [void=false] This property is used by the HTML exporter as void elements don't have closing tags, eg. `
`, `
`, etc. Default: `false` * @property {Object} [style={}] Component default style, eg. `{ width: '100px', height: '100px', 'background-color': 'red' }` * @property {String} [styles=''] Component related styles, eg. `.my-component-class { color: red }` * @property {String} [content=''] Content of the component (not escaped) which will be appended before children rendering. Default: `''` * @property {String} [icon=''] Component's icon, this string will be inserted before the name (in Layers and badge), eg. it can be an HTML string ''. Default: `''` * @property {String|Function} [script=''] Component's javascript. More about it [here](/modules/Components-js.html). Default: `''` * @property {String|Function} [script-export=''] You can specify javascript available only in export functions (eg. when you get the HTML). * If this property is defined it will overwrite the `script` one (in export functions). Default: `''` * @property {Array} [traits=''] Component's traits. More about it [here](/modules/Traits.html). Default: `['id', 'title']` * @property {Array} [propagate=[]] Indicates an array of properties which will be inhereted by all NEW appended children. * For example if you create a component likes this: `{ removable: false, draggable: false, propagate: ['removable', 'draggable'] }` * and append some new component inside, the new added component will get the exact same properties indicated in the `propagate` array (and the `propagate` property itself). Default: `[]` * @property {Array} [toolbar=null] Set an array of items to show up inside the toolbar when the component is selected (move, clone, delete). * Eg. `toolbar: [ { attributes: {class: 'fa fa-arrows'}, command: 'tlb-move' }, ... ]`. * By default, when `toolbar` property is falsy the editor will add automatically commands `core:component-exit` (select parent component, added if there is one), `tlb-move` (added if `draggable`) , `tlb-clone` (added if `copyable`), `tlb-delete` (added if `removable`). * @property {Collection} [components=null] Children components. Default: `null` * @property {Object} [delegate=null] Delegate commands to other components. Available commands `remove` | `move` | `copy` | `select`. eg. `{ remove: (cmp) => cmp.closestType('other-type') }` * * @module docsjs.Component */ export declare class Component extends StyleableModel { /** * @private * @ts-ignore */ get defaults(): ComponentDefinitionDefined; get tagName(): string; get classes(): Selectors; get traits(): Traits; get content(): string; get toolbar(): ToolbarButtonProps[]; get resizable(): boolean | ResizerOptions; get delegate(): ComponentDelegateProps | undefined; get locked(): boolean | undefined; get frame(): Frame | undefined; get page(): Page | undefined; preInit(): void; /** * Hook method, called once the model is created */ init(): void; /** * Hook method, called when the model has been updated (eg. updated some model's property) * @param {String} property Property name, if triggered after some property update * @param {*} value Property value, if triggered after some property update * @param {*} previous Property previous value, if triggered after some property update */ updated(property: string, value: any, previous: any): void; /** * Hook method, called once the model has been removed */ removed(): void; em: EditorModel; opt: ComponentOptions; config: DomComponentsConfig; ccid: string; views: ComponentView[]; view?: ComponentView; viewLayer?: ItemView; rule?: CssRule; prevColl?: Components; __hasUm?: boolean; __symbReady?: boolean; /** * @private * @ts-ignore */ collection: Components; collectionStateListeners: string[]; dataResolverWatchers: ComponentDataResolverWatchers; constructor(props: ComponentProperties | undefined, opt: ComponentOptions); set(keyOrAttributes: A | Partial, valueOrOptions?: ComponentProperties[A] | ComponentSetOptions, optionsOrUndefined?: ComponentSetOptions): this; __postAdd(opts?: { recursive?: boolean; }): void; __postRemove(): void; __onChange(m: any, opts: any): void; __onStyleChange(newStyles: StyleProps): void; __changesUp(opts: any): void; __propSelfToParent(props: any): void; __propToParent(props: any): void; __emitUpdateTlb(): void; __getAllById(): { [id: string]: Component; }; __upSymbProps(m: any, opts?: SymbolToUpOptions): void; __upSymbCls(m: any, c: any, opts?: {}): void; __upSymbComps(m: Component, c: Components, o: any): void; /** * Check component's type * @param {string} type Component type * @return {Boolean} * @example * component.is('image') * // -> false */ is(type: string): boolean; /** * Return all the propeties * @returns {Object} */ props(): Partial; /** * Get the index of the component in the parent collection. * @return {Number} */ index(): number; /** * Change the drag mode of the component. * To get more about this feature read: https://github.com/GrapesJS/grapesjs/issues/1936 * @param {String} value Drag mode, options: `'absolute'` | `'translate'` | `''` * @returns {this} */ setDragMode(value?: DragMode): this; /** * Get the drag mode of the component. * @returns {String} Drag mode value, options: `'absolute'` | `'translate'` | `''` */ getDragMode(): DragMode; /** * Set symbol override. * By setting override to `true`, none of its property changes will be propagated to relative symbols. * By setting override to specific properties, changes of those properties will be skipped from propagation. * @param {Boolean|String|Array} value * @example * component.setSymbolOverride(['children', 'classes']); */ setSymbolOverride(value: boolean | string | string[], options?: DynamicWatchersOptions): void; /** * Get symbol override value. * @returns {Boolean|Array} */ getSymbolOverride(): boolean | string[] | undefined; /** * Find inner components by query string. * **ATTENTION**: this method works only with already rendered component * @param {String} query Query string * @return {Array} Array of components * @example * component.find('div > .class'); * // -> [Component, Component, ...] */ find(query: string): Component[]; /** * Find all inner components by component type. * The advantage of this method over `find` is that you can use it * also before rendering the component * @param {String} type Component type * @returns {Array} * @example * const allImages = component.findType('image'); * console.log(allImages[0]) // prints the first found component */ findType(type: string): Component[]; /** * Find the first inner component by component type. * If no component is found, it returns `undefined`. * @param {String} type Component type * @returns {Component|undefined} * @example * const image = component.findFirstType('image'); * if (image) { * console.log(image); * } */ findFirstType(type: string): Component | undefined; /** * Find the closest parent component by query string. * **ATTENTION**: this method works only with already rendered component * @param {string} query Query string * @return {Component} * @example * component.closest('div.some-class'); * // -> Component */ closest(query: string): Component | undefined; /** * Find the closest parent component by its type. * The advantage of this method over `closest` is that you can use it * also before rendering the component * @param {String} type Component type * @returns {Component} Found component, otherwise `undefined` * @example * const Section = component.closestType('section'); * console.log(Section); */ closestType(type: string): Component | undefined; /** * The method returns a Boolean value indicating whether the passed * component is a descendant of a given component * @param {Component} component Component to check * @returns {Boolean} */ contains(component: Component): boolean; /** * Once the tag is updated I have to rerender the element * @private */ tagUpdated(): void; /** * Replace a component with another one * @param {String|Component} el Component or HTML string * @param {Object} [opts={}] Options for the append action * @returns {Array} New replaced components * @example * const result = component.replaceWith('
Some new content
'); * // result -> [Component] */ replaceWith(el: ComponentAdd, opts?: AddOptions): C[]; /** * Emit changes for each updated attribute * @private */ attrUpdated(m: any, v: any, opts?: SetAttrOptions): void; /** * Update attributes of the component * @param {Object} attrs Key value attributes * @param {Object} options Options for the model update * @return {this} * @example * component.setAttributes({ id: 'test', 'data-key': 'value' }); */ setAttributes(attrs: ObjectAny, opts?: SetAttrOptions): this; /** * Add attributes to the component * @param {Object} attrs Key value attributes * @param {Object} options Options for the model update * @return {this} * @example * component.addAttributes({ 'data-key': 'value' }); */ addAttributes(attrs: ObjectAny, opts?: SetAttrOptions): this; /** * Remove attributes from the component * @param {String|Array} attrs Array of attributes to remove * @param {Object} options Options for the model update * @return {this} * @example * component.removeAttributes('some-attr'); * component.removeAttributes(['some-attr1', 'some-attr2']); */ removeAttributes(attrs?: string | string[], opts?: SetOptions): this; /** * Get the style of the component * @return {Object} */ getStyle(options?: any, optsAdd?: any): StyleProps; /** * Set the style on the component * @param {Object} prop Key value style object * @return {Object} * @example * component.setStyle({ color: 'red' }); */ setStyle(prop?: StyleProps, opts?: UpdateStyleOptions): StyleProps; /** * Return all component's attributes * @return {Object} */ getAttributes(opts?: { noClass?: boolean; noStyle?: boolean; }): { [x: string]: any; }; /** * Add classes * @param {Array|String} classes Array or string of classes * @return {Array} Array of added selectors * @example * model.addClass('class1'); * model.addClass('class1 class2'); * model.addClass(['class1', 'class2']); * // -> [SelectorObject, ...] */ addClass(classes: string | string[]): Selector; /** * Set classes (resets current collection) * @param {Array|String} classes Array or string of classes * @return {Array} Array of added selectors * @example * model.setClass('class1'); * model.setClass('class1 class2'); * model.setClass(['class1', 'class2']); * // -> [SelectorObject, ...] */ setClass(classes: string | string[]): Selector; /** * Remove classes * @param {Array|String} classes Array or string of classes * @return {Array} Array of removed selectors * @example * model.removeClass('class1'); * model.removeClass('class1 class2'); * model.removeClass(['class1', 'class2']); * // -> [SelectorObject, ...] */ removeClass(classes: string | string[]): Selector[]; /** * Returns component's classes as an array of strings * @return {Array} */ getClasses(): any; initClasses(m?: any, c?: any, opts?: any): this; initComponents(): this; initTraits(changed?: any): this; initScriptProps(): void; __scriptPropsChange(m: any, v: any, opts?: any): void; /** * Add new component children * @param {Component|String} components Component to add * @param {Object} [opts={}] Options for the append action * @return {Array} Array of appended components * @example * someComponent.get('components').length // -> 0 * const videoComponent = someComponent.append('
')[0]; * // This will add 2 components (`video` and `div`) to your `someComponent` * someComponent.get('components').length // -> 2 * // You can pass components directly * otherComponent.append(otherComponent2); * otherComponent.append([otherComponent3, otherComponent4]); * // append at specific index (eg. at the beginning) * someComponent.append(otherComponent, { at: 0 }); */ append(components: ComponentAdd, opts?: AddOptions): T[]; /** * Set new collection if `components` are provided, otherwise the * current collection is returned * @param {Component|Component[]|String} [components] Component Definitions or HTML string * @param {Object} [opts={}] Options, same as in `Component.append()` * @returns {Collection|Array<[Component]>} * @example * // Set new collection * component.components('
'); * // Get current collection * const collection = component.components(); * console.log(collection.length); * // -> 2 */ components(components?: T, opts?: ResetComponentsOptions): undefined extends T ? Components : Component[]; /** * If exists, returns the child component at specific index. * @param {Number} index Index of the component to return * @returns {[Component]|null} * @example * // Return first child * component.getChildAt(0); * // Return second child * component.getChildAt(1); */ getChildAt(index: number): Component; /** * If exists, returns the last child component. * @returns {[Component]|null} * @example * const lastChild = component.getLastChild(); */ getLastChild(): Component; /** * Remove all inner components * * @return {this} */ empty(opts?: {}): this; /** * Get the parent component, if exists * @return {Component|null} * @example * component.parent(); * // -> Component */ parent(opts?: any): Component | undefined; /** * Return all parents of the component. * @returns {Array} */ parents(): Component[]; /** * Script updated * @private */ scriptUpdated(): void; /** * Init toolbar * @private */ initToolbar(): void; __loadTraits(tr?: Traits | TraitProperties[], opts?: {}): this; /** * Get traits. * @returns {Array} * @example * const traits = component.getTraits(); * console.log(traits); * // [Trait, Trait, Trait, ...] */ getTraits(): Trait[]; /** * Replace current collection of traits with a new one. * @param {Array} traits Array of trait definitions * @returns {Array} * @example * const traits = component.setTraits([{ type: 'checkbox', name: 'disabled'}, ...]); * console.log(traits); * // [Trait, ...] */ setTraits(traits: TraitProperties[]): Trait[]; /** * Get the trait by id/name. * @param {String} id The `id` or `name` of the trait * @return {Trait|null} Trait getModelToStyle * @example * const traitTitle = component.getTrait('title'); * traitTitle && traitTitle.set('label', 'New label'); */ getTrait(id: string): Trait; /** * Update a trait. * @param {String} id The `id` or `name` of the trait * @param {Object} props Object with the props to update * @return {this} * @example * component.updateTrait('title', { * type: 'select', * options: [ 'Option 1', 'Option 2' ], * }); */ updateTrait(id: string, props: Partial): this; /** * Get the trait position index by id/name. Useful in case you want to * replace some trait, at runtime, with something else. * @param {String} id The `id` or `name` of the trait * @return {Number} Index position of the current trait * @example * const traitTitle = component.getTraitIndex('title'); * console.log(traitTitle); // 1 */ getTraitIndex(id: string): number; /** * Remove trait/s by id/s. * @param {String|Array} id The `id`/`name` of the trait (or an array) * @return {Array} Array of removed traits * @example * component.removeTrait('title'); * component.removeTrait(['title', 'id']); */ removeTrait(id: string | string[]): Trait[]; /** * Add new trait/s. * @param {String|Object|Array} trait Trait to add (or an array of traits) * @param {Options} opts Options for the add * @return {Array} Array of added traits * @example * component.addTrait('title', { at: 1 }); // Add title trait (`at` option is the position index) * component.addTrait({ * type: 'checkbox', * name: 'disabled', * }); * component.addTrait(['title', {...}, ...]); */ addTrait(trait: Parameters[0], opts?: AddOptions): Trait[]; /** * Normalize input classes from array to array of objects * @param {Array} arr * @return {Array} * @private */ normalizeClasses(arr: string[]): Selector[]; /** * Override original clone method * @private * @ts-ignore */ clone(opt?: { symbol?: boolean; symbolInv?: boolean; }): this; /** * Get the name of the component. * @param {Object} [opts={}] Options * @param {Boolean} [opts.noCustom] Avoid custom name assigned to the component. * @returns {String} * */ getName(opts?: { noCustom?: boolean; }): any; /** * Update component name. * @param {String} name New name. */ setName(name?: string, opts?: SetOptions): void; /** * Get the icon string * @return {String} */ getIcon(): string; /** * Return HTML string of the component * @param {Object} [opts={}] Options * @param {String} [opts.tag] Custom tagName * @param {Object|Function} [opts.attributes=null] You can pass an object of custom attributes to replace with the current ones or you can even pass a function to generate attributes dynamically. * @param {Boolean} [opts.withProps] Include component properties as `data-gjs-*` attributes. This allows you to have re-importable HTML. * @param {Boolean} [opts.altQuoteAttr] In case the attribute value contains a `"` char, instead of escaping it (`attr="value ""`), the attribute will be quoted using single quotes (`attr='value "'`). * @return {String} HTML string * @example * // Simple HTML return * component.set({ tagName: 'span' }); * component.setAttributes({ title: 'Hello' }); * component.toHTML(); * // -> * * // Custom attributes * component.toHTML({ attributes: { 'data-test': 'Hello' } }); * // -> * * // Custom dynamic attributes * component.toHTML({ * attributes(component, attributes) { * if (component.get('tagName') == 'span') { * attributes.title = 'Custom attribute'; * } * return attributes; * }, * }); * // -> */ toHTML(opts?: ToHTMLOptions): string; /** * Get inner HTML of the component * @param {Object} [opts={}] Same options of `toHTML` * @returns {String} HTML string */ getInnerHTML(opts?: ToHTMLOptions): string; __innerHTML(opts?: ToHTMLOptions): string; __attrToString(opts?: ToHTMLOptions): string; /** * Returns object of attributes for HTML * @return {Object} * @private */ getAttrToHTML(opts?: ToHTMLOptions): { [x: string]: any; }; /** * Return a shallow copy of the model's attributes for JSON * stringification. * @return {Object} * @private */ toJSON(opts?: ObjectAny): ComponentDefinition; /** * Return an object containing only changed props */ getChangedProps(res: Partial): Partial; /** * Return the component id * @return {String} */ getId(): string; /** * Set new id on the component * @param {String} id * @return {this} */ setId(id: string, opts?: SetOptions & { idUpdate?: boolean; }): this; /** * Get the DOM element of the component. * This works only if the component is already rendered * @param {Frame} frame Specific frame from which taking the element * @return {HTMLElement} */ getEl(frame?: Frame): HTMLElement | undefined; /** * Get the View of the component. * This works only if the component is already rendered * @param {Frame} frame Get View of a specific frame * @return {ComponentView} */ getView(frame?: Frame): ComponentView | undefined; getCurrentView(): ComponentView | undefined; __getScriptProps(): Partial; /** * Return script in string format, cleans 'function() {..' from scripts * if it's a function * @param {string|Function} script * @return {string} * @private */ getScriptString(script?: string | Function): string; emitUpdate(property?: string, ...args: any[]): void; emitWithEditor(event: string, data?: Record, extra?: Record): void; /** * Execute callback function on itself and all inner components * @param {Function} clb Callback function, the model is passed as an argument * @return {this} * @example * component.onAll(component => { * // do something with component * }) */ onAll(clb: (cmp: Component) => void): this; /** * Execute a callback function on all inner child components. * @param {Function} clb Callback function, the child component is passed as an argument * @example * component.forEachChild(child => { * console.log(child) * }) */ forEachChild(clb: (child: Component) => void): void; /** * Remove the component * @return {this} */ remove(opts?: any): this; destroy(options?: ModelDestroyOptions | undefined): false | JQueryXHR; /** * Move the component to another destination component * @param {Component} component Destination component (so the current one will be appended as a child) * @param {Object} opts Options for the append action * @returns {this} * @example * // Move the selected component on top of the wrapper * const dest = editor.getWrapper(); * editor.getSelected().move(dest, { at: 0 }); */ move(component: Component, opts?: AddOptions): this; /** * Check if the component is an instance of some component type. * @param {String} type Component type * @returns {Boolean} * @example * // Add a new component type by extending an existing one * editor.Components.addType('text-ext', { extend: 'text' }); * // Append a new component somewhere * const newTextExt = editor.getSelected().append({ type: 'text-ext' })[0]; * newTextExt.isInstanceOf('text-ext'); // true * newTextExt.isInstanceOf('text'); // true */ isInstanceOf(type: string): boolean; /** * Check if the component is a child of some other component (or component type) * @param {[Component]|String} component Component parent to check. In case a string is passed, * the check will be performed on the component type. * @returns {Boolean} * @example * const newTextComponent = editor.getSelected().append({ * type: 'text', * components: 'My text here', * })[0]; * const innerComponent = newTextComponent.find('b')[0]; * innerComponent.isChildOf(newTextComponent); // true * innerComponent.isChildOf('text'); // true */ isChildOf(component: string | Component): boolean; /** * Reset id of the component and any of its style rule * @param {Object} [opts={}] Options * @return {this} * @private */ resetId(opts?: {}): this; _getStyleRule({ id }?: { id?: string; }): CssRule | undefined; _getStyleSelector(opts?: { id?: string; }): Selector | undefined; _idUpdated(m: any, v: any, opts?: { idUpdate?: boolean; }): this | undefined; static typeExtends: Set; static getDefaults(): any; static isComponent(el: HTMLElement, opts?: any): ComponentDefinitionDefined | boolean | undefined; static ensureInList(model: Component): void; static createId(model: Component, opts?: any): string; static getNewId(list: ObjectAny): string; static getIncrementId(id: string, list: ObjectAny, opts?: { keepIds?: string[]; }): string; static getList(model: Component): { [id: string]: Component; }; static checkId(components: ComponentDefinitionDefined | ComponentDefinitionDefined[], styles?: CssRuleJSON[], list?: ObjectAny, opts?: { keepIds?: string[]; idMap?: PrevToNewIdMap; }): void; } declare class Selectable extends Model { } declare class Selected extends Collection { getByComponent(component: Component): Selectable; addComponent(component: Component, opts: any): Selectable; getComponent(model: Selectable): Component; hasComponent(component: Component): boolean; lastComponent(): Component | undefined; allComponents(): Component[]; removeComponent(component: Component | Component[], opts: any): Selectable; } declare class EditorView extends View { constructor(model: EditorModel); render(): this; private sendTelemetryData; } export interface AssetManagerConfig { /** * Default assets. * @example * [ * 'https://...image1.png', * 'https://...image2.png', * {type: 'image', src: 'https://...image3.png', someOtherCustomProp: 1} * ] */ assets?: (string | Record)[]; /** * Content to add where there is no assets to show. * @default '' * @example 'No assets here, drag to upload' */ noAssets?: string; /** * Style prefix * @default 'am-' */ stylePrefix?: string; /** * Upload endpoint, set `false` to disable upload. * @example 'https://endpoint/upload/assets' */ upload?: false | string; /** * The name used in POST to pass uploaded files. * @default 'files' */ uploadName?: string; /** * Custom headers to pass with the upload request. * @default {} */ headers?: Record; /** * Custom parameters to pass with the upload request, eg. csrf token. * @default {} */ params?: Record; /** * The credentials setting for the upload request, eg. 'include', 'omit'. * @default 'include' */ credentials?: RequestCredentials; /** * Allow uploading multiple files per request. If disabled filename will not have the 'multiUploadSuffix' appended. * @default true */ multiUpload?: boolean; /** * The suffix to append to 'uploadName' when 'multiUpload' is true. * @default '[]' */ multiUploadSuffix?: string; /** * If true, tries to add automatically uploaded assets. To make it work the server should respond with a JSON containing assets in a data key, eg: * { data: [ 'https://.../image.png', {src: 'https://.../image2.png'} ] * @default true */ autoAdd?: boolean; /** * Customize the options passed to the default Fetch API. * @example * fetchOptions: (options) => ({ ...options, method: 'put' }), */ fetchOptions?: (options: RequestInit) => RequestInit; /** * To upload your assets, the module uses Fetch API. With this option you can overwrite it with your own logic. The custom function should return a Promise. * @example * customFetch: (url, options) => axios(url, { data: options.body }), */ customFetch?: (url: string, options: Record) => Promise; /** * Custom uploadFile function. * Differently from the `customFetch` option, this gives a total control over the uploading process, but you also have to emit all `asset:upload:*` events b * y yourself (if you need to use them somewhere). * @example * uploadFile: (ev) => { * const files = ev.dataTransfer ? ev.dataTransfer.files : ev.target.files; * // ...send somewhere * } */ uploadFile?: (ev: DragEvent) => void; /** * In the absence of 'uploadFile' or 'upload' assets will be embedded as Base64. * @default true */ embedAsBase64?: boolean; /** * Handle the image url submit from the built-in 'Add image' form. * @example * handleAdd: (textFromInput) => { * // some check... * editor.AssetManager.add(textFromInput); * } */ handleAdd?: (value: string) => void; /** * Method called before upload, on return false upload is canceled. * @example * beforeUpload: (files) => { * // logic... * const stopUpload = true; * if(stopUpload) return false; * } */ beforeUpload?: (files: any) => void | false; /** * Toggles visiblity of assets url input * @default true */ showUrlInput?: boolean; /** * Avoid rendering the default asset manager. * @default false */ custom?: boolean | { open?: (props: any) => void; close?: (props: any) => void; }; /** * Enable an upload dropzone on the entire editor (not document) when dragging files over it. * If active the dropzone disable/hide the upload dropzone in asset modal, otherwise you will get double drops (#507). * @deprecated */ dropzone?: boolean; /** * Open the asset manager once files are been dropped via the dropzone. * @deprecated */ openAssetsOnDrop?: boolean; /** * Any dropzone content to append inside dropzone element * @deprecated */ dropzoneContent?: string; } export interface BlockManagerConfig { /** * Specify the element to use as a container, string (query) or HTMLElement. * With the empty value, nothing will be rendered. * @default '' */ appendTo?: HTMLElement | string; /** * Default blocks. * @default [] */ blocks?: BlockProperties[]; /** * Append blocks to canvas on click. * With the `true` value, it will try to append the block to the selected component * If there is no selected component, the block will be appened to the wrapper. * You can also pass a function to this option, use it as a catch-all for all block * clicks and implement a custom logic for each block. * @default false * @example * // Example with a function * appendOnClick: (block, editor) => { * if (block.get('id') === 'some-id') * editor.getSelected().append(block.get('content')) * else * editor.getWrapper().append(block.get('content')) * } */ appendOnClick?: boolean | ((block: Block, editor: Editor, opts: { event: Event; }) => void); /** * Avoid rendering the default block manager UI. * More about it here: https://grapesjs.com/docs/modules/Blocks.html#customization * @default false */ custom?: boolean; } export interface CodeManagerConfig { /** * Style prefix. * @default 'cm-' */ stylePrefix?: string; /** * Pass default options to code viewer * @default {} */ optsCodeViewer?: Record; } /** @private */ export interface DeviceProperties { id?: string; /** * Device name. * @example 'Mobile' */ name: string; /** * Width to set for the editor iframe. * @example '900px' */ width: string | null; /** * Height to set for the editor iframe. * @example '600px' */ height?: string; /** * Min height to set for the editor iframe. * @example '600px' */ minHeight?: string; /** * The width which will be used in media queries, if empty the `width` will be used. * @example '900px' */ widthMedia?: string | null; /** * Setup the order of media queries * @example 1 */ priority?: number | null; } /** * @typedef Device * @property {String} [name=''] Device type, eg. `Mobile` * @property {String} [width] Width to set for the editor iframe, eg. '900px' * @property {String} [height=''] Height to set for the editor iframe, eg. '600px' * @property {String} [widthMedia=''] The width which will be used in media queries, If empty the width will be used * @property {Number} [priority=null] Setup the order of media queries */ export declare class Device extends Model { defaults(): { name: string; width: null; height: string; widthMedia: null; priority: null; }; initialize(): void; checkUnit(prop: keyof DeviceProperties): void; getName(): string | undefined; getWidthMedia(): string; } export interface DeviceManagerConfig { /** * The device `id` to select on start, if not indicated, the first available from `devices` will be used. * @default '' */ default?: string; /** * Default devices. * @example * devices: [{ * id: 'desktop', * name: 'Desktop', * width: '', * }, { * id: 'tablet', * name: 'Tablet', * width: '770px', * widthMedia: '992px', * }, * ... * ] */ devices?: DeviceProperties[]; } export interface I18nConfig { /** * Locale value. * @default 'en' */ locale?: string; /** * Fallback locale. * @default 'en' */ localeFallback?: string; /** * Detect locale by checking browser language. * @default true */ detectLocale?: boolean; /** * Show warnings when some of the i18n resources are missing. * @default false */ debug?: boolean; /** * Messages to translate. * @default { en: {...} } */ messages?: Record; /** * Additional messages. This allows extending the default `messages` set directly from the configuration. */ messagesAdd?: Record; } export interface ModalConfig { stylePrefix?: string; title?: string; content?: string; /** * Close modal on interact with backdrop. * @default true */ backdrop?: boolean; /** * Avoid rendering the default modal. * @default false */ custom?: boolean; /** * Extend ModalView object (view/ModalView.js) * @example * extend: { * template() { * return '
...New modal template...
'; * }, * }, */ extend?: Record; } export interface Keymap { id: string; keys: string; handler: string | CommandFunction; } export interface KeymapOptions { /** * Force the handler to be executed. */ force?: boolean; /** * Prevent default of the original triggered event. */ prevent?: boolean; } export interface KeymapsConfig { /** * Default keymaps. */ defaults?: Record & { opts?: KeymapOptions; }>; } export declare class Panels extends ModuleCollection { constructor(module: PanelManager, models: Panel[] | Array>); } declare class PanelsView extends ModuleView { constructor(target: Panels); private onRemove; /** * Add to collection * @param Object Model * * @return Object * @private * */ private addTo; /** * Add new object to collection * @param Object Model * @param Object Fragment collection * @param integer Index of append * * @return Object Object created * @private * */ private addToCollection; render(): this; } declare class PanelManager extends Module { panels: Panels; PanelsViewObj?: PanelsView; /** * Initialize module. Automatically called with a new instance of the editor * @param {Object} config Configurations * @private */ constructor(em: EditorModel); /** * Returns the collection of panels * @return {Collection} Collection of panel */ getPanels(): Panels; /** * Returns panels element * @return {HTMLElement} */ getPanelsEl(): HTMLElement | undefined; /** * Add new panel to the collection * @param {Object|Panel} panel Object with right properties or an instance of Panel * @return {Panel} Added panel. Useful in case passed argument was an Object * @example * const newPanel = panelManager.addPanel({ * id: 'myNewPanel', * visible: true, * buttons: [...], * }); */ addPanel(panel: Panel | PanelProperties): Panel; /** * Remove a panel from the collection * @param {Panel|String} panel Panel instance or panel id * @return {Panel} Removed panel * @example * const somePanel = panelManager.getPanel('somePanel'); * const removedPanel = panelManager.removePanel(somePanel); * * // or by id * const removedPanel = panelManager.removePanel('myNewPanel'); * */ removePanel(panel: Panel | string): Panel; /** * Get panel by ID * @param {string} id Id string * @return {Panel|null} * @example * const myPanel = panelManager.getPanel('myPanel'); */ getPanel(id: string): Panel | null; /** * Add button to the panel * @param {string} panelId Panel's ID * @param {Object|Button} button Button object or instance of Button * @return {Button|null} Added button. Useful in case passed button was an Object * @example * const newButton = panelManager.addButton('myNewPanel',{ * id: 'myNewButton', * className: 'someClass', * command: 'someCommand', * attributes: { title: 'Some title'}, * active: false, * }); * // It's also possible to pass the command as an object * // with .run and .stop methods * ... * command: { * run: function(editor) { * ... * }, * stop: function(editor) { * ... * } * }, * // Or simply like a function which will be evaluated as a single .run command * ... * command: function(editor) { * ... * } */ addButton(panelId: string, button: any): Button | null; /** * Remove button from the panel * @param {String} panelId Panel's ID * @param {String} buttonId Button's ID * @return {Button|null} Removed button. * @example * const removedButton = panelManager.addButton('myNewPanel',{ * id: 'myNewButton', * className: 'someClass', * command: 'someCommand', * attributes: { title: 'Some title'}, * active: false, * }); * * const removedButton = panelManager.removeButton('myNewPanel', 'myNewButton'); * */ removeButton(panelId: string, button: any): Button | null; /** * Get button from the panel * @param {string} panelId Panel's ID * @param {string} id Button's ID * @return {Button|null} * @example * const button = panelManager.getButton('myPanel', 'myButton'); */ getButton(panelId: string, id: string): Button | null; /** * Render panels and buttons * @return {HTMLElement} * @private */ render(): HTMLElement; /** * Active activable buttons * @private */ active(): void; /** * Disable buttons flagged as disabled * @private */ disableButtons(): void; destroy(): void; } export declare class Button extends ModuleModel { defaults(): { id: string; label: string; tagName: string; className: string; command: string; context: string; buttons: never[]; attributes: {}; options: {}; active: boolean; dragDrop: boolean; togglable: boolean; runDefaultCommand: boolean; stopDefaultCommand: boolean; disable: boolean; }; get className(): string; get command(): string; get active(): boolean; set active(isActive: boolean); get togglable(): boolean; get runDefaultCommand(): boolean; get stopDefaultCommand(): boolean; get disable(): boolean; constructor(module: PanelManager, options: any); } export declare class Buttons extends ModuleCollection