From 36fbbec28d7b926faf7f8a9086c6a9992555a42e Mon Sep 17 00:00:00 2001 From: Amalija Ramljak Date: Mon, 16 Nov 2026 14:52:33 +0100 Subject: [PATCH 1/3] JGLWEB-1832 make CKEditor 5 plugin locations safe for versioned editor data - add copyLocationsOnLoad option: loaded elements switch to a copy of their location before they can be edited - never delete locations from the editor: undo, paste and drag and drop can bring removed elements back - send source when updating a location, so it is kept after the first edit - run location requests of one element one after another, update targets the location created before it - report failed location requests through the onError option, revert the selection when creating fails - keep stored CSS class and variation when data is saved before the selected image is loaded - export waitForLocationRequests() and hasPendingLocationRequests() for integrations --- bundle/Controller/Configuration.php | 4 ++ .../public/js/ckeditor-plugin/constants.js | 5 +- .../handle-remote-resource-location.js | 30 +++++--- .../operation-handlers/index.js | 3 +- .../operation-handlers/remove.js | 17 ----- .../remote-resource-location/create.js | 43 ++++++++---- .../remote-resource-location/delete.js | 11 --- .../remote-resource-location/load.js | 70 +++++++++++++++++++ .../remote-resource-location/update.js | 22 ++++-- .../conversion/editing-downcast.js | 1 - .../js/ckeditor-plugin/conversion/upcast.js | 43 +++--------- .../public/js/ckeditor-plugin/index.js | 10 ++- .../public/js/ckeditor-plugin/plugin.js | 7 ++ .../utils/location-requests.js | 58 +++++++++++++++ .../translations/ngremotemedia.en.yaml | 5 ++ .../translations/ngremotemedia.hr.yaml | 5 ++ .../translations/ngremotemedia.no.yaml | 5 ++ docs/CHANGELOG.md | 20 ++++++ 18 files changed, 265 insertions(+), 94 deletions(-) delete mode 100644 bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/operation-handlers/remove.js delete mode 100644 bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/delete.js create mode 100644 bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/load.js create mode 100644 bundle/Resources/public/js/ckeditor-plugin/utils/location-requests.js diff --git a/bundle/Controller/Configuration.php b/bundle/Controller/Configuration.php index 73a3346c..a90efc64 100644 --- a/bundle/Controller/Configuration.php +++ b/bundle/Controller/Configuration.php @@ -143,6 +143,10 @@ private function resolveTranslations(): array 'upload_error_existing_resource' => $this->translator->trans('ngrm.edit.vue.upload.error.existing_resource', [], 'ngremotemedia'), 'upload_error_existing_resource_in_folder' => $this->translator->trans('ngrm.edit.vue.upload.error.existing_resource_in_folder', [], 'ngremotemedia'), 'upload_error_unsupported_resource_type' => $this->translator->trans('ngrm.edit.vue.upload.error.unsupported_resource_type', [], 'ngremotemedia'), + 'ckeditor_location_load_error' => $this->translator->trans('ngrm.edit.vue.ckeditor.location_load_error', [], 'ngremotemedia'), + 'ckeditor_location_copy_error' => $this->translator->trans('ngrm.edit.vue.ckeditor.location_copy_error', [], 'ngremotemedia'), + 'ckeditor_location_create_error' => $this->translator->trans('ngrm.edit.vue.ckeditor.location_create_error', [], 'ngremotemedia'), + 'ckeditor_location_update_error' => $this->translator->trans('ngrm.edit.vue.ckeditor.location_update_error', [], 'ngremotemedia'), ]; } diff --git a/bundle/Resources/public/js/ckeditor-plugin/constants.js b/bundle/Resources/public/js/ckeditor-plugin/constants.js index f505d2b4..afee6b46 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/constants.js +++ b/bundle/Resources/public/js/ckeditor-plugin/constants.js @@ -44,7 +44,6 @@ export const defaultValue = { endpoints: { createLocation: '/ngremotemedia/ajax/location/create', updateLocation: locationId => `/ngremotemedia/ajax/location/update/${locationId}`, - deleteLocation: locationId => `/ngremotemedia/ajax/location/delete/${locationId}`, getSelectedImage: locationId => `/ngremotemedia/ajax/location/${locationId}/selected-image`, viewResource: locationId => `/ngremotemedia/ajax/resource/view/${locationId}`, }, @@ -147,6 +146,10 @@ export const defaultValue = { 'upload_placeholder_new_folder': 'upload_placeholder_new_folder', 'upload_error_existing_resource': 'upload_error_existing_resource', 'upload_error_unsupported_resource_type': 'upload_error_unsupported_resource_type', + 'ckeditor_location_load_error': 'Remote media could not be loaded in the editor. The stored media is kept unchanged.', + 'ckeditor_location_copy_error': 'Remote media could not be prepared for editing. The stored media is kept unchanged, select it again to edit it.', + 'ckeditor_location_create_error': 'Selected remote media could not be saved. Select it again.', + 'ckeditor_location_update_error': 'Changes to the remote media could not be saved. Make the change again.', }, inputFields: { locationId: 'locationId', diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/handle-remote-resource-location.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/handle-remote-resource-location.js index 56b0ade4..8288d4b1 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/handle-remote-resource-location.js +++ b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/handle-remote-resource-location.js @@ -1,23 +1,33 @@ import { attributes } from '../../constants'; import createLocation from './remote-resource-location/create'; -import deleteLocation from './remote-resource-location/delete'; import updateLocation from './remote-resource-location/update'; +/** + * Locations are never deleted from the editor: removed, replaced or cut elements can come back through undo or paste, + * and the stored editor data may still reference them until it is saved. + */ const handleRemoteResourceLocation = ({ editor, model, domElement, eventDetail: { selectedImage, inputFields } }) => { selectedImage.cropSettings = domElement.querySelector(`[name="${inputFields.cropSettings}"]`)?.value ?? ''; - const oldImage = model.getAttribute(attributes.selectedImage); - if (oldImage.id !== selectedImage.id) { - if (oldImage.id) { - deleteLocation({ editor, model }); - } - + const previousImage = model.getAttribute(attributes.selectedImage); + if (previousImage.id === selectedImage.id) { if (selectedImage.id) { - createLocation({ editor, model, selectedImage }); + updateLocation({ editor, model, selectedImage }); } - } else { - updateLocation({ editor, model, selectedImage }); + + return; } + + if (selectedImage.id) { + createLocation({ editor, model, selectedImage, previousImage }); + + return; + } + + // Resource removed from the element, which then no longer references a location + editor.model.change((writer) => { + writer.setAttribute(attributes.locationId, null, model); + }); }; export default handleRemoteResourceLocation; diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/operation-handlers/index.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/operation-handlers/index.js index c346fed7..b19bb0c9 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/operation-handlers/index.js +++ b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/operation-handlers/index.js @@ -1,4 +1,3 @@ import alignment from './alignment'; -import remove from './remove'; -export { alignment, remove }; +export { alignment }; diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/operation-handlers/remove.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/operation-handlers/remove.js deleted file mode 100644 index c90c4edb..00000000 --- a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/operation-handlers/remove.js +++ /dev/null @@ -1,17 +0,0 @@ -import { attributes, pluginKey } from "../../../constants"; -import deleteLocation from "../remote-resource-location/delete"; - -const handleRemove = ({ editor, operation }) => { - if ( - operation.targetPosition.nodeAfter.name !== pluginKey || - operation.batch.operations[0].type === "detach" - ) { - return; - } - - if (operation.targetPosition.nodeAfter.getAttribute(attributes.locationId)) { - deleteLocation({ editor, model: operation.targetPosition.nodeAfter }); - } -}; - -export default handleRemove; diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/create.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/create.js index c930c747..629b84c1 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/create.js +++ b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/create.js @@ -1,21 +1,38 @@ -import { attributes, defaultValue, pluginKey } from '../../../constants'; +import { attributes, pluginKey } from '../../../constants'; +import { enqueueLocationRequest, getEndpoint, reportError, request } from '../../../utils/location-requests'; -const createLocation = ({ editor, model, selectedImage }) => { - const createLocationEndpoint = editor.config.get(pluginKey).endpoints.createLocation ?? defaultValue.endpoints.createLocation; +/** + * Creates a location for the newly selected resource. When the request fails, the element goes back to the + * previously selected resource and the editor is notified, instead of silently storing an element without a location. + */ +const createLocation = ({ editor, model, selectedImage, previousImage }) => { + // Another resource may have been selected in the meantime, its own request sets the location + const isStillSelected = () => model.getAttribute(attributes.selectedImage).id === selectedImage.id; - fetch(createLocationEndpoint, { - method: 'POST', - body: JSON.stringify({ - ...selectedImage, - source: editor.config.get(pluginKey).source - }), - }) - .then(response => response.json()) - .then(({ locationId }) => { + enqueueLocationRequest(model, async () => { + const response = await request(getEndpoint(editor, 'createLocation'), { + method: 'POST', + body: JSON.stringify({ + ...selectedImage, + source: editor.config.get(pluginKey).source, + }), + }); + const { locationId } = await response.json(); + + if (isStillSelected()) { editor.model.change((writer) => { writer.setAttribute(attributes.locationId, locationId, model); }); - }); + } + }).catch((error) => { + if (isStillSelected()) { + editor.model.change((writer) => { + writer.setAttribute(attributes.selectedImage, previousImage, model); + }); + } + + reportError(editor, 'ckeditor_location_create_error', error); + }); }; export default createLocation; diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/delete.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/delete.js deleted file mode 100644 index 2a5f443f..00000000 --- a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/delete.js +++ /dev/null @@ -1,11 +0,0 @@ -import { attributes, defaultValue, pluginKey } from '../../../constants'; - -const deleteLocation = ({ editor, model }) => { - const deleteLocationEndpoint = editor.config.get(pluginKey).endpoints.deleteLocation ?? defaultValue.endpoints.deleteLocation; - - fetch(deleteLocationEndpoint(model.getAttribute(attributes.locationId)), { - method: 'DELETE', - }); -}; - -export default deleteLocation; diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/load.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/load.js new file mode 100644 index 00000000..1326c132 --- /dev/null +++ b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/load.js @@ -0,0 +1,70 @@ +import { attributes, pluginKey } from '../../../constants'; +import { enqueueLocationRequest, getEndpoint, reportError, request } from '../../../utils/location-requests'; + +const copy = (editor, selectedImage) => request(getEndpoint(editor, 'createLocation'), { + method: 'POST', + body: JSON.stringify({ + ...selectedImage, + cropSettings: JSON.stringify(selectedImage.variations ?? {}), + source: editor.config.get(pluginKey).source, + }), +}).then(response => response.json()); + +/** + * Loads the selected image of a stored element. + * + * With the `copyLocationsOnLoad` option, the element is switched to a copy of the stored location before it can be + * edited, so changes made in the editor never reach the stored location, which other versions, translations or copies + * of the content may reference. When loading or copying fails the element keeps the stored location unchanged. + */ +const loadLocation = ({ editor, model, locationId }) => { + const { copyLocationsOnLoad } = editor.config.get(pluginKey); + + enqueueLocationRequest(model, async () => { + let selectedImage; + try { + selectedImage = await request(getEndpoint(editor, 'getSelectedImage')(locationId)).then(response => response.json()); + } catch (error) { + reportError(editor, 'ckeditor_location_load_error', error); + + return; + } + + let editedLocationId = locationId; + if (copyLocationsOnLoad) { + try { + ({ locationId: editedLocationId } = await copy(editor, selectedImage)); + } catch (error) { + reportError(editor, 'ckeditor_location_copy_error', error); + + return; + } + } + + // Values restored on upcast, unless another resource has been selected in the meantime + const currentValues = model.getAttribute(attributes.selectedImage); + if (currentValues.id) { + return; + } + + const variationName = currentValues.selectedVariation?.label; + + // Not undoable: undo must not switch the element back to the stored location + editor.model.enqueueChange({ isUndoable: false }, (writer) => { + writer.setAttribute(attributes.locationId, editedLocationId, model); + writer.setAttribute( + attributes.selectedImage, + { + ...selectedImage, + cssClass: currentValues.cssClass, + selectedVariation: variationName + ? { label: variationName, value: selectedImage.variations?.[variationName] } + : null, + }, + model, + ); + }); + }); +}; + +export default loadLocation; diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/update.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/update.js index 6f038538..af46719f 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/update.js +++ b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/update.js @@ -1,12 +1,22 @@ -import { attributes, defaultValue, pluginKey } from '../../../constants'; +import { attributes, pluginKey } from '../../../constants'; +import { enqueueLocationRequest, getEndpoint, reportError, request } from '../../../utils/location-requests'; const updateLocation = ({ editor, model, selectedImage }) => { - const updateLocationEndpoint = editor.config.get(pluginKey).endpoints.updateLocation ?? defaultValue.endpoints.updateLocation; + enqueueLocationRequest(model, () => { + // Read when the request runs: a preceding create or copy request sets the location of the element + const locationId = model.getAttribute(attributes.locationId); + if (!locationId) { + return null; + } - fetch(updateLocationEndpoint(model.getAttribute(attributes.locationId)), { - method: 'PUT', - body: JSON.stringify(selectedImage), - }); + return request(getEndpoint(editor, 'updateLocation')(locationId), { + method: 'PUT', + body: JSON.stringify({ + ...selectedImage, + source: editor.config.get(pluginKey).source, + }), + }); + }).catch(error => reportError(editor, 'ckeditor_location_update_error', error)); }; export default updateLocation; diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast.js index 2b91cde3..77a5b3e1 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast.js +++ b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast.js @@ -3,7 +3,6 @@ import { dataModel, attributes, pluginKey, editingView, defaultValue } from '../ import { toWidget } from '@ckeditor/ckeditor5-widget'; import renderField from './editing-downcast-utils/render-field'; import * as operationHandlers from './editing-downcast-utils/operation-handlers'; -import createLocation from './editing-downcast-utils/remote-resource-location/create'; import handleRemoteResourceLocation from './editing-downcast-utils/handle-remote-resource-location'; /** diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/upcast.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/upcast.js index f02551a0..ac0e8ef6 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/conversion/upcast.js +++ b/bundle/Resources/public/js/ckeditor-plugin/conversion/upcast.js @@ -1,6 +1,7 @@ -import { dataModel, attributes, pluginKey, defaultValue } from '../constants'; +import { dataModel, attributes, defaultValue } from '../constants'; import getFormat from '../utils/get-format'; import { createFieldId } from '../utils/field-id'; +import loadLocation from './editing-downcast-utils/remote-resource-location/load'; /** * Defines the upcast conversion. @@ -18,45 +19,23 @@ const defineUpcast = (editor) => { const model = writer.createElement(dataModel.name, { [attributes.fieldId]: fieldId || createFieldId(editor), [attributes.locationId]: locationId || null, - [attributes.selectedImage]: defaultValue.selectedImage, + // Stored values are kept right away, so they are not lost when the editor data is saved + // before the selected image is loaded, or when loading it fails + [attributes.selectedImage]: { + ...defaultValue.selectedImage, + cssClass: cssClass || '', + selectedVariation: variationName ? { label: variationName } : null, + }, }); if (alignment) { writer.setAttribute(attributes.alignment, alignment, model); } - if (!locationId) { - return model; + if (locationId) { + loadLocation({ editor, model, locationId }); } - const getSelectedImageEndpoint = editor.config.get(pluginKey).endpoints.getSelectedImage ?? defaultValue.endpoints.getSelectedImage; - - fetch(getSelectedImageEndpoint(locationId)) - .then((response) => { - if (!response.ok) { - throw new Error(`Failed to load selected image for location ${locationId}: ${response.status}`); - } - - return response.json(); - }) - .then((selectedImage) => { - editor.model.change((writer) => { - writer.setAttribute( - attributes.selectedImage, - { - ...selectedImage, - cssClass, - selectedVariation: { - label: variationName, - value: selectedImage.variations?.[variationName], - }, - }, - model, - ); - }); - }) - .catch(error => console.error(error)); - return model; }, }); diff --git a/bundle/Resources/public/js/ckeditor-plugin/index.js b/bundle/Resources/public/js/ckeditor-plugin/index.js index 7efc162c..8d5fe77a 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/index.js +++ b/bundle/Resources/public/js/ckeditor-plugin/index.js @@ -2,5 +2,13 @@ import NetgenRemoteMediaPlugin from './plugin'; import { pluginKey } from './constants'; import renderNgrmEditorViews from './render-views'; import htmlFormat from './formats/html'; +import { hasPendingLocationRequests, waitForLocationRequests } from './utils/location-requests'; -export { NetgenRemoteMediaPlugin, pluginKey as netgenremoteMediaPluginKey, renderNgrmEditorViews, htmlFormat }; +export { + NetgenRemoteMediaPlugin, + pluginKey as netgenremoteMediaPluginKey, + renderNgrmEditorViews, + htmlFormat, + waitForLocationRequests, + hasPendingLocationRequests, +}; diff --git a/bundle/Resources/public/js/ckeditor-plugin/plugin.js b/bundle/Resources/public/js/ckeditor-plugin/plugin.js index b8bcf9d9..86ea7484 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/plugin.js +++ b/bundle/Resources/public/js/ckeditor-plugin/plugin.js @@ -20,6 +20,13 @@ function NetgenRemoteMediaPlugin(editor) { endpoints: defaultValue.endpoints, /** Storage format of the remote media element in editor data, defaults to `formats/html.js` */ format: null, + /** + * Edit copies of stored locations instead of the stored locations, for integrations which store editor data + * in versions, translations or copies sharing the same locations + */ + copyLocationsOnLoad: false, + /** Called with a translated message and the error when a location request fails, defaults to `console.error` */ + onError: null, }); editor.commands.add(pluginKey, new NetgenRemoteMediaCommand(editor)); diff --git a/bundle/Resources/public/js/ckeditor-plugin/utils/location-requests.js b/bundle/Resources/public/js/ckeditor-plugin/utils/location-requests.js new file mode 100644 index 00000000..302191dc --- /dev/null +++ b/bundle/Resources/public/js/ckeditor-plugin/utils/location-requests.js @@ -0,0 +1,58 @@ +import { defaultValue, pluginKey } from '../constants'; +import mergeDeep from './merge-deep'; + +/** Location requests of all editors on the page which have not settled yet */ +const pendingRequests = new Set(); + +/** Last queued location request per model element, requests of one element run one after another */ +const elementQueues = new WeakMap(); + +/** + * Resolves when all location requests started so far have settled. Integrations wait for it before submitting + * editor data, so an element whose location is still being created is not stored without its location. + */ +export const waitForLocationRequests = () => Promise.allSettled([...pendingRequests]); + +export const hasPendingLocationRequests = () => pendingRequests.size > 0; + +/** + * Runs `task` after the previous location request of the same model element has settled, so for example an update + * always targets the location created or copied by the request before it. + */ +export const enqueueLocationRequest = (model, task) => { + const request = (elementQueues.get(model) ?? Promise.resolve()).then(task); + const settled = request.catch(() => {}); + + elementQueues.set(model, settled); + pendingRequests.add(settled); + settled.then(() => pendingRequests.delete(settled)); + + return request; +}; + +/** Fetch which rejects on HTTP error responses too */ +export const request = async (url, options = {}) => { + const response = await fetch(url, options); + + if (!response.ok) { + throw new Error(`Request ${options.method ?? 'GET'} ${url} failed with status ${response.status}`); + } + + return response; +}; + +export const getEndpoint = (editor, name) => editor.config.get(pluginKey).endpoints?.[name] ?? defaultValue.endpoints[name]; + +/** Reports a failed location request through the `onError` plugin option, with a translated message */ +export const reportError = (editor, translationKey, error) => { + const pluginConfig = editor.config.get(pluginKey); + const message = mergeDeep(defaultValue.config, pluginConfig.config).translations[translationKey] ?? translationKey; + + if (typeof pluginConfig.onError === 'function') { + pluginConfig.onError(message, error); + + return; + } + + console.error(message, error); +}; diff --git a/bundle/Resources/translations/ngremotemedia.en.yaml b/bundle/Resources/translations/ngremotemedia.en.yaml index eaa5a169..bbf04a26 100644 --- a/bundle/Resources/translations/ngremotemedia.en.yaml +++ b/bundle/Resources/translations/ngremotemedia.en.yaml @@ -30,6 +30,11 @@ ngrm: select_folder_interaction: button: 'Select folder' empty: 'No folder selected' + ckeditor: + location_load_error: 'Remote media could not be loaded in the editor. The stored media is kept unchanged.' + location_copy_error: 'Remote media could not be prepared for editing. The stored media is kept unchanged, select it again to edit it.' + location_create_error: 'Selected remote media could not be saved. Select it again.' + location_update_error: 'Changes to the remote media could not be saved. Make the change again.' preview: alternate_text: 'Alternate text' alternate_text_info: 'Alt text is stored directly in Cloudinary on a resource so updating it here will also update it on all other locations which are using that same resource.' diff --git a/bundle/Resources/translations/ngremotemedia.hr.yaml b/bundle/Resources/translations/ngremotemedia.hr.yaml index ba762000..f74692a6 100644 --- a/bundle/Resources/translations/ngremotemedia.hr.yaml +++ b/bundle/Resources/translations/ngremotemedia.hr.yaml @@ -30,6 +30,11 @@ ngrm: select_folder_interaction: button: 'Odaberi mapu' empty: 'Nije odabrana ni jedna mapa' + ckeditor: + location_load_error: 'Resurs nije moguće učitati u uređivač. Spremljeni resurs ostaje nepromijenjen.' + location_copy_error: 'Resurs nije moguće pripremiti za uređivanje. Spremljeni resurs ostaje nepromijenjen, odaberite ga ponovno za uređivanje.' + location_create_error: 'Odabrani resurs nije moguće spremiti. Odaberite ga ponovno.' + location_update_error: 'Promjene resursa nije moguće spremiti. Ponovite promjenu.' preview: alternate_text: 'Alternativni tekst' alternate_text_info: 'Alternativni tekst se sprema direktno na resurs u oblaku. Ukoliko se promjeni ovdje, promjenit će se i na svim ostalim lokacijama koje koriste taj resurs.' diff --git a/bundle/Resources/translations/ngremotemedia.no.yaml b/bundle/Resources/translations/ngremotemedia.no.yaml index 5220f0a1..24830b54 100644 --- a/bundle/Resources/translations/ngremotemedia.no.yaml +++ b/bundle/Resources/translations/ngremotemedia.no.yaml @@ -30,6 +30,11 @@ ngrm: select_folder_interaction: button: 'Select folder' empty: 'No folder selected' + ckeditor: + location_load_error: 'Remote media could not be loaded in the editor. The stored media is kept unchanged.' + location_copy_error: 'Remote media could not be prepared for editing. The stored media is kept unchanged, select it again to edit it.' + location_create_error: 'Selected remote media could not be saved. Select it again.' + location_update_error: 'Changes to the remote media could not be saved. Make the change again.' preview: alternate_text: 'Alternate text' alternate_text_info: 'Alt text is stored directly to the resource in the cloud. Changing it here will also change it on all other locations which are using that same resource.' diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 53c6bb14..f42d5438 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,5 +1,25 @@ # Netgen Remote Media Bundle changelog +## 3.1.1 + +### Added + +* CKEditor 5 plugin `copyLocationsOnLoad` option, which switches every loaded element to a copy of its stored location before it can be edited, for integrations whose stored editor data is shared by versions, translations or copies (the edited data then never changes locations referenced by other stored data) +* CKEditor 5 plugin `onError` option, called with a translated message and the error when loading, copying, creating or updating a location fails (defaults to `console.error`), with the `ngrm.edit.vue.ckeditor.*` translations +* `waitForLocationRequests()` and `hasPendingLocationRequests()` exports of the CKEditor 5 plugin, to check for and wait for pending location requests before submitting editor data (an element whose location is still being created would be stored without it) + +### Changed + +* CKEditor 5 plugin no longer deletes locations: removing an element or replacing its resource leaves the location in the database, as the element can come back through undo, paste or drag and drop, the `deleteLocation` endpoint option is removed +* CKEditor 5 plugin location requests of one element run one after another, so an update always targets the location created by the request before it + +### Fixed + +* CKEditor 5 plugin sends the configured `source` when updating a location, so the location keeps it after the first edit +* CKEditor 5 plugin keeps the stored CSS class and variation when the editor data is saved before the selected image is loaded or when loading it fails +* CKEditor 5 plugin no longer silently stores an element without a location when creating the location fails, the element goes back to the previously selected resource and `onError` is called +* CKEditor 5 plugin clears the location of an element when its resource is removed in the interface, instead of keeping the previous location + ## 3.1.0 ### Added From a8947d68603aea1f24983895cfea778fe0e5201c Mon Sep 17 00:00:00 2001 From: Amalija Ramljak Date: Fri, 20 Nov 2026 10:49:20 +0100 Subject: [PATCH 2/3] JGLWEB-1832 copy CKEditor 5 plugin locations on the first change and delete unused locations on save - copyLocationsOnLoad is replaced by copyLocationsOnChange: stored locations are copied on the first change of an element instead of when the editor loads, opening the editor creates nothing - locations the editor created or copied (and, without copyLocationsOnChange, the stored locations it loaded) are deleted on submit of the form containing the editor when no editor on the page references them anymore, with keepalive requests - deleteUnusedLocations() export for integrations which save the editor data otherwise, deleteLocation endpoint option restored - the copy error translation is removed, a failed copy reports the update error - changelog section renamed to 3.2.0 --- bundle/Controller/Configuration.php | 1 - .../public/js/ckeditor-plugin/constants.js | 2 +- .../handle-remote-resource-location.js | 5 +- .../remote-resource-location/create.js | 3 + .../remote-resource-location/load.js | 36 ++----- .../remote-resource-location/update.js | 38 +++++-- .../public/js/ckeditor-plugin/index.js | 2 + .../public/js/ckeditor-plugin/plugin.js | 12 ++- .../js/ckeditor-plugin/utils/locations.js | 101 ++++++++++++++++++ .../translations/ngremotemedia.en.yaml | 1 - .../translations/ngremotemedia.hr.yaml | 1 - .../translations/ngremotemedia.no.yaml | 1 - docs/CHANGELOG.md | 9 +- 13 files changed, 163 insertions(+), 49 deletions(-) create mode 100644 bundle/Resources/public/js/ckeditor-plugin/utils/locations.js diff --git a/bundle/Controller/Configuration.php b/bundle/Controller/Configuration.php index a90efc64..10cdd591 100644 --- a/bundle/Controller/Configuration.php +++ b/bundle/Controller/Configuration.php @@ -144,7 +144,6 @@ private function resolveTranslations(): array 'upload_error_existing_resource_in_folder' => $this->translator->trans('ngrm.edit.vue.upload.error.existing_resource_in_folder', [], 'ngremotemedia'), 'upload_error_unsupported_resource_type' => $this->translator->trans('ngrm.edit.vue.upload.error.unsupported_resource_type', [], 'ngremotemedia'), 'ckeditor_location_load_error' => $this->translator->trans('ngrm.edit.vue.ckeditor.location_load_error', [], 'ngremotemedia'), - 'ckeditor_location_copy_error' => $this->translator->trans('ngrm.edit.vue.ckeditor.location_copy_error', [], 'ngremotemedia'), 'ckeditor_location_create_error' => $this->translator->trans('ngrm.edit.vue.ckeditor.location_create_error', [], 'ngremotemedia'), 'ckeditor_location_update_error' => $this->translator->trans('ngrm.edit.vue.ckeditor.location_update_error', [], 'ngremotemedia'), ]; diff --git a/bundle/Resources/public/js/ckeditor-plugin/constants.js b/bundle/Resources/public/js/ckeditor-plugin/constants.js index afee6b46..6b5ed952 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/constants.js +++ b/bundle/Resources/public/js/ckeditor-plugin/constants.js @@ -44,6 +44,7 @@ export const defaultValue = { endpoints: { createLocation: '/ngremotemedia/ajax/location/create', updateLocation: locationId => `/ngremotemedia/ajax/location/update/${locationId}`, + deleteLocation: locationId => `/ngremotemedia/ajax/location/delete/${locationId}`, getSelectedImage: locationId => `/ngremotemedia/ajax/location/${locationId}/selected-image`, viewResource: locationId => `/ngremotemedia/ajax/resource/view/${locationId}`, }, @@ -147,7 +148,6 @@ export const defaultValue = { 'upload_error_existing_resource': 'upload_error_existing_resource', 'upload_error_unsupported_resource_type': 'upload_error_unsupported_resource_type', 'ckeditor_location_load_error': 'Remote media could not be loaded in the editor. The stored media is kept unchanged.', - 'ckeditor_location_copy_error': 'Remote media could not be prepared for editing. The stored media is kept unchanged, select it again to edit it.', 'ckeditor_location_create_error': 'Selected remote media could not be saved. Select it again.', 'ckeditor_location_update_error': 'Changes to the remote media could not be saved. Make the change again.', }, diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/handle-remote-resource-location.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/handle-remote-resource-location.js index 8288d4b1..f7221b0e 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/handle-remote-resource-location.js +++ b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/handle-remote-resource-location.js @@ -3,8 +3,9 @@ import createLocation from './remote-resource-location/create'; import updateLocation from './remote-resource-location/update'; /** - * Locations are never deleted from the editor: removed, replaced or cut elements can come back through undo or paste, - * and the stored editor data may still reference them until it is saved. + * Locations are not deleted when an element is removed or its resource replaced: the element can come back through + * undo, paste or drag and drop. Locations which are no longer in the editor data are deleted when the data is saved, + * see `utils/locations.js`. */ const handleRemoteResourceLocation = ({ editor, model, domElement, eventDetail: { selectedImage, inputFields } }) => { selectedImage.cropSettings = domElement.querySelector(`[name="${inputFields.cropSettings}"]`)?.value ?? ''; diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/create.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/create.js index 629b84c1..08176ef1 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/create.js +++ b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/create.js @@ -1,5 +1,6 @@ import { attributes, pluginKey } from '../../../constants'; import { enqueueLocationRequest, getEndpoint, reportError, request } from '../../../utils/location-requests'; +import { addOwnLocation } from '../../../utils/locations'; /** * Creates a location for the newly selected resource. When the request fails, the element goes back to the @@ -18,6 +19,8 @@ const createLocation = ({ editor, model, selectedImage, previousImage }) => { }), }); const { locationId } = await response.json(); + // Deleted once it is no longer in the editor data, also when another resource has been selected in the meantime + addOwnLocation(editor, locationId); if (isStillSelected()) { editor.model.change((writer) => { diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/load.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/load.js index 1326c132..e5e8a07c 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/load.js +++ b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/load.js @@ -1,24 +1,18 @@ import { attributes, pluginKey } from '../../../constants'; import { enqueueLocationRequest, getEndpoint, reportError, request } from '../../../utils/location-requests'; - -const copy = (editor, selectedImage) => request(getEndpoint(editor, 'createLocation'), { - method: 'POST', - body: JSON.stringify({ - ...selectedImage, - cropSettings: JSON.stringify(selectedImage.variations ?? {}), - source: editor.config.get(pluginKey).source, - }), -}).then(response => response.json()); +import { addStoredLocation } from '../../../utils/locations'; /** - * Loads the selected image of a stored element. + * Loads the selected image of a stored element. When loading fails the element keeps the stored location unchanged. * - * With the `copyLocationsOnLoad` option, the element is switched to a copy of the stored location before it can be - * edited, so changes made in the editor never reach the stored location, which other versions, translations or copies - * of the content may reference. When loading or copying fails the element keeps the stored location unchanged. + * Without the `copyLocationsOnChange` option, the stored location belongs to this editor data only, so it is deleted + * once the element is no longer in the saved data. With it, the stored location is never changed nor deleted, see + * `update.js`. */ const loadLocation = ({ editor, model, locationId }) => { - const { copyLocationsOnLoad } = editor.config.get(pluginKey); + if (!editor.config.get(pluginKey).copyLocationsOnChange) { + addStoredLocation(editor, locationId); + } enqueueLocationRequest(model, async () => { let selectedImage; @@ -30,17 +24,6 @@ const loadLocation = ({ editor, model, locationId }) => { return; } - let editedLocationId = locationId; - if (copyLocationsOnLoad) { - try { - ({ locationId: editedLocationId } = await copy(editor, selectedImage)); - } catch (error) { - reportError(editor, 'ckeditor_location_copy_error', error); - - return; - } - } - // Values restored on upcast, unless another resource has been selected in the meantime const currentValues = model.getAttribute(attributes.selectedImage); if (currentValues.id) { @@ -49,9 +32,8 @@ const loadLocation = ({ editor, model, locationId }) => { const variationName = currentValues.selectedVariation?.label; - // Not undoable: undo must not switch the element back to the stored location + // Not undoable: undo must not switch the element back to an image which isn't loaded editor.model.enqueueChange({ isUndoable: false }, (writer) => { - writer.setAttribute(attributes.locationId, editedLocationId, model); writer.setAttribute( attributes.selectedImage, { diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/update.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/update.js index af46719f..8c44c58d 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/update.js +++ b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/update.js @@ -1,20 +1,42 @@ import { attributes, pluginKey } from '../../../constants'; import { enqueueLocationRequest, getEndpoint, reportError, request } from '../../../utils/location-requests'; +import { addOwnLocation, isOwnLocation } from '../../../utils/locations'; +/** + * Saves changes of the element to its location. + * + * With the `copyLocationsOnChange` option, a stored location (which other versions, translations or copies of the + * stored data may reference) is never changed: the first change of the element creates a copy of the location with + * the change, and the element is switched to the copy. Opening the editor without changing anything creates nothing. + */ const updateLocation = ({ editor, model, selectedImage }) => { - enqueueLocationRequest(model, () => { + const { copyLocationsOnChange, source } = editor.config.get(pluginKey); + const body = JSON.stringify({ ...selectedImage, source }); + + enqueueLocationRequest(model, async () => { // Read when the request runs: a preceding create or copy request sets the location of the element const locationId = model.getAttribute(attributes.locationId); if (!locationId) { - return null; + return; + } + + if (!copyLocationsOnChange || isOwnLocation(editor, locationId)) { + await request(getEndpoint(editor, 'updateLocation')(locationId), { method: 'PUT', body }); + + return; + } + + const response = await request(getEndpoint(editor, 'createLocation'), { method: 'POST', body }); + const { locationId: copyId } = await response.json(); + addOwnLocation(editor, copyId); + + if (model.getAttribute(attributes.locationId) !== locationId) { + return; } - return request(getEndpoint(editor, 'updateLocation')(locationId), { - method: 'PUT', - body: JSON.stringify({ - ...selectedImage, - source: editor.config.get(pluginKey).source, - }), + // Not undoable: undo must not switch the element back to the stored location + editor.model.enqueueChange({ isUndoable: false }, (writer) => { + writer.setAttribute(attributes.locationId, copyId, model); }); }).catch(error => reportError(editor, 'ckeditor_location_update_error', error)); }; diff --git a/bundle/Resources/public/js/ckeditor-plugin/index.js b/bundle/Resources/public/js/ckeditor-plugin/index.js index 8d5fe77a..670755dc 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/index.js +++ b/bundle/Resources/public/js/ckeditor-plugin/index.js @@ -3,6 +3,7 @@ import { pluginKey } from './constants'; import renderNgrmEditorViews from './render-views'; import htmlFormat from './formats/html'; import { hasPendingLocationRequests, waitForLocationRequests } from './utils/location-requests'; +import { deleteUnusedLocations } from './utils/locations'; export { NetgenRemoteMediaPlugin, @@ -11,4 +12,5 @@ export { htmlFormat, waitForLocationRequests, hasPendingLocationRequests, + deleteUnusedLocations, }; diff --git a/bundle/Resources/public/js/ckeditor-plugin/plugin.js b/bundle/Resources/public/js/ckeditor-plugin/plugin.js index 86ea7484..301e9b8d 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/plugin.js +++ b/bundle/Resources/public/js/ckeditor-plugin/plugin.js @@ -4,6 +4,7 @@ import NetgenRemoteMediaCommand from './command'; import getNetgenRemoteMediaToolbarButton from './button'; import setupDataCasting from './conversion'; +import { deleteUnusedLocationsOnSubmit, registerEditor } from './utils/locations'; // A regular function, not an arrow function: CKEditor instantiates function plugins with `new` function NetgenRemoteMediaPlugin(editor) { @@ -21,10 +22,11 @@ function NetgenRemoteMediaPlugin(editor) { /** Storage format of the remote media element in editor data, defaults to `formats/html.js` */ format: null, /** - * Edit copies of stored locations instead of the stored locations, for integrations which store editor data - * in versions, translations or copies sharing the same locations + * Never change stored locations, for integrations which store editor data in versions, translations or copies + * sharing the same locations: the first change of an element creates a copy of its location, and the element + * is switched to the copy. Stored locations are then never deleted by the editor either. */ - copyLocationsOnLoad: false, + copyLocationsOnChange: false, /** Called with a translated message and the error when a location request fails, defaults to `console.error` */ onError: null, }); @@ -38,6 +40,10 @@ function NetgenRemoteMediaPlugin(editor) { }); setupDataCasting(editor); + + // Locations the editor created, copied or loaded are deleted when the data is saved and no longer references them + registerEditor(editor); + deleteUnusedLocationsOnSubmit(editor); } export default NetgenRemoteMediaPlugin; diff --git a/bundle/Resources/public/js/ckeditor-plugin/utils/locations.js b/bundle/Resources/public/js/ckeditor-plugin/utils/locations.js new file mode 100644 index 00000000..27e57941 --- /dev/null +++ b/bundle/Resources/public/js/ckeditor-plugin/utils/locations.js @@ -0,0 +1,101 @@ +import { attributes, pluginKey } from '../constants'; +import { getEndpoint } from './location-requests'; + +/** Editors on the page, a location is kept while any of them references it */ +const editors = new Set(); + +/** Locations each editor may delete once they are no longer in the editor data, by editor */ +const deletableLocations = new WeakMap(); + +/** Locations each editor created or copied, by editor */ +const ownLocations = new WeakMap(); + +const toKey = locationId => String(locationId); + +export const registerEditor = (editor) => { + editors.add(editor); + deletableLocations.set(editor, new Set()); + ownLocations.set(editor, new Set()); + + editor.on('destroy', () => editors.delete(editor)); +}; + +/** + * A location the editor created or copied: nothing else references it, so the editor changes it in place and + * deletes it once it is no longer in the editor data. + */ +export const addOwnLocation = (editor, locationId) => { + ownLocations.get(editor)?.add(toKey(locationId)); + deletableLocations.get(editor)?.add(toKey(locationId)); +}; + +export const isOwnLocation = (editor, locationId) => ownLocations.get(editor)?.has(toKey(locationId)) ?? false; + +/** + * A location of the stored editor data, deleted once it is no longer in the editor data. Only for integrations + * whose stored editor data is not shared (without `copyLocationsOnChange`). + */ +export const addStoredLocation = (editor, locationId) => { + deletableLocations.get(editor)?.add(toKey(locationId)); +}; + +const getReferencedLocations = () => { + const referenced = new Set(); + + editors.forEach((editor) => { + editor.model.document.getRoots() + .filter(root => root.rootName !== '$graveyard') + .forEach((root) => { + for (const item of editor.model.createRangeIn(root).getItems()) { + if (item.is('element', pluginKey) && item.getAttribute(attributes.locationId)) { + referenced.add(toKey(item.getAttribute(attributes.locationId))); + } + } + }); + }); + + return referenced; +}; + +/** + * Deletes the locations of the given editors (by default all editors on the page) which are no longer referenced + * by any editor on the page. Call it when the editor data is saved: until then, removed elements can come back + * through undo, paste or drag and drop. Requests are sent with `keepalive`, so they complete when the page is + * left right after, e.g. by the form submission. + */ +export const deleteUnusedLocations = (editorsToClean = [...editors]) => { + const referenced = getReferencedLocations(); + const requests = []; + + editorsToClean.forEach((editor) => { + const locations = deletableLocations.get(editor) ?? new Set(); + + [...locations].filter(locationId => !referenced.has(locationId)).forEach((locationId) => { + locations.delete(locationId); + ownLocations.get(editor)?.delete(locationId); + + requests.push(fetch(getEndpoint(editor, 'deleteLocation')(locationId), { method: 'DELETE', keepalive: true })); + }); + }); + + return Promise.allSettled(requests); +}; + +/** + * Deletes unused locations when the form containing the editor is submitted. Integrations which save the editor + * data otherwise (e.g. with a request instead of the form submission) call `deleteUnusedLocations()` themselves. + */ +export const deleteUnusedLocationsOnSubmit = (editor) => { + const form = editor.sourceElement?.closest?.('form'); + if (!form) { + return; + } + + form.addEventListener('submit', (event) => { + if (event.defaultPrevented) { + return; + } + + deleteUnusedLocations([...editors].filter(otherEditor => form.contains(otherEditor.sourceElement))); + }); +}; diff --git a/bundle/Resources/translations/ngremotemedia.en.yaml b/bundle/Resources/translations/ngremotemedia.en.yaml index bbf04a26..c889455c 100644 --- a/bundle/Resources/translations/ngremotemedia.en.yaml +++ b/bundle/Resources/translations/ngremotemedia.en.yaml @@ -32,7 +32,6 @@ ngrm: empty: 'No folder selected' ckeditor: location_load_error: 'Remote media could not be loaded in the editor. The stored media is kept unchanged.' - location_copy_error: 'Remote media could not be prepared for editing. The stored media is kept unchanged, select it again to edit it.' location_create_error: 'Selected remote media could not be saved. Select it again.' location_update_error: 'Changes to the remote media could not be saved. Make the change again.' preview: diff --git a/bundle/Resources/translations/ngremotemedia.hr.yaml b/bundle/Resources/translations/ngremotemedia.hr.yaml index f74692a6..2981c13a 100644 --- a/bundle/Resources/translations/ngremotemedia.hr.yaml +++ b/bundle/Resources/translations/ngremotemedia.hr.yaml @@ -32,7 +32,6 @@ ngrm: empty: 'Nije odabrana ni jedna mapa' ckeditor: location_load_error: 'Resurs nije moguće učitati u uređivač. Spremljeni resurs ostaje nepromijenjen.' - location_copy_error: 'Resurs nije moguće pripremiti za uređivanje. Spremljeni resurs ostaje nepromijenjen, odaberite ga ponovno za uređivanje.' location_create_error: 'Odabrani resurs nije moguće spremiti. Odaberite ga ponovno.' location_update_error: 'Promjene resursa nije moguće spremiti. Ponovite promjenu.' preview: diff --git a/bundle/Resources/translations/ngremotemedia.no.yaml b/bundle/Resources/translations/ngremotemedia.no.yaml index 24830b54..352e6730 100644 --- a/bundle/Resources/translations/ngremotemedia.no.yaml +++ b/bundle/Resources/translations/ngremotemedia.no.yaml @@ -32,7 +32,6 @@ ngrm: empty: 'No folder selected' ckeditor: location_load_error: 'Remote media could not be loaded in the editor. The stored media is kept unchanged.' - location_copy_error: 'Remote media could not be prepared for editing. The stored media is kept unchanged, select it again to edit it.' location_create_error: 'Selected remote media could not be saved. Select it again.' location_update_error: 'Changes to the remote media could not be saved. Make the change again.' preview: diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index f42d5438..54c59f54 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,16 +1,17 @@ # Netgen Remote Media Bundle changelog -## 3.1.1 +## 3.2.0 ### Added -* CKEditor 5 plugin `copyLocationsOnLoad` option, which switches every loaded element to a copy of its stored location before it can be edited, for integrations whose stored editor data is shared by versions, translations or copies (the edited data then never changes locations referenced by other stored data) -* CKEditor 5 plugin `onError` option, called with a translated message and the error when loading, copying, creating or updating a location fails (defaults to `console.error`), with the `ngrm.edit.vue.ckeditor.*` translations +* CKEditor 5 plugin `copyLocationsOnChange` option, for integrations whose stored editor data is shared by versions, translations or copies: stored locations are never changed nor deleted, the first change of an element creates a copy of its location with the change and switches the element to it (opening the editor without changes creates nothing) +* CKEditor 5 plugin `onError` option, called with a translated message and the error when loading, creating or updating a location fails (defaults to `console.error`), with the `ngrm.edit.vue.ckeditor.*` translations * `waitForLocationRequests()` and `hasPendingLocationRequests()` exports of the CKEditor 5 plugin, to check for and wait for pending location requests before submitting editor data (an element whose location is still being created would be stored without it) +* `deleteUnusedLocations()` export of the CKEditor 5 plugin, which deletes the locations the editors on the page created or copied (and, without `copyLocationsOnChange`, the stored locations they loaded) which no editor on the page references anymore, for integrations which save the editor data otherwise than by submitting the form containing the editor ### Changed -* CKEditor 5 plugin no longer deletes locations: removing an element or replacing its resource leaves the location in the database, as the element can come back through undo, paste or drag and drop, the `deleteLocation` endpoint option is removed +* CKEditor 5 plugin deletes locations when the editor data is saved instead of when an element is removed or its resource replaced, so an element brought back through undo, paste or drag and drop keeps its location: on submit of the form containing the editor, the locations which no editor on the page references anymore are deleted (requests are sent with `keepalive`, so they complete after the page is left) * CKEditor 5 plugin location requests of one element run one after another, so an update always targets the location created by the request before it ### Fixed From aebe55780067219d0a724359a3055b13c00f437e Mon Sep 17 00:00:00 2001 From: Amalija Ramljak Date: Fri, 20 Nov 2026 11:01:23 +0100 Subject: [PATCH 3/3] JGLWEB-1832 report unused stored locations of the CKEditor 5 plugin - getUnusedStoredLocations(form) returns, with copyLocationsOnChange, the stored locations the editors loaded which no editor on the page references anymore, for integrations to send with the saved data so the server deletes those nothing else references - deleteUnusedLocations() takes the form to clean instead of a list of editors --- .../remote-resource-location/load.js | 10 ++-- .../public/js/ckeditor-plugin/index.js | 3 +- .../js/ckeditor-plugin/utils/locations.js | 55 +++++++++++++++---- docs/CHANGELOG.md | 3 +- 4 files changed, 52 insertions(+), 19 deletions(-) diff --git a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/load.js b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/load.js index e5e8a07c..8aca03f1 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/load.js +++ b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/load.js @@ -1,4 +1,4 @@ -import { attributes, pluginKey } from '../../../constants'; +import { attributes } from '../../../constants'; import { enqueueLocationRequest, getEndpoint, reportError, request } from '../../../utils/location-requests'; import { addStoredLocation } from '../../../utils/locations'; @@ -6,13 +6,11 @@ import { addStoredLocation } from '../../../utils/locations'; * Loads the selected image of a stored element. When loading fails the element keeps the stored location unchanged. * * Without the `copyLocationsOnChange` option, the stored location belongs to this editor data only, so it is deleted - * once the element is no longer in the saved data. With it, the stored location is never changed nor deleted, see - * `update.js`. + * once the element is no longer in the saved data. With it, the stored location is never changed nor deleted by the + * editor (see `update.js`), it is reported by `getUnusedStoredLocations()` once it is no longer in the editor data. */ const loadLocation = ({ editor, model, locationId }) => { - if (!editor.config.get(pluginKey).copyLocationsOnChange) { - addStoredLocation(editor, locationId); - } + addStoredLocation(editor, locationId); enqueueLocationRequest(model, async () => { let selectedImage; diff --git a/bundle/Resources/public/js/ckeditor-plugin/index.js b/bundle/Resources/public/js/ckeditor-plugin/index.js index 670755dc..da76dc91 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/index.js +++ b/bundle/Resources/public/js/ckeditor-plugin/index.js @@ -3,7 +3,7 @@ import { pluginKey } from './constants'; import renderNgrmEditorViews from './render-views'; import htmlFormat from './formats/html'; import { hasPendingLocationRequests, waitForLocationRequests } from './utils/location-requests'; -import { deleteUnusedLocations } from './utils/locations'; +import { deleteUnusedLocations, getUnusedStoredLocations } from './utils/locations'; export { NetgenRemoteMediaPlugin, @@ -13,4 +13,5 @@ export { waitForLocationRequests, hasPendingLocationRequests, deleteUnusedLocations, + getUnusedStoredLocations, }; diff --git a/bundle/Resources/public/js/ckeditor-plugin/utils/locations.js b/bundle/Resources/public/js/ckeditor-plugin/utils/locations.js index 27e57941..85c95249 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/utils/locations.js +++ b/bundle/Resources/public/js/ckeditor-plugin/utils/locations.js @@ -10,12 +10,16 @@ const deletableLocations = new WeakMap(); /** Locations each editor created or copied, by editor */ const ownLocations = new WeakMap(); +/** Locations of the stored editor data each editor loaded, by editor */ +const storedLocations = new WeakMap(); + const toKey = locationId => String(locationId); export const registerEditor = (editor) => { editors.add(editor); deletableLocations.set(editor, new Set()); ownLocations.set(editor, new Set()); + storedLocations.set(editor, new Set()); editor.on('destroy', () => editors.delete(editor)); }; @@ -32,13 +36,23 @@ export const addOwnLocation = (editor, locationId) => { export const isOwnLocation = (editor, locationId) => ownLocations.get(editor)?.has(toKey(locationId)) ?? false; /** - * A location of the stored editor data, deleted once it is no longer in the editor data. Only for integrations - * whose stored editor data is not shared (without `copyLocationsOnChange`). + * A location of the stored editor data. Without `copyLocationsOnChange` the stored editor data is not shared, so the + * editor deletes the location once it is no longer in the editor data. With it, other stored data may reference the + * location, so it is only reported by `getUnusedStoredLocations()`. */ export const addStoredLocation = (editor, locationId) => { + if (editor.config.get(pluginKey).copyLocationsOnChange) { + storedLocations.get(editor)?.add(toKey(locationId)); + + return; + } + deletableLocations.get(editor)?.add(toKey(locationId)); }; +/** Editors in the given form, or all editors on the page */ +const getEditors = form => [...editors].filter(editor => form === null || form.contains(editor.sourceElement)); + const getReferencedLocations = () => { const referenced = new Set(); @@ -58,16 +72,16 @@ const getReferencedLocations = () => { }; /** - * Deletes the locations of the given editors (by default all editors on the page) which are no longer referenced - * by any editor on the page. Call it when the editor data is saved: until then, removed elements can come back - * through undo, paste or drag and drop. Requests are sent with `keepalive`, so they complete when the page is + * Deletes the locations of the editors in the given form (by default of all editors on the page) which are no longer + * referenced by any editor on the page. Call it when the editor data is saved: until then, removed elements can come + * back through undo, paste or drag and drop. Requests are sent with `keepalive`, so they complete when the page is * left right after, e.g. by the form submission. */ -export const deleteUnusedLocations = (editorsToClean = [...editors]) => { +export const deleteUnusedLocations = (form = null) => { const referenced = getReferencedLocations(); const requests = []; - editorsToClean.forEach((editor) => { + getEditors(form).forEach((editor) => { const locations = deletableLocations.get(editor) ?? new Set(); [...locations].filter(locationId => !referenced.has(locationId)).forEach((locationId) => { @@ -81,6 +95,27 @@ export const deleteUnusedLocations = (editorsToClean = [...editors]) => { return Promise.allSettled(requests); }; +/** + * With `copyLocationsOnChange`: IDs of the stored locations the editors in the given form (by default all editors on + * the page) loaded, which are no longer referenced by any editor on the page (e.g. replaced by copies, or of removed + * elements). The editor never deletes them, as other stored data may reference them: integrations send them along + * with the saved data, so the server deletes those which nothing references anymore once the data is saved. + */ +export const getUnusedStoredLocations = (form = null) => { + const referenced = getReferencedLocations(); + const unused = new Set(); + + getEditors(form).forEach((editor) => { + storedLocations.get(editor)?.forEach((locationId) => { + if (!referenced.has(locationId)) { + unused.add(locationId); + } + }); + }); + + return [...unused]; +}; + /** * Deletes unused locations when the form containing the editor is submitted. Integrations which save the editor * data otherwise (e.g. with a request instead of the form submission) call `deleteUnusedLocations()` themselves. @@ -92,10 +127,8 @@ export const deleteUnusedLocationsOnSubmit = (editor) => { } form.addEventListener('submit', (event) => { - if (event.defaultPrevented) { - return; + if (!event.defaultPrevented) { + deleteUnusedLocations(form); } - - deleteUnusedLocations([...editors].filter(otherEditor => form.contains(otherEditor.sourceElement))); }); }; diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 54c59f54..70d0af0d 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,7 +7,8 @@ * CKEditor 5 plugin `copyLocationsOnChange` option, for integrations whose stored editor data is shared by versions, translations or copies: stored locations are never changed nor deleted, the first change of an element creates a copy of its location with the change and switches the element to it (opening the editor without changes creates nothing) * CKEditor 5 plugin `onError` option, called with a translated message and the error when loading, creating or updating a location fails (defaults to `console.error`), with the `ngrm.edit.vue.ckeditor.*` translations * `waitForLocationRequests()` and `hasPendingLocationRequests()` exports of the CKEditor 5 plugin, to check for and wait for pending location requests before submitting editor data (an element whose location is still being created would be stored without it) -* `deleteUnusedLocations()` export of the CKEditor 5 plugin, which deletes the locations the editors on the page created or copied (and, without `copyLocationsOnChange`, the stored locations they loaded) which no editor on the page references anymore, for integrations which save the editor data otherwise than by submitting the form containing the editor +* `deleteUnusedLocations(form)` export of the CKEditor 5 plugin, which deletes the locations the editors in the form (or on the page) created or copied (and, without `copyLocationsOnChange`, the stored locations they loaded) which no editor on the page references anymore, for integrations which save the editor data otherwise than by submitting the form containing the editor +* `getUnusedStoredLocations(form)` export of the CKEditor 5 plugin, which returns, with `copyLocationsOnChange`, the IDs of the stored locations the editors in the form (or on the page) loaded which no editor on the page references anymore (replaced by copies or of removed elements), for integrations to send along with the saved data, so the server deletes those which no other stored data references ### Changed