diff --git a/CHANGELOG.md b/CHANGELOG.md index d3231a4..c4783e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,27 @@ versioning follows [SemVer](https://semver.org/). +## [2.3.0](https://github.com/FicSysFR/jsonforms_builder/compare/2.2.0...2.3.0) - 2026-11-20 + +### ✨ Features + +- `options.blockEditor` turns the WYSIWYG renderer into a page edited block by block, Notion + style: a gutter handle on every top-level block (`+` inserts a block below and opens the `/` + palette, the grip drags the block or opens its menu: turn into, clear formatting, duplicate, + copy text, move up/down, delete), a hint on the empty block holding the cursor, no fixed + toolbar and no border. The bubble menu and `/` palette turn on unless set explicitly, and + `dragHandle`, `placeholders` and `bordered` tune the mode. No node type is added, so stored + `json`, `html` and `markdown` values are unchanged. The handle is built on ProseMirror alone: + unlike Nuxt UI's `UEditorDragHandle`, it needs no `@tiptap/y-tiptap`, `yjs` or `y-protocols`. +- `buildWysiwygBlockMenu`, `runWysiwygBlockAction`, `createWysiwygBlockPlaceholder`, + `findWysiwygBlockAt`, `insertWysiwygBlockAfter` and `resolveWysiwygBlockEditor` are exported + from `/advanced` for custom editors. + +### 📝 Documentation + +- Guides (FR/EN): block editing section, `blockEditor` option, `nuxt-wysiwyg-blocks` playground + example. + ## [2.2.0](https://github.com/FicSysFR/jsonforms_builder/compare/2.1.0...2.2.0) - 2026-11-20 ### ⚠️ Behavior changes diff --git a/README.md b/README.md index 3f91cea..5ec186a 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,8 @@ WYSIWYG options (`options.wysiwyg: true`): | `image` | `false` to disable, or `{ upload, accept, maxSize, resize, bubble, … }` | | `extensions` / `handlers` | extra TipTap extensions / Nuxt UI handlers (host versions win) | | `features` | tables, task lists, alignment, colors, highlight, link panel, find & replace, source mode, preview — all on; `false` or `{ table: false, … }` to opt out | -| `bubbleMenu` / `slashCommands` | formatting bubble on selection / `/` palette (default `false`) | +| `bubbleMenu` / `slashCommands` | formatting bubble on selection / `/` palette (default `false`, `true` with `blockEditor`) | +| `blockEditor` | Notion-style block editing: gutter `+` / drag / block menu, per-block hints, no fixed toolbar nor border (default `false`) | | `ai` | optional AI assistant, inert unless `ai.enabled === true` | ```ts diff --git a/changelog/2.3.0.md b/changelog/2.3.0.md new file mode 100644 index 0000000..74fa264 --- /dev/null +++ b/changelog/2.3.0.md @@ -0,0 +1,26 @@ +--- +version: 2.3.0 +date: 2026-11-20 +title: Notion-style block editing for the WYSIWYG renderer +previous: 2.2.0 +prerelease: false +--- + +### ✨ Features + +- `options.blockEditor` turns the WYSIWYG renderer into a page edited block by block, Notion + style: a gutter handle on every top-level block (`+` inserts a block below and opens the `/` + palette, the grip drags the block or opens its menu: turn into, clear formatting, duplicate, + copy text, move up/down, delete), a hint on the empty block holding the cursor, no fixed + toolbar and no border. The bubble menu and `/` palette turn on unless set explicitly, and + `dragHandle`, `placeholders` and `bordered` tune the mode. No node type is added, so stored + `json`, `html` and `markdown` values are unchanged. The handle is built on ProseMirror alone: + unlike Nuxt UI's `UEditorDragHandle`, it needs no `@tiptap/y-tiptap`, `yjs` or `y-protocols`. +- `buildWysiwygBlockMenu`, `runWysiwygBlockAction`, `createWysiwygBlockPlaceholder`, + `findWysiwygBlockAt`, `insertWysiwygBlockAfter` and `resolveWysiwygBlockEditor` are exported + from `/advanced` for custom editors. + +### 📝 Documentation + +- Guides (FR/EN): block editing section, `blockEditor` option, `nuxt-wysiwyg-blocks` playground + example. diff --git a/docs/en/guide/options/string.md b/docs/en/guide/options/string.md index ff9d527..23b2663 100644 --- a/docs/en/guide/options/string.md +++ b/docs/en/guide/options/string.md @@ -317,8 +317,9 @@ Requires `allRenderers` (not just `nuxtUiRenderers`). | `toolbar` | `Array` \| `false` | built-in toolbar | Replaces the toolbar (`EditorToolbarItem[][]`) or hides it. | | `placeholder` | `String` | — | Editor placeholder. | | `features` | `false` \| `Object` | all on | Tables, task lists, alignment, colors, highlight, link, find & replace, source, preview. | -| `bubbleMenu` | `Boolean` | `false` | Formatting bubble on selection. | -| `slashCommands` | `Boolean` | `false` | `/` command palette. | +| `bubbleMenu` | `Boolean` | `false` (`true` with `blockEditor`) | Formatting bubble on selection. | +| `slashCommands` | `Boolean` | `false` (`true` with `blockEditor`) | `/` command palette. | +| `blockEditor` | `Boolean` \| `Object` | `false` | Notion-style block editing: `+` / drag / block menu handle, per-block hints, no fixed toolbar nor border. See [Block editing](/en/guide/wysiwyg-ai#block-editing). | | `ai` | `Object` | — | Optional AI assistant (`enabled`, `endpoint` or `transport`, `actions`…). | | `editor` | `Object` | — | Pass-through → `UEditor`. | @@ -372,3 +373,4 @@ image has no Markdown equivalent and is not kept. Source mode then edits the raw - [Autocomplete API](/en/playground#/?section=docs&example=nuxt-autocomplete) - [WYSIWYG](/en/playground#/?section=docs&example=nuxt-wysiwyg) - [WYSIWYG + AI](/en/playground#/?section=docs&example=nuxt-wysiwyg-ai) +- [Block WYSIWYG](/en/playground#/?section=docs&example=nuxt-wysiwyg-blocks) diff --git a/docs/en/guide/playground-examples.md b/docs/en/guide/playground-examples.md index f61a4d1..b80499f 100644 --- a/docs/en/guide/playground-examples.md +++ b/docs/en/guide/playground-examples.md @@ -30,6 +30,7 @@ Any example whose `name` starts with `nuxt-` automatically lands in **Documentat | [Autocomplete API](/en/playground#/?section=docs&example=nuxt-autocomplete) | `UInputMenu` | `api.*`, `minLength`, `suggestion` | | [WYSIWYG](/en/playground#/?section=docs&example=nuxt-wysiwyg) | `UEditor` | `wysiwyg`, `contentType` (`json` \| `html`) | | [WYSIWYG + AI](/en/playground#/?section=docs&example=nuxt-wysiwyg-ai) | `UEditor` + AI | `bubbleMenu`, `slashCommands`, `ai` (local transport) | +| [Block WYSIWYG](/en/playground#/?section=docs&example=nuxt-wysiwyg-blocks) | `UEditor` (block mode) | `blockEditor` | ### Numbers & booleans diff --git a/docs/en/guide/wysiwyg-ai.md b/docs/en/guide/wysiwyg-ai.md index d9eba25..c92c9e6 100644 --- a/docs/en/guide/wysiwyg-ai.md +++ b/docs/en/guide/wysiwyg-ai.md @@ -21,8 +21,9 @@ off by default. | `features.findReplace` | `Boolean` | `true` | Find & replace (optional case sensitivity). | | `features.sourceMode` | `Boolean` | `true` | Raw HTML or JSON editing; applied content goes through the Tiptap schema. | | `features.preview` | `Boolean` | `true` | Read-only preview. | -| `bubbleMenu` | `Boolean` | `false` | Formatting bubble on text selection. | -| `slashCommands` | `Boolean` | `false` | `/` command palette. | +| `bubbleMenu` | `Boolean` | `false` (`true` with `blockEditor`) | Formatting bubble on text selection. | +| `slashCommands` | `Boolean` | `false` (`true` with `blockEditor`) | `/` command palette. | +| `blockEditor` | `Boolean` \| `Object` | `false` | Block editing (see below). | | `ai` | `WysiwygAiOptions` | — | AI assistant (see below). | A host extension passed through `options.extensions` (e.g. its own `Table`) wins over the @@ -30,6 +31,45 @@ built-in extension of the same name. A custom `toolbar` is never altered; its it the built-in `kind`s: `textColor`, `highlight`, `table`, `tableAction`, `findReplace`, `sourceMode`, `preview`, `ai`. +## Block editing + +`blockEditor: true` turns the field into a page edited block by block, Notion style: + +- on hover, a handle shows in the left gutter of every block: `+` adds a block below (and + opens the `/` palette when it is on), the `⋮⋮` grip is **dragged** to move the block or + **clicked** to open its menu: *Turn into* (paragraph, headings, lists, quote, code), + *Clear formatting*, *Duplicate*, *Copy text*, *Move up*, *Move down*, *Delete*; +- the empty block holding the cursor shows a hint (`Heading 2` on a heading, "type '/'" + elsewhere); the host `placeholder` stays while the document is empty; +- the fixed toolbar gives way to the formatting bubble and the `/` palette; +- the page loses its border and keeps a left gutter for the handle (hidden below `sm`). + +The handle acts on top-level blocks: a list or a table moves as a whole. It relies on +ProseMirror alone and adds no dependency (no `@tiptap/y-tiptap`, unlike `UEditorDragHandle`). + +Tiptap's Markdown shortcuts stay on (`# `, `- `, `1. `, `[ ] `, `> `, ` ``` `). Every explicit +option wins: `toolbar`, `bubbleMenu`, `slashCommands`, `density`, `padding`, `minHeight` and +`blockSpacing`. Locked (read-only, disabled) or in preview, the editor shows neither handle +nor hint. + +| Option | Type | Default | Description | +|---|---|---|---| +| `blockEditor` | `Boolean` \| `Object` | `false` | Turns block editing on. | +| `blockEditor.dragHandle` | `Boolean` | `true` | Gutter handle: `+`, drag and drop, block menu. | +| `blockEditor.placeholders` | `Boolean` | `true` | Hint on the empty block holding the cursor. | +| `blockEditor.bordered` | `Boolean` | `false` | Keeps the field border around the page. | + +```json +{ + "type": "Control", + "scope": "#/properties/page", + "options": { "wysiwyg": true, "contentType": "json", "blockEditor": true } +} +``` + +No new node type is added: the content stays the same in `json`, `html` or `markdown` and +reads back with or without `blockEditor`. + ## AI assistant ```ts diff --git a/docs/guide/options/string.md b/docs/guide/options/string.md index 03768cc..e2bf8b5 100644 --- a/docs/guide/options/string.md +++ b/docs/guide/options/string.md @@ -318,8 +318,9 @@ Nécessite `allRenderers` (pas seulement `nuxtUiRenderers`). | `toolbar` | `Array` \| `false` | barre intégrée | Remplace la barre d’outils (`EditorToolbarItem[][]`) ou la masque. | | `placeholder` | `String` | — | Placeholder de l’éditeur. | | `features` | `false` \| `Object` | tout activé | Tableaux, listes de tâches, alignement, couleurs, surlignage, lien, rechercher/remplacer, source, aperçu. | -| `bubbleMenu` | `Boolean` | `false` | Bulle de mise en forme sur sélection. | -| `slashCommands` | `Boolean` | `false` | Palette de commandes `/`. | +| `bubbleMenu` | `Boolean` | `false` (`true` avec `blockEditor`) | Bulle de mise en forme sur sélection. | +| `slashCommands` | `Boolean` | `false` (`true` avec `blockEditor`) | Palette de commandes `/`. | +| `blockEditor` | `Boolean` \| `Object` | `false` | Édition par blocs façon Notion : poignée `+` / glisser / menu du bloc, indices par bloc, sans barre fixe ni bordure. Voir [Édition par blocs](/guide/wysiwyg-ai#edition-par-blocs). | | `ai` | `Object` | — | Assistant IA optionnel (`enabled`, `endpoint` ou `transport`, `actions`…). | | `editor` | `Object` | — | Pass-through → `UEditor`. | @@ -373,4 +374,5 @@ d'une image redimensionnée n'a pas d'équivalent Markdown et n'est pas conserv - [File Upload](/playground#/?section=docs&example=nuxt-file-upload) - [Autocomplete API](/playground#/?section=docs&example=nuxt-autocomplete) - [WYSIWYG](/playground#/?section=docs&example=nuxt-wysiwyg) +- [WYSIWYG par blocs](/playground#/?section=docs&example=nuxt-wysiwyg-blocks) - [WYSIWYG + IA](/playground#/?section=docs&example=nuxt-wysiwyg-ai) diff --git a/docs/guide/playground-examples.md b/docs/guide/playground-examples.md index bab730a..1854d55 100644 --- a/docs/guide/playground-examples.md +++ b/docs/guide/playground-examples.md @@ -30,6 +30,7 @@ Tout exemple dont le `name` commence par `nuxt-` atterrit automatiquement dans * | [Autocomplete API](/playground#/?section=docs&example=nuxt-autocomplete) | `UInputMenu` | `api.*`, `minLength`, `suggestion` | | [WYSIWYG](/playground#/?section=docs&example=nuxt-wysiwyg) | `UEditor` | `wysiwyg`, `contentType` (`json` \| `html`) | | [WYSIWYG + IA](/playground#/?section=docs&example=nuxt-wysiwyg-ai) | `UEditor` + IA | `bubbleMenu`, `slashCommands`, `ai` (transport local) | +| [WYSIWYG par blocs](/playground#/?section=docs&example=nuxt-wysiwyg-blocks) | `UEditor` (mode bloc) | `blockEditor` | ### Nombres & booléens diff --git a/docs/guide/wysiwyg-ai.md b/docs/guide/wysiwyg-ai.md index cba8205..d0c2a79 100644 --- a/docs/guide/wysiwyg-ai.md +++ b/docs/guide/wysiwyg-ai.md @@ -21,8 +21,9 @@ sont désactivés par défaut. | `features.findReplace` | `Boolean` | `true` | Rechercher / remplacer (sensible à la casse en option). | | `features.sourceMode` | `Boolean` | `true` | Édition brute du HTML ou du JSON ; le contenu appliqué passe par le schéma Tiptap. | | `features.preview` | `Boolean` | `true` | Aperçu en lecture seule. | -| `bubbleMenu` | `Boolean` | `false` | Bulle de mise en forme sur sélection de texte. | -| `slashCommands` | `Boolean` | `false` | Palette de commandes `/`. | +| `bubbleMenu` | `Boolean` | `false` (`true` avec `blockEditor`) | Bulle de mise en forme sur sélection de texte. | +| `slashCommands` | `Boolean` | `false` (`true` avec `blockEditor`) | Palette de commandes `/`. | +| `blockEditor` | `Boolean` \| `Object` | `false` | Édition par blocs (voir ci-dessous). | | `ai` | `WysiwygAiOptions` | — | Assistant IA (voir ci-dessous). | Une extension fournie par l'hôte via `options.extensions` (par exemple sa propre `Table`) @@ -30,6 +31,47 @@ prend le pas sur l'extension intégrée du même nom. Une `toolbar` personnalis modifiée ; ses éléments peuvent utiliser les `kind` intégrés : `textColor`, `highlight`, `table`, `tableAction`, `findReplace`, `sourceMode`, `preview`, `ai`. +## Édition par blocs + +`blockEditor: true` transforme le champ en page éditée bloc par bloc, à la manière de Notion : + +- au survol, une poignée apparaît dans la marge gauche de chaque bloc : `+` ajoute un bloc en + dessous (et ouvre la palette `/` si elle est active), la poignée `⋮⋮` se **glisse** pour + déplacer le bloc ou se **clique** pour ouvrir son menu : *Transformer en* (paragraphe, + titres, listes, citation, code), *Effacer la mise en forme*, *Dupliquer*, *Copier le texte*, + *Monter*, *Descendre*, *Supprimer* ; +- le bloc vide qui porte le curseur affiche un indice (`Titre 2` sur un titre, « tapez « / » » + ailleurs) ; le `placeholder` de l'hôte reste affiché tant que le document est vide ; +- la barre d'outils fixe disparaît au profit de la bulle de mise en forme et de la palette `/` ; +- la page n'a plus de bordure et garde une marge gauche pour la poignée (masquée sous `sm`). + +La poignée agit sur les blocs de premier niveau : une liste ou un tableau se déplace en entier. +Elle ne repose que sur ProseMirror et n'ajoute aucune dépendance (pas de `@tiptap/y-tiptap`, +contrairement à `UEditorDragHandle`). + +Les raccourcis Markdown de Tiptap restent actifs (`# `, `- `, `1. `, `[ ] `, `> `, ` ``` `). +Chaque option explicite l'emporte : `toolbar`, `bubbleMenu`, `slashCommands`, `density`, +`padding`, `minHeight` et `blockSpacing`. Verrouillé (lecture seule, désactivé) ou en aperçu, +l'éditeur n'affiche ni poignée ni indice. + +| Option | Type | Défaut | Description | +|---|---|---|---| +| `blockEditor` | `Boolean` \| `Object` | `false` | Active l'édition par blocs. | +| `blockEditor.dragHandle` | `Boolean` | `true` | Poignée de marge : `+`, glisser-déposer, menu du bloc. | +| `blockEditor.placeholders` | `Boolean` | `true` | Indice sur le bloc vide qui porte le curseur. | +| `blockEditor.bordered` | `Boolean` | `false` | Garde la bordure du champ autour de la page. | + +```json +{ + "type": "Control", + "scope": "#/properties/page", + "options": { "wysiwyg": true, "contentType": "json", "blockEditor": true } +} +``` + +Aucun nouveau type de nœud n'est ajouté : le contenu reste identique en `json`, `html` ou +`markdown` et se relit avec ou sans `blockEditor`. + ## Assistant IA ```ts diff --git a/playground/docs-api/props.ts b/playground/docs-api/props.ts index 208db32..96fed63 100644 --- a/playground/docs-api/props.ts +++ b/playground/docs-api/props.ts @@ -608,12 +608,18 @@ const WYSIWYG: ApiPropGroup = { { name: 'bubbleMenu', type: 'Boolean', - description: 'Bulle de mise en forme sur sélection (défaut false).', + description: 'Bulle de mise en forme sur sélection (défaut false, true avec blockEditor).', }, { name: 'slashCommands', type: 'Boolean', - description: 'Palette de commandes / (défaut false).', + description: 'Palette de commandes / (défaut false, true avec blockEditor).', + }, + { + name: 'blockEditor', + type: 'Boolean | Object', + description: + 'Édition par blocs façon page : poignée + / glisser / menu du bloc, placeholders par bloc, sans barre fixe ni bordure (dragHandle, placeholders, bordered).', }, { name: 'ai', @@ -731,6 +737,7 @@ export const API_BY_EXAMPLE: Record = { 'nuxt-array': [COMMON_OPTIONS, ARRAY], 'nuxt-wysiwyg': [COMMON_OPTIONS, WYSIWYG], 'nuxt-wysiwyg-ai': [COMMON_OPTIONS, WYSIWYG], + 'nuxt-wysiwyg-blocks': [COMMON_OPTIONS, WYSIWYG], 'nuxt-layouts': [COMMON_OPTIONS, LAYOUTS], 'nuxt-pin-input': [COMMON_OPTIONS, PIN], 'nuxt-color': [COMMON_OPTIONS, COLOR], diff --git a/playground/examples/items/nuxt-wysiwyg-blocks.ts b/playground/examples/items/nuxt-wysiwyg-blocks.ts new file mode 100644 index 0000000..92968ea --- /dev/null +++ b/playground/examples/items/nuxt-wysiwyg-blocks.ts @@ -0,0 +1,97 @@ +import { registerExamples } from '../register' + +export const data = { + page: { + type: 'doc', + content: [ + { + type: 'heading', + attrs: { level: 1 }, + content: [{ type: 'text', text: 'Compte-rendu de chantier' }], + }, + { + type: 'paragraph', + content: [ + { type: 'text', text: 'Survolez un bloc : ' }, + { type: 'text', marks: [{ type: 'bold' }], text: '+' }, + { type: 'text', text: ' ajoute un bloc en dessous, la poignée ' }, + { type: 'text', marks: [{ type: 'bold' }], text: '⋮⋮' }, + { type: 'text', text: ' le déplace ou ouvre son menu. Tapez « / » sur une ligne vide.' }, + ], + }, + { + type: 'heading', + attrs: { level: 2 }, + content: [{ type: 'text', text: 'Actions' }], + }, + { + type: 'taskList', + content: [ + { + type: 'taskItem', + attrs: { checked: true }, + content: [ + { type: 'paragraph', content: [{ type: 'text', text: 'Vérifier les accès' }] }, + ], + }, + { + type: 'taskItem', + attrs: { checked: false }, + content: [ + { type: 'paragraph', content: [{ type: 'text', text: 'Commander le matériel' }] }, + ], + }, + ], + }, + { + type: 'blockquote', + content: [ + { + type: 'paragraph', + content: [ + { type: 'text', text: 'Sélectionnez du texte pour la bulle de mise en forme.' }, + ], + }, + ], + }, + { type: 'paragraph' }, + ], + }, +} + +export const schema = { + type: 'object', + properties: { + page: { + type: 'object', + title: 'Page', + description: 'options.blockEditor: true — édition par blocs, sans barre d’outils fixe.', + }, + }, +} + +export const uischema = { + type: 'VerticalLayout', + elements: [ + { + type: 'Control', + scope: '#/properties/page', + options: { + wysiwyg: true, + contentType: 'json', + blockEditor: true, + placeholder: 'Commencez à écrire…', + }, + }, + ], +} + +registerExamples([ + { + name: 'nuxt-wysiwyg-blocks', + label: 'Nuxt UI — WYSIWYG par blocs', + data, + schema, + uischema, + }, +]) diff --git a/src/advanced/index.ts b/src/advanced/index.ts index 8031dfb..49cb930 100644 --- a/src/advanced/index.ts +++ b/src/advanced/index.ts @@ -45,6 +45,20 @@ export { buildWysiwygToolbar, } from './wysiwyg/toolbar' export { WYSIWYG_SLASH_FILTER_FIELDS, buildWysiwygSlashItems } from './wysiwyg/slash/commands' +export { + DISABLED_WYSIWYG_BLOCK_EDITOR, + WYSIWYG_BLOCK_LAYOUT, + buildWysiwygBlockMenu, + createWysiwygBlockPlaceholder, + findWysiwygBlockAt, + insertWysiwygBlockAfter, + resolveWysiwygBlockEditor, + runWysiwygBlockAction, + type ResolvedWysiwygBlockEditor, + type WysiwygBlockAction, + type WysiwygBlockType, + type WysiwygBlockEditorOptions, +} from './wysiwyg/block' export { WYSIWYG_TABLE_ACTIONS, createWysiwygHandlers, diff --git a/src/advanced/wysiwyg.vue b/src/advanced/wysiwyg.vue index 0c4d413..0e9de91 100644 --- a/src/advanced/wysiwyg.vue +++ b/src/advanced/wysiwyg.vue @@ -6,18 +6,19 @@ :show-description="showDescription()" :hide-required-asterisk="!!appliedOptions.hideRequiredAsterisk" ) - .relative(ref="rootEl") + //- Block mode: contain the gutter handle's z-index so portalled menus stay above it. + .relative(ref="rootEl" :class="{ isolate: resolved.blockEditor.dragHandle }") u-editor( ref="editorRef" v-bind="uiProps('editor')" :model-value="control.data" :content-type="resolved.contentType" :editable="editable" - :placeholder="resolved.placeholder" + :placeholder="editorPlaceholder" :image="false" :extensions="editorExtensions" :handlers="editorHandlers" - :class="[styles.control.input, 'rounded-md border border-default']" + :class="[styles.control.input, resolved.blockEditor.bordered ? 'rounded-md border border-default' : 'rounded-md']" :ui="editorUi" @update:model-value="onChange" ) @@ -55,6 +56,12 @@ @close="closePanel(editor)" ) template(v-if="editable && ui.mode === 'edit'") + wysiwyg-block-handle( + v-if="resolved.blockEditor.dragHandle" + :editor="editor" + :features="resolved.features" + :slash-commands="resolved.slashCommands" + ) u-editor-toolbar( v-if="resolved.imageBubble" :editor="editor" @@ -121,7 +128,7 @@ import { } from 'vue' import { rendererProps, useJsonFormsControl, type RendererProps } from '@jsonforms/vue' import type { Editor } from '@tiptap/vue-3' -import type { EditorState } from '@tiptap/pm/state' +import { NodeSelection, type EditorState } from '@tiptap/pm/state' import { CellSelection } from '@tiptap/pm/tables' import UButton from '@nuxt/ui/components/Button.vue' import UEditor from '@nuxt/ui/components/Editor.vue' @@ -143,11 +150,13 @@ import { refreshWysiwygImageResizeStyles } from './wysiwygImageResizeStyles' import { selectWysiwygAiSlashActions } from './wysiwyg/ai/actions' import { useWysiwygAi, type WysiwygAiController } from './wysiwyg/ai/useWysiwygAi' import WysiwygAiResult from './wysiwyg/ai/WysiwygAiResult.vue' +import { createWysiwygBlockPlaceholder } from './wysiwyg/block' import { buildWysiwygFeatureExtensions } from './wysiwyg/extensions' import { createWysiwygHandlers, type WysiwygUiState } from './wysiwyg/handlers' import { WYSIWYG_SLASH_FILTER_FIELDS, buildWysiwygSlashItems } from './wysiwyg/slash/commands' import { refreshWysiwygEditorStyles } from './wysiwyg/styles' import { buildWysiwygTableBubble, buildWysiwygTextBubble } from './wysiwyg/toolbar' +import WysiwygBlockHandle from './wysiwyg/WysiwygBlockHandle.vue' import WysiwygFindReplace from './wysiwyg/WysiwygFindReplace.vue' import WysiwygLinkPanel from './wysiwyg/WysiwygLinkPanel.vue' import WysiwygSourceEditor from './wysiwyg/WysiwygSourceEditor.vue' @@ -168,6 +177,7 @@ const controlRenderer: Component = defineComponent({ UEditorToolbar, UIcon, WysiwygAiResult, + WysiwygBlockHandle, WysiwygFindReplace, WysiwygLinkPanel, WysiwygSourceEditor, @@ -276,6 +286,20 @@ const controlRenderer: Component = defineComponent({ ] }) + // Block mode: hint on the empty block holding the cursor (`UEditor` reads it at creation). + const editorPlaceholder = computed(() => { + const cfg = resolved.value + if (!cfg.blockEditor.placeholders) return cfg.placeholder + return { + placeholder: createWysiwygBlockPlaceholder( + { hostPlaceholder: cfg.placeholder, slashCommands: cfg.slashCommands }, + t, + ), + mode: 'everyLine', + showOnlyWhenEditable: true, + } + }) + const editorHandlers = computed(() => { const cfg = resolved.value const base = cfg.imagesEnabled ? { imageUpload: imageUploadHandler } : {} @@ -354,7 +378,9 @@ const controlRenderer: Component = defineComponent({ const shouldShowTextBubble = ({ editor, state }: { editor: Editor; state: EditorState }) => { const { selection } = state if (ai.value?.isOpen.value) return false + // A node selection is a selected block (block menu, image…), not text to format. if (selection.empty || selection instanceof CellSelection) return false + if (selection instanceof NodeSelection) return false if (!state.doc.textBetween(selection.from, selection.to).trim()) return false return !editor.isActive('image') && !editor.isActive('codeBlock') } @@ -473,6 +499,7 @@ const controlRenderer: Component = defineComponent({ editorUi, editorExtensions, editorHandlers, + editorPlaceholder, imageBubbleItems, shouldShowImageBubble, textBubbleItems, diff --git a/src/advanced/wysiwyg/WysiwygBlockHandle.vue b/src/advanced/wysiwyg/WysiwygBlockHandle.vue new file mode 100644 index 0000000..fd58a4f --- /dev/null +++ b/src/advanced/wysiwyg/WysiwygBlockHandle.vue @@ -0,0 +1,280 @@ + + + diff --git a/src/advanced/wysiwyg/block.ts b/src/advanced/wysiwyg/block.ts new file mode 100644 index 0000000..6210033 --- /dev/null +++ b/src/advanced/wysiwyg/block.ts @@ -0,0 +1,349 @@ +import type { Editor } from '@tiptap/core' +import type { EditorView } from '@tiptap/pm/view' +import type { Node as ProseMirrorNode } from '@tiptap/pm/model' +import { NodeSelection, TextSelection, type Transaction } from '@tiptap/pm/state' +import { createUiText, type UiText } from '../../i18n/ui' +import type { ResolvedWysiwygFeatures } from './features' + +/** + * Block editing: the document reads as a page, each top-level block gets a gutter handle + * (`+` to insert below, grip to drag or open the block menu) and empty blocks hint at `/`. + */ +export type WysiwygBlockEditorOptions = { + /** Gutter handle: `+` button, drag and drop, block menu. Default: `true`. */ + dragHandle?: boolean + /** Placeholder on the empty block holding the cursor (`Titre 1`, `/` hint). Default: `true`. */ + placeholders?: boolean + /** Keep the field border around the page. Default: `false`. */ + bordered?: boolean +} + +export type ResolvedWysiwygBlockEditor = { + enabled: boolean + dragHandle: boolean + placeholders: boolean + bordered: boolean +} + +export const DISABLED_WYSIWYG_BLOCK_EDITOR: Readonly = Object.freeze({ + enabled: false, + dragHandle: false, + placeholders: false, + bordered: true, +}) + +/** `true` enables every default; an object overrides them; anything else disables the mode. */ +export const resolveWysiwygBlockEditor = (raw: unknown): ResolvedWysiwygBlockEditor => { + if (raw !== true && !(raw && typeof raw === 'object' && !Array.isArray(raw))) { + return { ...DISABLED_WYSIWYG_BLOCK_EDITOR } + } + const options = (raw === true ? {} : raw) as Record + const flag = (key: string, fallback: boolean) => + typeof options[key] === 'boolean' ? (options[key] as boolean) : fallback + return { + enabled: true, + dragHandle: flag('dragHandle', true), + placeholders: flag('placeholders', true), + bordered: flag('bordered', false), + } +} + +/** Layout defaults of the block mode; explicit `density`, `padding`… still win. */ +export const WYSIWYG_BLOCK_LAYOUT = Object.freeze({ + minHeight: 'min-h-52', + // The gutter handle sits left of the block and is hidden below `sm`. + padding: 'py-4 pe-4 ps-4 sm:ps-16', + blockSpacing: '*:!my-1.5', +}) + +type PlaceholderContext = { editor: Editor; node: ProseMirrorNode } + +/** + * Placeholder of the empty block holding the cursor: the heading level on a heading, the host + * placeholder on an empty document, the `/` hint elsewhere (when slash commands are on). + */ +export const createWysiwygBlockPlaceholder = + ( + { hostPlaceholder, slashCommands }: { hostPlaceholder?: string; slashCommands: boolean }, + t: UiText = createUiText(), + ) => + ({ editor, node }: PlaceholderContext): string => { + if (node.type.name === 'heading') { + return t('jsonformsBuilder.wysiwyg.heading', { level: node.attrs.level ?? 1 }) + } + if (node.type.name !== 'paragraph') return '' + if (hostPlaceholder && editor.isEmpty) return hostPlaceholder + return slashCommands + ? t('jsonformsBuilder.wysiwyg.block.placeholder') + : t('jsonformsBuilder.wysiwyg.block.placeholderNoSlash') + } + +type Item = Record + +/** Block conversions offered by "turn into". */ +export type WysiwygBlockType = + | { type: 'paragraph' } + | { type: 'heading'; level: 1 | 2 | 3 } + | { type: 'bulletList' | 'orderedList' | 'taskList' | 'blockquote' | 'codeBlock' } + +export type WysiwygBlockAction = + | { action: 'turnInto'; to: WysiwygBlockType } + | { action: 'clearFormatting' | 'duplicate' | 'moveUp' | 'moveDown' | 'delete' } + +/** Top-level block at `pos`, or `null` when `pos` does not start one. */ +const topLevelBlockAt = (editor: Editor, pos: number) => { + const { doc } = editor.state + if (!Number.isInteger(pos) || pos < 0 || pos >= doc.content.size) return null + if (doc.resolve(pos).depth !== 0) return null + const node = doc.nodeAt(pos) + if (!node) return null + let index = 0 + doc.forEach((_child, offset, childIndex) => { + if (offset === pos) index = childIndex + }) + return { node, index, count: doc.childCount } +} + +/** Selects the inline content of the block, so block commands apply to all of it. */ +const selectBlockContent = + (pos: number, size: number) => + ({ tr }: { tr: Transaction }) => { + const $from = tr.doc.resolve(pos + 1) + const $to = tr.doc.resolve(pos + size - 1) + tr.setSelection(TextSelection.between($from, $to)) + return true + } + +/** + * Runs a block menu action on the top-level block at `pos`, with plain Tiptap commands (no + * Nuxt UI handler). Returns `false` when the action cannot apply (no block, first block moved + * up, missing node type…). + */ +export const runWysiwygBlockAction = ( + editor: Editor, + pos: number, + command: WysiwygBlockAction, +): boolean => { + const block = topLevelBlockAt(editor, pos) + if (!block) return false + const { node, index, count } = block + const end = pos + node.nodeSize + + switch (command.action) { + case 'duplicate': + return editor.chain().focus().insertContentAt(end, node.toJSON()).run() + case 'delete': + return editor.chain().focus().deleteRange({ from: pos, to: end }).run() + case 'moveUp': + case 'moveDown': { + const up = command.action === 'moveUp' + if (up ? index === 0 : index === count - 1) return false + const neighbour = editor.state.doc.child(up ? index - 1 : index + 1) + const target = up ? pos - neighbour.nodeSize : pos + neighbour.nodeSize + return editor + .chain() + .focus() + .command(({ tr }) => { + tr.delete(pos, end).insert(target, node) + tr.setSelection(NodeSelection.create(tr.doc, target)) + return true + }) + .run() + } + case 'clearFormatting': + return editor + .chain() + .focus() + .command(selectBlockContent(pos, node.nodeSize)) + .clearNodes() + .unsetAllMarks() + .run() + case 'turnInto': { + const { to } = command + if (!editor.schema.nodes[to.type]) return false + // Back to plain paragraphs first (lifts lists and quotes), then convert. + const chain = editor + .chain() + .focus() + .command(selectBlockContent(pos, node.nodeSize)) + .clearNodes() + switch (to.type) { + case 'paragraph': + // `clearNodes` already leaves paragraphs; `setParagraph` would fail on them. + return chain.run() + case 'heading': + return chain.setHeading({ level: to.level }).run() + case 'codeBlock': + return chain.setCodeBlock().run() + case 'blockquote': + return chain.setBlockquote().run() + case 'bulletList': + return chain.toggleBulletList().run() + case 'orderedList': + return chain.toggleOrderedList().run() + case 'taskList': + return chain.toggleTaskList().run() + } + } + } + return false +} + +type BlockMenuOptions = { + editor: Editor + features: ResolvedWysiwygFeatures + /** Document position of the top-level block the menu acts on. */ + pos: number + /** Copies the block text; omitted when the clipboard is unavailable. */ + onCopy?: () => void +} + +/** + * Block menu items for Nuxt UI `UDropdownMenu`: turn into, clear formatting, duplicate, copy, + * move and delete, each running `runWysiwygBlockAction` on the block at `pos`. + */ +export const buildWysiwygBlockMenu = ( + { editor, features, pos, onCopy }: BlockMenuOptions, + t: UiText = createUiText(), +): Item[][] => { + const block = topLevelBlockAt(editor, pos) + const run = (command: WysiwygBlockAction) => () => { + runWysiwygBlockAction(editor, pos, command) + } + const turnInto = (to: WysiwygBlockType, label: string, icon: string): Item => ({ + label, + icon, + disabled: !editor.schema.nodes[to.type], + onSelect: run({ action: 'turnInto', to }), + }) + + const conversions: Item[] = [ + { type: 'label', label: t('jsonformsBuilder.wysiwyg.block.turnInto') }, + turnInto({ type: 'paragraph' }, t('jsonformsBuilder.wysiwyg.paragraph'), 'i-lucide-pilcrow'), + // Full icon names: the published icon lists are checked against the names written here. + ...(['i-lucide-heading-1', 'i-lucide-heading-2', 'i-lucide-heading-3'] as const).map( + (icon, index) => + turnInto( + { type: 'heading', level: (index + 1) as 1 | 2 | 3 }, + t('jsonformsBuilder.wysiwyg.heading', { level: index + 1 }), + icon, + ), + ), + turnInto({ type: 'bulletList' }, t('jsonformsBuilder.wysiwyg.bulletList'), 'i-lucide-list'), + turnInto( + { type: 'orderedList' }, + t('jsonformsBuilder.wysiwyg.orderedList'), + 'i-lucide-list-ordered', + ), + ...(features.taskList + ? [ + turnInto( + { type: 'taskList' }, + t('jsonformsBuilder.wysiwyg.taskList'), + 'i-lucide-list-checks', + ), + ] + : []), + turnInto({ type: 'blockquote' }, t('jsonformsBuilder.wysiwyg.blockquote'), 'i-lucide-quote'), + turnInto( + { type: 'codeBlock' }, + t('jsonformsBuilder.wysiwyg.codeBlock'), + 'i-lucide-square-code', + ), + ] + + return [ + [ + { + label: t('jsonformsBuilder.wysiwyg.block.turnInto'), + icon: 'i-lucide-repeat', + children: conversions, + }, + { + label: t('jsonformsBuilder.wysiwyg.block.clearFormatting'), + icon: 'i-lucide-rotate-ccw', + onSelect: run({ action: 'clearFormatting' }), + }, + ], + [ + { + label: t('jsonformsBuilder.wysiwyg.block.duplicate'), + icon: 'i-lucide-copy', + onSelect: run({ action: 'duplicate' }), + }, + ...(onCopy + ? [ + { + label: t('jsonformsBuilder.wysiwyg.block.copy'), + icon: 'i-lucide-clipboard', + onSelect: onCopy, + }, + ] + : []), + ], + [ + { + label: t('jsonformsBuilder.wysiwyg.block.moveUp'), + icon: 'i-lucide-arrow-up', + disabled: !block || block.index === 0, + onSelect: run({ action: 'moveUp' }), + }, + { + label: t('jsonformsBuilder.wysiwyg.block.moveDown'), + icon: 'i-lucide-arrow-down', + disabled: !block || block.index === block.count - 1, + onSelect: run({ action: 'moveDown' }), + }, + ], + [ + { + label: t('jsonformsBuilder.wysiwyg.block.delete'), + icon: 'i-lucide-trash-2', + color: 'error', + onSelect: run({ action: 'delete' }), + }, + ], + ] +} + +/** + * Inserts an empty paragraph after the block at `pos` and puts the cursor in it; with + * `slash`, the paragraph starts with `/` so the command palette opens (Notion's `+`). + */ +export const insertWysiwygBlockAfter = (editor: Editor, pos: number, slash: boolean): boolean => { + const { doc } = editor.state + if (pos < 0 || pos >= doc.content.size) return false + const node = doc.nodeAt(pos) + if (!node || doc.resolve(pos).depth !== 0) return false + const at = pos + node.nodeSize + return editor + .chain() + .focus() + .insertContentAt( + at, + slash ? { type: 'paragraph', content: [{ type: 'text', text: '/' }] } : { type: 'paragraph' }, + ) + .setTextSelection(at + (slash ? 2 : 1)) + .run() +} + +/** + * Start of the top-level block nearest to `clientY` (the block under the pointer, or the + * closest one when the pointer sits in the gap between two blocks or in the gutter). + */ +export const findWysiwygBlockAt = (view: EditorView, clientY: number): number | null => { + let best: number | null = null + let bestDistance = Number.POSITIVE_INFINITY + view.state.doc.forEach((_node, offset) => { + const dom = view.nodeDOM(offset) + if (dom?.nodeType !== 1) return + const rect = (dom as HTMLElement).getBoundingClientRect() + const distance = + clientY < rect.top ? rect.top - clientY : clientY > rect.bottom ? clientY - rect.bottom : 0 + if (distance < bestDistance) { + best = offset + bestDistance = distance + } + }) + return best +} diff --git a/src/advanced/wysiwygOptions.ts b/src/advanced/wysiwygOptions.ts index 5fbe524..722d154 100644 --- a/src/advanced/wysiwygOptions.ts +++ b/src/advanced/wysiwygOptions.ts @@ -6,6 +6,13 @@ import { type ResolvedWysiwygAiOptions, } from './wysiwyg/ai/options' import type { WysiwygAiOptions } from './wysiwyg/ai/types' +import { + DISABLED_WYSIWYG_BLOCK_EDITOR, + WYSIWYG_BLOCK_LAYOUT, + resolveWysiwygBlockEditor, + type ResolvedWysiwygBlockEditor, + type WysiwygBlockEditorOptions, +} from './wysiwyg/block' import { resolveWysiwygFeatures, type ResolvedWysiwygFeatures, @@ -103,6 +110,12 @@ export type WysiwygOptions = { slashCommands?: boolean /** AI writing assistant, inert unless `ai.enabled === true`. */ ai?: WysiwygAiOptions + /** + * Block editing, page-like (Notion style): gutter handle to insert, drag and transform + * blocks, per-block placeholders, borderless page. Turns the fixed toolbar off and the + * bubble menu and `/` palette on, unless those options are set explicitly. Default: `false`. + */ + blockEditor?: boolean | WysiwygBlockEditorOptions } export type ResolvedWysiwygOptions = { @@ -132,6 +145,7 @@ export type ResolvedWysiwygOptions = { bubbleMenu: boolean slashCommands: boolean ai: ResolvedWysiwygAiOptions + blockEditor: ResolvedWysiwygBlockEditor } const DENSITY_PRESETS: Record< @@ -164,8 +178,16 @@ export const resolveWysiwygOptions = ( t: UiText = createUiText(), ): ResolvedWysiwygOptions => { const opts = (raw ?? {}) as WysiwygOptions + const blockEditor = + opts.blockEditor === undefined + ? { ...DISABLED_WYSIWYG_BLOCK_EDITOR } + : resolveWysiwygBlockEditor(opts.blockEditor) const density = opts.density ?? 'compact' - const preset = DENSITY_PRESETS[density] ?? DENSITY_PRESETS.compact + // The block mode has its own page layout, unless the host picks a density. + const preset = + blockEditor.enabled && opts.density === undefined + ? WYSIWYG_BLOCK_LAYOUT + : (DENSITY_PRESETS[density] ?? DENSITY_PRESETS.compact) const explicitContent = opts.contentType const contentType: WysiwygContentType = @@ -211,7 +233,7 @@ export const resolveWysiwygOptions = ( const ai = opts.ai === undefined ? DISABLED_WYSIWYG_AI : resolveWysiwygAiOptions(opts.ai, t) const toolbar = - opts.toolbar === false + opts.toolbar === false || (blockEditor.enabled && opts.toolbar === undefined) ? false : Array.isArray(opts.toolbar) ? opts.toolbar @@ -249,8 +271,10 @@ export const resolveWysiwygOptions = ( extensions: Array.isArray(opts.extensions) ? opts.extensions : [], handlers: opts.handlers, features, - bubbleMenu: opts.bubbleMenu === true, - slashCommands: opts.slashCommands === true, + bubbleMenu: typeof opts.bubbleMenu === 'boolean' ? opts.bubbleMenu : blockEditor.enabled, + slashCommands: + typeof opts.slashCommands === 'boolean' ? opts.slashCommands : blockEditor.enabled, ai, + blockEditor, } } diff --git a/src/i18n/ui/advanced.ts b/src/i18n/ui/advanced.ts index 554ad5f..c56247e 100644 --- a/src/i18n/ui/advanced.ts +++ b/src/i18n/ui/advanced.ts @@ -60,6 +60,17 @@ export const advancedUiMessages = { 'jsonformsBuilder.wysiwyg.slash.lists': 'Listes', 'jsonformsBuilder.wysiwyg.slash.insert': 'Insérer', 'jsonformsBuilder.wysiwyg.slash.table': 'Tableau', + 'jsonformsBuilder.wysiwyg.block.placeholder': 'Écrivez, ou tapez « / » pour les commandes…', + 'jsonformsBuilder.wysiwyg.block.placeholderNoSlash': 'Écrivez…', + 'jsonformsBuilder.wysiwyg.block.insert': 'Ajouter un bloc en dessous', + 'jsonformsBuilder.wysiwyg.block.menu': 'Glisser pour déplacer, cliquer pour le menu du bloc', + 'jsonformsBuilder.wysiwyg.block.turnInto': 'Transformer en', + 'jsonformsBuilder.wysiwyg.block.clearFormatting': 'Effacer la mise en forme', + 'jsonformsBuilder.wysiwyg.block.duplicate': 'Dupliquer', + 'jsonformsBuilder.wysiwyg.block.copy': 'Copier le texte', + 'jsonformsBuilder.wysiwyg.block.moveUp': 'Monter', + 'jsonformsBuilder.wysiwyg.block.moveDown': 'Descendre', + 'jsonformsBuilder.wysiwyg.block.delete': 'Supprimer', 'jsonformsBuilder.wysiwyg.imageBubble.replace': 'Remplacer', 'jsonformsBuilder.wysiwyg.imageBubble.remove': 'Supprimer', 'jsonformsBuilder.wysiwyg.imageUpload.label': 'Ajouter une image', @@ -171,6 +182,17 @@ export const advancedUiMessages = { 'jsonformsBuilder.wysiwyg.slash.lists': 'Lists', 'jsonformsBuilder.wysiwyg.slash.insert': 'Insert', 'jsonformsBuilder.wysiwyg.slash.table': 'Table', + 'jsonformsBuilder.wysiwyg.block.placeholder': "Write, or type '/' for commands…", + 'jsonformsBuilder.wysiwyg.block.placeholderNoSlash': 'Write…', + 'jsonformsBuilder.wysiwyg.block.insert': 'Add a block below', + 'jsonformsBuilder.wysiwyg.block.menu': 'Drag to move, click for the block menu', + 'jsonformsBuilder.wysiwyg.block.turnInto': 'Turn into', + 'jsonformsBuilder.wysiwyg.block.clearFormatting': 'Clear formatting', + 'jsonformsBuilder.wysiwyg.block.duplicate': 'Duplicate', + 'jsonformsBuilder.wysiwyg.block.copy': 'Copy text', + 'jsonformsBuilder.wysiwyg.block.moveUp': 'Move up', + 'jsonformsBuilder.wysiwyg.block.moveDown': 'Move down', + 'jsonformsBuilder.wysiwyg.block.delete': 'Delete', 'jsonformsBuilder.wysiwyg.imageBubble.replace': 'Replace', 'jsonformsBuilder.wysiwyg.imageBubble.remove': 'Delete', 'jsonformsBuilder.wysiwyg.imageUpload.label': 'Add an image', diff --git a/src/icons.ts b/src/icons.ts index 9ceaf5b..87d518b 100644 --- a/src/icons.ts +++ b/src/icons.ts @@ -33,6 +33,7 @@ export const WYSIWYG_ICONS = [ 'i-lucide-align-justify', 'i-lucide-align-left', 'i-lucide-align-right', + 'i-lucide-arrow-down', 'i-lucide-arrow-left', 'i-lucide-arrow-up', 'i-lucide-baseline', @@ -49,10 +50,13 @@ export const WYSIWYG_ICONS = [ 'i-lucide-circle', 'i-lucide-circle-alert', 'i-lucide-circle-off', + 'i-lucide-clipboard', 'i-lucide-code', 'i-lucide-code-xml', + 'i-lucide-copy', 'i-lucide-eye', 'i-lucide-grid-2x2-x', + 'i-lucide-grip-vertical', 'i-lucide-heading-1', 'i-lucide-heading-2', 'i-lucide-heading-3', @@ -75,6 +79,7 @@ export const WYSIWYG_ICONS = [ 'i-lucide-pen-line', 'i-lucide-pencil', 'i-lucide-pilcrow', + 'i-lucide-plus', 'i-lucide-quote', 'i-lucide-redo-2', 'i-lucide-refresh-cw', diff --git a/tests/advanced/wysiwygBlock.test.ts b/tests/advanced/wysiwygBlock.test.ts new file mode 100644 index 0000000..89bea20 --- /dev/null +++ b/tests/advanced/wysiwygBlock.test.ts @@ -0,0 +1,357 @@ +// @vitest-environment jsdom + +import { afterEach, describe, expect, it } from 'vitest' +import type { Editor } from '@tiptap/core' +import { TaskItem, TaskList } from '@tiptap/extension-list' +import { + DISABLED_WYSIWYG_BLOCK_EDITOR, + findWysiwygBlockAt, + WYSIWYG_BLOCK_LAYOUT, + buildWysiwygBlockMenu, + createWysiwygBlockPlaceholder, + insertWysiwygBlockAfter, + resolveWysiwygBlockEditor, + runWysiwygBlockAction, + type WysiwygBlockAction, + type WysiwygBlockType, +} from '../../src/advanced/wysiwyg/block' +import { DEFAULT_WYSIWYG_FEATURES } from '../../src/advanced/wysiwyg/features' +import { resolveWysiwygOptions } from '../../src/advanced/wysiwygOptions' +import { buildWysiwygToolbar } from '../../src/advanced/wysiwyg/toolbar' +import { createJsonFormsTranslator } from '../../src/i18n/createJsonFormsTranslator' +import { createUiText } from '../../src/i18n/ui' +import { createTestEditor } from './wysiwygEditorHarness' + +type Item = Record + +let editor: Editor | undefined +afterEach(() => { + editor?.destroy() + editor = undefined +}) + +/** Position of the n-th top-level block. */ +const blockPos = (target: Editor, index: number) => { + let pos = 0 + for (let i = 0; i < index; i++) pos += target.state.doc.child(i).nodeSize + return pos +} + +describe('resolveWysiwygBlockEditor', () => { + it('stays off unless true or an object is given', () => { + for (const raw of [undefined, false, 'yes', 1, []]) { + expect(resolveWysiwygBlockEditor(raw)).toEqual(DISABLED_WYSIWYG_BLOCK_EDITOR) + } + }) + + it('enables the handle and placeholders on a borderless page by default', () => { + expect(resolveWysiwygBlockEditor(true)).toEqual({ + enabled: true, + dragHandle: true, + placeholders: true, + bordered: false, + }) + expect( + resolveWysiwygBlockEditor({ dragHandle: false, placeholders: 'no', bordered: true }), + ).toEqual({ enabled: true, dragHandle: false, placeholders: true, bordered: true }) + }) +}) + +describe('resolveWysiwygOptions with blockEditor', () => { + it('keeps the historical defaults without blockEditor', () => { + const resolved = resolveWysiwygOptions({}, 'object') + expect(resolved).toMatchObject({ + bubbleMenu: false, + slashCommands: false, + padding: 'p-3', + blockEditor: DISABLED_WYSIWYG_BLOCK_EDITOR, + }) + expect(resolved.toolbar).not.toBe(false) + }) + + it('swaps the fixed toolbar for the bubble menu, the / palette and a page layout', () => { + expect(resolveWysiwygOptions({ blockEditor: true }, 'object')).toMatchObject({ + toolbar: false, + bubbleMenu: true, + slashCommands: true, + ...WYSIWYG_BLOCK_LAYOUT, + blockEditor: { enabled: true, dragHandle: true }, + }) + }) + + it('lets explicit options win over the block mode defaults', () => { + const toolbar = [[{ kind: 'bold' }]] + const resolved = resolveWysiwygOptions( + { blockEditor: true, toolbar, bubbleMenu: false, slashCommands: false, density: 'prose' }, + 'object', + ) + expect(resolved).toMatchObject({ + toolbar, + bubbleMenu: false, + slashCommands: false, + padding: 'p-6', + }) + expect(resolveWysiwygOptions({ blockEditor: true, padding: 'p-2' }, 'object').padding).toBe( + 'p-2', + ) + expect( + resolveWysiwygOptions({ blockEditor: { bordered: true }, toolbar: undefined }, 'object') + .toolbar, + ).toBe(false) + // An unknown density still beats the block layout and falls back to `compact`. + expect( + resolveWysiwygOptions({ blockEditor: true, density: 'huge' as 'compact' }, 'object').padding, + ).toBe('p-3') + expect(resolveWysiwygOptions({ blockEditor: false }, 'object').toolbar).toEqual( + buildWysiwygToolbar({ features: DEFAULT_WYSIWYG_FEATURES, imagesEnabled: true }), + ) + }) +}) + +describe('createWysiwygBlockPlaceholder', () => { + it('names headings, hints at / and keeps the host placeholder on an empty document', () => { + editor = createTestEditor('

') + const heading = editor.state.doc.child(0) + const paragraph = editor.state.doc.child(1) + + const hint = createWysiwygBlockPlaceholder({ slashCommands: true }) + expect(hint({ editor, node: heading })).toBe('Titre 2') + expect(hint({ editor, node: paragraph })).toBe('Écrivez, ou tapez « / » pour les commandes…') + + const noSlash = createWysiwygBlockPlaceholder({ slashCommands: false }) + expect(noSlash({ editor, node: paragraph })).toBe('Écrivez…') + + const english = createWysiwygBlockPlaceholder( + { slashCommands: true }, + createUiText(createJsonFormsTranslator({ locale: 'en' })), + ) + expect(english({ editor, node: paragraph })).toBe("Write, or type '/' for commands…") + }) + + it('shows the host placeholder only while the document is empty', () => { + editor = createTestEditor('

') + const host = createWysiwygBlockPlaceholder({ + hostPlaceholder: 'Décrivez…', + slashCommands: true, + }) + expect(host({ editor, node: editor.state.doc.child(0) })).toBe('Décrivez…') + + editor.commands.setContent('

Texte

') + expect(host({ editor, node: editor.state.doc.child(1) })).toBe( + 'Écrivez, ou tapez « / » pour les commandes…', + ) + }) + + it('falls back to level 1 for a heading without level', () => { + editor = createTestEditor('

') + const heading = editor.schema.nodes.heading?.create({ level: null }) + if (!heading) throw new Error('heading node missing') + const hint = createWysiwygBlockPlaceholder({ slashCommands: true }) + expect(hint({ editor, node: heading })).toBe('Titre 1') + }) + + it('leaves code blocks without hint', () => { + editor = createTestEditor('
') + const hint = createWysiwygBlockPlaceholder({ slashCommands: true }) + expect(hint({ editor, node: editor.state.doc.child(0) })).toBe('') + }) +}) + +describe('buildWysiwygBlockMenu', () => { + const menuOf = (target: Editor, pos: number, extra: Partial<{ onCopy: () => void }> = {}) => + buildWysiwygBlockMenu({ editor: target, features: DEFAULT_WYSIWYG_FEATURES, pos, ...extra }) + const labels = (items: Item[]) => items.map((item) => item.label) + + it('groups turn-into, duplicate/copy, move and delete entries', () => { + editor = createTestEditor('

Un

Deux

') + const onCopy = () => undefined + const groups = menuOf(editor, 0, { onCopy }) + expect(groups.map(labels)).toEqual([ + ['Transformer en', 'Effacer la mise en forme'], + ['Dupliquer', 'Copier le texte'], + ['Monter', 'Descendre'], + ['Supprimer'], + ]) + expect(groups[1]?.[1]?.onSelect).toBe(onCopy) + expect(labels((groups[0]?.[0]?.children ?? []) as Item[])).toEqual([ + 'Transformer en', + 'Paragraphe', + 'Titre 1', + 'Titre 2', + 'Titre 3', + 'Liste à puces', + 'Liste numérotée', + 'Liste de tâches', + 'Citation', + 'Bloc de code', + ]) + // First block: nothing above; second block: nothing below. + expect(groups[2]?.map((item) => item.disabled)).toEqual([true, false]) + expect(menuOf(editor, blockPos(editor, 1))[2]?.map((item) => item.disabled)).toEqual([ + false, + true, + ]) + }) + + it('drops the task list without the feature and copy without a clipboard', () => { + editor = createTestEditor('

Un

') + const groups = buildWysiwygBlockMenu({ + editor, + features: { ...DEFAULT_WYSIWYG_FEATURES, taskList: false }, + pos: 0, + }) + const turnInto = (groups[0]?.[0]?.children ?? []) as Item[] + expect(turnInto.some((item) => item.icon === 'i-lucide-list-checks')).toBe(false) + expect(groups[1]).toHaveLength(1) + }) + + it('disables conversions whose node type the editor lacks', () => { + editor = createTestEditor('

Un

') + const turnInto = (menuOf(editor, 0)[0]?.[0]?.children ?? []) as Item[] + const taskList = turnInto.find((item) => item.icon === 'i-lucide-list-checks') + expect(taskList?.disabled).toBe(true) + }) + + it('runs its entries on the targeted block', () => { + editor = createTestEditor('

Un

Deux

Trois

') + const target = editor + const select = (pos: number, group: number, index: number) => { + const onSelect = menuOf(target, pos)[group]?.[index]?.onSelect + if (typeof onSelect !== 'function') throw new Error(`no entry at ${group}/${index}`) + onSelect() + } + select(blockPos(target, 1), 2, 0) // move up + expect(target.getText({ blockSeparator: '|' })).toBe('Deux|Un|Trois') + select(0, 1, 0) // duplicate + expect(target.getText({ blockSeparator: '|' })).toBe('Deux|Deux|Un|Trois') + select(blockPos(target, 3), 3, 0) // delete + expect(target.getText({ blockSeparator: '|' })).toBe('Deux|Deux|Un') + }) + + it('translates the menu', () => { + editor = createTestEditor('

Un

') + const groups = buildWysiwygBlockMenu( + { editor, features: DEFAULT_WYSIWYG_FEATURES, pos: 0 }, + createUiText(createJsonFormsTranslator({ locale: 'en' })), + ) + expect(groups[0]?.[0]?.label).toBe('Turn into') + expect(groups[3]?.[0]?.label).toBe('Delete') + }) +}) + +describe('runWysiwygBlockAction', () => { + const types = (target: Editor) => { + const names: string[] = [] + target.state.doc.forEach((node) => { + names.push(node.type.name === 'heading' ? `h${node.attrs.level}` : node.type.name) + }) + return names + } + + it('turns a block into each type, through plain paragraphs', () => { + editor = createTestEditor('

Un

Deux

Trois

', [ + TaskList, + TaskItem, + ]) + const pos = () => blockPos(editor as Editor, 1) + const turn = (to: WysiwygBlockType) => + runWysiwygBlockAction(editor as Editor, pos(), { action: 'turnInto', to }) + + expect(turn({ type: 'heading', level: 2 })).toBe(true) + expect(types(editor)).toEqual(['paragraph', 'h2', 'paragraph']) + expect(turn({ type: 'bulletList' })).toBe(true) + expect(types(editor)).toEqual(['paragraph', 'bulletList', 'paragraph']) + expect(turn({ type: 'orderedList' })).toBe(true) + expect(types(editor)).toEqual(['paragraph', 'orderedList', 'paragraph']) + expect(turn({ type: 'taskList' })).toBe(true) + expect(types(editor)).toEqual(['paragraph', 'taskList', 'paragraph']) + expect(turn({ type: 'blockquote' })).toBe(true) + expect(types(editor)).toEqual(['paragraph', 'blockquote', 'paragraph']) + expect(turn({ type: 'codeBlock' })).toBe(true) + expect(types(editor)).toEqual(['paragraph', 'codeBlock', 'paragraph']) + expect(turn({ type: 'paragraph' })).toBe(true) + expect(types(editor)).toEqual(['paragraph', 'paragraph', 'paragraph']) + expect(editor.getText({ blockSeparator: '|' })).toBe('Un|Deux|Trois') + }) + + it('clears marks and block type', () => { + editor = createTestEditor('

Un

Deux

') + expect(runWysiwygBlockAction(editor, 0, { action: 'clearFormatting' })).toBe(true) + expect(editor.getHTML()).toBe('

Un

Deux

') + }) + + it('moves blocks within bounds and refuses positions that start no top-level block', () => { + editor = createTestEditor('

Un

Deux

') + expect(runWysiwygBlockAction(editor, 0, { action: 'moveUp' })).toBe(false) + expect(runWysiwygBlockAction(editor, 0, { action: 'moveDown' })).toBe(true) + expect(editor.getText({ blockSeparator: '|' })).toBe('Deux|Un') + expect(runWysiwygBlockAction(editor, blockPos(editor, 1), { action: 'moveDown' })).toBe(false) + expect(runWysiwygBlockAction(editor, 1, { action: 'delete' })).toBe(false) + expect(runWysiwygBlockAction(editor, 999, { action: 'delete' })).toBe(false) + expect(runWysiwygBlockAction(editor, -1, { action: 'delete' })).toBe(false) + expect(runWysiwygBlockAction(editor, 0.5, { action: 'delete' })).toBe(false) + expect(runWysiwygBlockAction(editor, 0, { action: 'turnInto', to: { type: 'taskList' } })).toBe( + false, + ) + }) + + it('ignores unknown actions and conversions', () => { + editor = createTestEditor('

Un

') + const unknownAction = { action: 'archive' } as unknown as WysiwygBlockAction + const unknownType = { + action: 'turnInto', + to: { type: 'text' }, + } as unknown as WysiwygBlockAction + expect(runWysiwygBlockAction(editor, 0, unknownAction)).toBe(false) + expect(runWysiwygBlockAction(editor, 0, unknownType)).toBe(false) + expect(editor.getHTML()).toBe('

Un

') + }) +}) + +describe('insertWysiwygBlockAfter', () => { + it('inserts an empty paragraph after the block and moves the cursor into it', () => { + editor = createTestEditor('

Titre

Fin

') + expect(insertWysiwygBlockAfter(editor, 0, false)).toBe(true) + expect(editor.state.doc.child(1).type.name).toBe('paragraph') + expect(editor.state.doc.child(1).textContent).toBe('') + expect(editor.state.selection.$from.parent).toBe(editor.state.doc.child(1)) + }) + + it('starts the new block with / to open the command palette', () => { + editor = createTestEditor('

Un

') + insertWysiwygBlockAfter(editor, 0, true) + expect(editor.state.doc.child(1).textContent).toBe('/') + expect(editor.state.selection.from).toBe(blockPos(editor, 1) + 2) + }) + + it('refuses a position without top-level block', () => { + editor = createTestEditor('

Un

  • Item

') + expect(insertWysiwygBlockAfter(editor, 999, true)).toBe(false) + expect(insertWysiwygBlockAfter(editor, -1, true)).toBe(false) + expect(insertWysiwygBlockAfter(editor, blockPos(editor, 1) + 1, true)).toBe(false) + }) +}) + +describe('findWysiwygBlockAt', () => { + it('returns the block under the pointer, or the nearest one', () => { + editor = createTestEditor('

Un

Deux

Trois

') + const rects = [ + { top: 0, bottom: 20 }, + { top: 30, bottom: 50 }, + { top: 60, bottom: 80 }, + ] + Array.from(editor.view.dom.children).forEach((child, index) => { + ;(child as HTMLElement).getBoundingClientRect = () => rects[index] as DOMRect + }) + expect(findWysiwygBlockAt(editor.view, 40)).toBe(blockPos(editor, 1)) + expect(findWysiwygBlockAt(editor.view, 27)).toBe(blockPos(editor, 1)) + expect(findWysiwygBlockAt(editor.view, 200)).toBe(blockPos(editor, 2)) + expect(findWysiwygBlockAt(editor.view, -50)).toBe(0) + }) + + it('skips blocks without rendered element', () => { + editor = createTestEditor('

Un

') + const view = { state: editor.state, nodeDOM: () => null } as unknown as Editor['view'] + expect(findWysiwygBlockAt(view, 0)).toBeNull() + }) +})