Skip to content

Commit

Permalink
docs: update jsdoc comments
Browse files Browse the repository at this point in the history
  • Loading branch information
andrepolischuk committed Apr 15, 2024
1 parent dd36411 commit 905211e
Show file tree
Hide file tree
Showing 15 changed files with 276 additions and 206 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ mediator.defineWidget({
// - should render the widget
async initialize() {
// Wait until the widget enters the viewport
await this.container.whenEnterViewport({lazy: true})
await this.whenContainerInViewport({lazy: true})
// Create an iframe tied to the current widget
this.iframe = this.createIframe(iframeUrl)
// Create an embedded layout
Expand Down
27 changes: 18 additions & 9 deletions src/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,26 @@ import {isVisible} from './utils/dom/viewport'
import type {Debounce} from './types'
import type {Widget} from './widget'

interface ContainerElement extends HTMLElement {
/**
* Container element
*/
export interface ContainerElement extends HTMLElement {
rcWidget?: Widget
}

/**
* Options for waiting when the container enters the viewport
*/
export interface EnterViewportOptions {
/** Включить ленивую загрузку, по-умолчанию false */
/** Enable lazy loading, default is false */
lazy?: boolean
/** Оффсет для ленивой загрузки, по-умолчанию 300 */
/** Offset for lazy loading, default is 300 */
offset?: number
}

/**
* Container for widgets
*/
export class Container extends EventEmitter {
private element: ContainerElement
private reduceViewportChange?: Debounce
Expand All @@ -27,10 +36,10 @@ export class Container extends EventEmitter {
private destroyed = false

/**
* Конструктор контейнера
* Container constructor
*
* @param element DOM-элемент контейнера
* @param reduceViewportChange Функция замедления обработки изменений
* @param element Container's DOM element
* @param reduceViewportChange Function to throttle viewport change events
*/
public constructor(
element: ContainerElement,
Expand All @@ -48,14 +57,14 @@ export class Container extends EventEmitter {
}

/**
* Добавить элемент с контентом
* Append content element
*/
public appendChild(element: HTMLElement) {
this.element.appendChild(element)
}

/**
* Уничтожить контейнер вручную
* Manually destroy the container
*/
public destroy = () => {
if (!this.destroyed) {
Expand Down Expand Up @@ -83,7 +92,7 @@ export class Container extends EventEmitter {
}

/**
* Метод возвращает Promise, который резолвится, когда контейнер входит во вьюпорт сверху
* Returns a Promise that resolves when the container enters the viewport from the top
*/
public async whenEnterViewportFromTop(options: EnterViewportOptions) {
const {lazy = false, offset = 300} = options
Expand Down
31 changes: 17 additions & 14 deletions src/iframe/consumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,21 @@ import {Consumer} from 'magic-transport'
import {IFrameResizer} from './consumer-resizer'

/**
* Конфигурация консъюмера внутри iframe
* Configuration of the consumer inside an iframe
*/
export interface IFrameConsumerConfig {
/** Функция инициализации виджета, должна отрисовывать приложение */
/** Widget initialization function, should render the application */
initialize(): void
/** Фабрика, которая экспортирует фасад, доступный снаружи виджета пользователю */
/** Factory that exports a facade available externally to the widget user */
externalize?(): void
/** Фабрика, которая экспортирует фасад, доступный виджету */
/** Factory that exports a facade available to the widget */
externalizeAsConsumer?(): void
}

class IFrameConsumer {
/**
* Consumer inside an iframe
*/
export class IFrameConsumer {
public id: string
public resizer: IFrameResizer
public transport: Consumer<any, any>
Expand All @@ -28,10 +31,10 @@ class IFrameConsumer {
private parentOrigin?: string

/**
* Конструктор
* Constructor
*
* @param config Конфиг
* @param properties Общие свойства
* @param config Configuration
* @param properties Additional properties
*/
public constructor(
config: IFrameConsumerConfig,
Expand Down Expand Up @@ -77,18 +80,18 @@ class IFrameConsumer {
}

/**
* Фабрика, которая экспортирует фасад, доступный снаружи виджета (вебмастеру)
* Factory that exports a facade available externally to the widget (for the webmaster)
*/
externalize() {
return this.config.externalize?.call(this) ?? this.properties
}

/**
* Фабрика, которая экспортирует фасад, доступный виджету
* Factory that exports a facade available to the widget
*/
externalizeAsConsumer() {
return {
// Эту функцию должен вызывать provider для инициализации
// This function should be called by the provider for initialization
initialize: this.config.initialize.bind(this),
externalizedProps: this.externalize(),
getSize: () => this.resizer.getSize(),
Expand All @@ -100,10 +103,10 @@ class IFrameConsumer {
}

/**
* Регистрация айфрейма
* Iframe registration
*
* @param config Конфиг
* @param properties Общие свойства
* @param config Configuration
* @param properties Additional properties
*/
export function registerIFrame(
config: IFrameConsumerConfig,
Expand Down
38 changes: 25 additions & 13 deletions src/iframe/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import type {Widget} from '../widget'
import {Resizer} from './provider-resizer'

/**
* Обертка над iframe
* Wrapper over an iframe
*
* @event viewportChange Событие изменение вьюпорта элемента
* @event destroy Завершение работы провайдера
* @event viewportChange Event when the viewport of the element changes
* @event destroy Termination of the provider
*/
export class IFrameProvider extends EventEmitter {
public id: string
Expand All @@ -33,12 +33,12 @@ export class IFrameProvider extends EventEmitter {
private destroyed = false

/**
* Создание новой инстанции провайдера
* Creating a new provider instance
*
* @param url URL по которому нужно загрузить iframe
* @param widget Объект виджета
* @param id Уникальный идентификатор виджета
* @param reduceViewportChange Метод создания замедления отслеживания изменения Viewport
* @param url URL to load the iframe from
* @param widget Widget object
* @param id Unique widget identifier
* @param reduceViewportChange Method to debounce viewport change tracking
*/
// eslint-disable-next-line max-params
public constructor(
Expand All @@ -59,10 +59,16 @@ export class IFrameProvider extends EventEmitter {
this.createElement()
}

/**
* Get the current iframe element
*/
public getElement() {
return this.element
}

/**
* Create an iframe element
*/
public createElement() {
this.element = document.createElement('iframe')
this.element.style.display = 'block !important'
Expand All @@ -75,6 +81,9 @@ export class IFrameProvider extends EventEmitter {
onRemoveFromDOM(this.element, this.destroy)
}

/**
* Initialization of the iframe provider
*/
public async initialize() {
this.transport = new Provider<any, any>({
id: this.id,
Expand All @@ -96,9 +105,9 @@ export class IFrameProvider extends EventEmitter {
}

/**
* Подписка на изменение видимой области iframe
* Subscription to changes in the visible area of the iframe
*
* @param callback Функция обратного вызова
* @param callback Callback function
*/
public subscribeVisibleAreaChange(callback: Callback) {
this.subscribeViewportChange()
Expand All @@ -114,6 +123,9 @@ export class IFrameProvider extends EventEmitter {
}
}

/**
* Get the visible area of the iframe
*/
public getVisibleArea(): VisibleArea {
return getVisibleArea(this.element)
}
Expand All @@ -127,21 +139,21 @@ export class IFrameProvider extends EventEmitter {
}

/**
* Обработчик скролла
* Scroll event handler
*/
public updateViewport = () => {
this.emit('viewportChange')
}

/**
* Пересчитать размеры айфрейма
* Recalculate iframe sizes
*/
public resize() {
this.resizer?.resize()
}

/**
* Метод вызывается при удалении айфрейма
* Method called when removing the iframe
*/
public destroy = () => {
if (!this.destroyed) {
Expand Down
18 changes: 15 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
/* eslint-disable import/no-unused-modules */
export {registerIFrame, type IFrameConsumerConfig} from './iframe/consumer'
export {
registerIFrame,
type IFrameConsumer,
type IFrameConsumerConfig
} from './iframe/consumer'
export type {IFrameProvider} from './iframe/provider'
export {BaseLayout} from './layouts/base-layout'
export {EmbedLayout, type EmbedLayoutConfig} from './layouts/embed-layout'
export {OverlayLayout, type OverlayLayoutConfig} from './layouts/overlay-layout'
export type {ContentElement} from './layouts/content-element'
export {
globalViewportEvents,
mutationEvents,
Expand All @@ -10,6 +17,11 @@ export {
type ViewportManager
} from './utils/dom'
export {getVisibleArea, type VisibleArea} from './utils/dom/viewport'
export type {Container} from './container'
export type {Widget, WidgetConfig} from './widget'
export type {
Container,
ContainerElement,
EnterViewportOptions
} from './container'
export type {Widget, WidgetConfig, ExternalizedWidget} from './widget'
export type {Debounce, Callback} from './types'
export {createMediator, Mediator, type MediatorConfig} from './mediator'
21 changes: 12 additions & 9 deletions src/layouts/base-layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import type {Container} from '../container'
import type {ContentElement} from './content-element'

/**
* Базовый лэйаут
* Basic layout
*
* @event destroy Закрытие лэйаута
* @event destroy Destroy layout
*/
export abstract class BaseLayout<T = any> extends EventEmitter {
public id: string
Expand All @@ -24,42 +24,45 @@ export abstract class BaseLayout<T = any> extends EventEmitter {
onRemoveFromDOM(this.element, this.destroy)
}

/**
* Get the current layout element
*/
public getElement() {
return this.element
}

/**
* Показать загрузчик (спиннер)
* Show the loader (spinner)
*/
abstract showLoading(): void

/**
* Скрыть загрузчик (спиннер)
* Hide the loader (spinner)
*/
abstract hideLoading(): void

/**
* Установить контент (или добавить iframe)
* Set content (or add iframe)
*/
abstract setContent(content: ContentElement): void

/**
* Добавить этот лэйаут к элементу
* Add this layout to an element
*/
abstract addToDOM(container: Container): void

/**
* Скрыть лэйаут (возможно с анимацией)
* Hide the layout (possibly with animation)
*/
abstract hide(): void

/**
* Показать лэйаут
* Show the layout
*/
abstract show(): void

/**
* Удалить лэйаут из DOM
* Remove the layout from the DOM
*/
abstract destroy(): void
}
3 changes: 3 additions & 0 deletions src/layouts/content-element.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/**
* Content element
*/
export abstract class ContentElement {
protected abstract element: HTMLElement

Expand Down
Loading

0 comments on commit 905211e

Please sign in to comment.