useblocks 1.1.43 → 1.1.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,635 +1,507 @@
1
- <p align="left">
2
- <a href="https://emailmaker.ru/" target="blank"><img src="https://emcdn.ru/389992/240402_17_0uOwHpL.png" width="500" alt="EmailMaker" /></a>
3
- </p>
4
1
 
2
+ # Installation
5
3
 
6
- # Установка
7
-
8
- Установите пакет из npm:
4
+ Install the Blocks package:
9
5
 
10
6
  ```bash
11
- npm install @emailmaker/emailmaker
7
+ npm install useblocks
12
8
  ```
13
9
 
14
- ### Полезные ссылки
15
-
16
- - Каталог пакета на npm: [@emailmaker/emailmaker](https://www.npmjs.com/package/@emailmaker/emailmaker)
17
- - Справка на сайте EmailMaker: [Подключение редактора](https://emailmaker.ru/docs/help/plugin/connecting-the-editor/)
10
+ Add the Blocks **build plugin** to your bundled app configuration (it copies package assets into the output and injects **`__useblocks__.publicPath`** for chunk URLs). Without the helper plugin you must set the bundle base URL yourself.
18
11
 
19
- Добавьте плагин сборки EmailMaker в конфигурацию приложения (он копирует статику пакета и задаёт **`__emailmaker__.publicPath`** для загрузки чанков). Без Webpack/Vite-плагина вручную нужно обеспечить корректный базовый путь к бандлу.
12
+ ## Agents & automation checklist
20
13
 
21
- ## Чеклист для агентов и автоматизации
14
+ Use this when generating integration code or reviewing PRs against the Blocks plugin SDK. Canonical typings live in **`useblocks.d.ts`** (**`ExportedApi`**); avoid inventing field names.
22
15
 
23
- Используйте таблицу при генерации кода интеграции или ревью. Источник типов — **`emailmaker.d.ts`** в пакете (**`ExportedApi`**); не подставляйте вымышленные поля API.
16
+ For how merged **`ExportedApi`** interfaces, **`AppEvent`**, and payload types fit together (and how **`handleSubjectChanged`** differs), see **`docs/plugin-types-agents.md`** in the upstream authoring repository.
24
17
 
25
- Подробнее о том, как в `.d.ts` сливаются **`ExportedApi.Options` / `Instance`**, что такое **`AppEvent`** и **`SaveEventPayload`**, и как читать исключения (**`handleSubjectChanged`** и др.): в репозитории EmailMaker — **`docs/plugin-types-agents.md`**.
26
-
27
- | Правило | Детали |
18
+ | Rule | Details |
28
19
  | --- | --- |
29
- | **`init`** | Обязательно **`content`**. Сигнатура: **`init(options)` → `Promise<Instance>`**. |
30
- | Namespace vs **instance** | У модуля **`emailmaker`** — в основном **`init`** (+ именованные ESM-экспорты). **`setConfig`**, **`show`**, **`save`**, **`destroy`** — у **экземпляра** после **`init`**. |
31
- | Повтор на том же DOM | Повторный **`init`** на тот же узел ведёт к **`reset`** — не запускайте два параллельных **`init`** на один контейнер. |
32
- | События | **`instance.handle*(…)`** обычно возвращает **отписку**. **`handleSubjectChanged`** / **`handlePreheaderChanged`** — другая сигнатура (см. типы). |
33
- | Async | Колбэки и **`getAuthToken`** могут быть **`async`**; ошибки — через **`handleError`** или свою логику. |
34
- | Сборка | Без штатного плагина Webpack/Vite задайте **`publicPath`** (**`__emailmaker__`**). Бандл крупный (React, Monaco и др.). |
35
- | Авторизация | **`getAuthToken`** или **`jwtAuth`**; **`client_secret`** только на сервере. |
36
- | Файловый менеджер | **`storageProvider`**, **`config.imageCenterFileManagerView: true`**, при необходимости секция **`config.fileManager`** (**`ExportedApi.FileManagerOptions`**). Контракт **`StorageProvider`** объёмен — сверяйтесь с типами. |
37
- | **`baseUrl`** | Origin API без суффикса `/wp-json` (напр. `https://api.emailmaker.ru` или `https://app.emailmaker.ru/api`); SDK добавляет `/wp-json` сам. |
38
- | **`standaloneKey`** | Режимы с прокси файлов через события (см. код плагина); редкие сценарии. |
39
- | **`commonStyles`** | Опционально на **`init` / `reset`**: объект стилей контента (частичный merge с **`COMMON_STYLES`**). Подробности — **`docs/plugin-content-styles.md`**. |
20
+ | **`init`** | **`content` is mandatory**. **`init(options) → Promise<Instance>`**. |
21
+ | Module vs **instance** | The **`useblocks`** bundle exports **`init`** (plus optional named ESM APIs). **`setConfig`**, **`show`**, **`save`**, **`destroy`** belong to the **`init`** return value—not the namespace object. |
22
+ | Same DOM repeat | Calling **`init`** again on an existing mount triggers **`reset`**. Avoid parallel **`init`** on one container. |
23
+ | Events | **`instance.handle*(…)`** usually returns **unsubscribe**. **`handleSubjectChanged`** / **`handlePreheaderChanged`** use bespoke signatures — see typings. |
24
+ | Async | Handlers plus **`getAuthToken`** may be **`async`**; funnel errors via **`handleError`** or your own telemetry. |
25
+ | Build | Without Webpack/Vite helpers you must wire **`__useblocks__`** / **`publicPath`**. Expect a heavy UI bundle (React, Monaco, etc.). |
26
+ | Auth | Prefer **`getAuthToken`** or **`jwtAuth`**; keep **`client_secret`** on the server only. |
27
+ | File manager | Wire **`storageProvider`** + **`config.imageCenterFileManagerView`** and read the **`StorageProvider`** contract before stubbing backends. |
28
+ | **`commonStyles`** | Optional on **`init` / `reset`**: content-styles object (partial merge with **`COMMON_STYLES`**). Details — **`docs/plugin-content-styles.md`** in the authoring repository. |
40
29
 
41
- Примеры в репозитории: **`src/pluginExamples/`** (например **`plugin_default.html`**).
30
+ Reference HTML samples (`plugin_default.html`, etc.) live under **`src/pluginExamples/`** in the authoring repository.
42
31
 
43
- ### Для сборщика Webpack
32
+ ### Webpack
44
33
 
45
- Импортируйте класс и передайте его в `plugins` под тем же именем:
34
+ Use the exported class constructor with matching variable name:
46
35
 
47
36
  ```javascript
48
- const EmailmakerWebpackPlugin = require('@emailmaker/emailmaker/webpack');
37
+ const UseblocksWebpackPlugin = require('useblocks/webpack');
49
38
 
50
39
  module.exports = {
51
40
  plugins: [
52
- new EmailmakerWebpackPlugin({
53
- // По желанию: outputFolder, modulesPath, publicPath — см. пакет.
41
+ new UseblocksWebpackPlugin({
42
+ // Optional: outputFolder, modulesPath, publicPath — see package.
54
43
  }),
55
44
  ],
56
45
  };
57
46
  ```
58
47
 
59
- ### Для сборщика Vite
60
-
61
- Импорт только из **scoped-пакета**:
48
+ ### Vite
62
49
 
63
50
  ```javascript
64
51
  import { defineConfig } from 'vite';
65
- import emailmakerVite from '@emailmaker/emailmaker/vite';
52
+ import useblocksVite from 'useblocks/vite';
66
53
 
67
54
  export default defineConfig({
68
55
  plugins: [
69
- emailmakerVite({
70
- // По желанию: outputFolder, modulesPath, publicPath — см. пакет.
56
+ useblocksVite({
57
+ // Optional: outputFolder, modulesPath, publicPath — see package.
71
58
  }),
72
59
  ],
73
60
  });
74
61
  ```
75
62
 
76
- ## `__emailmaker__`
63
+ ## `__useblocks__`
77
64
 
78
- Плагины Webpack/Vite добавляют в бандл объект **`__emailmaker__ = { publicPath: '...' }`** с базовым URL к чанкам пакета. Вручную менять его обычно не нужно; без штатного плагина задайте **`publicPath`** самостоятельно так, чтобы загрузчик нашёл собранные **`emailmaker.js`** / **`emailmaker-esm.js`**.
65
+ Webpack/Vite host plugins inject **`__useblocks__ = { publicPath: '...' }`** so chunk URLs resolve correctly. You rarely need to touch it manually; without the helper plugins, set **`publicPath`** so the loader finds **`useblocks.js`** / **`useblocks-esm.js`**.
79
66
 
80
- Имя класса Webpack-плагина строится из имени приложения в `package.json` (для **`@emailmaker/emailmaker`** это **`EmailmakerWebpackPlugin`**).
67
+ For **`useblocks`** the Webpack plugin class is **`UseblocksWebpackPlugin`**.
81
68
 
82
- # Инициализация
69
+ # Initialization
83
70
 
84
- Импортируйте плагин в коде приложения:
71
+ Import the plugin in application code:
85
72
 
86
73
  ```javascript
87
- import * as emailmaker from '@emailmaker/emailmaker';
74
+ import * as useblocks from 'useblocks';
88
75
  ```
89
76
 
90
- У **`init`** обязательное поле — **`content`** (HTML-строка или объект письма / шаблона). После успешной инициализации методы **`setConfig`**, **`updateConfig`**, **`show`**, **`save`** и др. доступны у **экземпляра**, возвращённого из **`init`** (не у объекта `emailmaker`).
77
+ **`init`** requires **`content`** (HTML string or email/template wrapper). Methods such as **`setConfig`**, **`updateConfig`**, **`show`**, **`save`** are on the **instance returned from `init`**, not on the **`useblocks`** namespace object.
91
78
 
92
- Частые поля верхнего уровня — в таблице; детали конфигурации и содержимого см. ниже в разделе **«Конфигурация»**.
79
+ Typical root fields include **`getAuthToken`** or **`jwtAuth`**, **`element`**, **`content`**, **`config`**, **`project`**, **`baseUrl`**, **`storageProvider`**, **`commonStyles`**.
93
80
 
94
- | Поле | Назначение |
95
- | --- | --- |
96
- | **`getAuthToken`** или **`jwtAuth`** | OAuth-колбэк **или** вход по логину/паролю (**`ExportedApi.JWTMixin`** / **`jwtAuth`**). Не смешивайте сценарии без необходимости. |
97
- | **`element`** | Контейнер монтирования (селектор, узел или фрагмент). |
98
- | **`content`** | Обязательно: HTML-строка или объект письма/шаблона. |
99
- | **`config`** | Настройки UI редактора (**`ExportedApi.Config`**). |
100
- | **`project`** | Идентификатор проекта в вашей системе / в EmailMaker. |
101
- | **`baseUrl`** | Origin API без `/wp-json` (см. **`AppInitMixin.Options`**). |
102
- | **`storageProvider`** | Реализация **`StorageProvider`** для файлового менеджера. |
103
- | **`standaloneKey`** | Редкие режимы прокси файлов (**`instance.handleFileProxy`** / **`handleUrlProxy`**). |
104
- | **`commonStyles`** | Объект стилей контента (частичный **merge** с **`COMMON_STYLES`**). См. **`docs/plugin-content-styles.md`**. |
81
+ - **`commonStyles`** — optional content-styles preset merged with shipped **`COMMON_STYLES`** (see **`docs/plugin-content-styles.md`** in the authoring repository). Partial objects are safe.
105
82
 
106
- - **`getAuthToken`** — функция **`(user?, project?, prevToken?) => string | Promise<string>`**, возвращающая OAuth access token. **`client_secret`** получайте **только на сервере**.
107
- - **`jwtAuth`** — **`{ email, password, remember? }`** вместо **`getAuthToken`** (см. **`ExportedApi.JWTMixin`** в **`emailmaker.d.ts`**).
83
+ - **`getAuthToken`** — **`(user?, project?, prevToken?) => string | Promise<string>`**. Obtain **`client_secret` only from your backend**; never expose it in the browser.
84
+ - **`jwtAuth`** — alternative to **`getAuthToken`**: **`{ email, password, remember? }`** (see **`useblocks.d.ts`** or shipped typings).
108
85
 
109
- Именованные экспорты в ESM-сборке (**`emailmaker-esm.js`**):
86
+ ESM builds also expose named exports (for example **`useblocks-esm.js`**):
110
87
 
111
88
  ```javascript
112
- import { init, parseAMP, COMMON_STYLES, version, helpers, errors } from '@emailmaker/emailmaker';
89
+ import { init, parseAMP, COMMON_STYLES, version, helpers, errors } from 'useblocks';
113
90
  ```
114
91
 
115
- | Экспорт | Назначение |
116
- | --- | --- |
117
- | **`init`** | То же, что **`emailmaker.init`**, с ленивой подгрузкой ядра (**`Promise<Instance>`**). |
118
- | **`parseAMP`** | Разбор AMP: вход — строка или **`{ code }`**, результат **`ParsedAMP`** (html / ampHtml и т.д.). |
119
- | **`COMMON_STYLES`** | Дефолтный пресет стилей контента текущей сборки EmailMaker. Для **`init({ commonStyles: { ...COMMON_STYLES, … } })`**. Исходник с JSDoc: **`src/constants/commonStyles.defaults.ts`**. |
120
- | **`version`** | Строка версии сборки. |
121
- | **`helpers`** | Вспомогательные утилиты (например, соответствие HTTP-статусов кодам ошибок). |
122
- | **`errors`** | Ошибки API, в т.ч. **`errors.FileManagerApiError`** для контракта с файловым менеджером. |
92
+ **`parseAMP`** parses AMP email code without UI; **`COMMON_STYLES`** is the default content-styles object for this build (spread into **`init({ commonStyles })`**); documented in **`src/constants/commonStyles.defaults.ts`**. **`version`** is the build string; **`helpers`** / **`errors`** include HTTP helpers and error classes (e.g. file manager).
123
93
 
124
- ### Получение OAuth токена на бэкенде
94
+ ### Fetching the OAuth token on the backend
125
95
 
126
96
  ```bash
127
- curl --location 'https://api.emailmaker.ru/oauth/token' \
97
+ curl --location 'https://api.useblocks.io/oauth/token' \
128
98
  --header 'Content-Type: application/x-www-form-urlencoded' \
129
99
  --data-urlencode 'client_id=*******' \
130
100
  --data-urlencode 'client_secret=*******' \
131
101
  --data-urlencode 'grant_type=client_credentials'
132
102
  ```
133
103
 
134
- Пример **клиентской** функции: токен отдаёт ваш бэкенд (секрет не уходит в браузер):
104
+ ### Creating the plugin instance
135
105
 
136
106
  ```javascript
137
- async function getAuthToken(user, project, prevToken) {
138
- const res = await fetch('/api/your-backend/emailmaker-token', { method: 'POST' });
139
- const data = await res.json();
140
- return data.access_token;
141
- }
142
- ```
143
-
144
- ### Создание сущности EmailMaker plugin
145
-
146
- Простейший вариант — HTML письма и тема:
147
-
148
- ```javascript
149
- emailmaker
107
+ useblocks
150
108
  .init({
151
109
  getAuthToken,
152
110
  element: '#test',
153
111
  content: {
154
- subject: 'Тема письма',
155
- html: `КОД_ПИСЬМА`,
112
+ subject: 'Email subject',
113
+ html: 'EMAIL_CODE',
156
114
  },
157
115
  config: {},
158
116
  })
159
117
  .then((instance) => {});
160
118
  ```
161
119
 
162
- Вариант с **шаблоном** и внешним id письма:
120
+ You can take **`EMAIL_CODE`** from <a href="https://cdn.useblocks.io/plugin/new-email.html" target="_blank">our sample</a> or paste your own HTML.
163
121
 
164
- ```javascript
165
- emailmaker
166
- .init({
167
- getAuthToken,
168
- element: '#editor',
169
- project: 'ключ-проекта-в-вашей-системе',
170
- content: {
171
- templateId: 22304,
172
- email: {
173
- id: 'crm-email-id-123',
174
- },
175
- blocks: [],
176
- },
177
- config: {
178
- theme: 'light',
179
- // advancedConfigs: { editor: { … }, pro: { … } },
180
- },
181
- })
182
- .then((instance) => {});
183
- ```
184
-
185
- КОД_ПИСЬМА можно взять из <a href="https://emcdn.ru/plugin/new-email.html" target="_blank">нашего образца</a> или вставить HTML-код своего письма.
186
-
187
- ### React (обёртка)
188
-
189
- Минимальный каркас: монтирование, **`destroy`** при размонтировании.
190
-
191
- ```tsx
192
- import { useEffect, useRef } from 'react';
193
- import * as emailmaker from '@emailmaker/emailmaker';
194
-
195
- export function EmailmakerEditor({
196
- project,
197
- templateId,
198
- getAuthToken,
199
- }: {
200
- project: string | number;
201
- templateId: number;
202
- getAuthToken: NonNullable<Parameters<typeof emailmaker.init>[0]['getAuthToken']>;
203
- }) {
204
- const rootRef = useRef<HTMLDivElement>(null);
205
-
206
- useEffect(() => {
207
- let instance: Awaited<ReturnType<typeof emailmaker.init>> | undefined;
208
-
209
- (async () => {
210
- instance = await emailmaker.init({
211
- getAuthToken,
212
- element: rootRef.current ?? '#emailmaker-root',
213
- project,
214
- content: { email: { id: 'new' }, templateId },
215
- config: { theme: 'light' },
216
- });
217
- })();
218
-
219
- return () => {
220
- instance?.destroy();
221
- };
222
- }, [project, templateId, getAuthToken]);
223
-
224
- return <div id="emailmaker-root" ref={rootRef} style={{ height: '100vh' \}} />;
225
- }
226
- ```
122
+ For debugging, the dev build may support a front-end token flow — configure an auth proxy in your app if you use that path.
227
123
 
228
- # Конфигурация
124
+ # Configuration
229
125
 
230
- Конфигурация задаётся объектом с несколькими уровнями вложенности: внешний вид редактора, стартовое содержимое и обработчики событий.
126
+ Configuration is a nested object: editor chrome, initial email payload, and callback hooks.
231
127
 
232
- Повторный вызов **`init`** на **тот же DOM-элемент** внутри приводит к **`reset`** с новыми опциями — не запускайте параллельно два **`init`** на один контейнер.
128
+ Calling **`init`** again on the **same DOM host** internally performs **`reset`** with the new options — avoid two concurrent **`init`** calls on one container.
233
129
 
234
- ### element
130
+ ### Element
235
131
 
236
- Строка-селектор, **`Element`** или **`DocumentFragment`**: контейнер, куда монтируется редактор. Если элемент не задан, приложение может работать в фоновом режиме без видимого контейнера.
132
+ Pass a selector string, an **`Element`**, or a **`DocumentFragment`**. Omitting **`element`** can run in background mode without a visible host.
237
133
 
238
- ### content
134
+ ### Content
239
135
 
240
- Секция **`content`** задаёт данные для редактора. Варианты:
136
+ Possible shapes:
241
137
 
242
- #### {string}
138
+ #### `{string}`
243
139
 
244
- HTML-разметка письма.
140
+ Raw HTML markup for the email.
245
141
 
246
- #### {object} параметры письма
142
+ #### `{object}` email fields
247
143
 
248
144
  ```javascript
249
145
  {
250
- id?: string; // Уникальный ID письма в вашей системе.
251
- html?: string; // HTML письма.
252
- subject?: string; // Тема письма.
253
- preheader?: string; // Прехедер.
146
+ id?: string; // Unique email ID in your system.
147
+ html?: string;
148
+ subject?: string;
149
+ preheader?: string;
254
150
  }
255
151
  ```
256
152
 
257
- #### {object} шаблон, блоки, комментарии
153
+ #### `{object}` Template, blocks, comments
258
154
 
259
155
  ```javascript
260
156
  {
261
- templateId?: string | number; // ID шаблона в EmailMaker.
262
- email?: object; // параметры письма (см. выше).
263
- blocks?: []; // блоки.
264
- comments?: []; // комментарии к письму.
157
+ templateId?: string | number; // Template ID inside Blocks.
158
+ email?: object;
159
+ blocks?: [],
160
+ comments?: [],
265
161
  }
266
162
  ```
267
163
 
268
- Сменить контент после инициализации: **`instance.show(content)`**.
269
-
270
- ### Стили контента (`commonStyles`)
271
-
272
- Не путать с **`config`**: объект **`commonStyles`** передаётся **на верхнем уровне** **`init`** / **`reset`** (тип **`ExportedApi.AppConfigMixin.Options`**).
273
-
274
- - **Дефолт из сборки:** именованный экспорт **`COMMON_STYLES`** (см. исходник **`src/constants/commonStyles.defaults.ts`**, там же подробный **JSDoc** для IDE).
275
- - **Частичное переопределение:** можно передать только нужные ветки (например `{ block: { backgroundColor: '#000' } }`) — приложение **сливает** их с **`COMMON_STYLES`**, чтобы панель «Стили контента», iframe и список общих блоков не ломались на «дырах» в объекте.
276
- - **Приоритет:** сохранённое **`email.common_styles`** важнее, чем **`init.commonStyles`**.
277
- - **Сброс** сохранённого в сторе плагина override: **`commonStyles: undefined`** в **`reset`** или **`updateConfig`** (с ключом).
278
- - **Вкладка в UI:** флаг **`config.commonStylesEnabled`** (часто `true` по умолчанию).
279
-
280
- Полное описание: **`docs/plugin-content-styles.md`** в репозитории EmailMaker.
281
-
282
- ### config
283
-
284
- Настройки UI редактора. После **`init`** используйте **`instance.setConfig`**, **`instance.updateConfig`** и **`instance.getConfig`** — не методы объекта **`emailmaker`**.
285
-
286
- ##### Список параметров секции config
287
- | Параметр | Описание | Значение по умолчанию |
288
- | -------------------------------------- | --------------------------------------------------------------------------- | --------------------- |
289
- | theme | Тема плагина: light, dark. | light |
290
- | autosaveTimeout | Задержка перед автосохранением, мс. | 10000 |
291
- | mergeTags | JSON со списком динамических переменных. | undefined |
292
- | styles | Строка со стилями в формате CSS. | '' |
293
- | | | |
294
- | headerShow | Показ шапки. | true |
295
- | headerArrowBackVisible | Показ стрелки "Назад". | true |
296
- | headerTitleVisible | Показ поля "Тема". | true |
297
- | headerPreheaderVisible | Показ поля "Прехедер". | true |
298
- | historyEnabled | Показ кнопки "История версий". | true |
299
- | codeEnabled | Показ кнопки "Code-mode". | true |
300
- | codeModeDirection | Режим показа редактора кода по умолчанию | none|left|right|bottom|
301
- | codeSideEnabled | Показ кнопки "Code-mode" в режиме, когда есть переключатель десктоп/мобайл. | true |
302
- | previewIconEnabled | Показ кнопки "Предпросмотр". | true |
303
- | previewModeEnabled | Ссылка на Предпросмотр. | true |
304
- | livePreviewEnabled | Показ кнопки "Тестировние в почтовиках". | true |
305
- | sendTestEnabled | Показ кнопки "Отправить тест". | true |
306
- | sharePreviewEnabled | Показ кнопки "Поделиться". | true |
307
- | webversionEnabled | Показ ссылки на веб-версию. | true |
308
- | commonStylesEnabled | Показ стилей контента. | true |
309
- | emailResponsiveControlEnabled | Показ переключателя адаптивности письма. | true |
310
- | templateNotEmAlertShow | Показ уведомления о том, что шаблон не из EM. | true |
311
- | | | |
312
- | emailDropdownMenuEnabled | Показ меню письма. | true |
313
- | emailDropdownMenuClone | Показ пункта "Клонировать". | true |
314
- | emailDropdownMenuImport | Показ пункта "Импортировать". | true |
315
- | emailDropdownMenuImportButton | Показ пункта "Импортировать" кнопкой | true |
316
- | emailDropdownMenuLock | Показ пункта "Заблокировать". | true |
317
- | emailDropdownMenuRemove | Показ пункта "Удалить". | true |
318
- | | | |
319
- | emailExportEnabled | Показ кнопки "Экспорт". | true |
320
- | exportHtmlEnabled | Экспорт в HTML. | true |
321
- | exportZipEnabled | Экспорт в ZIP. | true |
322
- | exportClipboardEnabled | Экспорт в буфер. | true |
323
- | exportWebHookEnabled | Экспорт в вебхук. | true |
324
- | exportOutlookEnabled | Экспорт в Outlook. | true |
325
- | exportPdfEnabled | Экспорт в PDF. | true |
326
- | exportPngEnabled | Экспорт в PNG. | true |
327
- | | | |
328
- | nextButtonEnabled | Показ второстепенной кнопки. | false |
329
- | nextButtonText | Текст на второстепенной кнопке. | '' |
330
- | saveButtonEnabled | Показ основной кнопки. | true |
331
- | saveButtonText | Текст основной кнопки. | '' |
332
- | commandButtonsEnabled | Показ основной и второстепенной кнопки. | true |
333
- | | | |
334
- | sidePanelFloating | Плавающая боковая панель. | true |
335
- | desktopMobileSwitchRule | Полоса переключения режимов. | true |
336
- | desktopMobileSwitchPanel | Панель переключения режимов. | false |
337
- | onlyCodeModeInMobile | вывод в мобиле только кода. | false |
338
- | | | |
339
- | pathEnabled | Показ хлебных крошек. | true |
340
- | copyPasteEnabled | Показ копирования-вставки блока в iframe. | true |
341
- | saveBlockEnabled | Показ кнопки сохранения блока. | true |
342
- | editImageControlEnabled | Показ кнопки редактирования изображения. | true |
343
- | | | |
344
- | menuDirection | Расположение боковой панели. | 'right' |
345
- | defaultBuildPanel | Настройка открывающейся вкладки по умолчанию. | ''/'empty'/'project'/'common'/'template' |
346
- | commentsEnabled | Показ кнопки "Комментарии". | true |
347
- | aiAssistentEnabled | Показ "AI ассистента". | true |
348
- | optimizeEnabled | Показ кнопки "Оптимизация". | true |
349
- | optimizeLinksEnabled | Показ проверки ссылок. | true |
350
- | optimizeImagesEnabled | Показ проверки картинок. | true |
351
- | optimizeSpamAssassinEnabled | Показ проверки SpamAssassin. | true |
352
- | optimizeCheckCodeEnabled | Показ проверки кода. | true |
353
- | settingsEnabled | Показ кнопки "Настройки". | true |
354
- | UTMEnabled | Показ таба UTM-метки. | true |
355
- | descriptionEnabled | Показ поля "Описание" в настройках. | true |
356
- | tagsEnabled | Показ поля Теги в настройках. | true |
357
- | switchDesktopMobilePropsEnabled | Показ переключателя мобильных свойств. | true |
358
- | stepToOtherElementEnabled | Показ кнопок перехода к другим элементам. | true |
359
- | deleteButtonEnabled | Показ кнопки удаления элемента. | true |
360
- | toggleSidePanel | Возможность схлопывать боковую панель. | true |
361
- | blocksSectionsShow | Показ меню блоков. | true |
362
- | blocksEmptyEnabled | Показ пустых блоков. | true |
363
- | blocksSavedEnabled | Показ сохранённых блоков. | true |
364
- | blocksCommonEnabled | Показ общих блоков. | true |
365
- | blocksTemplateEnabled | Показ блоков шаблона. | true |
366
- | blocksSearchEnabled | Показ поиска по блокам. | true |
367
- | blocksAddPanelEnabled | Показ панели добавления блока в визуальном редакторе. | true |
368
- | imagePathDropdownEnabled | Показ выпадашки с путём к изображению. | true |
369
- | | | |
370
- | formFieldImageTitleEnabled | Показ поля title в форме картинки. | true |
371
- | formFieldBorderEnabled | Показ полей изменения рамки. | true |
372
- | formFieldBorderRadiusEnabled | Показ полей изменения скругления. | true |
373
- | formFieldBoxShadowEnabled | Показ полей изменения тени. | true |
374
- | formFieldVisibilityEnabled | Показ кнопок изменения видимости элемента. | true |
375
- | formFieldExportAsPictureEnabled | Показ переключателя экспорт в картинку. | true |
376
- | | | |
377
- | formButtonFieldInsertImageEnabled | Показ кнопки вставки изображения в текст у кнопки. | true |
378
- | formButtonFieldVerticalAlignEnabled | Показ кнопок вертикального выравнивания у кнопки. | true |
379
- | formButtonFieldTextAlignEnabled | Показ кнопок выравнивания текста у кнопки. | true |
380
- | formButtonFieldBackgroundImageEnabled | Показ полей фонового изображения у кнопки. | true |
381
- | formButtonFieldPaddingsEnabled | Показ полей внутренних отступов у кнопки. | true |
382
- | formButtonFieldReplacerEnabled | Показ реплейсера у кнопки. | true |
383
- | | | |
384
- | formCellFieldVerticalAlignEnabled | Показ кнопок вертикального выравнивания у ячейки. | true |
385
- | formCellFieldBackgroundImageEnabled | Показ полей фонового изображения у ячейки. | true |
386
- | formCellFieldPaddingsEnabled | Показ полей внутренних отступов у ячейки. | true |
387
- | formCellFieldSizeEnabled | Показ полей ширины и высоты. | true |
388
- | | | |
389
- | formImageFieldVerticalAlignEnabled | Показ кнопок вертикального выравнивания у картинки. | true |
390
- | formImageFieldReplacerEnabled | Показ кнопок вертикального выравнивания у картинки. | true |
391
- | formImageFieldHeightEnabled | Показ поля высоты у картинки. | true |
392
- | | | |
393
- | formTableFieldBackgroundImageEnabled | Показ полей фонового изображения у таблицы. | true |
394
- | formDivFieldBackgroundImageEnabled | Показ полей фонового изображения у контейнера. | true |
395
- | formEmailFieldBackgroundImageEnabled | Показ полей фонового изображения у письма. | true |
396
- | | | |
397
- | formTextFieldTypografEnabled | Показ кнопки типографа. | true |
398
- | formTextFieldReplacerEnabled | Показ кнопки реплейсера. | true |
399
- | | | |
400
- | elementImageEnabled | Элемент Картинка. | true |
401
- | elementTextEnabled | Элемент Текст. | true |
402
- | elementHeaderEnabled | Элемент Заголовок. | true |
403
- | elementButtonEnabled | Элемент Кнопка. | true |
404
- | elementListULEnabled | Элемент Список UL. | true |
405
- | elementListOLEnabled | Элемент Список OL. | true |
406
- | elementDividerEnabled | Элемент Разделитель. | true |
407
- | elementSpacerEnabled | Элемент Отступ. | true |
408
- | elementSocialEnabled | Элемент Соцсети | true |
409
- | elementTableEnabled | Элемент Таблица. | true |
410
- | elementCountdownEnabled | Элемент Счётчик. | true |
411
- | elementVideoEnabled | Элемент Видео. | true |
412
- | elementAIimageEnabled | Элемент AI картинка. | true |
413
- | elementAItextEnabled | Элемент AI текст. | true |
414
- | elementCarouselEnabled | Элемент AMP карусель. | true |
415
- | elementAccordionEnabled | Элемент AMP аккордион. | true |
416
- | elementFormEnabled | Элемент AMP форма. | true |
417
- | | | |
418
- | imageCenterLocalUploadEnabled | Поле загрузки файла с компьютера в Image Center. | true |
419
- | imageCenterStockEnabled | Таб Стока фотографий. | true |
420
- | imageCenterGifEnabled | Таб Стока гифок. | true |
421
- | imageCenterEditorEnabled | Таб редактора изображений. | true |
422
- | compressMaxSize | Макс. размер файла для клиентского сжатия в файловом менеджере, байт (по умолчанию порядка 5 MiB). | см. типы |
423
- | compressMaxWidthOrHeight | Макс. ширина/высота после ресайза, px (по умолчанию 2000). | см. типы |
424
-
425
- ### Обработка событий
426
-
427
- Обработчики передаются в **`init({ ... })`** или подписываются на экземпляре: **`instance.handle*(listener, priority?)`**. Подписка обычно возвращает **функцию отписки**. Обработчики могут быть **`async`**.
428
-
429
- События **`handleSaveEmail`**, **`handleSaveBlock`**, **`handleSaveComment`** получают **не сырой объект**, а **`SaveEventPayload`**: **`{ patch, value, prev?, source? }`** — полезно сравнивать **`patch`** и итоговое **`value`**.
430
-
431
- **`handleSubjectChanged`** и **`handlePreheaderChanged`** оформлены иначе: через них подписываются на строковые значения темы и прехедера — см. **`emailmaker.d.ts`**.
432
-
433
- #### Пример
164
+ After **`init`**, update with **`instance.show(content)`**.
165
+
166
+ ### Content styles (`commonStyles`)
167
+
168
+ Top-level **`init` / `reset`** option (not inside **`config`**). Shallow docs here — full reference: **`docs/plugin-content-styles.md`**.
169
+
170
+ - **`COMMON_STYLES`** named export — default preset for this product build.
171
+ - Partial overrides are deep-merged with **`COMMON_STYLES`** so UI panels stay consistent.
172
+ - Saved **`email.common_styles`** wins over **`init.commonStyles`** when present.
173
+ - Clear stored plugin override with **`commonStyles: undefined`** on **`reset`** / **`updateConfig`**.
174
+ - Show the sidebar tab via **`config.commonStylesEnabled`** (usually default **true**).
175
+
176
+ ### Config
177
+
178
+ Editor UI tuning. Use **`instance.setConfig`**, **`instance.updateConfig`**, **`instance.getConfig`** after **`init`** — **not** `useblocks.setConfig` / `useblocks.updateConfig`.
179
+
180
+ ##### Parameter list (`config`)
181
+
182
+ | Parameter | Description | Default |
183
+ | ---------------------- | --------------------------------- | ------- |
184
+ | theme | Plugin theme: light, dark. | light |
185
+ | autosaveTimeout | Delay before autosave, ms. | 10000 |
186
+ | mergeTags | JSON with the list of dynamic variables. | undefined |
187
+ | styles | String with styles in CSS format. | '' |
188
+ | | | |
189
+ | headerShow | Show header. | true |
190
+ | headerArrowBackVisible | Show “Back” arrow. | true |
191
+ | headerTitleVisible | Show “Subject” field. | true |
192
+ | headerPreheaderVisible | Show “Preheader” field. | true |
193
+ | historyEnabled | Show “Version history” button. | true |
194
+ | codeEnabled | Show “Code mode” button. | true |
195
+ | codeModeDirection | Default code editor display mode | none|left|right|bottom|
196
+ | codeSideEnabled | Show “Code mode” button when desktop/mobile toggle is available. | true |
197
+ | previewIconEnabled | Show “Preview” button. | true |
198
+ | previewModeEnabled | Link to Preview. | true |
199
+ | livePreviewEnabled | Show “Email client testing” button. | true |
200
+ | sendTestEnabled | Show “Send test” button. | true |
201
+ | sharePreviewEnabled | Show “Share” button. | true |
202
+ | webversionEnabled | Show link to web version. | true |
203
+ | commonStylesEnabled | Show content styles. | true |
204
+ | emailResponsiveControlEnabled | Show email responsiveness toggle. | true |
205
+ | templateNotEmAlertShow | Show alert that template is not from EM. | true |
206
+ | | | |
207
+ | emailDropdownMenuEnabled | Show email menu. | true |
208
+ | emailDropdownMenuClone | Show “Clone” item. | true |
209
+ | emailDropdownMenuImport | Show “Import” item. | true |
210
+ | emailDropdownMenuImportButton | Show “Import” as a button. | true |
211
+ | emailDropdownMenuLock | Show “Lock” item. | true |
212
+ | emailDropdownMenuRemove | Show “Delete” item. | true |
213
+ | | | |
214
+ | emailExportEnabled | Show “Export” button. | true |
215
+ | exportHtmlEnabled | Export to HTML. | true |
216
+ | exportZipEnabled | Export to ZIP. | true |
217
+ | exportClipboardEnabled | Export to clipboard. | true |
218
+ | exportWebHookEnabled | Export to webhook. | true |
219
+ | exportOutlookEnabled | Export to Outlook. | true |
220
+ | exportPdfEnabled | Export to PDF. | true |
221
+ | exportPngEnabled | Export to PNG. | true |
222
+ | | | |
223
+ | nextButtonEnabled | Show secondary button. | false |
224
+ | nextButtonText | Text on secondary button. | '' |
225
+ | saveButtonEnabled | Show primary button. | true |
226
+ | saveButtonText | Text on primary button. | '' |
227
+ | commandButtonsEnabled | Show primary and secondary buttons. | true |
228
+ | | | |
229
+ | sidePanelFloating | Floating side panel. | true |
230
+ | desktopMobileSwitchRule | Modes switch bar. | true |
231
+ | desktopMobileSwitchPanel | Modes switch panel. | false |
232
+ | onlyCodeModeInMobile | Show only code on mobile. | false |
233
+ | | | |
234
+ | pathEnabled | Show breadcrumbs. | true |
235
+ | copyPasteEnabled | Show copy–paste block in iframe. | true |
236
+ | saveBlockEnabled | Show save block button. | true |
237
+ | globalBlockCheckboxEnabled | “Global block” switch in Save block modal (off in bundled defaults — set **`true`** in plugin **`config`** to enable). | false |
238
+ | editImageControlEnabled | Show image editing button. | true |
239
+ | | | |
240
+ | menuDirection | Side panel position. | 'right' |
241
+ | defaultBuildPanel | Default opened tab setting. | ''/'empty'/'project'/'common'/'template' |
242
+ | commentsEnabled | Show “Comments” button. | true |
243
+ | aiAssistentEnabled | Show “AI assistant”. | true |
244
+ | optimizeEnabled | Show “Optimization” button. | true |
245
+ | optimizeLinksEnabled | Show links check. | true |
246
+ | optimizeImagesEnabled | Show images check. | true |
247
+ | optimizeSpamAssassinEnabled | Show SpamAssassin check. | true |
248
+ | optimizeCheckCodeEnabled | Show code check. | true |
249
+ | settingsEnabled | Show “Settings” button. | true |
250
+ | UTMEnabled | Show UTM tags tab. | true |
251
+ | descriptionEnabled | Show “Description” field in settings. | true |
252
+ | tagsEnabled | Show “Tags” field in settings. | true |
253
+ | switchDesktopMobilePropsEnabled | Show mobile properties toggle. | true |
254
+ | stepToOtherElementEnabled | Show buttons to jump to other elements. | true |
255
+ | deleteButtonEnabled | Show delete element button. | true |
256
+ | toggleSidePanel | Allow collapsing side panel. | true |
257
+ | blocksSectionsShow | Show blocks menu. | true |
258
+ | blocksEmptyEnabled | Show empty blocks. | true |
259
+ | blocksSavedEnabled | Show saved blocks. | true |
260
+ | blocksCommonEnabled | Show common blocks. | true |
261
+ | blocksTemplateEnabled | Show template blocks. | true |
262
+ | blocksSearchEnabled | Show blocks search. | true |
263
+ | blocksAddPanelEnabled | Show add block panel in visual editor. | true |
264
+ | imagePathDropdownEnabled | Show dropdown with image path. | true |
265
+ | | | |
266
+ | formFieldImageTitleEnabled | Show title field in image form. | true |
267
+ | formFieldBorderEnabled | Show border controls. | true |
268
+ | formFieldBorderRadiusEnabled | Show border radius controls. | true |
269
+ | formFieldBoxShadowEnabled | Show shadow controls. | true |
270
+ | formFieldVisibilityEnabled | Show element visibility controls. | true |
271
+ | formFieldExportAsPictureEnabled | Show “export as image” toggle. | true |
272
+ | | | |
273
+ | formButtonFieldInsertImageEnabled | Show “insert image into text” button for button. | true |
274
+ | formButtonFieldVerticalAlignEnabled | Show vertical alignment controls for button. | true |
275
+ | formButtonFieldTextAlignEnabled | Show text alignment controls for button. | true |
276
+ | formButtonFieldBackgroundImageEnabled | Show background image controls for button. | true |
277
+ | formButtonFieldPaddingsEnabled | Show padding controls for button. | true |
278
+ | formButtonFieldReplacerEnabled | Show replacer for button. | true |
279
+ | | | |
280
+ | formCellFieldVerticalAlignEnabled | Show vertical alignment controls for cell. | true |
281
+ | formCellFieldBackgroundImageEnabled | Show background image controls for cell. | true |
282
+ | formCellFieldPaddingsEnabled | Show padding controls for cell. | true |
283
+ | formCellFieldSizeEnabled | Show width and height controls. | true |
284
+ | | | |
285
+ | formImageFieldVerticalAlignEnabled | Show vertical alignment controls for image. | true |
286
+ | formImageFieldReplacerEnabled | Show replacer for image. | true |
287
+ | formImageFieldHeightEnabled | Show height field for image. | true |
288
+ | | | |
289
+ | formTableFieldBackgroundImageEnabled | Show background image controls for table. | true |
290
+ | formDivFieldBackgroundImageEnabled | Show background image controls for container. | true |
291
+ | formEmailFieldBackgroundImageEnabled | Show background image controls for email. | true |
292
+ | | | |
293
+ | formTextFieldTypografEnabled | Show typograph button. | true |
294
+ | formTextFieldReplacerEnabled | Show replacer button. | true |
295
+ | | | |
296
+ | elementImageEnabled | Element Image. | true |
297
+ | elementTextEnabled | Element Text. | true |
298
+ | elementHeaderEnabled | Element Heading. | true |
299
+ | elementButtonEnabled | Element Button. | true |
300
+ | elementListULEnabled | Element List UL. | true |
301
+ | elementListOLEnabled | Element List OL. | true |
302
+ | elementDividerEnabled | Element Divider. | true |
303
+ | elementSpacerEnabled | Element Spacer. | true |
304
+ | elementSocialEnabled | Element Social. | true |
305
+ | elementTableEnabled | Element Table. | true |
306
+ | elementCountdownEnabled | Element Countdown. | true |
307
+ | elementVideoEnabled | Element Video. | true |
308
+ | elementAIimageEnabled | Element AI image. | true |
309
+ | elementAItextEnabled | Element AI text. | true |
310
+ | elementCarouselEnabled | Element AMP carousel. | true |
311
+ | elementAccordionEnabled | Element AMP accordion. | true |
312
+ | elementFormEnabled | Element AMP form. | true |
313
+ | | | |
314
+ | imageCenterLocalUploadEnabled | Local file upload field in Image Center. | true |
315
+ | imageCenterStockEnabled | Stock photos tab. | true |
316
+ | imageCenterGifEnabled | Stock GIFs tab. | true |
317
+ | imageCenterEditorEnabled | Image editor tab. | true |
318
+ | compressMaxSize | Client-side compression max bytes in file manager (~5&nbsp;MiB default). | see types |
319
+ | compressMaxWidthOrHeight | Resize max width/height, px (2000 default). | see types |
320
+
321
+ ### Event wiring
322
+
323
+ Either pass callbacks to **`init`**, or call **`instance.handle*(listener, priority?)`** — typical pattern returns **unsubscribe** fn. Hooks may be **`async`**.
324
+
325
+ **Save** handlers (**`handleSaveEmail`**, **`handleSaveBlock`**, **`handleSaveComment`**) receive **`SaveEventPayload`**: **`{ patch, value, prev?, source? }`**.
326
+
327
+ Subject / preheader use different subscription signatures — inspect **`useblocks.d.ts`**.
434
328
 
435
329
  ```javascript
436
- emailmaker.init({
330
+ useblocks.init({
437
331
  element: '#test',
438
332
  content: { email: { id: '1' } },
439
333
  getAuthToken,
440
334
  handleReadEmail: async (id) => fetchEmail(id),
441
335
  handleSaveEmail: async (payload) => saveEmail(payload.value),
442
336
  }).then((instance) => {
443
- const unsubscribe = instance.handleEmailChanged(async () => {
444
- /* ... */
445
- });
337
+ const unsubscribe = instance.handleEmailChanged(async () => {});
446
338
  /* unsubscribe(); */
447
339
  });
448
340
  ```
449
341
 
450
- ### События
451
-
452
- | Обработчик | Описание |
453
- | ---------- | -------- |
454
- | handleReadEmail | Загрузка письма по id с вашего API (**аргумент — строка id**). |
455
- | handleSaveEmail | Сохранение письма; полезная нагрузка — **`SaveEventPayload`** с **`value`** и **`patch`**. |
456
- | handleRemoveEmail | Удаление письма. |
457
- | handleReadEmailRevisions | Список автосохранений / ревизий для письма. |
458
- | handleEmailAutosave | Создано автосохранение (**`EmailRevision`**). |
459
- | handleRemoveEmailAutoSave | Удалено автосохранение. |
460
- | handleReadBlocks | Список блоков проекта. |
461
- | handleReadCommonBlocks | Общие блоки. |
462
- | handleReadTemplateBlocks | Блоки шаблона в контексте письма. |
463
- | handleSaveBlock | Сохранение блока (**`SaveEventPayload`**). |
464
- | handleRemoveBlock | Удаление блока. |
465
- | handleReadComments | Комментарии к письму. |
466
- | handleSaveComment | Сохранение комментария. |
467
- | handleRemoveComment | Удаление комментария. |
468
- | handleSaveButtonClick | Клик по основной кнопке (например «Сохранить»). |
469
- | handleNextButtonClick | Клик по «Далее». |
470
- | handlePreviousButtonClick | Клик «Назад» в шапке. |
471
- | handleEmailInit | Инициализирован контур письма. |
472
- | handleEmailChanged | Изменился параметр письма. |
473
- | handleHtmlChanged | Изменился HTML-код. |
474
- | handleSubjectChanged | Изменилась тема (особая подпись — см. типы). |
475
- | handlePreheaderChanged | Изменился прехедер (особая подпись — см. типы). |
476
- | handleCloneEmail | Клонирование письма. |
477
- | handleShareEmail | Поделиться. |
478
- | handleLivePreviewEmail | Живой предпросмотр. |
479
- | handlePreviewEmail | Предпросмотр. |
480
- | handleValidate | Результат проверки кода (**`CodeError[]`**). |
481
- | handleTestEmailSend | Отправка тестового письма. |
482
- | handleTestEmailModal | Открыто окно тестовой отправки. |
483
- | handleDestroy | Перед уничтожением экземпляра. |
484
- | handleLoad | Завершена загрузка экземпляра; можно безопасно вызывать **`getEmail`** и др. |
485
- | handleLoadImage | Загрузка изображения пользователем; **`handleFileProxy`**, **`handleUrlProxy`** — прокси файлов/URL при необходимости. |
486
- | handleNotify | Произвольное уведомление. |
487
- | handleError | Ошибка (можно переопределить UI). |
488
- | handleSuccess | Успешная операция. |
489
- | handleReadLocale | Язык интерфейса (**`AppConfigMixin`**). |
490
- | handleTranslate | Пользовательский перевод строк. |
491
- | handleLimitUsage | Отображение квот / лимитов. |
492
-
493
- Полный перечень и сигнатуры — в **`emailmaker.d.ts`** (**`ExportedApi.DataMixin.Events`** и смежные миксины).
494
-
495
- ### Методы
496
-
497
- Модуль экспортирует **`init`** (и именованные символы в ESM). Остальное — методы **экземпляра** после **`await emailmaker.init(...)`**.
498
-
499
- | Метод | Описание |
500
- | ----- | -------- |
501
- | init | Асинхронная инициализация: **`Promise<Instance>`**. |
502
- | show | Подмена контента (**строка или объект `Content`**). |
503
- | save | Сохранить текущее письмо по цепочке приложения. |
504
- | getEmail | Текущее письмо; для скомпилированных полей см. **`compileEmail`** / **`CompiledEmail`**. |
505
- | compileEmail | Явная компиляция HTML/AMP/текста; опционально **`email`** и флаги форматов. |
506
- | setEmailMeta | Обновить **`meta`** текущего письма без полной замены. |
507
- | setBlockMeta | Обновить **`meta`** блока в кэше blocks DataSource по **`blockId`**. |
508
- | getBlocks | Блоки в текущем контексте (**`Block.meta`** round-trip при own-property). |
509
- | getComments | Комментарии. |
510
- | getEmailRevisions | Ревизии / автосохранения. |
511
- | getCodeErrors | Ошибки линтера кода в редакторе. |
512
- | getConfig | Текущий **`config`**. |
513
- | setConfig | Полная замена настроек UI. |
514
- | updateConfig | Глубокое слияние с текущим **`config`**. |
515
- | notify | Показать уведомление (строка или объект). |
516
- | getElement | DOM-узел или фрагмент монтирования. |
517
- | destroy | Уничтожить экземпляр (вызывайте при размонтировании в SPA). |
518
- | reset | Переинициализация с новыми **`Options`** (**`Promise<Instance>`**). |
519
- | undoRedoService | Сервис отмены/повтора (**`undo`**, **`redo`**, снимки истории и др.). |
520
-
521
- ### 📂 Файловый менеджер
522
-
523
- Для включения файлового менеджера необходимо в конфигурации инициализации указать параметры:
342
+ ### Events
343
+
344
+ See typings (**`ExportedApi.DataMixin.Events`**) — includes for example **`handleRemoveEmail`**, **`handleRemoveEmailAutoSave`**, **`handleReadCommonBlocks`**, **`handleReadTemplateBlocks`**, **`handleCloneEmail`**, **`handleShareEmail`**, **`handleLivePreviewEmail`**, **`handlePreviewEmail`**, **`handleValidate`**, **`handleSubjectChanged`**, **`handlePreheaderChanged`**, **`handleReadLocale`**, **`handleTranslate`**, **`handleLimitUsage`**, plus the rows below.
345
+
346
+ | Name | Summary |
347
+ | ------------------------- | ------------------------------------ |
348
+ | handleReadEmail | Load email by id (**string**) |
349
+ | handleSaveEmail | Persist email (**`SaveEventPayload`**) |
350
+ | handleReadEmailRevisions | Autosaves / revisions |
351
+ | handleEmailAutosave | Autosave created |
352
+ | handleReadBlocks | Project blocks |
353
+ | handleReadCommonBlocks | Shared / common blocks |
354
+ | handleReadTemplateBlocks | Template blocks for current email |
355
+ | handleSaveBlock | Save block (**`SaveEventPayload`**) |
356
+ | handleRemoveBlock | Delete block |
357
+ | handleReadComments | Email comments |
358
+ | handleSaveComment | Save comment |
359
+ | handleRemoveComment | Delete comment |
360
+ | handleSaveButtonClick | Toolbar primary click |
361
+ | handleNextButtonClick | “Next” click |
362
+ | handlePreviousButtonClick | “Back” click |
363
+ | handleEmailChanged | Email payload changed |
364
+ | handleHtmlChanged | HTML string changed |
365
+ | handleDestroy | Destroy lifecycle |
366
+ | handleLoad | Instance ready hook |
367
+ | handleLoadImage | Image upload helpers & proxies |
368
+ | handleNotify | Generic notification |
369
+ | handleError | Error toast hook |
370
+ | handleSuccess | Success toast hook |
371
+ | handleTestEmailSend | Send test mail |
372
+ | handleTestEmailModal | Test send modal opened |
373
+
374
+ ### Methods
375
+
376
+ Exports on the module bundle: **`init`**, **`parseAMP`**, etc. Everything else below lives on **`useblocks.init()`’s fulfilled instance**:
377
+
378
+ | Method | Notes |
379
+ | ------ | ----- |
380
+ | show | Swap email content (**`Content`**) |
381
+ | save | Trigger persistence pipeline |
382
+ | getEmail | Current **`CompiledEmail`** |
383
+ | compileEmail | Controlled compilation |
384
+ | setEmailMeta | Merge **`meta`** on the current email only |
385
+ | setBlockMeta | Merge or clear **`meta`** for a block by **`blockId`** (blocks cache) |
386
+ | getBlocks / getComments / getEmailRevisions | Data snapshots (**`Block.meta`** round-trip when the host sets own-property) |
387
+ | getCodeErrors | Linter output |
388
+ | getConfig / setConfig / updateConfig | UI config |
389
+ | notify | Push notification |
390
+ | getElement | Mount node |
391
+ | destroy | Teardown (call on SPA unmount) |
392
+ | reset | Re-init with new options |
393
+ | undoRedoService | Undo/redo API |
394
+
395
+ ## 📂 File Manager
524
396
 
525
397
  ```ts
526
- emailmaker.init({
527
- storageProvider: ..., // реализация интерфейса StorageProvider
398
+ useblocks.init({
399
+ storageProvider: /* StorageProvider implementation */,
528
400
  config: {
529
- imageCenterFileManagerView: true
530
- }
401
+ imageCenterFileManagerView: true,
402
+ },
531
403
  });
532
404
  ```
533
405
 
534
- Секция `fileManager` управляет возможностями файлового менеджера. Все поля необязательные; если не заданы или `false`, соответствующая функция отключена.
406
+ The `fileManager` section controls feature flags; every field is optional — default **true** when omitted unless noted in typings.
535
407
 
536
408
  #### Basic Operations
537
409
 
538
- - **enableTrash** — включает функциональность корзины для удаленных файлов. При включении файлы перемещаются в корзину вместо полного удаления. По умолчанию true
539
- - **enableRenameFolder** — разрешает переименование папок. По умолчанию true
540
- - **enableRenameFile** — разрешает переименование файлов. По умолчанию true
541
- - **enableUpdateFile** — разрешает обновление содержимого или метаданных файлов. По умолчанию true
542
- - **enableEdit** — разрешает редактирование файлов (изменение содержимого или свойств). По умолчанию true
543
- - **enableMoveFile** — разрешает перемещение файлов между папками. По умолчанию true
544
- - **enableMoveFolder** — разрешает перемещение папок. По умолчанию true
545
- - **enableCopyFile** — разрешает копирование файлов. По умолчанию true
546
- - **enableCopyFolder** — разрешает копирование папок. По умолчанию true
547
- - **enableDelete** — разрешает удаление файлов и папок. При включенной корзине файлы перемещаются в корзину. По умолчанию true
548
- - **multiSelect** — разрешает множественный выбор файлов и папок для групповых операций. По умолчанию true
549
- - **defaultFolderName** — Имя папки по умолчанию
550
- - **sortOptions** — белый список значений сортировки в дропдауне списка файлов (`'date-desc' \| 'date-asc' \| 'size-desc' \| 'size-asc' \| 'name-asc' \| 'name-desc' \| 'type-asc'`). Если не задан или массив пустой — доступны все варианты, которые отображает file-manager. Пример: `['date-desc', 'name-asc']` — скрыть сортировки по размеру и типу, если платформа их не реализует.
410
+ - **enableTrash** — enables trash functionality for deleted files. When enabled, files are moved to trash instead of permanent deletion. Default: true
411
+ - **enableRenameFolder** — allows renaming folders. Default is true
412
+ - **enableRenameFile** — allows renaming files. Default is true
413
+ - **enableUpdateFile** — allows updating file content or metadata. Default is true
414
+ - **enableEdit** — allows editing files (changing content or properties). Default is true
415
+ - **enableMoveFile** — allows moving files between folders. Default is true
416
+ - **enableMoveFolder** — allows moving folders. Default is true
417
+ - **enableCopyFile** — allows copying files. Default is true
418
+ - **enableCopyFolder** — allows copying folders. Default is true
419
+ - **enableDelete** — allows deleting files and folders. When the recycle bin is enabled, files are moved there instead of being permanently deleted. Default is true
420
+ - **multiSelect** — allows multiple selection of files and folders for batch operations. Default is true
421
+ - **defaultFolderName** — default folder name
422
+ - **sortOptions** — whitelist of sort dropdown values (`'date-desc' \| 'date-asc' \| 'size-desc' \| 'size-asc' \| 'name-asc' \| 'name-desc' \| 'type-asc'`). If omitted or empty, all options supported by the file-manager package are shown. Use a non-empty array to hide sorts your platform does not implement (e.g. size or type).
551
423
 
552
424
  #### Pagination & Display
553
425
 
554
- - **enablePagination** — разрешает постраничную навигацию. Если отключено, все элементы загружаются сразу. По умолчанию true
426
+ - **enablePagination** — enables paginated navigation. If disabled, all items are loaded at once. Default: true
555
427
 
556
428
  #### Client-Side Processing
557
429
 
558
- - **clientSideSorting** — клиентская сортировка файлов.
559
- - Если `true`, применяется стандартная сортировка (по имени по возрастанию).
560
- - Если указана функция, она принимает текущий массив файлов, необязательные `sortBy` и `sortOrder`, и возвращает отсортированный массив.
430
+ - **clientSideSorting** — client-side file sorting.
431
+ - If `true`, applies standard sorting (by name ascending).
432
+ - If a function is provided, it receives the current file array, optional `sortBy` and `sortOrder`, and returns a sorted array.
561
433
 
562
- - **clientSidePaging** — клиентская пагинация файлов.
563
- - Если `true`, применяется стандартная нарезка массива по `page` и `limit`.
564
- - Если указана функция, она принимает массив файлов, `page` и `limit`, и возвращает массив только для нужной страницы.
434
+ - **clientSidePaging** — client-side file pagination.
435
+ - If `true`, applies standard array slicing based on `page` and `limit`.
436
+ - If a function is provided, it receives the file array, `page` and `limit`, and returns an array for the specific page only.
565
437
 
566
- - **clientSideFilter** — клиентская фильтрация файлов.
567
- - Если `true`, применяется стандартная фильтрация по тексту `search`.
568
- - Если указана функция, она принимает массив файлов и необязательный `search`, и возвращает отфильтрованный массив.
438
+ - **clientSideFilter** — client-side file filtering.
439
+ - If `true`, applies standard filtering by `search` text.
440
+ - If a function is provided, it receives the file array and optional `search`, and returns a filtered array.
569
441
 
570
442
  #### Cache Strategy
571
443
 
572
- - **cacheStrategy** — стратегия кэширования для оптимизации производительности.
573
- - **ttl** — время жизни кэша в миллисекундах. По умолчанию 300000 (5 минут)
574
- - **errorTtl** — время жизни кэша для ошибок в миллисекундах. По умолчанию 60000 (1 минута)
575
- - **allowSortedInsert** — разрешает вставку элемента в отсортированный массив без полной инвалидации кэша. По умолчанию false
576
- - **allowSearchInsert** — разрешает вставку элемента в массив с фильтрами без полной инвалидации кэша. По умолчанию false
577
- - **invalidateOnPaginationFull** — если страница полная, кэш помечается как устаревший при вставке нового элемента. По умолчанию true
578
- - **comparator** — функция сравнения двух файлов для сортировки. По умолчанию сравнение по имени
579
- - **filterMatch** — функция проверки, проходит ли файл текущий фильтр. По умолчанию поиск по имени
580
-
581
- ### Интерфейс `StorageProvider`
582
-
583
- #### Свойства
584
-
585
- | Свойство | Тип | Описание | По умолчанию |
586
- | --------------------------- | --------- | ----------------------------------------------------------- | ------------ |
587
- | `pathMode` | `boolean` | Использовать путь как идентификатор для папок | - |
588
- | `rootId` | `string` | Пользовательский идентификатор корневой папки | `''` |
589
- | `trashPath` | `string` | Путь к корзине/папке для удаленных файлов | - |
590
- | `tempPath` | `string` | Путь к временной папке для загрузок | - |
591
- | `useSoftDelete` | `boolean` | Включить программное мягкое удаление | `false` |
592
- | `ensureFolderTrailingSlash` | `boolean` | Добавлять к путям папок завершающий слэш | `true` |
593
- | `validateDuplicates` | `boolean` | Проверка на существование при операциях с файлами и папками | - |
594
-
595
- #### Методы
596
-
597
- ##### Основные методы
598
-
599
- | Метод | Параметры | Возвращает | Описание |
600
- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
601
- | **getItems** | `options`:<br>- `folderId?: string`<br>- `search?: string`<br>- `sortBy?: string`<br>- `sortOrder?: 'asc'\|'desc'`<br>- `page?: number`<br>- `limit?: number`<br>- `itemType: 'all'\|'file'\|'folder'` | `{ items: FileSystemItem[], pagination?: Partial<ApiPaginationResponse> }` | Получить список файлов и папок с фильтрацией, сортировкой, пагинацией |
602
- | **createFolder** | `name: string`, `parentid?: string` | `FileSystemItem` | Создать новую папку |
603
- | uploadFile | `file`: <br>- `name: string`<br>- `size: number`<br>- `type: string`<br>- `folderId?: string`<br>- `data: Blob \| string`<br>- `thumbnail?: string`<br>- `dimensions?: string`<br>- `aspectRatio?: string`<br>- `extension?: string` | `FileSystemItemUpdate` | Загрузить файл с метаданными |
604
- | uploadFiles | `request`:<br>- `items`: массив объектов:<br>&nbsp;&nbsp;&nbsp;&nbsp;- `requestId?: string` — необязательный идентификатор для сопоставления результата<br>&nbsp;&nbsp;&nbsp;&nbsp;- `name: string` — имя файла<br>&nbsp;&nbsp;&nbsp;&nbsp;- `size: number` — размер файла в байтах<br>&nbsp;&nbsp;&nbsp;&nbsp;- `type: string` — MIME-тип файла<br>&nbsp;&nbsp;&nbsp;&nbsp;- `folderId?: string \| null` — целевая папка<br>&nbsp;&nbsp;&nbsp;&nbsp;- `data: Blob \| string` — содержимое файла<br>&nbsp;&nbsp;&nbsp;&nbsp;- `extension?: string` — расширение файла<br>- `folderId?: string \| null` — папка для загрузки по умолчанию | `BatchResult<UploadFileResultData>` | Загрузить несколько файлов. Порядок элементов важен — при отсутствии `requestId` результаты сопоставляются по индексу |
605
- | **uploadFileByUrl** | `url: string`, `folderId?: string` | `FileSystemItem` | Загрузить файл по URL (проверять существующие файлы) |
606
- | `findItemByPath` | `path: string` | `FileSystemItem \| undefined` | Найти системные файлы/папки по пути |
607
- | `setController` | `controller: StorageProviderController` | `void` | Установить контроллер управления кэшем |
608
- | `getFileData` | `file: FileSystemItem` | `Blob` | Получить содержимое файла как blob |
609
- | `getUrl` | `file: FileSystemItem` | `string` | Получить URL для доступа к файлу |
610
- | `getThumbnailUrl` | `file: FileSystemItem` | `string` | Получить URL миниатюры |
611
- | `renameItem` | `item: FileSystemItem`, `newName: string` | `FileSystemItemUpdate` | Переименовать файл/папку |
612
- | `deleteItem` | `item: FileSystemItem` | `void` | Удалить один элемент (перемещает в корзину при мягком удалении) |
613
- | `deleteItems` | `items: FileSystemItem[]` | `BatchResult<never>` | Удалить несколько элементов |
614
- | `moveItem` | `item: FileSystemItem`, `targetFolderId?: string` | `FileSystemItemUpdate` | Переместить один элемент |
615
- | `moveItems` | `items: FileSystemItem[]`, `targetFolderId?: string` | `BatchResult<FileSystemItemUpdate>` | Переместить несколько элементов |
616
- | `copyItem` | `item: FileSystemItem`, `targetFolderId?: string` | `FileSystemItemUpdate` | Копировать один элемент |
617
- | `copyItems` | `items: FileSystemItem[]`, `targetFolderId?: string` | `BatchResult<FileSystemItemUpdate>` | Копировать несколько элементов |
618
- | `updateFile` | `file: FileSystemItem`, `updates`: объект с метаданными | `FileSystemItemUpdate` | Обновить метаданные/содержимое файла |
619
-
620
- ##### Определения типов
444
+ - **cacheStrategy** — caching strategy for performance optimization.
445
+ - **ttl** — cache time-to-live in milliseconds. Default: 300000 (5 minutes)
446
+ - **errorTtl** — cache TTL for errors in milliseconds. Default: 60000 (1 minute)
447
+ - **allowSortedInsert** — allows inserting elements into sorted arrays without full cache invalidation. Default: false
448
+ - **allowSearchInsert** — allows inserting elements into filtered arrays without full cache invalidation. Default: false
449
+ - **invalidateOnPaginationFull** — marks cache as stale when inserting into a full paginated page. Default: true
450
+ - **comparator** — comparison function for sorting two files. Default: name-based comparison
451
+ - **filterMatch** — function to check if a file passes current filters. Default: name-based search
452
+
453
+ ### Interface StorageProvider
454
+
455
+ #### Properties
456
+
457
+ | Property | Type | Description | Default |
458
+ | --------------------------- | --------- | ----------------------------------------------- | ------- |
459
+ | `pathMode` | `boolean` | Use path as identifier for folders | - |
460
+ | `rootId` | `string` | Custom identifier for root folder | `''` |
461
+ | `trashPath` | `string` | Path to trash/recycle bin folder | - |
462
+ | `tempPath` | `string` | Path to temporary folder for uploads | - |
463
+ | `useSoftDelete` | `boolean` | Enable client-side soft delete | `false` |
464
+ | `ensureFolderTrailingSlash` | boolean | Add a trailing slash to folder paths | `true` |
465
+ | `validateDuplicates` | `boolean` | Client-side check for existing files or folders | - |
466
+
467
+ #### Methods
468
+
469
+ ##### Core Methods
470
+
471
+ | Method | Parameters | Returns | Description |
472
+ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
473
+ | **getItems** | `options`:<br>- `folderId?: string`<br>- `search?: string`<br>- `sortBy?: string`<br>- `sortOrder?: 'asc'\|'desc'`<br>- `page?: number`<br>- `limit?: number`<br>- `itemType: 'all'\|'file'\|'folder'` | `{ items: FileSystemItem[], pagination?: Partial<ApiPaginationResponse> }` | Retrieve files/folders with filtering, sorting, pagination |
474
+ | **createFolder** | `name: string`, `parentid?: string` | `FileSystemItem` | Create new folder |
475
+ | uploadFile | `file`: <br>- `name: string`<br>- `size: number`<br>- `type: string`<br>- `folderId?: string`<br>- `data: Blob \| string`<br>- `thumbnail?: string`<br>- `dimensions?: string`<br>- `aspectRatio?: string`<br>- `extension?: string` | `FileSystemItemUpdate` | Upload file with metadata |
476
+ | uploadFiles | `request`:<br>- `items: { requestId?: string, name: string, size: number, type: string, folderId?: string \| null, data: Blob \| string, extension?: string }[]`<br>- `folderId?: string \| null` | `BatchResult<UploadFileResultData>` | Upload multiple files. The order of items matters — if `requestId` is not provided, results are matched by index |
477
+ | **uploadFileByUrl** | `url: string`, `folderId?: string` | `FileSystemItem` | Upload file from URL (check for existing files) |
478
+ | `findItemByPath` | `path: string` | `FileSystemItem \| undefined` | Find system files/folders by path |
479
+ | `setController` | `controller: StorageProviderController` | `void` | Set cache management controller |
480
+ | `getFileData` | `file: FileSystemItem` | `Blob` | Get file content as blob |
481
+ | `getUrl` | `file: FileSystemItem` | `string` | Get file access URL |
482
+ | `getThumbnailUrl` | `file: FileSystemItem` | `string` | Get thumbnail URL |
483
+ | `renameItem` | `item: FileSystemItem`, `newName: string` | `FileSystemItemUpdate` | Rename file/folder |
484
+ | `deleteItem` | `item: FileSystemItem` | `void` | Delete single item (moves to trash if soft delete enabled) |
485
+ | `deleteItems` | `items: FileSystemItem[]` | `BatchResult<never>` | Delete multiple items |
486
+ | `moveItem` | `item: FileSystemItem`, `targetFolderId?: string` | `FileSystemItemUpdate` | Move single item |
487
+ | `moveItems` | `items: FileSystemItem[]`, `targetFolderId?: string` | `BatchResult<FileSystemItemUpdate>` | Move multiple items |
488
+ | `copyItem` | `item: FileSystemItem`, `targetFolderId?: string` | `FileSystemItemUpdate` | Copy single item |
489
+ | `copyItems` | `items: FileSystemItem[]`, `targetFolderId?: string` | `BatchResult<FileSystemItemUpdate>` | Copy multiple items |
490
+ | `updateFile` | `file: FileSystemItem`, `updates`: metadata object | `FileSystemItemUpdate` | Update file metadata/content |
491
+
492
+ ##### Type Definitions
621
493
 
622
494
  - **`MayBePromise<T>`**: `T | Promise<T>`
623
- - **`FileSystemItem`**: Объект файла или папки
624
- - **`FileSystemItemUpdate`**: Элемент с измененными полями
625
- - **`BatchResult<T>`**: Результат с деталями успеха/ошибки
626
- - **`ApiPaginationResponse`**: Метаданные пагинации
627
-
628
- ##### Важные примечания
629
-
630
- - **Мягкое удаление**: Когда `useSoftDelete=true`, операции удаления перемещают элементы в `trashPath`
631
- - **Корневая папка**: Используйте `rootId` или пустую строку для операций с корневой папкой
632
- - **Разрешение путей**: `trashPath` и `tempPath` преобразуются в реальные идентификаторы папок
633
- - **Загрузка по URL**: Должна проверять, существует ли файл уже на текущем сервере
634
- - **Управление кэшем**: Используйте `setController` для запросов инвалидации кэша
635
- - **Двойное мягкое удаление**: Если бэкенд уже реализует мягкое удаление, оставьте `useSoftDelete=false`
495
+ - **`FileSystemItem`**: File or folder object
496
+ - **`FileSystemItemUpdate`**: Item with changed fields
497
+ - **`BatchResult<T>`**: Result with success/failure details
498
+ - **`ApiPaginationResponse`**: Pagination metadata
499
+
500
+ ##### Important Notes
501
+
502
+ - **Soft Delete**: When `useSoftDelete=true`, delete operations move items to `trashPath`
503
+ - **Root Folder**: Use `rootId` or empty string for root operations
504
+ - **Path Resolution**: `trashPath` and `tempPath` are resolved to actual folder IDs
505
+ - **URL Upload**: Should check if file already exists on current server
506
+ - **Cache Control**: Use `setController` for cache invalidation requests
507
+ - **Double soft delete**: If your backend already implements soft delete, keep `useSoftDelete=false`