@ngstarter-ui/components 22.2.3 → 22.2.4

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.
Files changed (55) hide show
  1. package/ai/component-registry.json +22 -0
  2. package/content-editor/BLOCK_FORMAT.md +144 -0
  3. package/fesm2022/ngstarter-ui-components-content-editor-attachment-block-rzZKJ2JH.mjs +35 -0
  4. package/fesm2022/ngstarter-ui-components-content-editor-attachment-block-rzZKJ2JH.mjs.map +1 -0
  5. package/fesm2022/{ngstarter-ui-components-content-editor-callout-block-Jbf8h2yz.mjs → ngstarter-ui-components-content-editor-callout-block-DTdApN0r.mjs} +2 -3
  6. package/fesm2022/{ngstarter-ui-components-content-editor-callout-block-Jbf8h2yz.mjs.map → ngstarter-ui-components-content-editor-callout-block-DTdApN0r.mjs.map} +1 -1
  7. package/fesm2022/{ngstarter-ui-components-content-editor-code-block.component-BizHRPdC.mjs → ngstarter-ui-components-content-editor-code-block.component-DpONkTMU.mjs} +2 -2
  8. package/fesm2022/{ngstarter-ui-components-content-editor-code-block.component-BizHRPdC.mjs.map → ngstarter-ui-components-content-editor-code-block.component-DpONkTMU.mjs.map} +1 -1
  9. package/fesm2022/{ngstarter-ui-components-content-editor-embed-block-BzoaJvai.mjs → ngstarter-ui-components-content-editor-embed-block-CmhzpaRk.mjs} +2 -2
  10. package/fesm2022/{ngstarter-ui-components-content-editor-embed-block-BzoaJvai.mjs.map → ngstarter-ui-components-content-editor-embed-block-CmhzpaRk.mjs.map} +1 -1
  11. package/fesm2022/{ngstarter-ui-components-content-editor-gallery-block-C4p-S0Do.mjs → ngstarter-ui-components-content-editor-gallery-block-gtH7yWd5.mjs} +16 -39
  12. package/fesm2022/ngstarter-ui-components-content-editor-gallery-block-gtH7yWd5.mjs.map +1 -0
  13. package/fesm2022/{ngstarter-ui-components-content-editor-grid-block-Cdq_Dcv2.mjs → ngstarter-ui-components-content-editor-grid-block-Pb-xV7Pw.mjs} +3 -4
  14. package/fesm2022/{ngstarter-ui-components-content-editor-grid-block-Cdq_Dcv2.mjs.map → ngstarter-ui-components-content-editor-grid-block-Pb-xV7Pw.mjs.map} +1 -1
  15. package/fesm2022/{ngstarter-ui-components-content-editor-heading-block.component-CDSt4rXe.mjs → ngstarter-ui-components-content-editor-heading-block.component-BKe9Zy_x.mjs} +2 -2
  16. package/fesm2022/{ngstarter-ui-components-content-editor-heading-block.component-CDSt4rXe.mjs.map → ngstarter-ui-components-content-editor-heading-block.component-BKe9Zy_x.mjs.map} +1 -1
  17. package/fesm2022/ngstarter-ui-components-content-editor-image-block.component-DSpBVTu-.mjs +113 -0
  18. package/fesm2022/ngstarter-ui-components-content-editor-image-block.component-DSpBVTu-.mjs.map +1 -0
  19. package/fesm2022/{ngstarter-ui-components-content-editor-list-block.component-CdQ30RjA.mjs → ngstarter-ui-components-content-editor-list-block.component-BPKPE1uY.mjs} +2 -2
  20. package/fesm2022/{ngstarter-ui-components-content-editor-list-block.component-CdQ30RjA.mjs.map → ngstarter-ui-components-content-editor-list-block.component-BPKPE1uY.mjs.map} +1 -1
  21. package/fesm2022/{ngstarter-ui-components-content-editor-nested-blocks-CbZY0keH.mjs → ngstarter-ui-components-content-editor-nested-blocks-Dh-p3WMp.mjs} +4 -4
  22. package/fesm2022/ngstarter-ui-components-content-editor-nested-blocks-Dh-p3WMp.mjs.map +1 -0
  23. package/fesm2022/{ngstarter-ui-components-content-editor-ngstarter-ui-components-content-editor-CK4ssnlk.mjs → ngstarter-ui-components-content-editor-ngstarter-ui-components-content-editor-CR-NrarE.mjs} +2021 -1505
  24. package/fesm2022/ngstarter-ui-components-content-editor-ngstarter-ui-components-content-editor-CR-NrarE.mjs.map +1 -0
  25. package/fesm2022/{ngstarter-ui-components-content-editor-paragraph-block.component-Dd0pQquG.mjs → ngstarter-ui-components-content-editor-paragraph-block.component-D5wS3m6O.mjs} +2 -2
  26. package/fesm2022/{ngstarter-ui-components-content-editor-paragraph-block.component-Dd0pQquG.mjs.map → ngstarter-ui-components-content-editor-paragraph-block.component-D5wS3m6O.mjs.map} +1 -1
  27. package/fesm2022/{ngstarter-ui-components-content-editor-quote-block.component-CUxKoeb_.mjs → ngstarter-ui-components-content-editor-quote-block.component-C3GFAGKF.mjs} +2 -2
  28. package/fesm2022/{ngstarter-ui-components-content-editor-quote-block.component-CUxKoeb_.mjs.map → ngstarter-ui-components-content-editor-quote-block.component-C3GFAGKF.mjs.map} +1 -1
  29. package/fesm2022/{ngstarter-ui-components-content-editor-table-block.component-BTExrXy8.mjs → ngstarter-ui-components-content-editor-table-block.component-DQgs_kyN.mjs} +2 -2
  30. package/fesm2022/{ngstarter-ui-components-content-editor-table-block.component-BTExrXy8.mjs.map → ngstarter-ui-components-content-editor-table-block.component-DQgs_kyN.mjs.map} +1 -1
  31. package/fesm2022/{ngstarter-ui-components-content-editor-toggle-block-B46YeMGQ.mjs → ngstarter-ui-components-content-editor-toggle-block-Cb67ChE8.mjs} +3 -4
  32. package/fesm2022/{ngstarter-ui-components-content-editor-toggle-block-B46YeMGQ.mjs.map → ngstarter-ui-components-content-editor-toggle-block-Cb67ChE8.mjs.map} +1 -1
  33. package/fesm2022/ngstarter-ui-components-content-editor-upload-status-QnKI_Rfz.mjs +19 -0
  34. package/fesm2022/ngstarter-ui-components-content-editor-upload-status-QnKI_Rfz.mjs.map +1 -0
  35. package/fesm2022/ngstarter-ui-components-content-editor-video-block.component-CRa0g9Ez.mjs +134 -0
  36. package/fesm2022/ngstarter-ui-components-content-editor-video-block.component-CRa0g9Ez.mjs.map +1 -0
  37. package/fesm2022/ngstarter-ui-components-content-editor.mjs +1 -1
  38. package/fesm2022/ngstarter-ui-components-headless-editor.mjs +57 -0
  39. package/fesm2022/ngstarter-ui-components-headless-editor.mjs.map +1 -1
  40. package/package.json +1 -1
  41. package/types/ngstarter-ui-components-content-editor.d.ts +205 -10
  42. package/types/ngstarter-ui-components-headless-editor.d.ts +6 -1
  43. package/fesm2022/ngstarter-ui-components-content-editor-attachment-block-DlUkhwCu.mjs +0 -54
  44. package/fesm2022/ngstarter-ui-components-content-editor-attachment-block-DlUkhwCu.mjs.map +0 -1
  45. package/fesm2022/ngstarter-ui-components-content-editor-block-base-C46lyMrp.mjs +0 -47
  46. package/fesm2022/ngstarter-ui-components-content-editor-block-base-C46lyMrp.mjs.map +0 -1
  47. package/fesm2022/ngstarter-ui-components-content-editor-gallery-block-C4p-S0Do.mjs.map +0 -1
  48. package/fesm2022/ngstarter-ui-components-content-editor-image-block.component-LfKZapgv.mjs +0 -169
  49. package/fesm2022/ngstarter-ui-components-content-editor-image-block.component-LfKZapgv.mjs.map +0 -1
  50. package/fesm2022/ngstarter-ui-components-content-editor-nested-blocks-CbZY0keH.mjs.map +0 -1
  51. package/fesm2022/ngstarter-ui-components-content-editor-ngstarter-ui-components-content-editor-CK4ssnlk.mjs.map +0 -1
  52. package/fesm2022/ngstarter-ui-components-content-editor-upload-block-base-DKqojf--.mjs +0 -29
  53. package/fesm2022/ngstarter-ui-components-content-editor-upload-block-base-DKqojf--.mjs.map +0 -1
  54. package/fesm2022/ngstarter-ui-components-content-editor-video-block.component-hBR5AauH.mjs +0 -201
  55. package/fesm2022/ngstarter-ui-components-content-editor-video-block.component-hBR5AauH.mjs.map +0 -1
@@ -1,11 +1,11 @@
1
1
  import * as i0 from '@angular/core';
2
- import { inject, DestroyRef, signal, computed, Injectable, ElementRef, input, output, effect, untracked, afterNextRender, Directive, ChangeDetectionStrategy, Component, DOCUMENT as DOCUMENT$1, model, InjectionToken, makeEnvironmentProviders, EventEmitter, HostListener, Output, Input as Input$1, PLATFORM_ID, viewChild, EnvironmentInjector, ChangeDetectorRef, numberAttribute, booleanAttribute, runInInjectionContext, forwardRef, linkedSignal, viewChildren, afterRenderEffect } from '@angular/core';
2
+ import { inject, Injectable, InjectionToken, makeEnvironmentProviders, DestroyRef, signal, computed, ElementRef, input, output, effect, untracked, afterNextRender, afterRenderEffect, Directive, ChangeDetectionStrategy, Component, DOCUMENT as DOCUMENT$1, model, EventEmitter, HostListener, Output, Input as Input$1, PLATFORM_ID, viewChild, numberAttribute, EnvironmentInjector, ChangeDetectorRef, booleanAttribute, runInInjectionContext, forwardRef, linkedSignal, viewChildren } from '@angular/core';
3
3
  import { Button } from '@ngstarter-ui/components/button';
4
4
  import { Icon } from '@ngstarter-ui/components/icon';
5
5
  import { Menu, MenuItem, MenuTrigger, MenuHeading, MenuContent } from '@ngstarter-ui/components/menu';
6
6
  import { DialogRef, DialogContent, DialogTitle, DialogActions, DIALOG_DATA, Dialog } from '@ngstarter-ui/components/dialog';
7
7
  import * as i1 from '@ngstarter-ui/components/headless-editor';
8
- import { isNgsHeadlessEditorTextContent, getNgsHeadlessEditorTableData, NgsHeadlessEditor, NgsHeadlessEditorInlineRegion, NgsHeadlessEditorSurface, createNgsHeadlessEditorId, provideNgsHeadlessEditorInlineRegion, NGS_HEADLESS_EDITOR_TOGGLE_BOLD, NGS_HEADLESS_EDITOR_TOGGLE_ITALIC, NGS_HEADLESS_EDITOR_TOGGLE_CODE, NGS_HEADLESS_EDITOR_TOGGLE_STRIKE, NGS_HEADLESS_EDITOR_TOGGLE_UNDERLINE, NGS_HEADLESS_EDITOR_TOGGLE_SUPERSCRIPT, NGS_HEADLESS_EDITOR_TOGGLE_SUBSCRIPT, NGS_HEADLESS_EDITOR_SET_LINK, NGS_HEADLESS_EDITOR_UNSET_LINK, NGS_HEADLESS_EDITOR_SET_TEXT_COLOR, NGS_HEADLESS_EDITOR_UNSET_TEXT_COLOR, NGS_HEADLESS_EDITOR_SET_BACKGROUND_COLOR, NGS_HEADLESS_EDITOR_UNSET_BACKGROUND_COLOR, provideNgsHeadlessEditor, withHeadlessEditorPlugin, basicTextEditorPlugin, colorEditorPlugin, linkEditorPlugin, createNgsHeadlessEditorText, normalizeNgsHeadlessEditorLink, normalizeNgsHeadlessEditorColor, normalizeNgsHeadlessEditorTextContent, createNgsHeadlessEditorDocument, readNgsHeadlessEditorInlineContent, NgsHeadlessEditorRuns } from '@ngstarter-ui/components/headless-editor';
8
+ import { isNgsHeadlessEditorTextContent, getNgsHeadlessEditorTableData, createNgsHeadlessEditorId, normalizeNgsHeadlessEditorLink, normalizeNgsHeadlessEditorColor, basicTextEditorPlugin, colorEditorPlugin, linkEditorPlugin, createNgsHeadlessEditorText, normalizeNgsHeadlessEditorTextContent, NgsHeadlessEditor, NgsHeadlessEditorInlineRegion, NgsHeadlessEditorSurface, provideNgsHeadlessEditorInlineRegion, NGS_HEADLESS_EDITOR_TOGGLE_BOLD, NGS_HEADLESS_EDITOR_TOGGLE_ITALIC, NGS_HEADLESS_EDITOR_TOGGLE_CODE, NGS_HEADLESS_EDITOR_TOGGLE_STRIKE, NGS_HEADLESS_EDITOR_TOGGLE_UNDERLINE, NGS_HEADLESS_EDITOR_TOGGLE_SUPERSCRIPT, NGS_HEADLESS_EDITOR_TOGGLE_SUBSCRIPT, NGS_HEADLESS_EDITOR_SET_LINK, NGS_HEADLESS_EDITOR_UNSET_LINK, NGS_HEADLESS_EDITOR_SET_TEXT_COLOR, NGS_HEADLESS_EDITOR_UNSET_TEXT_COLOR, NGS_HEADLESS_EDITOR_SET_BACKGROUND_COLOR, NGS_HEADLESS_EDITOR_UNSET_BACKGROUND_COLOR, provideNgsHeadlessEditor, withHeadlessEditorPlugin, createNgsHeadlessEditorDocument, NgsHeadlessEditorRuns } from '@ngstarter-ui/components/headless-editor';
9
9
  import { DOCUMENT, isPlatformBrowser, isPlatformServer, NgComponentOutlet, AsyncPipe, NgTemplateOutlet } from '@angular/common';
10
10
  import { Input } from '@ngstarter-ui/components/input';
11
11
  import { FormField, Label, Hint } from '@ngstarter-ui/components/form-field';
@@ -153,1420 +153,1691 @@ function cloneContentEditorValue(value) {
153
153
  }
154
154
  return value;
155
155
  }
156
-
157
- /** UI state and block operations. The headless document is the only content store. */
158
- class ContentBuilderStore {
159
- editor = inject(NgsHeadlessEditor);
160
- dragging = false;
161
- constructor() {
162
- const document = inject(DOCUMENT);
163
- // Capture the current point before CDK chooses a connected list. Its moved
164
- // output is emitted after hit testing and would provide the previous point.
165
- const mouse = (event) => { if (this.dragging)
166
- this.dragPointer.set({ x: event.clientX, y: event.clientY }); };
167
- const touch = (event) => {
168
- const point = event.touches[0];
169
- if (this.dragging && point)
170
- this.dragPointer.set({ x: point.clientX, y: point.clientY });
171
- };
172
- document.addEventListener('mousemove', mouse, true);
173
- document.addEventListener('touchmove', touch, { capture: true, passive: true });
174
- inject(DestroyRef).onDestroy(() => {
175
- document.removeEventListener('mousemove', mouse, true);
176
- document.removeEventListener('touchmove', touch, true);
177
- });
178
- }
179
- textEdit = null;
180
- /** Scopes typing groups to one text region, so adjacent cells never share undo. */
181
- withTextEdit(origin, group, edit) {
182
- const previous = this.textEdit;
183
- this.textEdit = { origin, group };
184
- try {
185
- edit();
186
- }
187
- finally {
188
- this.textEdit = previous;
156
+ /** Locates the collection owning a block, including deeply nested Grid/Toggle blocks. */
157
+ function contentEditorBlockScope(blocks, id, scope = {}) {
158
+ for (const block of blocks) {
159
+ if (block.id === id)
160
+ return scope;
161
+ if (block.type === 'toggle') {
162
+ const found = contentEditorBlockScope(block.content.blocks, id, { parentId: block.id });
163
+ if (found)
164
+ return found;
189
165
  }
190
- }
191
- focusedBlockId = signal(null, /* @ts-ignore */
192
- ...(ngDevMode ? [{ debugName: "focusedBlockId" }] : /* istanbul ignore next */ []));
193
- activeBlockId = signal(null, /* @ts-ignore */
194
- ...(ngDevMode ? [{ debugName: "activeBlockId" }] : /* istanbul ignore next */ []));
195
- dragPointer = signal(null, /* @ts-ignore */
196
- ...(ngDevMode ? [{ debugName: "dragPointer" }] : /* istanbul ignore next */ []));
197
- setDragging(dragging) {
198
- this.dragging = dragging;
199
- if (!dragging)
200
- this.dragPointer.set(null);
201
- }
202
- dropLists = signal([], /* @ts-ignore */
203
- ...(ngDevMode ? [{ debugName: "dropLists" }] : /* istanbul ignore next */ []));
204
- registerDropList(list) {
205
- if (!this.dropLists().includes(list))
206
- this.dropLists.update(lists => [...lists, list]);
207
- }
208
- unregisterDropList(list) {
209
- this.dropLists.update(lists => lists.filter(item => item !== list));
210
- }
211
- blocks = computed(() => this.editor.document().blocks.map(contentEditorBlockView), /* @ts-ignore */
212
- ...(ngDevMode ? [{ debugName: "blocks" }] : /* istanbul ignore next */ []));
213
- setFocusedBlockId(id) { this.focusedBlockId.set(id); }
214
- setActiveBlockId(id) { this.activeBlockId.set(id); }
215
- setBlocks(value) {
216
- this.editor.setDocument(value);
217
- }
218
- addBlock(block, index, scope = {}) {
219
- const native = contentEditorNativeBlock(block);
220
- const blocks = cloneContentEditorValue([...this.editor.document().blocks]);
221
- const collection = [...contentEditorCollection(blocks, scope)];
222
- collection.splice(index, 0, native);
223
- replaceContentEditorCollection(blocks, scope, collection);
224
- this.editor.updateDocument({ version: 1, blocks });
225
- }
226
- deleteBlock(id, _index) {
227
- const blocks = cloneContentEditorValue([...this.editor.document().blocks]);
228
- const remove = (items) => {
229
- const index = items.findIndex(block => block.id === id);
230
- if (index !== -1) {
231
- items.splice(index, 1);
232
- return true;
166
+ if (block.type === 'grid')
167
+ for (const cell of block.content.cells) {
168
+ const found = contentEditorBlockScope(cell.blocks, id, { parentId: block.id, cellId: cell.id });
169
+ if (found)
170
+ return found;
233
171
  }
234
- return items.some(block => contentEditorChildCollections(block).some(children => remove(children)));
235
- };
236
- if (remove(blocks))
237
- this.editor.updateDocument({ version: 1, blocks });
238
- }
239
- updateBlock(id, data) {
240
- const blocks = cloneContentEditorValue([...this.editor.document().blocks]);
241
- const previous = findContentEditorBlock(blocks, id);
242
- if (!previous)
243
- return;
244
- const next = contentEditorNativeBlock({ ...contentEditorBlockView(previous), ...data });
245
- const origin = this.textEdit?.origin ?? 'command';
246
- const typing = origin === 'keyboard' || origin === 'composition';
247
- const root = blocks.find(block => !!findContentEditorBlock([block], id));
248
- Object.assign(previous, next);
249
- this.editor.updateBlock(root.id, { content: root.content, attrs: root.attrs }, typing ? origin : 'command', typing ? this.textEdit?.group ?? null : null);
250
- }
251
- moveBlock(from, to) {
252
- const blocks = [...this.editor.document().blocks];
253
- const [block] = blocks.splice(from, 1);
254
- blocks.splice(to, 0, block);
255
- this.editor.updateDocument({ version: 1, blocks });
256
- }
257
- moveBetweenCollections(from, to, source, target) {
258
- const blocks = cloneContentEditorValue([...this.editor.document().blocks]);
259
- const sourceItems = [...contentEditorCollection(blocks, source)];
260
- const block = sourceItems[from];
261
- if (!block || (target.parentId && findContentEditorBlock([block], target.parentId)))
262
- return;
263
- sourceItems.splice(from, 1);
264
- replaceContentEditorCollection(blocks, source, sourceItems);
265
- const targetItems = [...contentEditorCollection(blocks, target)];
266
- targetItems.splice(to, 0, block);
267
- replaceContentEditorCollection(blocks, target, targetItems);
268
- this.editor.updateDocument({ version: 1, blocks });
269
172
  }
270
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentBuilderStore, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
271
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentBuilderStore });
173
+ return null;
174
+ }
175
+ /** Copies for insertion/duplication receive fresh ids throughout the tree. */
176
+ function contentEditorCopyBlocks(blocks) {
177
+ const copy = cloneContentEditorValue([...blocks]);
178
+ const visit = (block) => {
179
+ block.id = createNgsHeadlessEditorId(block.type);
180
+ for (const children of contentEditorChildCollections(block))
181
+ children.forEach(visit);
182
+ if (block.type === 'grid')
183
+ block.content.cells.forEach((cell) => cell.id = createNgsHeadlessEditorId('cell'));
184
+ if (block.type === 'gallery')
185
+ block.content.images.forEach((image) => image.id = createNgsHeadlessEditorId('image'));
186
+ };
187
+ copy.forEach(visit);
188
+ return copy;
189
+ }
190
+ /** UTF-16 offsets match the editor selection model; marks remain on sliced runs. */
191
+ function contentEditorSliceText(content, start, end = Infinity) {
192
+ let offset = 0;
193
+ return content.flatMap(run => {
194
+ const from = Math.max(0, start - offset);
195
+ const to = Math.min(run.text.length, end - offset);
196
+ offset += run.text.length;
197
+ return to > from ? [{ ...run, text: run.text.slice(from, to) }] : [];
198
+ });
272
199
  }
273
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentBuilderStore, decorators: [{
274
- type: Injectable
275
- }], ctorParameters: () => [] });
276
200
 
277
- const regions = new WeakMap();
278
- /** A headless inline editor bound to a text field in a content block. */
279
- class ContentEditorContentEditableDirective {
280
- region = inject(NgsHeadlessEditorInlineRegion);
281
- surface = inject(NgsHeadlessEditorSurface);
282
- store = inject(ContentBuilderStore, { optional: true });
283
- historyGroup = createNgsHeadlessEditorId('content-region');
284
- element = inject(ElementRef).nativeElement;
285
- content = input([], { ...(ngDevMode ? { debugName: "content" } : /* istanbul ignore next */ {}), alias: 'ngsContentEditorContentEditable' });
286
- settings = input({}, /* @ts-ignore */
287
- ...(ngDevMode ? [{ debugName: "settings" }] : /* istanbul ignore next */ []));
288
- props = input([], /* @ts-ignore */
289
- ...(ngDevMode ? [{ debugName: "props" }] : /* istanbul ignore next */ []));
290
- singleLine = input(false, /* @ts-ignore */
291
- ...(ngDevMode ? [{ debugName: "singleLine" }] : /* istanbul ignore next */ []));
292
- contentChanged = output();
293
- propsChanged = output();
294
- pressedEnter = output();
295
- initialized = output();
296
- static forElement(element) {
297
- return element ? regions.get(element) : undefined;
298
- }
299
- constructor() {
300
- regions.set(this.element, this);
301
- effect(() => {
302
- const content = this.content();
303
- untracked(() => this.region.load(content));
304
- });
305
- effect(() => {
306
- const content = this.region.content();
307
- const origin = this.region.editor.origin();
308
- if (origin !== 'external' && origin !== 'history') {
309
- untracked(() => {
310
- if (this.store)
311
- this.store.withTextEdit(origin, this.historyGroup, () => this.contentChanged.emit(content));
312
- else
313
- this.contentChanged.emit(content);
314
- });
315
- }
316
- });
317
- // Capture before the surface and the block's own listeners. Structural Enter
318
- // stays with the content builder; multiline fields use the headless surface.
319
- this.element.addEventListener('keydown', this.onKeydown, true);
320
- this.element.addEventListener('beforeinput', this.onBeforeInput, true);
321
- afterNextRender(() => this.initialized.emit());
201
+ function getTextAlignment(props) {
202
+ const value = props?.find(prop => prop.name === 'text-alignment')?.value;
203
+ if (value === 'center' || value === 'right' || value === 'justify') {
204
+ return value;
322
205
  }
323
- activate() { this.region.activate(); }
324
- focus() { this.activate(); this.surface.focus(); }
325
- getContent() { return this.region.content(); }
326
- alignment() { return this.props().find(prop => prop.name === 'text-alignment')?.value ?? 'left'; }
327
- setAlignment(value) {
328
- this.propsChanged.emit([
329
- ...this.props().filter(prop => prop.name !== 'text-alignment'),
330
- { name: 'text-alignment', value }
331
- ]);
206
+ return 'left';
207
+ }
208
+ function getDimensionAttribute(value) {
209
+ if (typeof value === 'number' && Number.isFinite(value)) {
210
+ return value;
332
211
  }
333
- onKeydown = (event) => {
334
- if (event.key === 'Enter' && this.singleLine() && !event.shiftKey && !event.isComposing) {
335
- event.preventDefault();
336
- event.stopImmediatePropagation();
337
- this.pressedEnter.emit(event);
338
- }
339
- };
340
- onBeforeInput = (event) => {
341
- if (event.inputType === 'insertParagraph' && this.singleLine() && !event.isComposing) {
342
- event.preventDefault();
343
- event.stopImmediatePropagation();
344
- this.pressedEnter.emit(new KeyboardEvent('keydown', { key: 'Enter' }));
212
+ if (typeof value === 'string') {
213
+ const trimmed = value.trim();
214
+ if (!trimmed || trimmed === 'auto') {
215
+ return null;
345
216
  }
346
- };
347
- ngOnDestroy() {
348
- regions.delete(this.element);
349
- this.element.removeEventListener('keydown', this.onKeydown, true);
350
- this.element.removeEventListener('beforeinput', this.onBeforeInput, true);
217
+ const parsed = Number.parseFloat(trimmed);
218
+ return Number.isFinite(parsed) ? parsed : null;
351
219
  }
352
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorContentEditableDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
353
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.1.7", type: ContentEditorContentEditableDirective, isStandalone: true, selector: "[ngsContentEditorContentEditable]", inputs: { content: { classPropertyName: "content", publicName: "ngsContentEditorContentEditable", isSignal: true, isRequired: false, transformFunction: null }, settings: { classPropertyName: "settings", publicName: "settings", isSignal: true, isRequired: false, transformFunction: null }, props: { classPropertyName: "props", publicName: "props", isSignal: true, isRequired: false, transformFunction: null }, singleLine: { classPropertyName: "singleLine", publicName: "singleLine", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { contentChanged: "contentChanged", propsChanged: "propsChanged", pressedEnter: "pressedEnter", initialized: "initialized" }, host: { listeners: { "focus": "activate()" }, properties: { "class.align-left": "alignment() === \"left\"", "class.align-center": "alignment() === \"center\"", "class.align-right": "alignment() === \"right\"", "class.align-justify": "alignment() === \"justify\"" }, classAttribute: "ngs-content-editor-content-editable" }, providers: [provideNgsHeadlessEditorInlineRegion()], exportAs: ["ngsContentEditorContentEditable"], hostDirectives: [{ directive: i1.NgsHeadlessEditorSurface }], ngImport: i0 });
220
+ return null;
354
221
  }
355
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorContentEditableDirective, decorators: [{
356
- type: Directive,
357
- args: [{
358
- selector: '[ngsContentEditorContentEditable]',
359
- exportAs: 'ngsContentEditorContentEditable',
360
- providers: [provideNgsHeadlessEditorInlineRegion()],
361
- hostDirectives: [NgsHeadlessEditorSurface],
362
- host: {
363
- 'class': 'ngs-content-editor-content-editable',
364
- '[class.align-left]': 'alignment() === "left"',
365
- '[class.align-center]': 'alignment() === "center"',
366
- '[class.align-right]': 'alignment() === "right"',
367
- '[class.align-justify]': 'alignment() === "justify"',
368
- '(focus)': 'activate()'
369
- }
370
- }]
371
- }], ctorParameters: () => [], propDecorators: { content: [{ type: i0.Input, args: [{ isSignal: true, alias: "ngsContentEditorContentEditable", required: false }] }], settings: [{ type: i0.Input, args: [{ isSignal: true, alias: "settings", required: false }] }], props: [{ type: i0.Input, args: [{ isSignal: true, alias: "props", required: false }] }], singleLine: [{ type: i0.Input, args: [{ isSignal: true, alias: "singleLine", required: false }] }], contentChanged: [{ type: i0.Output, args: ["contentChanged"] }], propsChanged: [{ type: i0.Output, args: ["propsChanged"] }], pressedEnter: [{ type: i0.Output, args: ["pressedEnter"] }], initialized: [{ type: i0.Output, args: ["initialized"] }] } });
372
222
 
373
- class AddLinkDialog {
374
- _dialogRef = inject(DialogRef);
375
- _formBuilder = inject(FormBuilder);
376
- form = this._formBuilder.group({
377
- href: [''],
378
- openInNewTab: [true, [Validators.required]]
379
- });
380
- cancel() {
381
- this._dialogRef.close(false);
382
- }
383
- add() {
384
- this._dialogRef.close(this.form.value);
385
- }
386
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: AddLinkDialog, deps: [], target: i0.ɵɵFactoryTarget.Component });
387
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "22.1.7", type: AddLinkDialog, isStandalone: true, selector: "ngs-add-link", ngImport: i0, template: "<h1 ngs-dialog-title>Add link</h1>\n<ngs-dialog-content [formGroup]=\"form\" class=\"!overflow-hidden\">\n <ngs-form-field class=\"w-full\">\n <ngs-label>Href (Url, Tel or other)</ngs-label>\n <input ngsInput type=\"text\" formControlName=\"href\">\n </ngs-form-field>\n <ngs-slide-toggle formControlName=\"openInNewTab\">Open link in a new tab</ngs-slide-toggle>\n</ngs-dialog-content>\n<ngs-dialog-actions>\n <button ngsButton (click)=\"cancel()\">Cancel</button>\n <button ngsButton=\"filled\"\n [disabled]=\"form.invalid\" (click)=\"add()\">Add</button>\n</ngs-dialog-actions>\n", styles: [""], dependencies: [{ kind: "component", type: DialogContent, selector: "ngs-dialog-content,[ngs-dialog-content],[ngsDialogContent]" }, { kind: "component", type: FormField, selector: "ngs-form-field", inputs: ["labelMode", "subscriptHiddenIfEmpty", "sameHeightAsButton"], exportAs: ["ngsFormField"] }, { kind: "directive", type: Input, selector: "input[ngsInput], textarea[ngsInput]", inputs: ["id", "placeholder", "required", "disabled", "readonly", "errorStateMatcher"], exportAs: ["ngsInput"] }, { kind: "component", type: DialogTitle, selector: "ngs-dialog-title, [ngs-dialog-title], [ngsDialogTitle]", inputs: ["id"], exportAs: ["ngsDialogTitle"] }, { kind: "component", type: DialogActions, selector: "ngs-dialog-actions, [ngs-dialog-actions], [ngsDialogActions]", inputs: ["align"] }, { kind: "component", type: Button, selector: " button[ngsButton], button[ngsIconButton], a[ngsButton], a[ngsIconButton] ", inputs: ["ngsButton", "ngsIconButton", "loading", "disabled", "disabledInteractive", "disableRipple", "reverse", "fullWidth", "hideTextOnMobile"], exportAs: ["ngsButton"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i1$1.DefaultValueAccessor, selector: "input:not([type=checkbox]):not([ngNoCva])[formControlName],textarea:not([ngNoCva])[formControlName],input:not([type=checkbox]):not([ngNoCva])[formControl],textarea:not([ngNoCva])[formControl],input:not([type=checkbox]):not([ngNoCva])[ngModel],textarea:not([ngNoCva])[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i1$1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1$1.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],[formArray],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i1$1.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i1$1.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { kind: "component", type: Label, selector: "ngs-label" }, { kind: "component", type: SlideToggle, selector: "ngs-slide-toggle", inputs: ["id", "name", "labelPosition", "aria-label", "aria-labelledby", "aria-describedby", "required", "disabled", "disableRipple", "tabIndex", "hideIcon", "color", "checked"], outputs: ["disabledChange", "checkedChange", "change", "toggleChange"], exportAs: ["ngsSlideToggle"] }], changeDetection: i0.ChangeDetectionStrategy.Eager });
223
+ /** Defaults shared by editing and read-only layout. */
224
+ function contentEditorGridSettings(settings) {
225
+ return {
226
+ columns: settings.columns === 3 || settings.columns === 4 ? settings.columns : 2,
227
+ gap: settings.gap === 'small' || settings.gap === 'large' ? settings.gap : 'medium',
228
+ stackOnMobile: settings.stackOnMobile !== false
229
+ };
388
230
  }
389
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: AddLinkDialog, decorators: [{
390
- type: Component,
391
- args: [{ selector: 'ngs-add-link', imports: [
392
- DialogContent,
393
- FormField,
394
- Input,
395
- DialogTitle,
396
- DialogActions,
397
- Button,
398
- ReactiveFormsModule,
399
- Label,
400
- SlideToggle
401
- ], changeDetection: ChangeDetectionStrategy.Eager, template: "<h1 ngs-dialog-title>Add link</h1>\n<ngs-dialog-content [formGroup]=\"form\" class=\"!overflow-hidden\">\n <ngs-form-field class=\"w-full\">\n <ngs-label>Href (Url, Tel or other)</ngs-label>\n <input ngsInput type=\"text\" formControlName=\"href\">\n </ngs-form-field>\n <ngs-slide-toggle formControlName=\"openInNewTab\">Open link in a new tab</ngs-slide-toggle>\n</ngs-dialog-content>\n<ngs-dialog-actions>\n <button ngsButton (click)=\"cancel()\">Cancel</button>\n <button ngsButton=\"filled\"\n [disabled]=\"form.invalid\" (click)=\"add()\">Add</button>\n</ngs-dialog-actions>\n" }]
402
- }] });
403
231
 
404
- class EditLinkDialog {
405
- _dialogRef = inject(DialogRef);
406
- _dialogData = inject(DIALOG_DATA);
407
- _formBuilder = inject(FormBuilder);
408
- form = this._formBuilder.group({
409
- href: [this._dialogData.href],
410
- openInNewTab: [this._dialogData.openInNewTab, [Validators.required]]
411
- });
412
- cancel() {
413
- this._dialogRef.close(false);
232
+ /** Plain HTML layout styles, independent of Angular and the component library's theme. */
233
+ const CONTENT_EDITOR_GRID_HTML_STYLES = `.ngs-content-editor-html-grid{container-type:inline-size}.ngs-content-editor-html-grid-cells{display:grid;grid-template-columns:repeat(var(--ngs-html-grid-columns),minmax(0,1fr));gap:var(--ngs-html-grid-gap)}.ngs-content-editor-html-grid-cell{min-width:0}@container(max-width:480px){.ngs-content-editor-html-grid-stack{grid-template-columns:minmax(0,1fr)}}`;
234
+ const CONTENT_EDITOR_CALLOUT_HTML_STYLES = `.ngs-content-editor-html-callout{padding:16px;border-radius:8px;background:var(--ngs-color-primary-container,#eef3ff);color:var(--ngs-color-on-surface,#172033)}.ngs-content-editor-html-callout[data-callout=tip]{background:var(--ngs-color-success-container,#e8f5ee)}.ngs-content-editor-html-callout[data-callout=warning]{background:var(--ngs-color-warning-container,#fff3dc)}.ngs-content-editor-html-callout[data-callout=danger]{background:var(--ngs-color-danger-container,#fdeaea)}`;
235
+ const CONTENT_EDITOR_GALLERY_HTML_STYLES = `.ngs-content-editor-html-gallery{display:flex;overflow-x:auto;scroll-snap-type:x mandatory;gap:16px}.ngs-content-editor-html-gallery>figure{flex:0 0 100%;min-width:0;margin:0;scroll-snap-align:start}.ngs-content-editor-html-gallery img{display:block;width:100%}`;
236
+ function settings(block) { return block.attrs?.['settings'] ?? {}; }
237
+ function alignment(props) {
238
+ const align = getTextAlignment(props);
239
+ return align === 'left' ? '' : ` style="text-align:${align}"`;
240
+ }
241
+ function dimension(name, value) {
242
+ const number = getDimensionAttribute(value);
243
+ return number !== null && number > 0 ? ` ${name}="${Math.round(number)}"` : '';
244
+ }
245
+ const contentEditorParagraphToHtml = (block, ctx) => `<p${alignment(block.attrs?.['props'])}>${ctx.renderText(block.content)}</p>`;
246
+ const contentEditorHeadingToHtml = (block, ctx) => {
247
+ const value = settings(block)['level'];
248
+ const level = Number.isInteger(value) && value >= 1 && value <= 6 ? value : 2;
249
+ return `<h${level}${alignment(block.attrs?.['props'])}>${ctx.renderText(block.content)}</h${level}>`;
250
+ };
251
+ const contentEditorCodeToHtml = (block, ctx) => `<pre><code data-language="${ctx.escape(settings(block)['language'] ?? 'none')}">${ctx.escape(contentEditorText(block.content))}</code></pre>`;
252
+ const contentEditorDividerToHtml = () => '<hr>';
253
+ const contentEditorListToHtml = (block, ctx) => {
254
+ const tag = block.type === 'orderedList' ? 'ol' : 'ul';
255
+ const list = (items) => `<${tag}>${items.map(item => `<li${alignment(item.props)}>${ctx.renderText(item.content)}${item.children?.length ? list(item.children) : ''}</li>`).join('')}</${tag}>`;
256
+ return list(block.content ?? []);
257
+ };
258
+ const contentEditorQuoteToHtml = (block, ctx) => {
259
+ const quote = block.content?.cite;
260
+ const caption = block.content?.caption;
261
+ return `<figure><blockquote${alignment(quote?.props)}>${ctx.renderText(quote?.content ?? [])}</blockquote>${contentEditorText(caption?.content).trim() ? `<figcaption${alignment(caption.props)}>${ctx.renderText(caption.content)}</figcaption>` : ''}</figure>`;
262
+ };
263
+ const contentEditorTableToHtml = (block, ctx) => {
264
+ const table = getNgsHeadlessEditorTableData(block);
265
+ const metadata = block.attrs?.['cellMetadata'];
266
+ const rows = table.rows.map((row, r) => `<tr>${row.map((runs, c) => {
267
+ const tag = r === 0 && table.header ? 'th' : 'td';
268
+ const cell = metadata?.[r]?.[c];
269
+ return `<${tag}${dimension('colspan', cell?.options?.['colspan'])}${dimension('rowspan', cell?.options?.['rowspan'])}${dimension('width', cell?.options?.['width'])}${alignment(cell?.props)}>${ctx.renderText(runs)}</${tag}>`;
270
+ }).join('')}</tr>`).join('');
271
+ return `<table><tbody>${rows}</tbody></table>`;
272
+ };
273
+ const contentEditorImageToHtml = (block, ctx) => {
274
+ const src = ctx.safeUrl(block.content?.src, 'image');
275
+ if (!src)
276
+ return '';
277
+ const alt = block.content?.alt ?? '';
278
+ const config = settings(block);
279
+ return `<figure><img src="${ctx.escape(src)}" alt="${ctx.escape(alt)}"${dimension('width', config['width'])}${dimension('height', config['height'])} style="max-width:100%;height:auto">${alt ? `<figcaption>${ctx.escape(alt)}</figcaption>` : ''}</figure>`;
280
+ };
281
+ const contentEditorVideoToHtml = (block, ctx) => {
282
+ const src = ctx.safeUrl(block.content?.src, 'media');
283
+ if (!src)
284
+ return '';
285
+ const config = settings(block);
286
+ return `<figure><video src="${ctx.escape(src)}" controls${dimension('width', config['width'])}${dimension('height', config['height'])} style="max-width:100%"></video>${block.content?.caption ? `<figcaption>${ctx.escape(block.content.caption)}</figcaption>` : ''}</figure>`;
287
+ };
288
+ const contentEditorEmbedToHtml = (block, ctx) => {
289
+ const src = ctx.safeUrl(block.content?.url, 'embed');
290
+ if (!src)
291
+ return '';
292
+ const config = settings(block);
293
+ return `<figure><iframe src="${ctx.escape(src)}" title="${ctx.escape(block.content?.type || 'Embedded content')}"${dimension('width', config['width'] ?? 700)}${dimension('height', config['height'] ?? 400)} style="max-width:100%" allowfullscreen></iframe></figure>`;
294
+ };
295
+ const contentEditorCalloutToHtml = (block, ctx) => {
296
+ ctx.addStyles(CONTENT_EDITOR_CALLOUT_HTML_STYLES);
297
+ const value = settings(block)['variant'];
298
+ const variant = ['note', 'tip', 'warning', 'danger'].includes(value) ? value : 'note';
299
+ return `<aside class="ngs-content-editor-html-callout" data-callout="${variant}"${alignment(block.attrs?.['props'])}>${ctx.renderText(block.content)}</aside>`;
300
+ };
301
+ const contentEditorToggleToHtml = (block, ctx) => `<details${settings(block)['expanded'] ? ' open' : ''}><summary>${ctx.renderText(block.content?.title ?? [])}</summary>${ctx.renderBlocks(block.content?.blocks ?? [])}</details>`;
302
+ const contentEditorAttachmentToHtml = (block, ctx) => {
303
+ const url = ctx.safeUrl(block.content?.url, 'attachment');
304
+ return url ? `<a href="${ctx.escape(url)}" download="${ctx.escape(block.content?.name)}">${ctx.escape(block.content?.name || 'Download')}</a>` : '';
305
+ };
306
+ const contentEditorGalleryToHtml = (block, ctx) => {
307
+ ctx.addStyles(CONTENT_EDITOR_GALLERY_HTML_STYLES);
308
+ return `<div class="ngs-content-editor-html-gallery" data-content-editor="gallery">${(block.content?.images ?? []).map(image => {
309
+ const src = ctx.safeUrl(image.src, 'image');
310
+ return src ? `<figure><img src="${ctx.escape(src)}" alt="${ctx.escape(image.alt)}" style="max-width:100%;height:auto">${contentEditorText(image.caption).trim() ? `<figcaption>${ctx.renderText(image.caption)}</figcaption>` : ''}</figure>` : '';
311
+ }).join('')}</div>`;
312
+ };
313
+ const contentEditorGridToHtml = (block, ctx) => {
314
+ const layout = contentEditorGridSettings(settings(block));
315
+ ctx.addStyles(CONTENT_EDITOR_GRID_HTML_STYLES);
316
+ const gap = { small: 12, medium: 24, large: 36 }[layout.gap];
317
+ return `<div class="ngs-content-editor-html-grid" style="--ngs-html-grid-columns:${layout.columns};--ngs-html-grid-gap:${gap}px"><div class="ngs-content-editor-html-grid-cells${layout.stackOnMobile ? ' ngs-content-editor-html-grid-stack' : ''}">${(block.content?.cells ?? []).map(cell => `<div class="ngs-content-editor-html-grid-cell">${ctx.renderBlocks(cell.blocks)}</div>`).join('')}</div></div>`;
318
+ };
319
+ const CONTENT_EDITOR_DEFAULT_HTML_CONVERTERS = {
320
+ paragraph: contentEditorParagraphToHtml, heading: contentEditorHeadingToHtml,
321
+ code: contentEditorCodeToHtml, divider: contentEditorDividerToHtml,
322
+ bulletList: contentEditorListToHtml, orderedList: contentEditorListToHtml,
323
+ quote: contentEditorQuoteToHtml, table: contentEditorTableToHtml,
324
+ image: contentEditorImageToHtml, video: contentEditorVideoToHtml,
325
+ embed: contentEditorEmbedToHtml, callout: contentEditorCalloutToHtml,
326
+ toggle: contentEditorToggleToHtml, attachment: contentEditorAttachmentToHtml,
327
+ gallery: contentEditorGalleryToHtml, grid: contentEditorGridToHtml
328
+ };
329
+
330
+ function escapeContentEditorHtml(value) {
331
+ return String(value ?? '').replace(/[&<>"']/g, character => ({
332
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
333
+ })[character]);
334
+ }
335
+ function safeContentEditorHtmlUrl(value, kind = 'link') {
336
+ if (typeof value !== 'string')
337
+ return null;
338
+ const url = value.trim();
339
+ if (!url || /[\u0000-\u0020\u007f]/.test(url))
340
+ return null;
341
+ if (kind === 'link')
342
+ return normalizeNgsHeadlessEditorLink(url);
343
+ if (/^https?:/i.test(url) || !/^[a-z][a-z\d+.-]*:/i.test(url))
344
+ return url;
345
+ if (kind !== 'embed' && /^blob:https?:\/\//i.test(url))
346
+ return url;
347
+ if (kind === 'attachment' && /^(mailto:|tel:)/i.test(url))
348
+ return url;
349
+ const mime = kind === 'image' ? 'image/[a-z0-9.+-]+' : kind === 'media'
350
+ ? '(?:audio|video)/[a-z0-9.+-]+' : kind === 'attachment'
351
+ ? '(?:application/(?!xhtml\\+xml|xml|javascript)[a-z0-9.+-]+|text/(?:plain|csv)|(?:image|audio|video)/[a-z0-9.+-]+)' : null;
352
+ return mime && new RegExp(`^data:${mime};base64,[a-z0-9+/=]${kind === 'attachment' ? '*' : '+'}$`, 'i').test(url) ? url : null;
353
+ }
354
+
355
+ const MARK_TAGS = {
356
+ bold: 'strong', italic: 'em', strike: 's', underline: 'u', code: 'code', superscript: 'sup', subscript: 'sub'
357
+ };
358
+ /** Pure document export: works without DOM, Angular DI, or a mounted editor. */
359
+ function contentEditorToHtml(document, config = {}) {
360
+ return serialize(document.blocks, config);
361
+ }
362
+ function contentEditorBlockToHtml(block, config = {}) {
363
+ return serialize([block], config);
364
+ }
365
+ function serialize(blocks, config) {
366
+ const styles = new Set();
367
+ const context = {
368
+ escape: escapeContentEditorHtml,
369
+ safeUrl: safeContentEditorHtmlUrl,
370
+ addStyles: css => { if (config.includeStyles !== false)
371
+ styles.add(css); },
372
+ renderBlock: block => {
373
+ const converter = config.blocks?.[block.type]?.toHtml ?? defaultConverter(block.type) ?? config.unknownBlockToHtml;
374
+ if (!converter)
375
+ throw new Error(`No HTML converter for Content Editor block "${block.type}".`);
376
+ return converter(block, context);
377
+ },
378
+ renderBlocks: children => children.map(context.renderBlock).join(''),
379
+ defaultToHtml: block => {
380
+ const converter = defaultConverter(block.type);
381
+ if (!converter)
382
+ throw new Error(`No default HTML converter for Content Editor block "${block.type}".`);
383
+ return converter(block, context);
384
+ },
385
+ renderText: text => renderText(text, context, config)
386
+ };
387
+ const html = context.renderBlocks(blocks);
388
+ return [...styles].map(css => `<style>${css}</style>`).join('') + html;
389
+ }
390
+ function renderText(text, ctx, config) {
391
+ if (!isNgsHeadlessEditorTextContent(text))
392
+ return '';
393
+ return text.map(run => run.marks.reduce((html, mark) => {
394
+ const override = config.marks && Object.hasOwn(config.marks, mark.type) ? config.marks[mark.type] : undefined;
395
+ return override ? override(html, mark, ctx) : renderMark(html, mark, ctx);
396
+ }, ctx.escape(run.text).replace(/\r\n|\r|\n/g, '<br>'))).join('');
397
+ }
398
+ function renderMark(html, mark, ctx) {
399
+ const tag = Object.hasOwn(MARK_TAGS, mark.type) ? MARK_TAGS[mark.type] : undefined;
400
+ if (tag)
401
+ return `<${tag}>${html}</${tag}>`;
402
+ if (mark.type === 'link') {
403
+ const href = ctx.safeUrl(mark.attrs?.['href']);
404
+ if (!href)
405
+ return html;
406
+ const target = mark.attrs?.['target'] === '_blank' ? '_blank' : '_self';
407
+ return `<a href="${ctx.escape(href)}" target="${target}" rel="noopener noreferrer">${html}</a>`;
414
408
  }
415
- add() {
416
- this._dialogRef.close(this.form.value);
409
+ if (mark.type === 'textColor' || mark.type === 'backgroundColor') {
410
+ const color = normalizeNgsHeadlessEditorColor(String(mark.attrs?.['color'] ?? ''));
411
+ return color ? `<span style="${mark.type === 'textColor' ? 'color' : 'background-color'}:${ctx.escape(color)}">${html}</span>` : html;
417
412
  }
418
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: EditLinkDialog, deps: [], target: i0.ɵɵFactoryTarget.Component });
419
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "22.1.7", type: EditLinkDialog, isStandalone: true, selector: "ngs-edit-link", ngImport: i0, template: "<h1 ngs-dialog-title>Edit link</h1>\n<ngs-dialog-content [formGroup]=\"form\" class=\"!overflow-hidden\">\n <ngs-form-field class=\"w-full\">\n <ngs-label>Href (Url, Tel or other)</ngs-label>\n <input ngsInput type=\"text\" formControlName=\"href\">\n <ngs-hint>To delete the link, clear this field and apply</ngs-hint>\n </ngs-form-field>\n <ngs-slide-toggle formControlName=\"openInNewTab\" class=\"mt-5\">Open link in a new tab</ngs-slide-toggle>\n</ngs-dialog-content>\n<ngs-dialog-actions>\n <button ngsButton (click)=\"cancel()\">Cancel</button>\n <button ngsButton=\"filled\"\n [disabled]=\"form.invalid\" (click)=\"add()\">Apply</button>\n</ngs-dialog-actions>\n", styles: [""], dependencies: [{ kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i1$1.DefaultValueAccessor, selector: "input:not([type=checkbox]):not([ngNoCva])[formControlName],textarea:not([ngNoCva])[formControlName],input:not([type=checkbox]):not([ngNoCva])[formControl],textarea:not([ngNoCva])[formControl],input:not([type=checkbox]):not([ngNoCva])[ngModel],textarea:not([ngNoCva])[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i1$1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1$1.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],[formArray],form:not([ngNoForm]),[ngForm]" }, { kind: "component", type: Button, selector: " button[ngsButton], button[ngsIconButton], a[ngsButton], a[ngsIconButton] ", inputs: ["ngsButton", "ngsIconButton", "loading", "disabled", "disabledInteractive", "disableRipple", "reverse", "fullWidth", "hideTextOnMobile"], exportAs: ["ngsButton"] }, { kind: "component", type: DialogActions, selector: "ngs-dialog-actions, [ngs-dialog-actions], [ngsDialogActions]", inputs: ["align"] }, { kind: "component", type: DialogContent, selector: "ngs-dialog-content,[ngs-dialog-content],[ngsDialogContent]" }, { kind: "component", type: DialogTitle, selector: "ngs-dialog-title, [ngs-dialog-title], [ngsDialogTitle]", inputs: ["id"], exportAs: ["ngsDialogTitle"] }, { kind: "component", type: FormField, selector: "ngs-form-field", inputs: ["labelMode", "subscriptHiddenIfEmpty", "sameHeightAsButton"], exportAs: ["ngsFormField"] }, { kind: "directive", type: Input, selector: "input[ngsInput], textarea[ngsInput]", inputs: ["id", "placeholder", "required", "disabled", "readonly", "errorStateMatcher"], exportAs: ["ngsInput"] }, { kind: "component", type: Label, selector: "ngs-label" }, { kind: "component", type: SlideToggle, selector: "ngs-slide-toggle", inputs: ["id", "name", "labelPosition", "aria-label", "aria-labelledby", "aria-describedby", "required", "disabled", "disableRipple", "tabIndex", "hideIcon", "color", "checked"], outputs: ["disabledChange", "checkedChange", "change", "toggleChange"], exportAs: ["ngsSlideToggle"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i1$1.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i1$1.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { kind: "component", type: Hint, selector: "ngs-hint", inputs: ["align"], exportAs: ["ngsHint"] }], changeDetection: i0.ChangeDetectionStrategy.Eager });
413
+ return html;
420
414
  }
421
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: EditLinkDialog, decorators: [{
422
- type: Component,
423
- args: [{ selector: 'ngs-edit-link', imports: [
424
- FormsModule,
425
- Button,
426
- DialogActions,
427
- DialogContent,
428
- DialogTitle,
429
- FormField,
430
- Input,
431
- Label,
432
- SlideToggle,
433
- ReactiveFormsModule,
434
- Hint
435
- ], changeDetection: ChangeDetectionStrategy.Eager, template: "<h1 ngs-dialog-title>Edit link</h1>\n<ngs-dialog-content [formGroup]=\"form\" class=\"!overflow-hidden\">\n <ngs-form-field class=\"w-full\">\n <ngs-label>Href (Url, Tel or other)</ngs-label>\n <input ngsInput type=\"text\" formControlName=\"href\">\n <ngs-hint>To delete the link, clear this field and apply</ngs-hint>\n </ngs-form-field>\n <ngs-slide-toggle formControlName=\"openInNewTab\" class=\"mt-5\">Open link in a new tab</ngs-slide-toggle>\n</ngs-dialog-content>\n<ngs-dialog-actions>\n <button ngsButton (click)=\"cancel()\">Cancel</button>\n <button ngsButton=\"filled\"\n [disabled]=\"form.invalid\" (click)=\"add()\">Apply</button>\n</ngs-dialog-actions>\n" }]
415
+ function defaultConverter(type) {
416
+ return Object.hasOwn(CONTENT_EDITOR_DEFAULT_HTML_CONVERTERS, type) ? CONTENT_EDITOR_DEFAULT_HTML_CONVERTERS[type] : undefined;
417
+ }
418
+
419
+ /** Export saved documents with the current environment's shared configuration. */
420
+ class ContentEditorHtmlSerializer {
421
+ config = inject(CONTENT_EDITOR_CONFIG);
422
+ toHtml(document, config = {}) {
423
+ return contentEditorToHtml(document, mergeContentEditorConfig(this.config, config));
424
+ }
425
+ blockToHtml(block, config = {}) {
426
+ return contentEditorBlockToHtml(block, mergeContentEditorConfig(this.config, config));
427
+ }
428
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorHtmlSerializer, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
429
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorHtmlSerializer, providedIn: 'root' });
430
+ }
431
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorHtmlSerializer, decorators: [{
432
+ type: Injectable,
433
+ args: [{ providedIn: 'root' }]
436
434
  }] });
437
435
 
438
- class TextColorComponent {
439
- _document = inject(DOCUMENT$1);
440
- recentlyUsed = model(this._getRecentlyUsed(), /* @ts-ignore */
441
- ...(ngDevMode ? [{ debugName: "recentlyUsed" }] : /* istanbul ignore next */ []));
442
- selectedTextColor = model(null, /* @ts-ignore */
443
- ...(ngDevMode ? [{ debugName: "selectedTextColor" }] : /* istanbul ignore next */ []));
444
- selectedBackgroundColor = model(null, /* @ts-ignore */
445
- ...(ngDevMode ? [{ debugName: "selectedBackgroundColor" }] : /* istanbul ignore next */ []));
446
- textColors = input([
447
- {
448
- name: 'Default',
449
- color: '',
450
- type: 'text'
451
- },
452
- {
453
- name: 'Gray',
454
- color: '#7f7f7f',
455
- type: 'text'
456
- },
457
- {
458
- name: 'Brown',
459
- color: '#ae2012',
460
- type: 'text'
461
- },
462
- {
463
- name: 'Orange',
464
- color: '#fb5607',
465
- type: 'text'
466
- },
467
- {
468
- name: 'Yellow',
469
- color: '#ffa200',
470
- type: 'text'
471
- },
472
- {
473
- name: 'Green',
474
- color: '#40916c',
475
- type: 'text'
476
- },
477
- {
478
- name: 'Blue',
479
- color: '#00bbf9',
480
- type: 'text'
481
- },
482
- {
483
- name: 'Purple',
484
- color: '#907ad6',
485
- type: 'text'
486
- },
487
- {
488
- name: 'Pink',
489
- color: '#fa3faf',
490
- type: 'text'
491
- },
492
- {
493
- name: 'Red',
494
- color: '#ef233c',
495
- type: 'text'
436
+ /** Nested renderers inherit per-instance configuration through their parent. */
437
+ const CONTENT_EDITOR_RENDER_CONFIG = new InjectionToken('CONTENT_EDITOR_RENDER_CONFIG');
438
+ const CONTENT_EDITOR_CONFIG = new InjectionToken('CONTENT_EDITOR_CONFIG', {
439
+ providedIn: 'root', factory: () => ({})
440
+ });
441
+ /** Later configurations override individual block fields, preserving unrelated options. */
442
+ function mergeContentEditorConfig(...configs) {
443
+ const result = { blocks: Object.create(null), marks: {} };
444
+ for (const config of configs) {
445
+ for (const [type, block] of Object.entries(config.blocks ?? {})) {
446
+ const previous = result.blocks[type];
447
+ result.blocks[type] = {
448
+ ...previous, ...block, options: { ...previous?.options, ...block.options }
449
+ };
496
450
  }
497
- ], /* @ts-ignore */
498
- ...(ngDevMode ? [{ debugName: "textColors" }] : /* istanbul ignore next */ []));
499
- backgroundColors = input([
500
- {
501
- name: 'Default',
502
- color: '',
503
- type: 'background'
504
- },
505
- {
506
- name: 'Gray',
507
- color: '#e9ecef',
508
- type: 'background'
509
- },
510
- {
511
- name: 'Brown',
512
- color: '#ffe0c0',
513
- type: 'background'
514
- },
515
- {
516
- name: 'Orange',
517
- color: '#ffd8c6',
518
- type: 'background'
519
- },
520
- {
521
- name: 'Yellow',
522
- color: '#fff3b0',
523
- type: 'background'
524
- },
525
- {
526
- name: 'Green',
527
- color: '#eff6e0',
528
- type: 'background'
529
- },
530
- {
531
- name: 'Blue',
532
- color: '#edf6f9',
533
- type: 'background'
534
- },
535
- {
536
- name: 'Purple',
537
- color: '#e0aaff',
538
- type: 'background'
539
- },
451
+ result.marks = { ...result.marks, ...config.marks };
452
+ if (config.draft !== undefined)
453
+ result.draft = { ...result.draft, ...config.draft };
454
+ if (config.includeStyles !== undefined)
455
+ result.includeStyles = config.includeStyles;
456
+ if (config.importMarks !== undefined)
457
+ result.importMarks = config.importMarks;
458
+ if (config.unknownBlockToHtml !== undefined)
459
+ result.unknownBlockToHtml = config.unknownBlockToHtml;
460
+ }
461
+ return result;
462
+ }
463
+ /** Application or route environment configuration. Child environments inherit parent settings. */
464
+ function provideContentEditorConfig(config = {}) {
465
+ return makeEnvironmentProviders([
540
466
  {
541
- name: 'Pink',
542
- color: '#fae0ec',
543
- type: 'background'
467
+ provide: CONTENT_EDITOR_CONFIG,
468
+ useFactory: () => mergeContentEditorConfig(inject(CONTENT_EDITOR_CONFIG, { skipSelf: true, optional: true }) ?? {}, config)
544
469
  },
545
- {
546
- name: 'Red',
547
- color: '#ffdccc',
548
- type: 'background'
549
- }
550
- ], /* @ts-ignore */
551
- ...(ngDevMode ? [{ debugName: "backgroundColors" }] : /* istanbul ignore next */ []));
552
- textColorChanged = output();
553
- backgroundColorChanged = output();
554
- selectRecentlyColor(color) {
555
- if (color.type === 'text') {
556
- this.selectTextColor(color);
557
- }
558
- else if (color.type === 'background') {
559
- this.selectBackgroundColor(color);
560
- }
561
- }
562
- selectTextColor(color) {
563
- this.selectedTextColor.set(color);
564
- this.textColorChanged.emit(color.color);
565
- this._addToRecently(color);
566
- }
567
- selectBackgroundColor(color) {
568
- this.selectedBackgroundColor.set(color);
569
- this.backgroundColorChanged.emit(color.color);
570
- this._addToRecently(color);
470
+ ContentEditorHtmlSerializer,
471
+ ContentEditorImporter
472
+ ]);
473
+ }
474
+
475
+ /** Structured failure. The editor is never modified when parsing fails. */
476
+ class ContentEditorImportError extends Error {
477
+ path;
478
+ constructor(path, message) {
479
+ super(`${path}: ${message}`);
480
+ this.path = path;
481
+ this.name = 'ContentEditorImportError';
571
482
  }
572
- _addToRecently(color) {
573
- const hasRecentlyUsed = this.recentlyUsed()
574
- .filter(recentlyColor => recentlyColor.name === color.name && recentlyColor.type === color.type)
575
- .length > 0;
576
- if (hasRecentlyUsed) {
577
- return;
578
- }
579
- let colors = [...this.recentlyUsed()];
580
- colors = colors.length >= 5 ? colors.slice(1, 5) : colors;
581
- this.recentlyUsed.set([...colors, color]);
582
- try {
583
- this._document.defaultView?.localStorage.setItem('ngsContentEditorRecentlyUsedTextColor', JSON.stringify(this.recentlyUsed()));
584
- }
585
- catch {
586
- // Keep the recent colors in memory when browser storage is unavailable.
587
- }
483
+ }
484
+
485
+ /** Parses and validates the native version-1 format without changing the caller's objects. */
486
+ function contentEditorFromJson(source, config = {}, options = {}) {
487
+ const maxDepth = options.maxDepth ?? 64;
488
+ const maxBlocks = options.maxBlocks ?? 10000;
489
+ if (!Number.isInteger(maxDepth) || maxDepth < 1 || !Number.isInteger(maxBlocks) || maxBlocks < 1) {
490
+ throw new ContentEditorImportError('$options', 'maxDepth and maxBlocks must be positive integers');
588
491
  }
589
- _getRecentlyUsed() {
492
+ let value = source;
493
+ if (typeof source === 'string') {
590
494
  try {
591
- const value = this._document.defaultView?.localStorage.getItem('ngsContentEditorRecentlyUsedTextColor');
592
- const colors = value ? JSON.parse(value) : [];
593
- return Array.isArray(colors) ? colors : [];
495
+ value = JSON.parse(source);
594
496
  }
595
497
  catch {
596
- return [];
498
+ throw new ContentEditorImportError('$', 'Invalid JSON');
597
499
  }
598
500
  }
599
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: TextColorComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
600
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.7", type: TextColorComponent, isStandalone: true, selector: "ngs-text-color", inputs: { recentlyUsed: { classPropertyName: "recentlyUsed", publicName: "recentlyUsed", isSignal: true, isRequired: false, transformFunction: null }, selectedTextColor: { classPropertyName: "selectedTextColor", publicName: "selectedTextColor", isSignal: true, isRequired: false, transformFunction: null }, selectedBackgroundColor: { classPropertyName: "selectedBackgroundColor", publicName: "selectedBackgroundColor", isSignal: true, isRequired: false, transformFunction: null }, textColors: { classPropertyName: "textColors", publicName: "textColors", isSignal: true, isRequired: false, transformFunction: null }, backgroundColors: { classPropertyName: "backgroundColors", publicName: "backgroundColors", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { recentlyUsed: "recentlyUsedChange", selectedTextColor: "selectedTextColorChange", selectedBackgroundColor: "selectedBackgroundColorChange", textColorChanged: "textColorChanged", backgroundColorChanged: "backgroundColorChanged" }, ngImport: i0, template: "@if (recentlyUsed().length > 0) {\n <div class=\"mb-5\">\n <div class=\"text-xs text-neutral-700 text-semibold\">Recently colors</div>\n <div class=\"flex gap-2 flex-wrap mt-3\">\n @for (recentlyColor of recentlyUsed(); track recentlyColor) {\n @if (recentlyColor.type === 'text') {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\"\n [style.color]=\"recentlyColor.color\" [ngsTooltip]=\"recentlyColor.name\"\n (click)=\"selectRecentlyColor(recentlyColor)\">\n <ngs-icon name=\"fluent:text-field-24-regular\"/>\n </button>\n } @else if (recentlyColor.type === 'background') {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\"\n [style.background-color]=\"recentlyColor.color\" [ngsTooltip]=\"recentlyColor.name\"\n (click)=\"selectRecentlyColor(recentlyColor)\">\n </button>\n }\n }\n </div>\n </div>\n}\n\n<div class=\"mb-5\">\n <div class=\"text-xs text-neutral-700 text-semibold\">Text color</div>\n <div class=\"flex gap-2 flex-wrap mt-3\">\n @for (textColor of textColors(); track $index) {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\n [&.is-selected]:outline [&.is-selected]:outline-primary\"\n [style.color]=\"textColor.color\" [ngsTooltip]=\"textColor.name\"\n [class.is-selected]=\"selectedTextColor()?.color === textColor.color\"\n (click)=\"selectTextColor(textColor)\">\n <ngs-icon name=\"fluent:text-field-24-regular\"/>\n </button>\n }\n </div>\n</div>\n\n<div>\n <div class=\"text-xs text-neutral-700 text-semibold\">Background color</div>\n <div class=\"flex gap-2 flex-wrap mt-3\">\n @for (backgroundColor of backgroundColors(); track $index) {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\n [&.is-selected]:outline [&.is-selected]:outline-primary\"\n [style.background-color]=\"backgroundColor.color\" [ngsTooltip]=\"backgroundColor.name\"\n [class.is-selected]=\"selectedBackgroundColor()?.color === backgroundColor.color\"\n (click)=\"selectBackgroundColor(backgroundColor)\">\n </button>\n }\n </div>\n</div>\n", styles: [":host{display:block;width:172px}\n"], dependencies: [{ kind: "component", type: Icon, selector: "ngs-icon", inputs: ["name"], exportAs: ["ngsIcon"] }, { kind: "directive", type: Tooltip, selector: "[ngsTooltip]", inputs: ["ngsTooltip", "ngsTooltipPosition", "ngsTooltipClass", "ngsTooltipShowDelay", "ngsTooltipHideDelay", "ngsTooltipOffset", "ngsTooltipPositionAtOrigin", "ngsTooltipDisabled"], exportAs: ["ngsTooltip"] }], changeDetection: i0.ChangeDetectionStrategy.Eager });
601
- }
602
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: TextColorComponent, decorators: [{
603
- type: Component,
604
- args: [{ selector: 'ngs-text-color', imports: [
605
- Icon,
606
- Tooltip
607
- ], changeDetection: ChangeDetectionStrategy.Eager, template: "@if (recentlyUsed().length > 0) {\n <div class=\"mb-5\">\n <div class=\"text-xs text-neutral-700 text-semibold\">Recently colors</div>\n <div class=\"flex gap-2 flex-wrap mt-3\">\n @for (recentlyColor of recentlyUsed(); track recentlyColor) {\n @if (recentlyColor.type === 'text') {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\"\n [style.color]=\"recentlyColor.color\" [ngsTooltip]=\"recentlyColor.name\"\n (click)=\"selectRecentlyColor(recentlyColor)\">\n <ngs-icon name=\"fluent:text-field-24-regular\"/>\n </button>\n } @else if (recentlyColor.type === 'background') {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\"\n [style.background-color]=\"recentlyColor.color\" [ngsTooltip]=\"recentlyColor.name\"\n (click)=\"selectRecentlyColor(recentlyColor)\">\n </button>\n }\n }\n </div>\n </div>\n}\n\n<div class=\"mb-5\">\n <div class=\"text-xs text-neutral-700 text-semibold\">Text color</div>\n <div class=\"flex gap-2 flex-wrap mt-3\">\n @for (textColor of textColors(); track $index) {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\n [&.is-selected]:outline [&.is-selected]:outline-primary\"\n [style.color]=\"textColor.color\" [ngsTooltip]=\"textColor.name\"\n [class.is-selected]=\"selectedTextColor()?.color === textColor.color\"\n (click)=\"selectTextColor(textColor)\">\n <ngs-icon name=\"fluent:text-field-24-regular\"/>\n </button>\n }\n </div>\n</div>\n\n<div>\n <div class=\"text-xs text-neutral-700 text-semibold\">Background color</div>\n <div class=\"flex gap-2 flex-wrap mt-3\">\n @for (backgroundColor of backgroundColors(); track $index) {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\n [&.is-selected]:outline [&.is-selected]:outline-primary\"\n [style.background-color]=\"backgroundColor.color\" [ngsTooltip]=\"backgroundColor.name\"\n [class.is-selected]=\"selectedBackgroundColor()?.color === backgroundColor.color\"\n (click)=\"selectBackgroundColor(backgroundColor)\">\n </button>\n }\n </div>\n</div>\n", styles: [":host{display:block;width:172px}\n"] }]
608
- }], propDecorators: { recentlyUsed: [{ type: i0.Input, args: [{ isSignal: true, alias: "recentlyUsed", required: false }] }, { type: i0.Output, args: ["recentlyUsedChange"] }], selectedTextColor: [{ type: i0.Input, args: [{ isSignal: true, alias: "selectedTextColor", required: false }] }, { type: i0.Output, args: ["selectedTextColorChange"] }], selectedBackgroundColor: [{ type: i0.Input, args: [{ isSignal: true, alias: "selectedBackgroundColor", required: false }] }, { type: i0.Output, args: ["selectedBackgroundColorChange"] }], textColors: [{ type: i0.Input, args: [{ isSignal: true, alias: "textColors", required: false }] }], backgroundColors: [{ type: i0.Input, args: [{ isSignal: true, alias: "backgroundColors", required: false }] }], textColorChanged: [{ type: i0.Output, args: ["textColorChanged"] }], backgroundColorChanged: [{ type: i0.Output, args: ["backgroundColorChanged"] }] } });
609
-
610
- class CommandBarComponent {
611
- editor = inject(NgsHeadlessEditor);
612
- dialog = inject(Dialog);
613
- observedElement = input(null, /* @ts-ignore */
614
- ...(ngDevMode ? [{ debugName: "observedElement" }] : /* istanbul ignore next */ []));
615
- alignment = computed(() => this.region()?.alignment() ?? 'left', /* @ts-ignore */
616
- ...(ngDevMode ? [{ debugName: "alignment" }] : /* istanbul ignore next */ []));
617
- savedSelection = null;
618
- region() { return ContentEditorContentEditableDirective.forElement(this.observedElement()); }
619
- toggleBold() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_BOLD); }
620
- toggleItalic() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_ITALIC); }
621
- toggleCode() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_CODE); }
622
- toggleStrike() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_STRIKE); }
623
- toggleUnderline() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_UNDERLINE); }
624
- toggleSuperscript() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_SUPERSCRIPT); }
625
- toggleSubscript() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_SUBSCRIPT); }
626
- isLinkActive() { return this.editor.isMarkActive('link'); }
627
- isActive(tag) {
628
- return this.editor.isMarkActive({ strong: 'bold', em: 'italic', s: 'strike', u: 'underline', sup: 'superscript', sub: 'subscript' }[tag] ?? tag);
629
- }
630
- setTextAlignment(value) { this.restoreSelection()?.setAlignment(value); }
631
- isTextAlignment(value) { return this.alignment() === value; }
632
- addLink() { this.openLinkDialog(false); }
633
- editLink() { this.openLinkDialog(true); }
634
- openLinkDialog(edit) {
635
- this.retainSelection();
636
- const saved = this.savedSelection;
637
- if (!saved)
501
+ const fail = (path, message) => { throw new ContentEditorImportError(path, message); };
502
+ const ancestors = new Set();
503
+ const copy = (input, path, depth) => {
504
+ if (depth > maxDepth)
505
+ fail(path, `Maximum nesting depth (${maxDepth}) exceeded`);
506
+ if (input === null || typeof input === 'string' || typeof input === 'boolean')
507
+ return input;
508
+ if (typeof input === 'number' && Number.isFinite(input))
509
+ return input;
510
+ if (!input || typeof input !== 'object')
511
+ return fail(path, 'Expected a JSON-compatible value');
512
+ if (ancestors.has(input))
513
+ fail(path, 'Cyclic data is not supported');
514
+ if (!Array.isArray(input) && ![Object.prototype, null].includes(Object.getPrototypeOf(input)))
515
+ fail(path, 'Expected a plain JSON object');
516
+ ancestors.add(input);
517
+ const output = Array.isArray(input)
518
+ ? Array.from(input, (item, i) => copy(item, `${path}[${i}]`, depth + 1))
519
+ : Object.fromEntries(Object.entries(input).filter(([, item]) => item !== undefined).map(([key, item]) => [key, copy(item, `${path}.${key}`, depth + 1)]));
520
+ ancestors.delete(input);
521
+ return output;
522
+ };
523
+ const object = (input, path) => {
524
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
525
+ fail(path, 'Expected an object');
526
+ return input;
527
+ };
528
+ const array = (input, path) => { if (!Array.isArray(input))
529
+ fail(path, 'Expected an array'); return input; };
530
+ const string = (input, path, nonempty = false) => {
531
+ if (typeof input !== 'string' || (nonempty && !input.trim()))
532
+ fail(path, nonempty ? 'Expected a non-empty string' : 'Expected a string');
533
+ };
534
+ const props = (input, path) => {
535
+ if (input === undefined)
638
536
  return;
639
- const target = saved.region.region.editor;
640
- const mark = target.getActiveMark('link');
641
- const ref = edit
642
- ? this.dialog.open(EditLinkDialog, { data: { href: mark?.attrs?.['href'], openInNewTab: mark?.attrs?.['target'] === '_blank' }, width: '500px', restoreFocus: false })
643
- : this.dialog.open(AddLinkDialog, { width: '500px', restoreFocus: false });
644
- ref.afterClosed().subscribe((value) => {
645
- if (!this.restoreSelection())
646
- return;
647
- if (value) {
648
- if (value.href)
649
- this.editor.execute(NGS_HEADLESS_EDITOR_SET_LINK, { href: value.href, target: value.openInNewTab ? '_blank' : '_self' });
650
- else
651
- this.editor.execute(NGS_HEADLESS_EDITOR_UNSET_LINK);
652
- }
653
- this.restoreSelectionAfterOverlay();
537
+ array(input, path).forEach((prop, i) => {
538
+ object(prop, `${path}[${i}]`);
539
+ string(prop.name, `${path}[${i}].name`, true);
540
+ string(prop.value, `${path}[${i}].value`);
654
541
  });
655
- }
656
- preserveSelection(event) {
657
- event.preventDefault();
658
- this.region()?.activate();
659
- this.retainSelection();
660
- }
661
- retainSelection() {
662
- if (this.savedSelection)
663
- return;
664
- const region = this.region();
665
- const selection = region?.region.editor.selection();
666
- if (region && selection)
667
- this.savedSelection = { region, selection };
668
- }
669
- restoreSelection() {
670
- const saved = this.savedSelection;
671
- if (!saved)
672
- return this.region();
673
- if (!this.observedElement()?.isConnected || saved.region.region.editor !== this.editor.inlineTarget())
674
- return;
675
- saved.region.region.editor.setSelection(saved.selection);
676
- return saved.region;
677
- }
678
- restoreSelectionAfterOverlay() {
679
- // MenuTrigger restores its own focus after emitting menuClosed.
680
- // Restore the editor afterwards, using model points rather than old DOM nodes.
681
- Promise.resolve().then(() => {
682
- const region = this.restoreSelection();
683
- this.savedSelection = null;
684
- if (region && this.observedElement()?.isConnected)
685
- region.focus();
542
+ };
543
+ const runs = (input, path) => {
544
+ array(input, path).forEach((run, i) => {
545
+ const p = `${path}[${i}]`;
546
+ object(run, p);
547
+ if (run.type !== 'text')
548
+ fail(`${p}.type`, 'Expected "text"');
549
+ string(run.text, `${p}.text`);
550
+ array(run.marks, `${p}.marks`).forEach((mark, j) => {
551
+ const m = `${p}.marks[${j}]`;
552
+ object(mark, m);
553
+ string(mark.type, `${m}.type`, true);
554
+ if (mark.attrs !== undefined) {
555
+ for (const [key, attr] of Object.entries(object(mark.attrs, `${m}.attrs`))) {
556
+ if (attr !== null && !['string', 'number', 'boolean'].includes(typeof attr))
557
+ fail(`${m}.attrs.${key}`, 'Expected a scalar mark attribute');
558
+ }
559
+ }
560
+ if (mark.type === 'link' && !safeContentEditorHtmlUrl(mark.attrs?.href))
561
+ fail(`${m}.attrs.href`, 'Expected a supported non-empty link URL');
562
+ if (mark.type === 'link')
563
+ enumValue(mark.attrs?.target, ['_blank', '_self'], `${m}.attrs.target`);
564
+ if (['textColor', 'backgroundColor'].includes(mark.type) && (typeof mark.attrs?.color !== 'string' || !normalizeNgsHeadlessEditorColor(mark.attrs.color)))
565
+ fail(`${m}.attrs.color`, 'Expected a supported CSS color');
566
+ });
686
567
  });
687
- }
688
- preventMenuClose(event) { event.stopPropagation(); event.preventDefault(); }
689
- onTextColorChanged(color) {
690
- const region = this.restoreSelection();
691
- if (!region)
692
- return;
693
- if (color)
694
- this.editor.execute(NGS_HEADLESS_EDITOR_SET_TEXT_COLOR, color);
695
- else
696
- this.editor.execute(NGS_HEADLESS_EDITOR_UNSET_TEXT_COLOR);
697
- region.focus();
698
- }
699
- onBackgroundColorChanged(color) {
700
- const region = this.restoreSelection();
701
- if (!region)
702
- return;
703
- if (color)
704
- this.editor.execute(NGS_HEADLESS_EDITOR_SET_BACKGROUND_COLOR, color);
705
- else
706
- this.editor.execute(NGS_HEADLESS_EDITOR_UNSET_BACKGROUND_COLOR);
707
- region.focus();
708
- }
709
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: CommandBarComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
710
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.7", type: CommandBarComponent, isStandalone: true, selector: "ngs-command-bar", inputs: { observedElement: { classPropertyName: "observedElement", publicName: "observedElement", isSignal: true, isRequired: false, transformFunction: null } }, host: { listeners: { "mousedown": "preserveSelection($event)" }, classAttribute: "ngs-command-bar" }, ngImport: i0, template: "<div class=\"flex items-center gap-1\">\n <button ngsIconButton (click)=\"toggleBold()\"\n [class.is-active]=\"isActive('strong')\">\n <ngs-icon name=\"fluent:text-bold-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleItalic()\"\n [class.is-active]=\"isActive('em')\">\n <ngs-icon name=\"fluent:text-italic-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleStrike()\"\n [class.is-active]=\"isActive('s')\">\n <ngs-icon name=\"fluent:text-strikethrough-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleUnderline()\"\n [class.is-active]=\"isActive('u')\">\n <ngs-icon name=\"fluent:text-underline-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleSuperscript()\"\n [class.is-active]=\"isActive('sup')\">\n <ngs-icon name=\"fluent:text-superscript-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleSubscript()\"\n [class.is-active]=\"isActive('sub')\">\n <ngs-icon name=\"fluent:text-subscript-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleCode()\"\n [class.is-active]=\"isActive('code')\">\n <ngs-icon name=\"fluent:code-24-regular\"/>\n </button>\n\n @if (isLinkActive()) {\n <button ngsIconButton (click)=\"editLink()\">\n <ngs-icon name=\"fluent:link-24-regular\"/>\n </button>\n } @else {\n <button ngsIconButton (click)=\"addLink()\">\n <ngs-icon name=\"fluent:link-add-24-regular\"/>\n </button>\n }\n <button ngsIconButton [ngsMenuTriggerFor]=\"alignMenu\"\n (menuOpened)=\"retainSelection()\" (menuClosed)=\"restoreSelectionAfterOverlay()\">\n @switch (alignment()) {\n @case ('left') {\n <ngs-icon name=\"fluent:text-align-left-24-regular\"/>\n }\n @case ('center') {\n <ngs-icon name=\"fluent:text-align-center-24-regular\"/>\n }\n @case ('right') {\n <ngs-icon name=\"fluent:text-align-right-24-regular\"/>\n }\n }\n </button>\n <button ngsIconButton [ngsMenuTriggerFor]=\"formatColorText\"\n (menuOpened)=\"retainSelection()\" (menuClosed)=\"restoreSelectionAfterOverlay()\">\n <ngs-icon name=\"fluent:text-color-24-regular\"/>\n </button>\n</div>\n\n<ngs-menu #alignMenu=\"ngsMenu\">\n <button class=\"[&.is-active]:!bg-secondary-container\"\n [class.is-active]=\"isTextAlignment('left')\"\n ngs-menu-item\n (click)=\"setTextAlignment('left')\">\n <ngs-icon name=\"fluent:text-align-left-24-regular\"/>\n Align Left\n </button>\n <button class=\"[&.is-active]:!bg-secondary-container\"\n [class.is-active]=\"isTextAlignment('center')\"\n ngs-menu-item\n (click)=\"setTextAlignment('center')\">\n <ngs-icon name=\"fluent:text-align-center-24-regular\"/>\n Align Center\n </button>\n <button class=\"[&.is-active]:!bg-secondary-container\"\n [class.is-active]=\"isTextAlignment('right')\"\n ngs-menu-item (click)=\"setTextAlignment('right')\">\n <ngs-icon name=\"fluent:text-align-right-24-regular\"/>\n Align Right\n </button>\n</ngs-menu>\n\n<ngs-menu #formatColorText=\"ngsMenu\">\n <div class=\"px-4 py-3\" (mousedown)=\"preventMenuClose($event)\">\n <ngs-text-color (textColorChanged)=\"onTextColorChanged($event)\"\n (backgroundColorChanged)=\"onBackgroundColorChanged($event)\"/>\n </div>\n</ngs-menu>\n", styles: [":host{background:var(--ngs-color-on-surface);color:var(--ngs-color-surface);border-radius:calc(var(--spacing, .25rem) * 3);padding:var(--spacing, .25rem);box-shadow:var(--ngs-shadow-lg)}:host button[ngsIconButton]{--ngs-button-color: var(--ngs-color-surface);--ngs-button-hover-bg: var(--ngs-color-surface);--ngs-state-focus-ring: var(--ngs-color-surface)}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton]{--ngs-button-hover-bg: color-mix(in srgb, var(--ngs-color-surface) 12%, transparent)}}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton]{--ngs-state-focus-ring: color-mix(in srgb, var(--ngs-color-surface) 40%, transparent)}}:host button[ngsIconButton].is-active{--ngs-button-bg: var(--ngs-color-surface);--ngs-button-hover-bg: var(--ngs-color-surface)}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton].is-active{--ngs-button-bg: color-mix(in srgb, var(--ngs-color-surface) 20%, transparent)}}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton].is-active{--ngs-button-hover-bg: color-mix(in srgb, var(--ngs-color-surface) 28%, transparent)}}\n/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n"], dependencies: [{ kind: "component", type: Button, selector: " button[ngsButton], button[ngsIconButton], a[ngsButton], a[ngsIconButton] ", inputs: ["ngsButton", "ngsIconButton", "loading", "disabled", "disabledInteractive", "disableRipple", "reverse", "fullWidth", "hideTextOnMobile"], exportAs: ["ngsButton"] }, { kind: "component", type: Icon, selector: "ngs-icon", inputs: ["name"], exportAs: ["ngsIcon"] }, { kind: "component", type: Menu, selector: "ngs-menu", inputs: ["role", "classList", "xPosition", "yPosition", "pushIntoViewport"], outputs: ["closed"], exportAs: ["ngsMenu"] }, { kind: "component", type: MenuItem, selector: "ngs-menu-item, [ngs-menu-item]", inputs: ["disabled", "role", "selected"], outputs: ["_triggered"], exportAs: ["ngsMenuItem"] }, { kind: "directive", type: MenuTrigger, selector: "[ngsMenuTriggerFor]", inputs: ["ngsMenuTriggerFor", "ngsMenuTriggerData", "ngsMenuDisabled", "xPosition", "yPosition", "ngsMenuTriggerRestoreFocus"], outputs: ["menuOpened", "menuClosed"], exportAs: ["ngsMenuTrigger"] }, { kind: "component", type: TextColorComponent, selector: "ngs-text-color", inputs: ["recentlyUsed", "selectedTextColor", "selectedBackgroundColor", "textColors", "backgroundColors"], outputs: ["recentlyUsedChange", "selectedTextColorChange", "selectedBackgroundColorChange", "textColorChanged", "backgroundColorChanged"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
711
- }
712
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: CommandBarComponent, decorators: [{
713
- type: Component,
714
- args: [{ selector: 'ngs-command-bar', imports: [Button, Icon, Menu, MenuItem, MenuTrigger, TextColorComponent], changeDetection: ChangeDetectionStrategy.OnPush, host: {
715
- 'class': 'ngs-command-bar',
716
- '(mousedown)': 'preserveSelection($event)'
717
- }, template: "<div class=\"flex items-center gap-1\">\n <button ngsIconButton (click)=\"toggleBold()\"\n [class.is-active]=\"isActive('strong')\">\n <ngs-icon name=\"fluent:text-bold-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleItalic()\"\n [class.is-active]=\"isActive('em')\">\n <ngs-icon name=\"fluent:text-italic-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleStrike()\"\n [class.is-active]=\"isActive('s')\">\n <ngs-icon name=\"fluent:text-strikethrough-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleUnderline()\"\n [class.is-active]=\"isActive('u')\">\n <ngs-icon name=\"fluent:text-underline-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleSuperscript()\"\n [class.is-active]=\"isActive('sup')\">\n <ngs-icon name=\"fluent:text-superscript-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleSubscript()\"\n [class.is-active]=\"isActive('sub')\">\n <ngs-icon name=\"fluent:text-subscript-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleCode()\"\n [class.is-active]=\"isActive('code')\">\n <ngs-icon name=\"fluent:code-24-regular\"/>\n </button>\n\n @if (isLinkActive()) {\n <button ngsIconButton (click)=\"editLink()\">\n <ngs-icon name=\"fluent:link-24-regular\"/>\n </button>\n } @else {\n <button ngsIconButton (click)=\"addLink()\">\n <ngs-icon name=\"fluent:link-add-24-regular\"/>\n </button>\n }\n <button ngsIconButton [ngsMenuTriggerFor]=\"alignMenu\"\n (menuOpened)=\"retainSelection()\" (menuClosed)=\"restoreSelectionAfterOverlay()\">\n @switch (alignment()) {\n @case ('left') {\n <ngs-icon name=\"fluent:text-align-left-24-regular\"/>\n }\n @case ('center') {\n <ngs-icon name=\"fluent:text-align-center-24-regular\"/>\n }\n @case ('right') {\n <ngs-icon name=\"fluent:text-align-right-24-regular\"/>\n }\n }\n </button>\n <button ngsIconButton [ngsMenuTriggerFor]=\"formatColorText\"\n (menuOpened)=\"retainSelection()\" (menuClosed)=\"restoreSelectionAfterOverlay()\">\n <ngs-icon name=\"fluent:text-color-24-regular\"/>\n </button>\n</div>\n\n<ngs-menu #alignMenu=\"ngsMenu\">\n <button class=\"[&.is-active]:!bg-secondary-container\"\n [class.is-active]=\"isTextAlignment('left')\"\n ngs-menu-item\n (click)=\"setTextAlignment('left')\">\n <ngs-icon name=\"fluent:text-align-left-24-regular\"/>\n Align Left\n </button>\n <button class=\"[&.is-active]:!bg-secondary-container\"\n [class.is-active]=\"isTextAlignment('center')\"\n ngs-menu-item\n (click)=\"setTextAlignment('center')\">\n <ngs-icon name=\"fluent:text-align-center-24-regular\"/>\n Align Center\n </button>\n <button class=\"[&.is-active]:!bg-secondary-container\"\n [class.is-active]=\"isTextAlignment('right')\"\n ngs-menu-item (click)=\"setTextAlignment('right')\">\n <ngs-icon name=\"fluent:text-align-right-24-regular\"/>\n Align Right\n </button>\n</ngs-menu>\n\n<ngs-menu #formatColorText=\"ngsMenu\">\n <div class=\"px-4 py-3\" (mousedown)=\"preventMenuClose($event)\">\n <ngs-text-color (textColorChanged)=\"onTextColorChanged($event)\"\n (backgroundColorChanged)=\"onBackgroundColorChanged($event)\"/>\n </div>\n</ngs-menu>\n", styles: [":host{background:var(--ngs-color-on-surface);color:var(--ngs-color-surface);border-radius:calc(var(--spacing, .25rem) * 3);padding:var(--spacing, .25rem);box-shadow:var(--ngs-shadow-lg)}:host button[ngsIconButton]{--ngs-button-color: var(--ngs-color-surface);--ngs-button-hover-bg: var(--ngs-color-surface);--ngs-state-focus-ring: var(--ngs-color-surface)}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton]{--ngs-button-hover-bg: color-mix(in srgb, var(--ngs-color-surface) 12%, transparent)}}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton]{--ngs-state-focus-ring: color-mix(in srgb, var(--ngs-color-surface) 40%, transparent)}}:host button[ngsIconButton].is-active{--ngs-button-bg: var(--ngs-color-surface);--ngs-button-hover-bg: var(--ngs-color-surface)}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton].is-active{--ngs-button-bg: color-mix(in srgb, var(--ngs-color-surface) 20%, transparent)}}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton].is-active{--ngs-button-hover-bg: color-mix(in srgb, var(--ngs-color-surface) 28%, transparent)}}\n/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n"] }]
718
- }], propDecorators: { observedElement: [{ type: i0.Input, args: [{ isSignal: true, alias: "observedElement", required: false }] }] } });
719
-
720
- const CONTENT_BUILDER = new InjectionToken('CONTENT_BUILDER');
721
- const CONTENT_EDITOR_BLOCK = new InjectionToken('CONTENT_EDITOR_BLOCK');
722
-
723
- /** Shared marks and commands for content editing and read-only rendering. */
724
- function provideContentEditor() {
725
- return provideNgsHeadlessEditor(withHeadlessEditorPlugin(basicTextEditorPlugin()), withHeadlessEditorPlugin(colorEditorPlugin()), withHeadlessEditorPlugin(linkEditorPlugin()));
726
- }
727
-
728
- function getTextAlignment(props) {
729
- const value = props?.find(prop => prop.name === 'text-alignment')?.value;
730
- if (value === 'center' || value === 'right' || value === 'justify') {
731
- return value;
732
- }
733
- return 'left';
734
- }
735
- function getDimensionAttribute(value) {
736
- if (typeof value === 'number' && Number.isFinite(value)) {
737
- return value;
738
- }
739
- if (typeof value === 'string') {
740
- const trimmed = value.trim();
741
- if (!trimmed || trimmed === 'auto') {
742
- return null;
743
- }
744
- const parsed = Number.parseFloat(trimmed);
745
- return Number.isFinite(parsed) ? parsed : null;
746
- }
747
- return null;
748
- }
749
-
750
- /** Defaults shared by editing and read-only layout. */
751
- function contentEditorGridSettings(settings) {
752
- return {
753
- columns: settings.columns === 3 || settings.columns === 4 ? settings.columns : 2,
754
- gap: settings.gap === 'small' || settings.gap === 'large' ? settings.gap : 'medium',
755
- stackOnMobile: settings.stackOnMobile !== false
756
568
  };
757
- }
758
-
759
- /** Plain HTML layout styles, independent of Angular and the component library's theme. */
760
- const CONTENT_EDITOR_GRID_HTML_STYLES = `.ngs-content-editor-html-grid{container-type:inline-size}.ngs-content-editor-html-grid-cells{display:grid;grid-template-columns:repeat(var(--ngs-html-grid-columns),minmax(0,1fr));gap:var(--ngs-html-grid-gap)}.ngs-content-editor-html-grid-cell{min-width:0}@container(max-width:480px){.ngs-content-editor-html-grid-stack{grid-template-columns:minmax(0,1fr)}}`;
761
- const CONTENT_EDITOR_CALLOUT_HTML_STYLES = `.ngs-content-editor-html-callout{padding:16px;border-radius:8px;background:var(--ngs-color-primary-container,#eef3ff);color:var(--ngs-color-on-surface,#172033)}.ngs-content-editor-html-callout[data-callout=tip]{background:var(--ngs-color-success-container,#e8f5ee)}.ngs-content-editor-html-callout[data-callout=warning]{background:var(--ngs-color-warning-container,#fff3dc)}.ngs-content-editor-html-callout[data-callout=danger]{background:var(--ngs-color-danger-container,#fdeaea)}`;
762
- const CONTENT_EDITOR_GALLERY_HTML_STYLES = `.ngs-content-editor-html-gallery{display:flex;overflow-x:auto;scroll-snap-type:x mandatory;gap:16px}.ngs-content-editor-html-gallery>figure{flex:0 0 100%;min-width:0;margin:0;scroll-snap-align:start}.ngs-content-editor-html-gallery img{display:block;width:100%}`;
763
- function settings(block) { return block.attrs?.['settings'] ?? {}; }
764
- function alignment(props) {
765
- const align = getTextAlignment(props);
766
- return align === 'left' ? '' : ` style="text-align:${align}"`;
767
- }
768
- function dimension(name, value) {
769
- const number = getDimensionAttribute(value);
770
- return number !== null && number > 0 ? ` ${name}="${Math.round(number)}"` : '';
771
- }
772
- const contentEditorParagraphToHtml = (block, ctx) => `<p${alignment(block.attrs?.['props'])}>${ctx.renderText(block.content)}</p>`;
773
- const contentEditorHeadingToHtml = (block, ctx) => {
774
- const value = settings(block)['level'];
775
- const level = Number.isInteger(value) && value >= 1 && value <= 6 ? value : 2;
776
- return `<h${level}${alignment(block.attrs?.['props'])}>${ctx.renderText(block.content)}</h${level}>`;
777
- };
778
- const contentEditorCodeToHtml = (block, ctx) => `<pre><code data-language="${ctx.escape(settings(block)['language'] ?? 'none')}">${ctx.escape(contentEditorText(block.content))}</code></pre>`;
779
- const contentEditorDividerToHtml = () => '<hr>';
780
- const contentEditorListToHtml = (block, ctx) => {
781
- const tag = block.type === 'orderedList' ? 'ol' : 'ul';
782
- const list = (items) => `<${tag}>${items.map(item => `<li${alignment(item.props)}>${ctx.renderText(item.content)}${item.children?.length ? list(item.children) : ''}</li>`).join('')}</${tag}>`;
783
- return list(block.content ?? []);
784
- };
785
- const contentEditorQuoteToHtml = (block, ctx) => {
786
- const quote = block.content?.cite;
787
- const caption = block.content?.caption;
788
- return `<figure><blockquote${alignment(quote?.props)}>${ctx.renderText(quote?.content ?? [])}</blockquote>${contentEditorText(caption?.content).trim() ? `<figcaption${alignment(caption.props)}>${ctx.renderText(caption.content)}</figcaption>` : ''}</figure>`;
789
- };
790
- const contentEditorTableToHtml = (block, ctx) => {
791
- const table = getNgsHeadlessEditorTableData(block);
792
- const metadata = block.attrs?.['cellMetadata'];
793
- const rows = table.rows.map((row, r) => `<tr>${row.map((runs, c) => {
794
- const tag = r === 0 && table.header ? 'th' : 'td';
795
- const cell = metadata?.[r]?.[c];
796
- return `<${tag}${dimension('colspan', cell?.options?.['colspan'])}${dimension('rowspan', cell?.options?.['rowspan'])}${dimension('width', cell?.options?.['width'])}${alignment(cell?.props)}>${ctx.renderText(runs)}</${tag}>`;
797
- }).join('')}</tr>`).join('');
798
- return `<table><tbody>${rows}</tbody></table>`;
799
- };
800
- const contentEditorImageToHtml = (block, ctx) => {
801
- const src = ctx.safeUrl(block.content?.src, 'image');
802
- if (!src)
803
- return '';
804
- const alt = block.content?.alt ?? '';
805
- const config = settings(block);
806
- return `<figure><img src="${ctx.escape(src)}" alt="${ctx.escape(alt)}"${dimension('width', config['width'])}${dimension('height', config['height'])} style="max-width:100%;height:auto">${alt ? `<figcaption>${ctx.escape(alt)}</figcaption>` : ''}</figure>`;
807
- };
808
- const contentEditorVideoToHtml = (block, ctx) => {
809
- const src = ctx.safeUrl(block.content?.src, 'media');
810
- if (!src)
811
- return '';
812
- const config = settings(block);
813
- return `<figure><video src="${ctx.escape(src)}" controls${dimension('width', config['width'])}${dimension('height', config['height'])} style="max-width:100%"></video>${block.content?.caption ? `<figcaption>${ctx.escape(block.content.caption)}</figcaption>` : ''}</figure>`;
814
- };
815
- const contentEditorEmbedToHtml = (block, ctx) => {
816
- const src = ctx.safeUrl(block.content?.url, 'embed');
817
- if (!src)
818
- return '';
819
- const config = settings(block);
820
- return `<figure><iframe src="${ctx.escape(src)}" title="${ctx.escape(block.content?.type || 'Embedded content')}"${dimension('width', config['width'] ?? 700)}${dimension('height', config['height'] ?? 400)} style="max-width:100%" allowfullscreen></iframe></figure>`;
821
- };
822
- const contentEditorCalloutToHtml = (block, ctx) => {
823
- ctx.addStyles(CONTENT_EDITOR_CALLOUT_HTML_STYLES);
824
- const value = settings(block)['variant'];
825
- const variant = ['note', 'tip', 'warning', 'danger'].includes(value) ? value : 'note';
826
- return `<aside class="ngs-content-editor-html-callout" data-callout="${variant}"${alignment(block.attrs?.['props'])}>${ctx.renderText(block.content)}</aside>`;
827
- };
828
- const contentEditorToggleToHtml = (block, ctx) => `<details${settings(block)['expanded'] ? ' open' : ''}><summary>${ctx.renderText(block.content?.title ?? [])}</summary>${ctx.renderBlocks(block.content?.blocks ?? [])}</details>`;
829
- const contentEditorAttachmentToHtml = (block, ctx) => {
830
- const url = ctx.safeUrl(block.content?.url, 'attachment');
831
- return url ? `<a href="${ctx.escape(url)}" download="${ctx.escape(block.content?.name)}">${ctx.escape(block.content?.name || 'Download')}</a>` : '';
832
- };
833
- const contentEditorGalleryToHtml = (block, ctx) => {
834
- ctx.addStyles(CONTENT_EDITOR_GALLERY_HTML_STYLES);
835
- return `<div class="ngs-content-editor-html-gallery" data-content-editor="gallery">${(block.content?.images ?? []).map(image => {
836
- const src = ctx.safeUrl(image.src, 'image');
837
- return src ? `<figure><img src="${ctx.escape(src)}" alt="${ctx.escape(image.alt)}" style="max-width:100%;height:auto">${contentEditorText(image.caption).trim() ? `<figcaption>${ctx.renderText(image.caption)}</figcaption>` : ''}</figure>` : '';
838
- }).join('')}</div>`;
839
- };
840
- const contentEditorGridToHtml = (block, ctx) => {
841
- const layout = contentEditorGridSettings(settings(block));
842
- ctx.addStyles(CONTENT_EDITOR_GRID_HTML_STYLES);
843
- const gap = { small: 12, medium: 24, large: 36 }[layout.gap];
844
- return `<div class="ngs-content-editor-html-grid" style="--ngs-html-grid-columns:${layout.columns};--ngs-html-grid-gap:${gap}px"><div class="ngs-content-editor-html-grid-cells${layout.stackOnMobile ? ' ngs-content-editor-html-grid-stack' : ''}">${(block.content?.cells ?? []).map(cell => `<div class="ngs-content-editor-html-grid-cell">${ctx.renderBlocks(cell.blocks)}</div>`).join('')}</div></div>`;
845
- };
846
- const CONTENT_EDITOR_DEFAULT_HTML_CONVERTERS = {
847
- paragraph: contentEditorParagraphToHtml, heading: contentEditorHeadingToHtml,
848
- code: contentEditorCodeToHtml, divider: contentEditorDividerToHtml,
849
- bulletList: contentEditorListToHtml, orderedList: contentEditorListToHtml,
850
- quote: contentEditorQuoteToHtml, table: contentEditorTableToHtml,
851
- image: contentEditorImageToHtml, video: contentEditorVideoToHtml,
852
- embed: contentEditorEmbedToHtml, callout: contentEditorCalloutToHtml,
853
- toggle: contentEditorToggleToHtml, attachment: contentEditorAttachmentToHtml,
854
- gallery: contentEditorGalleryToHtml, grid: contentEditorGridToHtml
855
- };
856
-
857
- const CONTENT_EDITOR_EXTRA_BLOCK_DEFS = [
858
- {
859
- type: 'callout', component: () => import('./ngstarter-ui-components-content-editor-callout-block-Jbf8h2yz.mjs').then(m => m.ContentEditorCalloutBlock),
860
- empty: () => ({ content: [createNgsHeadlessEditorText()], settings: { variant: 'note' } }), options: {}
861
- },
862
- {
863
- type: 'toggle', component: () => import('./ngstarter-ui-components-content-editor-toggle-block-B46YeMGQ.mjs').then(m => m.ContentEditorToggleBlock),
864
- empty: () => ({ content: { title: [], blocks: [emptyParagraph()] }, settings: { expanded: true } }), options: {}
865
- },
866
- {
867
- type: 'attachment', component: () => import('./ngstarter-ui-components-content-editor-attachment-block-DlUkhwCu.mjs').then(m => m.ContentEditorAttachmentBlock),
868
- empty: () => ({ content: { url: '', name: '', size: 0, mimeType: '' }, settings: {} }),
869
- options: { uploadFn: (_file, dataUrl) => Promise.resolve(dataUrl) }
870
- },
871
- {
872
- type: 'gallery', component: () => import('./ngstarter-ui-components-content-editor-gallery-block-C4p-S0Do.mjs').then(m => m.ContentEditorGalleryBlock),
873
- empty: () => ({ content: { images: [] }, settings: {} }),
874
- options: { uploadFn: (_file, dataUrl) => Promise.resolve(dataUrl) }
875
- },
876
- {
877
- type: 'grid', component: () => import('./ngstarter-ui-components-content-editor-grid-block-Cdq_Dcv2.mjs').then(m => m.ContentEditorGridBlock),
878
- empty: () => ({ content: { cells: Array.from({ length: 4 }, emptyGridCell) }, settings: { columns: 2, gap: 'medium', stackOnMobile: true } }), options: {}
879
- }
880
- ].map(def => ({ ...def, toHtml: CONTENT_EDITOR_DEFAULT_HTML_CONVERTERS[def.type] }));
881
- function emptyParagraph() {
882
- return { id: createNgsHeadlessEditorId('paragraph'), type: 'paragraph', content: [createNgsHeadlessEditorText()] };
883
- }
884
- function emptyGridCell() { return { id: createNgsHeadlessEditorId('cell'), blocks: [emptyParagraph()] }; }
885
- const CONTENT_EDITOR_EXTRA_SUGGESTIONS = [
886
- { type: 'heading', title: 'Content & layout' },
887
- ...[
888
- ['callout', 'Callout', 'Notes, tips and warnings', 'fluent:info-24-regular'],
889
- ['toggle', 'Toggle', 'Collapsible content with nested blocks', 'fluent:chevron-down-24-regular'],
890
- ['attachment', 'Attachment', 'Upload a file for download', 'fluent:attach-24-regular'],
891
- ['gallery', 'Gallery', 'Image carousel with captions', 'fluent:image-multiple-24-regular'],
892
- ['grid', 'Grid', 'Responsive grid with nested blocks', 'fluent:grid-24-regular']
893
- ].map(([blockType, title, description, iconName]) => ({ type: 'item', blockType, title, description, iconName, blockSettings: {} }))
894
- ];
895
-
896
- function escapeContentEditorHtml(value) {
897
- return String(value ?? '').replace(/[&<>"']/g, character => ({
898
- '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
899
- })[character]);
900
- }
901
- function safeContentEditorHtmlUrl(value, kind = 'link') {
902
- if (typeof value !== 'string')
903
- return null;
904
- const url = value.trim();
905
- if (!url || /[\u0000-\u0020\u007f]/.test(url))
906
- return null;
907
- if (kind === 'link')
908
- return normalizeNgsHeadlessEditorLink(url);
909
- if (/^https?:/i.test(url) || !/^[a-z][a-z\d+.-]*:/i.test(url))
910
- return url;
911
- if (kind !== 'embed' && /^blob:https?:\/\//i.test(url))
912
- return url;
913
- if (kind === 'attachment' && /^(mailto:|tel:)/i.test(url))
914
- return url;
915
- const mime = kind === 'image' ? 'image/[a-z0-9.+-]+' : kind === 'media'
916
- ? '(?:audio|video)/[a-z0-9.+-]+' : kind === 'attachment'
917
- ? '(?:application/(?!xhtml\\+xml|xml|javascript)[a-z0-9.+-]+|text/(?:plain|csv)|(?:image|audio|video)/[a-z0-9.+-]+)' : null;
918
- return mime && new RegExp(`^data:${mime};base64,[a-z0-9+/=]${kind === 'attachment' ? '*' : '+'}$`, 'i').test(url) ? url : null;
919
- }
920
-
921
- const MARK_TAGS = {
922
- bold: 'strong', italic: 'em', strike: 's', underline: 'u', code: 'code', superscript: 'sup', subscript: 'sub'
923
- };
924
- /** Pure document export: works without DOM, Angular DI, or a mounted editor. */
925
- function contentEditorToHtml(document, config = {}) {
926
- return serialize(document.blocks, config);
927
- }
928
- function contentEditorBlockToHtml(block, config = {}) {
929
- return serialize([block], config);
930
- }
931
- function serialize(blocks, config) {
932
- const styles = new Set();
933
- const context = {
934
- escape: escapeContentEditorHtml,
935
- safeUrl: safeContentEditorHtmlUrl,
936
- addStyles: css => { if (config.includeStyles !== false)
937
- styles.add(css); },
938
- renderBlock: block => {
939
- const converter = config.blocks?.[block.type]?.toHtml ?? defaultConverter(block.type) ?? config.unknownBlockToHtml;
940
- if (!converter)
941
- throw new Error(`No HTML converter for Content Editor block "${block.type}".`);
942
- return converter(block, context);
943
- },
944
- renderBlocks: children => children.map(context.renderBlock).join(''),
945
- defaultToHtml: block => {
946
- const converter = defaultConverter(block.type);
947
- if (!converter)
948
- throw new Error(`No default HTML converter for Content Editor block "${block.type}".`);
949
- return converter(block, context);
950
- },
951
- renderText: text => renderText(text, context, config)
569
+ const enumValue = (input, allowed, path) => {
570
+ if (input !== undefined && !allowed.includes(input))
571
+ fail(path, `Expected one of: ${allowed.join(', ')}`);
952
572
  };
953
- const html = context.renderBlocks(blocks);
954
- return [...styles].map(css => `<style>${css}</style>`).join('') + html;
955
- }
956
- function renderText(text, ctx, config) {
957
- if (!isNgsHeadlessEditorTextContent(text))
958
- return '';
959
- return text.map(run => run.marks.reduce((html, mark) => {
960
- const override = config.marks && Object.hasOwn(config.marks, mark.type) ? config.marks[mark.type] : undefined;
961
- return override ? override(html, mark, ctx) : renderMark(html, mark, ctx);
962
- }, ctx.escape(run.text).replace(/\r\n|\r|\n/g, '<br>'))).join('');
963
- }
964
- function renderMark(html, mark, ctx) {
965
- const tag = Object.hasOwn(MARK_TAGS, mark.type) ? MARK_TAGS[mark.type] : undefined;
966
- if (tag)
967
- return `<${tag}>${html}</${tag}>`;
968
- if (mark.type === 'link') {
969
- const href = ctx.safeUrl(mark.attrs?.['href']);
970
- if (!href)
971
- return html;
972
- const target = mark.attrs?.['target'] === '_blank' ? '_blank' : '_self';
973
- return `<a href="${ctx.escape(href)}" target="${target}" rel="noopener noreferrer">${html}</a>`;
974
- }
975
- if (mark.type === 'textColor' || mark.type === 'backgroundColor') {
976
- const color = normalizeNgsHeadlessEditorColor(String(mark.attrs?.['color'] ?? ''));
977
- return color ? `<span style="${mark.type === 'textColor' ? 'color' : 'background-color'}:${ctx.escape(color)}">${html}</span>` : html;
978
- }
979
- return html;
980
- }
981
- function defaultConverter(type) {
982
- return Object.hasOwn(CONTENT_EDITOR_DEFAULT_HTML_CONVERTERS, type) ? CONTENT_EDITOR_DEFAULT_HTML_CONVERTERS[type] : undefined;
983
- }
984
-
985
- /** Export saved documents with the current environment's shared configuration. */
986
- class ContentEditorHtmlSerializer {
987
- config = inject(CONTENT_EDITOR_CONFIG);
988
- toHtml(document, config = {}) {
989
- return contentEditorToHtml(document, mergeContentEditorConfig(this.config, config));
990
- }
991
- blockToHtml(block, config = {}) {
992
- return contentEditorBlockToHtml(block, mergeContentEditorConfig(this.config, config));
993
- }
994
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorHtmlSerializer, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
995
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorHtmlSerializer, providedIn: 'root' });
573
+ const dimension = (input, path) => {
574
+ if (input !== undefined && input !== null && input !== 'auto' && !(typeof input === 'number' && Number.isFinite(input) && input > 0))
575
+ fail(path, 'Expected a positive pixel dimension, "auto", or null');
576
+ };
577
+ const usedIds = new Set();
578
+ let count = 0;
579
+ const list = (input, path) => {
580
+ array(input, path).forEach((item, i) => {
581
+ const p = `${path}[${i}]`;
582
+ object(item, p);
583
+ runs(item.content, `${p}.content`);
584
+ props(item.props, `${p}.props`);
585
+ list(item.children, `${p}.children`);
586
+ });
587
+ };
588
+ const blocks = (input, path) => {
589
+ array(input, path).forEach((block, i) => {
590
+ const p = `${path}[${i}]`;
591
+ object(block, p);
592
+ if (++count > maxBlocks)
593
+ fail(p, `Maximum block count (${maxBlocks}) exceeded`);
594
+ string(block.id, `${p}.id`, true);
595
+ string(block.type, `${p}.type`, true);
596
+ if (usedIds.has(block.id))
597
+ fail(`${p}.id`, `Duplicate block ID "${block.id}"`);
598
+ usedIds.add(block.id);
599
+ if (!Object.hasOwn(block, 'content'))
600
+ fail(`${p}.content`, 'Required field');
601
+ const attrs = block.attrs === undefined ? {} : object(block.attrs, `${p}.attrs`);
602
+ const settings = attrs['settings'] === undefined ? {} : object(attrs['settings'], `${p}.attrs.settings`);
603
+ props(attrs['props'], `${p}.attrs.props`);
604
+ const c = block.content;
605
+ const cp = `${p}.content`;
606
+ const sp = `${p}.attrs.settings`;
607
+ switch (block.type) {
608
+ case 'paragraph':
609
+ case 'heading':
610
+ case 'code':
611
+ case 'callout':
612
+ runs(c, cp);
613
+ if (block.type === 'heading')
614
+ enumValue(settings['level'], [1, 2, 3, 4, 5, 6], `${sp}.level`);
615
+ if (block.type === 'code' && settings['language'] !== undefined)
616
+ string(settings['language'], `${sp}.language`);
617
+ if (block.type === 'callout')
618
+ enumValue(settings['variant'], ['note', 'tip', 'warning', 'danger'], `${sp}.variant`);
619
+ break;
620
+ case 'divider':
621
+ if (c !== null)
622
+ fail(cp, 'Divider content must be null');
623
+ break;
624
+ case 'bulletList':
625
+ case 'orderedList':
626
+ list(c, cp);
627
+ enumValue(settings['listStyle'], ['bullet', 'ordered'], `${sp}.listStyle`);
628
+ break;
629
+ case 'quote':
630
+ object(c, cp);
631
+ for (const name of ['cite', 'caption']) {
632
+ object(c[name], `${cp}.${name}`);
633
+ runs(c[name].content, `${cp}.${name}.content`);
634
+ props(c[name].props, `${cp}.${name}.props`);
635
+ }
636
+ break;
637
+ case 'table':
638
+ if (c !== null)
639
+ fail(cp, 'Native table content must be null; use attrs.rows');
640
+ if (array(attrs['rows'], `${p}.attrs.rows`).length > 500)
641
+ fail(`${p}.attrs.rows`, 'Tables support at most 500 rows');
642
+ attrs['rows'].forEach((row, r) => {
643
+ if (array(row, `${p}.attrs.rows[${r}]`).length > 50)
644
+ fail(`${p}.attrs.rows[${r}]`, 'Tables support at most 50 columns');
645
+ row.forEach((cell, col) => runs(cell, `${p}.attrs.rows[${r}][${col}]`));
646
+ });
647
+ enumValue(attrs['header'], [true, false], `${p}.attrs.header`);
648
+ if (attrs['cellMetadata'] !== undefined)
649
+ array(attrs['cellMetadata'], `${p}.attrs.cellMetadata`).forEach((row, r) => array(row, `${p}.attrs.cellMetadata[${r}]`).forEach((cell, col) => {
650
+ const mp = `${p}.attrs.cellMetadata[${r}][${col}]`;
651
+ object(cell, mp);
652
+ props(cell.props, `${mp}.props`);
653
+ if (cell.options !== undefined) {
654
+ const opts = object(cell.options, `${mp}.options`);
655
+ for (const key of ['colspan', 'rowspan'])
656
+ if (opts[key] !== undefined && !(Number.isInteger(opts[key]) && opts[key] > 0))
657
+ fail(`${mp}.options.${key}`, 'Expected a positive integer');
658
+ dimension(opts['width'], `${mp}.options.width`);
659
+ }
660
+ }));
661
+ break;
662
+ case 'image':
663
+ case 'video':
664
+ case 'embed':
665
+ case 'attachment':
666
+ object(c, cp);
667
+ for (const key of block.type === 'image' ? ['src', 'alt'] : block.type === 'video' ? ['src', 'caption'] : block.type === 'embed' ? ['url', 'type'] : ['url', 'name', 'mimeType'])
668
+ string(c[key], `${cp}.${key}`);
669
+ {
670
+ const key = ['image', 'video'].includes(block.type) ? 'src' : 'url';
671
+ const kind = block.type === 'video' ? 'media' : block.type === 'image' ? 'image' : block.type === 'embed' ? 'embed' : 'attachment';
672
+ if (c[key] && !safeContentEditorHtmlUrl(c[key], kind))
673
+ fail(`${cp}.${key}`, 'Unsupported resource URL');
674
+ }
675
+ if (block.type === 'attachment' && !(Number.isInteger(c.size) && c.size >= 0))
676
+ fail(`${cp}.size`, 'Expected a non-negative integer byte count');
677
+ if (block.type === 'video')
678
+ enumValue(c.orientation, ['portrait', 'landscape'], `${cp}.orientation`);
679
+ for (const key of ['width', 'height', 'actualWidth', 'actualHeight'])
680
+ dimension(settings[key], `${sp}.${key}`);
681
+ break;
682
+ case 'gallery': {
683
+ object(c, cp);
684
+ const ids = new Set();
685
+ array(c.images, `${cp}.images`).forEach((image, j) => {
686
+ const ip = `${cp}.images[${j}]`;
687
+ object(image, ip);
688
+ string(image.id, `${ip}.id`, true);
689
+ if (ids.has(image.id))
690
+ fail(`${ip}.id`, 'Duplicate image ID');
691
+ ids.add(image.id);
692
+ string(image.src, `${ip}.src`);
693
+ string(image.alt, `${ip}.alt`);
694
+ runs(image.caption, `${ip}.caption`);
695
+ if (image.src && !safeContentEditorHtmlUrl(image.src, 'image'))
696
+ fail(`${ip}.src`, 'Unsupported image URL');
697
+ });
698
+ break;
699
+ }
700
+ case 'toggle':
701
+ object(c, cp);
702
+ runs(c.title, `${cp}.title`);
703
+ blocks(c.blocks, `${cp}.blocks`);
704
+ enumValue(settings['expanded'], [true, false], `${sp}.expanded`);
705
+ break;
706
+ case 'grid': {
707
+ object(c, cp);
708
+ const ids = new Set();
709
+ array(c.cells, `${cp}.cells`).forEach((cell, j) => {
710
+ const gp = `${cp}.cells[${j}]`;
711
+ object(cell, gp);
712
+ string(cell.id, `${gp}.id`, true);
713
+ if (ids.has(cell.id))
714
+ fail(`${gp}.id`, 'Duplicate grid cell ID');
715
+ ids.add(cell.id);
716
+ blocks(cell.blocks, `${gp}.blocks`);
717
+ });
718
+ enumValue(settings['columns'], [2, 3, 4], `${sp}.columns`);
719
+ enumValue(settings['gap'], ['small', 'medium', 'large'], `${sp}.gap`);
720
+ enumValue(settings['stackOnMobile'], [true, false], `${sp}.stackOnMobile`);
721
+ break;
722
+ }
723
+ default:
724
+ if (!options.allowUnknownBlocks && !Object.hasOwn(config.blocks ?? {}, block.type))
725
+ fail(`${p}.type`, `Unknown block type "${block.type}"`);
726
+ }
727
+ const validation = config.blocks?.[block.type]?.validateImport?.(block);
728
+ if (validation !== undefined)
729
+ fail(p, validation);
730
+ });
731
+ };
732
+ const document = object(copy(value, '$', 0), '$');
733
+ if (document['version'] !== 1)
734
+ fail('$.version', 'Only document version 1 is supported');
735
+ blocks(document['blocks'], '$.blocks');
736
+ return { version: 1, blocks: document['blocks'] };
996
737
  }
997
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorHtmlSerializer, decorators: [{
998
- type: Injectable,
999
- args: [{ providedIn: 'root' }]
1000
- }] });
1001
738
 
1002
- /** Structured failure. The editor is never modified when parsing fails. */
1003
- class ContentEditorImportError extends Error {
1004
- path;
1005
- constructor(path, message) {
1006
- super(`${path}: ${message}`);
1007
- this.path = path;
1008
- this.name = 'ContentEditorImportError';
739
+ const ignoredTags = new Set(['script', 'style', 'noscript', 'template', 'object', 'embed', 'head', 'meta', 'link']);
740
+ const blockTags = new Set(['p', 'div', 'section', 'article', 'header', 'footer', 'main', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'blockquote', 'figure', 'ul', 'ol', 'table', 'details', 'hr']);
741
+ /** Imports semantic HTML into native blocks. Scripts, event handlers and arbitrary CSS are never stored. */
742
+ function contentEditorFromHtml(html, config = {}, options = {}) {
743
+ if (typeof html !== 'string')
744
+ throw new ContentEditorImportError('$html', 'Expected an HTML string');
745
+ const owner = options.document ?? globalThis.document;
746
+ if (!owner?.implementation?.createHTMLDocument) {
747
+ throw new ContentEditorImportError('$html', 'HTML import requires a DOM document; supply options.document when running on the server');
1009
748
  }
1010
- }
1011
-
1012
- /** Parses and validates the native version-1 format without changing the caller's objects. */
1013
- function contentEditorFromJson(source, config = {}, options = {}) {
749
+ const inert = owner.implementation.createHTMLDocument('');
750
+ inert.body.innerHTML = html;
1014
751
  const maxDepth = options.maxDepth ?? 64;
1015
752
  const maxBlocks = options.maxBlocks ?? 10000;
1016
- if (!Number.isInteger(maxDepth) || maxDepth < 1 || !Number.isInteger(maxBlocks) || maxBlocks < 1) {
753
+ if (!Number.isInteger(maxDepth) || maxDepth < 1 || !Number.isInteger(maxBlocks) || maxBlocks < 1)
1017
754
  throw new ContentEditorImportError('$options', 'maxDepth and maxBlocks must be positive integers');
1018
- }
1019
- let value = source;
1020
- if (typeof source === 'string') {
755
+ const definitions = [...new Map([...basicTextEditorPlugin().marks, ...colorEditorPlugin().marks, ...linkEditorPlugin().marks, ...(config.importMarks ?? [])].map(mark => [mark.type, mark])).values()];
756
+ const overrides = Object.values(config.blocks ?? {}).flatMap(block => block.fromHtml ? [block.fromHtml] : []);
757
+ let depth = 0;
758
+ let count = 0;
759
+ const guarded = (read) => {
760
+ if (++depth > maxDepth)
761
+ throw new ContentEditorImportError('$html', `Maximum nesting depth (${maxDepth}) exceeded`);
1021
762
  try {
1022
- value = JSON.parse(source);
763
+ return read();
1023
764
  }
1024
- catch {
1025
- throw new ContentEditorImportError('$', 'Invalid JSON');
765
+ finally {
766
+ depth--;
1026
767
  }
1027
- }
1028
- const fail = (path, message) => { throw new ContentEditorImportError(path, message); };
1029
- const ancestors = new Set();
1030
- const copy = (input, path, depth) => {
1031
- if (depth > maxDepth)
1032
- fail(path, `Maximum nesting depth (${maxDepth}) exceeded`);
1033
- if (input === null || typeof input === 'string' || typeof input === 'boolean')
1034
- return input;
1035
- if (typeof input === 'number' && Number.isFinite(input))
1036
- return input;
1037
- if (!input || typeof input !== 'object')
1038
- return fail(path, 'Expected a JSON-compatible value');
1039
- if (ancestors.has(input))
1040
- fail(path, 'Cyclic data is not supported');
1041
- if (!Array.isArray(input) && ![Object.prototype, null].includes(Object.getPrototypeOf(input)))
1042
- fail(path, 'Expected a plain JSON object');
1043
- ancestors.add(input);
1044
- const output = Array.isArray(input)
1045
- ? Array.from(input, (item, i) => copy(item, `${path}[${i}]`, depth + 1))
1046
- : Object.fromEntries(Object.entries(input).filter(([, item]) => item !== undefined).map(([key, item]) => [key, copy(item, `${path}.${key}`, depth + 1)]));
1047
- ancestors.delete(input);
1048
- return output;
1049
768
  };
1050
- const object = (input, path) => {
1051
- if (input === null || typeof input !== 'object' || Array.isArray(input))
1052
- fail(path, 'Expected an object');
1053
- return input;
769
+ const tag = (element) => element.tagName.toLowerCase();
770
+ const children = (element) => Array.from(element.children);
771
+ const direct = (element, selector) => children(element).find(child => child.matches(selector));
772
+ const alignment = (element) => {
773
+ const value = element.style?.textAlign || element.getAttribute('align');
774
+ return value && ['left', 'center', 'right', 'justify'].includes(value) ? [{ name: 'text-alignment', value }] : [];
1054
775
  };
1055
- const array = (input, path) => { if (!Array.isArray(input))
1056
- fail(path, 'Expected an array'); return input; };
1057
- const string = (input, path, nonempty = false) => {
1058
- if (typeof input !== 'string' || (nonempty && !input.trim()))
1059
- fail(path, nonempty ? 'Expected a non-empty string' : 'Expected a string');
776
+ const dimension = (element, name) => {
777
+ const raw = element.getAttribute(name);
778
+ if (!raw || !/^\d+(?:\.\d+)?$/.test(raw))
779
+ return null;
780
+ const value = Number(raw);
781
+ return value > 0 && Number.isFinite(value) ? value : null;
1060
782
  };
1061
- const props = (input, path) => {
1062
- if (input === undefined)
1063
- return;
1064
- array(input, path).forEach((prop, i) => {
1065
- object(prop, `${path}[${i}]`);
1066
- string(prop.name, `${path}[${i}].name`, true);
1067
- string(prop.value, `${path}[${i}].value`);
1068
- });
783
+ const createBlock = (type, content, attrs) => {
784
+ if (++count > maxBlocks)
785
+ throw new ContentEditorImportError('$html', `Maximum block count (${maxBlocks}) exceeded`);
786
+ return { id: createNgsHeadlessEditorId(type), type, content, ...(attrs ? { attrs } : {}) };
1069
787
  };
1070
- const runs = (input, path) => {
1071
- array(input, path).forEach((run, i) => {
1072
- const p = `${path}[${i}]`;
1073
- object(run, p);
1074
- if (run.type !== 'text')
1075
- fail(`${p}.type`, 'Expected "text"');
1076
- string(run.text, `${p}.text`);
1077
- array(run.marks, `${p}.marks`).forEach((mark, j) => {
1078
- const m = `${p}.marks[${j}]`;
1079
- object(mark, m);
1080
- string(mark.type, `${m}.type`, true);
1081
- if (mark.attrs !== undefined) {
1082
- for (const [key, attr] of Object.entries(object(mark.attrs, `${m}.attrs`))) {
1083
- if (attr !== null && !['string', 'number', 'boolean'].includes(typeof attr))
1084
- fail(`${m}.attrs.${key}`, 'Expected a scalar mark attribute');
1085
- }
1086
- }
1087
- if (mark.type === 'link' && !safeContentEditorHtmlUrl(mark.attrs?.href))
1088
- fail(`${m}.attrs.href`, 'Expected a supported non-empty link URL');
1089
- if (mark.type === 'link')
1090
- enumValue(mark.attrs?.target, ['_blank', '_self'], `${m}.attrs.target`);
1091
- if (['textColor', 'backgroundColor'].includes(mark.type) && (typeof mark.attrs?.color !== 'string' || !normalizeNgsHeadlessEditorColor(mark.attrs.color)))
1092
- fail(`${m}.attrs.color`, 'Expected a supported CSS color');
1093
- });
788
+ const parseText = (element) => {
789
+ const runs = [];
790
+ const newline = () => { if (runs.length && !runs.at(-1).text.endsWith('\n'))
791
+ runs.push(createNgsHeadlessEditorText('\n')); };
792
+ const visit = (node, marks) => guarded(() => {
793
+ if (node.nodeType === 3) {
794
+ const text = (node.textContent ?? '').replace(/[\t\r\n ]+/g, ' ');
795
+ if (text)
796
+ runs.push(createNgsHeadlessEditorText(text, marks));
797
+ return;
798
+ }
799
+ if (node.nodeType !== 1)
800
+ return;
801
+ const el = node;
802
+ const name = tag(el);
803
+ if (ignoredTags.has(name) || ['iframe', 'img', 'video', 'audio', 'ul', 'ol'].includes(name))
804
+ return;
805
+ if (name === 'br') {
806
+ runs.push(createNgsHeadlessEditorText('\n', marks));
807
+ return;
808
+ }
809
+ const next = [...marks];
810
+ for (const definition of definitions) {
811
+ const explicit = el.getAttribute('data-ngs-headless-editor-mark');
812
+ const styleMark = ['textColor', 'backgroundColor'].includes(definition.type) && !!el.style;
813
+ if (explicit ? explicit !== definition.type : name !== definition.tagName && !definition.parseTags?.includes(name) && !styleMark)
814
+ continue;
815
+ const attrs = definition.readAttributes?.(el);
816
+ if (!definition.readAttributes || attrs)
817
+ next.push({ type: definition.type, ...(attrs ? { attrs } : {}) });
818
+ }
819
+ // Common HTML produced by external WYSIWYG editors also expresses marks as inline styles.
820
+ const css = el.style;
821
+ if (css?.fontWeight === 'bold' || Number(css?.fontWeight) >= 600)
822
+ next.push({ type: 'bold' });
823
+ if (css?.fontStyle === 'italic')
824
+ next.push({ type: 'italic' });
825
+ if (css?.textDecoration.includes('underline'))
826
+ next.push({ type: 'underline' });
827
+ if (css?.textDecoration.includes('line-through'))
828
+ next.push({ type: 'strike' });
829
+ if (blockTags.has(name))
830
+ newline();
831
+ Array.from(node.childNodes).forEach(child => visit(child, next));
832
+ if (blockTags.has(name))
833
+ newline();
1094
834
  });
835
+ visit(element, []);
836
+ while (runs.length && !runs[0].text.trim())
837
+ runs.shift();
838
+ while (runs.length && !runs.at(-1).text.trim())
839
+ runs.pop();
840
+ if (runs.length) {
841
+ runs[0] = { ...runs[0], text: runs[0].text.replace(/^\s+/, '') };
842
+ const last = runs.length - 1;
843
+ runs[last] = { ...runs[last], text: runs[last].text.replace(/\s+$/, '') };
844
+ }
845
+ return [...normalizeNgsHeadlessEditorTextContent(runs)];
1095
846
  };
1096
- const enumValue = (input, allowed, path) => {
1097
- if (input !== undefined && !allowed.includes(input))
1098
- fail(path, `Expected one of: ${allowed.join(', ')}`);
847
+ const listItems = (element) => guarded(() => children(element).filter(el => tag(el) === 'li').map(li => {
848
+ const text = li.cloneNode(true);
849
+ children(text).filter(el => ['ul', 'ol'].includes(tag(el))).forEach(el => el.remove());
850
+ return { content: parseText(text), props: alignment(li), children: children(li).filter(el => ['ul', 'ol'].includes(tag(el))).flatMap(listItems) };
851
+ }));
852
+ const media = (element, figure) => {
853
+ const name = tag(element);
854
+ const kind = name === 'img' ? 'image' : name === 'video' ? 'media' : 'embed';
855
+ const src = safeContentEditorHtmlUrl(element.getAttribute('src') || element.querySelector('source')?.getAttribute('src'), kind);
856
+ if (!src)
857
+ return [];
858
+ const caption = figure ? direct(figure, 'figcaption') : undefined;
859
+ const settings = Object.fromEntries(['width', 'height'].flatMap(key => { const n = dimension(element, key); return n ? [[key, n]] : []; }));
860
+ const content = name === 'img' ? { src, alt: element.getAttribute('alt') ?? '' }
861
+ : name === 'video' ? { src, caption: caption?.textContent ?? '', orientation: 'landscape' }
862
+ : { url: src, type: element.getAttribute('title') ?? '' };
863
+ return [createBlock(name === 'img' ? 'image' : name === 'video' ? 'video' : 'embed', content, { settings })];
1099
864
  };
1100
- const dimension = (input, path) => {
1101
- if (input !== undefined && input !== null && input !== 'auto' && !(typeof input === 'number' && Number.isFinite(input) && input > 0))
1102
- fail(path, 'Expected a positive pixel dimension, "auto", or null');
865
+ const builtin = (element) => {
866
+ const name = tag(element);
867
+ const attrs = { props: alignment(element) };
868
+ if (ignoredTags.has(name))
869
+ return [];
870
+ if (element.matches('[data-content-editor="gallery"], .ngs-content-editor-html-gallery')) {
871
+ const images = children(element).flatMap(figure => {
872
+ const image = tag(figure) === 'img' ? figure : direct(figure, 'img');
873
+ const src = safeContentEditorHtmlUrl(image?.getAttribute('src'), 'image');
874
+ if (!image || !src)
875
+ return [];
876
+ const caption = direct(figure, 'figcaption');
877
+ return [{ id: createNgsHeadlessEditorId('image'), src, alt: image.getAttribute('alt') ?? '', caption: caption ? parseText(caption) : [] }];
878
+ });
879
+ return [createBlock('gallery', { images })];
880
+ }
881
+ if (element.matches('.ngs-content-editor-html-grid')) {
882
+ const container = direct(element, '.ngs-content-editor-html-grid-cells') ?? element;
883
+ const css = element.style;
884
+ const columnValue = Number(element.getAttribute('data-columns') || css?.getPropertyValue('--ngs-html-grid-columns'));
885
+ const gapValue = css?.getPropertyValue('--ngs-html-grid-gap').trim();
886
+ const settings = { columns: [2, 3, 4].includes(columnValue) ? columnValue : 2, gap: gapValue === '12px' ? 'small' : gapValue === '36px' ? 'large' : 'medium', stackOnMobile: container.classList.contains('ngs-content-editor-html-grid-stack') };
887
+ const cells = children(container).filter(cell => cell.matches('.ngs-content-editor-html-grid-cell')).map(cell => ({ id: createNgsHeadlessEditorId('cell'), blocks: parseBlocks(cell) }));
888
+ return [createBlock('grid', { cells }, { settings })];
889
+ }
890
+ if (name === 'p' || /^h[1-6]$/.test(name)) {
891
+ if (element.querySelector('img, video, iframe, a[download]'))
892
+ return parseBlocks(element);
893
+ return [createBlock(name === 'p' ? 'paragraph' : 'heading', parseText(element), { ...attrs, ...(name !== 'p' ? { settings: { level: Number(name[1]) } } : {}) })];
894
+ }
895
+ if (name === 'hr')
896
+ return [createBlock('divider', null)];
897
+ if (name === 'pre') {
898
+ const code = direct(element, 'code') ?? element;
899
+ const language = code.getAttribute('data-language') ?? Array.from(code.classList).find(cls => cls.startsWith('language-'))?.slice(9) ?? 'none';
900
+ return [createBlock('code', [createNgsHeadlessEditorText(code.textContent ?? '')], { settings: { language } })];
901
+ }
902
+ if (name === 'ul' || name === 'ol')
903
+ return [createBlock(name === 'ol' ? 'orderedList' : 'bulletList', listItems(element), { settings: { listStyle: name === 'ol' ? 'ordered' : 'bullet' } })];
904
+ if (name === 'details') {
905
+ const summary = direct(element, 'summary');
906
+ const body = element.cloneNode(true);
907
+ direct(body, 'summary')?.remove();
908
+ return [createBlock('toggle', { title: summary ? parseText(summary) : [], blocks: parseBlocks(body) }, { settings: { expanded: element.hasAttribute('open') } })];
909
+ }
910
+ if (name === 'aside' && (element.hasAttribute('data-callout') || element.classList.contains('ngs-content-editor-html-callout'))) {
911
+ const value = element.getAttribute('data-callout');
912
+ return [createBlock('callout', parseText(element), { ...attrs, settings: { variant: ['note', 'tip', 'warning', 'danger'].includes(value ?? '') ? value : 'note' } })];
913
+ }
914
+ if (name === 'blockquote' || (name === 'figure' && direct(element, 'blockquote'))) {
915
+ const quote = name === 'blockquote' ? element : direct(element, 'blockquote');
916
+ const caption = name === 'figure' ? direct(element, 'figcaption') : undefined;
917
+ return [createBlock('quote', { cite: { content: parseText(quote), props: alignment(quote) }, caption: { content: caption ? parseText(caption) : [], props: caption ? alignment(caption) : [] } })];
918
+ }
919
+ if (name === 'table') {
920
+ const rows = Array.from(element.querySelectorAll('tr')).filter(row => row.closest('table') === element);
921
+ const cells = rows.map(row => children(row).filter(cell => ['td', 'th'].includes(tag(cell))));
922
+ return [createBlock('table', null, {
923
+ rows: cells.map(row => row.map(parseText)), header: !!cells[0]?.some(cell => tag(cell) === 'th'),
924
+ cellMetadata: cells.map(row => row.map(cell => ({ props: alignment(cell), options: {
925
+ colspan: Math.max(1, Math.floor(dimension(cell, 'colspan') ?? 1)), rowspan: Math.max(1, Math.floor(dimension(cell, 'rowspan') ?? 1)),
926
+ ...(dimension(cell, 'width') ? { width: dimension(cell, 'width') } : {})
927
+ } })))
928
+ })];
929
+ }
930
+ if (name === 'figure') {
931
+ const child = direct(element, 'img, video, iframe');
932
+ if (child)
933
+ return media(child, element);
934
+ }
935
+ if (['img', 'video', 'iframe'].includes(name))
936
+ return media(element);
937
+ if (name === 'a' && element.hasAttribute('download')) {
938
+ const url = safeContentEditorHtmlUrl(element.getAttribute('href'), 'attachment');
939
+ return url ? [createBlock('attachment', { url, name: element.getAttribute('download') || element.textContent?.trim() || 'Download', size: 0, mimeType: '' })] : [];
940
+ }
941
+ return parseBlocks(element);
1103
942
  };
1104
- const usedIds = new Set();
1105
- let count = 0;
1106
- const list = (input, path) => {
1107
- array(input, path).forEach((item, i) => {
1108
- const p = `${path}[${i}]`;
1109
- object(item, p);
1110
- runs(item.content, `${p}.content`);
1111
- props(item.props, `${p}.props`);
1112
- list(item.children, `${p}.children`);
1113
- });
943
+ const context = {
944
+ createBlock, createId: createNgsHeadlessEditorId, parseText, parseBlocks: element => parseBlocks(element),
945
+ defaultFromHtml: builtin, safeUrl: safeContentEditorHtmlUrl
1114
946
  };
1115
- const blocks = (input, path) => {
1116
- array(input, path).forEach((block, i) => {
1117
- const p = `${path}[${i}]`;
1118
- object(block, p);
1119
- if (++count > maxBlocks)
1120
- fail(p, `Maximum block count (${maxBlocks}) exceeded`);
1121
- string(block.id, `${p}.id`, true);
1122
- string(block.type, `${p}.type`, true);
1123
- if (usedIds.has(block.id))
1124
- fail(`${p}.id`, `Duplicate block ID "${block.id}"`);
1125
- usedIds.add(block.id);
1126
- if (!Object.hasOwn(block, 'content'))
1127
- fail(`${p}.content`, 'Required field');
1128
- const attrs = block.attrs === undefined ? {} : object(block.attrs, `${p}.attrs`);
1129
- const settings = attrs['settings'] === undefined ? {} : object(attrs['settings'], `${p}.attrs.settings`);
1130
- props(attrs['props'], `${p}.attrs.props`);
1131
- const c = block.content;
1132
- const cp = `${p}.content`;
1133
- const sp = `${p}.attrs.settings`;
1134
- switch (block.type) {
1135
- case 'paragraph':
1136
- case 'heading':
1137
- case 'code':
1138
- case 'callout':
1139
- runs(c, cp);
1140
- if (block.type === 'heading')
1141
- enumValue(settings['level'], [1, 2, 3, 4, 5, 6], `${sp}.level`);
1142
- if (block.type === 'code' && settings['language'] !== undefined)
1143
- string(settings['language'], `${sp}.language`);
1144
- if (block.type === 'callout')
1145
- enumValue(settings['variant'], ['note', 'tip', 'warning', 'danger'], `${sp}.variant`);
1146
- break;
1147
- case 'divider':
1148
- if (c !== null)
1149
- fail(cp, 'Divider content must be null');
1150
- break;
1151
- case 'bulletList':
1152
- case 'orderedList':
1153
- list(c, cp);
1154
- enumValue(settings['listStyle'], ['bullet', 'ordered'], `${sp}.listStyle`);
1155
- break;
1156
- case 'quote':
1157
- object(c, cp);
1158
- for (const name of ['cite', 'caption']) {
1159
- object(c[name], `${cp}.${name}`);
1160
- runs(c[name].content, `${cp}.${name}.content`);
1161
- props(c[name].props, `${cp}.${name}.props`);
1162
- }
1163
- break;
1164
- case 'table':
1165
- if (c !== null)
1166
- fail(cp, 'Native table content must be null; use attrs.rows');
1167
- if (array(attrs['rows'], `${p}.attrs.rows`).length > 500)
1168
- fail(`${p}.attrs.rows`, 'Tables support at most 500 rows');
1169
- attrs['rows'].forEach((row, r) => {
1170
- if (array(row, `${p}.attrs.rows[${r}]`).length > 50)
1171
- fail(`${p}.attrs.rows[${r}]`, 'Tables support at most 50 columns');
1172
- row.forEach((cell, col) => runs(cell, `${p}.attrs.rows[${r}][${col}]`));
1173
- });
1174
- enumValue(attrs['header'], [true, false], `${p}.attrs.header`);
1175
- if (attrs['cellMetadata'] !== undefined)
1176
- array(attrs['cellMetadata'], `${p}.attrs.cellMetadata`).forEach((row, r) => array(row, `${p}.attrs.cellMetadata[${r}]`).forEach((cell, col) => {
1177
- const mp = `${p}.attrs.cellMetadata[${r}][${col}]`;
1178
- object(cell, mp);
1179
- props(cell.props, `${mp}.props`);
1180
- if (cell.options !== undefined) {
1181
- const opts = object(cell.options, `${mp}.options`);
1182
- for (const key of ['colspan', 'rowspan'])
1183
- if (opts[key] !== undefined && !(Number.isInteger(opts[key]) && opts[key] > 0))
1184
- fail(`${mp}.options.${key}`, 'Expected a positive integer');
1185
- dimension(opts['width'], `${mp}.options.width`);
1186
- }
1187
- }));
1188
- break;
1189
- case 'image':
1190
- case 'video':
1191
- case 'embed':
1192
- case 'attachment':
1193
- object(c, cp);
1194
- for (const key of block.type === 'image' ? ['src', 'alt'] : block.type === 'video' ? ['src', 'caption'] : block.type === 'embed' ? ['url', 'type'] : ['url', 'name', 'mimeType'])
1195
- string(c[key], `${cp}.${key}`);
1196
- {
1197
- const key = ['image', 'video'].includes(block.type) ? 'src' : 'url';
1198
- const kind = block.type === 'video' ? 'media' : block.type === 'image' ? 'image' : block.type === 'embed' ? 'embed' : 'attachment';
1199
- if (c[key] && !safeContentEditorHtmlUrl(c[key], kind))
1200
- fail(`${cp}.${key}`, 'Unsupported resource URL');
1201
- }
1202
- if (block.type === 'attachment' && !(Number.isInteger(c.size) && c.size >= 0))
1203
- fail(`${cp}.size`, 'Expected a non-negative integer byte count');
1204
- if (block.type === 'video')
1205
- enumValue(c.orientation, ['portrait', 'landscape'], `${cp}.orientation`);
1206
- for (const key of ['width', 'height', 'actualWidth', 'actualHeight'])
1207
- dimension(settings[key], `${sp}.${key}`);
1208
- break;
1209
- case 'gallery': {
1210
- object(c, cp);
1211
- const ids = new Set();
1212
- array(c.images, `${cp}.images`).forEach((image, j) => {
1213
- const ip = `${cp}.images[${j}]`;
1214
- object(image, ip);
1215
- string(image.id, `${ip}.id`, true);
1216
- if (ids.has(image.id))
1217
- fail(`${ip}.id`, 'Duplicate image ID');
1218
- ids.add(image.id);
1219
- string(image.src, `${ip}.src`);
1220
- string(image.alt, `${ip}.alt`);
1221
- runs(image.caption, `${ip}.caption`);
1222
- if (image.src && !safeContentEditorHtmlUrl(image.src, 'image'))
1223
- fail(`${ip}.src`, 'Unsupported image URL');
1224
- });
1225
- break;
947
+ const parseElement = (element) => guarded(() => {
948
+ if (ignoredTags.has(tag(element)))
949
+ return [];
950
+ for (const override of overrides) {
951
+ if (element.matches(override.selector)) {
952
+ const result = override.parse(element, context);
953
+ return result === null ? [] : Array.isArray(result) ? [...result] : [result];
954
+ }
955
+ }
956
+ return builtin(element);
957
+ });
958
+ const parseBlocks = (element) => guarded(() => {
959
+ const output = [];
960
+ let inline = inert.createElement('div');
961
+ const flush = () => {
962
+ const runs = parseText(inline);
963
+ if (runs.some(run => run.text.trim()))
964
+ output.push(createBlock('paragraph', runs, { props: alignment(element) }));
965
+ inline = inert.createElement('div');
966
+ };
967
+ for (const node of Array.from(element.childNodes)) {
968
+ if (node.nodeType === 1) {
969
+ const child = node;
970
+ if (ignoredTags.has(tag(child)))
971
+ continue;
972
+ if (blockTags.has(tag(child)) || ['img', 'video', 'iframe'].includes(tag(child)) || child.matches('a[download]') || overrides.some(override => child.matches(override.selector))) {
973
+ flush();
974
+ output.push(...parseElement(child));
975
+ continue;
1226
976
  }
1227
- case 'toggle':
1228
- object(c, cp);
1229
- runs(c.title, `${cp}.title`);
1230
- blocks(c.blocks, `${cp}.blocks`);
1231
- enumValue(settings['expanded'], [true, false], `${sp}.expanded`);
1232
- break;
1233
- case 'grid': {
1234
- object(c, cp);
1235
- const ids = new Set();
1236
- array(c.cells, `${cp}.cells`).forEach((cell, j) => {
1237
- const gp = `${cp}.cells[${j}]`;
1238
- object(cell, gp);
1239
- string(cell.id, `${gp}.id`, true);
1240
- if (ids.has(cell.id))
1241
- fail(`${gp}.id`, 'Duplicate grid cell ID');
1242
- ids.add(cell.id);
1243
- blocks(cell.blocks, `${gp}.blocks`);
1244
- });
1245
- enumValue(settings['columns'], [2, 3, 4], `${sp}.columns`);
1246
- enumValue(settings['gap'], ['small', 'medium', 'large'], `${sp}.gap`);
1247
- enumValue(settings['stackOnMobile'], [true, false], `${sp}.stackOnMobile`);
1248
- break;
977
+ // Unknown inline wrappers may contain block elements; keep those structures.
978
+ if (child.querySelector([...blockTags, 'img', 'video', 'iframe', 'a[download]'].join(',')) || overrides.some(override => child.querySelector(override.selector))) {
979
+ flush();
980
+ output.push(...parseElement(child));
981
+ continue;
1249
982
  }
1250
- default:
1251
- if (!options.allowUnknownBlocks && !Object.hasOwn(config.blocks ?? {}, block.type))
1252
- fail(`${p}.type`, `Unknown block type "${block.type}"`);
1253
983
  }
1254
- const validation = config.blocks?.[block.type]?.validateImport?.(block);
1255
- if (validation !== undefined)
1256
- fail(p, validation);
1257
- });
1258
- };
1259
- const document = object(copy(value, '$', 0), '$');
1260
- if (document['version'] !== 1)
1261
- fail('$.version', 'Only document version 1 is supported');
1262
- blocks(document['blocks'], '$.blocks');
1263
- return { version: 1, blocks: document['blocks'] };
984
+ inline.appendChild(node.cloneNode(true));
985
+ }
986
+ flush();
987
+ return output;
988
+ });
989
+ return contentEditorFromJson({ version: 1, blocks: parseBlocks(inert.body) }, config, options);
990
+ }
991
+
992
+ /** Parsing only: applications decide when to replace their current document. */
993
+ class ContentEditorImporter {
994
+ config = inject(CONTENT_EDITOR_CONFIG);
995
+ document = inject(DOCUMENT);
996
+ fromJson(source, config = {}, options = {}) {
997
+ return contentEditorFromJson(source, mergeContentEditorConfig(this.config, config), options);
998
+ }
999
+ fromHtml(html, config = {}, options = {}) {
1000
+ return contentEditorFromHtml(html, mergeContentEditorConfig(this.config, config), { document: this.document, ...options });
1001
+ }
1002
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorImporter, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1003
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorImporter, providedIn: 'root' });
1004
+ }
1005
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorImporter, decorators: [{
1006
+ type: Injectable,
1007
+ args: [{ providedIn: 'root' }]
1008
+ }] });
1009
+
1010
+ /** Text fields use the same HTML parser as documents, flattening structure to lines. */
1011
+ function contentEditorImportedText(blocks) {
1012
+ const parts = [];
1013
+ const read = (block) => {
1014
+ const content = block.content;
1015
+ if (isNgsHeadlessEditorTextContent(content))
1016
+ parts.push(content);
1017
+ else if (block.type === 'quote') {
1018
+ parts.push(content.cite.content, content.caption.content);
1019
+ }
1020
+ else if (block.type === 'bulletList' || block.type === 'orderedList') {
1021
+ const item = (value) => { parts.push(value.content); value.children?.forEach(item); };
1022
+ content.forEach(item);
1023
+ }
1024
+ else if (block.type === 'table') {
1025
+ for (const row of (block.attrs?.['rows'] ?? []))
1026
+ parts.push(row.flatMap((cell, i) => i ? [createNgsHeadlessEditorText('\t'), ...cell] : cell));
1027
+ }
1028
+ else if (block.type === 'toggle') {
1029
+ parts.push(content.title);
1030
+ content.blocks.forEach(read);
1031
+ }
1032
+ else if (block.type === 'grid')
1033
+ content.cells.forEach((cell) => cell.blocks.forEach(read));
1034
+ else if (block.type === 'image' || block.type === 'gallery')
1035
+ parts.push([createNgsHeadlessEditorText(content.alt ?? '')]);
1036
+ };
1037
+ blocks.forEach(read);
1038
+ return normalizeNgsHeadlessEditorTextContent(parts.filter(part => part.some(run => run.text)).flatMap((part, i) => i ? [createNgsHeadlessEditorText('\n'), ...part] : part));
1264
1039
  }
1265
1040
 
1266
- const ignoredTags = new Set(['script', 'style', 'noscript', 'template', 'object', 'embed', 'head', 'meta', 'link']);
1267
- const blockTags = new Set(['p', 'div', 'section', 'article', 'header', 'footer', 'main', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'blockquote', 'figure', 'ul', 'ol', 'table', 'details', 'hr']);
1268
- /** Imports semantic HTML into native blocks. Scripts, event handlers and arbitrary CSS are never stored. */
1269
- function contentEditorFromHtml(html, config = {}, options = {}) {
1270
- if (typeof html !== 'string')
1271
- throw new ContentEditorImportError('$html', 'Expected an HTML string');
1272
- const owner = options.document ?? globalThis.document;
1273
- if (!owner?.implementation?.createHTMLDocument) {
1274
- throw new ContentEditorImportError('$html', 'HTML import requires a DOM document; supply options.document when running on the server');
1041
+ const CONTENT_BUILDER = new InjectionToken('CONTENT_BUILDER');
1042
+ const CONTENT_EDITOR_BLOCK = new InjectionToken('CONTENT_EDITOR_BLOCK');
1043
+
1044
+ /** UI state and block operations. The headless document is the only content store. */
1045
+ class ContentBuilderStore {
1046
+ editor = inject(NgsHeadlessEditor);
1047
+ dragging = false;
1048
+ constructor() {
1049
+ const document = inject(DOCUMENT);
1050
+ // Capture the current point before CDK chooses a connected list. Its moved
1051
+ // output is emitted after hit testing and would provide the previous point.
1052
+ const mouse = (event) => { if (this.dragging)
1053
+ this.dragPointer.set({ x: event.clientX, y: event.clientY }); };
1054
+ const touch = (event) => {
1055
+ const point = event.touches[0];
1056
+ if (this.dragging && point)
1057
+ this.dragPointer.set({ x: point.clientX, y: point.clientY });
1058
+ };
1059
+ document.addEventListener('mousemove', mouse, true);
1060
+ document.addEventListener('touchmove', touch, { capture: true, passive: true });
1061
+ inject(DestroyRef).onDestroy(() => {
1062
+ document.removeEventListener('mousemove', mouse, true);
1063
+ document.removeEventListener('touchmove', touch, true);
1064
+ });
1275
1065
  }
1276
- const inert = owner.implementation.createHTMLDocument('');
1277
- inert.body.innerHTML = html;
1278
- const maxDepth = options.maxDepth ?? 64;
1279
- const maxBlocks = options.maxBlocks ?? 10000;
1280
- if (!Number.isInteger(maxDepth) || maxDepth < 1 || !Number.isInteger(maxBlocks) || maxBlocks < 1)
1281
- throw new ContentEditorImportError('$options', 'maxDepth and maxBlocks must be positive integers');
1282
- const definitions = [...new Map([...basicTextEditorPlugin().marks, ...colorEditorPlugin().marks, ...linkEditorPlugin().marks, ...(config.importMarks ?? [])].map(mark => [mark.type, mark])).values()];
1283
- const overrides = Object.values(config.blocks ?? {}).flatMap(block => block.fromHtml ? [block.fromHtml] : []);
1284
- let depth = 0;
1285
- let count = 0;
1286
- const guarded = (read) => {
1287
- if (++depth > maxDepth)
1288
- throw new ContentEditorImportError('$html', `Maximum nesting depth (${maxDepth}) exceeded`);
1066
+ textEdit = null;
1067
+ /** Scopes typing groups to one text region, so adjacent cells never share undo. */
1068
+ withTextEdit(origin, group, edit) {
1069
+ const previous = this.textEdit;
1070
+ this.textEdit = { origin, group };
1289
1071
  try {
1290
- return read();
1072
+ edit();
1291
1073
  }
1292
1074
  finally {
1293
- depth--;
1075
+ this.textEdit = previous;
1294
1076
  }
1295
- };
1296
- const tag = (element) => element.tagName.toLowerCase();
1297
- const children = (element) => Array.from(element.children);
1298
- const direct = (element, selector) => children(element).find(child => child.matches(selector));
1299
- const alignment = (element) => {
1300
- const value = element.style?.textAlign || element.getAttribute('align');
1301
- return value && ['left', 'center', 'right', 'justify'].includes(value) ? [{ name: 'text-alignment', value }] : [];
1302
- };
1303
- const dimension = (element, name) => {
1304
- const raw = element.getAttribute(name);
1305
- if (!raw || !/^\d+(?:\.\d+)?$/.test(raw))
1306
- return null;
1307
- const value = Number(raw);
1308
- return value > 0 && Number.isFinite(value) ? value : null;
1309
- };
1310
- const createBlock = (type, content, attrs) => {
1311
- if (++count > maxBlocks)
1312
- throw new ContentEditorImportError('$html', `Maximum block count (${maxBlocks}) exceeded`);
1313
- return { id: createNgsHeadlessEditorId(type), type, content, ...(attrs ? { attrs } : {}) };
1314
- };
1315
- const parseText = (element) => {
1316
- const runs = [];
1317
- const newline = () => { if (runs.length && !runs.at(-1).text.endsWith('\n'))
1318
- runs.push(createNgsHeadlessEditorText('\n')); };
1319
- const visit = (node, marks) => guarded(() => {
1320
- if (node.nodeType === 3) {
1321
- const text = (node.textContent ?? '').replace(/[\t\r\n ]+/g, ' ');
1322
- if (text)
1323
- runs.push(createNgsHeadlessEditorText(text, marks));
1324
- return;
1325
- }
1326
- if (node.nodeType !== 1)
1327
- return;
1328
- const el = node;
1329
- const name = tag(el);
1330
- if (ignoredTags.has(name) || ['iframe', 'img', 'video', 'audio', 'ul', 'ol'].includes(name))
1331
- return;
1332
- if (name === 'br') {
1333
- runs.push(createNgsHeadlessEditorText('\n', marks));
1334
- return;
1077
+ }
1078
+ insertionTarget = signal({ scope: {} }, /* @ts-ignore */
1079
+ ...(ngDevMode ? [{ debugName: "insertionTarget" }] : /* istanbul ignore next */ []));
1080
+ restoreTextSelection = signal(null, /* @ts-ignore */
1081
+ ...(ngDevMode ? [{ debugName: "restoreTextSelection" }] : /* istanbul ignore next */ []));
1082
+ focusedBlockId = signal(null, /* @ts-ignore */
1083
+ ...(ngDevMode ? [{ debugName: "focusedBlockId" }] : /* istanbul ignore next */ []));
1084
+ activeBlockId = signal(null, /* @ts-ignore */
1085
+ ...(ngDevMode ? [{ debugName: "activeBlockId" }] : /* istanbul ignore next */ []));
1086
+ dragPointer = signal(null, /* @ts-ignore */
1087
+ ...(ngDevMode ? [{ debugName: "dragPointer" }] : /* istanbul ignore next */ []));
1088
+ setDragging(dragging) {
1089
+ this.dragging = dragging;
1090
+ if (!dragging)
1091
+ this.dragPointer.set(null);
1092
+ }
1093
+ dropLists = signal([], /* @ts-ignore */
1094
+ ...(ngDevMode ? [{ debugName: "dropLists" }] : /* istanbul ignore next */ []));
1095
+ registerDropList(list) {
1096
+ if (!this.dropLists().includes(list))
1097
+ this.dropLists.update(lists => [...lists, list]);
1098
+ }
1099
+ unregisterDropList(list) {
1100
+ this.dropLists.update(lists => lists.filter(item => item !== list));
1101
+ }
1102
+ blocks = computed(() => this.editor.document().blocks.map(contentEditorBlockView), /* @ts-ignore */
1103
+ ...(ngDevMode ? [{ debugName: "blocks" }] : /* istanbul ignore next */ []));
1104
+ setFocusedBlockId(id) { this.focusedBlockId.set(id); }
1105
+ setActiveBlockId(id) { this.activeBlockId.set(id); }
1106
+ setBlocks(value) {
1107
+ this.editor.setDocument(value);
1108
+ }
1109
+ addBlock(block, index, scope = {}) {
1110
+ const native = contentEditorNativeBlock(block);
1111
+ const blocks = cloneContentEditorValue([...this.editor.document().blocks]);
1112
+ const collection = [...contentEditorCollection(blocks, scope)];
1113
+ collection.splice(index, 0, native);
1114
+ replaceContentEditorCollection(blocks, scope, collection);
1115
+ this.editor.updateDocument({ version: 1, blocks });
1116
+ }
1117
+ deleteBlock(id, _index) { this.deleteBlocks([id]); }
1118
+ deleteBlocks(ids) {
1119
+ const selected = new Set(ids);
1120
+ const blocks = cloneContentEditorValue([...this.editor.document().blocks]);
1121
+ let changed = false;
1122
+ const remove = (items) => {
1123
+ for (let index = items.length - 1; index >= 0; index--) {
1124
+ if (selected.has(items[index].id)) {
1125
+ items.splice(index, 1);
1126
+ changed = true;
1127
+ }
1128
+ else
1129
+ for (const children of contentEditorChildCollections(items[index]))
1130
+ remove(children);
1335
1131
  }
1336
- const next = [...marks];
1337
- for (const definition of definitions) {
1338
- const explicit = el.getAttribute('data-ngs-headless-editor-mark');
1339
- const styleMark = ['textColor', 'backgroundColor'].includes(definition.type) && !!el.style;
1340
- if (explicit ? explicit !== definition.type : name !== definition.tagName && !definition.parseTags?.includes(name) && !styleMark)
1341
- continue;
1342
- const attrs = definition.readAttributes?.(el);
1343
- if (!definition.readAttributes || attrs)
1344
- next.push({ type: definition.type, ...(attrs ? { attrs } : {}) });
1132
+ };
1133
+ remove(blocks);
1134
+ if (changed)
1135
+ this.editor.updateDocument({ version: 1, blocks });
1136
+ }
1137
+ updateBlock(id, data) {
1138
+ const blocks = cloneContentEditorValue([...this.editor.document().blocks]);
1139
+ const previous = findContentEditorBlock(blocks, id);
1140
+ if (!previous)
1141
+ return;
1142
+ const next = contentEditorNativeBlock({ ...contentEditorBlockView(previous), ...data });
1143
+ const origin = this.textEdit?.origin ?? 'command';
1144
+ const typing = origin === 'keyboard' || origin === 'composition';
1145
+ const root = blocks.find(block => !!findContentEditorBlock([block], id));
1146
+ Object.assign(previous, next);
1147
+ this.editor.updateBlock(root.id, { content: root.content, attrs: root.attrs }, typing ? origin : 'command', typing ? this.textEdit?.group ?? null : null);
1148
+ }
1149
+ moveBlock(from, to) {
1150
+ const blocks = [...this.editor.document().blocks];
1151
+ const [block] = blocks.splice(from, 1);
1152
+ blocks.splice(to, 0, block);
1153
+ this.editor.updateDocument({ version: 1, blocks });
1154
+ }
1155
+ moveBetweenCollections(from, to, source, target) {
1156
+ const blocks = cloneContentEditorValue([...this.editor.document().blocks]);
1157
+ const sourceItems = [...contentEditorCollection(blocks, source)];
1158
+ const block = sourceItems[from];
1159
+ if (!block || (target.parentId && findContentEditorBlock([block], target.parentId)))
1160
+ return;
1161
+ sourceItems.splice(from, 1);
1162
+ replaceContentEditorCollection(blocks, source, sourceItems);
1163
+ const targetItems = [...contentEditorCollection(blocks, target)];
1164
+ targetItems.splice(to, 0, block);
1165
+ replaceContentEditorCollection(blocks, target, targetItems);
1166
+ this.editor.updateDocument({ version: 1, blocks });
1167
+ }
1168
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentBuilderStore, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1169
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentBuilderStore });
1170
+ }
1171
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentBuilderStore, decorators: [{
1172
+ type: Injectable
1173
+ }], ctorParameters: () => [] });
1174
+
1175
+ const regions = new WeakMap();
1176
+ /** A headless inline editor bound to a text field in a content block. */
1177
+ class ContentEditorContentEditableDirective {
1178
+ region = inject(NgsHeadlessEditorInlineRegion);
1179
+ surface = inject(NgsHeadlessEditorSurface);
1180
+ importer = inject(ContentEditorImporter);
1181
+ builder = inject(CONTENT_BUILDER, { optional: true });
1182
+ store = inject(ContentBuilderStore, { optional: true });
1183
+ historyGroup = createNgsHeadlessEditorId('content-region');
1184
+ element = inject(ElementRef).nativeElement;
1185
+ content = input([], { ...(ngDevMode ? { debugName: "content" } : /* istanbul ignore next */ {}), alias: 'ngsContentEditorContentEditable' });
1186
+ settings = input({}, /* @ts-ignore */
1187
+ ...(ngDevMode ? [{ debugName: "settings" }] : /* istanbul ignore next */ []));
1188
+ props = input([], /* @ts-ignore */
1189
+ ...(ngDevMode ? [{ debugName: "props" }] : /* istanbul ignore next */ []));
1190
+ singleLine = input(false, /* @ts-ignore */
1191
+ ...(ngDevMode ? [{ debugName: "singleLine" }] : /* istanbul ignore next */ []));
1192
+ contentChanged = output();
1193
+ propsChanged = output();
1194
+ pressedEnter = output();
1195
+ initialized = output();
1196
+ static forElement(element) {
1197
+ return element ? regions.get(element) : undefined;
1198
+ }
1199
+ constructor() {
1200
+ regions.set(this.element, this);
1201
+ effect(() => {
1202
+ const content = this.content();
1203
+ untracked(() => this.region.load(content));
1204
+ });
1205
+ effect(() => {
1206
+ const content = this.region.content();
1207
+ const origin = this.region.editor.origin();
1208
+ if (origin !== 'external' && origin !== 'history') {
1209
+ untracked(() => {
1210
+ if (this.store)
1211
+ this.store.withTextEdit(origin, this.historyGroup, () => this.contentChanged.emit(content));
1212
+ else
1213
+ this.contentChanged.emit(content);
1214
+ });
1345
1215
  }
1346
- // Common HTML produced by external WYSIWYG editors also expresses marks as inline styles.
1347
- const css = el.style;
1348
- if (css?.fontWeight === 'bold' || Number(css?.fontWeight) >= 600)
1349
- next.push({ type: 'bold' });
1350
- if (css?.fontStyle === 'italic')
1351
- next.push({ type: 'italic' });
1352
- if (css?.textDecoration.includes('underline'))
1353
- next.push({ type: 'underline' });
1354
- if (css?.textDecoration.includes('line-through'))
1355
- next.push({ type: 'strike' });
1356
- if (blockTags.has(name))
1357
- newline();
1358
- Array.from(node.childNodes).forEach(child => visit(child, next));
1359
- if (blockTags.has(name))
1360
- newline();
1361
1216
  });
1362
- visit(element, []);
1363
- while (runs.length && !runs[0].text.trim())
1364
- runs.shift();
1365
- while (runs.length && !runs.at(-1).text.trim())
1366
- runs.pop();
1367
- if (runs.length) {
1368
- runs[0] = { ...runs[0], text: runs[0].text.replace(/^\s+/, '') };
1369
- const last = runs.length - 1;
1370
- runs[last] = { ...runs[last], text: runs[last].text.replace(/\s+$/, '') };
1217
+ // Capture before the surface and the block's own listeners. Structural Enter
1218
+ // stays with the content builder; multiline fields use the headless surface.
1219
+ this.element.addEventListener('paste', this.onPaste, true);
1220
+ this.element.addEventListener('keydown', this.onKeydown, true);
1221
+ this.element.addEventListener('beforeinput', this.onBeforeInput, true);
1222
+ afterNextRender(() => this.initialized.emit());
1223
+ afterRenderEffect(() => {
1224
+ const pending = this.store?.restoreTextSelection();
1225
+ const wrapper = this.element.closest('[data-block-id]');
1226
+ if (pending && wrapper?.getAttribute('data-block-id') === pending.blockId &&
1227
+ wrapper.querySelector('.ngs-content-editor-content-editable') === this.element) {
1228
+ this.activate();
1229
+ this.region.editor.setSelection(pending.selection);
1230
+ this.surface.focus();
1231
+ this.store.restoreTextSelection.set(null);
1232
+ }
1233
+ });
1234
+ }
1235
+ activate() {
1236
+ this.region.activate();
1237
+ const id = this.element.closest('[data-block-id]')?.getAttribute('data-block-id');
1238
+ if (id && this.store) {
1239
+ const scope = this.builder && 'scope' in this.builder ? this.builder.scope() : {};
1240
+ this.store.insertionTarget.set({ scope, afterId: id });
1241
+ }
1242
+ }
1243
+ focus() { this.activate(); this.surface.focus(); }
1244
+ getContent() { return this.region.content(); }
1245
+ alignment() { return this.props().find(prop => prop.name === 'text-alignment')?.value ?? 'left'; }
1246
+ setAlignment(value) {
1247
+ this.propsChanged.emit([
1248
+ ...this.props().filter(prop => prop.name !== 'text-alignment'),
1249
+ { name: 'text-alignment', value }
1250
+ ]);
1251
+ }
1252
+ onPaste = (event) => {
1253
+ if (event.defaultPrevented || this.region.editor.readOnly())
1254
+ return;
1255
+ const html = event.clipboardData?.getData('text/html');
1256
+ if (!html)
1257
+ return;
1258
+ try {
1259
+ const config = this.builder?.rootBuilder.config() ?? {};
1260
+ const parsed = this.importer.fromHtml(html, config);
1261
+ this.activate();
1262
+ this.surface.syncSelectionFromDom();
1263
+ const id = this.element.closest('[data-block-id]')?.getAttribute('data-block-id');
1264
+ const structural = parsed.blocks.length > 1 || parsed.blocks.some(block => block.type !== 'paragraph');
1265
+ const selection = this.region.editor.selection();
1266
+ if (structural && id && this.builder && selection) {
1267
+ const lines = this.region.editor.document().blocks;
1268
+ const offset = (point) => lines.slice(0, lines.findIndex(line => line.id === point.blockId))
1269
+ .reduce((sum, line) => sum + line.content.reduce((total, run) => total + run.text.length, 0) + 1, 0) + point.offset;
1270
+ if (this.builder.rootBuilder.pasteBlocksAtSelection(id, parsed, offset(selection.anchor), offset(selection.focus))) {
1271
+ event.preventDefault();
1272
+ event.stopImmediatePropagation();
1273
+ return;
1274
+ }
1275
+ }
1276
+ const content = contentEditorImportedText(parsed.blocks);
1277
+ if (!content.some(run => run.text))
1278
+ return;
1279
+ this.activate();
1280
+ this.surface.syncSelectionFromDom();
1281
+ event.preventDefault();
1282
+ event.stopImmediatePropagation();
1283
+ this.region.editor.insertTextContent(content);
1284
+ }
1285
+ catch {
1286
+ // The surface can still paste the plain-text representation on parse failure.
1371
1287
  }
1372
- return [...normalizeNgsHeadlessEditorTextContent(runs)];
1373
- };
1374
- const listItems = (element) => guarded(() => children(element).filter(el => tag(el) === 'li').map(li => {
1375
- const text = li.cloneNode(true);
1376
- children(text).filter(el => ['ul', 'ol'].includes(tag(el))).forEach(el => el.remove());
1377
- return { content: parseText(text), props: alignment(li), children: children(li).filter(el => ['ul', 'ol'].includes(tag(el))).flatMap(listItems) };
1378
- }));
1379
- const media = (element, figure) => {
1380
- const name = tag(element);
1381
- const kind = name === 'img' ? 'image' : name === 'video' ? 'media' : 'embed';
1382
- const src = safeContentEditorHtmlUrl(element.getAttribute('src') || element.querySelector('source')?.getAttribute('src'), kind);
1383
- if (!src)
1384
- return [];
1385
- const caption = figure ? direct(figure, 'figcaption') : undefined;
1386
- const settings = Object.fromEntries(['width', 'height'].flatMap(key => { const n = dimension(element, key); return n ? [[key, n]] : []; }));
1387
- const content = name === 'img' ? { src, alt: element.getAttribute('alt') ?? '' }
1388
- : name === 'video' ? { src, caption: caption?.textContent ?? '', orientation: 'landscape' }
1389
- : { url: src, type: element.getAttribute('title') ?? '' };
1390
- return [createBlock(name === 'img' ? 'image' : name === 'video' ? 'video' : 'embed', content, { settings })];
1391
1288
  };
1392
- const builtin = (element) => {
1393
- const name = tag(element);
1394
- const attrs = { props: alignment(element) };
1395
- if (ignoredTags.has(name))
1396
- return [];
1397
- if (element.matches('[data-content-editor="gallery"], .ngs-content-editor-html-gallery')) {
1398
- const images = children(element).flatMap(figure => {
1399
- const image = tag(figure) === 'img' ? figure : direct(figure, 'img');
1400
- const src = safeContentEditorHtmlUrl(image?.getAttribute('src'), 'image');
1401
- if (!image || !src)
1402
- return [];
1403
- const caption = direct(figure, 'figcaption');
1404
- return [{ id: createNgsHeadlessEditorId('image'), src, alt: image.getAttribute('alt') ?? '', caption: caption ? parseText(caption) : [] }];
1405
- });
1406
- return [createBlock('gallery', { images })];
1289
+ onKeydown = (event) => {
1290
+ if (event.key === 'Enter' && this.singleLine() && !event.shiftKey && !event.isComposing) {
1291
+ event.preventDefault();
1292
+ event.stopImmediatePropagation();
1293
+ this.pressedEnter.emit(event);
1407
1294
  }
1408
- if (element.matches('.ngs-content-editor-html-grid')) {
1409
- const container = direct(element, '.ngs-content-editor-html-grid-cells') ?? element;
1410
- const css = element.style;
1411
- const columnValue = Number(element.getAttribute('data-columns') || css?.getPropertyValue('--ngs-html-grid-columns'));
1412
- const gapValue = css?.getPropertyValue('--ngs-html-grid-gap').trim();
1413
- const settings = { columns: [2, 3, 4].includes(columnValue) ? columnValue : 2, gap: gapValue === '12px' ? 'small' : gapValue === '36px' ? 'large' : 'medium', stackOnMobile: container.classList.contains('ngs-content-editor-html-grid-stack') };
1414
- const cells = children(container).filter(cell => cell.matches('.ngs-content-editor-html-grid-cell')).map(cell => ({ id: createNgsHeadlessEditorId('cell'), blocks: parseBlocks(cell) }));
1415
- return [createBlock('grid', { cells }, { settings })];
1295
+ };
1296
+ onBeforeInput = (event) => {
1297
+ if (event.inputType === 'insertParagraph' && this.singleLine() && !event.isComposing) {
1298
+ event.preventDefault();
1299
+ event.stopImmediatePropagation();
1300
+ this.pressedEnter.emit(new KeyboardEvent('keydown', { key: 'Enter' }));
1416
1301
  }
1417
- if (name === 'p' || /^h[1-6]$/.test(name)) {
1418
- if (element.querySelector('img, video, iframe, a[download]'))
1419
- return parseBlocks(element);
1420
- return [createBlock(name === 'p' ? 'paragraph' : 'heading', parseText(element), { ...attrs, ...(name !== 'p' ? { settings: { level: Number(name[1]) } } : {}) })];
1302
+ };
1303
+ ngOnDestroy() {
1304
+ regions.delete(this.element);
1305
+ this.element.removeEventListener('paste', this.onPaste, true);
1306
+ this.element.removeEventListener('keydown', this.onKeydown, true);
1307
+ this.element.removeEventListener('beforeinput', this.onBeforeInput, true);
1308
+ }
1309
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorContentEditableDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1310
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.1.7", type: ContentEditorContentEditableDirective, isStandalone: true, selector: "[ngsContentEditorContentEditable]", inputs: { content: { classPropertyName: "content", publicName: "ngsContentEditorContentEditable", isSignal: true, isRequired: false, transformFunction: null }, settings: { classPropertyName: "settings", publicName: "settings", isSignal: true, isRequired: false, transformFunction: null }, props: { classPropertyName: "props", publicName: "props", isSignal: true, isRequired: false, transformFunction: null }, singleLine: { classPropertyName: "singleLine", publicName: "singleLine", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { contentChanged: "contentChanged", propsChanged: "propsChanged", pressedEnter: "pressedEnter", initialized: "initialized" }, host: { listeners: { "focus": "activate()" }, properties: { "class.align-left": "alignment() === \"left\"", "class.align-center": "alignment() === \"center\"", "class.align-right": "alignment() === \"right\"", "class.align-justify": "alignment() === \"justify\"" }, classAttribute: "ngs-content-editor-content-editable" }, providers: [provideNgsHeadlessEditorInlineRegion()], exportAs: ["ngsContentEditorContentEditable"], hostDirectives: [{ directive: i1.NgsHeadlessEditorSurface }], ngImport: i0 });
1311
+ }
1312
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorContentEditableDirective, decorators: [{
1313
+ type: Directive,
1314
+ args: [{
1315
+ selector: '[ngsContentEditorContentEditable]',
1316
+ exportAs: 'ngsContentEditorContentEditable',
1317
+ providers: [provideNgsHeadlessEditorInlineRegion()],
1318
+ hostDirectives: [NgsHeadlessEditorSurface],
1319
+ host: {
1320
+ 'class': 'ngs-content-editor-content-editable',
1321
+ '[class.align-left]': 'alignment() === "left"',
1322
+ '[class.align-center]': 'alignment() === "center"',
1323
+ '[class.align-right]': 'alignment() === "right"',
1324
+ '[class.align-justify]': 'alignment() === "justify"',
1325
+ '(focus)': 'activate()'
1326
+ }
1327
+ }]
1328
+ }], ctorParameters: () => [], propDecorators: { content: [{ type: i0.Input, args: [{ isSignal: true, alias: "ngsContentEditorContentEditable", required: false }] }], settings: [{ type: i0.Input, args: [{ isSignal: true, alias: "settings", required: false }] }], props: [{ type: i0.Input, args: [{ isSignal: true, alias: "props", required: false }] }], singleLine: [{ type: i0.Input, args: [{ isSignal: true, alias: "singleLine", required: false }] }], contentChanged: [{ type: i0.Output, args: ["contentChanged"] }], propsChanged: [{ type: i0.Output, args: ["propsChanged"] }], pressedEnter: [{ type: i0.Output, args: ["pressedEnter"] }], initialized: [{ type: i0.Output, args: ["initialized"] }] } });
1329
+
1330
+ class AddLinkDialog {
1331
+ _dialogRef = inject(DialogRef);
1332
+ _formBuilder = inject(FormBuilder);
1333
+ form = this._formBuilder.group({
1334
+ href: [''],
1335
+ openInNewTab: [true, [Validators.required]]
1336
+ });
1337
+ cancel() {
1338
+ this._dialogRef.close(false);
1339
+ }
1340
+ add() {
1341
+ this._dialogRef.close(this.form.value);
1342
+ }
1343
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: AddLinkDialog, deps: [], target: i0.ɵɵFactoryTarget.Component });
1344
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "22.1.7", type: AddLinkDialog, isStandalone: true, selector: "ngs-add-link", ngImport: i0, template: "<h1 ngs-dialog-title>Add link</h1>\n<ngs-dialog-content [formGroup]=\"form\" class=\"!overflow-hidden\">\n <ngs-form-field class=\"w-full\">\n <ngs-label>Href (Url, Tel or other)</ngs-label>\n <input ngsInput type=\"text\" formControlName=\"href\">\n </ngs-form-field>\n <ngs-slide-toggle formControlName=\"openInNewTab\">Open link in a new tab</ngs-slide-toggle>\n</ngs-dialog-content>\n<ngs-dialog-actions>\n <button ngsButton (click)=\"cancel()\">Cancel</button>\n <button ngsButton=\"filled\"\n [disabled]=\"form.invalid\" (click)=\"add()\">Add</button>\n</ngs-dialog-actions>\n", styles: [""], dependencies: [{ kind: "component", type: DialogContent, selector: "ngs-dialog-content,[ngs-dialog-content],[ngsDialogContent]" }, { kind: "component", type: FormField, selector: "ngs-form-field", inputs: ["labelMode", "subscriptHiddenIfEmpty", "sameHeightAsButton"], exportAs: ["ngsFormField"] }, { kind: "directive", type: Input, selector: "input[ngsInput], textarea[ngsInput]", inputs: ["id", "placeholder", "required", "disabled", "readonly", "errorStateMatcher"], exportAs: ["ngsInput"] }, { kind: "component", type: DialogTitle, selector: "ngs-dialog-title, [ngs-dialog-title], [ngsDialogTitle]", inputs: ["id"], exportAs: ["ngsDialogTitle"] }, { kind: "component", type: DialogActions, selector: "ngs-dialog-actions, [ngs-dialog-actions], [ngsDialogActions]", inputs: ["align"] }, { kind: "component", type: Button, selector: " button[ngsButton], button[ngsIconButton], a[ngsButton], a[ngsIconButton] ", inputs: ["ngsButton", "ngsIconButton", "loading", "disabled", "disabledInteractive", "disableRipple", "reverse", "fullWidth", "hideTextOnMobile"], exportAs: ["ngsButton"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i1$1.DefaultValueAccessor, selector: "input:not([type=checkbox]):not([ngNoCva])[formControlName],textarea:not([ngNoCva])[formControlName],input:not([type=checkbox]):not([ngNoCva])[formControl],textarea:not([ngNoCva])[formControl],input:not([type=checkbox]):not([ngNoCva])[ngModel],textarea:not([ngNoCva])[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i1$1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1$1.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],[formArray],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i1$1.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i1$1.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { kind: "component", type: Label, selector: "ngs-label" }, { kind: "component", type: SlideToggle, selector: "ngs-slide-toggle", inputs: ["id", "name", "labelPosition", "aria-label", "aria-labelledby", "aria-describedby", "required", "disabled", "disableRipple", "tabIndex", "hideIcon", "color", "checked"], outputs: ["disabledChange", "checkedChange", "change", "toggleChange"], exportAs: ["ngsSlideToggle"] }], changeDetection: i0.ChangeDetectionStrategy.Eager });
1345
+ }
1346
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: AddLinkDialog, decorators: [{
1347
+ type: Component,
1348
+ args: [{ selector: 'ngs-add-link', imports: [
1349
+ DialogContent,
1350
+ FormField,
1351
+ Input,
1352
+ DialogTitle,
1353
+ DialogActions,
1354
+ Button,
1355
+ ReactiveFormsModule,
1356
+ Label,
1357
+ SlideToggle
1358
+ ], changeDetection: ChangeDetectionStrategy.Eager, template: "<h1 ngs-dialog-title>Add link</h1>\n<ngs-dialog-content [formGroup]=\"form\" class=\"!overflow-hidden\">\n <ngs-form-field class=\"w-full\">\n <ngs-label>Href (Url, Tel or other)</ngs-label>\n <input ngsInput type=\"text\" formControlName=\"href\">\n </ngs-form-field>\n <ngs-slide-toggle formControlName=\"openInNewTab\">Open link in a new tab</ngs-slide-toggle>\n</ngs-dialog-content>\n<ngs-dialog-actions>\n <button ngsButton (click)=\"cancel()\">Cancel</button>\n <button ngsButton=\"filled\"\n [disabled]=\"form.invalid\" (click)=\"add()\">Add</button>\n</ngs-dialog-actions>\n" }]
1359
+ }] });
1360
+
1361
+ class EditLinkDialog {
1362
+ _dialogRef = inject(DialogRef);
1363
+ _dialogData = inject(DIALOG_DATA);
1364
+ _formBuilder = inject(FormBuilder);
1365
+ form = this._formBuilder.group({
1366
+ href: [this._dialogData.href],
1367
+ openInNewTab: [this._dialogData.openInNewTab, [Validators.required]]
1368
+ });
1369
+ cancel() {
1370
+ this._dialogRef.close(false);
1371
+ }
1372
+ add() {
1373
+ this._dialogRef.close(this.form.value);
1374
+ }
1375
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: EditLinkDialog, deps: [], target: i0.ɵɵFactoryTarget.Component });
1376
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "22.1.7", type: EditLinkDialog, isStandalone: true, selector: "ngs-edit-link", ngImport: i0, template: "<h1 ngs-dialog-title>Edit link</h1>\n<ngs-dialog-content [formGroup]=\"form\" class=\"!overflow-hidden\">\n <ngs-form-field class=\"w-full\">\n <ngs-label>Href (Url, Tel or other)</ngs-label>\n <input ngsInput type=\"text\" formControlName=\"href\">\n <ngs-hint>To delete the link, clear this field and apply</ngs-hint>\n </ngs-form-field>\n <ngs-slide-toggle formControlName=\"openInNewTab\" class=\"mt-5\">Open link in a new tab</ngs-slide-toggle>\n</ngs-dialog-content>\n<ngs-dialog-actions>\n <button ngsButton (click)=\"cancel()\">Cancel</button>\n <button ngsButton=\"filled\"\n [disabled]=\"form.invalid\" (click)=\"add()\">Apply</button>\n</ngs-dialog-actions>\n", styles: [""], dependencies: [{ kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i1$1.DefaultValueAccessor, selector: "input:not([type=checkbox]):not([ngNoCva])[formControlName],textarea:not([ngNoCva])[formControlName],input:not([type=checkbox]):not([ngNoCva])[formControl],textarea:not([ngNoCva])[formControl],input:not([type=checkbox]):not([ngNoCva])[ngModel],textarea:not([ngNoCva])[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i1$1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1$1.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],[formArray],form:not([ngNoForm]),[ngForm]" }, { kind: "component", type: Button, selector: " button[ngsButton], button[ngsIconButton], a[ngsButton], a[ngsIconButton] ", inputs: ["ngsButton", "ngsIconButton", "loading", "disabled", "disabledInteractive", "disableRipple", "reverse", "fullWidth", "hideTextOnMobile"], exportAs: ["ngsButton"] }, { kind: "component", type: DialogActions, selector: "ngs-dialog-actions, [ngs-dialog-actions], [ngsDialogActions]", inputs: ["align"] }, { kind: "component", type: DialogContent, selector: "ngs-dialog-content,[ngs-dialog-content],[ngsDialogContent]" }, { kind: "component", type: DialogTitle, selector: "ngs-dialog-title, [ngs-dialog-title], [ngsDialogTitle]", inputs: ["id"], exportAs: ["ngsDialogTitle"] }, { kind: "component", type: FormField, selector: "ngs-form-field", inputs: ["labelMode", "subscriptHiddenIfEmpty", "sameHeightAsButton"], exportAs: ["ngsFormField"] }, { kind: "directive", type: Input, selector: "input[ngsInput], textarea[ngsInput]", inputs: ["id", "placeholder", "required", "disabled", "readonly", "errorStateMatcher"], exportAs: ["ngsInput"] }, { kind: "component", type: Label, selector: "ngs-label" }, { kind: "component", type: SlideToggle, selector: "ngs-slide-toggle", inputs: ["id", "name", "labelPosition", "aria-label", "aria-labelledby", "aria-describedby", "required", "disabled", "disableRipple", "tabIndex", "hideIcon", "color", "checked"], outputs: ["disabledChange", "checkedChange", "change", "toggleChange"], exportAs: ["ngsSlideToggle"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i1$1.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i1$1.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { kind: "component", type: Hint, selector: "ngs-hint", inputs: ["align"], exportAs: ["ngsHint"] }], changeDetection: i0.ChangeDetectionStrategy.Eager });
1377
+ }
1378
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: EditLinkDialog, decorators: [{
1379
+ type: Component,
1380
+ args: [{ selector: 'ngs-edit-link', imports: [
1381
+ FormsModule,
1382
+ Button,
1383
+ DialogActions,
1384
+ DialogContent,
1385
+ DialogTitle,
1386
+ FormField,
1387
+ Input,
1388
+ Label,
1389
+ SlideToggle,
1390
+ ReactiveFormsModule,
1391
+ Hint
1392
+ ], changeDetection: ChangeDetectionStrategy.Eager, template: "<h1 ngs-dialog-title>Edit link</h1>\n<ngs-dialog-content [formGroup]=\"form\" class=\"!overflow-hidden\">\n <ngs-form-field class=\"w-full\">\n <ngs-label>Href (Url, Tel or other)</ngs-label>\n <input ngsInput type=\"text\" formControlName=\"href\">\n <ngs-hint>To delete the link, clear this field and apply</ngs-hint>\n </ngs-form-field>\n <ngs-slide-toggle formControlName=\"openInNewTab\" class=\"mt-5\">Open link in a new tab</ngs-slide-toggle>\n</ngs-dialog-content>\n<ngs-dialog-actions>\n <button ngsButton (click)=\"cancel()\">Cancel</button>\n <button ngsButton=\"filled\"\n [disabled]=\"form.invalid\" (click)=\"add()\">Apply</button>\n</ngs-dialog-actions>\n" }]
1393
+ }] });
1394
+
1395
+ class TextColorComponent {
1396
+ _document = inject(DOCUMENT$1);
1397
+ recentlyUsed = model(this._getRecentlyUsed(), /* @ts-ignore */
1398
+ ...(ngDevMode ? [{ debugName: "recentlyUsed" }] : /* istanbul ignore next */ []));
1399
+ selectedTextColor = model(null, /* @ts-ignore */
1400
+ ...(ngDevMode ? [{ debugName: "selectedTextColor" }] : /* istanbul ignore next */ []));
1401
+ selectedBackgroundColor = model(null, /* @ts-ignore */
1402
+ ...(ngDevMode ? [{ debugName: "selectedBackgroundColor" }] : /* istanbul ignore next */ []));
1403
+ textColors = input([
1404
+ {
1405
+ name: 'Default',
1406
+ color: '',
1407
+ type: 'text'
1408
+ },
1409
+ {
1410
+ name: 'Gray',
1411
+ color: '#7f7f7f',
1412
+ type: 'text'
1413
+ },
1414
+ {
1415
+ name: 'Brown',
1416
+ color: '#ae2012',
1417
+ type: 'text'
1418
+ },
1419
+ {
1420
+ name: 'Orange',
1421
+ color: '#fb5607',
1422
+ type: 'text'
1423
+ },
1424
+ {
1425
+ name: 'Yellow',
1426
+ color: '#ffa200',
1427
+ type: 'text'
1428
+ },
1429
+ {
1430
+ name: 'Green',
1431
+ color: '#40916c',
1432
+ type: 'text'
1433
+ },
1434
+ {
1435
+ name: 'Blue',
1436
+ color: '#00bbf9',
1437
+ type: 'text'
1438
+ },
1439
+ {
1440
+ name: 'Purple',
1441
+ color: '#907ad6',
1442
+ type: 'text'
1443
+ },
1444
+ {
1445
+ name: 'Pink',
1446
+ color: '#fa3faf',
1447
+ type: 'text'
1448
+ },
1449
+ {
1450
+ name: 'Red',
1451
+ color: '#ef233c',
1452
+ type: 'text'
1421
1453
  }
1422
- if (name === 'hr')
1423
- return [createBlock('divider', null)];
1424
- if (name === 'pre') {
1425
- const code = direct(element, 'code') ?? element;
1426
- const language = code.getAttribute('data-language') ?? Array.from(code.classList).find(cls => cls.startsWith('language-'))?.slice(9) ?? 'none';
1427
- return [createBlock('code', [createNgsHeadlessEditorText(code.textContent ?? '')], { settings: { language } })];
1454
+ ], /* @ts-ignore */
1455
+ ...(ngDevMode ? [{ debugName: "textColors" }] : /* istanbul ignore next */ []));
1456
+ backgroundColors = input([
1457
+ {
1458
+ name: 'Default',
1459
+ color: '',
1460
+ type: 'background'
1461
+ },
1462
+ {
1463
+ name: 'Gray',
1464
+ color: '#e9ecef',
1465
+ type: 'background'
1466
+ },
1467
+ {
1468
+ name: 'Brown',
1469
+ color: '#ffe0c0',
1470
+ type: 'background'
1471
+ },
1472
+ {
1473
+ name: 'Orange',
1474
+ color: '#ffd8c6',
1475
+ type: 'background'
1476
+ },
1477
+ {
1478
+ name: 'Yellow',
1479
+ color: '#fff3b0',
1480
+ type: 'background'
1481
+ },
1482
+ {
1483
+ name: 'Green',
1484
+ color: '#eff6e0',
1485
+ type: 'background'
1486
+ },
1487
+ {
1488
+ name: 'Blue',
1489
+ color: '#edf6f9',
1490
+ type: 'background'
1491
+ },
1492
+ {
1493
+ name: 'Purple',
1494
+ color: '#e0aaff',
1495
+ type: 'background'
1496
+ },
1497
+ {
1498
+ name: 'Pink',
1499
+ color: '#fae0ec',
1500
+ type: 'background'
1501
+ },
1502
+ {
1503
+ name: 'Red',
1504
+ color: '#ffdccc',
1505
+ type: 'background'
1428
1506
  }
1429
- if (name === 'ul' || name === 'ol')
1430
- return [createBlock(name === 'ol' ? 'orderedList' : 'bulletList', listItems(element), { settings: { listStyle: name === 'ol' ? 'ordered' : 'bullet' } })];
1431
- if (name === 'details') {
1432
- const summary = direct(element, 'summary');
1433
- const body = element.cloneNode(true);
1434
- direct(body, 'summary')?.remove();
1435
- return [createBlock('toggle', { title: summary ? parseText(summary) : [], blocks: parseBlocks(body) }, { settings: { expanded: element.hasAttribute('open') } })];
1507
+ ], /* @ts-ignore */
1508
+ ...(ngDevMode ? [{ debugName: "backgroundColors" }] : /* istanbul ignore next */ []));
1509
+ textColorChanged = output();
1510
+ backgroundColorChanged = output();
1511
+ selectRecentlyColor(color) {
1512
+ if (color.type === 'text') {
1513
+ this.selectTextColor(color);
1436
1514
  }
1437
- if (name === 'aside' && (element.hasAttribute('data-callout') || element.classList.contains('ngs-content-editor-html-callout'))) {
1438
- const value = element.getAttribute('data-callout');
1439
- return [createBlock('callout', parseText(element), { ...attrs, settings: { variant: ['note', 'tip', 'warning', 'danger'].includes(value ?? '') ? value : 'note' } })];
1515
+ else if (color.type === 'background') {
1516
+ this.selectBackgroundColor(color);
1440
1517
  }
1441
- if (name === 'blockquote' || (name === 'figure' && direct(element, 'blockquote'))) {
1442
- const quote = name === 'blockquote' ? element : direct(element, 'blockquote');
1443
- const caption = name === 'figure' ? direct(element, 'figcaption') : undefined;
1444
- return [createBlock('quote', { cite: { content: parseText(quote), props: alignment(quote) }, caption: { content: caption ? parseText(caption) : [], props: caption ? alignment(caption) : [] } })];
1518
+ }
1519
+ selectTextColor(color) {
1520
+ this.selectedTextColor.set(color);
1521
+ this.textColorChanged.emit(color.color);
1522
+ this._addToRecently(color);
1523
+ }
1524
+ selectBackgroundColor(color) {
1525
+ this.selectedBackgroundColor.set(color);
1526
+ this.backgroundColorChanged.emit(color.color);
1527
+ this._addToRecently(color);
1528
+ }
1529
+ _addToRecently(color) {
1530
+ const hasRecentlyUsed = this.recentlyUsed()
1531
+ .filter(recentlyColor => recentlyColor.name === color.name && recentlyColor.type === color.type)
1532
+ .length > 0;
1533
+ if (hasRecentlyUsed) {
1534
+ return;
1445
1535
  }
1446
- if (name === 'table') {
1447
- const rows = Array.from(element.querySelectorAll('tr')).filter(row => row.closest('table') === element);
1448
- const cells = rows.map(row => children(row).filter(cell => ['td', 'th'].includes(tag(cell))));
1449
- return [createBlock('table', null, {
1450
- rows: cells.map(row => row.map(parseText)), header: !!cells[0]?.some(cell => tag(cell) === 'th'),
1451
- cellMetadata: cells.map(row => row.map(cell => ({ props: alignment(cell), options: {
1452
- colspan: Math.max(1, Math.floor(dimension(cell, 'colspan') ?? 1)), rowspan: Math.max(1, Math.floor(dimension(cell, 'rowspan') ?? 1)),
1453
- ...(dimension(cell, 'width') ? { width: dimension(cell, 'width') } : {})
1454
- } })))
1455
- })];
1536
+ let colors = [...this.recentlyUsed()];
1537
+ colors = colors.length >= 5 ? colors.slice(1, 5) : colors;
1538
+ this.recentlyUsed.set([...colors, color]);
1539
+ try {
1540
+ this._document.defaultView?.localStorage.setItem('ngsContentEditorRecentlyUsedTextColor', JSON.stringify(this.recentlyUsed()));
1456
1541
  }
1457
- if (name === 'figure') {
1458
- const child = direct(element, 'img, video, iframe');
1459
- if (child)
1460
- return media(child, element);
1542
+ catch {
1543
+ // Keep the recent colors in memory when browser storage is unavailable.
1461
1544
  }
1462
- if (['img', 'video', 'iframe'].includes(name))
1463
- return media(element);
1464
- if (name === 'a' && element.hasAttribute('download')) {
1465
- const url = safeContentEditorHtmlUrl(element.getAttribute('href'), 'attachment');
1466
- return url ? [createBlock('attachment', { url, name: element.getAttribute('download') || element.textContent?.trim() || 'Download', size: 0, mimeType: '' })] : [];
1545
+ }
1546
+ _getRecentlyUsed() {
1547
+ try {
1548
+ const value = this._document.defaultView?.localStorage.getItem('ngsContentEditorRecentlyUsedTextColor');
1549
+ const colors = value ? JSON.parse(value) : [];
1550
+ return Array.isArray(colors) ? colors : [];
1467
1551
  }
1468
- return parseBlocks(element);
1469
- };
1470
- const context = {
1471
- createBlock, createId: createNgsHeadlessEditorId, parseText, parseBlocks: element => parseBlocks(element),
1472
- defaultFromHtml: builtin, safeUrl: safeContentEditorHtmlUrl
1473
- };
1474
- const parseElement = (element) => guarded(() => {
1475
- if (ignoredTags.has(tag(element)))
1552
+ catch {
1476
1553
  return [];
1477
- for (const override of overrides) {
1478
- if (element.matches(override.selector)) {
1479
- const result = override.parse(element, context);
1480
- return result === null ? [] : Array.isArray(result) ? [...result] : [result];
1481
- }
1482
1554
  }
1483
- return builtin(element);
1484
- });
1485
- const parseBlocks = (element) => guarded(() => {
1486
- const output = [];
1487
- let inline = inert.createElement('div');
1488
- const flush = () => {
1489
- const runs = parseText(inline);
1490
- if (runs.some(run => run.text.trim()))
1491
- output.push(createBlock('paragraph', runs, { props: alignment(element) }));
1492
- inline = inert.createElement('div');
1493
- };
1494
- for (const node of Array.from(element.childNodes)) {
1495
- if (node.nodeType === 1) {
1496
- const child = node;
1497
- if (ignoredTags.has(tag(child)))
1498
- continue;
1499
- if (blockTags.has(tag(child)) || ['img', 'video', 'iframe'].includes(tag(child)) || child.matches('a[download]') || overrides.some(override => child.matches(override.selector))) {
1500
- flush();
1501
- output.push(...parseElement(child));
1502
- continue;
1503
- }
1504
- // Unknown inline wrappers may contain block elements; keep those structures.
1505
- if (child.querySelector([...blockTags, 'img', 'video', 'iframe', 'a[download]'].join(',')) || overrides.some(override => child.querySelector(override.selector))) {
1506
- flush();
1507
- output.push(...parseElement(child));
1508
- continue;
1509
- }
1555
+ }
1556
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: TextColorComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
1557
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.7", type: TextColorComponent, isStandalone: true, selector: "ngs-text-color", inputs: { recentlyUsed: { classPropertyName: "recentlyUsed", publicName: "recentlyUsed", isSignal: true, isRequired: false, transformFunction: null }, selectedTextColor: { classPropertyName: "selectedTextColor", publicName: "selectedTextColor", isSignal: true, isRequired: false, transformFunction: null }, selectedBackgroundColor: { classPropertyName: "selectedBackgroundColor", publicName: "selectedBackgroundColor", isSignal: true, isRequired: false, transformFunction: null }, textColors: { classPropertyName: "textColors", publicName: "textColors", isSignal: true, isRequired: false, transformFunction: null }, backgroundColors: { classPropertyName: "backgroundColors", publicName: "backgroundColors", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { recentlyUsed: "recentlyUsedChange", selectedTextColor: "selectedTextColorChange", selectedBackgroundColor: "selectedBackgroundColorChange", textColorChanged: "textColorChanged", backgroundColorChanged: "backgroundColorChanged" }, ngImport: i0, template: "@if (recentlyUsed().length > 0) {\n <div class=\"mb-5\">\n <div class=\"text-xs text-neutral-700 text-semibold\">Recently colors</div>\n <div class=\"flex gap-2 flex-wrap mt-3\">\n @for (recentlyColor of recentlyUsed(); track recentlyColor) {\n @if (recentlyColor.type === 'text') {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\"\n [style.color]=\"recentlyColor.color\" [ngsTooltip]=\"recentlyColor.name\"\n (click)=\"selectRecentlyColor(recentlyColor)\">\n <ngs-icon name=\"fluent:text-field-24-regular\"/>\n </button>\n } @else if (recentlyColor.type === 'background') {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\"\n [style.background-color]=\"recentlyColor.color\" [ngsTooltip]=\"recentlyColor.name\"\n (click)=\"selectRecentlyColor(recentlyColor)\">\n </button>\n }\n }\n </div>\n </div>\n}\n\n<div class=\"mb-5\">\n <div class=\"text-xs text-neutral-700 text-semibold\">Text color</div>\n <div class=\"flex gap-2 flex-wrap mt-3\">\n @for (textColor of textColors(); track $index) {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\n [&.is-selected]:outline [&.is-selected]:outline-primary\"\n [style.color]=\"textColor.color\" [ngsTooltip]=\"textColor.name\"\n [class.is-selected]=\"selectedTextColor()?.color === textColor.color\"\n (click)=\"selectTextColor(textColor)\">\n <ngs-icon name=\"fluent:text-field-24-regular\"/>\n </button>\n }\n </div>\n</div>\n\n<div>\n <div class=\"text-xs text-neutral-700 text-semibold\">Background color</div>\n <div class=\"flex gap-2 flex-wrap mt-3\">\n @for (backgroundColor of backgroundColors(); track $index) {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\n [&.is-selected]:outline [&.is-selected]:outline-primary\"\n [style.background-color]=\"backgroundColor.color\" [ngsTooltip]=\"backgroundColor.name\"\n [class.is-selected]=\"selectedBackgroundColor()?.color === backgroundColor.color\"\n (click)=\"selectBackgroundColor(backgroundColor)\">\n </button>\n }\n </div>\n</div>\n", styles: [":host{display:block;width:172px}\n"], dependencies: [{ kind: "component", type: Icon, selector: "ngs-icon", inputs: ["name"], exportAs: ["ngsIcon"] }, { kind: "directive", type: Tooltip, selector: "[ngsTooltip]", inputs: ["ngsTooltip", "ngsTooltipPosition", "ngsTooltipClass", "ngsTooltipShowDelay", "ngsTooltipHideDelay", "ngsTooltipOffset", "ngsTooltipPositionAtOrigin", "ngsTooltipDisabled"], exportAs: ["ngsTooltip"] }], changeDetection: i0.ChangeDetectionStrategy.Eager });
1558
+ }
1559
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: TextColorComponent, decorators: [{
1560
+ type: Component,
1561
+ args: [{ selector: 'ngs-text-color', imports: [
1562
+ Icon,
1563
+ Tooltip
1564
+ ], changeDetection: ChangeDetectionStrategy.Eager, template: "@if (recentlyUsed().length > 0) {\n <div class=\"mb-5\">\n <div class=\"text-xs text-neutral-700 text-semibold\">Recently colors</div>\n <div class=\"flex gap-2 flex-wrap mt-3\">\n @for (recentlyColor of recentlyUsed(); track recentlyColor) {\n @if (recentlyColor.type === 'text') {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\"\n [style.color]=\"recentlyColor.color\" [ngsTooltip]=\"recentlyColor.name\"\n (click)=\"selectRecentlyColor(recentlyColor)\">\n <ngs-icon name=\"fluent:text-field-24-regular\"/>\n </button>\n } @else if (recentlyColor.type === 'background') {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\"\n [style.background-color]=\"recentlyColor.color\" [ngsTooltip]=\"recentlyColor.name\"\n (click)=\"selectRecentlyColor(recentlyColor)\">\n </button>\n }\n }\n </div>\n </div>\n}\n\n<div class=\"mb-5\">\n <div class=\"text-xs text-neutral-700 text-semibold\">Text color</div>\n <div class=\"flex gap-2 flex-wrap mt-3\">\n @for (textColor of textColors(); track $index) {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\n [&.is-selected]:outline [&.is-selected]:outline-primary\"\n [style.color]=\"textColor.color\" [ngsTooltip]=\"textColor.name\"\n [class.is-selected]=\"selectedTextColor()?.color === textColor.color\"\n (click)=\"selectTextColor(textColor)\">\n <ngs-icon name=\"fluent:text-field-24-regular\"/>\n </button>\n }\n </div>\n</div>\n\n<div>\n <div class=\"text-xs text-neutral-700 text-semibold\">Background color</div>\n <div class=\"flex gap-2 flex-wrap mt-3\">\n @for (backgroundColor of backgroundColors(); track $index) {\n <button class=\"rounded-sm border border-border size-7 flex-none flex items-center justify-center cursor-pointer\n [&.is-selected]:outline [&.is-selected]:outline-primary\"\n [style.background-color]=\"backgroundColor.color\" [ngsTooltip]=\"backgroundColor.name\"\n [class.is-selected]=\"selectedBackgroundColor()?.color === backgroundColor.color\"\n (click)=\"selectBackgroundColor(backgroundColor)\">\n </button>\n }\n </div>\n</div>\n", styles: [":host{display:block;width:172px}\n"] }]
1565
+ }], propDecorators: { recentlyUsed: [{ type: i0.Input, args: [{ isSignal: true, alias: "recentlyUsed", required: false }] }, { type: i0.Output, args: ["recentlyUsedChange"] }], selectedTextColor: [{ type: i0.Input, args: [{ isSignal: true, alias: "selectedTextColor", required: false }] }, { type: i0.Output, args: ["selectedTextColorChange"] }], selectedBackgroundColor: [{ type: i0.Input, args: [{ isSignal: true, alias: "selectedBackgroundColor", required: false }] }, { type: i0.Output, args: ["selectedBackgroundColorChange"] }], textColors: [{ type: i0.Input, args: [{ isSignal: true, alias: "textColors", required: false }] }], backgroundColors: [{ type: i0.Input, args: [{ isSignal: true, alias: "backgroundColors", required: false }] }], textColorChanged: [{ type: i0.Output, args: ["textColorChanged"] }], backgroundColorChanged: [{ type: i0.Output, args: ["backgroundColorChanged"] }] } });
1566
+
1567
+ class CommandBarComponent {
1568
+ editor = inject(NgsHeadlessEditor);
1569
+ dialog = inject(Dialog);
1570
+ observedElement = input(null, /* @ts-ignore */
1571
+ ...(ngDevMode ? [{ debugName: "observedElement" }] : /* istanbul ignore next */ []));
1572
+ alignment = computed(() => this.region()?.alignment() ?? 'left', /* @ts-ignore */
1573
+ ...(ngDevMode ? [{ debugName: "alignment" }] : /* istanbul ignore next */ []));
1574
+ savedSelection = null;
1575
+ region() { return ContentEditorContentEditableDirective.forElement(this.observedElement()); }
1576
+ toggleBold() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_BOLD); }
1577
+ toggleItalic() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_ITALIC); }
1578
+ toggleCode() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_CODE); }
1579
+ toggleStrike() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_STRIKE); }
1580
+ toggleUnderline() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_UNDERLINE); }
1581
+ toggleSuperscript() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_SUPERSCRIPT); }
1582
+ toggleSubscript() { this.editor.execute(NGS_HEADLESS_EDITOR_TOGGLE_SUBSCRIPT); }
1583
+ isLinkActive() { return this.editor.isMarkActive('link'); }
1584
+ isActive(tag) {
1585
+ return this.editor.isMarkActive({ strong: 'bold', em: 'italic', s: 'strike', u: 'underline', sup: 'superscript', sub: 'subscript' }[tag] ?? tag);
1586
+ }
1587
+ setTextAlignment(value) { this.restoreSelection()?.setAlignment(value); }
1588
+ isTextAlignment(value) { return this.alignment() === value; }
1589
+ addLink() { this.openLinkDialog(false); }
1590
+ editLink() { this.openLinkDialog(true); }
1591
+ openLinkDialog(edit) {
1592
+ this.retainSelection();
1593
+ const saved = this.savedSelection;
1594
+ if (!saved)
1595
+ return;
1596
+ const target = saved.region.region.editor;
1597
+ const mark = target.getActiveMark('link');
1598
+ const ref = edit
1599
+ ? this.dialog.open(EditLinkDialog, { data: { href: mark?.attrs?.['href'], openInNewTab: mark?.attrs?.['target'] === '_blank' }, width: '500px', restoreFocus: false })
1600
+ : this.dialog.open(AddLinkDialog, { width: '500px', restoreFocus: false });
1601
+ ref.afterClosed().subscribe((value) => {
1602
+ if (!this.restoreSelection())
1603
+ return;
1604
+ if (value) {
1605
+ if (value.href)
1606
+ this.editor.execute(NGS_HEADLESS_EDITOR_SET_LINK, { href: value.href, target: value.openInNewTab ? '_blank' : '_self' });
1607
+ else
1608
+ this.editor.execute(NGS_HEADLESS_EDITOR_UNSET_LINK);
1510
1609
  }
1511
- inline.appendChild(node.cloneNode(true));
1512
- }
1513
- flush();
1514
- return output;
1515
- });
1516
- return contentEditorFromJson({ version: 1, blocks: parseBlocks(inert.body) }, config, options);
1610
+ this.restoreSelectionAfterOverlay();
1611
+ });
1612
+ }
1613
+ preserveSelection(event) {
1614
+ event.preventDefault();
1615
+ this.region()?.activate();
1616
+ this.retainSelection();
1617
+ }
1618
+ retainSelection() {
1619
+ if (this.savedSelection)
1620
+ return;
1621
+ const region = this.region();
1622
+ const selection = region?.region.editor.selection();
1623
+ if (region && selection)
1624
+ this.savedSelection = { region, selection };
1625
+ }
1626
+ restoreSelection() {
1627
+ const saved = this.savedSelection;
1628
+ if (!saved)
1629
+ return this.region();
1630
+ if (!this.observedElement()?.isConnected || saved.region.region.editor !== this.editor.inlineTarget())
1631
+ return;
1632
+ saved.region.region.editor.setSelection(saved.selection);
1633
+ return saved.region;
1634
+ }
1635
+ restoreSelectionAfterOverlay() {
1636
+ // MenuTrigger restores its own focus after emitting menuClosed.
1637
+ // Restore the editor afterwards, using model points rather than old DOM nodes.
1638
+ Promise.resolve().then(() => {
1639
+ const region = this.restoreSelection();
1640
+ this.savedSelection = null;
1641
+ if (region && this.observedElement()?.isConnected)
1642
+ region.focus();
1643
+ });
1644
+ }
1645
+ preventMenuClose(event) { event.stopPropagation(); event.preventDefault(); }
1646
+ onTextColorChanged(color) {
1647
+ const region = this.restoreSelection();
1648
+ if (!region)
1649
+ return;
1650
+ if (color)
1651
+ this.editor.execute(NGS_HEADLESS_EDITOR_SET_TEXT_COLOR, color);
1652
+ else
1653
+ this.editor.execute(NGS_HEADLESS_EDITOR_UNSET_TEXT_COLOR);
1654
+ region.focus();
1655
+ }
1656
+ onBackgroundColorChanged(color) {
1657
+ const region = this.restoreSelection();
1658
+ if (!region)
1659
+ return;
1660
+ if (color)
1661
+ this.editor.execute(NGS_HEADLESS_EDITOR_SET_BACKGROUND_COLOR, color);
1662
+ else
1663
+ this.editor.execute(NGS_HEADLESS_EDITOR_UNSET_BACKGROUND_COLOR);
1664
+ region.focus();
1665
+ }
1666
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: CommandBarComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
1667
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.7", type: CommandBarComponent, isStandalone: true, selector: "ngs-command-bar", inputs: { observedElement: { classPropertyName: "observedElement", publicName: "observedElement", isSignal: true, isRequired: false, transformFunction: null } }, host: { listeners: { "mousedown": "preserveSelection($event)" }, classAttribute: "ngs-command-bar" }, ngImport: i0, template: "<div class=\"flex items-center gap-1\">\n <button ngsIconButton (click)=\"toggleBold()\"\n [class.is-active]=\"isActive('strong')\">\n <ngs-icon name=\"fluent:text-bold-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleItalic()\"\n [class.is-active]=\"isActive('em')\">\n <ngs-icon name=\"fluent:text-italic-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleStrike()\"\n [class.is-active]=\"isActive('s')\">\n <ngs-icon name=\"fluent:text-strikethrough-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleUnderline()\"\n [class.is-active]=\"isActive('u')\">\n <ngs-icon name=\"fluent:text-underline-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleSuperscript()\"\n [class.is-active]=\"isActive('sup')\">\n <ngs-icon name=\"fluent:text-superscript-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleSubscript()\"\n [class.is-active]=\"isActive('sub')\">\n <ngs-icon name=\"fluent:text-subscript-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleCode()\"\n [class.is-active]=\"isActive('code')\">\n <ngs-icon name=\"fluent:code-24-regular\"/>\n </button>\n\n @if (isLinkActive()) {\n <button ngsIconButton (click)=\"editLink()\">\n <ngs-icon name=\"fluent:link-24-regular\"/>\n </button>\n } @else {\n <button ngsIconButton (click)=\"addLink()\">\n <ngs-icon name=\"fluent:link-add-24-regular\"/>\n </button>\n }\n <button ngsIconButton [ngsMenuTriggerFor]=\"alignMenu\"\n (menuOpened)=\"retainSelection()\" (menuClosed)=\"restoreSelectionAfterOverlay()\">\n @switch (alignment()) {\n @case ('left') {\n <ngs-icon name=\"fluent:text-align-left-24-regular\"/>\n }\n @case ('center') {\n <ngs-icon name=\"fluent:text-align-center-24-regular\"/>\n }\n @case ('right') {\n <ngs-icon name=\"fluent:text-align-right-24-regular\"/>\n }\n }\n </button>\n <button ngsIconButton [ngsMenuTriggerFor]=\"formatColorText\"\n (menuOpened)=\"retainSelection()\" (menuClosed)=\"restoreSelectionAfterOverlay()\">\n <ngs-icon name=\"fluent:text-color-24-regular\"/>\n </button>\n</div>\n\n<ngs-menu #alignMenu=\"ngsMenu\">\n <button class=\"[&.is-active]:!bg-secondary-container\"\n [class.is-active]=\"isTextAlignment('left')\"\n ngs-menu-item\n (click)=\"setTextAlignment('left')\">\n <ngs-icon name=\"fluent:text-align-left-24-regular\"/>\n Align Left\n </button>\n <button class=\"[&.is-active]:!bg-secondary-container\"\n [class.is-active]=\"isTextAlignment('center')\"\n ngs-menu-item\n (click)=\"setTextAlignment('center')\">\n <ngs-icon name=\"fluent:text-align-center-24-regular\"/>\n Align Center\n </button>\n <button class=\"[&.is-active]:!bg-secondary-container\"\n [class.is-active]=\"isTextAlignment('right')\"\n ngs-menu-item (click)=\"setTextAlignment('right')\">\n <ngs-icon name=\"fluent:text-align-right-24-regular\"/>\n Align Right\n </button>\n</ngs-menu>\n\n<ngs-menu #formatColorText=\"ngsMenu\">\n <div class=\"px-4 py-3\" (mousedown)=\"preventMenuClose($event)\">\n <ngs-text-color (textColorChanged)=\"onTextColorChanged($event)\"\n (backgroundColorChanged)=\"onBackgroundColorChanged($event)\"/>\n </div>\n</ngs-menu>\n", styles: [":host{background:var(--ngs-color-on-surface);color:var(--ngs-color-surface);border-radius:calc(var(--spacing, .25rem) * 3);padding:var(--spacing, .25rem);box-shadow:var(--ngs-shadow-lg)}:host button[ngsIconButton]{--ngs-button-color: var(--ngs-color-surface);--ngs-button-hover-bg: var(--ngs-color-surface);--ngs-state-focus-ring: var(--ngs-color-surface)}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton]{--ngs-button-hover-bg: color-mix(in srgb, var(--ngs-color-surface) 12%, transparent)}}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton]{--ngs-state-focus-ring: color-mix(in srgb, var(--ngs-color-surface) 40%, transparent)}}:host button[ngsIconButton].is-active{--ngs-button-bg: var(--ngs-color-surface);--ngs-button-hover-bg: var(--ngs-color-surface)}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton].is-active{--ngs-button-bg: color-mix(in srgb, var(--ngs-color-surface) 20%, transparent)}}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton].is-active{--ngs-button-hover-bg: color-mix(in srgb, var(--ngs-color-surface) 28%, transparent)}}\n/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n"], dependencies: [{ kind: "component", type: Button, selector: " button[ngsButton], button[ngsIconButton], a[ngsButton], a[ngsIconButton] ", inputs: ["ngsButton", "ngsIconButton", "loading", "disabled", "disabledInteractive", "disableRipple", "reverse", "fullWidth", "hideTextOnMobile"], exportAs: ["ngsButton"] }, { kind: "component", type: Icon, selector: "ngs-icon", inputs: ["name"], exportAs: ["ngsIcon"] }, { kind: "component", type: Menu, selector: "ngs-menu", inputs: ["role", "classList", "xPosition", "yPosition", "pushIntoViewport"], outputs: ["closed"], exportAs: ["ngsMenu"] }, { kind: "component", type: MenuItem, selector: "ngs-menu-item, [ngs-menu-item]", inputs: ["disabled", "role", "selected"], outputs: ["_triggered"], exportAs: ["ngsMenuItem"] }, { kind: "directive", type: MenuTrigger, selector: "[ngsMenuTriggerFor]", inputs: ["ngsMenuTriggerFor", "ngsMenuTriggerData", "ngsMenuDisabled", "xPosition", "yPosition", "ngsMenuTriggerRestoreFocus"], outputs: ["menuOpened", "menuClosed"], exportAs: ["ngsMenuTrigger"] }, { kind: "component", type: TextColorComponent, selector: "ngs-text-color", inputs: ["recentlyUsed", "selectedTextColor", "selectedBackgroundColor", "textColors", "backgroundColors"], outputs: ["recentlyUsedChange", "selectedTextColorChange", "selectedBackgroundColorChange", "textColorChanged", "backgroundColorChanged"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
1668
+ }
1669
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: CommandBarComponent, decorators: [{
1670
+ type: Component,
1671
+ args: [{ selector: 'ngs-command-bar', imports: [Button, Icon, Menu, MenuItem, MenuTrigger, TextColorComponent], changeDetection: ChangeDetectionStrategy.OnPush, host: {
1672
+ 'class': 'ngs-command-bar',
1673
+ '(mousedown)': 'preserveSelection($event)'
1674
+ }, template: "<div class=\"flex items-center gap-1\">\n <button ngsIconButton (click)=\"toggleBold()\"\n [class.is-active]=\"isActive('strong')\">\n <ngs-icon name=\"fluent:text-bold-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleItalic()\"\n [class.is-active]=\"isActive('em')\">\n <ngs-icon name=\"fluent:text-italic-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleStrike()\"\n [class.is-active]=\"isActive('s')\">\n <ngs-icon name=\"fluent:text-strikethrough-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleUnderline()\"\n [class.is-active]=\"isActive('u')\">\n <ngs-icon name=\"fluent:text-underline-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleSuperscript()\"\n [class.is-active]=\"isActive('sup')\">\n <ngs-icon name=\"fluent:text-superscript-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleSubscript()\"\n [class.is-active]=\"isActive('sub')\">\n <ngs-icon name=\"fluent:text-subscript-24-regular\"/>\n </button>\n <button ngsIconButton (click)=\"toggleCode()\"\n [class.is-active]=\"isActive('code')\">\n <ngs-icon name=\"fluent:code-24-regular\"/>\n </button>\n\n @if (isLinkActive()) {\n <button ngsIconButton (click)=\"editLink()\">\n <ngs-icon name=\"fluent:link-24-regular\"/>\n </button>\n } @else {\n <button ngsIconButton (click)=\"addLink()\">\n <ngs-icon name=\"fluent:link-add-24-regular\"/>\n </button>\n }\n <button ngsIconButton [ngsMenuTriggerFor]=\"alignMenu\"\n (menuOpened)=\"retainSelection()\" (menuClosed)=\"restoreSelectionAfterOverlay()\">\n @switch (alignment()) {\n @case ('left') {\n <ngs-icon name=\"fluent:text-align-left-24-regular\"/>\n }\n @case ('center') {\n <ngs-icon name=\"fluent:text-align-center-24-regular\"/>\n }\n @case ('right') {\n <ngs-icon name=\"fluent:text-align-right-24-regular\"/>\n }\n }\n </button>\n <button ngsIconButton [ngsMenuTriggerFor]=\"formatColorText\"\n (menuOpened)=\"retainSelection()\" (menuClosed)=\"restoreSelectionAfterOverlay()\">\n <ngs-icon name=\"fluent:text-color-24-regular\"/>\n </button>\n</div>\n\n<ngs-menu #alignMenu=\"ngsMenu\">\n <button class=\"[&.is-active]:!bg-secondary-container\"\n [class.is-active]=\"isTextAlignment('left')\"\n ngs-menu-item\n (click)=\"setTextAlignment('left')\">\n <ngs-icon name=\"fluent:text-align-left-24-regular\"/>\n Align Left\n </button>\n <button class=\"[&.is-active]:!bg-secondary-container\"\n [class.is-active]=\"isTextAlignment('center')\"\n ngs-menu-item\n (click)=\"setTextAlignment('center')\">\n <ngs-icon name=\"fluent:text-align-center-24-regular\"/>\n Align Center\n </button>\n <button class=\"[&.is-active]:!bg-secondary-container\"\n [class.is-active]=\"isTextAlignment('right')\"\n ngs-menu-item (click)=\"setTextAlignment('right')\">\n <ngs-icon name=\"fluent:text-align-right-24-regular\"/>\n Align Right\n </button>\n</ngs-menu>\n\n<ngs-menu #formatColorText=\"ngsMenu\">\n <div class=\"px-4 py-3\" (mousedown)=\"preventMenuClose($event)\">\n <ngs-text-color (textColorChanged)=\"onTextColorChanged($event)\"\n (backgroundColorChanged)=\"onBackgroundColorChanged($event)\"/>\n </div>\n</ngs-menu>\n", styles: [":host{background:var(--ngs-color-on-surface);color:var(--ngs-color-surface);border-radius:calc(var(--spacing, .25rem) * 3);padding:var(--spacing, .25rem);box-shadow:var(--ngs-shadow-lg)}:host button[ngsIconButton]{--ngs-button-color: var(--ngs-color-surface);--ngs-button-hover-bg: var(--ngs-color-surface);--ngs-state-focus-ring: var(--ngs-color-surface)}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton]{--ngs-button-hover-bg: color-mix(in srgb, var(--ngs-color-surface) 12%, transparent)}}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton]{--ngs-state-focus-ring: color-mix(in srgb, var(--ngs-color-surface) 40%, transparent)}}:host button[ngsIconButton].is-active{--ngs-button-bg: var(--ngs-color-surface);--ngs-button-hover-bg: var(--ngs-color-surface)}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton].is-active{--ngs-button-bg: color-mix(in srgb, var(--ngs-color-surface) 20%, transparent)}}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton].is-active{--ngs-button-hover-bg: color-mix(in srgb, var(--ngs-color-surface) 28%, transparent)}}\n/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n"] }]
1675
+ }], propDecorators: { observedElement: [{ type: i0.Input, args: [{ isSignal: true, alias: "observedElement", required: false }] }] } });
1676
+
1677
+ /** Shared marks and commands for content editing and read-only rendering. */
1678
+ function provideContentEditor() {
1679
+ return provideNgsHeadlessEditor(withHeadlessEditorPlugin(basicTextEditorPlugin()), withHeadlessEditorPlugin(colorEditorPlugin()), withHeadlessEditorPlugin(linkEditorPlugin()));
1517
1680
  }
1518
1681
 
1519
- /** Parsing only: applications decide when to replace their current document. */
1520
- class ContentEditorImporter {
1521
- config = inject(CONTENT_EDITOR_CONFIG);
1522
- document = inject(DOCUMENT);
1523
- fromJson(source, config = {}, options = {}) {
1524
- return contentEditorFromJson(source, mergeContentEditorConfig(this.config, config), options);
1525
- }
1526
- fromHtml(html, config = {}, options = {}) {
1527
- return contentEditorFromHtml(html, mergeContentEditorConfig(this.config, config), { document: this.document, ...options });
1682
+ const CONTENT_EDITOR_EXTRA_BLOCK_DEFS = [
1683
+ {
1684
+ type: 'callout', component: () => import('./ngstarter-ui-components-content-editor-callout-block-DTdApN0r.mjs').then(m => m.ContentEditorCalloutBlock),
1685
+ empty: () => ({ content: [createNgsHeadlessEditorText()], settings: { variant: 'note' } }), options: {}
1686
+ },
1687
+ {
1688
+ type: 'toggle', component: () => import('./ngstarter-ui-components-content-editor-toggle-block-Cb67ChE8.mjs').then(m => m.ContentEditorToggleBlock),
1689
+ empty: () => ({ content: { title: [], blocks: [emptyParagraph()] }, settings: { expanded: true } }), options: {}
1690
+ },
1691
+ {
1692
+ type: 'attachment', component: () => import('./ngstarter-ui-components-content-editor-attachment-block-rzZKJ2JH.mjs').then(m => m.ContentEditorAttachmentBlock),
1693
+ empty: () => ({ content: { url: '', name: '', size: 0, mimeType: '' }, settings: {} }),
1694
+ options: { uploadFn: (_file, dataUrl) => Promise.resolve(dataUrl) }
1695
+ },
1696
+ {
1697
+ type: 'gallery', component: () => import('./ngstarter-ui-components-content-editor-gallery-block-gtH7yWd5.mjs').then(m => m.ContentEditorGalleryBlock),
1698
+ empty: () => ({ content: { images: [] }, settings: {} }),
1699
+ options: { uploadFn: (_file, dataUrl) => Promise.resolve(dataUrl) }
1700
+ },
1701
+ {
1702
+ type: 'grid', component: () => import('./ngstarter-ui-components-content-editor-grid-block-Pb-xV7Pw.mjs').then(m => m.ContentEditorGridBlock),
1703
+ empty: () => ({ content: { cells: Array.from({ length: 4 }, emptyGridCell) }, settings: { columns: 2, gap: 'medium', stackOnMobile: true } }), options: {}
1528
1704
  }
1529
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorImporter, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1530
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorImporter, providedIn: 'root' });
1705
+ ].map(def => ({ ...def, toHtml: CONTENT_EDITOR_DEFAULT_HTML_CONVERTERS[def.type] }));
1706
+ function emptyParagraph() {
1707
+ return { id: createNgsHeadlessEditorId('paragraph'), type: 'paragraph', content: [createNgsHeadlessEditorText()] };
1531
1708
  }
1532
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorImporter, decorators: [{
1533
- type: Injectable,
1534
- args: [{ providedIn: 'root' }]
1535
- }] });
1709
+ function emptyGridCell() { return { id: createNgsHeadlessEditorId('cell'), blocks: [emptyParagraph()] }; }
1710
+ const CONTENT_EDITOR_EXTRA_SUGGESTIONS = [
1711
+ { type: 'heading', title: 'Content & layout' },
1712
+ ...[
1713
+ ['callout', 'Callout', 'Notes, tips and warnings', 'fluent:info-24-regular'],
1714
+ ['toggle', 'Toggle', 'Collapsible content with nested blocks', 'fluent:chevron-down-24-regular'],
1715
+ ['attachment', 'Attachment', 'Upload a file for download', 'fluent:attach-24-regular'],
1716
+ ['gallery', 'Gallery', 'Image carousel with captions', 'fluent:image-multiple-24-regular'],
1717
+ ['grid', 'Grid', 'Responsive grid with nested blocks', 'fluent:grid-24-regular']
1718
+ ].map(([blockType, title, description, iconName]) => ({ type: 'item', blockType, title, description, iconName, blockSettings: {} }))
1719
+ ];
1536
1720
 
1537
- const CONTENT_EDITOR_CONFIG = new InjectionToken('CONTENT_EDITOR_CONFIG', {
1538
- providedIn: 'root', factory: () => ({})
1539
- });
1540
- /** Later configurations override individual block fields, preserving unrelated options. */
1541
- function mergeContentEditorConfig(...configs) {
1542
- const result = { blocks: Object.create(null), marks: {} };
1543
- for (const config of configs) {
1544
- for (const [type, block] of Object.entries(config.blocks ?? {})) {
1545
- const previous = result.blocks[type];
1546
- result.blocks[type] = {
1547
- ...previous, ...block, options: { ...previous?.options, ...block.options }
1548
- };
1721
+ const browserStorage = {
1722
+ getItem: key => globalThis.localStorage.getItem(key),
1723
+ setItem: (key, value) => globalThis.localStorage.setItem(key, value),
1724
+ removeItem: key => globalThis.localStorage.removeItem(key)
1725
+ };
1726
+ /** Delayed persistence keeps storage errors visible and flushes before switching documents. */
1727
+ class ContentEditorDraftController {
1728
+ status = signal('disabled', /* @ts-ignore */
1729
+ ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
1730
+ error = signal('', /* @ts-ignore */
1731
+ ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
1732
+ savedAt = signal(null, /* @ts-ignore */
1733
+ ...(ngDevMode ? [{ debugName: "savedAt" }] : /* istanbul ignore next */ []));
1734
+ key = '';
1735
+ storage = browserStorage;
1736
+ debounceMs = 500;
1737
+ enabled = false;
1738
+ pending = null;
1739
+ timer = null;
1740
+ configure(key, enabled, config = {}) {
1741
+ const storage = config.storage ?? browserStorage;
1742
+ if (this.key !== key || this.enabled !== enabled || this.storage !== storage) {
1743
+ this.flush();
1744
+ this.key = key;
1745
+ this.enabled = enabled;
1746
+ this.storage = storage;
1747
+ this.status.set(enabled ? 'idle' : 'disabled');
1748
+ this.error.set('');
1749
+ this.savedAt.set(null);
1549
1750
  }
1550
- result.marks = { ...result.marks, ...config.marks };
1551
- if (config.includeStyles !== undefined)
1552
- result.includeStyles = config.includeStyles;
1553
- if (config.importMarks !== undefined)
1554
- result.importMarks = config.importMarks;
1555
- if (config.unknownBlockToHtml !== undefined)
1556
- result.unknownBlockToHtml = config.unknownBlockToHtml;
1751
+ this.debounceMs = Number.isFinite(config.debounceMs) ? Math.max(0, config.debounceMs) : 500;
1557
1752
  }
1558
- return result;
1753
+ read(validate) {
1754
+ if (!this.enabled)
1755
+ return null;
1756
+ try {
1757
+ const source = this.storage.getItem(this.key);
1758
+ if (!source)
1759
+ return null;
1760
+ const document = validate(source);
1761
+ this.status.set('saved');
1762
+ return document;
1763
+ }
1764
+ catch (error) {
1765
+ this.fail(error);
1766
+ return null;
1767
+ }
1768
+ }
1769
+ schedule(document) {
1770
+ if (!this.enabled)
1771
+ return;
1772
+ this.pending = document;
1773
+ this.status.set('saving');
1774
+ this.error.set('');
1775
+ if (this.timer)
1776
+ clearTimeout(this.timer);
1777
+ this.timer = setTimeout(() => this.flush(), this.debounceMs);
1778
+ }
1779
+ flush() {
1780
+ if (this.timer)
1781
+ clearTimeout(this.timer);
1782
+ this.timer = null;
1783
+ if (!this.enabled || !this.pending)
1784
+ return;
1785
+ const document = this.pending;
1786
+ this.pending = null;
1787
+ try {
1788
+ this.storage.setItem(this.key, JSON.stringify(document));
1789
+ this.status.set('saved');
1790
+ this.error.set('');
1791
+ this.savedAt.set(Date.now());
1792
+ }
1793
+ catch (error) {
1794
+ this.fail(error);
1795
+ }
1796
+ }
1797
+ clear() {
1798
+ if (this.timer)
1799
+ clearTimeout(this.timer);
1800
+ this.timer = null;
1801
+ this.pending = null;
1802
+ if (!this.enabled)
1803
+ return;
1804
+ try {
1805
+ this.storage.removeItem(this.key);
1806
+ this.status.set('idle');
1807
+ this.error.set('');
1808
+ this.savedAt.set(null);
1809
+ }
1810
+ catch (error) {
1811
+ this.fail(error);
1812
+ }
1813
+ }
1814
+ fail(error) { this.error.set(error instanceof Error ? error.message : 'Could not save draft'); this.status.set('error'); }
1559
1815
  }
1560
- /** Application or route environment configuration. Child environments inherit parent settings. */
1561
- function provideContentEditorConfig(config = {}) {
1562
- return makeEnvironmentProviders([
1563
- {
1564
- provide: CONTENT_EDITOR_CONFIG,
1565
- useFactory: () => mergeContentEditorConfig(inject(CONTENT_EDITOR_CONFIG, { skipSelf: true, optional: true }) ?? {}, config)
1566
- },
1567
- ContentEditorHtmlSerializer,
1568
- ContentEditorImporter
1569
- ]);
1816
+
1817
+ const CONTENT_EDITOR_CONVERTIBLE_BLOCKS = ['paragraph', 'heading', 'quote', 'callout'];
1818
+ /** Retains identity, rich text and alignment. Quote attribution becomes a final line. */
1819
+ function contentEditorConvertBlock(block, type, settings = {}) {
1820
+ if (!CONTENT_EDITOR_CONVERTIBLE_BLOCKS.includes(block.type) || !CONTENT_EDITOR_CONVERTIBLE_BLOCKS.includes(type)) {
1821
+ throw new Error(`Cannot convert ${block.type} to ${type}`);
1822
+ }
1823
+ if (type === 'heading' && settings['level'] !== undefined && ![1, 2, 3, 4, 5, 6].includes(settings['level']))
1824
+ throw new Error('Heading level must be between 1 and 6');
1825
+ if (type === 'callout' && settings['variant'] !== undefined && !['note', 'tip', 'warning', 'danger'].includes(settings['variant']))
1826
+ throw new Error('Unsupported callout variant');
1827
+ const next = cloneContentEditorValue(block);
1828
+ if (type === block.type)
1829
+ return { ...next, attrs: { ...next.attrs, settings: { ...next.attrs?.['settings'], ...settings } } };
1830
+ const quote = block.type === 'quote' ? block.content : null;
1831
+ const cite = quote ? quote.cite.content : block.content;
1832
+ const caption = quote?.caption?.content ?? [];
1833
+ const text = normalizeNgsHeadlessEditorTextContent(caption.some(run => run.text)
1834
+ ? [...cite, createNgsHeadlessEditorText('\n'), ...caption] : cite);
1835
+ const props = (quote?.cite.props ?? block.attrs?.['props'] ?? []);
1836
+ const defaults = type === 'heading' ? { level: 2 } : type === 'callout' ? { variant: 'note' } : {};
1837
+ return { ...next, type,
1838
+ content: type === 'quote' ? { cite: { content: text, props }, caption: { content: [], props: [] } } : text,
1839
+ attrs: { ...next.attrs, props, settings: { ...defaults, ...(type === block.type ? next.attrs?.['settings'] : {}), ...settings } }
1840
+ };
1570
1841
  }
1571
1842
 
1572
1843
  // src/app/text-selection-popup.directive.ts
@@ -2006,9 +2277,20 @@ class ContentBuilderComponent {
2006
2277
  config = input({}, /* @ts-ignore */
2007
2278
  ...(ngDevMode ? [{ debugName: "config" }] : /* istanbul ignore next */ []));
2008
2279
  /** One insertion menu shared by root controls, nested collections and custom blocks. */
2280
+ conversionMenu = viewChild.required('conversionMenu', /* @ts-ignore */
2281
+ ...(ngDevMode ? [{ debugName: "conversionMenu" }] : /* istanbul ignore next */ []));
2282
+ conversionTypes = CONTENT_EDITOR_CONVERTIBLE_BLOCKS;
2009
2283
  blockMenu = viewChild.required('suggestionsMenu', /* @ts-ignore */
2010
2284
  ...(ngDevMode ? [{ debugName: "blockMenu" }] : /* istanbul ignore next */ []));
2011
2285
  document = inject(DOCUMENT);
2286
+ drafts = new ContentEditorDraftController();
2287
+ draftStatus = this.drafts.status;
2288
+ draftError = this.drafts.error;
2289
+ draftSavedAt = this.drafts.savedAt;
2290
+ documentId = input(/* @ts-ignore */
2291
+ ...(ngDevMode ? [undefined, { debugName: "documentId" }] : /* istanbul ignore next */ []));
2292
+ draftDebounceMs = input(undefined, { ...(ngDevMode ? { debugName: "draftDebounceMs" } : /* istanbul ignore next */ {}), transform: numberAttribute });
2293
+ draftKey = '';
2012
2294
  loaded = false;
2013
2295
  lastInput = null;
2014
2296
  _platformId = inject(PLATFORM_ID);
@@ -2016,7 +2298,7 @@ class ContentBuilderComponent {
2016
2298
  dropList = viewChild.required(CdkDropList, /* @ts-ignore */
2017
2299
  ...(ngDevMode ? [{ debugName: "dropList" }] : /* istanbul ignore next */ []));
2018
2300
  connectedDropLists = this._store.dropLists;
2019
- elRef = inject((ElementRef));
2301
+ elRef = inject(ElementRef);
2020
2302
  envInjector = inject(EnvironmentInjector);
2021
2303
  cdr = inject(ChangeDetectorRef);
2022
2304
  confirmManager = inject(ConfirmManager);
@@ -2045,7 +2327,7 @@ class ContentBuilderComponent {
2045
2327
  }
2046
2328
  },
2047
2329
  {
2048
- component: () => import('./ngstarter-ui-components-content-editor-paragraph-block.component-Dd0pQquG.mjs').then(c => c.ParagraphBlockComponent),
2330
+ component: () => import('./ngstarter-ui-components-content-editor-paragraph-block.component-D5wS3m6O.mjs').then(c => c.ParagraphBlockComponent),
2049
2331
  type: 'paragraph',
2050
2332
  options: {},
2051
2333
  empty: () => {
@@ -2057,7 +2339,7 @@ class ContentBuilderComponent {
2057
2339
  }
2058
2340
  },
2059
2341
  {
2060
- component: () => import('./ngstarter-ui-components-content-editor-code-block.component-BizHRPdC.mjs').then(c => c.CodeBlockComponent),
2342
+ component: () => import('./ngstarter-ui-components-content-editor-code-block.component-DpONkTMU.mjs').then(c => c.CodeBlockComponent),
2061
2343
  type: 'code',
2062
2344
  options: {},
2063
2345
  empty: () => {
@@ -2070,7 +2352,7 @@ class ContentBuilderComponent {
2070
2352
  }
2071
2353
  },
2072
2354
  {
2073
- component: () => import('./ngstarter-ui-components-content-editor-heading-block.component-CDSt4rXe.mjs').then(c => c.HeadingBlockComponent),
2355
+ component: () => import('./ngstarter-ui-components-content-editor-heading-block.component-BKe9Zy_x.mjs').then(c => c.HeadingBlockComponent),
2074
2356
  type: 'heading',
2075
2357
  options: {},
2076
2358
  empty: () => {
@@ -2084,7 +2366,7 @@ class ContentBuilderComponent {
2084
2366
  }
2085
2367
  },
2086
2368
  {
2087
- component: () => import('./ngstarter-ui-components-content-editor-image-block.component-LfKZapgv.mjs').then(c => c.ImageBlockComponent),
2369
+ component: () => import('./ngstarter-ui-components-content-editor-image-block.component-DSpBVTu-.mjs').then(c => c.ImageBlockComponent),
2088
2370
  type: 'image',
2089
2371
  options: {
2090
2372
  uploadFn: (file, base64) => {
@@ -2111,7 +2393,7 @@ class ContentBuilderComponent {
2111
2393
  }
2112
2394
  },
2113
2395
  {
2114
- component: () => import('./ngstarter-ui-components-content-editor-video-block.component-hBR5AauH.mjs').then(c => c.VideoBlockComponent),
2396
+ component: () => import('./ngstarter-ui-components-content-editor-video-block.component-CRa0g9Ez.mjs').then(c => c.VideoBlockComponent),
2115
2397
  type: 'video',
2116
2398
  options: {
2117
2399
  uploadFn: (file, base64) => {
@@ -2139,7 +2421,7 @@ class ContentBuilderComponent {
2139
2421
  }
2140
2422
  },
2141
2423
  {
2142
- component: () => import('./ngstarter-ui-components-content-editor-list-block.component-CdQ30RjA.mjs').then(c => c.ListBlockComponent),
2424
+ component: () => import('./ngstarter-ui-components-content-editor-list-block.component-BPKPE1uY.mjs').then(c => c.ListBlockComponent),
2143
2425
  type: 'bulletList',
2144
2426
  options: {},
2145
2427
  empty: () => {
@@ -2152,7 +2434,7 @@ class ContentBuilderComponent {
2152
2434
  }
2153
2435
  },
2154
2436
  {
2155
- component: () => import('./ngstarter-ui-components-content-editor-list-block.component-CdQ30RjA.mjs').then(c => c.ListBlockComponent),
2437
+ component: () => import('./ngstarter-ui-components-content-editor-list-block.component-BPKPE1uY.mjs').then(c => c.ListBlockComponent),
2156
2438
  type: 'orderedList',
2157
2439
  options: {},
2158
2440
  empty: () => {
@@ -2165,7 +2447,7 @@ class ContentBuilderComponent {
2165
2447
  }
2166
2448
  },
2167
2449
  {
2168
- component: () => import('./ngstarter-ui-components-content-editor-table-block.component-BTExrXy8.mjs').then(c => c.TableBlockComponent),
2450
+ component: () => import('./ngstarter-ui-components-content-editor-table-block.component-DQgs_kyN.mjs').then(c => c.TableBlockComponent),
2169
2451
  type: 'table',
2170
2452
  options: {},
2171
2453
  empty: () => {
@@ -2234,7 +2516,7 @@ class ContentBuilderComponent {
2234
2516
  }
2235
2517
  },
2236
2518
  {
2237
- component: () => import('./ngstarter-ui-components-content-editor-quote-block.component-CUxKoeb_.mjs').then(c => c.QuoteBlockComponent),
2519
+ component: () => import('./ngstarter-ui-components-content-editor-quote-block.component-C3GFAGKF.mjs').then(c => c.QuoteBlockComponent),
2238
2520
  type: 'quote',
2239
2521
  options: {},
2240
2522
  empty: () => {
@@ -2254,7 +2536,7 @@ class ContentBuilderComponent {
2254
2536
  }
2255
2537
  },
2256
2538
  {
2257
- component: () => import('./ngstarter-ui-components-content-editor-embed-block-BzoaJvai.mjs').then(c => c.EmbedBlock),
2539
+ component: () => import('./ngstarter-ui-components-content-editor-embed-block-CmhzpaRk.mjs').then(c => c.EmbedBlock),
2258
2540
  type: 'embed',
2259
2541
  options: {},
2260
2542
  empty: () => {
@@ -2440,33 +2722,67 @@ class ContentBuilderComponent {
2440
2722
  };
2441
2723
  }
2442
2724
  // Build helper maps: component map and merged options map
2725
+ insertionSuggestions = computed(() => {
2726
+ const config = mergeContentEditorConfig(this.globalConfig, this.config());
2727
+ const custom = Object.entries(config.blocks ?? {}).flatMap(([type, definition]) => definition.menu ? [{
2728
+ type: 'item', title: definition.menu.title, description: definition.menu.description ?? '',
2729
+ iconName: definition.menu.iconName ?? 'fluent:document-24-regular', blockType: type,
2730
+ blockSettings: definition.menu.settings ?? {}, hotKeys: ''
2731
+ }] : []);
2732
+ const replaced = new Set(custom.map(item => item.blockType));
2733
+ return [...this.suggestions().filter((item) => !replaced.has(item.blockType)), ...custom];
2734
+ }, /* @ts-ignore */
2735
+ ...(ngDevMode ? [{ debugName: "insertionSuggestions" }] : /* istanbul ignore next */ []));
2736
+ componentSources = new Map();
2443
2737
  buildBlockDefMaps() {
2444
2738
  const overrides = this.options() || {};
2445
2739
  const config = mergeContentEditorConfig(this.globalConfig, this.config());
2446
2740
  this.blockDefsOptionsMap = new Map();
2447
- this.blockDefs().forEach((def) => {
2448
- if (!this.blockDefsMap.has(def.type)) {
2741
+ const definitions = new Map(this.blockDefs().map(def => [def.type, def]));
2742
+ for (const [type, block] of Object.entries(config.blocks ?? {})) {
2743
+ const previous = definitions.get(type);
2744
+ if (!previous && !(block.editor || block.loadEditor))
2745
+ continue;
2746
+ const component = block.loadEditor ?? (block.editor ? () => Promise.resolve(block.editor) : previous.component);
2747
+ definitions.set(type, { ...previous, type, component,
2748
+ empty: block.create ? () => {
2749
+ const initial = block.create();
2750
+ return { content: initial.content, settings: initial.attrs?.['settings'] ?? {}, props: initial.attrs?.['props'] ?? [], attrs: initial.attrs };
2751
+ } : previous?.empty ?? (() => ({ content: null, settings: {} })),
2752
+ toHtml: block.toHtml ?? previous?.toHtml, options: previous?.options ?? {} });
2753
+ const source = block.loadEditor ?? block.editor ?? previous?.component;
2754
+ if (this.componentSources.get(type) !== source)
2755
+ this.blockDefsMap.delete(type);
2756
+ this.componentSources.set(type, source);
2757
+ }
2758
+ for (const type of this.blockDefsMap.keys())
2759
+ if (!definitions.has(type))
2760
+ this.blockDefsMap.delete(type);
2761
+ definitions.forEach(def => {
2762
+ const configured = config.blocks?.[def.type];
2763
+ const source = configured?.loadEditor ?? configured?.editor ?? def.component;
2764
+ if (this.componentSources.get(def.type) !== source)
2765
+ this.blockDefsMap.delete(def.type);
2766
+ this.componentSources.set(def.type, source);
2767
+ if (!this.blockDefsMap.has(def.type))
2449
2768
  this.blockDefsMap.set(def.type, def.component());
2450
- }
2451
- const merged = {
2452
- ...(def.options || {}),
2453
- toHtml: def.toHtml,
2454
- ...config.blocks?.[def.type]?.options,
2455
- ...(config.blocks?.[def.type]?.toHtml ? { toHtml: config.blocks[def.type].toHtml } : {}),
2456
- ...(overrides[def.type] || {})
2457
- };
2458
- this.blockDefsOptionsMap.set(def.type, merged);
2769
+ this.blockDefsOptionsMap.set(def.type, { ...def.options, toHtml: def.toHtml,
2770
+ ...config.blocks?.[def.type]?.options, ...(overrides[def.type] || {}) });
2459
2771
  });
2772
+ this.resolvedBlockDefs = definitions;
2460
2773
  }
2774
+ resolvedBlockDefs = new Map();
2461
2775
  /** Shared by nested block collections; all edits use this root editor. */
2462
2776
  get rootBuilder() { return this; }
2463
2777
  getBlockComponent(type) { return this.blockDefsMap.get(type); }
2464
2778
  createBlockView(type, settings = {}, content) { return this._createBlock(type, settings, content); }
2465
2779
  getBlockDefOption(type, key) {
2466
- return this.blockDefsOptionsMap.get(type)[key];
2780
+ return this.blockDefsOptionsMap.get(type)?.[key];
2467
2781
  }
2468
2782
  ngOnInit() {
2469
2783
  this.lastInput = this.content();
2784
+ this.buildBlockDefMaps();
2785
+ this.configureDraft();
2470
2786
  const document = this._getDraftContent() ?? this.lastInput;
2471
2787
  const last = document.blocks.at(-1);
2472
2788
  const blocks = last && (last.type !== 'paragraph' || contentEditorText(last.content).length > 0)
@@ -2480,6 +2796,7 @@ class ContentBuilderComponent {
2480
2796
  }
2481
2797
  }
2482
2798
  constructor() {
2799
+ inject(DestroyRef).onDestroy(() => this.drafts.flush());
2483
2800
  effect(() => {
2484
2801
  this.config();
2485
2802
  this.options();
@@ -2488,10 +2805,18 @@ class ContentBuilderComponent {
2488
2805
  });
2489
2806
  effect(() => {
2490
2807
  const value = this.content();
2808
+ this.documentId();
2809
+ this.persistDraft();
2810
+ this.draftDebounceMs();
2811
+ this.config();
2491
2812
  untracked(() => {
2492
- if (this.loaded && value !== this.lastInput) {
2813
+ if (!this.loaded)
2814
+ return;
2815
+ const previousKey = this.draftKey;
2816
+ this.configureDraft();
2817
+ if (value !== this.lastInput || previousKey !== this.draftKey) {
2493
2818
  this.lastInput = value;
2494
- this._store.setBlocks(value);
2819
+ this._store.setBlocks(previousKey !== this.draftKey ? this._getDraftContent() ?? value : value);
2495
2820
  }
2496
2821
  });
2497
2822
  });
@@ -2631,7 +2956,9 @@ class ContentBuilderComponent {
2631
2956
  return this.editor.document().blocks.find(block => block.id === newBlock.id);
2632
2957
  }
2633
2958
  _createBlock(type, settings = {}, content) {
2634
- const blockDef = this.blockDefs().find(blockDefItem => blockDefItem.type === type);
2959
+ const blockDef = this.resolvedBlockDefs.get(type) ?? this.blockDefs().find(item => item.type === type);
2960
+ if (!blockDef)
2961
+ throw new Error(`No Content Editor definition for "${type}"`);
2635
2962
  const empty = blockDef.empty();
2636
2963
  if (settings) {
2637
2964
  empty.settings = {
@@ -2660,6 +2987,45 @@ class ContentBuilderComponent {
2660
2987
  }
2661
2988
  this.insertBlock(type, index, options);
2662
2989
  }
2990
+ canConvertBlock(id) {
2991
+ const block = findContentEditorBlock(this.editor.document().blocks, id);
2992
+ return !!block && this.conversionTypes.includes(block.type) && !this.editor.readOnly();
2993
+ }
2994
+ convertBlock(id, type, settings = {}) {
2995
+ if (!this.canConvertBlock(id))
2996
+ return false;
2997
+ const regions = Array.from(this.elRef.nativeElement.querySelectorAll('.ngs-content-editor-content-editable'));
2998
+ const activeElement = regions.find(element => element.closest('[data-block-id]')?.getAttribute('data-block-id') === id && ContentEditorContentEditableDirective.forElement(element)?.region.active());
2999
+ const region = ContentEditorContentEditableDirective.forElement(activeElement ?? null);
3000
+ let selection = region?.region.editor.selection();
3001
+ const source = findContentEditorBlock(this.editor.document().blocks, id);
3002
+ if (selection && source.type === 'quote' && type !== 'quote' && activeElement?.classList.contains('caption')) {
3003
+ const quote = source.content;
3004
+ const caption = contentEditorText(quote.caption?.content);
3005
+ const text = contentEditorText(quote.cite.content) + (caption ? '\n' + caption : '');
3006
+ const shift = contentEditorText(quote.cite.content).length + (caption ? 1 : 0);
3007
+ const lines = text.split('\n');
3008
+ const point = (value) => {
3009
+ const regionLines = region.region.editor.document().blocks;
3010
+ const index = regionLines.findIndex(line => line.id === value.blockId);
3011
+ let offset = shift + regionLines.slice(0, index).reduce((sum, line) => sum + contentEditorText(line.content).length + 1, 0) + value.offset;
3012
+ let line = 0;
3013
+ while (line < lines.length - 1 && offset > lines[line].length) {
3014
+ offset -= lines[line].length + 1;
3015
+ line++;
3016
+ }
3017
+ return { blockId: `line-${line}`, offset };
3018
+ };
3019
+ selection = { anchor: point(selection.anchor), focus: point(selection.focus) };
3020
+ }
3021
+ const blocks = cloneContentEditorValue([...this.editor.document().blocks]);
3022
+ const block = findContentEditorBlock(blocks, id);
3023
+ Object.assign(block, contentEditorConvertBlock(block, type, settings));
3024
+ this.editor.updateDocument({ version: 1, blocks });
3025
+ if (selection)
3026
+ this._store.restoreTextSelection.set({ blockId: id, selection });
3027
+ return true;
3028
+ }
2663
3029
  duplicateBlock(blockId) {
2664
3030
  const index = this._content().findIndex(dataBlock => dataBlock.id === blockId);
2665
3031
  if (index === -1) {
@@ -2790,19 +3156,91 @@ class ContentBuilderComponent {
2790
3156
  getData() {
2791
3157
  return this.editor.document();
2792
3158
  }
3159
+ /** Structural HTML paste splits the active text block without flattening lists/tables. */
3160
+ pasteBlocksAtSelection(id, imported, start, end) {
3161
+ if (this.editor.readOnly() || !imported.blocks.length)
3162
+ return false;
3163
+ const blocks = cloneContentEditorValue([...this.editor.document().blocks]);
3164
+ const source = findContentEditorBlock(blocks, id);
3165
+ const scope = contentEditorBlockScope(blocks, id) ?? this._store.insertionTarget().scope;
3166
+ if (!source) {
3167
+ // The empty nested paragraph is a UI placeholder until its first edit.
3168
+ const collection = contentEditorCollection(blocks, scope);
3169
+ if (collection.length)
3170
+ return false;
3171
+ this.applyImport(imported, { mode: 'insert', target: { scope } });
3172
+ return true;
3173
+ }
3174
+ if (!['paragraph', 'heading'].includes(source.type))
3175
+ return false;
3176
+ const text = source.content;
3177
+ const before = contentEditorSliceText(text, 0, Math.min(start, end));
3178
+ const after = contentEditorSliceText(text, Math.max(start, end));
3179
+ const insertion = contentEditorCopyBlocks(imported.blocks);
3180
+ if (contentEditorText(before)) {
3181
+ if (source.type === 'paragraph' && insertion[0].type === 'paragraph')
3182
+ insertion[0] = {
3183
+ ...source, content: [...before, ...insertion[0].content]
3184
+ };
3185
+ else
3186
+ insertion.unshift({ ...source, content: before });
3187
+ }
3188
+ const last = insertion.at(-1);
3189
+ const textLast = ['paragraph', 'heading'].includes(last.type);
3190
+ const caretLines = textLast ? contentEditorText(last.content).split('\n') : [''];
3191
+ const caretPoint = { blockId: `line-${caretLines.length - 1}`, offset: caretLines.at(-1).length };
3192
+ if (textLast)
3193
+ insertion[insertion.length - 1] = { ...last, content: [...last.content, ...after] };
3194
+ else if (contentEditorText(after))
3195
+ insertion.push({ id: v7(), type: 'paragraph', content: after, attrs: { props: source.attrs?.['props'] ?? [] } });
3196
+ const items = [...contentEditorCollection(blocks, scope)];
3197
+ items.splice(items.findIndex(block => block.id === id), 1, ...insertion);
3198
+ replaceContentEditorCollection(blocks, scope, items);
3199
+ this.editor.updateDocument({ version: 1, blocks });
3200
+ if (textLast)
3201
+ this._store.restoreTextSelection.set({ blockId: last.id, selection: { anchor: caretPoint, focus: caretPoint } });
3202
+ return true;
3203
+ }
2793
3204
  /** Validates before replacing the document. Import is one undoable edit. */
2794
3205
  importJson(source, config = {}, options = {}) {
2795
- return this.applyImport(this.importer.fromJson(source, mergeContentEditorConfig(this.config(), config), options));
3206
+ return this.applyImport(this.importer.fromJson(source, mergeContentEditorConfig(this.config(), config), options), options);
2796
3207
  }
2797
3208
  importHtml(html, config = {}, options = {}) {
2798
- return this.applyImport(this.importer.fromHtml(html, mergeContentEditorConfig(this.config(), config), options));
3209
+ return this.applyImport(this.importer.fromHtml(html, mergeContentEditorConfig(this.config(), config), options), options);
2799
3210
  }
2800
- applyImport(document) {
3211
+ getInsertionTarget() {
3212
+ const saved = this._store.insertionTarget();
3213
+ const id = saved.afterId ?? this._store.activeBlockId() ?? this._store.focusedBlockId();
3214
+ const scope = id ? contentEditorBlockScope(this.editor.document().blocks, id) : null;
3215
+ if (scope)
3216
+ return { scope, afterId: id };
3217
+ return { scope: saved.scope };
3218
+ }
3219
+ applyImport(document, placement = {}) {
2801
3220
  if (!this.loaded)
2802
3221
  throw new ContentEditorImportError('$editor', 'Initialize the builder before importing');
2803
3222
  if (this.editor.readOnly())
2804
3223
  throw new ContentEditorImportError('$editor', 'Cannot import into a read-only editor');
2805
- this.editor.updateDocument(document);
3224
+ if (placement.mode === 'insert') {
3225
+ const target = placement.target ?? this.getInsertionTarget();
3226
+ const blocks = cloneContentEditorValue([...this.editor.document().blocks]);
3227
+ if (target.scope.parentId) {
3228
+ const parent = findContentEditorBlock(blocks, target.scope.parentId);
3229
+ if (!parent || !['toggle', 'grid'].includes(parent.type) ||
3230
+ (parent.type === 'grid' && !parent.content.cells.some((cell) => cell.id === target.scope.cellId))) {
3231
+ throw new ContentEditorImportError('$target.scope', 'Insertion collection does not exist');
3232
+ }
3233
+ }
3234
+ const items = [...contentEditorCollection(blocks, target.scope)];
3235
+ const index = target.afterId ? items.findIndex(block => block.id === target.afterId) : items.length - 1;
3236
+ if (target.afterId && index < 0)
3237
+ throw new ContentEditorImportError('$target.afterId', 'Insertion block does not exist in this collection');
3238
+ items.splice(index + 1, 0, ...contentEditorCopyBlocks(document.blocks));
3239
+ replaceContentEditorCollection(blocks, target.scope, items);
3240
+ this.editor.updateDocument({ version: 1, blocks });
3241
+ }
3242
+ else
3243
+ this.editor.updateDocument(document);
2806
3244
  this.selectedBlocksModel.clear();
2807
3245
  this._store.setFocusedBlockId(null);
2808
3246
  this._store.setActiveBlockId(null);
@@ -2854,9 +3292,7 @@ class ContentBuilderComponent {
2854
3292
  .map(id => ({ id, index: this._content().findIndex(b => b.id === id) }))
2855
3293
  .filter(x => x.index !== -1)
2856
3294
  .sort((a, b) => b.index - a.index);
2857
- for (const item of toDelete) {
2858
- this.deleteBlock(item.id);
2859
- }
3295
+ this._store.deleteBlocks(toDelete.map(item => item.id));
2860
3296
  this.unselectSelectedBlocks();
2861
3297
  });
2862
3298
  }
@@ -2945,36 +3381,23 @@ class ContentBuilderComponent {
2945
3381
  }
2946
3382
  this._scroll$ = null;
2947
3383
  }
2948
- _getDraftContent() {
2949
- if (!this._canUseDraftStorage()) {
2950
- return null;
2951
- }
2952
- try {
2953
- const draft = localStorage.getItem(this._getDraftStorageKey());
2954
- if (!draft) {
2955
- return null;
2956
- }
2957
- const content = JSON.parse(draft);
2958
- return content?.version === 1 && Array.isArray(content.blocks) ? content : null;
2959
- }
2960
- catch {
2961
- return null;
2962
- }
2963
- }
2964
- _saveDraft(content) {
2965
- if (!this._canUseDraftStorage()) {
2966
- return;
2967
- }
2968
- try {
2969
- localStorage.setItem(this._getDraftStorageKey(), JSON.stringify(content));
2970
- }
2971
- catch {
2972
- }
3384
+ configureDraft() {
3385
+ this.draftKey = this._getDraftStorageKey();
3386
+ const config = mergeContentEditorConfig(this.globalConfig, this.config()).draft;
3387
+ this.drafts.configure(this.draftKey, this._canUseDraftStorage(), {
3388
+ ...config, ...(this.draftDebounceMs() === undefined ? {} : { debounceMs: this.draftDebounceMs() })
3389
+ });
2973
3390
  }
2974
- _canUseDraftStorage() {
2975
- return !isPlatformServer(this._platformId) && this.persistDraft();
3391
+ _getDraftContent() {
3392
+ return this.drafts.read(source => this.importer.fromJson(source, this.config()));
2976
3393
  }
3394
+ _saveDraft(content) { this.drafts.schedule(content); }
3395
+ saveDraftNow() { this.drafts.schedule(this.getData()); this.drafts.flush(); }
3396
+ clearDraft() { this.drafts.clear(); }
3397
+ _canUseDraftStorage() { return !isPlatformServer(this._platformId) && this.persistDraft(); }
2977
3398
  _getDraftStorageKey(prefix = ContentBuilderComponent.DRAFT_STORAGE_PREFIX) {
3399
+ if (this.documentId()?.trim())
3400
+ return `${prefix}:document:${encodeURIComponent(this.documentId())}`;
2978
3401
  const elementId = this.elRef.nativeElement.id;
2979
3402
  const locationKey = typeof window === 'undefined'
2980
3403
  ? 'server'
@@ -3018,7 +3441,13 @@ class ContentBuilderComponent {
3018
3441
  }
3019
3442
  }
3020
3443
  if (html) {
3021
- this._handleHtmlPaste(html, index);
3444
+ try {
3445
+ this._handleHtmlPaste(html, index);
3446
+ }
3447
+ catch {
3448
+ if (text)
3449
+ this._handleTextPaste(text, index);
3450
+ }
3022
3451
  }
3023
3452
  else if (text) {
3024
3453
  this._handleTextPaste(text, index);
@@ -3044,110 +3473,11 @@ class ContentBuilderComponent {
3044
3473
  }
3045
3474
  }
3046
3475
  _handleHtmlPaste(html, index) {
3047
- const body = this.document.createElement('div');
3048
- body.innerHTML = html;
3049
- let currentIndex = index;
3050
- Array.from(body.children).forEach(node => {
3051
- const block = this._mapNodeToBlock(node);
3052
- if (block) {
3053
- this.insertBlock(block.type, currentIndex, block.settings, false, block.content);
3054
- currentIndex++;
3055
- }
3056
- });
3057
- }
3058
- _mapNodeToBlock(node) {
3059
- const tag = node.tagName.toLowerCase();
3060
- switch (tag) {
3061
- case 'h1':
3062
- case 'h2':
3063
- case 'h3':
3064
- case 'h4':
3065
- case 'h5':
3066
- case 'h6':
3067
- return {
3068
- type: 'heading',
3069
- settings: { level: parseInt(tag.substring(1)) },
3070
- content: readNgsHeadlessEditorInlineContent(node, this.editor, { lineBreaks: true })
3071
- };
3072
- case 'p':
3073
- return {
3074
- type: 'paragraph',
3075
- settings: {},
3076
- content: readNgsHeadlessEditorInlineContent(node, this.editor, { lineBreaks: true })
3077
- };
3078
- case 'ul':
3079
- return {
3080
- type: 'bulletList',
3081
- settings: { listStyle: 'bullet' },
3082
- content: this._mapListItems(node)
3083
- };
3084
- case 'ol':
3085
- return {
3086
- type: 'orderedList',
3087
- settings: { listStyle: 'ordered' },
3088
- content: this._mapListItems(node)
3089
- };
3090
- case 'img':
3091
- return {
3092
- type: 'image',
3093
- settings: {},
3094
- content: {
3095
- src: node.getAttribute('src') || '',
3096
- alt: node.getAttribute('alt') || ''
3097
- }
3098
- };
3099
- case 'video':
3100
- return {
3101
- type: 'video',
3102
- settings: {},
3103
- content: {
3104
- src: node.getAttribute('src') || '',
3105
- caption: node.getAttribute('title') || ''
3106
- }
3107
- };
3108
- case 'blockquote':
3109
- return {
3110
- type: 'quote',
3111
- settings: {},
3112
- content: { cite: { content: readNgsHeadlessEditorInlineContent(node, this.editor, { lineBreaks: true }), props: [] }, caption: { content: [], props: [] } }
3113
- };
3114
- case 'pre':
3115
- const codeNode = node.querySelector('code');
3116
- const content = (codeNode || node).textContent || '';
3117
- return {
3118
- type: 'code',
3119
- settings: { language: 'none' },
3120
- content: [createNgsHeadlessEditorText(content.replace(/\r\n?/g, '\n').trimEnd())]
3121
- };
3122
- case 'hr':
3123
- return {
3124
- type: 'divider',
3125
- settings: {}
3126
- };
3127
- default:
3128
- if (node.textContent?.trim()) {
3129
- return {
3130
- type: 'paragraph',
3131
- settings: {},
3132
- content: readNgsHeadlessEditorInlineContent(node, this.editor, { lineBreaks: true })
3133
- };
3134
- }
3135
- return null;
3136
- }
3137
- }
3138
- _mapListItems(node) {
3139
- return Array.from(node.children)
3140
- .filter(child => child.tagName.toLowerCase() === 'li')
3141
- .map(li => {
3142
- const inline = li.cloneNode(true);
3143
- const nested = Array.from(inline.children).filter(child => ['ul', 'ol'].includes(child.tagName.toLowerCase()));
3144
- const children = nested.flatMap(list => this._mapListItems(list));
3145
- nested.forEach(list => list.remove());
3146
- return { content: readNgsHeadlessEditorInlineContent(inline, this.editor, { lineBreaks: true }), props: [], children };
3147
- });
3476
+ const afterId = this.editor.document().blocks[index - 1]?.id;
3477
+ this.importHtml(html, {}, { mode: 'insert', target: { scope: {}, afterId } });
3148
3478
  }
3149
3479
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentBuilderComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
3150
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.7", type: ContentBuilderComponent, isStandalone: true, selector: "ngs-content-editor-builder", inputs: { config: { classPropertyName: "config", publicName: "config", isSignal: true, isRequired: false, transformFunction: null }, content: { classPropertyName: "content", publicName: "content", isSignal: true, isRequired: false, transformFunction: null }, contentChangedDelay: { classPropertyName: "contentChangedDelay", publicName: "contentChangedDelay", isSignal: true, isRequired: false, transformFunction: null }, persistDraft: { classPropertyName: "persistDraft", publicName: "persistDraft", isSignal: true, isRequired: false, transformFunction: null }, suggestions: { classPropertyName: "suggestions", publicName: "suggestions", isSignal: true, isRequired: false, transformFunction: null }, options: { classPropertyName: "options", publicName: "options", isSignal: true, isRequired: false, transformFunction: null }, scrollContainer: { classPropertyName: "scrollContainer", publicName: "scrollContainer", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { contentChanged: "contentChanged" }, host: { attributes: { "tabindex": "0" }, listeners: { "paste": "_onPaste($event)", "keydown": "_onKeyDown($event)" }, properties: { "class.is-block-dragging": "_blockDragging()", "class.is-selection-of-blocks-active": "isSelectionOfBlocksActive()", "class.select-none": "isSelectionOfBlocksActive()", "style.user-select": "isSelectionOfBlocksActive() ? \"none\" : null" }, classAttribute: "ngs-content-editor-builder" }, providers: [
3480
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.7", type: ContentBuilderComponent, isStandalone: true, selector: "ngs-content-editor-builder", inputs: { config: { classPropertyName: "config", publicName: "config", isSignal: true, isRequired: false, transformFunction: null }, documentId: { classPropertyName: "documentId", publicName: "documentId", isSignal: true, isRequired: false, transformFunction: null }, draftDebounceMs: { classPropertyName: "draftDebounceMs", publicName: "draftDebounceMs", isSignal: true, isRequired: false, transformFunction: null }, content: { classPropertyName: "content", publicName: "content", isSignal: true, isRequired: false, transformFunction: null }, contentChangedDelay: { classPropertyName: "contentChangedDelay", publicName: "contentChangedDelay", isSignal: true, isRequired: false, transformFunction: null }, persistDraft: { classPropertyName: "persistDraft", publicName: "persistDraft", isSignal: true, isRequired: false, transformFunction: null }, suggestions: { classPropertyName: "suggestions", publicName: "suggestions", isSignal: true, isRequired: false, transformFunction: null }, options: { classPropertyName: "options", publicName: "options", isSignal: true, isRequired: false, transformFunction: null }, scrollContainer: { classPropertyName: "scrollContainer", publicName: "scrollContainer", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { contentChanged: "contentChanged" }, host: { attributes: { "tabindex": "0" }, listeners: { "paste": "_onPaste($event)", "keydown": "_onKeyDown($event)" }, properties: { "class.is-block-dragging": "_blockDragging()", "class.is-selection-of-blocks-active": "isSelectionOfBlocksActive()", "class.select-none": "isSelectionOfBlocksActive()", "style.user-select": "isSelectionOfBlocksActive() ? \"none\" : null" }, classAttribute: "ngs-content-editor-builder" }, providers: [
3151
3481
  provideContentEditor(),
3152
3482
  ContentEditorHtmlSerializer,
3153
3483
  ContentEditorImporter,
@@ -3156,7 +3486,7 @@ class ContentBuilderComponent {
3156
3486
  provide: CONTENT_BUILDER,
3157
3487
  useExisting: forwardRef(() => ContentBuilderComponent)
3158
3488
  }
3159
- ], viewQueries: [{ propertyName: "blockMenu", first: true, predicate: ["suggestionsMenu"], descendants: true, isSignal: true }, { propertyName: "dropList", first: true, predicate: CdkDropList, descendants: true, isSignal: true }], exportAs: ["ngsContentEditorBuilder"], hostDirectives: [{ directive: BlockSelectionDirective, inputs: ["autoScrollContainerSelector", "autoScrollContainerSelector"] }], ngImport: i0, template: "<div class=\"container py-4\">\n <div class=\"content\"\n cdkDropList\n [cdkDropListData]=\"{}\"\n [cdkDropListConnectedTo]=\"connectedDropLists()\"\n [cdkDropListEnterPredicate]=\"canEnterRoot\"\n ngsTextSelectionPopup\n closestContentObserverClass=\"ngs-content-editor-content-editable\"\n [targetComponent]=\"commandBar\"\n (tagSelected)=\"onTagSelected($event)\"\n (cdkDropListDropped)=\"drop($event)\">\n @for (contentBlock of _content(); track contentBlock.id) {\n <div class=\"block\"\n [attr.data-block-id]=\"contentBlock.id\"\n [class.is-focused]=\"isBlockFocused(contentBlock.id)\"\n [class.is-active]=\"isActiveBlock(contentBlock.id)\"\n cdkDrag\n [cdkDragData]=\"contentBlock.id\"\n cdkMonitorSubtreeFocus\n (cdkDragStarted)=\"onDragStarted($event, contentBlock)\"\n (cdkDragEnded)=\"onDragEnded($event, contentBlock)\"\n (cdkFocusChange)=\"onFocusChange($event, contentBlock)\">\n <div class=\"block-controls\" [class.is-settings-popover-open]=\"settingsTrigger.api.isOpen()\">\n <button class=\"block-control\" aria-label=\"Add block\"\n (mousedown)=\"setActiveBlockId($event, contentBlock.id)\"\n [ngsMenuTriggerFor]=\"suggestionsMenu\"\n [ngsMenuTriggerData]=\"{target: {scope: {}, afterId: contentBlock.id}}\"\n [ngsMenuTriggerRestoreFocus]=\"false\">\n <ngs-icon name=\"fluent:add-24-regular\"/>\n </button>\n <div class=\"block-control block-control-drag\"\n (click)=\"selectBlock(contentBlock.id)\"\n [ngsPopoverTriggerFor]=\"settingsPopover\"\n (closed)=\"onSettingsPopoverClose()\"\n #settingsTrigger=\"ngsPopoverTriggerFor\"\n hasBackdrop\n position=\"before-center\">\n <button cdkDragHandle\n trigger=\"hover\"\n closeOnOriginClick\n closeOnOriginMouseLeave\n #dragTrigger=\"ngsPopoverTriggerFor\"\n [ngsPopoverTriggerFor]=\"dragControlTooltip\"\n position=\"below-center\"\n (mousedown)=\"dragTrigger.api.close()\"\n delay=\"1000\" class=\"w-full h-full flex items-center justify-center\">\n <ngs-icon name=\"fluent:re-order-dots-vertical-24-regular\"/>\n </button>\n </div>\n <ng-template #dragControlTooltip>\n <div class=\"bg-neutral-900 text-xs flex flex-col gap-0.5 rounded-lg items-center px-2 py-1.5 font-medium\">\n <div>\n <div class=\"text-neutral-100\">Drag <span class=\"text-neutral-400\">to move</span></div>\n </div>\n <div>\n <div class=\"text-neutral-100\">Click <span class=\"text-neutral-400\">to open menu</span></div>\n </div>\n </div>\n </ng-template>\n </div>\n <div class=\"block-content\" [class.is-selected]=\"isBlockSelected(contentBlock.id)\">\n <div class=\"drag-placeholder\" *cdkDragPlaceholder></div>\n <ng-container [ngComponentOutlet]=\"blockDefsMap.get(contentBlock.type) | async\"\n [ngComponentOutletInputs]=\"{\n id: contentBlock.id,\n content: contentBlock.content,\n settings: contentBlock.settings,\n props: contentBlock.props,\n index: $index\n }\"/>\n </div>\n </div>\n }\n </div>\n</div>\n\n<ngs-popover #settingsPopover=\"ngsPopover\">\n <div class=\"px-2 py-0 w-72 settings-popover\">\n <ngs-list>\n <ngs-list-item (click)=\"duplicateSelectedBlocks(settingsPopover)\">\n <ngs-icon name=\"fluent:copy-24-regular\" ngsListItemIcon/>\n <div ngsListItemTitle>Duplicate</div>\n </ngs-list-item>\n <ngs-list-item (click)=\"deleteSelectedBlocks(settingsPopover)\">\n <ngs-icon name=\"fluent:delete-24-regular\" ngsListItemIcon/>\n <div ngsListItemTitle>Delete</div>\n </ngs-list-item>\n </ngs-list>\n </div>\n</ngs-popover>\n\n<ngs-menu #suggestionsMenu=\"ngsMenu\" classList=\"min-h-[70vh] max-h-[70vh]!\" pushIntoViewport (closed)=\"onSuggestionsMenuClose($event)\">\n <ng-template ngsMenuContent let-target=\"target\">\n <div (click)=\"preventMenuClose($event)\">\n @for (suggestionItem of suggestions(); track $index; let first = $first) {\n @switch (suggestionItem.type) {\n @case ('heading') {\n <ngs-menu-heading>{{ suggestionItem.title }}</ngs-menu-heading>\n }\n @case ('item') {\n <button ngs-menu-item\n (click)=\"addBlockFromSuggestionMenu(suggestionsMenu, target, suggestionItem.blockType, suggestionItem.blockSettings)\">\n <div class=\"h-full flex items-center gap-3 py-2\">\n <div class=\"size-9 flex items-center rounded-lg justify-center bg-surface-container\">\n <ngs-icon [name]=\"suggestionItem.iconName\" class=\"!me-0\"/>\n </div>\n <div class=\"grow min-w-[200px]\">\n <div>{{ suggestionItem.title }}</div>\n <div class=\"text-2xs text-neutral-600\">{{ suggestionItem.description }}</div>\n </div>\n @if (suggestionItem.hotKeys) {\n <div class=\"ms-auto bg-surface-container-highest rounded-full h-5\n text-4xs px-2 flex items-center font-bold\">{{ suggestionItem.hotKeys }}</div>\n }\n </div>\n </button>\n }\n }\n }\n </div>\n </ng-template>\n</ngs-menu>\n", styles: [":host{--ngs-content-editor-builder-content-width: 704px;outline:none}:host.is-block-dragging{cursor:grabbing}:host .container{display:flex;width:100%;max-width:820px;min-height:200px;height:100%;padding:calc(var(--spacing, .25rem) * 5) calc(var(--spacing, .25rem) * 5) calc(var(--spacing, .25rem) * 5) 0;margin:0 auto;outline:none}:host .content{flex-grow:1;width:100%;min-width:0}:host .block{position:relative;flex:none;padding:var(--spacing, .25rem) 0;display:flex;align-items:center}:host .block:not(:has(.block-content.is-selected)):hover .block-content{background:var(--ngs-color-neutral-50)}:host:not(.is-block-dragging) .block:hover .block-controls,:host:not(.is-block-dragging) .block.is-active .block-controls{opacity:1}:host .block-content{position:relative;flex-grow:1;min-width:0;padding:calc(var(--spacing, .25rem) * 3)}:host .block-content.is-selected{background:var(--ngs-color-primary-100)}:host ::ng-deep .selection-area{background:var(--ngs-color-primary-100);opacity:.4;border:1px solid var(--ngs-color-primary);border-radius:var(--ngs-radius-sm)}:host ::ng-deep .ngs-content-editor-content-editable{-webkit-user-select:text;user-select:text}:host ::ng-deep .ngs-content-editor-content-editable a[data-ngs-headless-editor-mark=link]{color:var(--ngs-color-primary);text-decoration:underline;text-underline-offset:.15em}:host ::ng-deep .ngs-content-editor-content-editable.align-center{text-align:center}:host ::ng-deep .ngs-content-editor-content-editable.align-right{text-align:right}:host ::ng-deep .ngs-content-editor-content-editable.align-justify{text-align:justify}:host ::ng-deep .ngs-content-editor-content-editable>p{margin:0}:host ::ng-deep .ngs-content-editor-content-editable[data-empty]:before{content:attr(data-empty-placeholder);display:block;height:0;color:var(--ngs-color-neutral-500);pointer-events:none}:host.select-none ::ng-deep .ngs-content-editor-content-editable,:host.is-selection-of-blocks-active ::ng-deep .ngs-content-editor-content-editable{-webkit-user-select:none!important;user-select:none!important}:host .block-controls{left:0;display:flex;align-items:center;color:var(--ngs-color-neutral-500);width:calc(var(--spacing, .25rem) * 18);padding:0 calc(var(--spacing, .25rem) * 2);opacity:0;flex:none}:host .block-controls.is-settings-popover-open{opacity:1}:host .block-controls.is-settings-popover-open .block-control:not(.block-control-drag){opacity:0}:host .block-control{cursor:pointer;width:calc(var(--spacing, .25rem) * 7);height:calc(var(--spacing, .25rem) * 7);flex:none;border-radius:var(--ngs-radius-lg);display:inline-flex;align-items:center;justify-content:center}:host .block-control:hover{background:var(--ngs-color-surface-container-low);color:var(--ngs-color-on-surface)}:host .block-control-drag button{cursor:grab}:host .drag-placeholder{height:calc(var(--spacing, .25rem) * 8);flex:none;position:relative}:host .drag-placeholder:before{position:absolute;left:calc(var(--spacing, .25rem) * 18);display:block;right:0;content:\"\";height:calc(var(--spacing, .25rem) * 2);top:50%;transform:translateY(-50%);background:var(--ngs-color-primary-300);border-radius:calc(var(--spacing, .25rem) * .5)}:host ::ng-deep code{color:var(--ngs-color-primary)}.cdk-drag.cdk-drag-preview{overflow:hidden;display:flex;align-items:center;color:var(--ngs-color-neutral-500);width:calc(var(--spacing, .25rem) * 18);padding:0 calc(var(--spacing, .25rem) * 2)}.cdk-drag.cdk-drag-preview .block-control{width:calc(var(--spacing, .25rem) * 7);height:calc(var(--spacing, .25rem) * 7);flex:none;border-radius:var(--ngs-radius-lg);display:inline-flex;align-items:center;justify-content:center;cursor:grabbing}.cdk-drag.cdk-drag-preview .block-control:first-child{opacity:0}.cdk-drag.cdk-drag-preview .block-control:last-child{color:var(--ngs-color-on-surface)}.cdk-drag.cdk-drag-preview .block-content{opacity:0}.settings-popover{--ngs-list-list-item-one-line-container-height: calc(var(--spacing, .25rem) * 10)}\n/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n"], dependencies: [{ kind: "component", type: Icon, selector: "ngs-icon", inputs: ["name"], exportAs: ["ngsIcon"] }, { kind: "directive", type: NgComponentOutlet, selector: "[ngComponentOutlet]", inputs: ["ngComponentOutlet", "ngComponentOutletInputs", "ngComponentOutletInjector", "ngComponentOutletEnvironmentInjector", "ngComponentOutletContent", "ngComponentOutletNgModule"], exportAs: ["ngComponentOutlet"] }, { kind: "directive", type: CdkDrag, selector: "[cdkDrag]", inputs: ["cdkDragData", "cdkDragLockAxis", "cdkDragRootElement", "cdkDragBoundary", "cdkDragStartDelay", "cdkDragFreeDragPosition", "cdkDragDisabled", "cdkDragConstrainPosition", "cdkDragPreviewClass", "cdkDragPreviewContainer", "cdkDragScale"], outputs: ["cdkDragStarted", "cdkDragReleased", "cdkDragEnded", "cdkDragEntered", "cdkDragExited", "cdkDragDropped", "cdkDragMoved"], exportAs: ["cdkDrag"] }, { kind: "directive", type: CdkDropList, selector: "[cdkDropList], cdk-drop-list", inputs: ["cdkDropListConnectedTo", "cdkDropListData", "cdkDropListOrientation", "id", "cdkDropListLockAxis", "cdkDropListDisabled", "cdkDropListSortingDisabled", "cdkDropListEnterPredicate", "cdkDropListSortPredicate", "cdkDropListAutoScrollDisabled", "cdkDropListAutoScrollStep", "cdkDropListElementContainer", "cdkDropListHasAnchor"], outputs: ["cdkDropListDropped", "cdkDropListEntered", "cdkDropListExited", "cdkDropListSorted"], exportAs: ["cdkDropList"] }, { kind: "directive", type: CdkDragHandle, selector: "[cdkDragHandle]", inputs: ["cdkDragHandleDisabled"] }, { kind: "directive", type: CdkDragPlaceholder, selector: "ng-template[cdkDragPlaceholder]", inputs: ["data"] }, { kind: "component", type: Menu, selector: "ngs-menu", inputs: ["role", "classList", "xPosition", "yPosition", "pushIntoViewport"], outputs: ["closed"], exportAs: ["ngsMenu"] }, { kind: "component", type: MenuItem, selector: "ngs-menu-item, [ngs-menu-item]", inputs: ["disabled", "role", "selected"], outputs: ["_triggered"], exportAs: ["ngsMenuItem"] }, { kind: "directive", type: MenuTrigger, selector: "[ngsMenuTriggerFor]", inputs: ["ngsMenuTriggerFor", "ngsMenuTriggerData", "ngsMenuDisabled", "xPosition", "yPosition", "ngsMenuTriggerRestoreFocus"], outputs: ["menuOpened", "menuClosed"], exportAs: ["ngsMenuTrigger"] }, { kind: "directive", type: CdkMonitorFocus, selector: "[cdkMonitorElementFocus], [cdkMonitorSubtreeFocus]", outputs: ["cdkFocusChange"], exportAs: ["cdkMonitorFocus"] }, { kind: "directive", type: TextSelectionPopupDirective, selector: "[ngsTextSelectionPopup]", inputs: ["targetComponent", "closestContentObserverClass"], outputs: ["tagSelected"] }, { kind: "directive", type: PopoverTriggerForDirective, selector: "[ngsPopoverTriggerFor]", inputs: ["ngsPopoverTriggerFor", "ngsPopoverContext", "trigger", "position", "delay", "origin", "closeOnOriginClick", "closeOnOriginMouseLeave", "hasBackdrop"], outputs: ["opened", "closed"], exportAs: ["ngsPopoverTriggerFor"] }, { kind: "component", type: Popover, selector: "ngs-popover", exportAs: ["ngsPopover"] }, { kind: "directive", type: ListItemTitle, selector: "[ngsListItemTitle]" }, { kind: "directive", type: ListItemIcon, selector: "[ngsListItemIcon]" }, { kind: "component", type: ListItem, selector: "ngs-list-item, a[ngs-list-item], button[ngs-list-item]", inputs: ["disabled", "lines"], exportAs: ["ngsListItem"] }, { kind: "component", type: List, selector: "ngs-list", inputs: ["disabled", "disableRipple"], exportAs: ["ngsList"] }, { kind: "component", type: MenuHeading, selector: "ngs-menu-heading" }, { kind: "directive", type: MenuContent, selector: "[ngsMenuContent]" }, { kind: "pipe", type: AsyncPipe, name: "async" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
3489
+ ], viewQueries: [{ propertyName: "conversionMenu", first: true, predicate: ["conversionMenu"], descendants: true, isSignal: true }, { propertyName: "blockMenu", first: true, predicate: ["suggestionsMenu"], descendants: true, isSignal: true }, { propertyName: "dropList", first: true, predicate: CdkDropList, descendants: true, isSignal: true }], exportAs: ["ngsContentEditorBuilder"], hostDirectives: [{ directive: BlockSelectionDirective, inputs: ["autoScrollContainerSelector", "autoScrollContainerSelector"] }], ngImport: i0, template: "<div class=\"container py-4\">\n <div class=\"content\"\n cdkDropList\n [cdkDropListData]=\"{}\"\n [cdkDropListConnectedTo]=\"connectedDropLists()\"\n [cdkDropListEnterPredicate]=\"canEnterRoot\"\n ngsTextSelectionPopup\n closestContentObserverClass=\"ngs-content-editor-content-editable\"\n [targetComponent]=\"commandBar\"\n (tagSelected)=\"onTagSelected($event)\"\n (cdkDropListDropped)=\"drop($event)\">\n @for (contentBlock of _content(); track contentBlock.id) {\n <div class=\"block\"\n [attr.data-block-id]=\"contentBlock.id\"\n [class.is-focused]=\"isBlockFocused(contentBlock.id)\"\n [class.is-active]=\"isActiveBlock(contentBlock.id)\"\n cdkDrag\n [cdkDragData]=\"contentBlock.id\"\n cdkMonitorSubtreeFocus\n (cdkDragStarted)=\"onDragStarted($event, contentBlock)\"\n (cdkDragEnded)=\"onDragEnded($event, contentBlock)\"\n (cdkFocusChange)=\"onFocusChange($event, contentBlock)\">\n <div class=\"block-controls\" [class.is-settings-popover-open]=\"settingsTrigger.api.isOpen()\">\n <button class=\"block-control\" aria-label=\"Add block\"\n (mousedown)=\"setActiveBlockId($event, contentBlock.id)\"\n [ngsMenuTriggerFor]=\"suggestionsMenu\"\n [ngsMenuTriggerData]=\"{target: {scope: {}, afterId: contentBlock.id}}\"\n [ngsMenuTriggerRestoreFocus]=\"false\">\n <ngs-icon name=\"fluent:add-24-regular\"/>\n </button>\n <div class=\"block-control block-control-drag\"\n (click)=\"selectBlock(contentBlock.id)\"\n [ngsPopoverTriggerFor]=\"settingsPopover\"\n (closed)=\"onSettingsPopoverClose()\"\n #settingsTrigger=\"ngsPopoverTriggerFor\"\n hasBackdrop\n position=\"before-center\">\n <button cdkDragHandle\n trigger=\"hover\"\n closeOnOriginClick\n closeOnOriginMouseLeave\n #dragTrigger=\"ngsPopoverTriggerFor\"\n [ngsPopoverTriggerFor]=\"dragControlTooltip\"\n position=\"below-center\"\n (mousedown)=\"dragTrigger.api.close()\"\n delay=\"1000\" class=\"w-full h-full flex items-center justify-center\">\n <ngs-icon name=\"fluent:re-order-dots-vertical-24-regular\"/>\n </button>\n </div>\n <ng-template #dragControlTooltip>\n <div class=\"bg-neutral-900 text-xs flex flex-col gap-0.5 rounded-lg items-center px-2 py-1.5 font-medium\">\n <div>\n <div class=\"text-neutral-100\">Drag <span class=\"text-neutral-400\">to move</span></div>\n </div>\n <div>\n <div class=\"text-neutral-100\">Click <span class=\"text-neutral-400\">to open menu</span></div>\n </div>\n </div>\n </ng-template>\n </div>\n <div class=\"block-content\" [class.is-selected]=\"isBlockSelected(contentBlock.id)\">\n <div class=\"drag-placeholder\" *cdkDragPlaceholder></div>\n <ng-container [ngComponentOutlet]=\"blockDefsMap.get(contentBlock.type) | async\"\n [ngComponentOutletInputs]=\"{\n id: contentBlock.id,\n content: contentBlock.content,\n settings: contentBlock.settings,\n props: contentBlock.props,\n index: $index\n }\"/>\n </div>\n </div>\n }\n </div>\n</div>\n\n<ngs-popover #settingsPopover=\"ngsPopover\">\n <div class=\"px-2 py-0 w-72 settings-popover\">\n <ngs-list>\n @if (selectedBlocksModel.selected.length === 1 && canConvertBlock(selectedBlocksModel.selected[0])) {\n <ngs-list-item [ngsMenuTriggerFor]=\"conversionMenu\" [ngsMenuTriggerData]=\"{blockId: selectedBlocksModel.selected[0]}\" [ngsMenuTriggerRestoreFocus]=\"false\">\n <ngs-icon name=\"fluent:arrow-swap-24-regular\" ngsListItemIcon/>\n <div ngsListItemTitle>Turn into</div>\n </ngs-list-item>\n }\n <ngs-list-item (click)=\"duplicateSelectedBlocks(settingsPopover)\">\n <ngs-icon name=\"fluent:copy-24-regular\" ngsListItemIcon/>\n <div ngsListItemTitle>Duplicate</div>\n </ngs-list-item>\n <ngs-list-item (click)=\"deleteSelectedBlocks(settingsPopover)\">\n <ngs-icon name=\"fluent:delete-24-regular\" ngsListItemIcon/>\n <div ngsListItemTitle>Delete</div>\n </ngs-list-item>\n </ngs-list>\n </div>\n</ngs-popover>\n\n<ngs-menu #suggestionsMenu=\"ngsMenu\" classList=\"min-h-[70vh] max-h-[70vh]!\" pushIntoViewport (closed)=\"onSuggestionsMenuClose($event)\">\n <ng-template ngsMenuContent let-target=\"target\">\n <div (click)=\"preventMenuClose($event)\">\n @for (suggestionItem of insertionSuggestions(); track $index; let first = $first) {\n @switch (suggestionItem.type) {\n @case ('heading') {\n <ngs-menu-heading>{{ suggestionItem.title }}</ngs-menu-heading>\n }\n @case ('item') {\n <button ngs-menu-item\n (click)=\"addBlockFromSuggestionMenu(suggestionsMenu, target, suggestionItem.blockType, suggestionItem.blockSettings)\">\n <div class=\"h-full flex items-center gap-3 py-2\">\n <div class=\"size-9 flex items-center rounded-lg justify-center bg-surface-container\">\n <ngs-icon [name]=\"suggestionItem.iconName\" class=\"!me-0\"/>\n </div>\n <div class=\"grow min-w-[200px]\">\n <div>{{ suggestionItem.title }}</div>\n <div class=\"text-2xs text-neutral-600\">{{ suggestionItem.description }}</div>\n </div>\n @if (suggestionItem.hotKeys) {\n <div class=\"ms-auto bg-surface-container-highest rounded-full h-5\n text-4xs px-2 flex items-center font-bold\">{{ suggestionItem.hotKeys }}</div>\n }\n </div>\n </button>\n }\n }\n }\n </div>\n </ng-template>\n</ngs-menu>\n\n<ngs-menu #conversionMenu>\n <ng-template ngsMenuContent let-blockId=\"blockId\">\n @for (type of conversionTypes; track type) {\n <button ngs-menu-item (click)=\"convertBlock(blockId, type); settingsPopover.close()\">{{type}}</button>\n }\n </ng-template>\n</ngs-menu>\n", styles: [":host{--ngs-content-editor-builder-content-width: 704px;outline:none}:host.is-block-dragging{cursor:grabbing}:host .container{display:flex;width:100%;max-width:820px;min-height:200px;height:100%;padding:calc(var(--spacing, .25rem) * 5) calc(var(--spacing, .25rem) * 5) calc(var(--spacing, .25rem) * 5) 0;margin:0 auto;outline:none}:host .content{flex-grow:1;width:100%;min-width:0}:host .block{position:relative;flex:none;padding:var(--spacing, .25rem) 0;display:flex;align-items:center}:host .block:not(:has(.block-content.is-selected)):hover .block-content{background:var(--ngs-color-neutral-50)}:host:not(.is-block-dragging) .block:hover .block-controls,:host:not(.is-block-dragging) .block.is-active .block-controls{opacity:1}:host .block-content{position:relative;flex-grow:1;min-width:0;padding:calc(var(--spacing, .25rem) * 3)}:host .block-content.is-selected{background:var(--ngs-color-primary-100)}:host ::ng-deep .selection-area{background:var(--ngs-color-primary-100);opacity:.4;border:1px solid var(--ngs-color-primary);border-radius:var(--ngs-radius-sm)}:host ::ng-deep .ngs-content-editor-content-editable{-webkit-user-select:text;user-select:text}:host ::ng-deep .ngs-content-editor-content-editable a[data-ngs-headless-editor-mark=link]{color:var(--ngs-color-primary);text-decoration:underline;text-underline-offset:.15em}:host ::ng-deep .ngs-content-editor-content-editable.align-center{text-align:center}:host ::ng-deep .ngs-content-editor-content-editable.align-right{text-align:right}:host ::ng-deep .ngs-content-editor-content-editable.align-justify{text-align:justify}:host ::ng-deep .ngs-content-editor-content-editable>p{margin:0}:host ::ng-deep .ngs-content-editor-content-editable[data-empty]:before{content:attr(data-empty-placeholder);display:block;height:0;color:var(--ngs-color-neutral-500);pointer-events:none}:host.select-none ::ng-deep .ngs-content-editor-content-editable,:host.is-selection-of-blocks-active ::ng-deep .ngs-content-editor-content-editable{-webkit-user-select:none!important;user-select:none!important}:host .block-controls{left:0;display:flex;align-items:center;color:var(--ngs-color-neutral-500);width:calc(var(--spacing, .25rem) * 18);padding:0 calc(var(--spacing, .25rem) * 2);opacity:0;flex:none}:host .block-controls.is-settings-popover-open{opacity:1}:host .block-controls.is-settings-popover-open .block-control:not(.block-control-drag){opacity:0}:host .block-control{cursor:pointer;width:calc(var(--spacing, .25rem) * 7);height:calc(var(--spacing, .25rem) * 7);flex:none;border-radius:var(--ngs-radius-lg);display:inline-flex;align-items:center;justify-content:center}:host .block-control:hover{background:var(--ngs-color-surface-container-low);color:var(--ngs-color-on-surface)}:host .block-control-drag button{cursor:grab}:host .drag-placeholder{height:calc(var(--spacing, .25rem) * 8);flex:none;position:relative}:host .drag-placeholder:before{position:absolute;left:calc(var(--spacing, .25rem) * 18);display:block;right:0;content:\"\";height:calc(var(--spacing, .25rem) * 2);top:50%;transform:translateY(-50%);background:var(--ngs-color-primary-300);border-radius:calc(var(--spacing, .25rem) * .5)}:host ::ng-deep code{color:var(--ngs-color-primary)}.cdk-drag.cdk-drag-preview{overflow:hidden;display:flex;align-items:center;color:var(--ngs-color-neutral-500);width:calc(var(--spacing, .25rem) * 18);padding:0 calc(var(--spacing, .25rem) * 2)}.cdk-drag.cdk-drag-preview .block-control{width:calc(var(--spacing, .25rem) * 7);height:calc(var(--spacing, .25rem) * 7);flex:none;border-radius:var(--ngs-radius-lg);display:inline-flex;align-items:center;justify-content:center;cursor:grabbing}.cdk-drag.cdk-drag-preview .block-control:first-child{opacity:0}.cdk-drag.cdk-drag-preview .block-control:last-child{color:var(--ngs-color-on-surface)}.cdk-drag.cdk-drag-preview .block-content{opacity:0}.settings-popover{--ngs-list-list-item-one-line-container-height: calc(var(--spacing, .25rem) * 10)}\n/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n"], dependencies: [{ kind: "component", type: Icon, selector: "ngs-icon", inputs: ["name"], exportAs: ["ngsIcon"] }, { kind: "directive", type: NgComponentOutlet, selector: "[ngComponentOutlet]", inputs: ["ngComponentOutlet", "ngComponentOutletInputs", "ngComponentOutletInjector", "ngComponentOutletEnvironmentInjector", "ngComponentOutletContent", "ngComponentOutletNgModule"], exportAs: ["ngComponentOutlet"] }, { kind: "directive", type: CdkDrag, selector: "[cdkDrag]", inputs: ["cdkDragData", "cdkDragLockAxis", "cdkDragRootElement", "cdkDragBoundary", "cdkDragStartDelay", "cdkDragFreeDragPosition", "cdkDragDisabled", "cdkDragConstrainPosition", "cdkDragPreviewClass", "cdkDragPreviewContainer", "cdkDragScale"], outputs: ["cdkDragStarted", "cdkDragReleased", "cdkDragEnded", "cdkDragEntered", "cdkDragExited", "cdkDragDropped", "cdkDragMoved"], exportAs: ["cdkDrag"] }, { kind: "directive", type: CdkDropList, selector: "[cdkDropList], cdk-drop-list", inputs: ["cdkDropListConnectedTo", "cdkDropListData", "cdkDropListOrientation", "id", "cdkDropListLockAxis", "cdkDropListDisabled", "cdkDropListSortingDisabled", "cdkDropListEnterPredicate", "cdkDropListSortPredicate", "cdkDropListAutoScrollDisabled", "cdkDropListAutoScrollStep", "cdkDropListElementContainer", "cdkDropListHasAnchor"], outputs: ["cdkDropListDropped", "cdkDropListEntered", "cdkDropListExited", "cdkDropListSorted"], exportAs: ["cdkDropList"] }, { kind: "directive", type: CdkDragHandle, selector: "[cdkDragHandle]", inputs: ["cdkDragHandleDisabled"] }, { kind: "directive", type: CdkDragPlaceholder, selector: "ng-template[cdkDragPlaceholder]", inputs: ["data"] }, { kind: "component", type: Menu, selector: "ngs-menu", inputs: ["role", "classList", "xPosition", "yPosition", "pushIntoViewport"], outputs: ["closed"], exportAs: ["ngsMenu"] }, { kind: "component", type: MenuItem, selector: "ngs-menu-item, [ngs-menu-item]", inputs: ["disabled", "role", "selected"], outputs: ["_triggered"], exportAs: ["ngsMenuItem"] }, { kind: "directive", type: MenuTrigger, selector: "[ngsMenuTriggerFor]", inputs: ["ngsMenuTriggerFor", "ngsMenuTriggerData", "ngsMenuDisabled", "xPosition", "yPosition", "ngsMenuTriggerRestoreFocus"], outputs: ["menuOpened", "menuClosed"], exportAs: ["ngsMenuTrigger"] }, { kind: "directive", type: CdkMonitorFocus, selector: "[cdkMonitorElementFocus], [cdkMonitorSubtreeFocus]", outputs: ["cdkFocusChange"], exportAs: ["cdkMonitorFocus"] }, { kind: "directive", type: TextSelectionPopupDirective, selector: "[ngsTextSelectionPopup]", inputs: ["targetComponent", "closestContentObserverClass"], outputs: ["tagSelected"] }, { kind: "directive", type: PopoverTriggerForDirective, selector: "[ngsPopoverTriggerFor]", inputs: ["ngsPopoverTriggerFor", "ngsPopoverContext", "trigger", "position", "delay", "origin", "closeOnOriginClick", "closeOnOriginMouseLeave", "hasBackdrop"], outputs: ["opened", "closed"], exportAs: ["ngsPopoverTriggerFor"] }, { kind: "component", type: Popover, selector: "ngs-popover", exportAs: ["ngsPopover"] }, { kind: "directive", type: ListItemTitle, selector: "[ngsListItemTitle]" }, { kind: "directive", type: ListItemIcon, selector: "[ngsListItemIcon]" }, { kind: "component", type: ListItem, selector: "ngs-list-item, a[ngs-list-item], button[ngs-list-item]", inputs: ["disabled", "lines"], exportAs: ["ngsListItem"] }, { kind: "component", type: List, selector: "ngs-list", inputs: ["disabled", "disableRipple"], exportAs: ["ngsList"] }, { kind: "component", type: MenuHeading, selector: "ngs-menu-heading" }, { kind: "directive", type: MenuContent, selector: "[ngsMenuContent]" }, { kind: "pipe", type: AsyncPipe, name: "async" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
3160
3490
  }
3161
3491
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentBuilderComponent, decorators: [{
3162
3492
  type: Component,
@@ -3206,8 +3536,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImpor
3206
3536
  'tabindex': '0',
3207
3537
  '(paste)': '_onPaste($event)',
3208
3538
  '(keydown)': '_onKeyDown($event)',
3209
- }, template: "<div class=\"container py-4\">\n <div class=\"content\"\n cdkDropList\n [cdkDropListData]=\"{}\"\n [cdkDropListConnectedTo]=\"connectedDropLists()\"\n [cdkDropListEnterPredicate]=\"canEnterRoot\"\n ngsTextSelectionPopup\n closestContentObserverClass=\"ngs-content-editor-content-editable\"\n [targetComponent]=\"commandBar\"\n (tagSelected)=\"onTagSelected($event)\"\n (cdkDropListDropped)=\"drop($event)\">\n @for (contentBlock of _content(); track contentBlock.id) {\n <div class=\"block\"\n [attr.data-block-id]=\"contentBlock.id\"\n [class.is-focused]=\"isBlockFocused(contentBlock.id)\"\n [class.is-active]=\"isActiveBlock(contentBlock.id)\"\n cdkDrag\n [cdkDragData]=\"contentBlock.id\"\n cdkMonitorSubtreeFocus\n (cdkDragStarted)=\"onDragStarted($event, contentBlock)\"\n (cdkDragEnded)=\"onDragEnded($event, contentBlock)\"\n (cdkFocusChange)=\"onFocusChange($event, contentBlock)\">\n <div class=\"block-controls\" [class.is-settings-popover-open]=\"settingsTrigger.api.isOpen()\">\n <button class=\"block-control\" aria-label=\"Add block\"\n (mousedown)=\"setActiveBlockId($event, contentBlock.id)\"\n [ngsMenuTriggerFor]=\"suggestionsMenu\"\n [ngsMenuTriggerData]=\"{target: {scope: {}, afterId: contentBlock.id}}\"\n [ngsMenuTriggerRestoreFocus]=\"false\">\n <ngs-icon name=\"fluent:add-24-regular\"/>\n </button>\n <div class=\"block-control block-control-drag\"\n (click)=\"selectBlock(contentBlock.id)\"\n [ngsPopoverTriggerFor]=\"settingsPopover\"\n (closed)=\"onSettingsPopoverClose()\"\n #settingsTrigger=\"ngsPopoverTriggerFor\"\n hasBackdrop\n position=\"before-center\">\n <button cdkDragHandle\n trigger=\"hover\"\n closeOnOriginClick\n closeOnOriginMouseLeave\n #dragTrigger=\"ngsPopoverTriggerFor\"\n [ngsPopoverTriggerFor]=\"dragControlTooltip\"\n position=\"below-center\"\n (mousedown)=\"dragTrigger.api.close()\"\n delay=\"1000\" class=\"w-full h-full flex items-center justify-center\">\n <ngs-icon name=\"fluent:re-order-dots-vertical-24-regular\"/>\n </button>\n </div>\n <ng-template #dragControlTooltip>\n <div class=\"bg-neutral-900 text-xs flex flex-col gap-0.5 rounded-lg items-center px-2 py-1.5 font-medium\">\n <div>\n <div class=\"text-neutral-100\">Drag <span class=\"text-neutral-400\">to move</span></div>\n </div>\n <div>\n <div class=\"text-neutral-100\">Click <span class=\"text-neutral-400\">to open menu</span></div>\n </div>\n </div>\n </ng-template>\n </div>\n <div class=\"block-content\" [class.is-selected]=\"isBlockSelected(contentBlock.id)\">\n <div class=\"drag-placeholder\" *cdkDragPlaceholder></div>\n <ng-container [ngComponentOutlet]=\"blockDefsMap.get(contentBlock.type) | async\"\n [ngComponentOutletInputs]=\"{\n id: contentBlock.id,\n content: contentBlock.content,\n settings: contentBlock.settings,\n props: contentBlock.props,\n index: $index\n }\"/>\n </div>\n </div>\n }\n </div>\n</div>\n\n<ngs-popover #settingsPopover=\"ngsPopover\">\n <div class=\"px-2 py-0 w-72 settings-popover\">\n <ngs-list>\n <ngs-list-item (click)=\"duplicateSelectedBlocks(settingsPopover)\">\n <ngs-icon name=\"fluent:copy-24-regular\" ngsListItemIcon/>\n <div ngsListItemTitle>Duplicate</div>\n </ngs-list-item>\n <ngs-list-item (click)=\"deleteSelectedBlocks(settingsPopover)\">\n <ngs-icon name=\"fluent:delete-24-regular\" ngsListItemIcon/>\n <div ngsListItemTitle>Delete</div>\n </ngs-list-item>\n </ngs-list>\n </div>\n</ngs-popover>\n\n<ngs-menu #suggestionsMenu=\"ngsMenu\" classList=\"min-h-[70vh] max-h-[70vh]!\" pushIntoViewport (closed)=\"onSuggestionsMenuClose($event)\">\n <ng-template ngsMenuContent let-target=\"target\">\n <div (click)=\"preventMenuClose($event)\">\n @for (suggestionItem of suggestions(); track $index; let first = $first) {\n @switch (suggestionItem.type) {\n @case ('heading') {\n <ngs-menu-heading>{{ suggestionItem.title }}</ngs-menu-heading>\n }\n @case ('item') {\n <button ngs-menu-item\n (click)=\"addBlockFromSuggestionMenu(suggestionsMenu, target, suggestionItem.blockType, suggestionItem.blockSettings)\">\n <div class=\"h-full flex items-center gap-3 py-2\">\n <div class=\"size-9 flex items-center rounded-lg justify-center bg-surface-container\">\n <ngs-icon [name]=\"suggestionItem.iconName\" class=\"!me-0\"/>\n </div>\n <div class=\"grow min-w-[200px]\">\n <div>{{ suggestionItem.title }}</div>\n <div class=\"text-2xs text-neutral-600\">{{ suggestionItem.description }}</div>\n </div>\n @if (suggestionItem.hotKeys) {\n <div class=\"ms-auto bg-surface-container-highest rounded-full h-5\n text-4xs px-2 flex items-center font-bold\">{{ suggestionItem.hotKeys }}</div>\n }\n </div>\n </button>\n }\n }\n }\n </div>\n </ng-template>\n</ngs-menu>\n", styles: [":host{--ngs-content-editor-builder-content-width: 704px;outline:none}:host.is-block-dragging{cursor:grabbing}:host .container{display:flex;width:100%;max-width:820px;min-height:200px;height:100%;padding:calc(var(--spacing, .25rem) * 5) calc(var(--spacing, .25rem) * 5) calc(var(--spacing, .25rem) * 5) 0;margin:0 auto;outline:none}:host .content{flex-grow:1;width:100%;min-width:0}:host .block{position:relative;flex:none;padding:var(--spacing, .25rem) 0;display:flex;align-items:center}:host .block:not(:has(.block-content.is-selected)):hover .block-content{background:var(--ngs-color-neutral-50)}:host:not(.is-block-dragging) .block:hover .block-controls,:host:not(.is-block-dragging) .block.is-active .block-controls{opacity:1}:host .block-content{position:relative;flex-grow:1;min-width:0;padding:calc(var(--spacing, .25rem) * 3)}:host .block-content.is-selected{background:var(--ngs-color-primary-100)}:host ::ng-deep .selection-area{background:var(--ngs-color-primary-100);opacity:.4;border:1px solid var(--ngs-color-primary);border-radius:var(--ngs-radius-sm)}:host ::ng-deep .ngs-content-editor-content-editable{-webkit-user-select:text;user-select:text}:host ::ng-deep .ngs-content-editor-content-editable a[data-ngs-headless-editor-mark=link]{color:var(--ngs-color-primary);text-decoration:underline;text-underline-offset:.15em}:host ::ng-deep .ngs-content-editor-content-editable.align-center{text-align:center}:host ::ng-deep .ngs-content-editor-content-editable.align-right{text-align:right}:host ::ng-deep .ngs-content-editor-content-editable.align-justify{text-align:justify}:host ::ng-deep .ngs-content-editor-content-editable>p{margin:0}:host ::ng-deep .ngs-content-editor-content-editable[data-empty]:before{content:attr(data-empty-placeholder);display:block;height:0;color:var(--ngs-color-neutral-500);pointer-events:none}:host.select-none ::ng-deep .ngs-content-editor-content-editable,:host.is-selection-of-blocks-active ::ng-deep .ngs-content-editor-content-editable{-webkit-user-select:none!important;user-select:none!important}:host .block-controls{left:0;display:flex;align-items:center;color:var(--ngs-color-neutral-500);width:calc(var(--spacing, .25rem) * 18);padding:0 calc(var(--spacing, .25rem) * 2);opacity:0;flex:none}:host .block-controls.is-settings-popover-open{opacity:1}:host .block-controls.is-settings-popover-open .block-control:not(.block-control-drag){opacity:0}:host .block-control{cursor:pointer;width:calc(var(--spacing, .25rem) * 7);height:calc(var(--spacing, .25rem) * 7);flex:none;border-radius:var(--ngs-radius-lg);display:inline-flex;align-items:center;justify-content:center}:host .block-control:hover{background:var(--ngs-color-surface-container-low);color:var(--ngs-color-on-surface)}:host .block-control-drag button{cursor:grab}:host .drag-placeholder{height:calc(var(--spacing, .25rem) * 8);flex:none;position:relative}:host .drag-placeholder:before{position:absolute;left:calc(var(--spacing, .25rem) * 18);display:block;right:0;content:\"\";height:calc(var(--spacing, .25rem) * 2);top:50%;transform:translateY(-50%);background:var(--ngs-color-primary-300);border-radius:calc(var(--spacing, .25rem) * .5)}:host ::ng-deep code{color:var(--ngs-color-primary)}.cdk-drag.cdk-drag-preview{overflow:hidden;display:flex;align-items:center;color:var(--ngs-color-neutral-500);width:calc(var(--spacing, .25rem) * 18);padding:0 calc(var(--spacing, .25rem) * 2)}.cdk-drag.cdk-drag-preview .block-control{width:calc(var(--spacing, .25rem) * 7);height:calc(var(--spacing, .25rem) * 7);flex:none;border-radius:var(--ngs-radius-lg);display:inline-flex;align-items:center;justify-content:center;cursor:grabbing}.cdk-drag.cdk-drag-preview .block-control:first-child{opacity:0}.cdk-drag.cdk-drag-preview .block-control:last-child{color:var(--ngs-color-on-surface)}.cdk-drag.cdk-drag-preview .block-content{opacity:0}.settings-popover{--ngs-list-list-item-one-line-container-height: calc(var(--spacing, .25rem) * 10)}\n/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n"] }]
3210
- }], ctorParameters: () => [], propDecorators: { config: [{ type: i0.Input, args: [{ isSignal: true, alias: "config", required: false }] }], blockMenu: [{ type: i0.ViewChild, args: ['suggestionsMenu', { isSignal: true }] }], dropList: [{ type: i0.ViewChild, args: [i0.forwardRef(() => CdkDropList), { isSignal: true }] }], content: [{ type: i0.Input, args: [{ isSignal: true, alias: "content", required: false }] }], contentChangedDelay: [{ type: i0.Input, args: [{ isSignal: true, alias: "contentChangedDelay", required: false }] }], persistDraft: [{ type: i0.Input, args: [{ isSignal: true, alias: "persistDraft", required: false }] }], suggestions: [{ type: i0.Input, args: [{ isSignal: true, alias: "suggestions", required: false }] }], options: [{ type: i0.Input, args: [{ isSignal: true, alias: "options", required: false }] }], scrollContainer: [{ type: i0.Input, args: [{ isSignal: true, alias: "scrollContainer", required: false }] }], contentChanged: [{ type: i0.Output, args: ["contentChanged"] }] } });
3539
+ }, template: "<div class=\"container py-4\">\n <div class=\"content\"\n cdkDropList\n [cdkDropListData]=\"{}\"\n [cdkDropListConnectedTo]=\"connectedDropLists()\"\n [cdkDropListEnterPredicate]=\"canEnterRoot\"\n ngsTextSelectionPopup\n closestContentObserverClass=\"ngs-content-editor-content-editable\"\n [targetComponent]=\"commandBar\"\n (tagSelected)=\"onTagSelected($event)\"\n (cdkDropListDropped)=\"drop($event)\">\n @for (contentBlock of _content(); track contentBlock.id) {\n <div class=\"block\"\n [attr.data-block-id]=\"contentBlock.id\"\n [class.is-focused]=\"isBlockFocused(contentBlock.id)\"\n [class.is-active]=\"isActiveBlock(contentBlock.id)\"\n cdkDrag\n [cdkDragData]=\"contentBlock.id\"\n cdkMonitorSubtreeFocus\n (cdkDragStarted)=\"onDragStarted($event, contentBlock)\"\n (cdkDragEnded)=\"onDragEnded($event, contentBlock)\"\n (cdkFocusChange)=\"onFocusChange($event, contentBlock)\">\n <div class=\"block-controls\" [class.is-settings-popover-open]=\"settingsTrigger.api.isOpen()\">\n <button class=\"block-control\" aria-label=\"Add block\"\n (mousedown)=\"setActiveBlockId($event, contentBlock.id)\"\n [ngsMenuTriggerFor]=\"suggestionsMenu\"\n [ngsMenuTriggerData]=\"{target: {scope: {}, afterId: contentBlock.id}}\"\n [ngsMenuTriggerRestoreFocus]=\"false\">\n <ngs-icon name=\"fluent:add-24-regular\"/>\n </button>\n <div class=\"block-control block-control-drag\"\n (click)=\"selectBlock(contentBlock.id)\"\n [ngsPopoverTriggerFor]=\"settingsPopover\"\n (closed)=\"onSettingsPopoverClose()\"\n #settingsTrigger=\"ngsPopoverTriggerFor\"\n hasBackdrop\n position=\"before-center\">\n <button cdkDragHandle\n trigger=\"hover\"\n closeOnOriginClick\n closeOnOriginMouseLeave\n #dragTrigger=\"ngsPopoverTriggerFor\"\n [ngsPopoverTriggerFor]=\"dragControlTooltip\"\n position=\"below-center\"\n (mousedown)=\"dragTrigger.api.close()\"\n delay=\"1000\" class=\"w-full h-full flex items-center justify-center\">\n <ngs-icon name=\"fluent:re-order-dots-vertical-24-regular\"/>\n </button>\n </div>\n <ng-template #dragControlTooltip>\n <div class=\"bg-neutral-900 text-xs flex flex-col gap-0.5 rounded-lg items-center px-2 py-1.5 font-medium\">\n <div>\n <div class=\"text-neutral-100\">Drag <span class=\"text-neutral-400\">to move</span></div>\n </div>\n <div>\n <div class=\"text-neutral-100\">Click <span class=\"text-neutral-400\">to open menu</span></div>\n </div>\n </div>\n </ng-template>\n </div>\n <div class=\"block-content\" [class.is-selected]=\"isBlockSelected(contentBlock.id)\">\n <div class=\"drag-placeholder\" *cdkDragPlaceholder></div>\n <ng-container [ngComponentOutlet]=\"blockDefsMap.get(contentBlock.type) | async\"\n [ngComponentOutletInputs]=\"{\n id: contentBlock.id,\n content: contentBlock.content,\n settings: contentBlock.settings,\n props: contentBlock.props,\n index: $index\n }\"/>\n </div>\n </div>\n }\n </div>\n</div>\n\n<ngs-popover #settingsPopover=\"ngsPopover\">\n <div class=\"px-2 py-0 w-72 settings-popover\">\n <ngs-list>\n @if (selectedBlocksModel.selected.length === 1 && canConvertBlock(selectedBlocksModel.selected[0])) {\n <ngs-list-item [ngsMenuTriggerFor]=\"conversionMenu\" [ngsMenuTriggerData]=\"{blockId: selectedBlocksModel.selected[0]}\" [ngsMenuTriggerRestoreFocus]=\"false\">\n <ngs-icon name=\"fluent:arrow-swap-24-regular\" ngsListItemIcon/>\n <div ngsListItemTitle>Turn into</div>\n </ngs-list-item>\n }\n <ngs-list-item (click)=\"duplicateSelectedBlocks(settingsPopover)\">\n <ngs-icon name=\"fluent:copy-24-regular\" ngsListItemIcon/>\n <div ngsListItemTitle>Duplicate</div>\n </ngs-list-item>\n <ngs-list-item (click)=\"deleteSelectedBlocks(settingsPopover)\">\n <ngs-icon name=\"fluent:delete-24-regular\" ngsListItemIcon/>\n <div ngsListItemTitle>Delete</div>\n </ngs-list-item>\n </ngs-list>\n </div>\n</ngs-popover>\n\n<ngs-menu #suggestionsMenu=\"ngsMenu\" classList=\"min-h-[70vh] max-h-[70vh]!\" pushIntoViewport (closed)=\"onSuggestionsMenuClose($event)\">\n <ng-template ngsMenuContent let-target=\"target\">\n <div (click)=\"preventMenuClose($event)\">\n @for (suggestionItem of insertionSuggestions(); track $index; let first = $first) {\n @switch (suggestionItem.type) {\n @case ('heading') {\n <ngs-menu-heading>{{ suggestionItem.title }}</ngs-menu-heading>\n }\n @case ('item') {\n <button ngs-menu-item\n (click)=\"addBlockFromSuggestionMenu(suggestionsMenu, target, suggestionItem.blockType, suggestionItem.blockSettings)\">\n <div class=\"h-full flex items-center gap-3 py-2\">\n <div class=\"size-9 flex items-center rounded-lg justify-center bg-surface-container\">\n <ngs-icon [name]=\"suggestionItem.iconName\" class=\"!me-0\"/>\n </div>\n <div class=\"grow min-w-[200px]\">\n <div>{{ suggestionItem.title }}</div>\n <div class=\"text-2xs text-neutral-600\">{{ suggestionItem.description }}</div>\n </div>\n @if (suggestionItem.hotKeys) {\n <div class=\"ms-auto bg-surface-container-highest rounded-full h-5\n text-4xs px-2 flex items-center font-bold\">{{ suggestionItem.hotKeys }}</div>\n }\n </div>\n </button>\n }\n }\n }\n </div>\n </ng-template>\n</ngs-menu>\n\n<ngs-menu #conversionMenu>\n <ng-template ngsMenuContent let-blockId=\"blockId\">\n @for (type of conversionTypes; track type) {\n <button ngs-menu-item (click)=\"convertBlock(blockId, type); settingsPopover.close()\">{{type}}</button>\n }\n </ng-template>\n</ngs-menu>\n", styles: [":host{--ngs-content-editor-builder-content-width: 704px;outline:none}:host.is-block-dragging{cursor:grabbing}:host .container{display:flex;width:100%;max-width:820px;min-height:200px;height:100%;padding:calc(var(--spacing, .25rem) * 5) calc(var(--spacing, .25rem) * 5) calc(var(--spacing, .25rem) * 5) 0;margin:0 auto;outline:none}:host .content{flex-grow:1;width:100%;min-width:0}:host .block{position:relative;flex:none;padding:var(--spacing, .25rem) 0;display:flex;align-items:center}:host .block:not(:has(.block-content.is-selected)):hover .block-content{background:var(--ngs-color-neutral-50)}:host:not(.is-block-dragging) .block:hover .block-controls,:host:not(.is-block-dragging) .block.is-active .block-controls{opacity:1}:host .block-content{position:relative;flex-grow:1;min-width:0;padding:calc(var(--spacing, .25rem) * 3)}:host .block-content.is-selected{background:var(--ngs-color-primary-100)}:host ::ng-deep .selection-area{background:var(--ngs-color-primary-100);opacity:.4;border:1px solid var(--ngs-color-primary);border-radius:var(--ngs-radius-sm)}:host ::ng-deep .ngs-content-editor-content-editable{-webkit-user-select:text;user-select:text}:host ::ng-deep .ngs-content-editor-content-editable a[data-ngs-headless-editor-mark=link]{color:var(--ngs-color-primary);text-decoration:underline;text-underline-offset:.15em}:host ::ng-deep .ngs-content-editor-content-editable.align-center{text-align:center}:host ::ng-deep .ngs-content-editor-content-editable.align-right{text-align:right}:host ::ng-deep .ngs-content-editor-content-editable.align-justify{text-align:justify}:host ::ng-deep .ngs-content-editor-content-editable>p{margin:0}:host ::ng-deep .ngs-content-editor-content-editable[data-empty]:before{content:attr(data-empty-placeholder);display:block;height:0;color:var(--ngs-color-neutral-500);pointer-events:none}:host.select-none ::ng-deep .ngs-content-editor-content-editable,:host.is-selection-of-blocks-active ::ng-deep .ngs-content-editor-content-editable{-webkit-user-select:none!important;user-select:none!important}:host .block-controls{left:0;display:flex;align-items:center;color:var(--ngs-color-neutral-500);width:calc(var(--spacing, .25rem) * 18);padding:0 calc(var(--spacing, .25rem) * 2);opacity:0;flex:none}:host .block-controls.is-settings-popover-open{opacity:1}:host .block-controls.is-settings-popover-open .block-control:not(.block-control-drag){opacity:0}:host .block-control{cursor:pointer;width:calc(var(--spacing, .25rem) * 7);height:calc(var(--spacing, .25rem) * 7);flex:none;border-radius:var(--ngs-radius-lg);display:inline-flex;align-items:center;justify-content:center}:host .block-control:hover{background:var(--ngs-color-surface-container-low);color:var(--ngs-color-on-surface)}:host .block-control-drag button{cursor:grab}:host .drag-placeholder{height:calc(var(--spacing, .25rem) * 8);flex:none;position:relative}:host .drag-placeholder:before{position:absolute;left:calc(var(--spacing, .25rem) * 18);display:block;right:0;content:\"\";height:calc(var(--spacing, .25rem) * 2);top:50%;transform:translateY(-50%);background:var(--ngs-color-primary-300);border-radius:calc(var(--spacing, .25rem) * .5)}:host ::ng-deep code{color:var(--ngs-color-primary)}.cdk-drag.cdk-drag-preview{overflow:hidden;display:flex;align-items:center;color:var(--ngs-color-neutral-500);width:calc(var(--spacing, .25rem) * 18);padding:0 calc(var(--spacing, .25rem) * 2)}.cdk-drag.cdk-drag-preview .block-control{width:calc(var(--spacing, .25rem) * 7);height:calc(var(--spacing, .25rem) * 7);flex:none;border-radius:var(--ngs-radius-lg);display:inline-flex;align-items:center;justify-content:center;cursor:grabbing}.cdk-drag.cdk-drag-preview .block-control:first-child{opacity:0}.cdk-drag.cdk-drag-preview .block-control:last-child{color:var(--ngs-color-on-surface)}.cdk-drag.cdk-drag-preview .block-content{opacity:0}.settings-popover{--ngs-list-list-item-one-line-container-height: calc(var(--spacing, .25rem) * 10)}\n/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n"] }]
3540
+ }], ctorParameters: () => [], propDecorators: { config: [{ type: i0.Input, args: [{ isSignal: true, alias: "config", required: false }] }], conversionMenu: [{ type: i0.ViewChild, args: ['conversionMenu', { isSignal: true }] }], blockMenu: [{ type: i0.ViewChild, args: ['suggestionsMenu', { isSignal: true }] }], documentId: [{ type: i0.Input, args: [{ isSignal: true, alias: "documentId", required: false }] }], draftDebounceMs: [{ type: i0.Input, args: [{ isSignal: true, alias: "draftDebounceMs", required: false }] }], dropList: [{ type: i0.ViewChild, args: [i0.forwardRef(() => CdkDropList), { isSignal: true }] }], content: [{ type: i0.Input, args: [{ isSignal: true, alias: "content", required: false }] }], contentChangedDelay: [{ type: i0.Input, args: [{ isSignal: true, alias: "contentChangedDelay", required: false }] }], persistDraft: [{ type: i0.Input, args: [{ isSignal: true, alias: "persistDraft", required: false }] }], suggestions: [{ type: i0.Input, args: [{ isSignal: true, alias: "suggestions", required: false }] }], options: [{ type: i0.Input, args: [{ isSignal: true, alias: "options", required: false }] }], scrollContainer: [{ type: i0.Input, args: [{ isSignal: true, alias: "scrollContainer", required: false }] }], contentChanged: [{ type: i0.Output, args: ["contentChanged"] }] } });
3211
3541
 
3212
3542
  const CONTENT_EDITOR_BLOCK_RENDERERS = new InjectionToken('CONTENT_EDITOR_BLOCK_RENDERERS', {
3213
3543
  factory: () => [],
@@ -3346,13 +3676,22 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImpor
3346
3676
  args: [{ selector: 'ngs-content-editor-gallery-renderer', imports: [NgsHeadlessEditorRuns, ImageViewerDirective, ImageViewerPictureDirective, Carousel, CarouselCard, Button, Icon], changeDetection: ChangeDetectionStrategy.OnPush, template: "@if (selectedImage(); as image) {\n <figure class=\"gallery m-0 flex min-w-0 flex-col gap-4\" ngsImageViewer role=\"region\" aria-label=\"Image gallery\" aria-roledescription=\"carousel\" (keydown)=\"onKeydown($event)\">\n <div class=\"gallery-preview relative overflow-hidden rounded-lg\">\n <ngs-carousel tabindex=\"0\" aria-label=\"Gallery images. Use arrow keys to navigate.\" (indexChange)=\"onIndexChange($event)\">\n @for (slide of images(); track slide.id) {\n <ngs-carousel-card role=\"group\" aria-roledescription=\"slide\" [attr.aria-label]=\"($index + 1) + ' of ' + images().length\" [attr.aria-hidden]=\"$index !== selectedIndex()\">\n <button ngsButton type=\"button\" class=\"gallery-picture\" [fullWidth]=\"true\" [attr.tabindex]=\"$index === selectedIndex() ? 0 : -1\" ngsImageViewerPicture [sourceUrl]=\"slide.src\" [caption]=\"captionText(slide.caption)\" [attr.aria-label]=\"slide.alt || 'View image'\">\n <img [src]=\"slide.src\" [alt]=\"slide.alt\" draggable=\"false\">\n </button>\n </ngs-carousel-card>\n }\n </ngs-carousel>\n <button ngsIconButton type=\"button\" class=\"preview-action expand-action absolute right-3 top-3\" aria-label=\"View full-size image\" ngsImageViewerPicture [sourceUrl]=\"image.src\" [caption]=\"captionText(image.caption)\">\n <ngs-icon name=\"fluent:arrow-expand-24-regular\"/>\n </button>\n @if (images().length > 1) {\n <button ngsIconButton type=\"button\" class=\"preview-action absolute left-3 top-1/2 -translate-y-1/2\" aria-label=\"Previous image\" [disabled]=\"selectedIndex() === 0\" (click)=\"selectImage(selectedIndex() - 1)\"><ngs-icon name=\"fluent:chevron-left-24-regular\"/></button>\n <button ngsIconButton type=\"button\" class=\"preview-action absolute right-3 top-1/2 -translate-y-1/2\" aria-label=\"Next image\" [disabled]=\"selectedIndex() === images().length - 1\" (click)=\"selectImage(selectedIndex() + 1)\"><ngs-icon name=\"fluent:chevron-right-24-regular\"/></button>\n }\n </div>\n @if (captionText(image.caption) || images().length > 1) {\n <figcaption class=\"flex min-w-0 items-start justify-between gap-4\">\n <span class=\"gallery-caption min-w-0 flex-1 text-sm\" [ngsHeadlessEditorRuns]=\"image.caption\"></span>\n @if (images().length > 1) {\n <span class=\"gallery-counter shrink-0 text-sm\" aria-live=\"polite\" aria-atomic=\"true\">{{ selectedIndex() + 1 }} of {{ images().length }}</span>\n }\n </figcaption>\n }\n @if (images().length > 1) {\n <div class=\"thumbnail-strip relative flex min-w-0 gap-3 overflow-x-auto p-1\" role=\"group\" aria-label=\"Choose an image\">\n @for (thumbnail of images(); track thumbnail.id) {\n <button #thumbnailButton ngsButton type=\"button\" class=\"thumbnail-picture shrink-0\" [class.is-selected]=\"$index === selectedIndex()\" [attr.aria-label]=\"'Select image ' + ($index + 1)\" [attr.aria-pressed]=\"$index === selectedIndex()\" (click)=\"selectImage($index)\">\n <img [src]=\"thumbnail.src\" alt=\"\" draggable=\"false\" loading=\"lazy\">\n </button>\n }\n </div>\n }\n </figure>\n}\n", styles: [":host{display:block;min-width:0}:host .gallery{margin:0}:host figcaption{margin:0}:host ngs-carousel{--ngs-carousel-gap: 0px;outline-offset:-3px}:host ngs-carousel:focus-visible{outline:2px solid var(--ngs-color-primary)}:host ngs-carousel ::ng-deep .content{overflow-x:auto;scrollbar-width:none;scroll-snap-type:x mandatory}:host ngs-carousel ::ng-deep .content::-webkit-scrollbar{display:none}:host ngs-carousel-card{width:100%;min-width:0;scroll-snap-align:center}:host button[ngsButton]{--ngs-button-height: auto;--ngs-button-padding: 0;--ngs-button-content-gap: 0;display:block;min-width:0;overflow:hidden;line-height:0}:host button[ngsButton] img{display:block;width:100%;margin:0;object-fit:cover}:host button[ngsButton] ::ng-deep .content{display:block;width:100%}:host button[ngsButton].gallery-picture{width:100%;border-radius:0}:host button[ngsButton].gallery-picture img{aspect-ratio:16/9}:host button[ngsButton].thumbnail-picture{width:calc(var(--spacing, .25rem) * 32);border-radius:var(--ngs-radius-md)}:host button[ngsButton].thumbnail-picture img{aspect-ratio:16/9}:host button[ngsButton].thumbnail-picture.is-selected{outline:2px solid var(--ngs-color-primary);outline-offset:2px}:host .gallery-preview{background:var(--ngs-color-surface-container-low)}:host button[ngsIconButton].preview-action{--ngs-button-height: calc(var(--spacing, .25rem) * 9);--ngs-button-bg: var(--ngs-color-white);--ngs-button-color: var(--ngs-color-black);--ngs-button-hover-bg: var(--ngs-color-white);position:absolute;box-shadow:var(--ngs-shadow-sm)}@supports (color: color-mix(in lab,red,red)){:host button[ngsIconButton].preview-action{--ngs-button-hover-bg: color-mix(in srgb, var(--ngs-color-white), var(--ngs-color-black) 8%)}}:host button[ngsIconButton].preview-action.ngs-button-disabled{opacity:.55;background:var(--ngs-color-white)}:host .gallery-caption,:host .gallery-counter{color:var(--ngs-color-on-surface-variant)}:host .gallery-caption{overflow-wrap:anywhere}:host .thumbnail-strip{scrollbar-width:thin}\n/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n"] }]
3347
3677
  }], ctorParameters: () => [], propDecorators: { cards: [{ type: i0.ViewChildren, args: [i0.forwardRef(() => CarouselCard), { isSignal: true }] }], thumbnails: [{ type: i0.ViewChildren, args: ['thumbnailButton', { ...{ read: (ElementRef) }, isSignal: true }] }] } });
3348
3678
 
3349
- /** Read files for the default data URL upload or a consumer's uploadFn. */
3350
- function readContentEditorFile(file) {
3679
+ /** Read files with actual cancellation and progress. */
3680
+ function readContentEditorFile(file, context) {
3351
3681
  return new Promise((resolve, reject) => {
3352
3682
  const reader = new FileReader();
3353
- reader.onload = () => typeof reader.result === 'string' ? resolve(reader.result) : reject(new Error('Could not read file'));
3354
- reader.onerror = () => reject(new Error('Could not read file'));
3355
- reader.onabort = () => reject(new Error('File reading cancelled'));
3683
+ const abort = () => { reader.abort(); reject(new DOMException('Upload cancelled', 'AbortError')); cleanup(); };
3684
+ const cleanup = () => context?.signal.removeEventListener('abort', abort);
3685
+ if (context?.signal.aborted) {
3686
+ abort();
3687
+ return;
3688
+ }
3689
+ context?.signal.addEventListener('abort', abort, { once: true });
3690
+ reader.onload = () => { cleanup(); typeof reader.result === 'string' ? resolve(reader.result) : reject(new Error('Could not read file')); };
3691
+ reader.onerror = () => { cleanup(); reject(new Error('Could not read file')); };
3692
+ reader.onabort = () => { cleanup(); reject(new DOMException('Upload cancelled', 'AbortError')); };
3693
+ reader.onprogress = event => { if (event.lengthComputable)
3694
+ context?.onProgress(event.loaded / event.total * 100); };
3356
3695
  reader.readAsDataURL(file);
3357
3696
  });
3358
3697
  }
@@ -3807,6 +4146,10 @@ const CONTENT_EDITOR_DEFAULT_RENDERERS = [
3807
4146
  ];
3808
4147
 
3809
4148
  class ContentEditorRenderer {
4149
+ globalConfig = inject(CONTENT_EDITOR_CONFIG);
4150
+ parentConfig = inject(CONTENT_EDITOR_RENDER_CONFIG, { skipSelf: true, optional: true });
4151
+ resolvedConfig = computed(() => mergeContentEditorConfig(this.globalConfig, this.parentConfig?.() ?? {}, this.config()), /* @ts-ignore */
4152
+ ...(ngDevMode ? [{ debugName: "resolvedConfig" }] : /* istanbul ignore next */ []));
3810
4153
  htmlSerializer = inject(ContentEditorHtmlSerializer);
3811
4154
  config = input({}, /* @ts-ignore */
3812
4155
  ...(ngDevMode ? [{ debugName: "config" }] : /* istanbul ignore next */ []));
@@ -3818,12 +4161,13 @@ class ContentEditorRenderer {
3818
4161
  blocks = input(null, /* @ts-ignore */
3819
4162
  ...(ngDevMode ? [{ debugName: "blocks" }] : /* istanbul ignore next */ []));
3820
4163
  toHtml(config = {}) {
3821
- return this.htmlSerializer.toHtml({ version: 1, blocks: this.blocks() ?? this.content().blocks }, mergeContentEditorConfig(this.config(), config));
4164
+ return this.htmlSerializer.toHtml({ version: 1, blocks: this.blocks() ?? this.content().blocks }, mergeContentEditorConfig(this.resolvedConfig(), config));
3822
4165
  }
3823
4166
  rendererMap = computed(() => {
3824
4167
  const renderers = [
3825
4168
  ...CONTENT_EDITOR_DEFAULT_RENDERERS,
3826
4169
  ...this.providedRendererGroups.flat(),
4170
+ ...Object.entries(this.resolvedConfig().blocks ?? {}).flatMap(([type, block]) => block.renderer ? [{ type, component: block.renderer }] : []),
3827
4171
  ];
3828
4172
  return new Map(renderers.map(renderer => [renderer.type, renderer.component]));
3829
4173
  }, /* @ts-ignore */
@@ -3850,20 +4194,192 @@ class ContentEditorRenderer {
3850
4194
  }, /* @ts-ignore */
3851
4195
  ...(ngDevMode ? [{ debugName: "items" }] : /* istanbul ignore next */ []));
3852
4196
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorRenderer, deps: [], target: i0.ɵɵFactoryTarget.Component });
3853
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.7", type: ContentEditorRenderer, isStandalone: true, selector: "ngs-content-editor-renderer", inputs: { config: { classPropertyName: "config", publicName: "config", isSignal: true, isRequired: false, transformFunction: null }, content: { classPropertyName: "content", publicName: "content", isSignal: true, isRequired: false, transformFunction: null }, blocks: { classPropertyName: "blocks", publicName: "blocks", isSignal: true, isRequired: false, transformFunction: null } }, host: { classAttribute: "ngs-content-editor-renderer prose max-w-full" }, providers: [provideContentEditor(), ContentEditorHtmlSerializer], exportAs: ["ngsContentEditorRenderer"], ngImport: i0, template: "@for (item of items(); track item.block.id || $index) {\n @if (item.component) {\n <div class=\"block\" [attr.data-block-id]=\"item.block.id\" [attr.data-block-type]=\"item.block.type\">\n <ng-container\n [ngComponentOutlet]=\"item.component\"\n [ngComponentOutletInputs]=\"item.inputs\"\n />\n </div>\n }\n}\n", styles: [":host{--ngs-content-editor-renderer-block-gap: calc(var(--spacing, .25rem) * 4);display:flex;flex-direction:column;gap:var(--ngs-content-editor-renderer-block-gap)}:host .block{min-width:0}:host ::ng-deep a[data-ngs-headless-editor-mark=link]{color:var(--ngs-color-primary);text-decoration:underline;text-underline-offset:.15em}\n/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n"], dependencies: [{ kind: "directive", type: NgComponentOutlet, selector: "[ngComponentOutlet]", inputs: ["ngComponentOutlet", "ngComponentOutletInputs", "ngComponentOutletInjector", "ngComponentOutletEnvironmentInjector", "ngComponentOutletContent", "ngComponentOutletNgModule"], exportAs: ["ngComponentOutlet"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
4197
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.7", type: ContentEditorRenderer, isStandalone: true, selector: "ngs-content-editor-renderer", inputs: { config: { classPropertyName: "config", publicName: "config", isSignal: true, isRequired: false, transformFunction: null }, content: { classPropertyName: "content", publicName: "content", isSignal: true, isRequired: false, transformFunction: null }, blocks: { classPropertyName: "blocks", publicName: "blocks", isSignal: true, isRequired: false, transformFunction: null } }, host: { classAttribute: "ngs-content-editor-renderer prose max-w-full" }, providers: [provideContentEditor(), ContentEditorHtmlSerializer, {
4198
+ provide: CONTENT_EDITOR_RENDER_CONFIG, useFactory: () => inject(forwardRef(() => ContentEditorRenderer)).resolvedConfig
4199
+ }], exportAs: ["ngsContentEditorRenderer"], ngImport: i0, template: "@for (item of items(); track item.block.id || $index) {\n @if (item.component) {\n <div class=\"block\" [attr.data-block-id]=\"item.block.id\" [attr.data-block-type]=\"item.block.type\">\n <ng-container\n [ngComponentOutlet]=\"item.component\"\n [ngComponentOutletInputs]=\"item.inputs\"\n />\n </div>\n }\n}\n", styles: [":host{--ngs-content-editor-renderer-block-gap: calc(var(--spacing, .25rem) * 4);display:flex;flex-direction:column;gap:var(--ngs-content-editor-renderer-block-gap)}:host .block{min-width:0}:host ::ng-deep a[data-ngs-headless-editor-mark=link]{color:var(--ngs-color-primary);text-decoration:underline;text-underline-offset:.15em}\n/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n"], dependencies: [{ kind: "directive", type: NgComponentOutlet, selector: "[ngComponentOutlet]", inputs: ["ngComponentOutlet", "ngComponentOutletInputs", "ngComponentOutletInjector", "ngComponentOutletEnvironmentInjector", "ngComponentOutletContent", "ngComponentOutletNgModule"], exportAs: ["ngComponentOutlet"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
3854
4200
  }
3855
4201
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorRenderer, decorators: [{
3856
4202
  type: Component,
3857
- args: [{ selector: 'ngs-content-editor-renderer', exportAs: 'ngsContentEditorRenderer', providers: [provideContentEditor(), ContentEditorHtmlSerializer], imports: [
4203
+ args: [{ selector: 'ngs-content-editor-renderer', exportAs: 'ngsContentEditorRenderer', providers: [provideContentEditor(), ContentEditorHtmlSerializer, {
4204
+ provide: CONTENT_EDITOR_RENDER_CONFIG, useFactory: () => inject(forwardRef(() => ContentEditorRenderer)).resolvedConfig
4205
+ }], imports: [
3858
4206
  NgComponentOutlet,
3859
4207
  ], changeDetection: ChangeDetectionStrategy.OnPush, host: {
3860
4208
  'class': 'ngs-content-editor-renderer prose max-w-full',
3861
4209
  }, template: "@for (item of items(); track item.block.id || $index) {\n @if (item.component) {\n <div class=\"block\" [attr.data-block-id]=\"item.block.id\" [attr.data-block-type]=\"item.block.type\">\n <ng-container\n [ngComponentOutlet]=\"item.component\"\n [ngComponentOutletInputs]=\"item.inputs\"\n />\n </div>\n }\n}\n", styles: [":host{--ngs-content-editor-renderer-block-gap: calc(var(--spacing, .25rem) * 4);display:flex;flex-direction:column;gap:var(--ngs-content-editor-renderer-block-gap)}:host .block{min-width:0}:host ::ng-deep a[data-ngs-headless-editor-mark=link]{color:var(--ngs-color-primary);text-decoration:underline;text-underline-offset:.15em}\n/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n"] }]
3862
4210
  }], propDecorators: { config: [{ type: i0.Input, args: [{ isSignal: true, alias: "config", required: false }] }], content: [{ type: i0.Input, args: [{ isSignal: true, alias: "content", required: false }] }], blocks: [{ type: i0.Input, args: [{ isSignal: true, alias: "blocks", required: false }] }] } });
3863
4211
 
4212
+ /** One cancellable request per block. Retry only sends failed files again. */
4213
+ class ContentEditorUploadTask {
4214
+ writable;
4215
+ uploading = signal(false, /* @ts-ignore */
4216
+ ...(ngDevMode ? [{ debugName: "uploading" }] : /* istanbul ignore next */ []));
4217
+ progress = signal(null, /* @ts-ignore */
4218
+ ...(ngDevMode ? [{ debugName: "progress" }] : /* istanbul ignore next */ []));
4219
+ error = signal('', /* @ts-ignore */
4220
+ ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
4221
+ canRetry = signal(false, /* @ts-ignore */
4222
+ ...(ngDevMode ? [{ debugName: "canRetry" }] : /* istanbul ignore next */ []));
4223
+ controller = null;
4224
+ failed = null;
4225
+ constructor(writable) {
4226
+ this.writable = writable;
4227
+ }
4228
+ cancel() {
4229
+ this.controller?.abort();
4230
+ this.controller = null;
4231
+ this.uploading.set(false);
4232
+ this.progress.set(null);
4233
+ this.failed = null;
4234
+ this.canRetry.set(false);
4235
+ this.error.set('');
4236
+ }
4237
+ retry() { return this.failed ? this.run(this.failed) : Promise.resolve(); }
4238
+ async run(request) {
4239
+ this.cancel();
4240
+ if (!request.files.length || !this.writable())
4241
+ return;
4242
+ const controller = new AbortController();
4243
+ this.controller = controller;
4244
+ const active = () => this.controller === controller && !controller.signal.aborted && this.writable();
4245
+ this.uploading.set(true);
4246
+ const progress = request.files.map(() => null);
4247
+ const report = (index, percent) => {
4248
+ if (!active())
4249
+ return;
4250
+ progress[index] = percent;
4251
+ this.progress.set(progress.every(value => value !== null) ? progress.reduce((sum, value) => sum + (value ?? 0), 0) / progress.length : null);
4252
+ };
4253
+ const results = await Promise.allSettled(request.files.map(async (file, index) => {
4254
+ if (request.accept && !request.accept(file))
4255
+ throw new Error(`Unsupported file: ${file.name}`);
4256
+ if (request.maxFileSize !== undefined && file.size > request.maxFileSize)
4257
+ throw new Error(`File is too large: ${file.name}`);
4258
+ const dataUrl = await readContentEditorFile(file, { signal: controller.signal, onProgress: value => report(index, value * 0.2) });
4259
+ if (!active())
4260
+ throw new DOMException('Upload cancelled', 'AbortError');
4261
+ report(index, null);
4262
+ const url = await abortable(request.upload(file, dataUrl, { signal: controller.signal, onProgress: value => {
4263
+ if (Number.isFinite(value))
4264
+ report(index, 20 + Math.max(0, Math.min(100, value)) * 0.8);
4265
+ } }), controller.signal);
4266
+ if (!active())
4267
+ throw new DOMException('Upload cancelled', 'AbortError');
4268
+ if (typeof url !== 'string' || !safeContentEditorHtmlUrl(url, request.urlKind ?? 'attachment'))
4269
+ throw new Error(`Invalid upload URL: ${file.name}`);
4270
+ report(index, 100);
4271
+ return { file, url, dataUrl };
4272
+ }));
4273
+ if (this.controller !== controller || controller.signal.aborted)
4274
+ return;
4275
+ if (!this.writable()) {
4276
+ this.cancel();
4277
+ return;
4278
+ }
4279
+ const succeeded = results.flatMap(result => result.status === 'fulfilled' ? [result.value] : []);
4280
+ const failed = request.files.filter((_, index) => results[index].status === 'rejected');
4281
+ try {
4282
+ if (succeeded.length)
4283
+ request.apply(succeeded);
4284
+ }
4285
+ catch (error) {
4286
+ this.error.set(error instanceof Error ? error.message : 'Could not save uploaded files.');
4287
+ this.failed = null;
4288
+ this.canRetry.set(false);
4289
+ this.uploading.set(false);
4290
+ return;
4291
+ }
4292
+ if (failed.length) {
4293
+ const reason = results.find(result => result.status === 'rejected');
4294
+ this.error.set(`Could not upload ${failed.length} file(s): ${reason.reason instanceof Error ? reason.reason.message : 'Upload failed'}`);
4295
+ const retryable = failed.filter(file => (!request.accept || request.accept(file)) && (request.maxFileSize === undefined || file.size <= request.maxFileSize));
4296
+ this.failed = retryable.length ? { ...request, files: retryable } : null;
4297
+ this.canRetry.set(!!this.failed);
4298
+ }
4299
+ this.uploading.set(false);
4300
+ }
4301
+ }
4302
+ function abortable(work, signal) {
4303
+ return new Promise((resolve, reject) => {
4304
+ const abort = () => reject(new DOMException('Upload cancelled', 'AbortError'));
4305
+ signal.addEventListener('abort', abort, { once: true });
4306
+ work.then(value => { signal.removeEventListener('abort', abort); resolve(value); }, error => { signal.removeEventListener('abort', abort); reject(error); });
4307
+ if (signal.aborted)
4308
+ abort();
4309
+ });
4310
+ }
4311
+
4312
+ /** Shared native inputs and root history for the built-in block editors. */
4313
+ class ContentEditorBlockBase {
4314
+ store = inject(ContentBuilderStore);
4315
+ builder = inject(CONTENT_BUILDER);
4316
+ element = inject(ElementRef).nativeElement;
4317
+ id = input.required(/* @ts-ignore */
4318
+ ...(ngDevMode ? [{ debugName: "id" }] : /* istanbul ignore next */ []));
4319
+ content = input.required(/* @ts-ignore */
4320
+ ...(ngDevMode ? [{ debugName: "content" }] : /* istanbul ignore next */ []));
4321
+ settings = input.required(/* @ts-ignore */
4322
+ ...(ngDevMode ? [{ debugName: "settings" }] : /* istanbul ignore next */ []));
4323
+ index = input(0, /* @ts-ignore */
4324
+ ...(ngDevMode ? [{ debugName: "index" }] : /* istanbul ignore next */ []));
4325
+ props = input([], /* @ts-ignore */
4326
+ ...(ngDevMode ? [{ debugName: "props" }] : /* istanbul ignore next */ []));
4327
+ initialized = signal(true, /* @ts-ignore */
4328
+ ...(ngDevMode ? [{ debugName: "initialized" }] : /* istanbul ignore next */ []));
4329
+ constructor() {
4330
+ effect(() => {
4331
+ if (this.store.focusedBlockId() === this.id())
4332
+ untracked(() => this.focus());
4333
+ });
4334
+ }
4335
+ focus() { this.element.querySelector('[contenteditable="true"], input, button')?.focus(); }
4336
+ getData() { return { content: this.content(), settings: this.settings(), props: this.props() }; }
4337
+ isEmpty() {
4338
+ const block = findContentEditorBlock(this.store.editor.document().blocks, this.id());
4339
+ return !block || isContentEditorBlockEmpty(block);
4340
+ }
4341
+ save(content, settings = this.settings()) { this.store.updateBlock(this.id(), { content, settings }); }
4342
+ latestContent() {
4343
+ const block = findContentEditorBlock(this.store.editor.document().blocks, this.id());
4344
+ return block ? contentEditorBlockView(block).content : this.content();
4345
+ }
4346
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorBlockBase, deps: [], target: i0.ɵɵFactoryTarget.Directive });
4347
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.1.7", type: ContentEditorBlockBase, isStandalone: true, inputs: { id: { classPropertyName: "id", publicName: "id", isSignal: true, isRequired: true, transformFunction: null }, content: { classPropertyName: "content", publicName: "content", isSignal: true, isRequired: true, transformFunction: null }, settings: { classPropertyName: "settings", publicName: "settings", isSignal: true, isRequired: true, transformFunction: null }, index: { classPropertyName: "index", publicName: "index", isSignal: true, isRequired: false, transformFunction: null }, props: { classPropertyName: "props", publicName: "props", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0 });
4348
+ }
4349
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorBlockBase, decorators: [{
4350
+ type: Directive
4351
+ }], ctorParameters: () => [], propDecorators: { id: [{ type: i0.Input, args: [{ isSignal: true, alias: "id", required: true }] }], content: [{ type: i0.Input, args: [{ isSignal: true, alias: "content", required: true }] }], settings: [{ type: i0.Input, args: [{ isSignal: true, alias: "settings", required: true }] }], index: [{ type: i0.Input, args: [{ isSignal: true, alias: "index", required: false }] }], props: [{ type: i0.Input, args: [{ isSignal: true, alias: "props", required: false }] }] } });
4352
+
4353
+ class ContentEditorUploadBlockBase extends ContentEditorBlockBase {
4354
+ uploadTask = new ContentEditorUploadTask(() => !this.store.editor.readOnly() && !!findContentEditorBlock(this.store.editor.document().blocks, this.id()));
4355
+ uploading = this.uploadTask.uploading;
4356
+ error = this.uploadTask.error;
4357
+ constructor() {
4358
+ super();
4359
+ effect(() => {
4360
+ if (this.store.editor.readOnly() || !findContentEditorBlock(this.store.editor.document().blocks, this.id()))
4361
+ this.uploadTask.cancel();
4362
+ });
4363
+ inject(DestroyRef).onDestroy(() => this.uploadTask.cancel());
4364
+ }
4365
+ uploadFiles(type, request) {
4366
+ return this.uploadTask.run({ ...request,
4367
+ urlKind: request.urlKind ?? (type === 'video' ? 'media' : type === 'image' || type === 'gallery' ? 'image' : 'attachment'),
4368
+ upload: this.builder.getBlockDefOption(type, 'uploadFn'),
4369
+ maxFileSize: this.builder.getBlockDefOption(type, 'maxFileSize')
4370
+ });
4371
+ }
4372
+ cancelUpload() { this.uploadTask.cancel(); }
4373
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorUploadBlockBase, deps: [], target: i0.ɵɵFactoryTarget.Directive });
4374
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "22.1.7", type: ContentEditorUploadBlockBase, isStandalone: true, usesInheritance: true, ngImport: i0 });
4375
+ }
4376
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: ContentEditorUploadBlockBase, decorators: [{
4377
+ type: Directive
4378
+ }], ctorParameters: () => [] });
4379
+
3864
4380
  /**
3865
4381
  * Generated bundle index. Do not edit.
3866
4382
  */
3867
4383
 
3868
- export { contentEditorFromJson as $, ContentEditorCodeRenderer as A, BlockSelectionDirective as B, ContentBuilderStore as C, ContentEditorDividerRenderer as D, ContentEditorEmbedRenderer as E, ContentEditorGalleryRenderer as F, ContentEditorGridRenderer as G, ContentEditorHeadingRenderer as H, ContentEditorHtmlSerializer as I, ContentEditorImageRenderer as J, ContentEditorImportError as K, ContentEditorImporter as L, ContentEditorListRenderer as M, ContentEditorParagraphRenderer as N, ContentEditorQuoteRenderer as O, ContentEditorRenderer as P, ContentEditorTableRenderer as Q, ContentEditorToggleRenderer as R, ContentEditorVideoRenderer as S, TextSelectionPopupDirective as T, contentEditorAttachmentToHtml as U, contentEditorBlockToHtml as V, contentEditorCalloutToHtml as W, contentEditorCodeToHtml as X, contentEditorDividerToHtml as Y, contentEditorEmbedToHtml as Z, contentEditorFromHtml as _, CONTENT_BUILDER as a, contentEditorGalleryToHtml as a0, contentEditorGridToHtml as a1, contentEditorHeadingToHtml as a2, contentEditorImageToHtml as a3, contentEditorListToHtml as a4, contentEditorNativeBlock as a5, contentEditorParagraphToHtml as a6, contentEditorQuoteToHtml as a7, contentEditorTableToHtml as a8, contentEditorToHtml as a9, contentEditorToggleToHtml as aa, contentEditorVideoToHtml as ab, mergeContentEditorConfig as ac, provideContentEditor as ad, provideContentEditorConfig as ae, provideContentEditorRenderer as af, provideContentEditorRenderers as ag, replaceContentEditorCollection as ah, contentEditorText as b, cloneContentEditorValue as c, ContentEditorContentEditableDirective as d, CONTENT_EDITOR_BLOCK as e, contentEditorFileSize as f, contentEditorResourceUrl as g, findContentEditorBlock as h, contentEditorGridSettings as i, emptyGridCell as j, contentEditorCollection as k, contentEditorBlockView as l, contentEditorChildCollections as m, isContentEditorBlockEmpty as n, CONTENT_EDITOR_BLOCK_RENDERERS as o, CONTENT_EDITOR_CALLOUT_HTML_STYLES as p, CONTENT_EDITOR_CONFIG as q, readContentEditorFile as r, CONTENT_EDITOR_DEFAULT_HTML_CONVERTERS as s, CONTENT_EDITOR_DEFAULT_RENDERERS as t, CONTENT_EDITOR_GALLERY_HTML_STYLES as u, CONTENT_EDITOR_GRID_HTML_STYLES as v, CommandBarComponent as w, ContentBuilderComponent as x, ContentEditorAttachmentRenderer as y, ContentEditorCalloutRenderer as z };
3869
- //# sourceMappingURL=ngstarter-ui-components-content-editor-ngstarter-ui-components-content-editor-CK4ssnlk.mjs.map
4384
+ export { contentEditorBlockToHtml as $, ContentEditorAttachmentRenderer as A, BlockSelectionDirective as B, ContentBuilderStore as C, ContentEditorCalloutRenderer as D, ContentEditorCodeRenderer as E, ContentEditorDividerRenderer as F, ContentEditorDraftController as G, ContentEditorEmbedRenderer as H, ContentEditorGalleryRenderer as I, ContentEditorGridRenderer as J, ContentEditorHeadingRenderer as K, ContentEditorHtmlSerializer as L, ContentEditorImageRenderer as M, ContentEditorImportError as N, ContentEditorImporter as O, ContentEditorListRenderer as P, ContentEditorParagraphRenderer as Q, ContentEditorQuoteRenderer as R, ContentEditorRenderer as S, ContentEditorRendererBase as T, ContentEditorTableRenderer as U, ContentEditorToggleRenderer as V, ContentEditorUploadTask as W, ContentEditorVideoRenderer as X, TextSelectionPopupDirective as Y, contentEditorAttachmentToHtml as Z, contentEditorBlockScope as _, CONTENT_BUILDER as a, contentEditorCalloutToHtml as a0, contentEditorCodeToHtml as a1, contentEditorConvertBlock as a2, contentEditorCopyBlocks as a3, contentEditorDividerToHtml as a4, contentEditorEmbedToHtml as a5, contentEditorFromHtml as a6, contentEditorFromJson as a7, contentEditorGalleryToHtml as a8, contentEditorGridToHtml as a9, contentEditorHeadingToHtml as aa, contentEditorImageToHtml as ab, contentEditorListToHtml as ac, contentEditorNativeBlock as ad, contentEditorParagraphToHtml as ae, contentEditorQuoteToHtml as af, contentEditorSliceText as ag, contentEditorTableToHtml as ah, contentEditorToHtml as ai, contentEditorToggleToHtml as aj, contentEditorVideoToHtml as ak, isContentEditorBlockEmpty as al, mergeContentEditorConfig as am, provideContentEditor as an, provideContentEditorConfig as ao, provideContentEditorRenderer as ap, provideContentEditorRenderers as aq, readContentEditorFile as ar, replaceContentEditorCollection as as, contentEditorText as b, cloneContentEditorValue as c, ContentEditorContentEditableDirective as d, CONTENT_EDITOR_BLOCK as e, ContentEditorUploadBlockBase as f, ContentEditorBlockBase as g, contentEditorFileSize as h, contentEditorResourceUrl as i, contentEditorGridSettings as j, findContentEditorBlock as k, emptyGridCell as l, contentEditorCollection as m, contentEditorBlockView as n, contentEditorChildCollections as o, CONTENT_EDITOR_BLOCK_RENDERERS as p, CONTENT_EDITOR_CALLOUT_HTML_STYLES as q, CONTENT_EDITOR_CONFIG as r, CONTENT_EDITOR_CONVERTIBLE_BLOCKS as s, CONTENT_EDITOR_DEFAULT_HTML_CONVERTERS as t, CONTENT_EDITOR_DEFAULT_RENDERERS as u, CONTENT_EDITOR_GALLERY_HTML_STYLES as v, CONTENT_EDITOR_GRID_HTML_STYLES as w, CONTENT_EDITOR_RENDER_CONFIG as x, CommandBarComponent as y, ContentBuilderComponent as z };
4385
+ //# sourceMappingURL=ngstarter-ui-components-content-editor-ngstarter-ui-components-content-editor-CR-NrarE.mjs.map