grapesjs-forms 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,62 @@
1
+ # grapesjs-forms — устройство
2
+
3
+ ## Идея
4
+
5
+ Форма — это **данные** (схема), а не дизайн. Схема живёт в хранилище форм (REST / IndexedDB / память),
6
+ редактируется в отдельном редакторе (модальное окно) и **собирается** в компонент GrapesJS из обычных
7
+ HTML-элементов со стабильными классами. Поэтому:
8
+
9
+ - форма выглядит как сайт: её стилизует CSS проекта (Style Manager), классы общие для всех форм;
10
+ - изменение схемы пересобирает все вставки формы в открытом проекте, свои классы/атрибуты `<form>` остаются;
11
+ - сервер проверяет заявку по той же схеме (`validateSubmission`), без DOM.
12
+
13
+ SurveyJS рассматривался как основа: раннер (survey-core, MIT) рисует свою разметку и темы — это
14
+ противоречит требованию «дизайн из страниц», а визуальный Creator — коммерческий. Поэтому своя
15
+ простая схема + импорт/экспорт SurveyJS JSON для того, что является обычной формой.
16
+
17
+ ## Модули
18
+
19
+ | файл | что делает |
20
+ |---|---|
21
+ | `schema.ts` | типы полей, `normalizeForm/Field/Options/Settings`, `cleanAttrs` (без `on*`, `javascript:`, служебных имён), `validateSubmission` (коды как в 422) |
22
+ | `placeholders.ts` | `{{…}}`: `resolveBuild` (form.*, page.* — при сборке), список для подсказок |
23
+ | `build.ts` | схема → дерево `El` → HTML (`formHtml`) или компоненты; `formAttrs` (action, тексты, коды ошибок, версия, страница) |
24
+ | `runtime/script.ts` | поведение формы на сайте. **Самодостаточная функция**: GrapesJS копирует её текст в `getJs()` (`script` + `script-props`), поэтому без импортов и внешних переменных. Тест `runtime.test.ts` исполняет её из исходного текста, `export.test.ts` — экспорт целиком |
25
+ | `runtime/index.ts` | `enhanceForms()` для HTML без GrapesJS; отдельная сборка `dist/runtime(.iife).js` |
26
+ | `editor/FormComponents.ts` | типы `gjsf-form` (`formId`, трейты, скрипт) и `gjsf-part` (части: стилизуются, но не двигаются/не удаляются); пересборка вне undo; защита холста от реальной отправки; служебное правило `.gjsf-hp` |
27
+ | `store/*` | `FormStore`: `MemoryFormStore` (проверяет заявки как сервер), `IndexedDbFormStore` (поверх Memory, запись по ключам `form:` / `submission:`), `RestFormStore` (openapi.yaml, snake_case, If-Match, multipart для файлов) |
28
+ | `surveyjs.ts` | `fromSurveyJs` / `toSurveyJs` |
29
+ | `ui/FormEditor.ts` | модальный редактор: список форм; вкладки Поля / Настройки / Просмотр / Заявки / JSON |
30
+ | `plugin.ts` | сборка всего: кэш форм, отложенная запись с версиями, блоки, команды, API `editor.Forms`, связь с grapesjs-pages, контракт плагинов |
31
+
32
+ ## Потоки
33
+
34
+ **Правка.** UI меняет свою копию формы → `change(form)` → кэш обновляется сразу (имя в блоках/трейтах),
35
+ запись в хранилище через `autosaveDelay` с `If-Match` = последняя сохранённая версия. 412 → форма
36
+ перечитывается, UI показывает конфликт. После записи — `rebuildAll(id)`.
37
+
38
+ **Пересборка компонента.** Удаляются атрибуты, которые плагин писал (`OWN_ATTRS` + прежние `attrs`
39
+ формы из `gjsfOwnAttrs`), пишутся новые, части заменяются. Ключ `gjsfKey` (хранится в компоненте) делает
40
+ `id` полей уникальными, если форма стоит на странице дважды. Инлайн-стили не используются (иначе
41
+ GrapesJS плодил бы правила `#id{}` при каждой пересборке).
42
+
43
+ **Загрузка проекта / открытие страницы pages.** `refreshStale`: пересобираются компоненты, у которых
44
+ `data-gjsf-version` ≠ версии формы, страница (`data-gjsf-page`) другая или форма была помечена удалённой.
45
+
46
+ **Отправка на сайте.** Скрипт: плейсхолдеры → проверка браузера + «хотя бы один» для обязательных
47
+ групп флажков → событие `gjsf:submit` (слушатель может сам отправить через `detail.promise` — так работает
48
+ превью редактора) → `fetch(action)` JSON `{data, meta}` (с файлами — multipart + `_meta`) → 2xx: сообщение
49
+ / redirect / сброс; 422: ошибки под полями (коды → тексты из `data-gjsf-codes`).
50
+
51
+ ## grapesjs-pages
52
+
53
+ Без жёсткой зависимости: читается `editor.PagesManager` и событие `pages-manager:open`. Запись страницы
54
+ даёт `{{page.*}}` при сборке и `meta.page_id`. Как и связанные компоненты pages, опубликованные страницы
55
+ содержат копию формы на момент публикации (сервер всё равно проверяет по актуальной схеме).
56
+
57
+ ## Открыто
58
+
59
+ - Локали: en, ru, uk (у остальных плагинов семьи — 23).
60
+ - Условная логика (показывать поле, если…), многошаговые формы, капча (кроме honeypot).
61
+ - Серверная часть — не в этом пакете: плагин только отправляет на endpoint; приём реализуется в микросервисе по `openapi.yaml`.
62
+ - Локальные хранилища (Memory/IndexedDB) не хранят содержимое файлов — только `{ name, size, type }`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alexander Shibisty
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,204 @@
1
- # Temporary Holding Version
1
+ # grapesjs-forms
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A GrapesJS plugin for forms made in **an editor of their own**: field types, options, placeholders,
4
+ attributes, hidden fields with values (`{{query.utm_source}}`, `{{page.slug}}`…). A form becomes a
5
+ **component** you drop on any page; it is built of plain HTML elements with stable classes, so it
6
+ **looks like the site** — the page's CSS (made in the Style Manager like anything else) styles it.
7
+ What visitors send goes to **your API** (`openapi.yaml`), or to IndexedDB / memory while you try it.
8
+
9
+ - 18 input types (text, e-mail, phone, URL, number, password, long text, dropdown, radio buttons,
10
+ checkbox, checkboxes, date, time, date and time, slider, colour, file, hidden) + heading and paragraph
11
+ - per field: label, key, placeholder, help, required, default value, options, min / max / step,
12
+ min / max length, pattern, accept, autocomplete, rows, read only, disabled, width (1/2, 1/3…), any attributes
13
+ - per form: endpoint, button text, success / error message, redirect, reset, spam trap (honeypot), form attributes
14
+ - preview with the open page's styles (sends to the store), submissions table with CSV, JSON view
15
+ - **SurveyJS** JSON import / export (`fromSurveyJs`, `toSurveyJs`) for the plain-form parts of a survey
16
+ - the site side is a few KB with no dependencies; servers get `validateSubmission()` with the same rules
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install grapesjs-forms
22
+ ```
23
+
24
+ ```js
25
+ import grapesjs from 'grapesjs';
26
+ import forms from 'grapesjs-forms';
27
+
28
+ grapesjs.init({
29
+ container: '#gjs',
30
+ plugins: [forms],
31
+ pluginsOpts: {
32
+ [forms.meta.id]: {
33
+ rest: { url: '/api/forms' }, // admin API (openapi.yaml); omit → IndexedDB
34
+ // submitUrl: 'https://api.site.com', // where the published site posts; default rest.url
35
+ },
36
+ },
37
+ });
38
+ ```
39
+
40
+ Or with `<script>`: `grapesjs-forms.umd.js` registers itself as `grapesjs-forms`
41
+ (`plugins: ['grapesjs-forms']`, `pluginsOpts: { 'grapesjs-forms': {…} }`).
42
+
43
+ ## How it works
44
+
45
+ 1. **Forms** (button in the *options* panel, or `editor.runCommand('forms:open')`) — the editor:
46
+ forms on the left; *Fields* (types → list → properties), *Settings*, *Preview*, *Submissions*, *JSON*.
47
+ Edits are saved after a short pause (`autosaveDelay`).
48
+ 2. **Blocks → Forms**: one block per form, and *New form* (creates one and opens the editor).
49
+ A form component has a *Form* trait (switch the form) and *Edit the form*; double-click opens the editor too.
50
+ 3. Inside, the parts are made by the plugin: they can be selected and **styled**, not moved or deleted.
51
+ Every part is its own layer (field → label, input, help, error; options; the button), and each has
52
+ a stable id made from the form component, the field and the part (`gjsf-k3x9a-email-label`), so
53
+ styles given to one part in GrapesJS (`#…` rules) stay with it when the form is edited or rebuilt.
54
+ When the form changes, every component of it in the open project is rebuilt (not on the undo stack);
55
+ the classes and attributes you added to the `<form>` stay. A project opened later with an older copy
56
+ is brought up to date. A deleted form leaves its copy, marked.
57
+ 4. The exported page has the form's HTML and its script (GrapesJS' `getJs()`): it fills placeholders,
58
+ checks, posts, shows the server's per-field errors and the message (or redirects).
59
+
60
+ ### Design
61
+
62
+ The site's CSS styles the forms. Classes:
63
+
64
+ | class | element |
65
+ |---|---|
66
+ | `.gjsf-form` | `<form>` (add your own class for a look of its own) |
67
+ | `.gjsf-field`, `.gjsf-field--<type>`, `.gjsf-w-1-2`… | a field's wrapper (`fieldset` for radio / checkboxes); `.is-required`, `.has-error` |
68
+ | `.gjsf-label`, `.gjsf-req` | label / legend, the `*` |
69
+ | `.gjsf-input` | input, textarea, select |
70
+ | `.gjsf-options`, `.gjsf-option`, `.gjsf-check`, `.gjsf-option-label` | choices |
71
+ | `.gjsf-help`, `.gjsf-error` | help line, error line |
72
+ | `.gjsf-heading`, `.gjsf-text` | heading, paragraph |
73
+ | `.gjsf-actions`, `.gjsf-submit` | the button row and the button (keeps the site's `button` look) |
74
+ | `.gjsf-message` | the message after sending; the form gets `.is-sending`, `.is-success`, `.is-error` |
75
+
76
+ `baseCss: true` (default) writes a small base sheet into the project CSS once — it inherits fonts
77
+ and colours; restyle or delete it freely. The honeypot rule (`.gjsf-hp`) is always added.
78
+
79
+ ### Placeholders
80
+
81
+ In a field's value (above all a hidden one):
82
+
83
+ | | |
84
+ |---|---|
85
+ | `{{form.id}}`, `{{form.name}}` | filled when the page is built |
86
+ | `{{page.id}}`, `{{page.name}}`, `{{page.slug}}`… | the open page of [grapesjs-site-pages](https://www.npmjs.com/package/grapesjs-site-pages) (any record field); without it the browser gives `path` / `title` |
87
+ | `{{url}}`, `{{path}}`, `{{host}}`, `{{referrer}}`, `{{title}}`, `{{lang}}` | the visitor's browser |
88
+ | `{{query.utm_source}}`, `{{cookie.name}}`, `{{storage.key}}` | query string, cookie, localStorage |
89
+ | `{{date}}`, `{{time}}`, `{{datetime}}`, `{{timestamp}}`, `{{uuid}}` | now; a random id |
90
+
91
+ Hidden fields are filled again on every submit; visible ones once (the visitor may change them).
92
+
93
+ ## Backend
94
+
95
+ `openapi.yaml` describes what the plugin calls and what it expects back:
96
+
97
+ | | |
98
+ |---|---|
99
+ | `GET /forms`, `GET/PUT/DELETE /forms/{id}` | the editor (admin); `PUT` with `If-Match` → 412 on a newer version |
100
+ | `POST /forms/{id}/submissions` | **the site** (public): `{ data, meta }` JSON, or multipart with files (`_meta`) |
101
+ | `GET /forms/{id}/submissions?limit&offset`, `DELETE …/{sid}` | the *Submissions* tab |
102
+
103
+ Answer 422 `{ error, errors: { field: ['required'] } }` to show errors under fields (codes become the
104
+ form's texts in the visitor's language; plain messages are shown as they are). A 201 may carry
105
+ `message` or `redirect`. Validate with the same rules as the editor:
106
+
107
+ ```js
108
+ import { validateSubmission } from 'grapesjs-forms'; // no DOM needed (Node, workers)
109
+ const r = validateSubmission(form, body.data); // { ok, errors, data (cleaned), spam }
110
+ ```
111
+
112
+ The server side is yours (e.g. a microservice): this package only posts to the endpoint and reads the answer.
113
+
114
+ ### Stores
115
+
116
+ ```js
117
+ import { RestFormStore, IndexedDbFormStore, MemoryFormStore } from 'grapesjs-forms';
118
+ forms(editor, { store: new RestFormStore({ url: '/api/forms', headers: () => ({ 'X-CSRF-TOKEN': token }), credentials: 'include' }) });
119
+ ```
120
+
121
+ Or your own: `listForms`, `getForm`, `saveForm(form, ifVersion)`, `deleteForm`, `submit(formId, data, meta)`,
122
+ and optionally `listSubmissions`, `deleteSubmission`. IndexedDB keeps the editor's own submissions (the
123
+ preview); a published site cannot reach it — give it a `submitUrl` / REST backend, or handle
124
+ `gjsf:submit` yourself:
125
+
126
+ ```js
127
+ form.addEventListener('gjsf:submit', (e) => {
128
+ e.detail.promise = myApi.send(e.detail.data); // resolve → success; reject { status, body: { error, errors } } → errors
129
+ });
130
+ ```
131
+
132
+ ### Forms without GrapesJS on the page
133
+
134
+ ```js
135
+ const html = editor.Forms.html(formId); // or formHtml(form, { action }) on a server
136
+ ```
137
+ ```html
138
+ <script type="module">import { enhanceForms } from 'grapesjs-forms/runtime'; enhanceForms();</script>
139
+ <!-- or dist/runtime.iife.js → gjsfRuntime.enhanceForms() -->
140
+ ```
141
+
142
+ ## SurveyJS
143
+
144
+ `fromSurveyJs(json)` takes text inputs (every `inputType`), comment, dropdown, tagbox, radiogroup,
145
+ checkbox, boolean, rating, file, html; panels and pages are flattened, invisible text questions become
146
+ hidden fields. Logic (visibleIf, expressions, matrices…) has no place in a plain HTML form: such
147
+ questions are listed in `skipped`. Paste a survey into the *JSON* tab, or:
148
+
149
+ ```js
150
+ const { form, skipped } = await editor.Forms.importSurveyJs(surveyJson);
151
+ const survey = editor.Forms.exportSurveyJs(form.id);
152
+ ```
153
+
154
+ The SurveyJS runner itself is not used: it renders its own markup and themes, while these forms take
155
+ the site's design.
156
+
157
+ ## API — `editor.Forms`
158
+
159
+ ```ts
160
+ list(), get(id), reload()
161
+ create(init?), update(id, patch), remove(id), duplicate(id), flush()
162
+ open(id?), close()
163
+ actionOf(form | id) // where it posts on the site
164
+ html(id, opts?) // the form as HTML
165
+ submit(id, data, meta?) // through the store
166
+ rebuild(id?) // components in the open project
167
+ importSurveyJs(json, into?), exportSurveyJs(id)
168
+ ```
169
+
170
+ Events: `forms:list`, `forms:saved`, `forms:removed`, `forms:submitted`.
171
+ Commands: `forms:open` (`{ id }`), `forms:edit` (`{ component }`).
172
+ Site (on the `<form>`): `gjsf:submit` (cancelable, `detail.promise`), `gjsf:success`, `gjsf:error`.
173
+
174
+ ## Options
175
+
176
+ | option | default | |
177
+ |---|---|---|
178
+ | `store` | — | your backend (wins) |
179
+ | `rest` | `null` | `{ url, headers?, credentials?, fetch? }` (openapi.yaml); `null` → IndexedDB |
180
+ | `submitUrl` | `rest.url` | base the published site posts to; applies live |
181
+ | `dbName` | `gjs-forms` | IndexedDB database |
182
+ | `autosaveDelay` | `600` | ms; applies live |
183
+ | `blocks` | `true` | blocks of the forms |
184
+ | `baseCss` | `true` | the base form sheet in the project CSS |
185
+ | `panelId` | `options` | panel of the *Forms* button |
186
+ | `labels` | `{}` | texts (any key of `FormsLabels`) |
187
+ | `injectCss` | `true` | the plugin's own UI styles |
188
+
189
+ Languages: English, Russian, Ukrainian (through `editor.I18n`, namespace `gjsForms`); others fall back to English
190
+ or take `labels`.
191
+
192
+ This plugin follows the plugin contract of grapesjs-plugins-manager (`getOptions` / `setOptions`).
193
+
194
+ ## Development
195
+
196
+ ```bash
197
+ npm install
198
+ npm run dev # index.html with the sources
199
+ npm test # vitest + jsdom + real grapesjs
200
+ npm run typecheck
201
+ npm run build # dist/: ES + UMD, runtime.js / runtime.iife.js, .d.ts
202
+ ```
203
+
204
+ MIT
@@ -0,0 +1,68 @@
1
+ import { type BuildContext } from './placeholders';
2
+ import { type FormDef } from './schema';
3
+ /**
4
+ * A form as a tree of plain HTML elements with stable classes. The same tree
5
+ * becomes GrapesJS components (`toComponents`) or an HTML string
6
+ * (`formHtml`, for servers and previews).
7
+ *
8
+ * The classes are the styling contract: the site's CSS (made in the Style
9
+ * Manager like any other) styles `.gjsf-input`, `.gjsf-label`… on every
10
+ * form at once, and a form gets its own look from a class on the form.
11
+ */
12
+ export interface El {
13
+ tag: string;
14
+ attrs?: Record<string, string>;
15
+ classes?: string[];
16
+ /** Text or elements. */
17
+ kids?: Array<El | string>;
18
+ /** `<input>` and friends. */
19
+ void?: boolean;
20
+ /** Which part of the form (`field`, `label`, `input`…): `data-gjsf-part`. */
21
+ part: string;
22
+ style?: Record<string, string>;
23
+ }
24
+ export declare const CLS: {
25
+ readonly form: "gjsf-form";
26
+ readonly field: "gjsf-field";
27
+ readonly label: "gjsf-label";
28
+ readonly req: "gjsf-req";
29
+ readonly input: "gjsf-input";
30
+ readonly options: "gjsf-options";
31
+ readonly option: "gjsf-option";
32
+ readonly check: "gjsf-check";
33
+ readonly optionLabel: "gjsf-option-label";
34
+ readonly help: "gjsf-help";
35
+ readonly error: "gjsf-error";
36
+ readonly heading: "gjsf-heading";
37
+ readonly text: "gjsf-text";
38
+ readonly actions: "gjsf-actions";
39
+ readonly submit: "gjsf-submit";
40
+ readonly message: "gjsf-message";
41
+ readonly hp: "gjsf-hp";
42
+ };
43
+ export interface BuildOptions {
44
+ /** Where the form posts (`action`); empty — the site handles `gjsf:submit` itself. */
45
+ action?: string;
46
+ /** Makes element ids unique when one form is on a page twice. */
47
+ key?: string;
48
+ ctx?: BuildContext;
49
+ /** Default texts (the form's own settings win). */
50
+ texts?: {
51
+ submit?: string;
52
+ success?: string;
53
+ error?: string;
54
+ };
55
+ /** Texts of problem codes (`required` → "Please fill in…") the site shows for a server's 422 codes. */
56
+ codes?: Record<string, string>;
57
+ /** grapesjs-pages record of the page (sent as `meta.page_id`). */
58
+ pageId?: string | null;
59
+ }
60
+ /** The attributes of a form element. */
61
+ export declare function formAttrs(form: FormDef, o?: BuildOptions): Record<string, string>;
62
+ /** The parts inside the `<form>`. */
63
+ export declare function buildChildren(form: FormDef, o?: BuildOptions): El[];
64
+ export declare function elHtml(el: El | string): string;
65
+ /** The whole `<form>` as HTML (servers, e-mails, previews, sites without GrapesJS). */
66
+ export declare function formHtml(form: FormDef, o?: BuildOptions & {
67
+ classes?: string[];
68
+ }): string;
@@ -0,0 +1,100 @@
1
+ /**
2
+ * GrapesJS plugin contract, v1.
3
+ *
4
+ * The same file is copied into every plugin of this family (no shared
5
+ * package): keep the copies identical. It lets a plugin
6
+ * - say who it is (`id`, `version`, `title`) and which options it takes
7
+ * (`options` schema) — on the plugin function, as `fn.meta`;
8
+ * - be used by its npm name like the official plugins:
9
+ * `plugins: ['grapesjs-site-pages']`, `pluginsOpts: { 'grapesjs-site-pages': {…} }`;
10
+ * - expose its current options and take new ones after start
11
+ * (`getOptions()` / `setOptions(patch)`), which grapesjs-plugins-manager
12
+ * uses for its "Settings" form.
13
+ *
14
+ * Everything is looked up through `Symbol.for(...)` keys, so separate
15
+ * bundles (each with its own copy of this file) see each other.
16
+ */
17
+ /** A field of an options form. */
18
+ export interface OptionField {
19
+ /** Option name; nested options are `type: 'object'` with `fields`. */
20
+ key: string;
21
+ type: 'boolean' | 'string' | 'number' | 'select' | 'list' | 'json' | 'object';
22
+ /** The value used when the option is not given. */
23
+ default?: unknown;
24
+ /** Short title (English); the key is shown when missing. */
25
+ title?: string;
26
+ /** One-line help (English). */
27
+ description?: string;
28
+ /** `select`: the allowed values. */
29
+ choices?: Array<{
30
+ value: string | number | boolean | null;
31
+ label?: string;
32
+ }>;
33
+ /** `object`: its fields. */
34
+ fields?: OptionField[];
35
+ /** Applied right away by `setOptions`; otherwise it needs a reload. */
36
+ live?: boolean;
37
+ /** Masked in forms (API keys, tokens). */
38
+ secret?: boolean;
39
+ /** Shown under "Advanced". */
40
+ advanced?: boolean;
41
+ /** Older names the plugin still accepts for this option. */
42
+ aliases?: string[];
43
+ }
44
+ export interface PluginMeta {
45
+ /** The npm name; also the id in `grapesjs.plugins` and `pluginsOpts`. */
46
+ id: string;
47
+ version?: string;
48
+ title?: string;
49
+ description?: string;
50
+ options?: OptionField[];
51
+ }
52
+ /** What `setOptions` did. */
53
+ export interface SetOptionsResult {
54
+ /** Keys applied right away. */
55
+ applied: string[];
56
+ /** Keys stored but taking effect after a reload. */
57
+ reload: string[];
58
+ }
59
+ /** A running plugin's options, registered per editor. */
60
+ export interface PluginControl {
61
+ meta: PluginMeta;
62
+ /** The options in effect (resolved, with defaults). */
63
+ getOptions(): Record<string, unknown>;
64
+ /** Applies what it can now; the rest needs a reload. */
65
+ setOptions(patch: Record<string, unknown>): SetOptionsResult;
66
+ }
67
+ export declare const CONTROLS: unique symbol;
68
+ /** Editor event after `setOptions`: `{ id, patch, result }`. */
69
+ export declare const OPTIONS_EVENT = "plugin:options";
70
+ type PluginFnLike = ((editor: any, opts?: any) => void) & {
71
+ meta?: PluginMeta;
72
+ };
73
+ /**
74
+ * Marks a plugin function with its meta and registers it in
75
+ * `grapesjs.plugins` under `meta.id` (when `grapesjs` is a global and the
76
+ * id is free), so it can be listed by name. Returns the same function.
77
+ */
78
+ export declare function definePlugin<F extends PluginFnLike>(fn: F, meta: PluginMeta): F & {
79
+ meta: PluginMeta;
80
+ };
81
+ /** The controls of the plugins running in an editor: id → control. */
82
+ export declare function getControls(editor: object): Map<string, PluginControl>;
83
+ /**
84
+ * Registers a plugin's options control for an editor; returns the remover.
85
+ * `apply(patch)` gets only the keys marked `live` and must apply them.
86
+ */
87
+ export declare function registerControl(editor: {
88
+ trigger?(event: string, ...args: unknown[]): unknown;
89
+ }, meta: PluginMeta, current: () => Record<string, unknown>, apply: (patch: Record<string, unknown>) => void): () => void;
90
+ /** Values of option fields by their defaults: `{ key: default }`. */
91
+ export declare function defaultsOf(fields?: OptionField[]): Record<string, unknown>;
92
+ /** Copies options given under an alias to the main key (the main key wins). */
93
+ export declare function applyAliases<T extends Record<string, unknown>>(opts: T, fields?: OptionField[]): T;
94
+ /**
95
+ * Writes a patch into a live options object. A plain-object option the
96
+ * plugin already holds (e.g. `labels`) is refilled in place, so closures
97
+ * that captured it see the new values; anything else is assigned.
98
+ */
99
+ export declare function assignOptions(target: Record<string, unknown>, patch: Record<string, unknown>): void;
100
+ export {};
@@ -0,0 +1,71 @@
1
+ import type { Component, Editor } from 'grapesjs';
2
+ import { type BuildOptions, type El } from '../build';
3
+ import type { FormDef } from '../schema';
4
+ export declare const FORM_TYPE = "gjsf-form";
5
+ export declare const PART_TYPE = "gjsf-part";
6
+ export declare const FORM_ATTR = "data-gjsf-form";
7
+ export declare const PART_ATTR = "data-gjsf-part";
8
+ /**
9
+ * Gives every built element without an id a stable one, made from the
10
+ * component's key, the field it belongs to and its part
11
+ * (`gjsf-k3x9a-email-label`, `gjsf-k3x9a-form-submit`): a rebuild (the form
12
+ * was edited, another page opened) makes the same ids, so styles given to
13
+ * the parts in GrapesJS (`#…` rules) stay with them.
14
+ */
15
+ export declare function stableIds(els: Array<El | string>, key: string): Array<El | string>;
16
+ /** A built element as a GrapesJS component definition. */
17
+ export declare function toComponent(el: El | string): Record<string, unknown>;
18
+ export interface FormHost {
19
+ /** The form of an id (cached). */
20
+ form(id: string | null | undefined): FormDef | undefined;
21
+ /** Options of a build (action, texts, page). */
22
+ buildOptions(form: FormDef, comp: Component): BuildOptions;
23
+ /** The select of the "Form" trait. */
24
+ formOptions(): Array<{
25
+ id: string;
26
+ name: string;
27
+ }>;
28
+ labels: {
29
+ chooseForm: () => string;
30
+ editForm: () => string;
31
+ noForm: () => string;
32
+ missingForm: () => string;
33
+ };
34
+ editCommand: string;
35
+ /** A form component without a form was dropped from the "New form" block. */
36
+ onCreate(comp: Component): void;
37
+ }
38
+ /** The rules every form needs on the site (in the project CSS, so they are exported). */
39
+ export declare const REQUIRED_CSS: string;
40
+ /** Shown only in the canvas. */
41
+ export declare const CANVAS_CSS: string;
42
+ /**
43
+ * The component types: `gjsf-form` (the `<form>`, its `formId` names the
44
+ * form; the script is the site's behaviour) and `gjsf-part` (everything
45
+ * inside, made from the form's schema).
46
+ */
47
+ export declare class FormComponents {
48
+ private readonly editor;
49
+ private readonly host;
50
+ private offs;
51
+ constructor(editor: Editor, host: FormHost);
52
+ traits(): any[];
53
+ private selectOptions;
54
+ /** The trait list of a form component (labels and the list of forms change). */
55
+ refreshTraits(c: Component): void;
56
+ /** All form components of the open project. */
57
+ all(): Component[];
58
+ /** Adds the rules the site needs once (in the project CSS). */
59
+ ensureCss(): void;
60
+ /**
61
+ * Rebuilds a form component from its form: its parts are replaced, the
62
+ * attributes the plugin owns rewritten; the user's classes and own
63
+ * attributes of the `<form>` stay. Not on the undo stack. A component
64
+ * whose form is gone keeps its parts (a copy) and is marked.
65
+ */
66
+ rebuild(c: Component): void;
67
+ private find;
68
+ /** Rebuilds the components of one form (all when no id); `stale` — only those built from another version or for another page. */
69
+ rebuildAll(formId?: string | null, stale?: (c: Component, f: FormDef) => boolean): number;
70
+ destroy(): void;
71
+ }
@@ -0,0 +1,23 @@
1
+ /** Events the plugin triggers on the editor (`editor.on(EVENTS.change, …)`). */
2
+ export declare const EVENTS: {
3
+ /** The forms were (re)read or one changed. Payload: `FormDef[]`. */
4
+ readonly forms: "forms:list";
5
+ /** A form was written. Payload: `FormDef`. */
6
+ readonly saved: "forms:saved";
7
+ /** A form was deleted. Payload: `id`. */
8
+ readonly removed: "forms:removed";
9
+ /** A submission was sent from the editor's preview. Payload: `{ formId, result }`. */
10
+ readonly submitted: "forms:submitted";
11
+ };
12
+ export declare const COMMANDS: {
13
+ /** Opens the forms editor; `{ id }` — on that form. */
14
+ readonly open: "forms:open";
15
+ /** Opens the editor on the form of the selected component (or `{ component }`). */
16
+ readonly edit: "forms:edit";
17
+ };
18
+ /** Events of the site's `<form>` (runtime). */
19
+ export declare const DOM_EVENTS: {
20
+ readonly submit: "gjsf:submit";
21
+ readonly success: "gjsf:success";
22
+ readonly error: "gjsf:error";
23
+ };