Skip to content

Build your personal knowledge base with Trilium Notes

refactor(ckeditor5): fold footnotes into the aggregate package

Elian Doranf17a54204180
diff --git a/CLAUDE.md b/CLAUDE.md
index 3105e4e752..ef1eafcf94 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -75,7 +75,7 @@ packages/
codemirror/ # Code editor integration
highlightjs/ # Syntax highlighting
share-theme/ # Theme for shared/published notes
- ckeditor5-footnotes/, ckeditor5-math/, ckeditor5-mermaid/
+ ckeditor5-math/, ckeditor5-mermaid/
express-partial-content/, pdfjs-viewer/, splitjs/
turndown-plugin-gfm/
```
diff --git a/docs/Developer Guide/Developer Guide/Architecture.md b/docs/Developer Guide/Developer Guide/Architecture.md
index f64bfe365b..85ac9f79e9 100644
--- a/docs/Developer Guide/Developer Guide/Architecture.md
+++ b/docs/Developer Guide/Developer Guide/Architecture.md
@@ -94,7 +94,6 @@ trilium/
│ ├── ckeditor5/ # Custom rich text editor
│ ├── codemirror/ # Code editor customizations
│ ├── highlightjs/ # Syntax highlighting
-│ ├── ckeditor5-footnotes/ # CKEditor plugin: footnotes
│ ├── ckeditor5-math/ # CKEditor plugin: math equations
│ ├── ckeditor5-mermaid/ # CKEditor plugin: diagrams
│ ├── express-partial-content/ # HTTP partial content middleware
diff --git a/flake.nix b/flake.nix
index 793b79c5e9..ce685db4da 100644
--- a/flake.nix
+++ b/flake.nix
@@ -238,7 +238,6 @@ nodejs.python
components = [
"packages/ckeditor5"
- "packages/ckeditor5-footnotes"
"packages/ckeditor5-math"
"packages/ckeditor5-mermaid"
"packages/codemirror"
diff --git a/packages/ckeditor5-footnotes/.editorconfig b/packages/ckeditor5-footnotes/.editorconfig
deleted file mode 100644
index 37ea8ff914..0000000000
--- a/packages/ckeditor5-footnotes/.editorconfig
+++ /dev/null
@@ -1,19 +0,0 @@
-# Configurations to normalize the IDE behavior.
-# http://editorconfig.org/
-
-root = true
-
-[*]
-indent_style = tab
-tab_width = 4
-charset = utf-8
-end_of_line = lf
-trim_trailing_whitespace = true
-insert_final_newline = true
-
-[*.{js,jsx,ts}]
-quote_type = single
-
-[package.json]
-indent_style = space
-tab_width = 2
diff --git a/packages/ckeditor5-footnotes/.gitattributes b/packages/ckeditor5-footnotes/.gitattributes
deleted file mode 100644
index 41be6fafe7..0000000000
--- a/packages/ckeditor5-footnotes/.gitattributes
+++ /dev/null
@@ -1,19 +0,0 @@
-* text=auto
-
-*.htaccess eol=lf
-*.cgi eol=lf
-*.sh eol=lf
-
-*.css text
-*.htm text
-*.html text
-*.js text
-*.ts text
-*.json text
-*.php text
-*.txt text
-*.md text
-
-*.png -text
-*.gif -text
-*.jpg -text
diff --git a/packages/ckeditor5-footnotes/.gitignore b/packages/ckeditor5-footnotes/.gitignore
deleted file mode 100644
index 437dda1d0a..0000000000
--- a/packages/ckeditor5-footnotes/.gitignore
+++ /dev/null
@@ -1,10 +0,0 @@
-build/
-coverage/
-dist/
-node_modules/
-tmp/
-sample/ckeditor.dist.js
-
-# Ignore compiled TypeScript files.
-src/**/*.js
-src/**/*.d.ts
diff --git a/packages/ckeditor5-footnotes/.stylelintrc b/packages/ckeditor5-footnotes/.stylelintrc
deleted file mode 100644
index 1d86a41f98..0000000000
--- a/packages/ckeditor5-footnotes/.stylelintrc
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "extends": "stylelint-config-ckeditor5"
-}
diff --git a/packages/ckeditor5-footnotes/README.md b/packages/ckeditor5-footnotes/README.md
deleted file mode 100644
index 21cc61d3fb..0000000000
--- a/packages/ckeditor5-footnotes/README.md
+++ /dev/null
@@ -1,141 +0,0 @@
-@triliumnext/ckeditor5-footnotes
-================================
-
-This package was created by the [ckeditor5-package-generator](https://www.npmjs.com/package/ckeditor5-package-generator) package.
-
-## Table of contents
-
-* [Developing the package](#developing-the-package)
-* [Available scripts](#available-scripts)
- * [`start`](#start)
- * [`test`](#test)
- * [`lint`](#lint)
- * [`stylelint`](#stylelint)
- * [`build:dist`](#builddist)
- * [`translations:synchronize`](#translationssynchronize)
- * [`translations:validate`](#translationsvalidate)
- * [`ts:build` and `ts:clear`](#tsbuild-and-tsclear)
-* [License](#license)
-
-## Developing the package
-
-To read about the CKEditor 5 Framework, visit the [CKEditor 5 Framework documentation](https://ckeditor.com/docs/ckeditor5/latest/framework/index.html).
-
-## Available scripts
-
-NPM scripts are a convenient way to provide commands in a project. They are defined in the `package.json` file and shared with people contributing to the project. It ensures developers use the same command with the same options (flags).
-
-All the scripts can be executed by running `npm run <script>`. Pre and post commands with matching names will be run for those as well.
-
-The following scripts are available in the package.
-
-### `start`
-
-Starts an HTTP server with the live-reload mechanism that allows previewing and testing of plugins available in the package.
-
-When the server starts, the default browser will open the developer sample. This can be disabled by passing the `--no-open` option to that command.
-
-You can also define the language that will translate the created editor by specifying the `--language [LANG]` option. It defaults to `'en'`.
-
-Examples:
-
-```bash
-# Starts the server and open the browser.
-npm run start
-
-# Disable auto-opening the browser.
-npm run start -- --no-open
-
-# Create the editor with the interface in German.
-npm run start -- --language=de
-```
-
-### `test`
-
-Allows executing unit tests for the package specified in the `tests/` directory. To check the code coverage, add the `--coverage` modifier. See other [CLI flags](https://vitest.dev/guide/cli.html) in Vitest.
-
-Examples:
-
-```bash
-# Execute tests.
-npm run test
-
-# Generate code coverage report after each change in the sources.
-npm run test -- --coverage
-```
-
-### `lint`
-
-Runs ESLint, which analyzes the code (all `*.ts` files) to quickly find problems.
-
-Examples:
-
-```bash
-# Execute eslint.
-npm run lint
-```
-
-### `stylelint`
-
-Similar to the `lint` task, stylelint analyzes the CSS code (`*.css` files in the `theme/` directory) in the package.
-
-Examples:
-
-```bash
-# Execute stylelint.
-npm run stylelint
-```
-
-### `build:dist`
-
-Creates npm and browser builds of your plugin. These builds can be added to the editor by following the [Configuring CKEditor 5 features](https://ckeditor.com/docs/ckeditor5/latest/getting-started/setup/configuration.html) guide.
-
-Examples:
-
-```bash
-# Builds the `npm` and browser files thats are ready to publish.
-npm run build:dist
-```
-
-### `translations:synchronize`
-
-Synchronizes translation messages (arguments of the `t()` function) by performing the following steps:
-
- * Collect all translation messages from the package by finding `t()` calls in source files.
- * Detect if translation context is valid, i.e. whether the provided values do not interfere with the values specified in the `@ckeditor/ckeditor5-core` package.
- * If there are no validation errors, update all translation files (`*.po` files) to be in sync with the context file:
- * unused translation entries are removed,
- * missing translation entries are added with empty string as the message translation,
- * missing translation files are created for languages that do not have own `*.po` file yet.
-
-The task may end with an error if one of the following conditions is met:
-
-* Found the `Unused context` error &ndash; entries specified in the `lang/contexts.json` file are not used in source files. They should be removed.
-* Found the `Duplicated contex` error &ndash; some of the entries are duplicated. Consider removing them from the `lang/contexts.json` file, or rewriting them.
-* Found the `Missing context` error &ndash; entries specified in source files are not described in the `lang/contexts.json` file. They should be added.
-
-Examples:
-
-```bash
-npm run translations:synchronize
-```
-
-### `translations:validate`
-
-Peforms only validation steps as described in [`translations:synchronize`](#translationssynchronize) script, but without modifying any files. It only checks the correctness of the context file against the `t()` function calls.
-
-Examples:
-
-```bash
-npm run translations:validate
-```
-
-### `ts:build` and `ts:clear`
-
-These scripts compile TypeScript and remove the compiled files. They are used in the aforementioned life cycle scripts, and there is no need to call them manually.
-
-## License
-
-The `@triliumnext/ckeditor5-footnotes` package is available under [MIT license](https://opensource.org/licenses/MIT).
-
-However, it is the default license of packages created by the [ckeditor5-package-generator](https://www.npmjs.com/package/ckeditor5-package-generator) package and can be changed.
diff --git a/packages/ckeditor5-footnotes/ckeditor5-metadata.json b/packages/ckeditor5-footnotes/ckeditor5-metadata.json
deleted file mode 100644
index 40825886ad..0000000000
--- a/packages/ckeditor5-footnotes/ckeditor5-metadata.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "plugins": [
- {
- "name": "Footnotes",
- "className": "Footnotes",
- "description": "Adds text to the editor.",
- "path": "src/footnotes.ts",
- "uiComponents": [
- {
- "name": "insertFootnote",
- "type": "Button",
- "iconPath": "theme/icons/insert-footnote.svg"
- }
- ]
- }
- ]
-}
diff --git a/packages/ckeditor5-footnotes/eslint.config.js b/packages/ckeditor5-footnotes/eslint.config.js
deleted file mode 100644
index 8e49f74ea6..0000000000
--- a/packages/ckeditor5-footnotes/eslint.config.js
+++ /dev/null
@@ -1,83 +0,0 @@
-import globals from 'globals';
-import { defineConfig } from 'eslint/config';
-import eslintConfigCKEditor5 from 'eslint-config-ckeditor5';
-import eslintPluginCKEditor5Rules from 'eslint-plugin-ckeditor5-rules';
-
-export default defineConfig( [
- eslintConfigCKEditor5,
- {
- name: 'Ignored files config',
- ignores: [
- // Ignore compiled JavaScript files, as they are generated automatically.
- 'src/**/*.js',
- // Also, do not check typing declarations, too.
- 'src/**/*.d.ts',
- // Ignore the entire `dist/` (the NIM build).
- 'dist/**'
- ]
- },
- {
- name: 'Base config',
- languageOptions: {
- ecmaVersion: 'latest',
- sourceType: 'module'
- },
- linterOptions: {
- reportUnusedInlineConfigs: 'error',
- reportUnusedDisableDirectives: 'error'
- },
- plugins: {
- 'ckeditor5-rules': eslintPluginCKEditor5Rules
- },
- rules: {
- // This rule disallows importing from any path other than the package main entrypoint.
- 'ckeditor5-rules/allow-imports-only-from-main-package-entry-point': 'error',
- // As required by the ECMAScript (ESM) standard, all imports must include a file extension.
- // If the import does not include it, this rule will try to automatically detect the correct file extension.
- 'ckeditor5-rules/require-file-extensions-in-imports': [ 'error', {
- extensions: [ '.ts', '.js', '.json' ]
- } ],
- // This rule ensures that all imports from `@ckeditor/*` packages are done through the main package entry points.
- // This is required for the editor types to work properly and to ease migration to the installation methods
- // introduced in CKEditor 5 version 42.0.0.
- 'ckeditor5-rules/no-legacy-imports': 'error'
- }
- },
- {
- name: 'NodeJS environment config',
- files: [
- './scripts/**/*.{js,mjs,cjs}'
- ],
- languageOptions: {
- globals: {
- ...globals.node
- }
- }
- },
- {
- name: 'Browser environment config',
- files: [
- './sample/**/*.{ts,mts,cts}',
- './src/**/*.{ts,mts,cts}',
- './tests/**/*.{ts,mts,cts}',
- './typings/**/*.d.ts'
- ],
- languageOptions: {
- globals: {
- ...globals.browser
- }
- }
- },
- {
- name: 'Sample and tests config',
- files: [
- 'sample/**/*.{ts,mts,cts}',
- 'tests/**/*.{ts,mts,cts}'
- ],
- rules: {
- // To write complex tests, you may need to import files that are not exported in DLL files by default.
- // Hence, imports CKEditor 5 packages in test files are not checked.
- 'ckeditor5-rules/ckeditor-imports': 'off'
- }
- }
-] );
diff --git a/packages/ckeditor5-footnotes/lang/contexts.json b/packages/ckeditor5-footnotes/lang/contexts.json
deleted file mode 100644
index 4185fdf9d1..0000000000
--- a/packages/ckeditor5-footnotes/lang/contexts.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "Footnotes": "Content for a tooltip is displayed when a user hovers the CKEditor 5 icon."
-}
diff --git a/packages/ckeditor5-footnotes/package.json b/packages/ckeditor5-footnotes/package.json
deleted file mode 100644
index 2ffa66afce..0000000000
--- a/packages/ckeditor5-footnotes/package.json
+++ /dev/null
@@ -1,42 +0,0 @@
-{
- "name": "@triliumnext/ckeditor5-footnotes",
- "version": "0.0.4",
- "description": "A plugin for CKEditor 5 to allow footnotes.",
- "keywords": [
- "ckeditor",
- "ckeditor5",
- "ckeditor 5",
- "ckeditor5-feature",
- "ckeditor5-plugin",
- "ckeditor5-package-generator"
- ],
- "type": "module",
- "main": "src/index.ts",
- "license": "ISC",
- "engines": {
- "node": ">=18.0.0",
- "npm": ">=5.7.1"
- },
- "devDependencies": {
- "@ckeditor/ckeditor5-inspector": ">=4.1.0",
- "@vitest/browser": "4.1.10",
- "ckeditor5": "48.3.1",
- "eslint": "10.8.0",
- "eslint-config-ckeditor5": ">=9.1.0",
- "stylelint": "17.14.1",
- "stylelint-config-ckeditor5": ">=9.1.0",
- "typescript": "6.0.3",
- "vite-plugin-svgo": "2.0.0",
- "vitest": "4.1.10",
- "webdriverio": "9.30.0"
- },
- "peerDependencies": {
- "ckeditor5": "48.3.1"
- },
- "scripts": {
- "lint": "eslint \"**/*.{js,ts}\" --quiet",
- "stylelint": "stylelint --quiet --allow-empty-input 'theme/**/*.css'",
- "test": "vitest",
- "test:debug": "vitest --inspect-brk --no-file-parallelism --browser.headless=false"
- }
-}
diff --git a/packages/ckeditor5-footnotes/sample/ckeditor.ts b/packages/ckeditor5-footnotes/sample/ckeditor.ts
deleted file mode 100644
index 1431b687c0..0000000000
--- a/packages/ckeditor5-footnotes/sample/ckeditor.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-declare global {
- interface Window {
- editor: ClassicEditor;
- }
-}
-
-import {
- ClassicEditor,
- Autoformat,
- Base64UploadAdapter,
- BlockQuote,
- Bold,
- Code,
- CodeBlock,
- Essentials,
- Heading,
- Image,
- ImageCaption,
- ImageStyle,
- ImageToolbar,
- ImageUpload,
- Indent,
- Italic,
- Link,
- List,
- MediaEmbed,
- Paragraph,
- Table,
- TableToolbar
-} from 'ckeditor5';
-
-import CKEditorInspector from '@ckeditor/ckeditor5-inspector';
-
-import Footnotes from '../src/footnotes.js';
-
-import 'ckeditor5/ckeditor5.css';
-
-ClassicEditor
- .create( document.getElementById( 'editor' )!, {
- licenseKey: 'GPL',
- plugins: [
- Footnotes,
- Essentials,
- Autoformat,
- BlockQuote,
- Bold,
- Heading,
- Image,
- ImageCaption,
- ImageStyle,
- ImageToolbar,
- ImageUpload,
- Indent,
- Italic,
- Link,
- List,
- MediaEmbed,
- Paragraph,
- Table,
- TableToolbar,
- CodeBlock,
- Code,
- Base64UploadAdapter
- ],
- toolbar: [
- 'undo',
- 'redo',
- '|',
- 'footnotes',
- '|',
- 'heading',
- '|',
- 'bold',
- 'italic',
- 'link',
- 'code',
- 'bulletedList',
- 'numberedList',
- '|',
- 'outdent',
- 'indent',
- '|',
- 'uploadImage',
- 'blockQuote',
- 'insertTable',
- 'mediaEmbed',
- 'codeBlock'
- ],
- image: {
- toolbar: [
- 'imageStyle:inline',
- 'imageStyle:block',
- 'imageStyle:side',
- '|',
- 'imageTextAlternative'
- ]
- },
- table: {
- contentToolbar: [
- 'tableColumn',
- 'tableRow',
- 'mergeTableCells'
- ]
- }
- } )
- .then( editor => {
- window.editor = editor;
- CKEditorInspector.attach( editor );
- window.console.log( 'CKEditor 5 is ready.', editor );
- } )
- .catch( err => {
- window.console.error( err.stack );
- } );
diff --git a/packages/ckeditor5-footnotes/sample/dll.html b/packages/ckeditor5-footnotes/sample/dll.html
deleted file mode 100644
index d7d88ec64d..0000000000
--- a/packages/ckeditor5-footnotes/sample/dll.html
+++ /dev/null
@@ -1,172 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <link rel="icon" type="image/png" href="https://ckeditor.com/docs/ckeditor5/latest/assets/img/favicons/32x32.png" sizes="32x32">
- <meta charset="utf-8">
- <title>CKEditor 5 – DLL Sample</title>
- <style>
- body {
- max-width: 800px;
- margin: 20px auto;
- }
- </style>
-</head>
-<body>
-
-<h1>CKEditor 5 – DLL Sample</h1>
-
-<div id="editor">
- <h2>Production sample</h2>
- <p>
- This is a demo of the <a href="https://ckeditor.com/docs/ckeditor5/latest/builds/guides/overview.html#classic-editor">classic editor
- build</a>, initialized using the <a href="https://ckeditor.com/docs/ckeditor5/latest/builds/guides/development/dll-builds.html">DLL builds</a>.
- </p>
- <p>
- Your plugin (Footnotes) generated by the tool is already loaded into the editor. By default, it has an example button that adds some text to the editor. Whenever you change the plugin's name or toolbar items, make sure to update the editor configuration in the <code>sample/dll.html</code> file.
- </p>
-
- <h3>Uncaught TypeError</h3>
- <p>If the editor is not initialized correctly and the browser console displays an error such as the following:</p>
- <pre><code>Uncaught TypeError: Cannot read properties of undefined (reading 'Footnotes') at dll.html:85</code></pre>
- <p>it means that the DLL build of the <code>@triliumnext/ckeditor5-footnotes</code> package has not been created.</p>
- <p>Please call the <code>npm run dll:build</code> command in the CLI, and after it finishes, refresh the page.</p>
-
- <h3>Anatomy of the DLL build</h3>
- <p>The source of the DLL build is located in the <code>src/index.ts</code> file. It may export as many things as the package offers.</p>
-
- <h4>Maintaining the sample</h4>
- <p>Whenever you change objects exported by the DLL build, please review the content of the sample. Things to keep in mind:</p>
- <ul>
- <li>Review the list of loaded plugins in the configuration.</li>
- <li>Review names of items registered in toolbars.</li>
- </ul>
-
- <h3>The goal</h3>
- <p>The primary purpose of the sample is to verify whether the plugins in the package will work together with CKEditor 5 created with the DLL approach.</p>
-
- <h3>Publishing the package</h3>
- <p>
- While releasing TypeScript package on npm, few things have to be taken care of:
- </p>
- <ul>
- <li>Building DLL</li>
- <li>Building TypeScript</li>
- <li>Changing the <code>main</code> filed in <code>package.json</code> to <code>.js</code> extension</li>
- </ul>
- <p>
- Likewise, after the release, there are few steps:
- </p>
- <ul>
- <li>Deleting compiled TypeScript files (they are generated in the <code>src</code> directory, and create needless clutter)</li>
- <li>Changing the <code>main</code> filed in <code>package.json</code> back to <code>.ts</code> extension</li>
- </ul>
- <p>
- When calling <code>npm publish</code>, those steps are handled automatically by predefined <code>prepublishOnly</code> and <code>postpublish</code> scripts. To learn more, see <a href="https://docs.npmjs.com/cli/v7/using-npm/scripts#pre--post-scripts">NPM docs</a>.
- </p>
-
- <h3>Reporting issues</h3>
- <p>If you found a problem with CKEditor 5 or the package generator, please, report an issue:</p>
- <ul>
- <li><a href="https://github.com/ckeditor/ckeditor5/issues/new/choose">CKEditor 5</a></li>
- <li><a href="https://github.com/ckeditor/create-ckeditor5-plugin/issues/new">The package generator</a></li>
- </ul>
-</div>
-
-<!-- DLL builds are served from the `node_modules/` directory -->
-<script src="../node_modules/ckeditor5/build/ckeditor5-dll.js"></script>
-<script src="../node_modules/@ckeditor/ckeditor5-editor-classic/build/editor-classic.js"></script>
-<script src="../node_modules/@ckeditor/ckeditor5-code-block/build/code-block.js"></script>
-<script src="../node_modules/@ckeditor/ckeditor5-essentials/build/essentials.js"></script>
-<script src="../node_modules/@ckeditor/ckeditor5-basic-styles/build/basic-styles.js"></script>
-<script src="../node_modules/@ckeditor/ckeditor5-heading/build/heading.js"></script>
-<script src="../node_modules/@ckeditor/ckeditor5-autoformat/build/autoformat.js"></script>
-<script src="../node_modules/@ckeditor/ckeditor5-block-quote/build/block-quote.js"></script>
-<script src="../node_modules/@ckeditor/ckeditor5-image/build/image.js"></script>
-<script src="../node_modules/@ckeditor/ckeditor5-link/build/link.js"></script>
-<script src="../node_modules/@ckeditor/ckeditor5-indent/build/indent.js"></script>
-<script src="../node_modules/@ckeditor/ckeditor5-media-embed/build/media-embed.js"></script>
-<script src="../node_modules/@ckeditor/ckeditor5-list/build/list.js"></script>
-<script src="../node_modules/@ckeditor/ckeditor5-table/build/table.js"></script>
-
-<!-- The "@triliumnext/ckeditor5-footnotes" package DLL build is served from the `build/` directory -->
-<script src="../build/footnotes.js"></script>
-
-<script>
- console.log( 'Objects exported by the DLL build:', CKEditor5[ 'footnotes' ] );
-
- CKEditor5.editorClassic.ClassicEditor
- .create( document.querySelector( '#editor' ), {
- plugins: [
- CKEditor5[ 'footnotes' ].Footnotes,
- CKEditor5.essentials.Essentials,
- CKEditor5.autoformat.Autoformat,
- CKEditor5.blockQuote.BlockQuote,
- CKEditor5.basicStyles.Bold,
- CKEditor5.heading.Heading,
- CKEditor5.image.Image,
- CKEditor5.image.ImageCaption,
- CKEditor5.image.ImageStyle,
- CKEditor5.image.ImageToolbar,
- CKEditor5.image.ImageUpload,
- CKEditor5.indent.Indent,
- CKEditor5.basicStyles.Italic,
- CKEditor5.link.Link,
- CKEditor5.list.List,
- CKEditor5.mediaEmbed.MediaEmbed,
- CKEditor5.paragraph.Paragraph,
- CKEditor5.table.Table,
- CKEditor5.table.TableToolbar,
- CKEditor5.codeBlock.CodeBlock,
- CKEditor5.basicStyles.Code,
- CKEditor5.upload.Base64UploadAdapter
- ],
- toolbar: [
- 'footnotes',
- '|',
- 'heading',
- '|',
- 'bold',
- 'italic',
- 'link',
- 'code',
- 'bulletedList',
- 'numberedList',
- '|',
- 'outdent',
- 'indent',
- '|',
- 'uploadImage',
- 'blockQuote',
- 'insertTable',
- 'mediaEmbed',
- 'codeBlock',
- '|',
- 'undo',
- 'redo'
- ],
- image: {
- toolbar: [
- 'imageStyle:inline',
- 'imageStyle:block',
- 'imageStyle:side',
- '|',
- 'imageTextAlternative'
- ]
- },
- table: {
- contentToolbar: [
- 'tableColumn',
- 'tableRow',
- 'mergeTableCells'
- ]
- }
- } )
- .then( editor => {
- window.editor = editor;
- } )
- .catch( error => {
- console.error( 'There was a problem initializing the editor.', error );
- } );
-</script>
-</body>
-</html>
diff --git a/packages/ckeditor5-footnotes/sample/index.html b/packages/ckeditor5-footnotes/sample/index.html
deleted file mode 100644
index 6267b57fbb..0000000000
--- a/packages/ckeditor5-footnotes/sample/index.html
+++ /dev/null
@@ -1,123 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-
-<head>
- <link rel="icon" type="image/png" href="https://ckeditor.com/docs/ckeditor5/latest/assets/img/favicons/32x32.png"
- sizes="32x32">
- <meta charset="utf-8">
- <title>CKEditor 5 – Development Sample</title>
- <style>
- body {
- max-width: 800px;
- margin: 20px auto;
- }
- </style>
-</head>
-
-<body>
-
- <h1>CKEditor 5 – Development Sample</h1>
-
- <div id="editor">
- <h2>Development environment</h2>
- <p>
- This is a demo of the <a
- href="https://ckeditor.com/docs/ckeditor5/latest/builds/guides/overview.html#classic-editor">classic
- editor
- build</a> that loads your plugin (<code>Footnotes</code>) generated by the
- tool. You can modify this
- sample and use it to validate whether a plugin or a set of plugins work fine.
- </p>
- <p>
- <code>Footnotes</code> inserts text into the editor. You can click the
- CKEditor 5 icon in the toolbar and see the results.
- </p>
-
- <h3>Helpful resources</h3>
- <ul>
- <li>Architecture
- <ul>
- <li>
- <a
- href="https://ckeditor.com/docs/ckeditor5/latest/framework/guides/architecture/core-editor-architecture.html">Core
- editor architecture</a>
- </li>
- </ul>
- <ul>
- <li>
- <a
- href="https://ckeditor.com/docs/ckeditor5/latest/framework/guides/architecture/editing-engine.html">The
- editing engine</a>
- </li>
- </ul>
- <ul>
- <li>
- <a
- href="https://ckeditor.com/docs/ckeditor5/latest/framework/guides/architecture/ui-library.html">The
- UI library</a>
- </li>
- </ul>
- </li>
-
- <li>
- <a
- href="https://ckeditor.com/docs/ckeditor5/latest/framework/guides/support/browser-compatibility.html">Browser
- compatibility</a>
- </li>
-
- <li>
- <a href="https://ckeditor.com/docs/ckeditor5/latest/framework/guides/support/error-codes.html">The error
- codes</a>
- </li>
-
- <li><a href="https://ckeditor.com/docs/ckeditor5/latest/builds/guides/development/dll-builds.html">The DLL
- builds</a></li>
- </ul>
-
- <h3>The directory structure</h3>
-
- <p>
- The code snippet below presents the directory structure.
- </p>
-
- <pre><code class="language-plaintext">.
-├─ lang
-│ └─ contexts.json # Entries used for creating translations.
-├─ sample
-│ ├─ dll.html # The editor initialized using the DLL builds. Check README for details.
-│ ├─ index.html # The currently displayed file.
-│ └─ ckeditor.ts # The editor initialization script.
-├─ src
-│ ├─ footnotes.ts
-│ ├─ augmentation.ts # Type augmentations for the `@ckeditor/ckeditor5-core` module. Read more in <a href="https://ckeditor.com/docs/ckeditor5/latest/api/module_core_plugincollection-PluginsMap.html">PluginsMap</a> and <a href="https://ckeditor.com/docs/ckeditor5/latest/api/module_core_commandcollection-CommandsMap.html">CommandsMap</a>.
-│ ├─ index.ts # The modules exported by the package when using the DLL builds.
-│ └─ **/*.ts # All TypeScript source files should be saved here.
-├─ tests
-│ ├─ footnotes.ts
-│ ├─ index.ts # Tests for the plugin.
-│ └─ **/*.ts # All tests should be saved here.
-├─ theme
-│ ├─ icons
-│ │ ├─ ckeditor.svg # The CKEditor 5 icon displayed in the toolbar.
-│ │ └─ **/*.svg # All icon files should be saved here.
-│ └─ **/*.css # All CSS files should be saved here.
-├─ typings
-│ └─ **/*.d.ts # Files containing type definitions.
-├─ .editorconfig
-├─ ...
-├─ README.md
-└─ tsconfig.json # TypeScript configuration file.</code></pre>
-
- <h3>Reporting issues</h3>
- <p>If you found a problem with CKEditor 5 or the package generator, please, report an issue:</p>
- <ul>
- <li><a href="https://github.com/ckeditor/ckeditor5/issues/new/choose">CKEditor 5</a></li>
- <li><a href="https://github.com/ckeditor/ckeditor5-package-generator/issues/new">The package generator</a>
- </li>
- </ul>
- </div>
-
- <script src="./ckeditor.dist.js"></script>
-</body>
-
-</html>
diff --git a/packages/ckeditor5-footnotes/src/augmentation.ts b/packages/ckeditor5-footnotes/src/augmentation.ts
deleted file mode 100644
index 49509a1630..0000000000
--- a/packages/ckeditor5-footnotes/src/augmentation.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import FootnoteEditing from './footnote-editing/footnote-editing.js';
-import FootnoteUI from './footnote-ui.js';
-import type { Footnotes } from './index.js';
-
-declare module 'ckeditor5' {
- interface PluginsMap {
- [ Footnotes.pluginName ]: Footnotes;
- [ FootnoteEditing.pluginName ]: FootnoteEditing;
- [ FootnoteUI.pluginName ]: FootnoteUI;
- }
-}
diff --git a/packages/ckeditor5-footnotes/src/constants.ts b/packages/ckeditor5-footnotes/src/constants.ts
deleted file mode 100644
index bb84f3d56e..0000000000
--- a/packages/ckeditor5-footnotes/src/constants.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-export const TOOLBAR_COMPONENT_NAME = 'footnote';
-export const DATA_FOOTNOTE_ID = 'data-footnote-id';
-
-export const ELEMENTS = {
- footnoteItem: 'footnoteItem',
- footnoteReference: 'footnoteReference',
- footnoteSection: 'footnoteSection',
- footnoteContent: 'footnoteContent',
- footnoteBackLink: 'footnoteBackLink'
-};
-
-export const CLASSES = {
- footnoteContent: 'footnote-content',
- footnoteItem: 'footnote-item',
- footnoteReference: 'footnote-reference',
- footnoteSection: 'footnote-section',
- footnoteBackLink: 'footnote-back-link',
- footnotes: 'footnotes', // a class already used on our sites for the footnote section
- hidden: 'hidden'
-};
-
-export const COMMANDS = {
- insertFootnote: 'InsertFootnote'
-};
-
-export const ATTRIBUTES = {
- footnoteContent: 'data-footnote-content',
- footnoteId: 'data-footnote-id',
- footnoteIndex: 'data-footnote-index',
- footnoteItem: 'data-footnote-item',
- footnoteReference: 'data-footnote-reference',
- footnoteSection: 'data-footnote-section',
- footnoteBackLink: 'data-footnote-back-link',
- footnoteBackLinkHref: 'data-footnote-back-link-href'
-};
diff --git a/packages/ckeditor5-footnotes/src/footnote-editing/auto-formatting.ts b/packages/ckeditor5-footnotes/src/footnote-editing/auto-formatting.ts
deleted file mode 100644
index 54d97cf103..0000000000
--- a/packages/ckeditor5-footnotes/src/footnote-editing/auto-formatting.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import { type Editor, ModelText, ModelTextProxy, type ModelElement, type ModelRange, type Autoformat, inlineAutoformatEditing } from 'ckeditor5';
-
-import { COMMANDS, ELEMENTS } from '../constants.js';
-import { modelQueryElement, modelQueryElementsAll } from '../utils.js';
-
-/**
- * CKEditor's autoformatting feature (basically find and replace) has two opinionated default modes:
- * block autoformatting, which replaces the entire line, and inline autoformatting,
- * which expects a section to be formatted (but, importantly, not removed) surrounded by
- * a pair of delimters which get removed.
- *
- * Neither of those are ideal for this case. We want to replace the matched text with a new element,
- * without deleting the entire line.
- *
- * However, inlineAutoformatEditing allows for passing in a custom callback to handle
- * regex matching, which also allows us to specify which sections to remove and
- * which sections pass on to the formatting callback. This method removes the entire
- * matched text, while passing the range of the numeric text on to the formatting callback.
- *
- * If 0 or more than 1 match is found, it returns empty ranges for both format and remove, which is a no-op.
- */
-const regexMatchCallback = (
- editor: Editor,
- text: string
-): {
- remove: Array<[number, number]>;
- format: Array<[number, number]>;
-} => {
- const selectionStart = editor.model.document.selection.anchor;
- // get the text node containing the cursor's position, or the one ending at `the cursor's position
- const surroundingText = selectionStart && ( selectionStart.textNode || selectionStart.getShiftedBy( -1 ).textNode );
-
- if ( !selectionStart || !surroundingText ) {
- return {
- remove: [],
- format: []
- };
- }
-
- const results = text.matchAll( /\[\^([0-9]+)\]/g );
-
- for ( const result of results || [] ) {
- const removeStartIndex = text.indexOf( result[ 0 ] );
- const removeEndIndex = removeStartIndex + result[ 0 ].length;
- const textNodeOffset = selectionStart.parent.getChildStartOffset( surroundingText );
-
- // if the cursor isn't at the end of the range to be replaced, do nothing
- if ( textNodeOffset === null || selectionStart.offset !== textNodeOffset + removeEndIndex ) {
- continue;
- }
- const formatStartIndex = removeStartIndex + 2;
- const formatEndIndex = formatStartIndex + result[ 1 ].length;
- return {
- remove: [ [ removeStartIndex, removeEndIndex ] ],
- format: [ [ formatStartIndex, formatEndIndex ] ]
- };
- }
- return {
- remove: [],
- format: []
- };
-};
-
-/**
- * This callback takes in a range of text passed on by regexMatchCallback,
- * and attempts to insert a corresponding footnote reference at the current location.
- *
- * Footnotes only get inserted if the matching range is an integer between 1
- * and the number of existing footnotes + 1.
- */
-const formatCallback = ( ranges: Array<ModelRange>, editor: Editor, rootElement: ModelElement ): boolean | undefined => {
- const command = editor.commands.get( COMMANDS.insertFootnote );
- if ( !command || !command.isEnabled ) {
- return;
- }
- const text = [ ...ranges[ 0 ].getItems() ][ 0 ];
- if ( !( text instanceof ModelTextProxy || text instanceof ModelText ) ) {
- return false;
- }
- const match = text.data.match( /[0-9]+/ );
- if ( !match ) {
- return false;
- }
- const footnoteIndex = parseInt( match[ 0 ] );
- const footnoteSection = modelQueryElement( editor, rootElement, element =>
- element.is( 'element', ELEMENTS.footnoteSection )
- );
- if ( !footnoteSection ) {
- if ( footnoteIndex !== 1 ) {
- return false;
- }
- editor.execute( COMMANDS.insertFootnote );
- return;
- }
- const footnoteCount = modelQueryElementsAll( editor, footnoteSection, element =>
- element.is( 'element', ELEMENTS.footnoteItem )
- ).length;
- if ( footnoteIndex === footnoteCount + 1 ) {
- editor.execute( COMMANDS.insertFootnote );
- return;
- } else if ( footnoteIndex >= 1 && footnoteIndex <= footnoteCount ) {
- editor.execute( COMMANDS.insertFootnote, { footnoteIndex } );
- return;
- }
- return false;
-};
-
-/**
- * Adds functionality to support creating footnotes using markdown syntax, e.g. `[^1]`.
- */
-export const addFootnoteAutoformatting = ( editor: Editor, rootElement: ModelElement ): void => {
- if ( editor.plugins.has( 'Autoformat' ) ) {
- const autoformatPluginInstance = editor.plugins.get( 'Autoformat' ) as Autoformat;
- inlineAutoformatEditing(
- editor,
- autoformatPluginInstance,
- text => regexMatchCallback( editor, text ),
- ( _, ranges: Array<ModelRange> ) => formatCallback( ranges, editor, rootElement )
- );
- }
-};
diff --git a/packages/ckeditor5-footnotes/src/footnote-editing/converters.ts b/packages/ckeditor5-footnotes/src/footnote-editing/converters.ts
deleted file mode 100644
index 48b6e653b1..0000000000
--- a/packages/ckeditor5-footnotes/src/footnote-editing/converters.ts
+++ /dev/null
@@ -1,370 +0,0 @@
-import { type Editor, type DowncastConversionApi, type ViewContainerElement, ModelElement, toWidget, toWidgetEditable } from 'ckeditor5';
-
-import { ATTRIBUTES, CLASSES, ELEMENTS } from '../constants.js';
-import { viewQueryElement } from '../utils.js';
-
-/**
- * Defines methods for converting between model, data view, and editing view representations of each element type.
- */
-export const defineConverters = ( editor: Editor ): void => {
- const conversion = editor.conversion;
-
- /** *********************************Attribute Conversion************************************/
-
- conversion.for( 'downcast' ).attributeToAttribute( {
- model: ATTRIBUTES.footnoteId,
- view: ATTRIBUTES.footnoteId
- } );
-
- conversion.for( 'downcast' ).attributeToAttribute( {
- model: ATTRIBUTES.footnoteIndex,
- view: ATTRIBUTES.footnoteIndex
- } );
-
- /** *********************************Footnote Section Conversion************************************/
-
- // ((data) view → model)
- conversion.for( 'upcast' ).elementToElement( {
- view: {
- attributes: {
- [ ATTRIBUTES.footnoteSection ]: true
- }
- },
- model: ELEMENTS.footnoteSection,
- converterPriority: 'high'
- } );
-
- // (model → data view)
- conversion.for( 'dataDowncast' ).elementToElement( {
- model: ELEMENTS.footnoteSection,
- view: {
- name: 'ol',
- attributes: {
- [ ATTRIBUTES.footnoteSection ]: '',
- role: 'doc-endnotes'
- },
- classes: [ CLASSES.footnoteSection, CLASSES.footnotes ]
- }
- } );
-
- // (model → editing view)
- conversion.for( 'editingDowncast' ).elementToElement( {
- model: ELEMENTS.footnoteSection,
- view: ( _, conversionApi ) => {
- const viewWriter = conversionApi.writer;
-
- // eslint-disable-next-line max-len
- /** The below is a div rather than an ol because using an ol here caused weird behavior, including randomly duplicating the footnotes section.
- * This is techincally invalid HTML, but it's valid in the data view (that is, the version shown in the post). I've added role='list'
- * as a next-best option, in accordance with ARIA recommendations.
- */
- const section = viewWriter.createContainerElement( 'div', {
- [ ATTRIBUTES.footnoteSection ]: '',
- role: 'doc-endnotes list',
- class: CLASSES.footnoteSection
- } );
-
- return toWidget( section, viewWriter, { label: 'footnote widget' } );
- }
- } );
-
- /** *********************************Footnote Content Conversion************************************/
-
- conversion.for( 'upcast' ).elementToElement( {
- view: {
- attributes: {
- [ ATTRIBUTES.footnoteContent ]: true
- }
- },
- model: ( viewElement, conversionApi ) => {
- const modelWriter = conversionApi.writer;
-
- return modelWriter.createElement( ELEMENTS.footnoteContent );
- }
- } );
-
- conversion.for( 'dataDowncast' ).elementToElement( {
- model: ELEMENTS.footnoteContent,
- view: {
- name: 'div',
- attributes: { [ ATTRIBUTES.footnoteContent ]: '' },
- classes: [ CLASSES.footnoteContent ]
- }
- } );
-
- conversion.for( 'editingDowncast' ).elementToElement( {
- model: ELEMENTS.footnoteContent,
- view: ( _, conversionApi ) => {
- const viewWriter = conversionApi.writer;
- // Note: You use a more specialized createEditableElement() method here.
- const section = viewWriter.createEditableElement( 'div', {
- [ ATTRIBUTES.footnoteContent ]: '',
- class: CLASSES.footnoteContent
- } );
-
- return toWidgetEditable( section, viewWriter );
- }
- } );
-
- /** *********************************Footnote Item Conversion************************************/
-
- conversion.for( 'upcast' ).elementToElement( {
- view: {
- attributes: {
- [ ATTRIBUTES.footnoteItem ]: true
- }
- },
- model: ( viewElement, conversionApi ) => {
- const modelWriter = conversionApi.writer;
- const id = viewElement.getAttribute( ATTRIBUTES.footnoteId );
- const index = viewElement.getAttribute( ATTRIBUTES.footnoteIndex );
- if ( id === undefined || index === undefined ) {
- return null;
- }
-
- return modelWriter.createElement( ELEMENTS.footnoteItem, {
- [ ATTRIBUTES.footnoteIndex ]: index,
- [ ATTRIBUTES.footnoteId ]: id
- } );
- },
-
- /** converterPriority is needed to supersede the builtin upcastListItemStyle
- * which for unknown reasons causes a null reference error.
- */
- converterPriority: 'high'
- } );
-
- conversion.for( 'dataDowncast' ).elementToElement( {
- model: ELEMENTS.footnoteItem,
- view: createFootnoteItemViewElement
- } );
-
- conversion.for( 'editingDowncast' ).elementToElement( {
- model: ELEMENTS.footnoteItem,
- view: createFootnoteItemViewElement
- } );
-
- /** *********************************Footnote Reference Conversion************************************/
-
- conversion.for( 'upcast' ).elementToElement( {
- view: {
- attributes: {
- [ ATTRIBUTES.footnoteReference ]: true
- }
- },
- model: ( viewElement, conversionApi ) => {
- const modelWriter = conversionApi.writer;
- const index = viewElement.getAttribute( ATTRIBUTES.footnoteIndex );
- const id = viewElement.getAttribute( ATTRIBUTES.footnoteId );
-
- if ( index === undefined || id === undefined ) {
- return null;
- }
-
- return modelWriter.createElement( ELEMENTS.footnoteReference, {
- [ ATTRIBUTES.footnoteIndex ]: index,
- [ ATTRIBUTES.footnoteId ]: id
- } );
- }
- } );
-
- conversion.for( 'editingDowncast' ).elementToElement( {
- model: ELEMENTS.footnoteReference,
- view: ( modelElement, conversionApi ) => {
- const viewWriter = conversionApi.writer;
- const footnoteReferenceViewElement = createFootnoteReferenceViewElement( modelElement, conversionApi );
- return toWidget( footnoteReferenceViewElement, viewWriter );
- }
- } );
-
- conversion.for( 'dataDowncast' ).elementToElement( {
- model: ELEMENTS.footnoteReference,
- view: createFootnoteReferenceViewElement
- } );
-
- /** This is an event listener for changes to the `data-footnote-index` attribute on `footnoteReference` elements.
- * When that event fires, the callback function below updates the displayed view of the footnote reference in the
- * editor to match the new index.
- */
- conversion.for( 'editingDowncast' ).add( dispatcher => {
- dispatcher.on(
- `attribute:${ ATTRIBUTES.footnoteIndex }:${ ELEMENTS.footnoteReference }`,
- ( _, data, conversionApi ) => updateFootnoteReferenceView( data, conversionApi, editor ),
- { priority: 'high' }
- );
- } );
-
- /** *********************************Footnote Back Link Conversion************************************/
-
- conversion.for( 'upcast' ).elementToElement( {
- view: {
- attributes: {
- [ ATTRIBUTES.footnoteBackLink ]: true
- }
- },
- model: ( viewElement, conversionApi ) => {
- const modelWriter = conversionApi.writer;
- const id = viewElement.getAttribute( ATTRIBUTES.footnoteId );
- if ( id === undefined ) {
- return null;
- }
-
- return modelWriter.createElement( ELEMENTS.footnoteBackLink, {
- [ ATTRIBUTES.footnoteId ]: id
- } );
- }
- } );
-
- conversion.for( 'dataDowncast' ).elementToElement( {
- model: ELEMENTS.footnoteBackLink,
- view: createFootnoteBackLinkViewElement
- } );
-
- conversion.for( 'editingDowncast' ).elementToElement( {
- model: ELEMENTS.footnoteBackLink,
- view: createFootnoteBackLinkViewElement
- } );
-};
-
-/**
- * Creates and returns a view element for a footnote backlink,
- * which navigates back to the inline reference in the text. Used
- * for both data and editing downcasts.
- */
-function createFootnoteBackLinkViewElement(
- modelElement: ModelElement,
- conversionApi: DowncastConversionApi
-): ViewContainerElement {
- const viewWriter = conversionApi.writer;
- const id = `${ modelElement.getAttribute( ATTRIBUTES.footnoteId ) }`;
- if ( id === undefined ) {
- throw new Error( 'Footnote return link has no provided Id.' );
- }
-
- const footnoteBackLinkView = viewWriter.createContainerElement( 'span', {
- class: CLASSES.footnoteBackLink,
- [ ATTRIBUTES.footnoteBackLink ]: '',
- [ ATTRIBUTES.footnoteId ]: id
- } );
- const sup = viewWriter.createContainerElement( 'sup' );
- const strong = viewWriter.createContainerElement( 'strong' );
- const anchor = viewWriter.createContainerElement( 'a', { href: `#fnref${ id }` } );
- const innerText = viewWriter.createText( '^' );
-
- viewWriter.insert( viewWriter.createPositionAt( anchor, 0 ), innerText );
- viewWriter.insert( viewWriter.createPositionAt( strong, 0 ), anchor );
- viewWriter.insert( viewWriter.createPositionAt( sup, 0 ), strong );
- viewWriter.insert( viewWriter.createPositionAt( footnoteBackLinkView, 0 ), sup );
-
- return footnoteBackLinkView;
-}
-
-/**
- * Creates and returns a view element for an inline footnote reference. Used for both
- * data downcast and editing downcast conversions.
- */
-function createFootnoteReferenceViewElement(
- modelElement: ModelElement,
- conversionApi: DowncastConversionApi
-): ViewContainerElement {
- const viewWriter = conversionApi.writer;
- const index = `${ modelElement.getAttribute( ATTRIBUTES.footnoteIndex ) }`;
- const id = `${ modelElement.getAttribute( ATTRIBUTES.footnoteId ) }`;
- if ( index === 'undefined' ) {
- throw new Error( 'Footnote reference has no provided index.' );
- }
- if ( id === 'undefined' ) {
- throw new Error( 'Footnote reference has no provided id.' );
- }
-
- const footnoteReferenceView = viewWriter.createContainerElement( 'span', {
- class: CLASSES.footnoteReference,
- [ ATTRIBUTES.footnoteReference ]: '',
- [ ATTRIBUTES.footnoteIndex ]: index,
- [ ATTRIBUTES.footnoteId ]: id,
- role: 'doc-noteref',
- id: `fnref${ id }`
- } );
-
- const innerText = viewWriter.createText( `[${ index }]` );
- const link = viewWriter.createContainerElement( 'a', { href: `#fn${ id }` } );
- const superscript = viewWriter.createContainerElement( 'sup' );
- viewWriter.insert( viewWriter.createPositionAt( link, 0 ), innerText );
- viewWriter.insert( viewWriter.createPositionAt( superscript, 0 ), link );
- viewWriter.insert( viewWriter.createPositionAt( footnoteReferenceView, 0 ), superscript );
-
- return footnoteReferenceView;
-}
-
-/**
- * Creates and returns a view element for an inline footnote reference. Used for both
- * data downcast and editing downcast conversions.
- */
-function createFootnoteItemViewElement(
- modelElement: ModelElement,
- conversionApi: DowncastConversionApi
-): ViewContainerElement {
- const viewWriter = conversionApi.writer;
- const index = modelElement.getAttribute( ATTRIBUTES.footnoteIndex );
- const id = modelElement.getAttribute( ATTRIBUTES.footnoteId );
- if ( !index ) {
- throw new Error( 'Footnote item has no provided index.' );
- }
- if ( !id ) {
- throw new Error( 'Footnote item has no provided id.' );
- }
-
- return viewWriter.createContainerElement( 'li', {
- class: CLASSES.footnoteItem,
- [ ATTRIBUTES.footnoteItem ]: '',
- [ ATTRIBUTES.footnoteIndex ]: `${ index }`,
- [ ATTRIBUTES.footnoteId ]: `${ id }`,
- role: 'doc-endnote',
- id: `fn${ id }`
- } );
-}
-
-/**
- * Triggers when the index attribute of a footnote changes, and
- * updates the editor display of footnote references accordingly.
- */
-function updateFootnoteReferenceView(
- data: {
- item: ModelElement;
- attributeOldValue: string;
- attributeNewValue: string;
- },
- conversionApi: DowncastConversionApi,
- editor: Editor
-) {
- const { item, attributeNewValue: newIndex } = data;
- if (
- !( item instanceof ModelElement ) ||
- !conversionApi.consumable.consume( item, `attribute:${ ATTRIBUTES.footnoteIndex }:${ ELEMENTS.footnoteReference }` )
- ) {
- return;
- }
-
- const footnoteReferenceView = conversionApi.mapper.toViewElement( item );
-
- if ( !footnoteReferenceView ) {
- return;
- }
-
- const viewWriter = conversionApi.writer;
-
- const anchor = viewQueryElement( editor, footnoteReferenceView, element => element.name === 'a' );
- const textNode = anchor?.getChild( 0 );
-
- if ( !textNode || !anchor ) {
- viewWriter.remove( footnoteReferenceView );
- return;
- }
-
- viewWriter.remove( textNode );
- const innerText = viewWriter.createText( `[${ newIndex }]` );
- viewWriter.insert( viewWriter.createPositionAt( anchor, 0 ), innerText );
-
- viewWriter.setAttribute( 'href', `#fn${ item.getAttribute( ATTRIBUTES.footnoteId ) }`, anchor );
- viewWriter.setAttribute( ATTRIBUTES.footnoteIndex, newIndex, footnoteReferenceView );
-}
diff --git a/packages/ckeditor5-footnotes/src/footnote-editing/footnote-editing.ts b/packages/ckeditor5-footnotes/src/footnote-editing/footnote-editing.ts
deleted file mode 100644
index bd19f8d936..0000000000
--- a/packages/ckeditor5-footnotes/src/footnote-editing/footnote-editing.ts
+++ /dev/null
@@ -1,313 +0,0 @@
-/**
- * CKEditor dataview nodes can be converted to a output view or an editor view via downcasting
- * * Upcasting is converting to the platonic ckeditor version.
- * * Downcasting is converting to the output version.
- */
-
-import { addFootnoteAutoformatting } from './auto-formatting.js';
-import { defineConverters } from './converters.js';
-import { defineSchema } from './schema.js';
-
-import { ATTRIBUTES, COMMANDS, ELEMENTS } from '../constants.js';
-import InsertFootnoteCommand from '../insert-footnote-command.js';
-import { modelQueryElement, modelQueryElementsAll } from '../utils.js';
-import { Autoformat, Batch, ModelElement, Plugin, ModelRootElement, viewToModelPositionOutsideModelElement, Widget, ModelWriter } from 'ckeditor5';
-
-export default class FootnoteEditing extends Plugin {
-
- public static get pluginName() {
- return 'FootnotesEditing' as const;
- }
-
- public static get requires() {
- return [ Widget, Autoformat ] as const;
- }
-
- /**
- * The root element of the document.
- */
- public get rootElement(): ModelRootElement {
- const rootElement = this.editor.model.document.getRoot();
- if ( !rootElement ) {
- throw new Error( 'Document has no rootElement element.' );
- }
- return rootElement;
- }
-
- public init(): void {
- defineSchema( this.editor.model.schema );
- defineConverters( this.editor );
-
- this.editor.commands.add( COMMANDS.insertFootnote, new InsertFootnoteCommand( this.editor ) );
-
- addFootnoteAutoformatting( this.editor, this.rootElement );
-
- this.editor.model.document.on(
- 'change:data',
- ( eventInfo, batch ) => {
- const eventSource: any = eventInfo.source;
- const diffItems = [ ...eventSource.differ.getChanges() ];
- // If a footnote reference is inserted, ensure that footnote references remain ordered.
- if ( diffItems.some( diffItem => diffItem.type === 'insert' && diffItem.name === ELEMENTS.footnoteReference ) ) {
- this._orderFootnotes( batch );
- }
- // for each change to a footnote item's index attribute, update the corresponding references accordingly
- diffItems.forEach( diffItem => {
- if ( diffItem.type === 'attribute' && diffItem.attributeKey === ATTRIBUTES.footnoteIndex ) {
- const { attributeNewValue: newFootnoteIndex } = diffItem;
- const footnote = [ ...diffItem.range.getItems() ].find( item => item.is( 'element', ELEMENTS.footnoteItem ) );
- const footnoteId = footnote instanceof ModelElement && footnote.getAttribute( ATTRIBUTES.footnoteId );
- if ( !footnoteId ) {
- return;
- }
- this._updateReferenceIndices( batch, `${ footnoteId }`, newFootnoteIndex );
- }
- } );
- },
- { priority: 'high' }
- );
-
- this._handleDelete();
-
- // The following callbacks are needed to map nonempty view elements
- // to empty model elements.
- // See https://ckeditor.com/docs/ckeditor5/latest/api/module_widget_utils.html#function-viewToModelPositionOutsideModelElement
- this.editor.editing.mapper.on(
- 'viewToModelPosition',
- viewToModelPositionOutsideModelElement( this.editor.model, viewElement =>
- viewElement.hasAttribute( ATTRIBUTES.footnoteReference )
- )
- );
- }
-
- /**
- * This method broadly deals with deletion of text and elements, and updating the model
- * accordingly. In particular, the following cases are handled:
- * 1. If the footnote section gets deleted, all footnote references are removed.
- * 2. If a delete operation happens in an empty footnote, the footnote is deleted.
- */
- private _handleDelete() {
- const viewDocument = this.editor.editing.view.document;
- const editor = this.editor;
- this.listenTo(
- viewDocument,
- 'delete',
- ( evt, data ) => {
- const doc = editor.model.document;
- const deletedElement = doc.selection.getSelectedElement();
- const selectionEndPos = doc.selection.getLastPosition();
- const selectionStartPos = doc.selection.getFirstPosition();
- if ( !selectionEndPos || !selectionStartPos ) {
- throw new Error( 'Selection must have at least one range to perform delete operation.' );
- }
-
- this.editor.model.change( modelWriter => {
- // delete all footnote references if footnote section gets deleted
- if ( deletedElement && deletedElement.is( 'element', ELEMENTS.footnoteSection ) ) {
- this._removeReferences( modelWriter );
- }
-
- const deletingFootnote = deletedElement && deletedElement.is( 'element', ELEMENTS.footnoteItem );
-
- const currentFootnote = deletingFootnote ?
- deletedElement :
- selectionEndPos.findAncestor( ELEMENTS.footnoteItem );
- if ( !currentFootnote ) {
- return;
- }
-
- const endParagraph = selectionEndPos.findAncestor( 'paragraph' );
- const startParagraph = selectionStartPos.findAncestor( 'paragraph' );
- const currentFootnoteContent = selectionEndPos.findAncestor( ELEMENTS.footnoteContent );
- if ( !currentFootnoteContent || !startParagraph || !endParagraph ) {
- return;
- }
-
- const footnoteIsEmpty = startParagraph.maxOffset === 0 && currentFootnoteContent.childCount === 1;
-
- if ( deletingFootnote || footnoteIsEmpty ) {
- this._removeFootnote( modelWriter, currentFootnote );
- data.preventDefault();
- evt.stop();
- }
- } );
- },
- { priority: 'high' }
- );
- }
-
- /**
- * Clear the children of the provided footnoteContent element,
- * leaving an empty paragraph behind. This allows users to empty
- * a footnote without deleting it. modelWriter is passed in to
- * batch these changes with the ones that instantiated them,
- * such that the set can be undone with a single action.
- */
- private _clearContents( modelWriter: ModelWriter, footnoteContent: ModelElement ) {
- const contents = modelWriter.createRangeIn( footnoteContent );
- modelWriter.appendElement( 'paragraph', footnoteContent );
- modelWriter.remove( contents );
- }
-
- /**
- * Removes a footnote and its references, and renumbers subsequent footnotes. When a footnote's
- * id attribute changes, it's references automatically update from a dispatcher event in converters.js,
- * which triggers the `updateReferenceIds` method. modelWriter is passed in to batch these changes with
- * the ones that instantiated them, such that the set can be undone with a single action.
- */
- private _removeFootnote( modelWriter: ModelWriter, footnote: ModelElement ) {
- // delete the current footnote and its references,
- // and renumber subsequent footnotes.
- if ( !this.editor ) {
- return;
- }
- const footnoteSection = footnote.findAncestor( ELEMENTS.footnoteSection );
-
- if ( !footnoteSection ) {
- modelWriter.remove( footnote );
- return;
- }
- const index = footnoteSection.getChildIndex( footnote );
- const id = footnote.getAttribute( ATTRIBUTES.footnoteId );
- this._removeReferences( modelWriter, `${ id }` );
-
- modelWriter.remove( footnote );
- // if no footnotes remain, remove the footnote section
- if ( footnoteSection.childCount === 0 ) {
- modelWriter.remove( footnoteSection );
- this._removeReferences( modelWriter );
- } else {
- if ( index == null ) {
- throw new Error( 'Index is nullish' );
- }
- // after footnote deletion the selection winds up surrounding the previous footnote
- // (or the following footnote if no previous footnote exists). Typing in that state
- // immediately deletes the footnote. This deliberately sets the new selection position
- // to avoid that.
- const neighborFootnote = index === 0 ? footnoteSection.getChild( index ) : footnoteSection.getChild( ( index ?? 0 ) - 1 );
- if ( !( neighborFootnote instanceof ModelElement ) ) {
- return;
- }
-
- const neighborEndParagraph = modelQueryElementsAll( this.editor, neighborFootnote, element =>
- element.is( 'element', 'paragraph' )
- ).pop();
-
- if ( neighborEndParagraph ) {
- modelWriter.setSelection( neighborEndParagraph, 'end' );
- }
- }
- if ( index == null ) {
- throw new Error( 'Index is nullish' );
- }
- // renumber subsequent footnotes
- const subsequentFootnotes = [ ...footnoteSection.getChildren() ].slice( index ?? 0 );
- for ( const [ i, child ] of subsequentFootnotes.entries() ) {
- modelWriter.setAttribute( ATTRIBUTES.footnoteIndex, `${ index ?? 0 + i + 1 }`, child );
- }
- }
-
- /**
- * Deletes all references to the footnote with the given id. If no id is provided,
- * all references are deleted. modelWriter is passed in to batch these changes with
- * the ones that instantiated them, such that the set can be undone with a single action.
- */
- private _removeReferences( modelWriter: ModelWriter, footnoteId: string | undefined = undefined ) {
- const removeList: Array<any> = [];
- if ( !this.rootElement ) {
- throw new Error( 'Document has no root element.' );
- }
- const footnoteReferences = modelQueryElementsAll( this.editor, this.rootElement, e =>
- e.is( 'element', ELEMENTS.footnoteReference )
- );
- footnoteReferences.forEach( footnoteReference => {
- const id = footnoteReference.getAttribute( ATTRIBUTES.footnoteId );
- if ( !footnoteId || id === footnoteId ) {
- removeList.push( footnoteReference );
- }
- } );
- for ( const item of removeList ) {
- modelWriter.remove( item );
- }
- }
-
- /**
- * Updates all references for a single footnote. This function is called when
- * the index attribute of an existing footnote changes, which happens when a footnote
- * with a lower index is deleted. batch is passed in to group these changes with
- * the ones that instantiated them.
- */
- private _updateReferenceIndices( batch: Batch, footnoteId: string, newFootnoteIndex: string ) {
- const footnoteReferences = modelQueryElementsAll(
- this.editor,
- this.rootElement,
- e => e.is( 'element', ELEMENTS.footnoteReference ) && e.getAttribute( ATTRIBUTES.footnoteId ) === footnoteId
- );
- this.editor.model.enqueueChange( batch, writer => {
- footnoteReferences.forEach( footnoteReference => {
- writer.setAttribute( ATTRIBUTES.footnoteIndex, newFootnoteIndex, footnoteReference );
- } );
- } );
- }
-
- /**
- * Reindexes footnotes such that footnote references occur in order, and reorders
- * footnote items in the footer section accordingly. batch is passed in to group changes with
- * the ones that instantiated them.
- */
- private _orderFootnotes( batch: Batch ) {
- const footnoteReferences = modelQueryElementsAll( this.editor, this.rootElement, e =>
- e.is( 'element', ELEMENTS.footnoteReference )
- );
- const uniqueIds = new Set( footnoteReferences.map( e => e.getAttribute( ATTRIBUTES.footnoteId ) ) );
- const orderedFootnotes = [ ...uniqueIds ].map( id =>
- modelQueryElement(
- this.editor,
- this.rootElement,
- e => e.is( 'element', ELEMENTS.footnoteItem ) && e.getAttribute( ATTRIBUTES.footnoteId ) === id
- )
- );
-
- this.editor.model.enqueueChange( batch, writer => {
- const footnoteSection = modelQueryElement( this.editor, this.rootElement, e =>
- e.is( 'element', ELEMENTS.footnoteSection )
- );
- if ( !footnoteSection ) {
- return;
- }
-
- /**
- * In order to keep footnotes with no existing references at the end of the list,
- * the loop below reverses the list of footnotes with references and inserts them
- * each at the beginning.
- */
- for ( const footnote of orderedFootnotes.reverse() ) {
- if ( footnote ) {
- writer.move( writer.createRangeOn( footnote ), footnoteSection, 0 );
- }
- }
-
- /**
- * once the list is sorted, make one final pass to update footnote indices.
- */
- for ( const footnote of modelQueryElementsAll( this.editor, footnoteSection, e =>
- e.is( 'element', ELEMENTS.footnoteItem )
- ) ) {
- const index = `${ ( footnoteSection?.getChildIndex( footnote ) ?? -1 ) + 1 }`;
- if ( footnote ) {
- writer.setAttribute( ATTRIBUTES.footnoteIndex, index, footnote );
- }
- const id = footnote.getAttribute( ATTRIBUTES.footnoteId );
-
- // /**
- // * unfortunately the following line seems to be necessary, even though updateReferenceIndices
- // * should fire from the attribute change immediately above. It seems that events initiated by
- // * a `change:data` event do not themselves fire another `change:data` event.
- // */
- if ( id ) {
- this._updateReferenceIndices( batch, `${ id }`, `${ index }` );
- }
- }
- } );
- }
-}
diff --git a/packages/ckeditor5-footnotes/src/footnote-editing/schema.ts b/packages/ckeditor5-footnotes/src/footnote-editing/schema.ts
deleted file mode 100644
index b26f8ec2c7..0000000000
--- a/packages/ckeditor5-footnotes/src/footnote-editing/schema.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-// eslint-disable-next-line no-restricted-imports
-import { ModelSchema } from 'ckeditor5';
-import { ATTRIBUTES, ELEMENTS } from '../constants.js';
-
-/**
- * Declares the custom element types used by the footnotes plugin.
- * See here for the meanings of each rule:
- * https://ckeditor.com/docs/ckeditor5/latest/api/module_engine_model_schema-SchemaItemDefinition.html#member-isObject
- */
-export const defineSchema = ( schema: ModelSchema ): void => {
- /**
- * Footnote section at the footer of the document.
- */
- schema.register( ELEMENTS.footnoteSection, {
- isObject: true,
- allowWhere: '$block',
- allowIn: '$root',
- allowChildren: ELEMENTS.footnoteItem,
- allowAttributes: [ ATTRIBUTES.footnoteSection ]
- } );
-
- /**
- * Individual footnote item within the footnote section.
- */
- schema.register( ELEMENTS.footnoteItem, {
- isBlock: true,
- isObject: true,
- allowContentOf: '$root',
- allowAttributes: [ ATTRIBUTES.footnoteSection, ATTRIBUTES.footnoteId, ATTRIBUTES.footnoteIndex ]
- } );
-
- /**
- * Editable footnote item content container.
- */
- schema.register( ELEMENTS.footnoteContent, {
- allowIn: ELEMENTS.footnoteItem,
- allowContentOf: '$root',
- allowAttributes: [ ATTRIBUTES.footnoteSection ]
- } );
-
- /**
- * Inline footnote citation, placed within the main text.
- */
- schema.register( ELEMENTS.footnoteReference, {
- allowWhere: '$text',
- isInline: true,
- isObject: true,
- allowAttributes: [ ATTRIBUTES.footnoteReference, ATTRIBUTES.footnoteId, ATTRIBUTES.footnoteIndex ]
- } );
-
- /**
- * return link which takes you from the footnote to the inline reference.
- */
- schema.register( ELEMENTS.footnoteBackLink, {
- allowIn: ELEMENTS.footnoteItem,
- isInline: true,
- isSelectable: false,
- allowAttributes: [ ATTRIBUTES.footnoteBackLink, ATTRIBUTES.footnoteId ]
- } );
-
- schema.addChildCheck( ( context, childDefinition ) => {
- if ( context.endsWith( ELEMENTS.footnoteContent ) && childDefinition.name === ELEMENTS.footnoteSection ) {
- return false;
- }
- if ( context.endsWith( ELEMENTS.footnoteContent ) && childDefinition.name === 'listItem' ) {
- return false;
- }
- } );
-};
diff --git a/packages/ckeditor5-footnotes/src/footnote-ui.ts b/packages/ckeditor5-footnotes/src/footnote-ui.ts
deleted file mode 100644
index c2e365cba0..0000000000
--- a/packages/ckeditor5-footnotes/src/footnote-ui.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { Plugin, addListToDropdown, createDropdown, SplitButtonView, ViewModel, type ListDropdownItemDefinition, Collection } from 'ckeditor5';
-
-import {
- ATTRIBUTES,
- COMMANDS,
- ELEMENTS,
- TOOLBAR_COMPONENT_NAME
-} from './constants.js';
-import insertFootnoteIcon from '../theme/icons/insert-footnote.svg?raw';
-import { modelQueryElement, modelQueryElementsAll } from './utils.js';
-
-export default class FootnoteUI extends Plugin {
-
- public static get pluginName() {
- return 'FootnoteUI' as const;
- }
-
- public init(): void {
- const editor = this.editor;
- const translate = editor.t;
-
- editor.ui.componentFactory.add( TOOLBAR_COMPONENT_NAME, locale => {
- const dropdownView = createDropdown( locale, SplitButtonView );
- const splitButtonView = dropdownView.buttonView;
-
- // Populate the list in the dropdown with items.
- // addListToDropdown( dropdownView, getDropdownItemsDefinitions( placeholderNames ) );
- const command = editor.commands.get( COMMANDS.insertFootnote );
- if ( !command ) {
- throw new Error( 'Command not found.' );
- }
-
- splitButtonView.set( {
- label: translate( 'Footnote' ),
- icon: insertFootnoteIcon,
- tooltip: true,
- isToggleable: true
- } );
- splitButtonView.bind( 'isOn' ).to( command, 'value', value => !!value );
- splitButtonView.on( 'execute', () => {
- editor.execute( COMMANDS.insertFootnote, {
- footnoteIndex: 0
- } );
- editor.editing.view.focus();
- } );
-
- dropdownView.class = 'ck-tn-dropdown';
- dropdownView.bind( 'isEnabled' ).to( command );
- dropdownView.on(
- 'change:isOpen',
- ( evt, propertyName, newValue ) => {
- dropdownView?.listView?.items.clear();
- if ( newValue ) {
- addListToDropdown(
- dropdownView,
- this.getDropdownItemsDefinitions() as any
- );
- } else {
- dropdownView?.listView?.items.clear();
- const listElement = dropdownView?.listView?.element;
- if ( listElement && listElement.parentNode ) {
- listElement.parentNode.removeChild( listElement );
- }
- }
- }
- );
- // Execute the command when the dropdown item is clicked (executed).
- this.listenTo( dropdownView, 'execute', evt => {
- editor.execute( COMMANDS.insertFootnote, {
- footnoteIndex: ( evt.source as any ).commandParam
- } );
- editor.editing.view.focus();
- } );
-
- return dropdownView;
- } );
- }
-
- public getDropdownItemsDefinitions(): Collection<ListDropdownItemDefinition> {
- const itemDefinitions = new Collection<ListDropdownItemDefinition>();
- const defaultDef: ListDropdownItemDefinition = {
- type: 'button',
- model: new ViewModel( {
- commandParam: 0,
- label: 'New footnote',
- withText: true
- } )
- };
- itemDefinitions.add( defaultDef );
-
- const rootElement = this.editor.model.document.getRoot();
- if ( !rootElement ) {
- throw new Error( 'Document has no root element.' );
- }
-
- const footnoteSection = modelQueryElement(
- this.editor,
- rootElement,
- element => element.is( 'element', ELEMENTS.footnoteSection )
- );
-
- if ( footnoteSection ) {
- const footnoteItems = modelQueryElementsAll(
- this.editor,
- rootElement,
- element => element.is( 'element', ELEMENTS.footnoteItem )
- );
- footnoteItems.forEach( footnote => {
- const index = footnote.getAttribute( ATTRIBUTES.footnoteIndex );
- const definition: ListDropdownItemDefinition = {
- type: 'button',
- model: new ViewModel( {
- commandParam: index,
- label: `Insert footnote ${ index }`,
- withText: true
- } )
- };
-
- itemDefinitions.add( definition );
- } );
- }
-
- return itemDefinitions;
- }
-}
diff --git a/packages/ckeditor5-footnotes/src/footnotes.ts b/packages/ckeditor5-footnotes/src/footnotes.ts
deleted file mode 100644
index 716e109dba..0000000000
--- a/packages/ckeditor5-footnotes/src/footnotes.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { Plugin } from 'ckeditor5';
-import FootnoteEditing from './footnote-editing/footnote-editing.js';
-import FootnoteUI from './footnote-ui.js';
-
-export default class Footnotes extends Plugin {
- public static get pluginName() {
- return 'Footnotes' as const;
- }
-
- public static get requires() {
- return [ FootnoteEditing, FootnoteUI ] as const;
- }
-}
diff --git a/packages/ckeditor5-footnotes/src/index.ts b/packages/ckeditor5-footnotes/src/index.ts
deleted file mode 100644
index b93f1d62cd..0000000000
--- a/packages/ckeditor5-footnotes/src/index.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import insertFootnoteIcon from './../theme/icons/insert-footnote.svg?raw';
-import './augmentation.js';
-import "../theme/footnote.css";
-
-export { default as Footnotes } from './footnotes.js';
-
-export const icons = {
- insertFootnoteIcon
-};
diff --git a/packages/ckeditor5-footnotes/src/insert-footnote-command.ts b/packages/ckeditor5-footnotes/src/insert-footnote-command.ts
deleted file mode 100644
index 27d1a61ed0..0000000000
--- a/packages/ckeditor5-footnotes/src/insert-footnote-command.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import { Command, type ModelElement, type ModelRootElement, type ModelWriter } from "ckeditor5";
-
-import { ATTRIBUTES, ELEMENTS } from './constants.js';
-import { modelQueryElement } from './utils.js';
-
-export default class InsertFootnoteCommand extends Command {
- /**
- * Creates a footnote reference with the given index, and creates a matching
- * footnote if one doesn't already exist. Also creates the footnote section
- * if it doesn't exist. If `footnoteIndex` is 0 (or not provided), the added
- * footnote is given the next unused index--e.g. 7, if 6 footnotes exist so far.
- */
- public override execute( { footnoteIndex }: { footnoteIndex?: number } = { footnoteIndex: 0 } ): void {
- this.editor.model.enqueueChange( modelWriter => {
- const doc = this.editor.model.document;
- const rootElement = doc.getRoot();
- if ( !rootElement ) {
- return;
- }
- const footnoteSection = this._getFootnoteSection( modelWriter, rootElement );
- let index: string | undefined = undefined;
- let id: string | undefined = undefined;
- if ( footnoteIndex === 0 ) {
- index = `${ footnoteSection.maxOffset + 1 }`;
- id = Math.random().toString( 36 ).slice( 2 );
- } else {
- index = `${ footnoteIndex }`;
- const matchingFootnote = modelQueryElement(
- this.editor,
- footnoteSection,
- element =>
- element.is( 'element', ELEMENTS.footnoteItem ) && element.getAttribute( ATTRIBUTES.footnoteIndex ) === index
- );
- if ( matchingFootnote ) {
- id = matchingFootnote.getAttribute( ATTRIBUTES.footnoteId ) as string;
- }
- }
- if ( !id || !index ) {
- return;
- }
- modelWriter.setSelection( doc.selection.getLastPosition() );
- const footnoteReference = modelWriter.createElement( ELEMENTS.footnoteReference, {
- [ ATTRIBUTES.footnoteId ]: id,
- [ ATTRIBUTES.footnoteIndex ]: index
- } );
- this.editor.model.insertContent( footnoteReference );
- modelWriter.setSelection( footnoteReference, 'after' );
- // if referencing an existing footnote
- if ( footnoteIndex !== 0 ) {
- return;
- }
-
- const footnoteContent = modelWriter.createElement( ELEMENTS.footnoteContent );
- const footnoteItem = modelWriter.createElement( ELEMENTS.footnoteItem, {
- [ ATTRIBUTES.footnoteId ]: id,
- [ ATTRIBUTES.footnoteIndex ]: index
- } );
- const footnoteBackLink = modelWriter.createElement( ELEMENTS.footnoteBackLink, { [ ATTRIBUTES.footnoteId ]: id } );
- const p = modelWriter.createElement( 'paragraph' );
- modelWriter.append( p, footnoteContent );
- modelWriter.append( footnoteContent, footnoteItem );
- modelWriter.insert( footnoteBackLink, footnoteItem, 0 );
-
- this.editor.model.insertContent(
- footnoteItem,
- modelWriter.createPositionAt( footnoteSection, footnoteSection.maxOffset )
- );
- } );
- }
-
- /**
- * Called automatically when changes are applied to the document. Sets `isEnabled`
- * to determine whether footnote creation is allowed at the current location.
- */
- public override refresh(): void {
- const model = this.editor.model;
- const lastPosition = model.document.selection.getLastPosition();
- const allowedIn = lastPosition && model.schema.findAllowedParent( lastPosition, ELEMENTS.footnoteReference );
- this.isEnabled = allowedIn !== null;
- }
-
- /**
- * Returns the footnote section if it exists, or creates on if it doesn't.
- */
- private _getFootnoteSection( writer: ModelWriter, rootElement: ModelRootElement ): ModelElement {
- const footnoteSection = modelQueryElement( this.editor, rootElement, element =>
- element.is( 'element', ELEMENTS.footnoteSection )
- );
- if ( footnoteSection ) {
- return footnoteSection;
- }
- const newFootnoteSection = writer.createElement( ELEMENTS.footnoteSection );
- this.editor.model.insertContent( newFootnoteSection, writer.createPositionAt( rootElement, rootElement.maxOffset ) );
- return newFootnoteSection;
- }
-}
diff --git a/packages/ckeditor5-footnotes/src/utils.ts b/packages/ckeditor5-footnotes/src/utils.ts
deleted file mode 100644
index 43dee09366..0000000000
--- a/packages/ckeditor5-footnotes/src/utils.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-import { type Editor, ModelElement, ModelText, ModelTextProxy, ViewElement } from 'ckeditor5';
-
-// There's ample DRY violation in this file; type checking
-// polymorphism without full typescript is just incredibly finicky.
-// I (Jonathan) suspect there's a more elegant solution for this,
-// but I tried a lot of things and none of them worked.
-
-/**
- * Returns an array of all descendant elements of
- * the root for which the provided predicate returns true.
- */
-export const modelQueryElementsAll = (
- editor: Editor,
- rootElement: ModelElement,
- predicate: ( item: ModelElement ) => boolean = _ => true
-): Array<ModelElement> => {
- const range = editor.model.createRangeIn( rootElement );
- const output: Array<ModelElement> = [];
-
- for ( const item of range.getItems() ) {
- if ( !( item instanceof ModelElement ) ) {
- continue;
- }
-
- if ( predicate( item ) ) {
- output.push( item );
- }
- }
- return output;
-};
-
-/**
- * Returns an array of all descendant text nodes and text proxies of
- * the root for which the provided predicate returns true.
- */
-export const modelQueryTextAll = (
- editor: Editor,
- rootElement: ModelElement,
- predicate: ( item: ModelText | ModelTextProxy ) => boolean = _ => true
-): Array<ModelText | ModelTextProxy> => {
- const range = editor.model.createRangeIn( rootElement );
- const output: Array<ModelText | ModelTextProxy> = [];
-
- for ( const item of range.getItems() ) {
- if ( !( item instanceof ModelText || item instanceof ModelTextProxy ) ) {
- continue;
- }
-
- if ( predicate( item ) ) {
- output.push( item );
- }
- }
- return output;
-};
-
-/**
- * Returns the first descendant element of the root for which the provided
- * predicate returns true, or null if no such element is found.
- */
-export const modelQueryElement = (
- editor: Editor,
- rootElement: ModelElement,
- predicate: ( item: ModelElement ) => boolean = _ => true
-): ModelElement | null => {
- const range = editor.model.createRangeIn( rootElement );
-
- for ( const item of range.getItems() ) {
- if ( !( item instanceof ModelElement ) ) {
- continue;
- }
-
- if ( predicate( item ) ) {
- return item;
- }
- }
- return null;
-};
-
-/**
- * Returns the first descendant text node or text proxy of the root for which the provided
- * predicate returns true, or null if no such element is found.
- */
-export const modelQueryText = (
- editor: Editor,
- rootElement: ModelElement,
- predicate: ( item: ModelText | ModelTextProxy ) => boolean = _ => true
-): ModelText | ModelTextProxy | null => {
- const range = editor.model.createRangeIn( rootElement );
-
- for ( const item of range.getItems() ) {
- if ( !( item instanceof ModelText || item instanceof ModelTextProxy ) ) {
- continue;
- }
-
- if ( predicate( item ) ) {
- return item;
- }
- }
- return null;
-};
-
-/**
- * Returns the first descendant element of the root for which the provided
- * predicate returns true, or null if no such element is found.
- */
-export const viewQueryElement = (
- editor: Editor,
- rootElement: ViewElement,
- predicate: ( item: ViewElement ) => boolean = _ => true
-): ViewElement | null => {
- const range = editor.editing.view.createRangeIn( rootElement );
-
- for ( const item of range.getItems() ) {
- if ( !( item instanceof ViewElement ) ) {
- continue;
- }
-
- if ( predicate( item ) ) {
- return item;
- }
- }
- return null;
-};
-
diff --git a/packages/ckeditor5-footnotes/tsconfig.json b/packages/ckeditor5-footnotes/tsconfig.json
deleted file mode 100644
index 303791fc66..0000000000
--- a/packages/ckeditor5-footnotes/tsconfig.json
+++ /dev/null
@@ -1,41 +0,0 @@
-{
- "compilerOptions": {
- /**
- * TypeScript automagically loads typings from all "@types/*" packages if the "compilerOptions.types" array is not defined in
- * this file. However, if some dependencies have "@types/*" packages as their dependencies, they'll also be loaded as well.
- * As a result, TypeScript loaded "@types/node" which we don't want to use, because it allows using Node.js specific APIs that
- * are not available in the browsers.
- *
- * To avoid such issues, we defined this empty "types" to disable automatic inclusion of the "@types/*" packages.
- */
- "types": [],
- "lib": [
- "ES2019", // Must match the "target".
- "ES2020.String",
- "DOM",
- "DOM.Iterable"
- ],
- "noImplicitAny": true,
- "noImplicitOverride": true,
- "composite": true,
- "strict": true,
- "target": "es2019",
- "sourceMap": true,
- "allowJs": true,
- "moduleDetection": "force",
- "moduleResolution": "NodeNext",
- "module": "NodeNext",
- "skipLibCheck": true,
- "noUncheckedSideEffectImports": false,
- "outDir": "out-tsc",
- "typeRoots": [
- "typings",
- "node_modules/@types"
- ]
- },
- "include": [
- "./sample",
- "./src",
- "./typings"
- ]
-}
diff --git a/packages/ckeditor5-footnotes/tsconfig.test.json b/packages/ckeditor5-footnotes/tsconfig.test.json
deleted file mode 100644
index 065d98e49b..0000000000
--- a/packages/ckeditor5-footnotes/tsconfig.test.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "types": [
- "@types/mocha"
- ],
- "sourceMap": true
- },
- "include": [
- "./sample",
- "./src",
- "./tests",
- "./typings"
- ]
-}
diff --git a/packages/ckeditor5-footnotes/typings/ckeditor5-inspector.d.ts b/packages/ckeditor5-footnotes/typings/ckeditor5-inspector.d.ts
deleted file mode 100644
index d50ee49c45..0000000000
--- a/packages/ckeditor5-footnotes/typings/ckeditor5-inspector.d.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-declare module '@ckeditor/ckeditor5-inspector' {
- const inspector: {
- attach( editor: any ): void;
- };
-
- export default inspector;
-}
diff --git a/packages/ckeditor5-footnotes/typings/types.d.ts b/packages/ckeditor5-footnotes/typings/types.d.ts
deleted file mode 100644
index 09be57e1c9..0000000000
--- a/packages/ckeditor5-footnotes/typings/types.d.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-declare module '*.svg?raw' {
- const content: string;
- export default content;
-}
diff --git a/packages/ckeditor5-footnotes/vitest.config.ts b/packages/ckeditor5-footnotes/vitest.config.ts
deleted file mode 100644
index 98b502659b..0000000000
--- a/packages/ckeditor5-footnotes/vitest.config.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * @license Copyright (c) 2023-2024, CKSource Holding sp. z o.o. All rights reserved.
- * For licensing, see LICENSE.md.
- */
-
-import { defineConfig } from 'vitest/config';
-import svg from 'vite-plugin-svgo';
-import { webdriverio } from "@vitest/browser-webdriverio";
-
-export default defineConfig( {
- plugins: [
- svg()
- ],
- test: {
- browser: {
- enabled: true,
- provider: webdriverio(),
- headless: true,
- ui: false,
- instances: [ { browser: 'chrome' } ]
- },
- include: [
- 'tests/**/*.[jt]s'
- ],
- globals: true,
- watch: false,
- passWithNoTests: true,
- coverage: {
- thresholds: {
- lines: 100,
- functions: 100,
- branches: 100,
- statements: 100
- },
- provider: 'v8',
- include: [ 'src/**/*.{ts,tsx}' ],
- exclude: [ '**/*.{test,spec}.{ts,mts,cts,tsx,js,jsx}', '**/*.d.ts' ],
- reporter: [ 'text', 'lcov' ]
- }
- }
-} );
diff --git a/packages/ckeditor5/package.json b/packages/ckeditor5/package.json
index f5a35356dc..f4cfbc4b95 100644
--- a/packages/ckeditor5/package.json
+++ b/packages/ckeditor5/package.json
@@ -15,7 +15,6 @@
},
"dependencies": {
"@triliumnext/commons": "workspace:*",
- "@triliumnext/ckeditor5-footnotes": "workspace:*",
"@triliumnext/ckeditor5-math": "workspace:*",
"@triliumnext/ckeditor5-mermaid": "workspace:*",
"ckeditor5": "48.3.1"
diff --git a/packages/ckeditor5/src/extra_slash_commands.ts b/packages/ckeditor5/src/extra_slash_commands.ts
index 28c430b54c..70d30ea968 100644
--- a/packages/ckeditor5/src/extra_slash_commands.ts
+++ b/packages/ckeditor5/src/extra_slash_commands.ts
@@ -1,5 +1,5 @@
import type { Editor } from 'ckeditor5';
-import { icons as footnoteIcons } from '@triliumnext/ckeditor5-footnotes';
+import insertFootnoteIcon from './icons/insert-footnote.svg?raw';
import { IconPageBreak, IconAlignLeft, IconAlignCenter, IconAlignRight, IconAlignJustify, IconBulletedList, IconNumberedList, IconTodoList } from "@ckeditor/ckeditor5-icons";
import bxInfoCircle from "boxicons/svg/regular/bx-info-circle.svg?raw";
import bxBulb from "boxicons/svg/regular/bx-bulb.svg?raw";
@@ -52,7 +52,7 @@ export default function buildExtraCommands(
id: 'footnote',
title: 'Footnote',
description: t("slash_commands.footnote_description"),
- icon: footnoteIcons.insertFootnoteIcon,
+ icon: insertFootnoteIcon,
commandName: "InsertFootnote"
},
{
diff --git a/packages/ckeditor5-footnotes/theme/icons/insert-footnote.svg b/packages/ckeditor5/src/icons/insert-footnote.svg
similarity index 100%
rename from packages/ckeditor5-footnotes/theme/icons/insert-footnote.svg
rename to packages/ckeditor5/src/icons/insert-footnote.svg
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index fc89068d7e..0300d1c6e2 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -27,7 +27,7 @@ import Kbd from "./plugins/keyboard_marker/keyboard_marker.js";
import { Mermaid } from "@triliumnext/ckeditor5-mermaid";
import Admonition from "./plugins/admonition/admonition.js";
import Collapsible from "./plugins/collapsible/collapsible.js";
-import { Footnotes } from "@triliumnext/ckeditor5-footnotes";
+import Footnotes from "./plugins/footnotes/footnotes.js";
import { Math, AutoformatMath } from "@triliumnext/ckeditor5-math";
import CopyAnchorLinkButton from "./plugins/copy_anchor_link.js";
import CopyLinkUrlButton from "./plugins/copy_link_url.js";
@@ -35,7 +35,6 @@ import ImageActions from "./plugins/image_actions.js";
import TriliumSnippets from "./plugins/snippets/snippets.js";
// import "@triliumnext/ckeditor5-mermaid/index.css";
-// import "@triliumnext/ckeditor5-footnotes/index.css";
// import "@triliumnext/ckeditor5-math/index.css";
import CodeBlockToolbar from "./plugins/code_block_toolbar.js";
import CodeBlockLanguageDropdown from "./plugins/code_block_language_dropdown.js";
diff --git a/packages/ckeditor5-footnotes/LICENSE.md b/packages/ckeditor5/src/plugins/footnotes/LICENSE.md
similarity index 100%
rename from packages/ckeditor5-footnotes/LICENSE.md
rename to packages/ckeditor5/src/plugins/footnotes/LICENSE.md
diff --git a/packages/ckeditor5/src/plugins/footnotes/README.md b/packages/ckeditor5/src/plugins/footnotes/README.md
new file mode 100644
index 0000000000..d71d9edb85
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/README.md
@@ -0,0 +1,50 @@
+# Footnotes
+
+An inline `[n]` reference in the text, paired with a numbered item in a footnote section at the end
+of the document. Typing `[^1]` autoformats into a reference.
+
+| File | Role |
+|---|---|
+| `footnotes.ts` | Glue plugin; also declares the `ckeditor5` module augmentation |
+| `footnote_editing.ts` | Command registration, delete handling, and the renumbering/reordering bookkeeping |
+| `schema.ts` | The five model elements (section, item, content, reference, back link) |
+| `converters.ts` | Upcast/downcast for each element, in both data and editing views |
+| `insert_footnote_command.ts` | The `InsertFootnote` command |
+| `footnote_ui.ts` | The split button and its list of existing footnotes |
+| `auto_formatting.ts` | The `[^n]` markdown-style shorthand |
+| `utils.ts` | Small model/view tree query helpers |
+| `constants.ts` | Element, class, attribute and command name tables |
+
+## Provenance
+
+Forked from [ThomasAitken/ckeditor5-footnotes](https://github.com/ThomasAitken/ckeditor5-footnotes)
+(as the *Technologies used* page in the User Guide records), which is itself highly derivative of
+the [Forum Magnum footnote
+plugin](https://github.com/ForumMagnum/ForumMagnum/tree/master/public/lesswrong-editor/src/ckeditor5-footnote/src),
+copyright (c) 2020 Bohan Niu, **ISC** licensed — see [`LICENSE.md`](./LICENSE.md) next to this file,
+which reproduces the original license in full. ISC is permissive and combines with this
+repository's AGPL-3.0-only license.
+
+Trilium ported the source to TypeScript and to current CKEditor 5 APIs (the `Element` →
+`ModelElement`, `Writer` → `ModelWriter` rename wave, among others); it is not tracked against
+upstream, which targets a much older CKEditor 5.
+
+It lived at `packages/ckeditor5-footnotes` until it was folded into this package — it had no
+consumers outside `@triliumnext/ckeditor5`, was never published, and shipped a
+`ckeditor5-package-generator` scaffold (sample pages, its own ESLint/Stylelint/vitest configs) that
+nothing invoked. Its vitest config declared a 100% coverage gate but the package contained no tests
+at all, and CI never ran it with `--coverage`, so ~1300 lines went unexercised.
+
+Straightened out during the move:
+
+- **Renumbering bug.** `_removeFootnote()` renumbered trailing footnotes with
+ `` `${ index ?? 0 + i + 1 }` ``, which parses as `index ?? (0 + i + 1)`. Since `index` is
+ non-null by that point, *every* trailing footnote was assigned the same number. Now
+ `` `${index + i + 1}` ``.
+- `utils.ts` exported four near-identical query helpers; `modelQueryText` and `modelQueryTextAll`
+ had no callers and are gone.
+- The unused `DATA_FOOTNOTE_ID` constant is gone.
+- Several unreachable guards were dropped rather than papered over with tests: an
+ `editor.plugins.has("Autoformat")` check in a plugin that `requires` Autoformat, a
+ `!index` check on a value built by a template literal, a `this.editor` null check inside a plugin
+ method, and a duplicated "index is nullish" throw.
diff --git a/packages/ckeditor5/src/plugins/footnotes/auto_formatting.spec.ts b/packages/ckeditor5/src/plugins/footnotes/auto_formatting.spec.ts
new file mode 100644
index 0000000000..5a5e39ed1c
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/auto_formatting.spec.ts
@@ -0,0 +1,114 @@
+import { _getModelData as getModelData, _setModelData as setModelData, ClassicEditor, Essentials, Paragraph } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { seedFootnotes } from "../../../test/footnotes-kit.js";
+import { ELEMENTS } from "./constants.js";
+import Footnotes from "./footnotes.js";
+
+/**
+ * Type `text` at the collapsed selection one character at a time, which is what the autoformat
+ * feature observes — it reacts to the `insertText` that completes the pattern.
+ */
+function type(editor: ClassicEditor, text: string): void {
+ for (const character of text) {
+ editor.execute("insertText", { text: character });
+ }
+}
+
+describe("footnote autoformatting", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, Footnotes]);
+ });
+
+ function model(): string {
+ return getModelData(editor.model, { withoutSelection: true });
+ }
+
+ function countOf(elementName: string): number {
+ return model().split(`<${elementName}`).length - 1;
+ }
+
+ it("turns `[^1]` into the first footnote", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+
+ type(editor, "[^1]");
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(1);
+ expect(countOf(ELEMENTS.footnoteReference)).toBe(1);
+ expect(model()).not.toContain("[^1]");
+ });
+
+ it("ignores `[^2]` when no footnote exists yet", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+
+ type(editor, "[^2]");
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(0);
+ expect(model()).toContain("[^2]");
+ });
+
+ it("appends a new footnote when the number is one past the end", () => {
+ seedFootnotes(editor, 1);
+
+ type(editor, "[^2]");
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(2);
+ });
+
+ it("references an existing footnote when the number is in range", () => {
+ seedFootnotes(editor, 2);
+
+ type(editor, "[^1]");
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(2);
+ expect(countOf(ELEMENTS.footnoteReference)).toBe(3);
+ });
+
+ it("ignores a number past the end of the list", () => {
+ seedFootnotes(editor, 1);
+
+ type(editor, "[^9]");
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(1);
+ expect(model()).toContain("[^9]");
+ });
+
+ it("ignores the pattern when the cursor is not at the end of the match", () => {
+ // Written with the writer rather than _setModelData, which would read the brackets as
+ // selection markers and silently drop the pattern from the text.
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (!paragraph?.is("element")) {
+ throw new Error("Expected a paragraph.");
+ }
+ writer.insertText("[^1]bar", paragraph, 0);
+ writer.setSelection(paragraph, "end");
+ });
+
+ // The matcher re-runs, but the cursor no longer sits at the end of the `[^1]` run.
+ type(editor, "x");
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(0);
+ expect(model()).toContain("[^1]");
+ });
+
+ it("does nothing when the insert command is disabled", () => {
+ seedFootnotes(editor, 1);
+ const command = editor.commands.get("InsertFootnote");
+ if (!command) {
+ throw new Error("Command not registered.");
+ }
+ command.forceDisabled("test");
+
+ type(editor, "[^1]");
+
+ expect(countOf(ELEMENTS.footnoteReference)).toBe(1);
+ // Note the matched text is still consumed: the callback returns `undefined` rather than
+ // `false` in this branch, and `inlineAutoformatEditing` only skips its deletion step on an
+ // explicit `false`. Preserved as-is from the original plugin.
+ expect(model()).not.toContain("[^1]");
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/footnotes/auto_formatting.ts b/packages/ckeditor5/src/plugins/footnotes/auto_formatting.ts
new file mode 100644
index 0000000000..415755ce30
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/auto_formatting.ts
@@ -0,0 +1,126 @@
+import { Autoformat, type Editor, inlineAutoformatEditing, type ModelElement, type ModelRange, ModelText, ModelTextProxy } from "ckeditor5";
+
+import { COMMANDS, ELEMENTS } from "./constants.js";
+import { modelQueryElement, modelQueryElementsAll } from "./utils.js";
+
+/**
+ * Adds support for creating footnotes using markdown syntax, e.g. `[^1]`.
+ */
+export const addFootnoteAutoformatting = (editor: Editor, rootElement: ModelElement): void => {
+ const autoformat = editor.plugins.get(Autoformat);
+
+ inlineAutoformatEditing(
+ editor,
+ autoformat,
+ (text) => regexMatchCallback(editor, text),
+ (_writer, ranges: Array<ModelRange>) => formatCallback(ranges, editor, rootElement)
+ );
+};
+
+/**
+ * CKEditor's autoformatting feature (basically find and replace) has two opinionated default modes:
+ * block autoformatting, which replaces the entire line, and inline autoformatting, which expects a
+ * section to be formatted (but, importantly, not removed) surrounded by a pair of delimiters which
+ * get removed.
+ *
+ * Neither is ideal here: the matched text should be replaced with a new element, without deleting
+ * the entire line. `inlineAutoformatEditing` does allow passing a custom callback to handle regex
+ * matching, which also allows specifying which sections to remove and which to pass on to the
+ * formatting callback. This removes the entire matched text, while passing the range of the numeric
+ * text on to the formatting callback.
+ *
+ * If 0 or more than 1 match is found, it returns empty ranges for both format and remove, a no-op.
+ */
+const regexMatchCallback = (
+ editor: Editor,
+ text: string
+): {
+ remove: Array<[number, number]>;
+ format: Array<[number, number]>;
+} => {
+ const noMatch = { remove: [], format: [] };
+ const selectionStart = editor.model.document.selection.anchor;
+ // Get the text node containing the cursor's position, or the one ending at it.
+ const surroundingText = selectionStart && (selectionStart.textNode || selectionStart.getShiftedBy(-1).textNode);
+
+ /* v8 ignore next 3 -- defensive: the matcher only runs off typed text, so the selection
+ anchor always sits in or right after a text node */
+ if (!selectionStart || !surroundingText) {
+ return noMatch;
+ }
+
+ for (const result of text.matchAll(/\[\^([0-9]+)\]/g)) {
+ const removeStartIndex = text.indexOf(result[0]);
+ const removeEndIndex = removeStartIndex + result[0].length;
+ const textNodeOffset = selectionStart.parent.getChildStartOffset(surroundingText);
+
+ // If the cursor isn't at the end of the range to be replaced, do nothing.
+ if (textNodeOffset === null || selectionStart.offset !== textNodeOffset + removeEndIndex) {
+ continue;
+ }
+
+ const formatStartIndex = removeStartIndex + 2;
+ const formatEndIndex = formatStartIndex + result[1].length;
+ return {
+ remove: [[removeStartIndex, removeEndIndex]],
+ format: [[formatStartIndex, formatEndIndex]]
+ };
+ }
+
+ return noMatch;
+};
+
+/**
+ * Takes a range of text passed on by {@link regexMatchCallback} and attempts to insert a
+ * corresponding footnote reference at the current location.
+ *
+ * Footnotes only get inserted if the matching range is an integer between 1 and the number of
+ * existing footnotes + 1.
+ */
+const formatCallback = (
+ ranges: Array<ModelRange>,
+ editor: Editor,
+ rootElement: ModelElement
+): boolean | undefined => {
+ const command = editor.commands.get(COMMANDS.insertFootnote);
+ if (!command || !command.isEnabled) {
+ return;
+ }
+
+ const text = [...ranges[0].getItems()][0];
+ /* v8 ignore next 3 -- defensive: the range handed over by regexMatchCallback always spans the
+ digits it captured, so its first item is always text */
+ if (!(text instanceof ModelTextProxy || text instanceof ModelText)) {
+ return false;
+ }
+
+ // The range handed over by `regexMatchCallback` is exactly the digits captured by its pattern.
+ const footnoteIndex = parseInt(text.data);
+ const footnoteSection = modelQueryElement(editor, rootElement, (element) =>
+ element.is("element", ELEMENTS.footnoteSection)
+ );
+
+ if (!footnoteSection) {
+ if (footnoteIndex !== 1) {
+ return false;
+ }
+ editor.execute(COMMANDS.insertFootnote);
+ return;
+ }
+
+ const footnoteCount = modelQueryElementsAll(editor, footnoteSection, (element) =>
+ element.is("element", ELEMENTS.footnoteItem)
+ ).length;
+
+ if (footnoteIndex === footnoteCount + 1) {
+ editor.execute(COMMANDS.insertFootnote);
+ return;
+ }
+
+ if (footnoteIndex >= 1 && footnoteIndex <= footnoteCount) {
+ editor.execute(COMMANDS.insertFootnote, { footnoteIndex });
+ return;
+ }
+
+ return false;
+};
diff --git a/packages/ckeditor5/src/plugins/footnotes/constants.ts b/packages/ckeditor5/src/plugins/footnotes/constants.ts
new file mode 100644
index 0000000000..278f924d3b
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/constants.ts
@@ -0,0 +1,34 @@
+export const TOOLBAR_COMPONENT_NAME = "footnote";
+
+export const ELEMENTS = {
+ footnoteItem: "footnoteItem",
+ footnoteReference: "footnoteReference",
+ footnoteSection: "footnoteSection",
+ footnoteContent: "footnoteContent",
+ footnoteBackLink: "footnoteBackLink"
+};
+
+export const CLASSES = {
+ footnoteContent: "footnote-content",
+ footnoteItem: "footnote-item",
+ footnoteReference: "footnote-reference",
+ footnoteSection: "footnote-section",
+ footnoteBackLink: "footnote-back-link",
+ footnotes: "footnotes",
+ hidden: "hidden"
+};
+
+export const COMMANDS = {
+ insertFootnote: "InsertFootnote"
+};
+
+export const ATTRIBUTES = {
+ footnoteContent: "data-footnote-content",
+ footnoteId: "data-footnote-id",
+ footnoteIndex: "data-footnote-index",
+ footnoteItem: "data-footnote-item",
+ footnoteReference: "data-footnote-reference",
+ footnoteSection: "data-footnote-section",
+ footnoteBackLink: "data-footnote-back-link",
+ footnoteBackLinkHref: "data-footnote-back-link-href"
+};
diff --git a/packages/ckeditor5/src/plugins/footnotes/converters.spec.ts b/packages/ckeditor5/src/plugins/footnotes/converters.spec.ts
new file mode 100644
index 0000000000..a5cfb9a8aa
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/converters.spec.ts
@@ -0,0 +1,167 @@
+import { _getModelData as getModelData, ClassicEditor, Essentials, type ModelElement, Paragraph } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { seedFootnotes } from "../../../test/footnotes-kit.js";
+import { ATTRIBUTES, CLASSES, ELEMENTS } from "./constants.js";
+import Footnotes from "./footnotes.js";
+
+describe("footnote converters", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, Footnotes]);
+ });
+
+ function model(): string {
+ return getModelData(editor.model, { withoutSelection: true });
+ }
+
+ describe("data downcast", () => {
+ it("writes the section as an ol with the endnotes role", () => {
+ seedFootnotes(editor, 1);
+
+ const data = editor.getData();
+
+ expect(data).toContain(`<ol class="${CLASSES.footnoteSection} ${CLASSES.footnotes}"`);
+ expect(data).toContain(`role="doc-endnotes"`);
+ });
+
+ it("writes each item as an li carrying its id and index", () => {
+ seedFootnotes(editor, 1);
+
+ const data = editor.getData();
+
+ expect(data).toContain(`<li class="${CLASSES.footnoteItem}"`);
+ expect(data).toContain(`id="fnid1"`);
+ expect(data).toContain(`role="doc-endnote"`);
+ });
+
+ it("writes the reference as a superscript link back to the item", () => {
+ seedFootnotes(editor, 1);
+
+ const data = editor.getData();
+
+ expect(data).toContain(`class="${CLASSES.footnoteReference}"`);
+ expect(data).toContain(`role="doc-noteref"`);
+ expect(data).toContain(`id="fnrefid1"`);
+ expect(data).toContain(`<sup><a href="#fnid1">[1]</a></sup>`);
+ });
+
+ it("writes the back link as a caret linking to the reference", () => {
+ seedFootnotes(editor, 1);
+
+ const data = editor.getData();
+
+ expect(data).toContain(`class="${CLASSES.footnoteBackLink}"`);
+ expect(data).toContain(`<a href="#fnrefid1">^</a>`);
+ });
+
+ it("writes the content container", () => {
+ seedFootnotes(editor, 1);
+
+ expect(editor.getData()).toContain(`class="${CLASSES.footnoteContent}"`);
+ });
+ });
+
+ describe("upcast", () => {
+ it("reads a full footnote structure back into the model", () => {
+ seedFootnotes(editor, 1);
+ const data = editor.getData();
+
+ editor.setData(data);
+
+ expect(model()).toContain(`<${ELEMENTS.footnoteSection}>`);
+ expect(model()).toContain(`${ATTRIBUTES.footnoteId}="id1"`);
+ expect(model()).toContain(`<${ELEMENTS.footnoteBackLink}`);
+ });
+
+ it("drops a footnote item that is missing its id or index", () => {
+ editor.setData(
+ `<ol ${ATTRIBUTES.footnoteSection}="" class="${CLASSES.footnoteSection}">` +
+ `<li ${ATTRIBUTES.footnoteItem}="" ${ATTRIBUTES.footnoteIndex}="1">no id</li>` +
+ `</ol>`
+ );
+
+ expect(model()).not.toContain(`<${ELEMENTS.footnoteItem}`);
+ });
+
+ it("drops a reference that is missing its id or index", () => {
+ editor.setData(
+ `<p>text<span ${ATTRIBUTES.footnoteReference}="" ${ATTRIBUTES.footnoteIndex}="1"></span></p>`
+ );
+
+ expect(model()).not.toContain(`<${ELEMENTS.footnoteReference}`);
+ });
+
+ it("drops a back link that is missing its id", () => {
+ editor.setData(
+ `<ol ${ATTRIBUTES.footnoteSection}="" class="${CLASSES.footnoteSection}">` +
+ `<li ${ATTRIBUTES.footnoteItem}="" ${ATTRIBUTES.footnoteId}="a" ${ATTRIBUTES.footnoteIndex}="1">` +
+ `<span ${ATTRIBUTES.footnoteBackLink}=""></span>` +
+ `<div ${ATTRIBUTES.footnoteContent}=""><p>x</p></div>` +
+ `</li></ol>`
+ );
+
+ expect(model()).not.toContain(`<${ELEMENTS.footnoteBackLink}`);
+ });
+ });
+
+ describe("downcast failure modes", () => {
+ function insertBareElement(name: string, attributes: Record<string, string> = {}): ModelElement {
+ return editor.model.change((writer) => {
+ const root = editor.model.document.getRoot();
+ const section = writer.createElement(ELEMENTS.footnoteSection);
+ writer.insert(section, writer.createPositionAt(root ?? section, "end"));
+ const element = writer.createElement(name, attributes);
+ writer.insert(element, section, 0);
+ return element;
+ });
+ }
+
+ it("throws when a footnote item has no index", () => {
+ expect(() => insertBareElement(ELEMENTS.footnoteItem, { [ATTRIBUTES.footnoteId]: "a" }))
+ .toThrow("Footnote item has no provided index.");
+ });
+
+ it("throws when a footnote item has no id", () => {
+ expect(() => insertBareElement(ELEMENTS.footnoteItem, { [ATTRIBUTES.footnoteIndex]: "1" }))
+ .toThrow("Footnote item has no provided id.");
+ });
+
+ function insertBareReference(attributes: Record<string, string> = {}): void {
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (!paragraph?.is("element")) {
+ throw new Error("Expected a paragraph.");
+ }
+ writer.insert(writer.createElement(ELEMENTS.footnoteReference, attributes), paragraph, 0);
+ });
+ }
+
+ it("throws when a footnote reference has no index", () => {
+ expect(() => insertBareReference({ [ATTRIBUTES.footnoteId]: "a" }))
+ .toThrow("Footnote reference has no provided index.");
+ });
+
+ it("throws when a footnote reference has no id", () => {
+ expect(() => insertBareReference({ [ATTRIBUTES.footnoteIndex]: "1" }))
+ .toThrow("Footnote reference has no provided id.");
+ });
+ });
+
+ describe("reference index updates", () => {
+ it("rewrites the reference text and href when the footnote index changes", () => {
+ const { items, references } = seedFootnotes(editor, 2);
+
+ editor.model.change((writer) => {
+ writer.setAttribute(ATTRIBUTES.footnoteIndex, "7", items[0]);
+ });
+
+ expect(references[0].getAttribute(ATTRIBUTES.footnoteIndex)).toBe("7");
+
+ const viewReference = editor.editing.mapper.toViewElement(references[0]);
+ expect(viewReference?.getAttribute(ATTRIBUTES.footnoteIndex)).toBe("7");
+ });
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/footnotes/converters.ts b/packages/ckeditor5/src/plugins/footnotes/converters.ts
new file mode 100644
index 0000000000..1fdbc42b46
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/converters.ts
@@ -0,0 +1,365 @@
+import { type DowncastConversionApi, type Editor, ModelElement, toWidget, toWidgetEditable, type ViewContainerElement } from "ckeditor5";
+
+import { ATTRIBUTES, CLASSES, ELEMENTS } from "./constants.js";
+import { viewQueryElement } from "./utils.js";
+
+/**
+ * Defines methods for converting between model, data view, and editing view representations of
+ * each element type.
+ */
+export const defineConverters = (editor: Editor): void => {
+ const conversion = editor.conversion;
+
+ /* Attribute conversion */
+
+ conversion.for("downcast").attributeToAttribute({
+ model: ATTRIBUTES.footnoteId,
+ view: ATTRIBUTES.footnoteId
+ });
+
+ conversion.for("downcast").attributeToAttribute({
+ model: ATTRIBUTES.footnoteIndex,
+ view: ATTRIBUTES.footnoteIndex
+ });
+
+ /* Footnote section */
+
+ // (data view -> model)
+ conversion.for("upcast").elementToElement({
+ view: {
+ attributes: {
+ [ATTRIBUTES.footnoteSection]: true
+ }
+ },
+ model: ELEMENTS.footnoteSection,
+ converterPriority: "high"
+ });
+
+ // (model -> data view)
+ conversion.for("dataDowncast").elementToElement({
+ model: ELEMENTS.footnoteSection,
+ view: {
+ name: "ol",
+ attributes: {
+ [ATTRIBUTES.footnoteSection]: "",
+ role: "doc-endnotes"
+ },
+ classes: [CLASSES.footnoteSection, CLASSES.footnotes]
+ }
+ });
+
+ // (model -> editing view)
+ conversion.for("editingDowncast").elementToElement({
+ model: ELEMENTS.footnoteSection,
+ view: (_, conversionApi) => {
+ const viewWriter = conversionApi.writer;
+
+ /**
+ * The below is a div rather than an ol because using an ol here caused weird behaviour,
+ * including randomly duplicating the footnotes section. This is technically invalid
+ * HTML, but it is valid in the data view (that is, the version shown in the post).
+ * `role='list'` is added as a next-best option, per ARIA recommendations.
+ */
+ const section = viewWriter.createContainerElement("div", {
+ [ATTRIBUTES.footnoteSection]: "",
+ role: "doc-endnotes list",
+ class: CLASSES.footnoteSection
+ });
+
+ return toWidget(section, viewWriter, { label: "footnote widget" });
+ }
+ });
+
+ /* Footnote content */
+
+ conversion.for("upcast").elementToElement({
+ view: {
+ attributes: {
+ [ATTRIBUTES.footnoteContent]: true
+ }
+ },
+ model: (_, conversionApi) => conversionApi.writer.createElement(ELEMENTS.footnoteContent)
+ });
+
+ conversion.for("dataDowncast").elementToElement({
+ model: ELEMENTS.footnoteContent,
+ view: {
+ name: "div",
+ attributes: { [ATTRIBUTES.footnoteContent]: "" },
+ classes: [CLASSES.footnoteContent]
+ }
+ });
+
+ conversion.for("editingDowncast").elementToElement({
+ model: ELEMENTS.footnoteContent,
+ view: (_, conversionApi) => {
+ const viewWriter = conversionApi.writer;
+ // Note: the more specialised createEditableElement() is used here.
+ const section = viewWriter.createEditableElement("div", {
+ [ATTRIBUTES.footnoteContent]: "",
+ class: CLASSES.footnoteContent
+ });
+
+ return toWidgetEditable(section, viewWriter);
+ }
+ });
+
+ /* Footnote item */
+
+ conversion.for("upcast").elementToElement({
+ view: {
+ attributes: {
+ [ATTRIBUTES.footnoteItem]: true
+ }
+ },
+ model: (viewElement, conversionApi) => {
+ const id = viewElement.getAttribute(ATTRIBUTES.footnoteId);
+ const index = viewElement.getAttribute(ATTRIBUTES.footnoteIndex);
+ if (id === undefined || index === undefined) {
+ return null;
+ }
+
+ return conversionApi.writer.createElement(ELEMENTS.footnoteItem, {
+ [ATTRIBUTES.footnoteIndex]: index,
+ [ATTRIBUTES.footnoteId]: id
+ });
+ },
+
+ /**
+ * converterPriority is needed to supersede the built-in upcastListItemStyle which, for
+ * unknown reasons, causes a null reference error.
+ */
+ converterPriority: "high"
+ });
+
+ conversion.for("dataDowncast").elementToElement({
+ model: ELEMENTS.footnoteItem,
+ view: createFootnoteItemViewElement
+ });
+
+ conversion.for("editingDowncast").elementToElement({
+ model: ELEMENTS.footnoteItem,
+ view: createFootnoteItemViewElement
+ });
+
+ /* Footnote reference */
+
+ conversion.for("upcast").elementToElement({
+ view: {
+ attributes: {
+ [ATTRIBUTES.footnoteReference]: true
+ }
+ },
+ model: (viewElement, conversionApi) => {
+ const index = viewElement.getAttribute(ATTRIBUTES.footnoteIndex);
+ const id = viewElement.getAttribute(ATTRIBUTES.footnoteId);
+ if (index === undefined || id === undefined) {
+ return null;
+ }
+
+ return conversionApi.writer.createElement(ELEMENTS.footnoteReference, {
+ [ATTRIBUTES.footnoteIndex]: index,
+ [ATTRIBUTES.footnoteId]: id
+ });
+ }
+ });
+
+ conversion.for("editingDowncast").elementToElement({
+ model: ELEMENTS.footnoteReference,
+ view: (modelElement, conversionApi) => {
+ const footnoteReferenceViewElement = createFootnoteReferenceViewElement(modelElement, conversionApi);
+ return toWidget(footnoteReferenceViewElement, conversionApi.writer);
+ }
+ });
+
+ conversion.for("dataDowncast").elementToElement({
+ model: ELEMENTS.footnoteReference,
+ view: createFootnoteReferenceViewElement
+ });
+
+ /**
+ * Listens for changes to the `data-footnote-index` attribute on `footnoteReference` elements.
+ * When that fires, the callback updates the displayed view of the footnote reference in the
+ * editor to match the new index.
+ */
+ conversion.for("editingDowncast").add((dispatcher) => {
+ dispatcher.on(
+ `attribute:${ATTRIBUTES.footnoteIndex}:${ELEMENTS.footnoteReference}`,
+ (_, data, conversionApi) => updateFootnoteReferenceView(data, conversionApi, editor),
+ { priority: "high" }
+ );
+ });
+
+ /* Footnote back link */
+
+ conversion.for("upcast").elementToElement({
+ view: {
+ attributes: {
+ [ATTRIBUTES.footnoteBackLink]: true
+ }
+ },
+ model: (viewElement, conversionApi) => {
+ const id = viewElement.getAttribute(ATTRIBUTES.footnoteId);
+ if (id === undefined) {
+ return null;
+ }
+
+ return conversionApi.writer.createElement(ELEMENTS.footnoteBackLink, {
+ [ATTRIBUTES.footnoteId]: id
+ });
+ }
+ });
+
+ conversion.for("dataDowncast").elementToElement({
+ model: ELEMENTS.footnoteBackLink,
+ view: createFootnoteBackLinkViewElement
+ });
+
+ conversion.for("editingDowncast").elementToElement({
+ model: ELEMENTS.footnoteBackLink,
+ view: createFootnoteBackLinkViewElement
+ });
+};
+
+/**
+ * Creates and returns a view element for a footnote backlink, which navigates back to the inline
+ * reference in the text. Used for both data and editing downcasts.
+ */
+function createFootnoteBackLinkViewElement(
+ modelElement: ModelElement,
+ conversionApi: DowncastConversionApi
+): ViewContainerElement {
+ const viewWriter = conversionApi.writer;
+ const id = `${modelElement.getAttribute(ATTRIBUTES.footnoteId)}`;
+
+ const footnoteBackLinkView = viewWriter.createContainerElement("span", {
+ class: CLASSES.footnoteBackLink,
+ [ATTRIBUTES.footnoteBackLink]: "",
+ [ATTRIBUTES.footnoteId]: id
+ });
+ const sup = viewWriter.createContainerElement("sup");
+ const strong = viewWriter.createContainerElement("strong");
+ const anchor = viewWriter.createContainerElement("a", { href: `#fnref${id}` });
+ const innerText = viewWriter.createText("^");
+
+ viewWriter.insert(viewWriter.createPositionAt(anchor, 0), innerText);
+ viewWriter.insert(viewWriter.createPositionAt(strong, 0), anchor);
+ viewWriter.insert(viewWriter.createPositionAt(sup, 0), strong);
+ viewWriter.insert(viewWriter.createPositionAt(footnoteBackLinkView, 0), sup);
+
+ return footnoteBackLinkView;
+}
+
+/**
+ * Creates and returns a view element for an inline footnote reference. Used for both data downcast
+ * and editing downcast conversions.
+ */
+function createFootnoteReferenceViewElement(
+ modelElement: ModelElement,
+ conversionApi: DowncastConversionApi
+): ViewContainerElement {
+ const viewWriter = conversionApi.writer;
+ const index = `${modelElement.getAttribute(ATTRIBUTES.footnoteIndex)}`;
+ const id = `${modelElement.getAttribute(ATTRIBUTES.footnoteId)}`;
+ if (index === "undefined") {
+ throw new Error("Footnote reference has no provided index.");
+ }
+ if (id === "undefined") {
+ throw new Error("Footnote reference has no provided id.");
+ }
+
+ const footnoteReferenceView = viewWriter.createContainerElement("span", {
+ class: CLASSES.footnoteReference,
+ [ATTRIBUTES.footnoteReference]: "",
+ [ATTRIBUTES.footnoteIndex]: index,
+ [ATTRIBUTES.footnoteId]: id,
+ role: "doc-noteref",
+ id: `fnref${id}`
+ });
+
+ const innerText = viewWriter.createText(`[${index}]`);
+ const link = viewWriter.createContainerElement("a", { href: `#fn${id}` });
+ const superscript = viewWriter.createContainerElement("sup");
+ viewWriter.insert(viewWriter.createPositionAt(link, 0), innerText);
+ viewWriter.insert(viewWriter.createPositionAt(superscript, 0), link);
+ viewWriter.insert(viewWriter.createPositionAt(footnoteReferenceView, 0), superscript);
+
+ return footnoteReferenceView;
+}
+
+/**
+ * Creates and returns a view element for a footnote item in the footnote section. Used for both
+ * data downcast and editing downcast conversions.
+ */
+function createFootnoteItemViewElement(
+ modelElement: ModelElement,
+ conversionApi: DowncastConversionApi
+): ViewContainerElement {
+ const index = modelElement.getAttribute(ATTRIBUTES.footnoteIndex);
+ const id = modelElement.getAttribute(ATTRIBUTES.footnoteId);
+ if (!index) {
+ throw new Error("Footnote item has no provided index.");
+ }
+ if (!id) {
+ throw new Error("Footnote item has no provided id.");
+ }
+
+ return conversionApi.writer.createContainerElement("li", {
+ class: CLASSES.footnoteItem,
+ [ATTRIBUTES.footnoteItem]: "",
+ [ATTRIBUTES.footnoteIndex]: `${index}`,
+ [ATTRIBUTES.footnoteId]: `${id}`,
+ role: "doc-endnote",
+ id: `fn${id}`
+ });
+}
+
+/**
+ * Triggers when the index attribute of a footnote changes, and updates the editor display of
+ * footnote references accordingly.
+ */
+function updateFootnoteReferenceView(
+ data: {
+ item: ModelElement;
+ attributeOldValue: string;
+ attributeNewValue: string;
+ },
+ conversionApi: DowncastConversionApi,
+ editor: Editor
+) {
+ const { item, attributeNewValue: newIndex } = data;
+ /* v8 ignore next 6 -- defensive: the dispatcher only fires this for footnoteReference
+ elements, and the high-priority listener always consumes first */
+ if (
+ !(item instanceof ModelElement) ||
+ !conversionApi.consumable.consume(item, `attribute:${ATTRIBUTES.footnoteIndex}:${ELEMENTS.footnoteReference}`)
+ ) {
+ return;
+ }
+
+ const footnoteReferenceView = conversionApi.mapper.toViewElement(item);
+
+ /* v8 ignore next 3 -- defensive: a downcast reference is always mapped to its view element */
+ if (!footnoteReferenceView) {
+ return;
+ }
+
+ const viewWriter = conversionApi.writer;
+
+ const anchor = viewQueryElement(editor, footnoteReferenceView, (element) => element.name === "a");
+ const textNode = anchor?.getChild(0);
+
+ /* v8 ignore next 4 -- defensive: createFootnoteReferenceViewElement always builds the anchor
+ and its text, so a mapped reference view always has both */
+ if (!textNode || !anchor) {
+ viewWriter.remove(footnoteReferenceView);
+ return;
+ }
+
+ viewWriter.remove(textNode);
+ const innerText = viewWriter.createText(`[${newIndex}]`);
+ viewWriter.insert(viewWriter.createPositionAt(anchor, 0), innerText);
+
+ viewWriter.setAttribute("href", `#fn${item.getAttribute(ATTRIBUTES.footnoteId)}`, anchor);
+ viewWriter.setAttribute(ATTRIBUTES.footnoteIndex, newIndex, footnoteReferenceView);
+}
diff --git a/packages/ckeditor5/src/plugins/footnotes/footnote_editing.spec.ts b/packages/ckeditor5/src/plugins/footnotes/footnote_editing.spec.ts
new file mode 100644
index 0000000000..cab48e8465
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/footnote_editing.spec.ts
@@ -0,0 +1,290 @@
+import { _getModelData as getModelData, _setModelData as setModelData, Autoformat, ClassicEditor, Essentials, type ModelElement, Paragraph, Widget } from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { seedFootnotes, selectInFootnoteContent } from "../../../test/footnotes-kit.js";
+import { ATTRIBUTES, COMMANDS, ELEMENTS } from "./constants.js";
+import FootnoteEditing from "./footnote_editing.js";
+import Footnotes from "./footnotes.js";
+
+describe("FootnoteEditing", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, Footnotes]);
+ });
+
+ function model(): string {
+ return getModelData(editor.model, { withoutSelection: true });
+ }
+
+ function countOf(elementName: string): number {
+ return model().split(`<${elementName}`).length - 1;
+ }
+
+ function indicesOf(elementName: string): Array<string> {
+ const pattern = new RegExp(`<${elementName}[^>]*${ATTRIBUTES.footnoteIndex}="([^"]*)"`, "g");
+ return [...model().matchAll(pattern)].map((match) => match[1]);
+ }
+
+ function fireDelete(): void {
+ editor.editing.view.document.fire("delete", {
+ direction: "backward",
+ unit: "character",
+ preventDefault: vi.fn()
+ });
+ }
+
+ /**
+ * Clear a footnote's content and put the collapsed selection in it — the state in which the
+ * plugin itself removes the footnote. (Selecting the item instead leaves the removal to
+ * CKEditor's default delete handling, which does not renumber.)
+ */
+ function emptyAndSelect(item: ModelElement): void {
+ editor.model.change((writer) => {
+ const content = item.getChild(1);
+ const paragraph = content?.is("element") ? content.getChild(0) : null;
+ if (!paragraph?.is("element")) {
+ throw new Error("Footnote item has no content paragraph.");
+ }
+ writer.remove(writer.createRangeIn(paragraph));
+ writer.setSelection(paragraph, 0);
+ });
+ }
+
+ it("declares its name and requirements", () => {
+ expect(FootnoteEditing.pluginName).toBe("FootnotesEditing");
+ expect(FootnoteEditing.requires).toContain(Widget);
+ expect(FootnoteEditing.requires).toContain(Autoformat);
+ });
+
+ it("registers the insert command", () => {
+ expect(editor.commands.get(COMMANDS.insertFootnote)).toBeDefined();
+ });
+
+ describe("rootElement", () => {
+ it("returns the document root", () => {
+ expect(editor.plugins.get(FootnoteEditing).rootElement.rootName).toBe("main");
+ });
+
+ it("throws when the document has no root", () => {
+ const editing = editor.plugins.get(FootnoteEditing);
+ const originalGetRoot = editor.model.document.getRoot.bind(editor.model.document);
+ editor.model.document.getRoot = (() => null) as typeof editor.model.document.getRoot;
+
+ try {
+ expect(() => editing.rootElement).toThrow("Document has no rootElement element.");
+ } finally {
+ editor.model.document.getRoot = originalGetRoot;
+ }
+ });
+ });
+
+ it("maps a view position inside a reference to the model position beside it", () => {
+ const { references } = seedFootnotes(editor, 1);
+ const viewReference = editor.editing.mapper.toViewElement(references[0]);
+ if (!viewReference) {
+ throw new Error("Reference has no view element.");
+ }
+
+ // A footnote reference renders as a non-empty widget over an empty model element, so a
+ // position inside the view element has to map outside the model element rather than into it.
+ const modelPosition = editor.editing.mapper.toModelPosition(
+ editor.editing.view.createPositionAt(viewReference, 0)
+ );
+
+ expect(modelPosition.parent.is("element", "paragraph")).toBe(true);
+ });
+
+ describe("ordering references", () => {
+ it("renumbers footnotes so items follow the order their references appear in", () => {
+ const { items } = seedFootnotes(editor, 2);
+
+ // Insert a reference to the *second* footnote before the existing ones.
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (paragraph?.is("element")) {
+ writer.setSelection(paragraph, 0);
+ }
+ });
+ editor.execute(COMMANDS.insertFootnote, { footnoteIndex: 2 });
+
+ // The footnote that is now referenced first must be numbered 1.
+ expect(items[1].getAttribute(ATTRIBUTES.footnoteIndex)).toBe("1");
+ expect(items[0].getAttribute(ATTRIBUTES.footnoteIndex)).toBe("2");
+ });
+
+ it("tolerates a reference whose footnote item does not exist", () => {
+ // Loaded content can carry a reference with no matching item; ordering must skip it
+ // rather than fail.
+ seedFootnotes(editor, 1);
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (!paragraph?.is("element")) {
+ throw new Error("Expected a paragraph.");
+ }
+ writer.insert(writer.createElement(ELEMENTS.footnoteReference, {
+ [ATTRIBUTES.footnoteId]: "missing",
+ [ATTRIBUTES.footnoteIndex]: "9"
+ }), paragraph, 0);
+ });
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(1);
+ expect(indicesOf(ELEMENTS.footnoteItem)).toEqual(["1"]);
+ });
+
+ it("keeps each reference's index in step with its footnote", () => {
+ seedFootnotes(editor, 2);
+
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (paragraph?.is("element")) {
+ writer.setSelection(paragraph, 0);
+ }
+ });
+ editor.execute(COMMANDS.insertFootnote, { footnoteIndex: 2 });
+
+ const itemIndices = indicesOf(ELEMENTS.footnoteItem);
+ const referenceIndices = indicesOf(ELEMENTS.footnoteReference);
+
+ expect(itemIndices).toEqual(["1", "2"]);
+ // Three references: the newly inserted one, then the two seeded ones.
+ expect(referenceIndices).toEqual(["1", "2", "1"]);
+ });
+ });
+
+ describe("deleting", () => {
+ it("removes an empty footnote and its reference on backspace", () => {
+ const { items } = seedFootnotes(editor, 1);
+ editor.model.change((writer) => {
+ const content = items[0].getChild(1);
+ const paragraph = content?.is("element") ? content.getChild(0) : null;
+ if (paragraph?.is("element")) {
+ writer.remove(writer.createRangeIn(paragraph));
+ writer.setSelection(paragraph, 0);
+ }
+ });
+
+ fireDelete();
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(0);
+ expect(countOf(ELEMENTS.footnoteSection)).toBe(0);
+ expect(countOf(ELEMENTS.footnoteReference)).toBe(0);
+ });
+
+ it("leaves a non-empty footnote alone", () => {
+ const { items } = seedFootnotes(editor, 1);
+ selectInFootnoteContent(editor, items[0]);
+
+ fireDelete();
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(1);
+ });
+
+ it("does nothing when the selection is outside any footnote", () => {
+ seedFootnotes(editor, 1);
+
+ fireDelete();
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(1);
+ });
+
+ it("removes every reference when the whole footnote section is deleted", () => {
+ const { section } = seedFootnotes(editor, 2);
+ editor.model.change((writer) => writer.setSelection(section, "on"));
+
+ fireDelete();
+
+ expect(countOf(ELEMENTS.footnoteReference)).toBe(0);
+ });
+
+ it("renumbers the footnotes after the one that was emptied and removed", () => {
+ const { items } = seedFootnotes(editor, 3);
+ emptyAndSelect(items[0]);
+
+ fireDelete();
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(2);
+ // The two survivors renumber to 1 and 2 — this is the case the old
+ // `index ?? 0 + i + 1` precedence bug got wrong, leaving both at the same number.
+ expect(indicesOf(ELEMENTS.footnoteItem)).toEqual(["1", "2"]);
+ });
+
+ it("renumbers correctly when a middle footnote is removed", () => {
+ const { items } = seedFootnotes(editor, 3);
+ emptyAndSelect(items[1]);
+
+ fireDelete();
+
+ expect(indicesOf(ELEMENTS.footnoteItem)).toEqual(["1", "2"]);
+ });
+
+ it("keeps the section when other footnotes remain", () => {
+ const { items } = seedFootnotes(editor, 2);
+ editor.model.change((writer) => writer.setSelection(items[1], "on"));
+
+ fireDelete();
+
+ expect(countOf(ELEMENTS.footnoteSection)).toBe(1);
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(1);
+ });
+
+ it("removes an emptied footnote that is not inside a section", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ editor.model.change((writer) => {
+ const root = editor.model.document.getRoot();
+ const item = writer.createElement(ELEMENTS.footnoteItem, {
+ [ATTRIBUTES.footnoteId]: "orphan",
+ [ATTRIBUTES.footnoteIndex]: "1"
+ });
+ const content = writer.createElement(ELEMENTS.footnoteContent);
+ const paragraph = writer.createElement("paragraph");
+ writer.insert(paragraph, content, 0);
+ writer.insert(content, item, 0);
+ writer.insert(item, writer.createPositionAt(root ?? item, "end"));
+ writer.setSelection(paragraph, 0);
+ });
+
+ fireDelete();
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(0);
+ });
+
+ it("removes a footnote that is not inside a section", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ const orphan = editor.model.change((writer) => {
+ const root = editor.model.document.getRoot();
+ const item = writer.createElement(ELEMENTS.footnoteItem, {
+ [ATTRIBUTES.footnoteId]: "orphan",
+ [ATTRIBUTES.footnoteIndex]: "1"
+ });
+ const content = writer.createElement(ELEMENTS.footnoteContent);
+ const paragraph = writer.createElement("paragraph");
+ writer.insert(paragraph, content, 0);
+ writer.insert(content, item, 0);
+ writer.insert(item, writer.createPositionAt(root ?? item, "end"));
+ writer.setSelection(item, "on");
+ return item;
+ });
+
+ expect(orphan.findAncestor(ELEMENTS.footnoteSection)).toBeNull();
+
+ fireDelete();
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(0);
+ });
+
+ it("throws when the selection has no range", () => {
+ seedFootnotes(editor, 1);
+ const selection = editor.model.document.selection;
+ const originalGetLastPosition = selection.getLastPosition.bind(selection);
+ selection.getLastPosition = (() => null) as typeof selection.getLastPosition;
+
+ try {
+ expect(() => fireDelete()).toThrow("Selection must have at least one range");
+ } finally {
+ selection.getLastPosition = originalGetLastPosition;
+ }
+ });
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/footnotes/footnote_editing.ts b/packages/ckeditor5/src/plugins/footnotes/footnote_editing.ts
new file mode 100644
index 0000000000..5829121742
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/footnote_editing.ts
@@ -0,0 +1,291 @@
+import { Autoformat, type Batch, ModelElement, type ModelRootElement, type ModelWriter, Plugin, viewToModelPositionOutsideModelElement, Widget } from "ckeditor5";
+
+import { addFootnoteAutoformatting } from "./auto_formatting.js";
+import { ATTRIBUTES, COMMANDS, ELEMENTS } from "./constants.js";
+import { defineConverters } from "./converters.js";
+import InsertFootnoteCommand from "./insert_footnote_command.js";
+import { defineSchema } from "./schema.js";
+import { modelQueryElement, modelQueryElementsAll } from "./utils.js";
+
+/**
+ * Owns the footnote model: schema, conversion, the insert command, and the bookkeeping that keeps
+ * footnote items and their inline references numbered consistently as the document changes.
+ */
+export default class FootnoteEditing extends Plugin {
+
+ public static get pluginName() {
+ return "FootnotesEditing" as const;
+ }
+
+ public static get requires() {
+ return [Widget, Autoformat] as const;
+ }
+
+ /**
+ * The root element of the document.
+ */
+ public get rootElement(): ModelRootElement {
+ const rootElement = this.editor.model.document.getRoot();
+ if (!rootElement) {
+ throw new Error("Document has no rootElement element.");
+ }
+ return rootElement;
+ }
+
+ public init(): void {
+ defineSchema(this.editor.model.schema);
+ defineConverters(this.editor);
+
+ this.editor.commands.add(COMMANDS.insertFootnote, new InsertFootnoteCommand(this.editor));
+
+ addFootnoteAutoformatting(this.editor, this.rootElement);
+
+ this.editor.model.document.on("change:data", (_evt, batch) => {
+ const differ = this.editor.model.document.differ;
+ const diffItems = [...differ.getChanges()];
+
+ // If a footnote reference is inserted, ensure that footnote references remain ordered.
+ if (diffItems.some((diffItem) => diffItem.type === "insert" && diffItem.name === ELEMENTS.footnoteReference)) {
+ this._orderFootnotes(batch);
+ }
+
+ // For each change to a footnote item's index attribute, update the matching references.
+ diffItems.forEach((diffItem) => {
+ if (diffItem.type !== "attribute" || diffItem.attributeKey !== ATTRIBUTES.footnoteIndex) {
+ return;
+ }
+
+ const { attributeNewValue: newFootnoteIndex } = diffItem;
+ const footnote = [...diffItem.range.getItems()].find((item) => item.is("element", ELEMENTS.footnoteItem));
+ const footnoteId = footnote instanceof ModelElement && footnote.getAttribute(ATTRIBUTES.footnoteId);
+ if (!footnoteId) {
+ return;
+ }
+
+ this._updateReferenceIndices(batch, `${footnoteId}`, `${newFootnoteIndex}`);
+ });
+ }, { priority: "high" });
+
+ this._handleDelete();
+
+ // The following callback is needed to map nonempty view elements to empty model elements.
+ // See https://ckeditor.com/docs/ckeditor5/latest/api/module_widget_utils.html#function-viewToModelPositionOutsideModelElement
+ this.editor.editing.mapper.on(
+ "viewToModelPosition",
+ viewToModelPositionOutsideModelElement(this.editor.model, (viewElement) =>
+ viewElement.hasAttribute(ATTRIBUTES.footnoteReference)
+ )
+ );
+ }
+
+ /**
+ * Deals with deletion of text and elements, and updating the model accordingly. In particular:
+ * 1. If the footnote section gets deleted, all footnote references are removed.
+ * 2. If a delete operation happens in an empty footnote, the footnote is deleted.
+ */
+ private _handleDelete() {
+ const viewDocument = this.editor.editing.view.document;
+ const editor = this.editor;
+
+ this.listenTo(viewDocument, "delete", (evt, data) => {
+ const doc = editor.model.document;
+ const deletedElement = doc.selection.getSelectedElement();
+ const selectionEndPos = doc.selection.getLastPosition();
+ const selectionStartPos = doc.selection.getFirstPosition();
+ if (!selectionEndPos || !selectionStartPos) {
+ throw new Error("Selection must have at least one range to perform delete operation.");
+ }
+
+ this.editor.model.change((modelWriter) => {
+ // Delete all footnote references if the footnote section gets deleted.
+ if (deletedElement && deletedElement.is("element", ELEMENTS.footnoteSection)) {
+ this._removeReferences(modelWriter);
+ }
+
+ const deletingFootnote = Boolean(deletedElement && deletedElement.is("element", ELEMENTS.footnoteItem));
+
+ const currentFootnote = deletingFootnote && deletedElement ?
+ deletedElement :
+ selectionEndPos.findAncestor(ELEMENTS.footnoteItem);
+ if (!currentFootnote) {
+ return;
+ }
+
+ const endParagraph = selectionEndPos.findAncestor("paragraph");
+ const startParagraph = selectionStartPos.findAncestor("paragraph");
+ const currentFootnoteContent = selectionEndPos.findAncestor(ELEMENTS.footnoteContent);
+ if (!currentFootnoteContent || !startParagraph || !endParagraph) {
+ return;
+ }
+
+ const footnoteIsEmpty = startParagraph.maxOffset === 0 && currentFootnoteContent.childCount === 1;
+
+ if (deletingFootnote || footnoteIsEmpty) {
+ this._removeFootnote(modelWriter, currentFootnote);
+ data.preventDefault();
+ evt.stop();
+ }
+ });
+ }, { priority: "high" });
+ }
+
+ /**
+ * Removes a footnote and its references, and renumbers subsequent footnotes. When a footnote's
+ * id attribute changes, its references automatically update from a dispatcher event in
+ * converters.ts, which triggers `_updateReferenceIndices`. `modelWriter` is passed in to batch
+ * these changes with the ones that instantiated them, so the set undoes as a single action.
+ */
+ private _removeFootnote(modelWriter: ModelWriter, footnote: ModelElement) {
+ const footnoteSection = footnote.findAncestor(ELEMENTS.footnoteSection);
+
+ /* v8 ignore next 4 -- defensive: the schema only allows a footnote item inside a section,
+ so a sectionless footnote cannot be reached through the editor */
+ if (!footnoteSection) {
+ modelWriter.remove(footnote);
+ return;
+ }
+
+ /* v8 ignore next -- defensive: findAncestor() returned this section, so the footnote is
+ one of its children */
+ const index = footnoteSection.getChildIndex(footnote) ?? 0;
+
+ const id = footnote.getAttribute(ATTRIBUTES.footnoteId);
+ this._removeReferences(modelWriter, `${id}`);
+
+ modelWriter.remove(footnote);
+
+ // If no footnotes remain, remove the footnote section.
+ if (footnoteSection.childCount === 0) {
+ modelWriter.remove(footnoteSection);
+ this._removeReferences(modelWriter);
+ } else {
+ // After footnote deletion the selection winds up surrounding the previous footnote (or
+ // the following one if no previous footnote exists). Typing in that state immediately
+ // deletes the footnote, so the selection is deliberately moved to avoid that.
+ // The section is non-empty, so this child always exists: either the footnote that
+ // shifted into the removed one's slot, or the one before it.
+ const neighborFootnote = footnoteSection.getChild(index === 0 ? index : index - 1);
+
+ /* v8 ignore next -- defensive: the branch above guarantees a remaining sibling */
+ if (neighborFootnote instanceof ModelElement) {
+ const neighborEndParagraph = modelQueryElementsAll(this.editor, neighborFootnote, (element) =>
+ element.is("element", "paragraph")
+ ).pop();
+
+ if (neighborEndParagraph) {
+ modelWriter.setSelection(neighborEndParagraph, "end");
+ }
+ }
+ }
+
+ // Renumber subsequent footnotes.
+ const subsequentFootnotes = [...footnoteSection.getChildren()].slice(index);
+ for (const [i, child] of subsequentFootnotes.entries()) {
+ modelWriter.setAttribute(ATTRIBUTES.footnoteIndex, `${index + i + 1}`, child);
+ }
+ }
+
+ /**
+ * Deletes all references to the footnote with the given id. If no id is provided, all
+ * references are deleted. `modelWriter` is passed in to batch these changes with the ones that
+ * instantiated them, so the set undoes as a single action.
+ */
+ private _removeReferences(modelWriter: ModelWriter, footnoteId: string | undefined = undefined) {
+ const footnoteReferences = modelQueryElementsAll(this.editor, this.rootElement, (element) =>
+ element.is("element", ELEMENTS.footnoteReference)
+ );
+
+ for (const footnoteReference of footnoteReferences) {
+ const id = footnoteReference.getAttribute(ATTRIBUTES.footnoteId);
+ if (!footnoteId || id === footnoteId) {
+ modelWriter.remove(footnoteReference);
+ }
+ }
+ }
+
+ /**
+ * Updates all references for a single footnote. Called when the index attribute of an existing
+ * footnote changes, which happens when a footnote with a lower index is deleted. `batch` is
+ * passed in to group these changes with the ones that instantiated them.
+ */
+ private _updateReferenceIndices(batch: Batch, footnoteId: string, newFootnoteIndex: string) {
+ const footnoteReferences = modelQueryElementsAll(
+ this.editor,
+ this.rootElement,
+ (element) => element.is("element", ELEMENTS.footnoteReference) &&
+ element.getAttribute(ATTRIBUTES.footnoteId) === footnoteId
+ );
+
+ this.editor.model.enqueueChange(batch, (writer) => {
+ footnoteReferences.forEach((footnoteReference) => {
+ writer.setAttribute(ATTRIBUTES.footnoteIndex, newFootnoteIndex, footnoteReference);
+ });
+ });
+ }
+
+ /**
+ * Reindexes footnotes such that footnote references occur in order, and reorders footnote items
+ * in the footer section accordingly. `batch` is passed in to group changes with the ones that
+ * instantiated them.
+ */
+ private _orderFootnotes(batch: Batch) {
+ const footnoteReferences = modelQueryElementsAll(this.editor, this.rootElement, (element) =>
+ element.is("element", ELEMENTS.footnoteReference)
+ );
+ const uniqueIds = new Set(footnoteReferences.map((element) => element.getAttribute(ATTRIBUTES.footnoteId)));
+ const orderedFootnotes = [...uniqueIds].map((id) =>
+ modelQueryElement(
+ this.editor,
+ this.rootElement,
+ (element) => element.is("element", ELEMENTS.footnoteItem) &&
+ element.getAttribute(ATTRIBUTES.footnoteId) === id
+ )
+ );
+
+ this.editor.model.enqueueChange(batch, (writer) => {
+ const footnoteSection = modelQueryElement(this.editor, this.rootElement, (element) =>
+ element.is("element", ELEMENTS.footnoteSection)
+ );
+ /* v8 ignore next 3 -- defensive: this only runs after a reference was inserted,
+ which implies the section exists */
+ if (!footnoteSection) {
+ return;
+ }
+
+ /**
+ * In order to keep footnotes with no existing references at the end of the list, the
+ * loop below reverses the list of footnotes with references and inserts each at the
+ * beginning.
+ */
+ for (const footnote of orderedFootnotes.reverse()) {
+ if (footnote) {
+ writer.move(writer.createRangeOn(footnote), footnoteSection, 0);
+ }
+ }
+
+ // Once the list is sorted, make one final pass to update footnote indices.
+ for (const footnote of modelQueryElementsAll(this.editor, footnoteSection, (element) =>
+ element.is("element", ELEMENTS.footnoteItem)
+ )) {
+ /* v8 ignore next -- defensive: the footnote was just queried out of this section */
+ const index = `${(footnoteSection.getChildIndex(footnote) ?? -1) + 1}`;
+ writer.setAttribute(ATTRIBUTES.footnoteIndex, index, footnote);
+
+ const id = footnote.getAttribute(ATTRIBUTES.footnoteId);
+
+ /**
+ * Unfortunately the following call seems to be necessary, even though
+ * `_updateReferenceIndices` should fire from the attribute change immediately
+ * above: events initiated by a `change:data` event do not themselves fire another
+ * `change:data` event.
+ */
+ /* v8 ignore next -- defensive: an item without an id cannot be downcast, so it
+ never reaches the document */
+ if (id) {
+ this._updateReferenceIndices(batch, `${id}`, index);
+ }
+ }
+ });
+ }
+
+}
diff --git a/packages/ckeditor5/src/plugins/footnotes/footnote_ui.spec.ts b/packages/ckeditor5/src/plugins/footnotes/footnote_ui.spec.ts
new file mode 100644
index 0000000000..9687fee817
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/footnote_ui.spec.ts
@@ -0,0 +1,164 @@
+import { _setModelData as setModelData, ClassicEditor, Essentials, Paragraph, SplitButtonView } from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { seedFootnotes } from "../../../test/footnotes-kit.js";
+import { COMMANDS, TOOLBAR_COMPONENT_NAME } from "./constants.js";
+import FootnoteUI from "./footnote_ui.js";
+import Footnotes from "./footnotes.js";
+
+interface ListButtonView {
+ commandParam?: number | string;
+ label?: string;
+ fire(event: string): void;
+}
+
+interface ListItemView {
+ children: { get(idx: number): ListButtonView };
+}
+
+interface ListView {
+ items: { length: number; get(idx: number): ListItemView };
+}
+
+interface FootnoteDropdownView {
+ isOpen: boolean;
+ isEnabled: boolean;
+ class: string;
+ buttonView: SplitButtonView;
+ listView?: ListView & { element: HTMLElement | null };
+}
+
+function createDropdown(editor: ClassicEditor): FootnoteDropdownView {
+ return editor.ui.componentFactory.create(TOOLBAR_COMPONENT_NAME) as unknown as FootnoteDropdownView;
+}
+
+function openDropdown(dropdown: FootnoteDropdownView): ListView {
+ dropdown.isOpen = true;
+ // Each open builds a fresh ListView; `dropdown.listView` is the live one, whereas
+ // `panelView.children` still holds the emptied lists from previous opens.
+ const listView = dropdown.listView;
+ if (!listView) {
+ throw new Error("Dropdown did not render a list view after opening.");
+ }
+ return listView;
+}
+
+describe("FootnoteUI", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, Footnotes]);
+ });
+
+ it("declares its plugin name", () => {
+ expect(FootnoteUI.pluginName).toBe("FootnoteUI");
+ });
+
+ it("registers a split button with the footnote icon", () => {
+ const dropdown = createDropdown(editor);
+
+ expect(dropdown.buttonView).toBeInstanceOf(SplitButtonView);
+ expect(dropdown.buttonView.label).toBe("Footnote");
+ expect(dropdown.buttonView.icon).toContain("<svg");
+ expect(dropdown.buttonView.tooltip).toBe(true);
+ expect(dropdown.buttonView.isToggleable).toBe(true);
+ expect(dropdown.class).toBe("ck-tn-dropdown");
+ });
+
+ it("inserts a new footnote when the split button itself is executed", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ const dropdown = createDropdown(editor);
+ const executeSpy = vi.spyOn(editor, "execute");
+ const focusSpy = vi.spyOn(editor.editing.view, "focus");
+
+ dropdown.buttonView.fire("execute");
+
+ expect(executeSpy).toHaveBeenCalledWith(COMMANDS.insertFootnote, { footnoteIndex: 0 });
+ expect(focusSpy).toHaveBeenCalled();
+ });
+
+ it("binds the button and dropdown to the command", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ const dropdown = createDropdown(editor);
+
+ expect(dropdown.isEnabled).toBe(true);
+ expect(dropdown.buttonView.isOn).toBe(false);
+ });
+
+ describe("the dropdown list", () => {
+ it("offers only 'New footnote' when the document has no footnotes", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ const listView = openDropdown(createDropdown(editor));
+
+ expect(listView.items.length).toBe(1);
+ expect(listView.items.get(0).children.get(0).label).toBe("New footnote");
+ expect(listView.items.get(0).children.get(0).commandParam).toBe(0);
+ });
+
+ it("lists every existing footnote after the 'New footnote' entry", () => {
+ seedFootnotes(editor, 2);
+ const listView = openDropdown(createDropdown(editor));
+
+ expect(listView.items.length).toBe(3);
+ expect(listView.items.get(1).children.get(0).label).toBe("Insert footnote 1");
+ expect(listView.items.get(1).children.get(0).commandParam).toBe("1");
+ expect(listView.items.get(2).children.get(0).label).toBe("Insert footnote 2");
+ });
+
+ it("rebuilds the list on each open, picking up newly added footnotes", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ const dropdown = createDropdown(editor);
+
+ expect(openDropdown(dropdown).items.length).toBe(1);
+
+ dropdown.isOpen = false;
+ editor.execute(COMMANDS.insertFootnote, { footnoteIndex: 0 });
+
+ expect(openDropdown(dropdown).items.length).toBe(2);
+ });
+
+ it("detaches the list element when the dropdown closes", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ const dropdown = createDropdown(editor);
+ openDropdown(dropdown);
+
+ dropdown.isOpen = false;
+
+ expect(dropdown.listView?.element?.parentNode ?? null).toBeNull();
+ });
+
+ it("inserts a reference to the picked footnote when a list item is executed", () => {
+ seedFootnotes(editor, 1);
+ const dropdown = createDropdown(editor);
+ const listView = openDropdown(dropdown);
+ const executeSpy = vi.spyOn(editor, "execute");
+ const focusSpy = vi.spyOn(editor.editing.view, "focus");
+
+ listView.items.get(1).children.get(0).fire("execute");
+
+ expect(executeSpy).toHaveBeenCalledWith(COMMANDS.insertFootnote, { footnoteIndex: "1" });
+ expect(focusSpy).toHaveBeenCalled();
+ });
+ });
+
+ describe("failure modes", () => {
+ it("throws when the insert command is not registered", async () => {
+ const bare = await createTestEditor([Essentials, Paragraph, FootnoteUI]);
+
+ expect(() => bare.ui.componentFactory.create(TOOLBAR_COMPONENT_NAME)).toThrow("Command not found.");
+ });
+
+ it("throws when building the list without a document root", () => {
+ const ui = editor.plugins.get(FootnoteUI);
+ const originalGetRoot = editor.model.document.getRoot.bind(editor.model.document);
+ editor.model.document.getRoot = (() => null) as typeof editor.model.document.getRoot;
+
+ try {
+ expect(() => ui.getDropdownItemsDefinitions()).toThrow("Document has no root element.");
+ } finally {
+ editor.model.document.getRoot = originalGetRoot;
+ }
+ });
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/footnotes/footnote_ui.ts b/packages/ckeditor5/src/plugins/footnotes/footnote_ui.ts
new file mode 100644
index 0000000000..af0fc63275
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/footnote_ui.ts
@@ -0,0 +1,117 @@
+import { addListToDropdown, Collection, createDropdown, type ListDropdownItemDefinition, Plugin, SplitButtonView, ViewModel } from "ckeditor5";
+
+import insertFootnoteIcon from "../../icons/insert-footnote.svg?raw";
+import { ATTRIBUTES, COMMANDS, ELEMENTS, TOOLBAR_COMPONENT_NAME } from "./constants.js";
+import { modelQueryElement, modelQueryElementsAll } from "./utils.js";
+
+/**
+ * Registers the footnote split button: the button inserts a new footnote, while the dropdown also
+ * lists the existing footnotes so an inline reference to one of them can be inserted instead.
+ */
+export default class FootnoteUI extends Plugin {
+
+ public static get pluginName() {
+ return "FootnoteUI" as const;
+ }
+
+ public init(): void {
+ const editor = this.editor;
+ const translate = editor.t;
+
+ editor.ui.componentFactory.add(TOOLBAR_COMPONENT_NAME, (locale) => {
+ const dropdownView = createDropdown(locale, SplitButtonView);
+ const splitButtonView = dropdownView.buttonView;
+
+ const command = editor.commands.get(COMMANDS.insertFootnote);
+ if (!command) {
+ throw new Error("Command not found.");
+ }
+
+ splitButtonView.set({
+ label: translate("Footnote"),
+ icon: insertFootnoteIcon,
+ tooltip: true,
+ isToggleable: true
+ });
+ splitButtonView.bind("isOn").to(command, "value", (value) => !!value);
+ splitButtonView.on("execute", () => {
+ editor.execute(COMMANDS.insertFootnote, { footnoteIndex: 0 });
+ editor.editing.view.focus();
+ });
+
+ dropdownView.class = "ck-tn-dropdown";
+ dropdownView.bind("isEnabled").to(command);
+
+ // The list is rebuilt every time the dropdown opens, because which footnotes exist —
+ // and therefore which items the list should offer — changes as the document is edited.
+ dropdownView.on("change:isOpen", (_evt, _propertyName, isOpen) => {
+ dropdownView.listView?.items.clear();
+
+ if (isOpen) {
+ addListToDropdown(dropdownView, this.getDropdownItemsDefinitions());
+ return;
+ }
+
+ const listElement = dropdownView.listView?.element;
+ listElement?.parentNode?.removeChild(listElement);
+ });
+
+ // Execute the command when a dropdown item is clicked (executed).
+ this.listenTo(dropdownView, "execute", (evt) => {
+ editor.execute(COMMANDS.insertFootnote, {
+ footnoteIndex: (evt.source as { commandParam?: number }).commandParam
+ });
+ editor.editing.view.focus();
+ });
+
+ return dropdownView;
+ });
+ }
+
+ /**
+ * Builds the dropdown contents: "New footnote", followed by one entry per existing footnote.
+ */
+ public getDropdownItemsDefinitions(): Collection<ListDropdownItemDefinition> {
+ const itemDefinitions = new Collection<ListDropdownItemDefinition>();
+
+ itemDefinitions.add({
+ type: "button",
+ model: new ViewModel({
+ commandParam: 0,
+ label: "New footnote",
+ withText: true
+ })
+ });
+
+ const rootElement = this.editor.model.document.getRoot();
+ if (!rootElement) {
+ throw new Error("Document has no root element.");
+ }
+
+ const footnoteSection = modelQueryElement(this.editor, rootElement, (element) =>
+ element.is("element", ELEMENTS.footnoteSection)
+ );
+
+ if (footnoteSection) {
+ const footnoteItems = modelQueryElementsAll(this.editor, rootElement, (element) =>
+ element.is("element", ELEMENTS.footnoteItem)
+ );
+
+ for (const footnote of footnoteItems) {
+ const index = footnote.getAttribute(ATTRIBUTES.footnoteIndex);
+
+ itemDefinitions.add({
+ type: "button",
+ model: new ViewModel({
+ commandParam: index,
+ label: `Insert footnote ${index}`,
+ withText: true
+ })
+ });
+ }
+ }
+
+ return itemDefinitions;
+ }
+
+}
diff --git a/packages/ckeditor5/src/plugins/footnotes/footnotes.spec.ts b/packages/ckeditor5/src/plugins/footnotes/footnotes.spec.ts
new file mode 100644
index 0000000000..d770e7db24
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/footnotes.spec.ts
@@ -0,0 +1,44 @@
+import { _getModelData as getModelData, ClassicEditor, Essentials, Paragraph } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { ELEMENTS } from "./constants.js";
+import FootnoteEditing from "./footnote_editing.js";
+import FootnoteUI from "./footnote_ui.js";
+import Footnotes from "./footnotes.js";
+import { seedFootnotes } from "../../../test/footnotes-kit.js";
+
+describe("Footnotes", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, Footnotes]);
+ });
+
+ it("loads the glue plugin and its editing/UI parts", () => {
+ expect(editor.plugins.get(Footnotes)).toBeInstanceOf(Footnotes);
+ expect(editor.plugins.get(FootnoteEditing)).toBeInstanceOf(FootnoteEditing);
+ expect(editor.plugins.get(FootnoteUI)).toBeInstanceOf(FootnoteUI);
+ });
+
+ it("declares its plugin name and requirements", () => {
+ expect(Footnotes.pluginName).toBe("Footnotes");
+ expect(Footnotes.requires).toContain(FootnoteEditing);
+ expect(Footnotes.requires).toContain(FootnoteUI);
+ });
+
+ it("round-trips a footnote through data and back", () => {
+ seedFootnotes(editor, 1);
+
+ const data = editor.getData();
+
+ expect(data).toContain(`class="footnote-reference"`);
+ expect(data).toContain(`class="footnote-section footnotes"`);
+ expect(data).toContain(`class="footnote-item"`);
+
+ editor.setData(data);
+
+ expect(getModelData(editor.model, { withoutSelection: true })).toContain(ELEMENTS.footnoteSection);
+ expect(getModelData(editor.model, { withoutSelection: true })).toContain(ELEMENTS.footnoteReference);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/footnotes/footnotes.ts b/packages/ckeditor5/src/plugins/footnotes/footnotes.ts
new file mode 100644
index 0000000000..7c0aebfca8
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/footnotes.ts
@@ -0,0 +1,35 @@
+import { Plugin } from "ckeditor5";
+
+import "../../theme/footnotes.css";
+
+import FootnoteEditing from "./footnote_editing.js";
+import FootnoteUI from "./footnote_ui.js";
+
+/**
+ * Footnotes: an inline `[n]` reference in the text, paired with a numbered item in a footnote
+ * section at the end of the document.
+ *
+ * This is a "glue" plugin which loads {@link FootnoteEditing} and {@link FootnoteUI}.
+ *
+ * Derived from the Forum Magnum footnote plugin; see the `LICENSE.md` and `README.md` next to this
+ * file.
+ */
+export default class Footnotes extends Plugin {
+
+ public static get pluginName() {
+ return "Footnotes" as const;
+ }
+
+ public static get requires() {
+ return [FootnoteEditing, FootnoteUI] as const;
+ }
+
+}
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [Footnotes.pluginName]: Footnotes;
+ [FootnoteEditing.pluginName]: FootnoteEditing;
+ [FootnoteUI.pluginName]: FootnoteUI;
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/footnotes/insert_footnote_command.spec.ts b/packages/ckeditor5/src/plugins/footnotes/insert_footnote_command.spec.ts
new file mode 100644
index 0000000000..e4ec4ac486
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/insert_footnote_command.spec.ts
@@ -0,0 +1,126 @@
+import { _getModelData as getModelData, _setModelData as setModelData, ClassicEditor, Essentials, Paragraph } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { ATTRIBUTES, COMMANDS, ELEMENTS } from "./constants.js";
+import type InsertFootnoteCommand from "./insert_footnote_command.js";
+import Footnotes from "./footnotes.js";
+import { seedFootnotes } from "../../../test/footnotes-kit.js";
+
+describe("InsertFootnoteCommand", () => {
+ let editor: ClassicEditor;
+ let command: InsertFootnoteCommand;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, Footnotes]);
+ command = editor.commands.get(COMMANDS.insertFootnote) as InsertFootnoteCommand;
+ });
+
+ function model(): string {
+ return getModelData(editor.model, { withoutSelection: true });
+ }
+
+ function countOf(elementName: string): number {
+ return model().split(`<${elementName}`).length - 1;
+ }
+
+ describe("refresh", () => {
+ it("is enabled inside a paragraph", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+
+ expect(command.isEnabled).toBe(true);
+ });
+
+ it("is disabled inside the footnote section, where a reference is not allowed", () => {
+ seedFootnotes(editor, 1);
+ const section = editor.model.document.getRoot()?.getChild(1);
+ if (!section?.is("element")) {
+ throw new Error("Expected a footnote section.");
+ }
+ editor.model.change((writer) => writer.setSelection(section, "on"));
+
+ expect(command.isEnabled).toBe(false);
+ });
+ });
+
+ describe("inserting a new footnote", () => {
+ it("creates the section, the item and the reference", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+
+ editor.execute(COMMANDS.insertFootnote, { footnoteIndex: 0 });
+
+ expect(countOf(ELEMENTS.footnoteSection)).toBe(1);
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(1);
+ expect(countOf(ELEMENTS.footnoteReference)).toBe(1);
+ expect(countOf(ELEMENTS.footnoteBackLink)).toBe(1);
+ expect(model()).toContain(`${ATTRIBUTES.footnoteIndex}="1"`);
+ });
+
+ it("defaults to inserting a new footnote when called with no options", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+
+ editor.execute(COMMANDS.insertFootnote);
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(1);
+ });
+
+ it("reuses the existing section and numbers the second footnote 2", () => {
+ seedFootnotes(editor, 1);
+
+ editor.execute(COMMANDS.insertFootnote, { footnoteIndex: 0 });
+
+ expect(countOf(ELEMENTS.footnoteSection)).toBe(1);
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(2);
+ expect(model()).toContain(`${ATTRIBUTES.footnoteIndex}="2"`);
+ });
+
+ it("gives each footnote a distinct id", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+
+ editor.execute(COMMANDS.insertFootnote, { footnoteIndex: 0 });
+ editor.execute(COMMANDS.insertFootnote, { footnoteIndex: 0 });
+
+ const ids = [...model().matchAll(new RegExp(`${ATTRIBUTES.footnoteId}="([^"]+)"`, "g"))]
+ .map((match) => match[1]);
+
+ expect(new Set(ids).size).toBeGreaterThan(1);
+ });
+ });
+
+ describe("referencing an existing footnote", () => {
+ it("adds a second reference without adding a second item", () => {
+ seedFootnotes(editor, 1);
+
+ editor.execute(COMMANDS.insertFootnote, { footnoteIndex: 1 });
+
+ expect(countOf(ELEMENTS.footnoteItem)).toBe(1);
+ expect(countOf(ELEMENTS.footnoteReference)).toBe(2);
+ });
+
+ it("does nothing when the requested index has no matching footnote", () => {
+ seedFootnotes(editor, 1);
+ const before = model();
+
+ editor.execute(COMMANDS.insertFootnote, { footnoteIndex: 9 });
+
+ expect(model()).toBe(before);
+ });
+ });
+
+ it("does nothing when the document has no root", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ const before = model();
+
+ // `getRoot()` returns null for a root name that does not exist; the command must bail
+ // rather than throw.
+ const originalGetRoot = editor.model.document.getRoot.bind(editor.model.document);
+ editor.model.document.getRoot = (() => null) as typeof editor.model.document.getRoot;
+ try {
+ editor.execute(COMMANDS.insertFootnote, { footnoteIndex: 0 });
+ } finally {
+ editor.model.document.getRoot = originalGetRoot;
+ }
+
+ expect(model()).toBe(before);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/footnotes/insert_footnote_command.ts b/packages/ckeditor5/src/plugins/footnotes/insert_footnote_command.ts
new file mode 100644
index 0000000000..46aba59aba
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/insert_footnote_command.ts
@@ -0,0 +1,122 @@
+import { Command, type ModelElement, type ModelRootElement, type ModelWriter } from "ckeditor5";
+
+import { ATTRIBUTES, ELEMENTS } from "./constants.js";
+import { modelQueryElement } from "./utils.js";
+
+/**
+ * Inserts a footnote reference at the selection, creating the footnote item (and the footnote
+ * section that holds it) when the reference is a new one.
+ */
+export default class InsertFootnoteCommand extends Command {
+
+ /**
+ * Creates a footnote reference with the given index, and creates a matching footnote if one
+ * doesn't already exist. Also creates the footnote section if it doesn't exist. If
+ * `footnoteIndex` is 0 (or not provided), the added footnote is given the next unused index —
+ * e.g. 7, if 6 footnotes exist so far.
+ */
+ public override execute({ footnoteIndex }: { footnoteIndex?: number } = { footnoteIndex: 0 }): void {
+ this.editor.model.enqueueChange((modelWriter) => {
+ const doc = this.editor.model.document;
+ const rootElement = doc.getRoot();
+ if (!rootElement) {
+ return;
+ }
+
+ const footnoteSection = this._getFootnoteSection(modelWriter, rootElement);
+ let index: string;
+ let id: string | undefined;
+
+ if (footnoteIndex === 0) {
+ index = `${footnoteSection.maxOffset + 1}`;
+ id = newFootnoteId();
+ } else {
+ index = `${footnoteIndex}`;
+ const matchingFootnote = modelQueryElement(
+ this.editor,
+ footnoteSection,
+ (element) => element.is("element", ELEMENTS.footnoteItem) &&
+ element.getAttribute(ATTRIBUTES.footnoteIndex) === index
+ );
+ if (matchingFootnote) {
+ id = matchingFootnote.getAttribute(ATTRIBUTES.footnoteId) as string;
+ }
+ }
+
+ if (!id) {
+ return;
+ }
+
+ modelWriter.setSelection(doc.selection.getLastPosition());
+ const footnoteReference = modelWriter.createElement(ELEMENTS.footnoteReference, {
+ [ATTRIBUTES.footnoteId]: id,
+ [ATTRIBUTES.footnoteIndex]: index
+ });
+ this.editor.model.insertContent(footnoteReference);
+ modelWriter.setSelection(footnoteReference, "after");
+
+ // If referencing an existing footnote, the item below already exists.
+ if (footnoteIndex !== 0) {
+ return;
+ }
+
+ const footnoteContent = modelWriter.createElement(ELEMENTS.footnoteContent);
+ const footnoteItem = modelWriter.createElement(ELEMENTS.footnoteItem, {
+ [ATTRIBUTES.footnoteId]: id,
+ [ATTRIBUTES.footnoteIndex]: index
+ });
+ const footnoteBackLink = modelWriter.createElement(ELEMENTS.footnoteBackLink, {
+ [ATTRIBUTES.footnoteId]: id
+ });
+ const paragraph = modelWriter.createElement("paragraph");
+ modelWriter.append(paragraph, footnoteContent);
+ modelWriter.append(footnoteContent, footnoteItem);
+ modelWriter.insert(footnoteBackLink, footnoteItem, 0);
+
+ this.editor.model.insertContent(
+ footnoteItem,
+ modelWriter.createPositionAt(footnoteSection, footnoteSection.maxOffset)
+ );
+ });
+ }
+
+ /**
+ * Called automatically when changes are applied to the document. Sets `isEnabled` to determine
+ * whether footnote creation is allowed at the current location.
+ */
+ public override refresh(): void {
+ const model = this.editor.model;
+ const lastPosition = model.document.selection.getLastPosition();
+ const allowedIn = lastPosition && model.schema.findAllowedParent(lastPosition, ELEMENTS.footnoteReference);
+ this.isEnabled = allowedIn !== null;
+ }
+
+ /**
+ * Returns the footnote section if it exists, or creates one if it doesn't.
+ */
+ private _getFootnoteSection(writer: ModelWriter, rootElement: ModelRootElement): ModelElement {
+ const footnoteSection = modelQueryElement(this.editor, rootElement, (element) =>
+ element.is("element", ELEMENTS.footnoteSection)
+ );
+ if (footnoteSection) {
+ return footnoteSection;
+ }
+
+ const newFootnoteSection = writer.createElement(ELEMENTS.footnoteSection);
+ this.editor.model.insertContent(
+ newFootnoteSection,
+ writer.createPositionAt(rootElement, rootElement.maxOffset)
+ );
+ return newFootnoteSection;
+ }
+
+}
+
+/**
+ * A short opaque id used to pair a footnote item with its references. Not security-sensitive — it
+ * only has to be unique within one document — so `Math.random()` is fine, and it keeps the plugin
+ * usable over plain HTTP where `crypto.randomUUID()` is unavailable.
+ */
+function newFootnoteId(): string {
+ return Math.random().toString(36).slice(2);
+}
diff --git a/packages/ckeditor5/src/plugins/footnotes/schema.spec.ts b/packages/ckeditor5/src/plugins/footnotes/schema.spec.ts
new file mode 100644
index 0000000000..f3d3df4bfd
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/schema.spec.ts
@@ -0,0 +1,83 @@
+import { ClassicEditor, Essentials, List, Paragraph } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { ATTRIBUTES, ELEMENTS } from "./constants.js";
+import Footnotes from "./footnotes.js";
+
+describe("footnote schema", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, List, Footnotes]);
+ });
+
+ it("registers every footnote element", () => {
+ const schema = editor.model.schema;
+
+ for (const name of Object.values(ELEMENTS)) {
+ expect(schema.isRegistered(name)).toBe(true);
+ }
+ });
+
+ it("allows the section in the root, and items only within the section", () => {
+ const schema = editor.model.schema;
+
+ expect(schema.checkChild(["$root"], ELEMENTS.footnoteSection)).toBe(true);
+ expect(schema.checkChild(["$root", ELEMENTS.footnoteSection], ELEMENTS.footnoteItem)).toBe(true);
+ expect(schema.checkChild(["$root", ELEMENTS.footnoteSection, ELEMENTS.footnoteItem], ELEMENTS.footnoteContent)).toBe(true);
+ expect(schema.checkChild(["$root", ELEMENTS.footnoteSection, ELEMENTS.footnoteItem], ELEMENTS.footnoteBackLink)).toBe(true);
+ });
+
+ it("allows a reference wherever text is allowed", () => {
+ expect(editor.model.schema.checkChild(["$root", "paragraph"], ELEMENTS.footnoteReference)).toBe(true);
+ });
+
+ it("marks the section, item and reference as objects, and the back link as unselectable", () => {
+ const schema = editor.model.schema;
+
+ expect(schema.isObject(ELEMENTS.footnoteSection)).toBe(true);
+ expect(schema.isObject(ELEMENTS.footnoteItem)).toBe(true);
+ expect(schema.isObject(ELEMENTS.footnoteReference)).toBe(true);
+ expect(schema.isInline(ELEMENTS.footnoteReference)).toBe(true);
+ expect(schema.isSelectable(ELEMENTS.footnoteBackLink)).toBe(false);
+ });
+
+ it("declares the id and index attributes on items and references", () => {
+ const schema = editor.model.schema;
+
+ expect(schema.checkAttribute([ELEMENTS.footnoteItem], ATTRIBUTES.footnoteId)).toBe(true);
+ expect(schema.checkAttribute([ELEMENTS.footnoteItem], ATTRIBUTES.footnoteIndex)).toBe(true);
+ expect(schema.checkAttribute([ELEMENTS.footnoteReference], ATTRIBUTES.footnoteId)).toBe(true);
+ expect(schema.checkAttribute([ELEMENTS.footnoteReference], ATTRIBUTES.footnoteIndex)).toBe(true);
+ });
+
+ describe("the child check", () => {
+ it("forbids nesting a footnote section inside footnote content", () => {
+ const allowed = editor.model.schema.checkChild(
+ ["$root", ELEMENTS.footnoteSection, ELEMENTS.footnoteItem, ELEMENTS.footnoteContent],
+ ELEMENTS.footnoteSection
+ );
+
+ expect(allowed).toBe(false);
+ });
+
+ it("forbids list items inside footnote content", () => {
+ const allowed = editor.model.schema.checkChild(
+ ["$root", ELEMENTS.footnoteSection, ELEMENTS.footnoteItem, ELEMENTS.footnoteContent],
+ "listItem"
+ );
+
+ expect(allowed).toBe(false);
+ });
+
+ it("still allows paragraphs inside footnote content", () => {
+ const allowed = editor.model.schema.checkChild(
+ ["$root", ELEMENTS.footnoteSection, ELEMENTS.footnoteItem, ELEMENTS.footnoteContent],
+ "paragraph"
+ );
+
+ expect(allowed).toBe(true);
+ });
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/footnotes/schema.ts b/packages/ckeditor5/src/plugins/footnotes/schema.ts
new file mode 100644
index 0000000000..2ae0eb2b36
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/schema.ts
@@ -0,0 +1,62 @@
+import { ModelSchema } from "ckeditor5";
+
+import { ATTRIBUTES, ELEMENTS } from "./constants.js";
+
+/**
+ * Declares the custom element types used by the footnotes plugin.
+ *
+ * See the meanings of each rule at
+ * https://ckeditor.com/docs/ckeditor5/latest/api/module_engine_model_schema-SchemaItemDefinition.html
+ */
+export const defineSchema = (schema: ModelSchema): void => {
+ /** Footnote section at the footer of the document. */
+ schema.register(ELEMENTS.footnoteSection, {
+ isObject: true,
+ allowWhere: "$block",
+ allowIn: "$root",
+ allowChildren: ELEMENTS.footnoteItem,
+ allowAttributes: [ATTRIBUTES.footnoteSection]
+ });
+
+ /** Individual footnote item within the footnote section. */
+ schema.register(ELEMENTS.footnoteItem, {
+ isBlock: true,
+ isObject: true,
+ allowContentOf: "$root",
+ allowAttributes: [ATTRIBUTES.footnoteSection, ATTRIBUTES.footnoteId, ATTRIBUTES.footnoteIndex]
+ });
+
+ /** Editable footnote item content container. */
+ schema.register(ELEMENTS.footnoteContent, {
+ allowIn: ELEMENTS.footnoteItem,
+ allowContentOf: "$root",
+ allowAttributes: [ATTRIBUTES.footnoteSection]
+ });
+
+ /** Inline footnote citation, placed within the main text. */
+ schema.register(ELEMENTS.footnoteReference, {
+ allowWhere: "$text",
+ isInline: true,
+ isObject: true,
+ allowAttributes: [ATTRIBUTES.footnoteReference, ATTRIBUTES.footnoteId, ATTRIBUTES.footnoteIndex]
+ });
+
+ /** Return link which takes you from the footnote back to the inline reference. */
+ schema.register(ELEMENTS.footnoteBackLink, {
+ allowIn: ELEMENTS.footnoteItem,
+ isInline: true,
+ isSelectable: false,
+ allowAttributes: [ATTRIBUTES.footnoteBackLink, ATTRIBUTES.footnoteId]
+ });
+
+ // A footnote may not contain the footnote section itself.
+ //
+ // The original plugin also rejected `listItem` here, but that element no longer exists: since
+ // CKEditor 5 v41 the list feature models list entries as ordinary blocks carrying
+ // `listItemId`/`listType` attributes, so the check could never fire.
+ schema.addChildCheck((context, childDefinition) => {
+ if (context.endsWith(ELEMENTS.footnoteContent) && childDefinition.name === ELEMENTS.footnoteSection) {
+ return false;
+ }
+ });
+};
diff --git a/packages/ckeditor5/src/plugins/footnotes/utils.spec.ts b/packages/ckeditor5/src/plugins/footnotes/utils.spec.ts
new file mode 100644
index 0000000000..f718f8a4c0
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/utils.spec.ts
@@ -0,0 +1,79 @@
+import { _setModelData as setModelData, ClassicEditor, Essentials, Paragraph } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { modelQueryElement, modelQueryElementsAll, viewQueryElement } from "./utils.js";
+
+describe("footnote utils", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph]);
+ setModelData(editor.model, "<paragraph>foo</paragraph><paragraph>bar[]</paragraph>");
+ });
+
+ function root() {
+ const rootElement = editor.model.document.getRoot();
+ if (!rootElement) {
+ throw new Error("Editor has no root element.");
+ }
+ return rootElement;
+ }
+
+ describe("modelQueryElementsAll", () => {
+ it("returns every element when no predicate is given, skipping text nodes", () => {
+ const found = modelQueryElementsAll(editor, root());
+
+ expect(found.map((element) => element.name)).toEqual(["paragraph", "paragraph"]);
+ });
+
+ it("returns only the elements matching the predicate", () => {
+ const found = modelQueryElementsAll(editor, root(), (element) => element.childCount === 1);
+
+ expect(found).toHaveLength(2);
+ });
+
+ it("returns an empty array when nothing matches", () => {
+ expect(modelQueryElementsAll(editor, root(), () => false)).toEqual([]);
+ });
+ });
+
+ describe("modelQueryElement", () => {
+ it("returns the first element when no predicate is given", () => {
+ expect(modelQueryElement(editor, root())?.name).toBe("paragraph");
+ });
+
+ it("returns the first element matching the predicate", () => {
+ const found = modelQueryElement(editor, root(), (element) => {
+ const child = element.getChild(0);
+ return Boolean(child?.is("$text") && child.data === "bar");
+ });
+
+ expect(found?.name).toBe("paragraph");
+ });
+
+ it("returns null when nothing matches", () => {
+ expect(modelQueryElement(editor, root(), () => false)).toBeNull();
+ });
+ });
+
+ describe("viewQueryElement", () => {
+ it("returns the first view element when no predicate is given", () => {
+ const viewRoot = editor.editing.view.document.getRoot();
+ if (!viewRoot) {
+ throw new Error("Editing view has no root element.");
+ }
+
+ expect(viewQueryElement(editor, viewRoot)?.name).toBe("p");
+ });
+
+ it("returns null when nothing matches", () => {
+ const viewRoot = editor.editing.view.document.getRoot();
+ if (!viewRoot) {
+ throw new Error("Editing view has no root element.");
+ }
+
+ expect(viewQueryElement(editor, viewRoot, () => false)).toBeNull();
+ });
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/footnotes/utils.ts b/packages/ckeditor5/src/plugins/footnotes/utils.ts
new file mode 100644
index 0000000000..3e7ef442b2
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/footnotes/utils.ts
@@ -0,0 +1,62 @@
+import { type Editor, ModelElement, ViewElement } from "ckeditor5";
+
+/**
+ * Returns an array of all descendant elements of the root for which the provided predicate
+ * returns true.
+ */
+export const modelQueryElementsAll = (
+ editor: Editor,
+ rootElement: ModelElement,
+ predicate: (item: ModelElement) => boolean = () => true
+): Array<ModelElement> => {
+ const range = editor.model.createRangeIn(rootElement);
+ const output: Array<ModelElement> = [];
+
+ for (const item of range.getItems()) {
+ if (item instanceof ModelElement && predicate(item)) {
+ output.push(item);
+ }
+ }
+
+ return output;
+};
+
+/**
+ * Returns the first descendant element of the root for which the provided predicate returns true,
+ * or null if no such element is found.
+ */
+export const modelQueryElement = (
+ editor: Editor,
+ rootElement: ModelElement,
+ predicate: (item: ModelElement) => boolean = () => true
+): ModelElement | null => {
+ const range = editor.model.createRangeIn(rootElement);
+
+ for (const item of range.getItems()) {
+ if (item instanceof ModelElement && predicate(item)) {
+ return item;
+ }
+ }
+
+ return null;
+};
+
+/**
+ * Returns the first descendant element of the view root for which the provided predicate returns
+ * true, or null if no such element is found.
+ */
+export const viewQueryElement = (
+ editor: Editor,
+ rootElement: ViewElement,
+ predicate: (item: ViewElement) => boolean = () => true
+): ViewElement | null => {
+ const range = editor.editing.view.createRangeIn(rootElement);
+
+ for (const item of range.getItems()) {
+ if (item instanceof ViewElement && predicate(item)) {
+ return item;
+ }
+ }
+
+ return null;
+};
diff --git a/packages/ckeditor5-footnotes/theme/footnote.css b/packages/ckeditor5/src/theme/footnotes.css
similarity index 100%
rename from packages/ckeditor5-footnotes/theme/footnote.css
rename to packages/ckeditor5/src/theme/footnotes.css
diff --git a/packages/ckeditor5/test/footnotes-kit.ts b/packages/ckeditor5/test/footnotes-kit.ts
new file mode 100644
index 0000000000..480acc089b
--- /dev/null
+++ b/packages/ckeditor5/test/footnotes-kit.ts
@@ -0,0 +1,98 @@
+import type { ClassicEditor, ModelElement } from "ckeditor5";
+
+import { ATTRIBUTES, ELEMENTS } from "../src/plugins/footnotes/constants.js";
+
+/**
+ * Test fixtures for the footnotes plugin.
+ *
+ * These build the document with a model writer rather than `_setModelData()`, because the parser
+ * coerces numeric-looking attribute values (`data-footnote-index="1"`) to numbers, whereas the
+ * plugin always writes them as strings and compares them as such. A `_setModelData()` fixture
+ * therefore silently fails to match production behaviour.
+ *
+ * This file lives outside `src/`, so it is excluded from both the production build and the
+ * coverage gate.
+ */
+
+export interface SeededFootnotes {
+ references: Array<ModelElement>;
+ items: Array<ModelElement>;
+ section: ModelElement;
+}
+
+/**
+ * Writes a document containing `count` footnotes, each referenced once from a leading paragraph,
+ * in the shape the plugin produces. Ids are deterministic (`id1`, `id2`, …).
+ *
+ * The collapsed selection is left at the end of the paragraph text, before the references.
+ */
+export function seedFootnotes(editor: ClassicEditor, count: number): SeededFootnotes {
+ return editor.model.change((writer) => {
+ const root = editor.model.document.getRoot();
+ if (!root) {
+ throw new Error("Editor has no root element.");
+ }
+
+ writer.remove(writer.createRangeIn(root));
+
+ const paragraph = writer.createElement("paragraph");
+ writer.insert(paragraph, root, 0);
+ writer.insertText("text", paragraph, 0);
+
+ const section = writer.createElement(ELEMENTS.footnoteSection);
+ writer.insert(section, root, "end");
+
+ const references: Array<ModelElement> = [];
+ const items: Array<ModelElement> = [];
+
+ for (let i = 0; i < count; i++) {
+ const id = `id${i + 1}`;
+ const index = `${i + 1}`;
+
+ const reference = writer.createElement(ELEMENTS.footnoteReference, {
+ [ATTRIBUTES.footnoteId]: id,
+ [ATTRIBUTES.footnoteIndex]: index
+ });
+ writer.insert(reference, paragraph, "end");
+ references.push(reference);
+
+ const item = writer.createElement(ELEMENTS.footnoteItem, {
+ [ATTRIBUTES.footnoteId]: id,
+ [ATTRIBUTES.footnoteIndex]: index
+ });
+ const backLink = writer.createElement(ELEMENTS.footnoteBackLink, {
+ [ATTRIBUTES.footnoteId]: id
+ });
+ const content = writer.createElement(ELEMENTS.footnoteContent);
+ const contentParagraph = writer.createElement("paragraph");
+
+ writer.insert(contentParagraph, content, 0);
+ writer.insertText(`note ${i + 1}`, contentParagraph, 0);
+ writer.insert(backLink, item, 0);
+ writer.insert(content, item, "end");
+ writer.insert(item, section, "end");
+ items.push(item);
+ }
+
+ writer.setSelection(paragraph, 4);
+
+ return { references, items, section };
+ });
+}
+
+/**
+ * Places the collapsed selection at the end of the given footnote's content paragraph.
+ */
+export function selectInFootnoteContent(editor: ClassicEditor, item: ModelElement): void {
+ editor.model.change((writer) => {
+ const content = [...item.getChildren()].find((child) => child.is("element", ELEMENTS.footnoteContent));
+ if (!content?.is("element")) {
+ throw new Error("Footnote item has no content element.");
+ }
+ const paragraph = content.getChild(0);
+ if (!paragraph?.is("element")) {
+ throw new Error("Footnote content has no paragraph.");
+ }
+ writer.setSelection(paragraph, "end");
+ });
+}
diff --git a/packages/ckeditor5/tsconfig.json b/packages/ckeditor5/tsconfig.json
index d2f168c533..60721af2a6 100644
--- a/packages/ckeditor5/tsconfig.json
+++ b/packages/ckeditor5/tsconfig.json
@@ -3,9 +3,6 @@
"files": [],
"include": [],
"references": [
- {
- "path": "../ckeditor5-footnotes"
- },
{
"path": "../ckeditor5-math"
},
diff --git a/packages/ckeditor5/tsconfig.lib.json b/packages/ckeditor5/tsconfig.lib.json
index 0937846bf1..4c1a9662b0 100644
--- a/packages/ckeditor5/tsconfig.lib.json
+++ b/packages/ckeditor5/tsconfig.lib.json
@@ -21,9 +21,6 @@
"src/**/*.spec.ts"
],
"references": [
- {
- "path": "../ckeditor5-footnotes"
- },
{
"path": "../ckeditor5-math"
},
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 35546bc9d7..a1e834800a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1094,21 +1094,18 @@ importers:
packages/ckeditor5:
dependencies:
- '@triliumnext/ckeditor5-footnotes':
- specifier: workspace:*
- version: link:../ckeditor5-footnotes
'@triliumnext/ckeditor5-math':
specifier: workspace:*
version: link:../ckeditor5-math
'@triliumnext/ckeditor5-mermaid':
specifier: workspace:*
version: link:../ckeditor5-mermaid
- '@triliumnext/ckeditor5-utils':
- specifier: workspace:*
- version: link:../ckeditor5-utils
'@triliumnext/commons':
specifier: workspace:*
version: link:../commons
+ bootstrap:
+ specifier: ^5.3.0
+ version: 5.3.8(@popperjs/[email protected])
ckeditor5:
specifier: 48.3.1
version: 48.3.1([email protected])
@@ -1123,42 +1120,6 @@ importers:
specifier: 9.30.0
version: 9.30.0([email protected])
- packages/ckeditor5-footnotes:
- devDependencies:
- '@ckeditor/ckeditor5-inspector':
- specifier: '>=4.1.0'
- version: 5.0.3
- '@vitest/browser':
- specifier: 4.1.10
- ckeditor5:
- specifier: 48.3.1
- version: 48.3.1([email protected])
- eslint:
- specifier: 10.8.0
- eslint-config-ckeditor5:
- specifier: '>=9.1.0'
- stylelint:
- specifier: 17.14.1
- stylelint-config-ckeditor5:
- specifier: '>=9.1.0'
- typescript:
- specifier: 6.0.3
- version: 6.0.3
- vite-plugin-svgo:
- specifier: 2.0.0
- vitest:
- specifier: 4.1.10
- webdriverio:
- specifier: 9.30.0
- version: 9.30.0([email protected])
-
packages/ckeditor5-math:
dependencies:
'@ckeditor/ckeditor5-icons':
@@ -1238,22 +1199,6 @@ importers:
specifier: 9.30.0
version: 9.30.0([email protected])
- packages/ckeditor5-utils:
- dependencies:
- bootstrap:
- specifier: ^5.3.0
- version: 5.3.8(@popperjs/[email protected])
- devDependencies:
- '@vitest/browser':
- specifier: 4.1.10
- vitest:
- specifier: 4.1.10
- webdriverio:
- specifier: 9.30.0
- version: 9.30.0([email protected])
-
packages/codemirror:
dependencies:
'@catppuccin/codemirror':
diff --git a/tsconfig.json b/tsconfig.json
index b14538090a..d395efe060 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -48,9 +48,6 @@
{
"path": "./packages/ckeditor5-mermaid"
},
- {
- "path": "./packages/ckeditor5-footnotes"
- },
{
"path": "./packages/ckeditor5-math"
},