import Backbone from 'backbone'; export type Debounced = Function & { cancel(): void; }; export type SetOptions = Backbone.ModelSetOptions & { avoidStore?: boolean; }; export type AddOptions = Backbone.AddOptions & { temporary?: boolean; }; export type RemoveOptions = Backbone.Silenceable; export type EventHandler = Backbone.EventHandler; export type ObjectHash = Backbone.ObjectHash; export type ObjectAny = Record; export type ObjectStrings = Record; export type Position = { x: number; y: number; }; export type CombinedModelConstructorOptions = Model> = Backbone.ModelConstructorOptions & E; export interface ViewOptions extends Backbone.ViewOptions { } declare class Model extends Backbone.Model { } declare class Collection extends Backbone.Collection { } declare class View extends Backbone.View { } export interface SelectorProps { name: string; label?: string; type?: number; active?: boolean; private?: boolean; protected?: boolean; } declare class Selector extends Model { defaults(): { name: string; label: string; type: number; active: boolean; private: boolean; protected: boolean; _undo: boolean; }; static readonly TYPE_CLASS = 1; static readonly TYPE_ID = 2; em: EditorModel; /** * @hideconstructor */ constructor(props: any, opts?: any); isId(): boolean; isClass(): boolean; getFullName(opts?: any): string; /** * Get selector as a string. * @returns {String} * @example * // Given such selector: { name: 'my-selector', type: 2 } * console.log(selector.toString()); * // -> `#my-selector` */ toString(): string; /** * Get selector label. * @returns {String} * @example * // Given such selector: { name: 'my-selector', label: 'My selector' } * console.log(selector.getLabel()); * // -> `My selector` */ getLabel(): any; /** * Update selector label. * @param {String} label New label * @example * // Given such selector: { name: 'my-selector', label: 'My selector' } * selector.setLabel('New Label') * console.log(selector.getLabel()); * // -> `New Label` */ setLabel(label: string): this; /** * Get selector active state. * @returns {Boolean} */ getActive(): boolean; /** * Update selector active state. * @param {Boolean} value New active state */ setActive(value: boolean): this; toJSON(opts?: {}): any; /** * Escape string * @param {string} name * @return {string} * @private */ static escapeName(name: string): string; } declare class Selectors extends Collection { modelId(attr: any): string; getStyleable(): Selector[]; getValid({ noDisabled }?: any): Selector[]; getFullString(collection?: Selector[] | null, opts?: { sort?: boolean; }): string; getFullName(opts?: any): string | string[]; } declare class StyleableModel extends Model { /** * Forward style string to `parseStyle` to be parse to an object * @param {string} str * @returns */ parseStyle(str: string): { [x: string]: string; }; /** * To trigger the style change event on models I have to * pass a new object instance * @param {Object} prop * @return {Object} */ extendStyle(prop: ObjectAny): ObjectAny; /** * Get style object * @return {Object} */ getStyle(prop?: string | ObjectAny): ObjectStrings; /** * Set new style object * @param {Object|string} prop * @param {Object} opts * @return {Object} Applied properties */ setStyle(prop?: string | ObjectAny, opts?: ObjectAny): { [x: string]: any; }; /** * Add style property * @param {Object|string} prop * @param {string} value * @example * this.addStyle({color: 'red'}); * this.addStyle('color', 'blue'); */ addStyle(prop: string | ObjectAny, value?: string, opts?: {}): void; /** * Remove style property * @param {string} prop */ removeStyle(prop: string): void; /** * Returns string of style properties * @param {Object} [opts={}] Options * @return {String} */ styleToString(opts?: ObjectAny): string; getSelectors(): Selectors; getSelectorsString(opts?: ObjectAny): any; } 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; /** * 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[]; } 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 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[]; } declare class ComponentWrapper extends Component { get defaults(): { tagName: string; removable: boolean; copyable: boolean; draggable: boolean; components: never[]; traits: never[]; stylable: string[]; }; __postAdd(): void; __postRemove(): void; static isComponent(): boolean; } declare class Frame extends ModuleModel { defaults(): { x: number; y: number; changesCount: number; attributes: {}; width: null; height: null; head: never[]; component: string; styles: string; _undo: boolean; _undoexc: string[]; }; view?: FrameView; /** * @hideconstructor */ constructor(module: CanvasModule, attr: any); get head(): { tag: string; attributes: any; }[]; 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; toJSON(opts?: any): any; } declare class Pages extends Collection { constructor(models: any, em: EditorModel); onReset(m: Page, opts?: { previousModels?: Pages; }): void; onRemove(removed?: Page): void; } export interface PageManagerConfig extends ModuleConfig { pages?: any[]; } declare class PageManager extends ItemManagerModule { storageKey: string; get pages(): Pages; model: ModuleModel; getAll(): Page[]; /** * Get all pages * @name getAll * @function * @returns {Array<[Page]>} * @example * const arrayOfPages = pageManager.getAll(); */ /** * Initialize module * @param {Object} config Configurations */ constructor(em: EditorModel); __onChange(event: string, page: Page, coll: Pages, opts?: any): void; onLoad(): void; _onPageChange(m: any, page: Page, opts: any): void; postLoad(): void; /** * Add new page * @param {Object} props Page properties * @param {Object} [opts] Options * @returns {[Page]} * @example * const newPage = pageManager.add({ * id: 'new-page-id', // without an explicit ID, a random one will be created * styles: `.my-class { color: red }`, // or a JSON of styles * component: '
My element
', // or a JSON of components * }); */ add(props: any, //{ id?: string; styles: string; component: string }, opts?: any): false | Page; /** * Remove page * @param {String|[Page]} page Page or page id * @returns {[Page]} Removed Page * @example * const removedPage = pageManager.remove('page-id'); * // or by passing the page * const somePage = pageManager.get('page-id'); * pageManager.remove(somePage); */ remove(page: string | Page, opts?: any): false | Page | undefined; /** * Get page by id * @param {String} id Page id * @returns {[Page]} * @example * const somePage = pageManager.get('page-id'); */ get(id: string): Page | undefined; /** * Get main page (the first one available) * @returns {[Page]} * @example * const mainPage = pageManager.getMain(); */ getMain(): Page; /** * Get wrapper components (aka body) from all pages and frames. * @returns {Array<[Component]>} * @example * const wrappers = pageManager.getAllWrappers(); * // Get all `image` components from the project * const allImages = wrappers.map(wrp => wrp.findType('image')).flat(); */ getAllWrappers(): ComponentWrapper[]; /** * Change the selected page. This will switch the page rendered in canvas * @param {String|[Page]} page Page or page id * @returns {this} * @example * pageManager.select('page-id'); * // or by passing the page * const somePage = pageManager.get('page-id'); * pageManager.select(somePage); */ select(page: string | Page, opts?: {}): this; /** * Get the selected page * @returns {[Page]} * @example * const selectedPage = pageManager.getSelected(); */ getSelected(): Page | undefined; destroy(): void; store(): any; load(data: any): any; _createId(): string; } declare class Page extends Model { defaults(): { frames: never[]; _undo: boolean; }; em: EditorModel; constructor(props: any, opts?: { em?: EditorModel; config?: PageManagerConfig; }); onRemove(): void; getFrames(): Frames; /** * Get page id * @returns {String} */ getId(): string | number; /** * Get page name * @returns {String} */ getName(): string; /** * Update page name * @param {String} name New page name * @example * page.setName('New name'); */ setName(name: string): this; /** * Get all frames * @returns {Array} * @example * const arrayOfFrames = page.getAllFrames(); */ getAllFrames(): Frame[]; /** * Get the first frame of the page (identified always as the main one) * @returns {Frame} * @example * const mainFrame = page.getMainFrame(); */ getMainFrame(): Frame; /** * Get the root component (usually is the `wrapper` component) from the main frame * @returns {Component} * @example * const rootComponent = page.getMainComponent(); * console.log(rootComponent.toHTML()); */ getMainComponent(): ComponentWrapper; toJSON(opts?: {}): any; } declare class Frames extends ModuleCollection { loadedItems: number; itemsToLoad: number; page?: Page; constructor(module: CanvasModule, models?: Frame[] | Array>); onReset(m: Frame, opts?: { previousModels?: Frame[]; }): void; onRemove(removed?: Frame): void; itemLoaded(): void; listenToLoad(): void; listenToLoadItems(on: boolean): void; } declare class Canvas extends ModuleModel { defaults(): { frame: string; frames: never[]; rulers: boolean; zoom: number; x: number; y: number; scripts: never[]; styles: never[]; }; constructor(module: CanvasModule); get frames(): Frames; init(): void; _pageUpdated(page: Page, prev?: Page): void; updateDevice(opts?: any): void; onZoomChange(): void; } declare abstract class ModuleDomainViews extends ModuleView { itemsView: string; protected itemType: string; reuseView: boolean; viewCollection: TItemView[]; constructor(opts?: any, autoAdd?: boolean); /** * Add new model to the collection * @param {ModuleModel} model * @private * */ private addTo; private itemViewNotFound; protected abstract renderView(model: ModuleModel, itemType: string): TItemView; /** * Render new model inside the view * @param {ModuleModel} model * @param {Object} fragment Fragment collection * @private * */ private add; render(): this; onRender(): void; onRemoveBefore(items: TItemView[], opts: any): void; onRemove(items: TItemView[], opts: any): void; remove(opts?: any): this; clearItems(): void; } export type DraggerPosition = Position & { end?: boolean; }; export type Guide = { x: number; y: number; lock?: number; active?: boolean; }; export interface DraggerOptions { /** * Element on which the drag will be executed. By default, the document will be used */ container?: HTMLElement; /** * Callback on drag start. * @example * onStart(ev, dragger) { * console.log('pointer start', dragger.startPointer, 'position start', dragger.startPosition); * } */ onStart?: (ev: Event, dragger: Dragger) => void; /** * Callback on drag. * @example * onDrag(ev, dragger) { * console.log('pointer', dragger.currentPointer, 'position', dragger.position, 'delta', dragger.delta); * } */ onDrag?: (ev: Event, dragger: Dragger) => void; /** * Callback on drag end. * @example * onEnd(ev, dragger) { * console.log('pointer', dragger.currentPointer, 'position', dragger.position, 'delta', dragger.delta); * } */ onEnd?: (ev: Event, dragger: Dragger, opts: { cancelled: boolean; }) => void; /** * Indicate a callback where to pass an object with new coordinates */ setPosition?: (position: DraggerPosition) => void; /** * Indicate a callback where to get initial coordinates. * @example * getPosition: () => { * // ... * return { x: 10, y: 100 } * } */ getPosition?: () => DraggerPosition; /** * Indicate a callback where to get pointer coordinates. */ getPointerPosition?: (ev: Event) => DraggerPosition; /** * Static guides to be snapped. */ guidesStatic?: () => Guide[]; /** * Target guides that will snap to static one. */ guidesTarget?: () => Guide[]; /** * Offset before snap to guides. * @default 5 */ snapOffset?: number; /** * Document on which listen to pointer events. */ doc?: Document; /** * Scale result points, can also be a function. * @default 1 */ scale?: number | (() => number); } declare class Dragger { opts: DraggerOptions; startPointer: DraggerPosition; delta: DraggerPosition; lastScroll: DraggerPosition; lastScrollDiff: DraggerPosition; startPosition: DraggerPosition; globScrollDiff: DraggerPosition; currentPointer: DraggerPosition; position: DraggerPosition; el?: HTMLElement; guidesStatic: Guide[]; guidesTarget: Guide[]; lockedAxis?: any; docs: Document[]; trgX?: Guide; trgY?: Guide; /** * Init the dragger * @param {Object} opts */ constructor(opts?: DraggerOptions); /** * Update options * @param {Object} options */ setOptions(opts?: Partial): void; toggleDrag(enable?: boolean): void; handleScroll(): void; /** * Start dragging * @param {Event} e */ start(ev: Event): void; /** * Drag event * @param {Event} event */ drag(ev: Event): void; /** * Check if the delta hits some guide */ snapGuides(delta: DraggerPosition): { newDelta: DraggerPosition; trgX: Guide | undefined; trgY: Guide | undefined; }; isPointIn(src: number, trg: number, { offset }?: { offset?: number; }): boolean; setGuideLock(guide: Guide, value: any): Guide; /** * Stop dragging */ stop(ev: Event, opts?: { cancel?: boolean; }): void; keyHandle(ev: Event): void; /** * Move the element * @param {integer} x * @param {integer} y */ move(x: number, y: number, end?: boolean): void; getContainerEl(): HTMLElement[] | Document[]; getWindowEl(): any[]; /** * Returns documents */ getDocumentEl(el?: HTMLElement): Document[]; /** * Get mouse coordinates * @param {Event} event * @return {Object} */ getPointerPos(ev: Event): DraggerPosition | { x: any; y: any; }; getStartPosition(): { x: number; y: number; }; getScrollInfo(): { y: number; x: number; }; detectAxisLock(x: number, y: number): "x" | "y" | undefined; } declare class FrameWrapView extends ModuleView { events(): { "click [data-action-remove]": string; "mousedown [data-action-move]": string; }; elTools?: HTMLElement; frame: FrameView; dragger?: Dragger; cv: CanvasView; classAnim: string; constructor(model: Frame, canvasView: CanvasView); setupDragger(): void; startDrag(ev?: Event): void; __clear(opts?: any): void; remove(opts?: any): this; updateOffset(): void; updatePos(md?: boolean): void; updateSize(): void; /** * Update dimensions of the frame * @private */ updateDim(): void; onScroll(): void; frameLoaded(): void; __handleSize(): { noChanges: boolean; width: any; height: any; newW: any; newH: any; }; render(): this; } declare class FramesView extends ModuleDomainViews { canvasView: CanvasView; private _module; constructor(opts: {} | undefined, config: any); onRemoveBefore(items: FrameWrapView[], opts?: {}): void; onRender(): void; protected renderView(item: any, type: string): FrameWrapView; } export interface MarginPaddingOffsets { marginTop?: number; marginRight?: number; marginBottom?: number; marginLeft?: number; paddingTop?: number; paddingRight?: number; paddingBottom?: number; paddingLeft?: number; } declare class CanvasView extends ModuleView { events(): { wheel: string; }; template(): string; hlEl?: HTMLElement; badgeEl?: HTMLElement; placerEl?: HTMLElement; ghostEl?: HTMLElement; toolbarEl?: HTMLElement; resizerEl?: HTMLElement; offsetEl?: HTMLElement; fixedOffsetEl?: HTMLElement; toolsGlobEl?: HTMLElement; toolsEl?: HTMLElement; framesArea?: HTMLElement; toolsWrapper?: HTMLElement; ready: boolean; frames: FramesView; frame?: FrameView; private timerZoom?; private frmOff?; private cvsOff?; constructor(model: Canvas); _onFramesUpdate(): void; _initFrames(): void; checkSelected(component: Component, opts?: any): void; remove(...args: any): this; preventDefault(ev: Event): void; onCanvasMove(ev: Event): void; toggleListeners(enable: boolean): void; onKeyPress(ev: KeyboardEvent): void; onWheel(ev: KeyboardEvent): void; updateFrames(ev: Event): void; getZoom(): any; /** * Checks if the element is visible in the canvas's viewport * @param {HTMLElement} el * @return {Boolean} */ isElInViewport(el: HTMLElement): boolean; /** * Get the offset of the element * @param {HTMLElement} el * @return { {top: number, left: number, width: number, height: number} } */ offset(el?: HTMLElement, opts?: any): { top: number; left: number; width: number; height: number; }; /** * Cleare cached offsets * @private */ clearOff(): void; /** * Return frame offset * @return { {top: number, left: number, width: number, height: number} } * @public */ getFrameOffset(el?: HTMLElement): { top: number; left: number; width: number; height: number; }; /** * Return canvas offset * @return { {top: number, left: number, width: number, height: number} } * @public */ getCanvasOffset(): { top: number; left: number; width: number; height: number; }; /** * Returns element's rect info * @param {HTMLElement} el * @return { {top: number, left: number, width: number, height: number, zoom: number, rect: any} } * @public */ getElementPos(el: HTMLElement, opts?: any): { top: number; left: number; height: number; width: number; zoom: any; rect: { top: number; left: number; width: number; height: number; }; }; /** * Returns element's offsets like margins and paddings * @param {HTMLElement} el * @return { MarginPaddingOffsets } * @public */ getElementOffsets(el: HTMLElement): MarginPaddingOffsets; /** * Returns position data of the canvas element * @return { {top: number, left: number, width: number, height: number} } obj Position object * @public */ getPosition(opts?: any): { top: number; left: number; width: number; height: number; } | undefined; /** * Update javascript of a specific component passed by its View * @param {ModuleView} view Component's View * @private */ updateScript(view: any): void; /** * Get javascript container * @private */ getJsContainer(view?: ComponentView): any; getFrameView(view?: ComponentView): any; _renderFrames(): void; render(): this; } export type CanvasEvent = "canvas:dragenter" | "canvas:dragover" | "canvas:drop" | "canvas:dragend" | "canvas:dragdata"; declare class CanvasModule extends Module { /** * Get configuration object * @name getConfig * @function * @return {Object} */ /** * Used inside RTE * @private */ getCanvasView(): CanvasView; canvas: Canvas; model: Canvas; private canvasView?; /** * Initialize module. Automatically called with a new instance of the editor * @param {Object} config Configurations * @private */ constructor(em: EditorModel); onLoad(): 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: any, 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; 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; /** * Returns offset viewer element * @returns {HTMLElement} * @private */ 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; /** * Get canvas rectangular data * @returns {Object} */ left: number; height: number; width: number; zoom: any; rect: { top: number; /** * Returns offset viewer element * @returns {HTMLElement} * @private */ 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; }; getTargetToElementFixed(el: any, elToMove: any, opts?: any): { top: number; left: any; canvasOffsetTop: any; canvasOffsetLeft: any; }; /** * 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, opts: any): { y: number; x: number; }; /** * 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 alredy 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: string): 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, y: string): this; /** * Get canvas position coordinates * @returns {Object} Object containing coordinates * @example * canvas.setCoords(100, 100); * const coords = canvas.getCoords(); * // { x: 100, y: 100 } */ getCoords(): { x: number; y: number; }; getZoomDecimal(): number; getZoomMultiplier(): number; toggleFramesEvents(on: boolean): void; getFrames(): Frame[]; /** * Add new frame to the canvas * @param {Object} props Frame properties * @returns {[Frame]} * @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; destroy(): void; } export type DragStop = (cancel?: boolean) => void; export type DragContent = (content: any) => void; declare class Droppable { em: EditorModel; canvas: CanvasModule; el: HTMLElement; counter: number; sortOpts?: Record | null; over?: boolean; dragStop?: DragStop; dragContent?: DragContent; sorter?: any; constructor(em: EditorModel, rootEl?: HTMLElement); toggleEffects(el: HTMLElement, enable: boolean): void; __customTglEff(enable: boolean): void; startCustom(): void; endCustom(cancel?: boolean): void; endDrop(cancel?: boolean, ev?: Event): void; handleDragLeave(ev: Event): void; updateCounter(value: number, ev: Event): void; handleDragEnter(ev: DragEvent | Event): void; 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; }; } declare class FrameView extends ModuleView { /** @ts-ignore */ get tagName(): string; /** @ts-ignore */ get attributes(): { allowfullscreen: string; }; dragging: boolean; droppable?: Droppable; rect?: DOMRect; lastClientY?: number; lastMaxHeight: number; private jsContainer?; private tools; private wrapper?; private frameWrapView?; constructor(model: Frame, view?: FrameWrapView); /** * Update `` 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; autoscroll(): void; updateClientY(ev: Event): void; showGlobalTools(): void; stopAutoscroll(): void; _toggleAutoscrollFx(enable: boolean): void; render(): this; renderScripts(): void; renderStyles(opts?: any): void; renderBody(): void; _toggleEffects(enable: boolean): void; _emitUpdate(): 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, coll?: any, opts?: { temporary?: boolean; }): 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, fragmentEl?: DocumentFragment | null, index?: number): HTMLElement | Text; resetChildren(models: Components, { previousModels }?: { previousModels?: never[] | undefined; }): void; render(parent?: HTMLElement): this; } 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(model: Trait, value: 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; } /** @private */ export interface TraitProperties { /** * Trait type, defines how the trait should 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; /** * The trait label to show for the rendered trait. */ label?: string | false; /** * If `true` the trait value is applied on component */ changeProp?: boolean; attributes?: Record; valueTrue?: string; valueFalse?: string; min?: number; max?: number; unit?: string; step?: number; value?: any; target?: Component; default?: any; placeholder?: string; command?: string | ((editor: Editor, trait: Trait) => any); options?: Record[]; labelButton?: string; text?: string; full?: boolean; } 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; changeProp: boolean; options: never[]; }; constructor(prop: TraitProperties); /** * Get the trait id. * @returns {String} */ getId(): string; /** * 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. * @returns {any} */ getValue(): 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?: { partial?: boolean; }): void; props(): Partial; targetUpdated(): void; getTargetValue(): any; setTargetValue(value: any, opts?: SetOptions): void; setValueFromInput(value: any, final?: boolean, opts?: SetOptions): void; getInitValue(): any; } declare class Traits extends Collection { em: EditorModel; target: Component; constructor(coll: TraitProperties[], options: { em: EditorModel; }); handleReset(coll: TraitProperties[], { previousModels }?: { previousModels?: Trait[]; }): void; handleAdd(model: Trait): void; setTarget(target: Component): void; /** @ts-ignore */ add(models: string | Trait | TraitProperties | (string | Trait | TraitProperties)[], opt?: AddOptions): any[]; } 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 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: any) => void; /** * Function which gets HTMLElement as an arg and returns it relative position */ posFetcher?: (el: HTMLElement, opts: any) => 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: any) => 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; } 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?: {}): 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; } 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; 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 interface ComponentProperties { /** * Component type, eg. `text`, `image`, `video`, etc. * @defaultValue '' */ type?: string; /** * HTML tag of the component, eg. `span`. Default: `div` * @defaultValue 'div' */ tagName?: string; /** * Key-value object of the component's attributes, eg. `{ title: 'Hello' }` Default: `{}` * @defaultValue {} */ attributes?: Record; /** * Name of the component. Will be used, for example, in Layers and badges * @defaultValue '' */ name?: string; /** * When `true` the component is removable from the canvas, default: `true` * @defaultValue 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` * @defaultValue true */ draggable?: boolean | string | ((...params: any[]) => any); /** * 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` * @defaultValue true */ droppable?: boolean | string | ((...params: any[]) => any); /** * Set to false if you don't want to see the badge (with the name) over the component. Default: `true` * @defaultValue 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` * @defaultValue true */ stylable?: boolean | String[]; /** * Indicate an array of style properties which should be hidden from the style manager. Default: `[]` * @defaultValue [] */ unstylable?: String[]; /** * It can be highlighted with 'dotted' borders if true. Default: `true` * @defaultValue true */ highlightable?: boolean; /** * True if it's possible to clone the component. Default: `true` * @defaultValue 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.js). 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` * @defaultValue true */ layerable?: boolean; /** * Allow component to be selected when clicked. Default: `true` * @defaultValue true */ selectable?: boolean; /** * Shows a highlight outline when hovering on the element if `true`. Default: `true` * @defaultValue true */ hoverable?: 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' }` * @defaultValue {} */ style?: any; /** * Component related styles, eg. `.my-component-class { color: red }` * @defaultValue '' */ styles?: string; /** * Content of the component (not escaped) which will be appended before children rendering. Default: `''` * @defaultValue '' */ 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: `''` * @defaultValue '' */ icon?: string; /** * Component's javascript. More about it [here](/modules/Components-js.html). Default: `''` * @defaultValue '' */ script?: string | ((...params: any[]) => any); /** * Component's traits. More about it [here](/modules/Traits.html). Default: `['id', 'title']` * @defaultValue '' */ 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: `[]` * @defaultValue [] */ 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[]; components?: Components; classes?: Selectors; dmode?: DragMode; "script-props"?: string[]; [key: string]: any; } export interface SymbolToUpOptions { 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 type ToHTMLOptions = { /** * 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; /** * 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; } export type ClbObj = ReturnType; export interface Rect { top?: number; left?: number; bottom?: number; right?: number; } declare class ComponentView extends View { /** @ts-ignore */ model: Component; /** @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; initialize(opt?: any): void; __isDraggable(): string | boolean | ((...params: any[]) => any) | undefined; _clbObj(): { editor: Editor; model: Component; 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(): 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; /** * 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(): Rect; isInViewport({ rect }?: { rect?: Rect; }): boolean; scrollIntoView(opts?: { force?: boolean; } & ScrollIntoViewOptions): void; /** * Recreate the element of the view */ reset(): void; _setData(): void; _getFrame(): any; /** * Render children components * @private */ renderChildren(): void; renderAttributes(): void; onAttrUpdate(): void; render(): this; postRender(): void; static getEvents(): any; } declare class ComponentWrapperView extends ComponentView { tagName(): string; } declare class ComponentTable extends Component { get defaults(): { type: string; tagName: string; droppable: string[]; components?: ComponentDefinitionDefined | ComponentDefinitionDefined[] | undefined; traits?: (string | Partial)[] | undefined; }; initialize(props: any, opts: any): void; static isComponent(el: HTMLElement): boolean; } declare class ComponentImage extends Component { get defaults(): { type: string; tagName: string; void: boolean; droppable: number; editable: number; highlightable: number; resizable: { ratioDefault: number; }; traits: string[]; src: string; fallback: string; file: string; components?: ComponentDefinitionDefined | ComponentDefinitionDefined[] | undefined; }; initialize(props: any, opts: any): void; initToolbar(): void; /** * Returns object of attributes for HTML * @return {Object} * @private */ getAttrToHTML(): { [x: string]: any; }; getSrcResult(opt?: { fallback?: boolean; }): any; isDefaultSrc(): boolean; /** * Return a shallow copy of the model's attributes for JSON * stringification. * @return {Object} * @private */ toJSON(opts: Parameters[0]): ComponentDefinition; /** * Parse uri * @param {string} uri * @return {object} * @private */ parseUri(uri: string): { hostname: string; pathname: string; protocol: string; search: string; hash: string; port: string; query: ObjectStrings; }; static isComponent(el: HTMLElement): boolean; } declare class ComponentMap extends ComponentImage { /** @ts-ignore */ get defaults(): { type: string; src: string; void: boolean; mapUrl: string; tagName: string; mapType: string; address: string; zoom: string; attributes: { frameborder: number; }; toolbar: any; traits: ({ label: string; name: string; placeholder: string; changeProp: number; type?: undefined; options?: undefined; min?: undefined; max?: undefined; } | { type: string; label: string; name: string; changeProp: number; options: { value: string; name: string; }[]; placeholder?: undefined; min?: undefined; max?: undefined; } | { label: string; name: string; type: string; min: string; max: string; changeProp: number; placeholder?: undefined; options?: undefined; })[]; droppable: number; editable: number; highlightable: number; resizable: { ratioDefault: number; }; fallback: string; file: string; components?: ComponentDefinitionDefined | ComponentDefinitionDefined[] | undefined; }; initialize(props: any, opts: any): void; updateSrc(): void; /** * Returns url of the map * @return {string} * @private */ getMapUrl(): string; /** * Set attributes by src string * @private */ parseFromSrc(): void; static isComponent(el: HTMLIFrameElement): { type: string; src: string; } | undefined; } declare class ComponentImageView extends ComponentView { classEmpty: string; model: ComponentImage; el: HTMLImageElement; tagName(): string; events(): ObjectAny; initialize(props: any): void; /** * Fetch file if exists */ fetchFile(): void; /** * Update src attribute * @private * */ updateSrc(): void; updateClasses(): void; /** * Open dialog for image changing * @param {Object} e Event * @private * */ onActive(ev: Event): void; onError(): void; onLoad(): void; noDrag(ev: Event): boolean; render(): this; } declare class ComponentMapView extends ComponentImageView { iframe?: HTMLIFrameElement; tagName(): string; events(): {}; initialize(props: any): void; /** * Update the map on the canvas * @private */ updateSrc(): void; getIframe(): HTMLIFrameElement; render(): this; } declare class ComponentText extends Component { get defaults(): { type: string; droppable: boolean; editable: boolean; components?: ComponentDefinitionDefined | ComponentDefinitionDefined[] | undefined; traits?: (string | Partial)[] | undefined; }; } declare class ComponentLink extends ComponentText { get defaults(): { type: string; tagName: string; traits: string[]; droppable: boolean; editable: boolean; components?: ComponentDefinitionDefined | ComponentDefinitionDefined[] | undefined; }; static isComponent(el: HTMLElement, opts?: any): any; } export interface RichTextEditorAction { name: string; icon: string; event?: string; attributes?: Record; result: (rte: RichTextEditor, action: RichTextEditorAction) => void; update?: (rte: RichTextEditor, action: RichTextEditorAction) => number; state?: (rte: RichTextEditor, doc: Document) => number; btn?: HTMLElement; } export interface RichTextEditorOptions { actions?: (RichTextEditorAction | string)[]; classes?: Record; actionbar?: HTMLElement; actionbarContainer?: HTMLElement; styleWithCSS?: boolean; } export type EffectOptions = { event?: Event; }; declare class RichTextEditor { em: EditorModel; settings: RichTextEditorOptions; classes: Record; actionbar: HTMLElement; actions: RichTextEditorAction[]; el: HTMLElement; doc: Document; enabled?: boolean; getContent?: () => string; constructor(em: EditorModel, el: HTMLElement & { _rte?: RichTextEditor; }, settings?: RichTextEditorOptions); destroy(): void; setEl(el: HTMLElement): void; updateActiveActions(): void; enable(opts: EffectOptions): this; disable(): this; __toggleEffects(enable?: boolean, opts?: EffectOptions): this; __onKeydown(event: Event): void; __onPaste(ev: Event): void; /** * Sync actions with the current RTE */ syncActions(): void; /** * Add new action to the actionbar * @param {Object} action * @param {Object} [opts={}] */ addAction(action: RichTextEditorAction, opts?: { sync?: boolean; }): void; /** * Get the array of current actions * @return {Array} */ getActions(): RichTextEditorAction[]; /** * Returns the Selection instance * @return {Selection} */ selection(): Selection | null; /** * Wrapper around [execCommand](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) to allow * you to perform operations like `insertText` * @param {string} command Command name * @param {any} [value=null Command's arguments */ exec(command: string, value?: string): void; /** * Get the actionbar element * @return {HTMLElement} */ actionbarEl(): HTMLElement; /** * Set custom HTML to the selection, useful as the default 'insertHTML' command * doesn't work in the same way on all browsers * @param {string} value HTML string */ insertHTML(value: string | HTMLElement, { select }?: { select?: boolean; }): void; } export interface RichTextEditorConfig { /** * Class name prefix for styles * @default 'rte-' */ stylePrefix?: string; /** * If true, moves the toolbar below the element when the top canvas edge is reached. * @default true */ adjustToolbar?: boolean; /** * Default RTE actions. * @default ['bold', 'italic', 'underline', 'strikethrough', 'link', 'wrap'] */ actions?: string[]; } export type RichTextEditorEvent = "rte:enable" | "rte:disable"; export interface CustomRTE { enable: (el: HTMLElement, rte: T) => T; disable: (el: HTMLElement, rte: T) => T; destroy?: () => void; } declare class RichTextEditorModule extends Module { pfx: string; toolbar: HTMLElement; globalRte?: RichTextEditor; actionbar?: HTMLElement; lastEl?: HTMLElement; actions?: (RichTextEditorAction | string)[]; customRte?: CustomRTE; /** * Get configuration object * @name getConfig * @function * @return {Object} */ constructor(em: EditorModel); destroy(): void; /** * Post render callback * @param {View} ev * @private */ postRender(ev: any): void; /** * Init the built-in RTE * @param {HTMLElement} el * @return {RichTextEditor} * @private */ initRte(el: HTMLElement): RichTextEditor; /** * Add a new action to the built-in RTE toolbar * @param {string} name Action name * @param {Object} action Action options * @example * rte.add('bold', { * icon: 'B', * attributes: {title: 'Bold'}, * result: rte => rte.exec('bold') * }); * rte.add('link', { * icon: document.getElementById('t'), * attributes: {title: 'Link',} * // Example on it's easy to wrap a selected content * result: rte => rte.insertHTML(`${rte.selection()}`) * }); * // An example with fontSize * rte.add('fontSize', { * icon: ``, * // Bind the 'result' on 'change' listener * event: 'change', * result: (rte, action) => rte.exec('fontSize', action.btn.firstChild.value), * // Callback on any input change (mousedown, keydown, etc..) * update: (rte, action) => { * const value = rte.doc.queryCommandValue(action.name); * if (value != 'false') { // value is a string * action.btn.firstChild.value = value; * } * } * }) * // An example with state * const isValidAnchor = (rte) => { * // a utility function to help determine if the selected is a valid anchor node * const anchor = rte.selection().anchorNode; * const parentNode = anchor && anchor.parentNode; * const nextSibling = anchor && anchor.nextSibling; * return (parentNode && parentNode.nodeName == 'A') || (nextSibling && nextSibling.nodeName == 'A') * } * rte.add('toggleAnchor', { * icon: ``, * state: (rte, doc) => { * if (rte && rte.selection()) { * // `btnState` is a integer, -1 for disabled, 0 for inactive, 1 for active * return isValidAnchor(rte) ? btnState.ACTIVE : btnState.INACTIVE; * } else { * return btnState.INACTIVE; * } * }, * result: (rte, action) => { * if (isValidAnchor(rte)) { * rte.exec('unlink'); * } else { * rte.insertHTML(`${rte.selection()}`); * } * } * }) */ add(name: string, action?: Partial): void; /** * Get the action by its name * @param {string} name Action name * @return {Object} * @example * const action = rte.get('bold'); * // {name: 'bold', ...} */ get(name: string): RichTextEditorAction | undefined; /** * Get all actions * @return {Array} */ getAll(): RichTextEditorAction[]; /** * Remove the action from the toolbar * @param {string} name * @return {Object} Removed action * @example * const action = rte.remove('bold'); * // {name: 'bold', ...} */ remove(name: string): RichTextEditorAction | undefined; /** * Get the toolbar element * @return {HTMLElement} */ getToolbarEl(): HTMLElement; /** * Triggered when the offset of the editor is changed * @private */ updatePosition(): void; /** * Enable rich text editor on the element * @param {View} view Component view * @param {Object} rte The instance of already defined RTE * @private * */ enable(view: ComponentView, rte: RichTextEditor, opts?: any): Promise; hideToolbar(): void; /** * Unbind rich text editor from the element * @param {View} view * @param {Object} rte The instance of already defined RTE * @private * */ disable(view: ComponentView, rte?: RichTextEditor): void; } declare class ComponentTextView extends ComponentView { rte?: RichTextEditorModule; rteEnabled?: boolean; activeRte?: RichTextEditor; lastContent?: string; events(): { dblclick: string; input: string; }; initialize(props: any): void; updateContentText(m: any, v: any, opts?: { fromDisable?: boolean; }): void; canActivate(): { result: boolean; delegate: Component | undefined; }; /** * Enable element content editing * @private * */ onActive(ev: Event): Promise; onDisable(): void; /** * Disable element content editing * @private * */ disableEditing(opts?: {}): Promise; /** * get content from RTE * @return string */ getContent(): string; /** * Merge content from the DOM to the model */ syncContent(opts?: ObjectAny): void; insertComponent(content: ComponentDefinition, opts?: {}): Component | Component[]; /** * Callback on input event * @param {Event} e */ onInput(): void; /** * Isolate disable propagation method * @param {Event} * @private * */ disablePropagation(e: Event): void; /** * Enable/Disable events * @param {Boolean} enable */ toggleEvents(enable?: boolean): void; } declare class ComponentLinkView extends ComponentTextView { render(): this; } declare class ComponentVideo extends ComponentImage { get defaults(): { type: string; tagName: string; videoId: string; void: boolean; provider: string; ytUrl: string; ytncUrl: string; viUrl: string; loop: number; poster: string; muted: number; autoplay: number; controls: number; color: string; list: string; rel: number; modestbranding: number; sources: never[]; attributes: { allowfullscreen: string; }; droppable: number; editable: number; highlightable: number; resizable: { ratioDefault: number; }; traits: string[]; src: string; fallback: string; file: string; /** * Update traits by provider * @private */ components?: ComponentDefinitionDefined | ComponentDefinitionDefined[] | undefined; }; initialize(props: any, opts: any): void; /** * Update traits by provider * @private */ updateTraits(): void; /** * Set attributes by src string */ parseFromSrc(): void; /** * Update src on change of video ID * @private */ updateSrc(): void; /** * Returns object of attributes for HTML * @return {Object} * @private */ getAttrToHTML(): { [x: string]: any; }; /** * Return the provider trait * @return {Object} * @private */ getProviderTrait(): { type: string; label: string; name: string; changeProp: boolean; options: { value: string; name: string; }[]; }; /** * Return traits for the source provider * @return {Array} * @private */ getSourceTraits(): ({ type: string; label: string; name: string; changeProp: boolean; } | { label: string; name: string; placeholder: string; changeProp: boolean; } | { label: string; name: string; placeholder: string; changeProp?: undefined; })[]; /** * Return traits for the source provider * @return {Array} * @private */ getYoutubeTraits(): ({ type: string; label: string; name: string; changeProp: boolean; } | { label: string; name: string; placeholder: string; changeProp: boolean; })[]; /** * Return traits for the source provider * @return {Array} * @private */ getVimeoTraits(): ({ type: string; label: string; name: string; changeProp: boolean; } | { label: string; name: string; placeholder: string; changeProp: boolean; })[]; /** * Return object trait * @return {Object} * @private */ getAutoplayTrait(): { type: string; label: string; name: string; changeProp: boolean; }; /** * Return object trait * @return {Object} * @private */ getLoopTrait(): { type: string; label: string; name: string; changeProp: boolean; }; /** * Return object trait * @return {Object} * @private */ getControlsTrait(): { type: string; label: string; name: string; changeProp: boolean; }; /** * Returns url to youtube video * @return {string} * @private */ getYoutubeSrc(): string; /** * Returns url to youtube no cookie video * @return {string} * @private */ getYoutubeNoCookieSrc(): string; /** * Returns url to vimeo video * @return {string} * @private */ getVimeoSrc(): string; static isComponent(el: HTMLVideoElement): any; } declare class ComponentVideoView extends ComponentImageView { videoEl?: HTMLVideoElement | HTMLIFrameElement; model: ComponentVideo; tagName(): string; events(): {}; initialize(): void; /** * Rerender on update of the provider * @private */ updateProvider(): void; /** * Update the source of the video * @private */ updateSrc(): void; /** * Update video parameters * @private */ updateVideo(): void; renderByProvider(prov: string): HTMLVideoElement | HTMLIFrameElement; renderSource(): HTMLVideoElement; renderYoutube(): HTMLIFrameElement; renderYoutubeNoCookie(): HTMLIFrameElement; renderVimeo(): HTMLIFrameElement; initVideoEl(el: HTMLElement): void; render(): this; } declare class ComponentScript extends Component { get defaults(): { type: string; tagName: string; droppable: boolean; draggable: boolean; layerable: boolean; components?: ComponentDefinitionDefined | ComponentDefinitionDefined[] | undefined; traits?: (string | Partial)[] | undefined; }; static isComponent(el: HTMLImageElement): any; } declare class ComponentScriptView extends ComponentView { tagName(): string; events(): {}; render(): this; } declare class ComponentSvg extends Component { get defaults(): { type: string; tagName: string; highlightable: boolean; resizable: { ratioDefault: boolean; }; components?: ComponentDefinitionDefined | ComponentDefinitionDefined[] | undefined; traits?: (string | Partial)[] | undefined; }; getName(): any; static isComponent(el: HTMLElement): boolean; } declare class ComponentSvgIn extends ComponentSvg { get defaults(): { selectable: boolean; hoverable: boolean; layerable: boolean; type: string; tagName: string; highlightable: boolean; resizable: { ratioDefault: boolean; }; components?: ComponentDefinitionDefined | ComponentDefinitionDefined[] | undefined; traits?: (string | Partial)[] | undefined; }; static isComponent(el: any, opts?: any): boolean; } declare class ComponentSvgView extends ComponentView { _createElement(tagName: string): SVGElement; } declare class ComponentTextNode extends Component { get defaults(): { tagName: string; droppable: boolean; layerable: boolean; selectable: boolean; editable: boolean; components?: ComponentDefinitionDefined | ComponentDefinitionDefined[] | undefined; traits?: (string | Partial)[] | undefined; }; toHTML(): string; __escapeContent(content: string): string; static isComponent(el: HTMLElement): { type: string; content: string | null; } | undefined; } declare class ComponentTextNodeView extends ComponentView { _setAttributes(): void; renderAttributes(): void; updateStatus(): void; updateClasses(): void; setAttribute(): void; updateAttributes(): void; initClasses(): void; initComponents(): void; delegateEvents(): this; _createElement(): Text; render(): this; } 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"; declare class ComponentManager extends ItemManagerModule { componentTypes: ({ id: string; model: typeof ComponentTable; view: any; } | { id: string; model: typeof ComponentMap; view: typeof ComponentMapView; } | { id: string; model: typeof ComponentLink; view: typeof ComponentLinkView; } | { id: string; model: typeof ComponentVideo; view: typeof ComponentVideoView; } | { id: string; model: typeof ComponentImage; view: typeof ComponentImageView; } | { id: string; model: typeof ComponentScript; view: typeof ComponentScriptView; } | { id: string; model: typeof ComponentSvgIn; view: typeof ComponentSvgView; } | { id: string; model: typeof ComponentTextNode; view: typeof ComponentTextNodeView; } | { id: string; model: typeof Component; view: typeof ComponentView; })[]; componentsById: { [id: string]: Component; }; componentView?: ComponentWrapperView; Component: typeof Component; Components: typeof Components; ComponentsView: typeof ComponentsView; /** * Name of the module * @type {String} * @private */ storageKey: string; shallow?: Component; /** * Initialize module. Called on a new instance of the editor with configurations passed * inside 'domComponents' field * @param {Object} config Configurations * @private */ constructor(em: EditorModel); load(data: any): any; store(): {}; /** * Returns privately 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?: {}): any[]; /** * 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: Component, opt?: {}): 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: any): 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(): ({ id: string; model: typeof ComponentTable; view: any; } | { id: string; model: typeof ComponentMap; view: typeof ComponentMapView; } | { id: string; model: typeof ComponentLink; view: typeof ComponentLinkView; } | { id: string; model: typeof ComponentVideo; view: typeof ComponentVideoView; } | { id: string; model: typeof ComponentImage; view: typeof ComponentImageView; } | { id: string; model: typeof ComponentScript; view: typeof ComponentScriptView; } | { id: string; model: typeof ComponentSvgIn; view: typeof ComponentSvgView; } | { id: string; model: typeof ComponentTextNode; view: typeof ComponentTextNodeView; } | { id: string; model: typeof Component; view: typeof ComponentView; })[]; 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 component can be moved inside another. * @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 or an HTML string. * @param {Number} [index] Index position. If not specified, the check will perform against appending the source to 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. * @private */ canMove(target: Component, source?: Component, index?: number): { result: boolean; reason: number; target: Component; source: null; }; allById(): { [id: string]: Component; }; getById(id: string): Component; destroy(): void; } export interface ComponentsOptions { em?: EditorModel; config?: DomComponentsConfig; domc?: ComponentManager; } declare class Components extends Collection { opt: ComponentsOptions; config?: DomComponentsConfig; em: EditorModel; domc?: ComponentManager; parent?: Component; __firstAdd?: any; initialize(models: any, opt?: ComponentsOptions): void; 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?: AddOptions & { temporary?: boolean; keepIds?: string[]; }): ComponentDefinitionDefined | ComponentDefinitionDefined[] | undefined; /** @ts-ignore */ add(models: ComponentAdd, opt?: AddOptions & { previousModels?: Component[]; keepIds?: string[]; }): any[]; /** * Process component definition. */ processDef(mdl: any): any; onAdd(model: Component, c?: any, opts?: { temporary?: boolean; }): void; } /** @private */ export interface CssRuleProperties { /** * Array of selectors */ selectors: Selector[]; /** * Object containing style definitions * @default {} */ style?: Record; /** * Additional string css selectors * @default '' */ selectorsAdd?: string; /** * Type of at-rule, eg. `media`, 'font-face' * @default '' */ atRuleType?: string; /** * At-rule value, eg. `(max-width: 1000px)` * @default '' */ mediaText?: string; /** * This property is used only on at-rules, like 'page' or 'font-face', where the block containes only style declarations. * @default false */ singleAtRule?: boolean; /** * State of the rule, eg: `hover`, `focused` * @default '' */ state?: string; /** * If true, sets `!important` on all properties. You can also pass an array to specify properties on which to use important. * @default false */ important?: boolean | string[]; /** * Indicates if the rule is stylable from the editor. * @default true */ stylable?: boolean | string[]; /** * Group for rules. * @default '' */ group?: string; /** * If true, the rule won't be stored in JSON or showed in CSS export. * @default false */ shallow?: boolean; } export interface CssRuleJSON extends Omit { selectors: (string | SelectorProps)[]; } declare class CssRule extends StyleableModel { config: CssRuleProperties; em?: EditorModel; opt: any; defaults(): { selectors: never[]; selectorsAdd: string; style: {}; mediaText: string; state: string; stylable: boolean; atRuleType: string; singleAtRule: boolean; important: boolean; group: string; shallow: boolean; _undo: boolean; }; constructor(props: CssRuleProperties, opt?: any); __onChange(m: CssRule, opts: any): void; clone(): CssRule; ensureSelectors(m: any, c: any, opts: any): void; /** * Returns the at-rule statement when exists, eg. `@media (...)`, `@keyframes` * @returns {String} * @example * const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { * atRuleType: 'media', * atRuleParams: '(min-width: 500px)' * }); * cssRule.getAtRule(); // "@media (min-width: 500px)" */ getAtRule(): string; /** * Return selectors of the rule as a string * @param {Object} [opts] Options * @param {Boolean} [opts.skipState] Skip state from the result * @returns {String} * @example * const cssRule = editor.Css.setRule('.class1:hover', { color: 'red' }); * cssRule.selectorsToString(); // ".class1:hover" * cssRule.selectorsToString({ skipState: true }); // ".class1" */ selectorsToString(opts?: ObjectAny): string; /** * Get declaration block (without the at-rule statement) * @param {Object} [opts={}] Options (same as in `selectorsToString`) * @returns {String} * @example * const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { * atRuleType: 'media', * atRuleParams: '(min-width: 500px)' * }); * cssRule.getDeclaration() // ".class1{color:red;}" */ getDeclaration(opts?: ObjectAny): string; /** * Get the Device the rule is related to. * @returns {[Device]|null} * @example * const device = rule.getDevice(); * console.log(device?.getName()); */ getDevice(): any; /** * Get the State the rule is related to. * @returns {[State]|null} * @example * const state = rule.getState(); * console.log(state?.getLabel()); */ getState(): any; /** * Returns the related Component (valid only for component-specific rules). * @returns {[Component]|null} * @example * const cmp = rule.getComponent(); * console.log(cmp?.toHTML()); */ getComponent(): any; /** * Return the CSS string of the rule * @param {Object} [opts={}] Options (same as in `getDeclaration`) * @return {String} CSS string * @example * const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { * atRuleType: 'media', * atRuleParams: '(min-width: 500px)' * }); * cssRule.toCSS() // "@media (min-width: 500px){.class1{color:red;}}" */ toCSS(opts?: ObjectAny): string; toJSON(...args: any): any; /** * Compare the actual model with parameters * @param {Object} selectors Collection of selectors * @param {String} state Css rule state * @param {String} width For which device this style is oriented * @param {Object} ruleProps Other rule props * @returns {Boolean} * @private */ compare(selectors: any, state?: string, width?: string, ruleProps?: Partial): boolean; } declare class Component extends StyleableModel { /** @ts-ignore */ get defaults(): ComponentDefinitionDefined; get classes(): Selectors; get traits(): Traits; /** * 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; frame?: Frame; rule?: CssRule; prevColl?: Components; __hasUm?: boolean; __symbReady?: boolean; /** @ts-ignore */ collection: Components; initialize(props?: {}, opt?: ComponentOptions): void; __postAdd(opts?: { recursive?: boolean; }): void; __postRemove(): void; __onChange(m: any, opts: any): void; __changesUp(opts: any): void; __propSelfToParent(props: any): void; __propToParent(props: any): void; __emitUpdateTlb(): 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; /** * 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 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 * @return {Component|Array} New added component/s * @example * component.replaceWith('
Some new content
'); * // -> Component */ replaceWith(el: Component): any[]; /** * Emit changes for each updated attribute * @private */ attrUpdated(m: any, v: any, opts?: any): 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?: SetOptions): 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?: SetOptions): 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[], opts?: SetOptions): this; /** * Get the style of the component * @return {Object} */ getStyle(options?: any, optsAdd?: any): ObjectStrings; /** * Set the style on the component * @param {Object} prop Key value style object * @return {Object} * @example * component.setStyle({ color: 'red' }); */ setStyle(prop?: ObjectStrings, opts?: any): ObjectStrings; /** * 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; __logSymbol(type: string, toUp: Component[], opts?: any): void; __initSymb(): void; __isSymbol(): boolean; __isSymbolOrInst(): boolean; __isSymbolTop(): boolean; __isSymbolNested(): boolean; __getAllById(): { [id: string]: Component; }; __getSymbol(): Component | undefined; __getSymbols(): Component[] | undefined; __isSymbOvrd(prop?: string): boolean; __getSymbToUp(opts?: SymbolToUpOptions): Component[]; __getSymbTop(opts?: any): Component; __upSymbProps(m: any, opts?: SymbolToUpOptions): void; __upSymbCls(m: any, c: any, opts?: {}): void; __upSymbComps(m: Component, c: Components, o: any): void; 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): Component[]; /** * 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?: any): 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): any[]; /** * Normalize input classes from array to array of objects * @param {Array} arr * @return {Array} * @private */ normalizeClasses(arr: string[]): Selector[]; /** * Override original clone method * @private */ clone(opt?: { symbol?: boolean; symbolInv?: boolean; }): any; /** * 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; /** * 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 | undefined; __innerHTML(opts?: ToHTMLOptions): string | undefined; /** * Returns object of attributes for HTML * @return {Object} * @private */ getAttrToHTML(): { [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?: undefined): 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; /** * 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; /** * Remove the component * @return {this} */ remove(opts?: any): this; /** * 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 getDefaults(): any; static isComponent(el: HTMLElement): 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): any; static checkId(components: ComponentDefinitionDefined | ComponentDefinitionDefined[], styles?: CssRuleJSON[], list?: ObjectAny, opts?: { keepIds?: string[]; }): 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; } export interface CssComposerConfig { /** * Style prefix. * @default 'css-' */ stylePrefix?: string; /** * Default CSS style rules */ rules?: Array; } 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; } export type RuleOptions = { atRuleType?: string; atRuleParams?: string; }; 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 * @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]} 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 } } */ setRule(selectors: any, style?: CssRuleProperties["style"], opts?: RuleOptions): 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?: ObjectAny): 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?: ObjectAny): 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?: ObjectAny): 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?: ObjectAny): 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?: ObjectAny): CssRule[]; /** * Render the block of CSS rules * @return {HTMLElement} * @private */ render(): HTMLElement; destroy(): void; } 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 '[]' appended. * @default true */ multiUpload?: boolean; /** * 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 CategoryViewConfig { em: EditorModel; pStylePrefix?: string; } declare class CategoryView extends View { em: EditorModel; config: CategoryViewConfig; pfx: string; caretR: string; caretD: string; iconClass: string; activeClass: string; iconEl?: HTMLElement; blocksEl?: HTMLElement; events(): { "click [data-title]": string; }; template({ pfx, label }: { pfx: string; label: string; }): string; /** @ts-ignore */ attributes(): Record; constructor(o: any, config: CategoryViewConfig); updateVisibility(): void; open(): void; close(): void; toggle(): void; getIconEl(): HTMLElement; getBlocksEl(): HTMLElement; append(el: HTMLElement): void; render(): this; } export interface BlockCategoryProperties { /** * 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; } declare class Category extends Model { view?: CategoryView; defaults(): { id: string; label: string; open: boolean; attributes: {}; }; } /** @private */ export interface BlockProperties { /** * Block label, eg. `My block` */ label: string; /** * The content of the block. Might be an HTML string or a [Component Defintion](/modules/Components.html#component-definition) */ content: string | ComponentDefinition; /** * 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; } 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: {}; }; /** * 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(): string | ComponentDefinition | undefined; /** * Get block category label * @returns {String} */ getCategoryLabel(): 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; /** * Inline Css * @default false */ inlineCss?: boolean; } /** @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; /** * 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; } 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 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 ButtonProps { id?: string; active?: boolean; togglable?: boolean; className?: string; command?: string | (() => any); context?: string; attributes?: Record; } export interface PanelProps { id?: string; buttons?: ButtonProps[]; } export interface PanelsConfig { stylePrefix?: string; /** * Default panels. */ defaults?: PanelProps[]; } export interface ParsedCssRule { selectors: string; style: Record; atRule?: string; params?: string; } export type CustomParserCss = (input: string, editor: Editor) => ParsedCssRule[]; export type CustomParserHtml = (input: string, options: HTMLParserOptions) => HTMLElement; export interface HTMLParserOptions { /** * DOMParser mime type. * If you use the `text/html` parser, it will fix the invalid syntax automatically. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString * @default 'text/html' */ htmlType?: DOMParserSupportedType; /** * Allow '; * const safeStr = 'Hello'; * // Use `$${var}` to avoid escaping * const strHtml = editor.html`Escaped ${unsafeStr} unescaped $${safeStr}`; */ html: typeof html; } declare const GrapesJS: { $: any; editors: Editor[]; plugins: PluginManager; version: any; /** * Initialize the editor with passed options * @param {Object} config Configuration object * @param {string|HTMLElement} config.container Selector which indicates where render the editor * @param {Boolean} [config.autorender=true] If true, auto-render the content * @param {Array} [config.plugins=[]] Array of plugins to execute on start * @param {Object} [config.pluginsOpts={}] Custom options for plugins * @param {Boolean} [config.headless=false] Init headless editor * @return {Editor} Editor instance * @example * var editor = grapesjs.init({ * container: '#myeditor', * components: '
Hello world
', * style: '.hello{color: red}', * }) */ init(config?: EditorConfig): Editor; }; export { GrapesJS as default, }; export {};