@fluxfiles/ckeditor5 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 thai-pc
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,112 @@
1
- # Temporary Holding Version
1
+ # FluxFiles — CKEditor 5 Plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Adds a **FluxFiles** toolbar button to CKEditor 5 for browsing and inserting files, plus an
4
+ "Insert image via FluxFiles" entry in the image toolbar's insert dropdown.
5
+
6
+ ## Requirements
7
+
8
+ - CKEditor 5 **42 or newer**, from the unified `ckeditor5` package (peer dependency, not bundled).
9
+ - A running **FluxFiles core** server (the PHP backend / standalone app in `packages/core`). `endpoint` must point at it.
10
+ - ESM only, like `ckeditor5` itself.
11
+
12
+ > **CKEditor 5 licensing.** CKEditor 5 is GPL-2.0-or-later or commercial, and the editor needs a
13
+ > `licenseKey` (`'GPL'` for open-source use, or your commercial key). That is the editor's
14
+ > requirement, set on the editor config. This plugin is MIT, embeds no key and never reads one.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install @fluxfiles/ckeditor5
20
+ ```
21
+
22
+ (`fluxfiles`, the browser SDK, is installed with it. If your page already loads `fluxfiles.js`
23
+ as a global, that copy is used instead.)
24
+
25
+ ```js
26
+ import { ClassicEditor, Essentials, Paragraph, Image, ImageInsert, Link } from 'ckeditor5';
27
+ import { FluxFiles } from '@fluxfiles/ckeditor5';
28
+ import 'ckeditor5/ckeditor5.css';
29
+
30
+ ClassicEditor.create(document.querySelector('#editor'), {
31
+ licenseKey: 'GPL',
32
+ plugins: [Essentials, Paragraph, Image, ImageInsert, Link, FluxFiles],
33
+ toolbar: ['undo', 'redo', '|', 'insertImage', 'link', 'fluxfiles'],
34
+ fluxfiles: {
35
+ endpoint: 'https://your-fluxfiles-host',
36
+ token: 'JWT_TOKEN', // or: token: () => fetch('/fluxfiles-token').then(r => r.text())
37
+ disk: 'local',
38
+ locale: 'en',
39
+ multiple: true,
40
+ onTokenRefresh: async () => (await fetch('/fluxfiles-token')).text(),
41
+ },
42
+ });
43
+ ```
44
+
45
+ ## How It Works
46
+
47
+ 1. **Toolbar button** `fluxfiles` (command `fluxfiles`): opens the picker and inserts the
48
+ selection at the caret.
49
+ - Images become image elements with `src`, and `alt` from the file's alt text (file name if
50
+ none). When the payload carries `img_srcset` (WebP/AVIF responsive images enabled on the
51
+ token) and the image plugin allows a `srcset` attribute, it is added too.
52
+ - Other files become links with the metadata title (or file name) as text.
53
+ - With `multiple: true`, every selected file is inserted in order. Folders are skipped.
54
+ - Without the image plugin, images are inserted as links; without the link plugin, as plain text.
55
+ 2. **Image insert dropdown**: when `ImageInsert` is loaded, the image toolbar's insert dropdown
56
+ offers FluxFiles next to "Insert image via URL". Turn it off with `imageInsert: false`.
57
+
58
+ The main JWT is never put in a URL: the SDK hands it to the picker iframe with `postMessage`
59
+ and checks the iframe's origin on every message.
60
+
61
+ > **Embedding and expiring URLs.** On a **private** disk the file URL is a *presigned* URL that
62
+ > expires, so embedding it in saved content breaks later (the plugin logs a `console.warn`).
63
+ > Use a **public** disk or a `public_url`. A preview-only selection (no embeddable URL, e.g. a
64
+ > watermark overlay with `allow_download=false`) is refused, as in the other editor plugins.
65
+
66
+ > CKEditor 5's image model has no `sizes` attribute and writes `sizes="100vw"` itself, so
67
+ > `img_sizes` is only used by a custom image plugin that registers one.
68
+
69
+ ## Configuration (`config.fluxfiles`)
70
+
71
+ | Option | Type | Default | Description |
72
+ |--------|------|---------|-------------|
73
+ | `endpoint` | string | `''` | FluxFiles server URL |
74
+ | `token` | string \| () => string \| Promise\<string\> | `''` | JWT, or a getter called each time the picker opens |
75
+ | `disk` | string | `'local'` | Storage disk |
76
+ | `disks` | string[] | | Disks shown in the picker sidebar |
77
+ | `path` | string | | Folder the picker opens in |
78
+ | `locale` | string | | UI language code |
79
+ | `theme` | string | | `light` / `dark` / `auto` |
80
+ | `multiple` | boolean | `false` | Allow multi-file selection |
81
+ | `allowedTypes` | string[] | | Restrict selectable types |
82
+ | `maxUploadMb` | number | | Max size per uploaded file, MB |
83
+ | `maxFiles` | number | | Max files per upload batch |
84
+ | `onTokenRefresh` | (ctx) => Promise\<string \| null\> | | Called when the picker gets a 401; return a fresh JWT |
85
+ | `imageInsert` | boolean | `true` | Offer FluxFiles in the image insert dropdown |
86
+ | `onInsert` | (files) => void | | Called after files were inserted |
87
+
88
+ ## API
89
+
90
+ - Plugin: `FluxFiles` (`pluginName: 'FluxFiles'`), named and default export
91
+ - Command: `fluxfiles` (`editor.execute('fluxfiles')`)
92
+ - Toolbar item: `fluxfiles`
93
+ - Types: `FluxFilesConfig`; `config.fluxfiles` is typed on `EditorConfig`
94
+
95
+ ## Development
96
+
97
+ ```bash
98
+ npm install
99
+ npm test # vitest, drives a real ClassicEditor in jsdom
100
+ npm run typecheck
101
+ npm run build # tsup -> dist/
102
+ ```
103
+
104
+ ## License
105
+
106
+ MIT — see [LICENSE](LICENSE) for details.
107
+
108
+ ## Links
109
+
110
+ - Main repository: `https://github.com/thai-pc/fluxfiles`
111
+ - Documentation: `https://github.com/thai-pc/fluxfiles#framework-adapters`
112
+ - Issues: `https://github.com/thai-pc/fluxfiles/issues`
@@ -0,0 +1,110 @@
1
+ import { Plugin, Command, Editor } from 'ckeditor5';
2
+ import { FluxFile } from 'fluxfiles';
3
+
4
+ /**
5
+ * FluxFiles for CKEditor 5.
6
+ *
7
+ * - command `fluxfiles`, toolbar item `fluxfiles`
8
+ * - an "Insert image via FluxFiles" entry in the image insert dropdown when the
9
+ * image insert UI is loaded (disable with `fluxfiles.imageInsert = false`)
10
+ *
11
+ * Configured under `config.fluxfiles`.
12
+ */
13
+ declare class FluxFiles extends Plugin {
14
+ static get pluginName(): "FluxFiles";
15
+ init(): void;
16
+ afterInit(): void;
17
+ private _createButton;
18
+ }
19
+
20
+ /** A selected file normalised into what the editor insert path needs. */
21
+ interface FileInfo {
22
+ url: string;
23
+ name: string;
24
+ isImage: boolean;
25
+ /** `false` for a preview-only selection (no permanent_url/url) that must not be saved into content. */
26
+ embeddable: boolean;
27
+ alt: string;
28
+ title: string;
29
+ width: number | null;
30
+ height: number | null;
31
+ srcset: string;
32
+ sizes: string;
33
+ }
34
+ /**
35
+ * Normalise a FluxFiles `onSelect` entry. Same rules as the CKEditor 4 / TinyMCE
36
+ * plugins: prefer `permanent_url`, refuse a preview-only selection (its only view
37
+ * is a short-lived token URL), warn about presigned (expiring) URLs.
38
+ */
39
+ declare function fileInfo(file: FluxFile): FileInfo;
40
+ /** `onSelect` hands over one file, an array, or folders; keep only real files. */
41
+ declare function selectedFiles(payload: FluxFile | FluxFile[] | null | undefined): FluxFile[];
42
+
43
+ type MaybePromise<T> = T | Promise<T>;
44
+ /** `config.fluxfiles`. Option names mirror the CKEditor 4 plugin. */
45
+ interface FluxFilesConfig {
46
+ /** FluxFiles server URL. */
47
+ endpoint: string;
48
+ /** JWT, or a function returning one (called each time the picker opens). */
49
+ token: string | (() => MaybePromise<string>);
50
+ /** Storage disk. Default `'local'`. */
51
+ disk?: string;
52
+ /** Disks shown in the picker sidebar. */
53
+ disks?: string[];
54
+ /** Folder to open the picker in. */
55
+ path?: string;
56
+ /** UI language code. */
57
+ locale?: string;
58
+ /** `light` | `dark` | `auto`. */
59
+ theme?: string;
60
+ /** Allow multi-file selection; every selected file is inserted. Default `false`. */
61
+ multiple?: boolean;
62
+ /** Restrict selectable types (e.g. `['image']`). */
63
+ allowedTypes?: string[];
64
+ /** Max size per uploaded file, MB. */
65
+ maxUploadMb?: number;
66
+ /** Max files per upload batch. */
67
+ maxFiles?: number;
68
+ /** Called when the picker needs a fresh JWT (401). Return a token or null. */
69
+ onTokenRefresh?: (context: {
70
+ reason: string;
71
+ disk?: string;
72
+ path?: string;
73
+ }) => Promise<string | null>;
74
+ /** Offer FluxFiles in the image toolbar's insert dropdown. Default `true`. */
75
+ imageInsert?: boolean;
76
+ /** Called after the selection has been inserted. */
77
+ onInsert?: (files: FluxFile[]) => void;
78
+ }
79
+ declare module '@ckeditor/ckeditor5-core' {
80
+ interface EditorConfig {
81
+ fluxfiles?: FluxFilesConfig;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Opens the FluxFiles picker and inserts the selection at the caret.
87
+ * Images become image elements, anything else a link with the file name as text.
88
+ */
89
+ declare class FluxFilesCommand extends Command {
90
+ constructor(editor: Editor);
91
+ private get _cfg();
92
+ refresh(): void;
93
+ /** Resolves once the picker has been opened (not when a file is chosen). */
94
+ execute(): Promise<void>;
95
+ private _insert;
96
+ /**
97
+ * A freshly inserted image stays selected, so the next insert would replace it.
98
+ * Move the caret past it: after an inline image, or into a new paragraph under
99
+ * a block image (the selection post-fixer pulls a root-level caret back onto it).
100
+ */
101
+ private _leaveImage;
102
+ }
103
+
104
+ declare module '@ckeditor/ckeditor5-core' {
105
+ interface PluginsMap {
106
+ [FluxFiles.pluginName]: FluxFiles;
107
+ }
108
+ }
109
+
110
+ export { type FileInfo, FluxFiles, FluxFilesCommand, type FluxFilesConfig, FluxFiles as default, fileInfo, selectedFiles };
package/dist/index.js ADDED
@@ -0,0 +1,181 @@
1
+ // src/fluxfiles.ts
2
+ import { Plugin, ButtonView } from "ckeditor5";
3
+
4
+ // src/fluxfilescommand.ts
5
+ import { Command } from "ckeditor5";
6
+ import FluxFilesSdk from "fluxfiles";
7
+
8
+ // src/convert.ts
9
+ var IMAGE_EXT = /\.(jpe?g|png|gif|webp|svg|bmp|ico|avif)$/i;
10
+ function fileInfo(file) {
11
+ const url = file.permanent_url || file.url || "";
12
+ const name = file.name || file.basename || file.path || "";
13
+ const meta = file.meta || {};
14
+ const embeddable = url !== "";
15
+ if (!embeddable) {
16
+ console.warn(
17
+ '[FluxFiles] "' + name + '" is preview-only (no embeddable URL, e.g. a watermark overlay with allow_download=false), so it was not inserted. Burn in the watermark (Watermark editor, Apply) or issue a downloadable token to embed it.'
18
+ );
19
+ } else if (/[?&](X-Amz-|Signature=)/.test(url)) {
20
+ console.warn("[FluxFiles] Inserting a presigned (expiring) URL, it will break when the URL expires. Use a public disk or public_url for embeds.");
21
+ }
22
+ const isImage = !!file.mime && file.mime.indexOf("image/") === 0 || IMAGE_EXT.test(name);
23
+ return {
24
+ url,
25
+ name,
26
+ isImage,
27
+ embeddable,
28
+ alt: meta.alt_text || name,
29
+ title: meta.title || name,
30
+ width: file.width || null,
31
+ height: file.height || null,
32
+ // Only a permanent URL set can carry a srcset; img_srcset is built from img_base.
33
+ srcset: isImage ? file.img_srcset || "" : "",
34
+ sizes: isImage ? file.img_sizes || "" : ""
35
+ };
36
+ }
37
+ function selectedFiles(payload) {
38
+ const list = Array.isArray(payload) ? payload : payload ? [payload] : [];
39
+ return list.filter((f) => f && !f.is_dir);
40
+ }
41
+
42
+ // src/fluxfilescommand.ts
43
+ function sdk() {
44
+ const g = globalThis.FluxFiles;
45
+ return g && typeof g.open === "function" ? g : FluxFilesSdk;
46
+ }
47
+ var FluxFilesCommand = class extends Command {
48
+ constructor(editor) {
49
+ super(editor);
50
+ this.affectsData = true;
51
+ }
52
+ get _cfg() {
53
+ return this.editor.config.get("fluxfiles") || {};
54
+ }
55
+ refresh() {
56
+ this.isEnabled = true;
57
+ }
58
+ /** Resolves once the picker has been opened (not when a file is chosen). */
59
+ async execute() {
60
+ const cfg = this._cfg;
61
+ const token = typeof cfg.token === "function" ? await cfg.token() : cfg.token || "";
62
+ const options = {
63
+ endpoint: cfg.endpoint || "",
64
+ token,
65
+ disk: cfg.disk || "local",
66
+ mode: "picker",
67
+ multiple: !!cfg.multiple,
68
+ onSelect: (payload) => this._insert(selectedFiles(payload))
69
+ };
70
+ if (cfg.disks) options.disks = cfg.disks;
71
+ if (cfg.path) options.path = cfg.path;
72
+ if (cfg.locale) options.locale = cfg.locale;
73
+ if (cfg.theme) options.theme = cfg.theme;
74
+ if (cfg.allowedTypes) options.allowedTypes = cfg.allowedTypes;
75
+ if (cfg.maxUploadMb) options.maxUploadMb = cfg.maxUploadMb;
76
+ if (cfg.maxFiles) options.maxFiles = cfg.maxFiles;
77
+ if (cfg.onTokenRefresh) options.onTokenRefresh = cfg.onTokenRefresh;
78
+ sdk().open(options);
79
+ }
80
+ _insert(files) {
81
+ const { editor } = this;
82
+ const schema = editor.model.schema;
83
+ const inserted = [];
84
+ for (const file of files) {
85
+ const info = fileInfo(file);
86
+ if (!info.embeddable) continue;
87
+ if (info.isImage && editor.commands.get("insertImage")) {
88
+ const source = { src: info.url, alt: info.alt };
89
+ const type = schema.isRegistered("imageBlock") ? "imageBlock" : "imageInline";
90
+ if (info.srcset && schema.checkAttribute(type, "srcset")) source.srcset = info.srcset;
91
+ if (info.sizes && schema.checkAttribute(type, "sizes")) source.sizes = info.sizes;
92
+ editor.execute("insertImage", { source: [source] });
93
+ this._leaveImage();
94
+ } else {
95
+ editor.model.change((writer) => {
96
+ const attrs = {};
97
+ if (schema.checkAttribute(["$text"], "linkHref")) attrs.linkHref = info.url;
98
+ if (inserted.length) editor.model.insertContent(writer.createText(" "));
99
+ editor.model.insertContent(writer.createText(info.title, attrs));
100
+ });
101
+ }
102
+ inserted.push(file);
103
+ }
104
+ if (inserted.length) {
105
+ editor.editing.view.focus();
106
+ this._cfg.onInsert?.(inserted);
107
+ }
108
+ }
109
+ /**
110
+ * A freshly inserted image stays selected, so the next insert would replace it.
111
+ * Move the caret past it: after an inline image, or into a new paragraph under
112
+ * a block image (the selection post-fixer pulls a root-level caret back onto it).
113
+ */
114
+ _leaveImage() {
115
+ const { model } = this.editor;
116
+ const selected = model.document.selection.getSelectedElement();
117
+ if (!selected) return;
118
+ model.change((writer) => {
119
+ if (selected.name === "imageInline") {
120
+ writer.setSelection(selected, "after");
121
+ } else if (selected.name === "imageBlock" && model.schema.isRegistered("paragraph")) {
122
+ const paragraph = writer.createElement("paragraph");
123
+ writer.insert(paragraph, selected, "after");
124
+ writer.setSelection(paragraph, "in");
125
+ }
126
+ });
127
+ }
128
+ };
129
+
130
+ // src/fluxfiles.ts
131
+ var ICON = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"><path d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M10 16.5v-6h4.5M10 13.5h3.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
132
+ var FluxFiles = class extends Plugin {
133
+ static get pluginName() {
134
+ return "FluxFiles";
135
+ }
136
+ init() {
137
+ const editor = this.editor;
138
+ editor.commands.add("fluxfiles", new FluxFilesCommand(editor));
139
+ editor.ui.componentFactory.add("fluxfiles", (locale) => this._createButton(locale, true));
140
+ }
141
+ afterInit() {
142
+ const editor = this.editor;
143
+ const cfg = editor.config.get("fluxfiles") || {};
144
+ if (cfg.imageInsert === false || !editor.plugins.has("ImageInsertUI")) return;
145
+ const ui = editor.plugins.get("ImageInsertUI");
146
+ ui.registerIntegration({
147
+ name: "fluxfiles",
148
+ observable: editor.commands.get("fluxfiles"),
149
+ buttonViewCreator: () => {
150
+ const button = this._createButton(editor.locale, false);
151
+ button.label = editor.locale.t("Insert image via FluxFiles");
152
+ button.tooltip = true;
153
+ return button;
154
+ },
155
+ formViewCreator: () => this._createButton(editor.locale, false),
156
+ requiresForm: false
157
+ });
158
+ }
159
+ _createButton(locale, withTooltip) {
160
+ const editor = this.editor;
161
+ const command = editor.commands.get("fluxfiles");
162
+ const button = new ButtonView(locale);
163
+ button.set({ label: editor.locale.t("FluxFiles"), icon: ICON, tooltip: withTooltip });
164
+ button.bind("isEnabled").to(command, "isEnabled");
165
+ this.listenTo(button, "execute", () => {
166
+ editor.execute("fluxfiles");
167
+ editor.editing.view.focus();
168
+ });
169
+ return button;
170
+ }
171
+ };
172
+
173
+ // src/index.ts
174
+ var index_default = FluxFiles;
175
+ export {
176
+ FluxFiles,
177
+ FluxFilesCommand,
178
+ index_default as default,
179
+ fileInfo,
180
+ selectedFiles
181
+ };
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@fluxfiles/ckeditor5",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "CKEditor 5 plugin for FluxFiles",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "module": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "src",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "sideEffects": false,
23
+ "scripts": {
24
+ "build": "tsup",
25
+ "dev": "tsup --watch",
26
+ "typecheck": "tsc --noEmit",
27
+ "test": "vitest run"
28
+ },
29
+ "dependencies": {
30
+ "fluxfiles": "^1.0.1"
31
+ },
32
+ "peerDependencies": {
33
+ "ckeditor5": ">=42.0.0"
34
+ },
35
+ "devDependencies": {
36
+ "ckeditor5": "^49.1.0",
37
+ "jsdom": "^25.0.1",
38
+ "tsup": "^8.0.0",
39
+ "typescript": "^5.0.0",
40
+ "vitest": "^2.1.8"
41
+ },
42
+ "publishConfig": { "access": "public" },
43
+ "author": "thai-pc",
44
+ "homepage": "https://github.com/thai-pc/fluxfiles#framework-adapters",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/thai-pc/fluxfiles.git",
48
+ "directory": "packages/ckeditor5"
49
+ },
50
+ "bugs": { "url": "https://github.com/thai-pc/fluxfiles/issues" },
51
+ "keywords": ["fluxfiles", "file-manager", "ckeditor", "ckeditor5", "plugin", "s3", "r2", "upload", "media"]
52
+ }
package/src/config.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { FluxFile } from 'fluxfiles';
2
+
3
+ type MaybePromise<T> = T | Promise<T>;
4
+
5
+ /** `config.fluxfiles`. Option names mirror the CKEditor 4 plugin. */
6
+ export interface FluxFilesConfig {
7
+ /** FluxFiles server URL. */
8
+ endpoint: string;
9
+ /** JWT, or a function returning one (called each time the picker opens). */
10
+ token: string | (() => MaybePromise<string>);
11
+ /** Storage disk. Default `'local'`. */
12
+ disk?: string;
13
+ /** Disks shown in the picker sidebar. */
14
+ disks?: string[];
15
+ /** Folder to open the picker in. */
16
+ path?: string;
17
+ /** UI language code. */
18
+ locale?: string;
19
+ /** `light` | `dark` | `auto`. */
20
+ theme?: string;
21
+ /** Allow multi-file selection; every selected file is inserted. Default `false`. */
22
+ multiple?: boolean;
23
+ /** Restrict selectable types (e.g. `['image']`). */
24
+ allowedTypes?: string[];
25
+ /** Max size per uploaded file, MB. */
26
+ maxUploadMb?: number;
27
+ /** Max files per upload batch. */
28
+ maxFiles?: number;
29
+ /** Called when the picker needs a fresh JWT (401). Return a token or null. */
30
+ onTokenRefresh?: (context: { reason: string; disk?: string; path?: string }) => Promise<string | null>;
31
+ /** Offer FluxFiles in the image toolbar's insert dropdown. Default `true`. */
32
+ imageInsert?: boolean;
33
+ /** Called after the selection has been inserted. */
34
+ onInsert?: (files: FluxFile[]) => void;
35
+ }
36
+
37
+ declare module '@ckeditor/ckeditor5-core' {
38
+ interface EditorConfig {
39
+ fluxfiles?: FluxFilesConfig;
40
+ }
41
+ }
package/src/convert.ts ADDED
@@ -0,0 +1,57 @@
1
+ import type { FluxFile } from 'fluxfiles';
2
+
3
+ /** A selected file normalised into what the editor insert path needs. */
4
+ export interface FileInfo {
5
+ url: string;
6
+ name: string;
7
+ isImage: boolean;
8
+ /** `false` for a preview-only selection (no permanent_url/url) that must not be saved into content. */
9
+ embeddable: boolean;
10
+ alt: string;
11
+ title: string;
12
+ width: number | null;
13
+ height: number | null;
14
+ srcset: string;
15
+ sizes: string;
16
+ }
17
+
18
+ const IMAGE_EXT = /\.(jpe?g|png|gif|webp|svg|bmp|ico|avif)$/i;
19
+
20
+ /**
21
+ * Normalise a FluxFiles `onSelect` entry. Same rules as the CKEditor 4 / TinyMCE
22
+ * plugins: prefer `permanent_url`, refuse a preview-only selection (its only view
23
+ * is a short-lived token URL), warn about presigned (expiring) URLs.
24
+ */
25
+ export function fileInfo(file: FluxFile): FileInfo {
26
+ const url = file.permanent_url || file.url || '';
27
+ const name = file.name || file.basename || file.path || '';
28
+ const meta = file.meta || {};
29
+ const embeddable = url !== '';
30
+ if (!embeddable) {
31
+ console.warn(
32
+ '[FluxFiles] "' + name + '" is preview-only (no embeddable URL, e.g. a watermark overlay with allow_download=false), so it was not inserted. Burn in the watermark (Watermark editor, Apply) or issue a downloadable token to embed it.'
33
+ );
34
+ } else if (/[?&](X-Amz-|Signature=)/.test(url)) {
35
+ console.warn('[FluxFiles] Inserting a presigned (expiring) URL, it will break when the URL expires. Use a public disk or public_url for embeds.');
36
+ }
37
+ const isImage = (!!file.mime && file.mime.indexOf('image/') === 0) || IMAGE_EXT.test(name);
38
+ return {
39
+ url,
40
+ name,
41
+ isImage,
42
+ embeddable,
43
+ alt: meta.alt_text || name,
44
+ title: meta.title || name,
45
+ width: file.width || null,
46
+ height: file.height || null,
47
+ // Only a permanent URL set can carry a srcset; img_srcset is built from img_base.
48
+ srcset: isImage ? file.img_srcset || '' : '',
49
+ sizes: isImage ? file.img_sizes || '' : '',
50
+ };
51
+ }
52
+
53
+ /** `onSelect` hands over one file, an array, or folders; keep only real files. */
54
+ export function selectedFiles(payload: FluxFile | FluxFile[] | null | undefined): FluxFile[] {
55
+ const list = Array.isArray(payload) ? payload : payload ? [payload] : [];
56
+ return list.filter((f) => f && !f.is_dir);
57
+ }
@@ -0,0 +1,78 @@
1
+ import { Plugin, ButtonView } from 'ckeditor5';
2
+ import type { Locale } from 'ckeditor5';
3
+ import type { FluxFilesConfig } from './config';
4
+ import { FluxFilesCommand } from './fluxfilescommand';
5
+
6
+ // The same F-folder glyph the TinyMCE and CKEditor 4 plugins use. currentColor
7
+ // lets CKEditor 5 recolour it for hover / disabled / dark themes.
8
+ const ICON =
9
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">' +
10
+ '<path d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" ' +
11
+ 'stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>' +
12
+ '<path d="M10 16.5v-6h4.5M10 13.5h3.5" ' +
13
+ 'stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
14
+
15
+ /** Minimal shape of the optional ImageInsertUI plugin (CKEditor's image package). */
16
+ interface ImageInsertUiLike {
17
+ registerIntegration(def: {
18
+ name: string;
19
+ observable: unknown;
20
+ buttonViewCreator: (isOnlyOne: boolean) => ButtonView;
21
+ formViewCreator: (isOnlyOne: boolean) => unknown;
22
+ requiresForm?: boolean;
23
+ }): void;
24
+ }
25
+
26
+ /**
27
+ * FluxFiles for CKEditor 5.
28
+ *
29
+ * - command `fluxfiles`, toolbar item `fluxfiles`
30
+ * - an "Insert image via FluxFiles" entry in the image insert dropdown when the
31
+ * image insert UI is loaded (disable with `fluxfiles.imageInsert = false`)
32
+ *
33
+ * Configured under `config.fluxfiles`.
34
+ */
35
+ export class FluxFiles extends Plugin {
36
+ public static get pluginName() {
37
+ return 'FluxFiles' as const;
38
+ }
39
+
40
+ public init(): void {
41
+ const editor = this.editor;
42
+ editor.commands.add('fluxfiles', new FluxFilesCommand(editor));
43
+ editor.ui.componentFactory.add('fluxfiles', (locale) => this._createButton(locale, true));
44
+ }
45
+
46
+ public afterInit(): void {
47
+ const editor = this.editor;
48
+ const cfg = ((editor.config.get as (k: string) => unknown)('fluxfiles') || {}) as FluxFilesConfig;
49
+ if (cfg.imageInsert === false || !editor.plugins.has('ImageInsertUI')) return;
50
+
51
+ const ui = editor.plugins.get('ImageInsertUI') as unknown as ImageInsertUiLike;
52
+ ui.registerIntegration({
53
+ name: 'fluxfiles',
54
+ observable: editor.commands.get('fluxfiles'),
55
+ buttonViewCreator: () => {
56
+ const button = this._createButton(editor.locale, false);
57
+ button.label = editor.locale.t('Insert image via FluxFiles');
58
+ button.tooltip = true;
59
+ return button;
60
+ },
61
+ formViewCreator: () => this._createButton(editor.locale, false),
62
+ requiresForm: false,
63
+ });
64
+ }
65
+
66
+ private _createButton(locale: Locale, withTooltip: boolean): ButtonView {
67
+ const editor = this.editor;
68
+ const command = editor.commands.get('fluxfiles')!;
69
+ const button = new ButtonView(locale);
70
+ button.set({ label: editor.locale.t('FluxFiles'), icon: ICON, tooltip: withTooltip });
71
+ button.bind('isEnabled').to(command, 'isEnabled');
72
+ this.listenTo(button, 'execute', () => {
73
+ editor.execute('fluxfiles');
74
+ editor.editing.view.focus();
75
+ });
76
+ return button;
77
+ }
78
+ }
@@ -0,0 +1,115 @@
1
+ import { Command } from 'ckeditor5';
2
+ import type { Editor } from 'ckeditor5';
3
+ import FluxFilesSdk from 'fluxfiles';
4
+ import type { FluxFile, FluxFilesOpenOptions, FluxFilesSDK } from 'fluxfiles';
5
+ import type { FluxFilesConfig } from './config';
6
+ import { fileInfo, selectedFiles } from './convert';
7
+
8
+ /** Prefer a page-level SDK (script tag), else the bundled `fluxfiles` dependency. */
9
+ function sdk(): FluxFilesSDK {
10
+ const g = (globalThis as { FluxFiles?: FluxFilesSDK }).FluxFiles;
11
+ return g && typeof g.open === 'function' ? g : (FluxFilesSdk as FluxFilesSDK);
12
+ }
13
+
14
+ /**
15
+ * Opens the FluxFiles picker and inserts the selection at the caret.
16
+ * Images become image elements, anything else a link with the file name as text.
17
+ */
18
+ export class FluxFilesCommand extends Command {
19
+ constructor(editor: Editor) {
20
+ super(editor);
21
+ this.affectsData = true;
22
+ }
23
+
24
+ private get _cfg(): FluxFilesConfig {
25
+ return ((this.editor.config.get as (k: string) => unknown)('fluxfiles') || {}) as FluxFilesConfig;
26
+ }
27
+
28
+ public override refresh(): void {
29
+ this.isEnabled = true;
30
+ }
31
+
32
+ /** Resolves once the picker has been opened (not when a file is chosen). */
33
+ public override async execute(): Promise<void> {
34
+ const cfg = this._cfg;
35
+ // The token is only ever handed to the SDK, which posts it to the iframe via
36
+ // postMessage after checking the iframe's origin. It never goes into a URL.
37
+ const token = typeof cfg.token === 'function' ? await cfg.token() : cfg.token || '';
38
+ // `path` is accepted by the SDK at runtime but missing from its typings.
39
+ const options: FluxFilesOpenOptions & { path?: string } = {
40
+ endpoint: cfg.endpoint || '',
41
+ token,
42
+ disk: cfg.disk || 'local',
43
+ mode: 'picker',
44
+ multiple: !!cfg.multiple,
45
+ onSelect: (payload) => this._insert(selectedFiles(payload)),
46
+ };
47
+ if (cfg.disks) options.disks = cfg.disks;
48
+ if (cfg.path) options.path = cfg.path;
49
+ if (cfg.locale) options.locale = cfg.locale;
50
+ if (cfg.theme) options.theme = cfg.theme;
51
+ if (cfg.allowedTypes) options.allowedTypes = cfg.allowedTypes;
52
+ if (cfg.maxUploadMb) options.maxUploadMb = cfg.maxUploadMb;
53
+ if (cfg.maxFiles) options.maxFiles = cfg.maxFiles;
54
+ if (cfg.onTokenRefresh) options.onTokenRefresh = cfg.onTokenRefresh;
55
+ sdk().open(options);
56
+ }
57
+
58
+ private _insert(files: FluxFile[]): void {
59
+ const { editor } = this;
60
+ const schema = editor.model.schema;
61
+ const inserted: FluxFile[] = [];
62
+
63
+ for (const file of files) {
64
+ const info = fileInfo(file);
65
+ if (!info.embeddable) continue; // preview-only: already warned
66
+
67
+ if (info.isImage && editor.commands.get('insertImage')) {
68
+ const source: Record<string, unknown> = { src: info.url, alt: info.alt };
69
+ // Responsive attributes only when the image plugin's schema knows them
70
+ // (core ImageEditing registers `srcset` as a plain string; it has no `sizes`
71
+ // model attribute and always writes sizes="100vw", so img_sizes is only
72
+ // honoured by a custom image plugin that registers one).
73
+ const type = schema.isRegistered('imageBlock') ? 'imageBlock' : 'imageInline';
74
+ if (info.srcset && schema.checkAttribute(type, 'srcset')) source.srcset = info.srcset;
75
+ if (info.sizes && schema.checkAttribute(type, 'sizes')) source.sizes = info.sizes;
76
+ editor.execute('insertImage', { source: [source] });
77
+ this._leaveImage();
78
+ } else {
79
+ editor.model.change((writer) => {
80
+ const attrs: Record<string, string> = {};
81
+ if (schema.checkAttribute(['$text'], 'linkHref')) attrs.linkHref = info.url;
82
+ // Separate consecutive inserts so several links don't fuse into one word.
83
+ if (inserted.length) editor.model.insertContent(writer.createText(' '));
84
+ editor.model.insertContent(writer.createText(info.title, attrs));
85
+ });
86
+ }
87
+ inserted.push(file);
88
+ }
89
+
90
+ if (inserted.length) {
91
+ editor.editing.view.focus();
92
+ this._cfg.onInsert?.(inserted);
93
+ }
94
+ }
95
+
96
+ /**
97
+ * A freshly inserted image stays selected, so the next insert would replace it.
98
+ * Move the caret past it: after an inline image, or into a new paragraph under
99
+ * a block image (the selection post-fixer pulls a root-level caret back onto it).
100
+ */
101
+ private _leaveImage(): void {
102
+ const { model } = this.editor;
103
+ const selected = model.document.selection.getSelectedElement();
104
+ if (!selected) return;
105
+ model.change((writer) => {
106
+ if (selected.name === 'imageInline') {
107
+ writer.setSelection(selected, 'after');
108
+ } else if (selected.name === 'imageBlock' && model.schema.isRegistered('paragraph')) {
109
+ const paragraph = writer.createElement('paragraph');
110
+ writer.insert(paragraph, selected, 'after');
111
+ writer.setSelection(paragraph, 'in');
112
+ }
113
+ });
114
+ }
115
+ }
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { FluxFiles } from './fluxfiles';
2
+
3
+ export { FluxFiles, FluxFilesCommand };
4
+ export { fileInfo, selectedFiles } from './convert';
5
+ export type { FileInfo } from './convert';
6
+ export type { FluxFilesConfig } from './config';
7
+ export default FluxFiles;
8
+
9
+ import { FluxFilesCommand } from './fluxfilescommand';
10
+
11
+ declare module '@ckeditor/ckeditor5-core' {
12
+ interface PluginsMap {
13
+ [FluxFiles.pluginName]: FluxFiles;
14
+ }
15
+ }