diff --git a/bundle/Controller/Configuration.php b/bundle/Controller/Configuration.php index 73a3346c..10cdd591 100644 --- a/bundle/Controller/Configuration.php +++ b/bundle/Controller/Configuration.php @@ -143,6 +143,9 @@ 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_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..6b5ed952 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/constants.js +++ b/bundle/Resources/public/js/ckeditor-plugin/constants.js @@ -147,6 +147,9 @@ 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_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..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 @@ -1,23 +1,34 @@ 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 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 ?? ''; - 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..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,21 +1,41 @@ -import { attributes, defaultValue, pluginKey } from '../../../constants'; +import { attributes, pluginKey } from '../../../constants'; +import { enqueueLocationRequest, getEndpoint, reportError, request } from '../../../utils/location-requests'; +import { addOwnLocation } from '../../../utils/locations'; -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(); + // 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) => { 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..8aca03f1 --- /dev/null +++ b/bundle/Resources/public/js/ckeditor-plugin/conversion/editing-downcast-utils/remote-resource-location/load.js @@ -0,0 +1,50 @@ +import { attributes } from '../../../constants'; +import { enqueueLocationRequest, getEndpoint, reportError, request } from '../../../utils/location-requests'; +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 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 }) => { + addStoredLocation(editor, locationId); + + 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; + } + + // 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 an image which isn't loaded + editor.model.enqueueChange({ isUndoable: false }, (writer) => { + 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..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,12 +1,44 @@ -import { attributes, defaultValue, pluginKey } from '../../../constants'; +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 }) => { - const updateLocationEndpoint = editor.config.get(pluginKey).endpoints.updateLocation ?? defaultValue.endpoints.updateLocation; + const { copyLocationsOnChange, source } = editor.config.get(pluginKey); + const body = JSON.stringify({ ...selectedImage, source }); - fetch(updateLocationEndpoint(model.getAttribute(attributes.locationId)), { - method: 'PUT', - body: JSON.stringify(selectedImage), - }); + 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; + } + + 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; + } + + // 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)); }; 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..da76dc91 100644 --- a/bundle/Resources/public/js/ckeditor-plugin/index.js +++ b/bundle/Resources/public/js/ckeditor-plugin/index.js @@ -2,5 +2,16 @@ 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'; +import { deleteUnusedLocations, getUnusedStoredLocations } from './utils/locations'; -export { NetgenRemoteMediaPlugin, pluginKey as netgenremoteMediaPluginKey, renderNgrmEditorViews, htmlFormat }; +export { + NetgenRemoteMediaPlugin, + pluginKey as netgenremoteMediaPluginKey, + renderNgrmEditorViews, + htmlFormat, + waitForLocationRequests, + hasPendingLocationRequests, + deleteUnusedLocations, + getUnusedStoredLocations, +}; diff --git a/bundle/Resources/public/js/ckeditor-plugin/plugin.js b/bundle/Resources/public/js/ckeditor-plugin/plugin.js index b8bcf9d9..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) { @@ -20,6 +21,14 @@ function NetgenRemoteMediaPlugin(editor) { endpoints: defaultValue.endpoints, /** Storage format of the remote media element in editor data, defaults to `formats/html.js` */ format: null, + /** + * 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. + */ + copyLocationsOnChange: 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)); @@ -31,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/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/public/js/ckeditor-plugin/utils/locations.js b/bundle/Resources/public/js/ckeditor-plugin/utils/locations.js new file mode 100644 index 00000000..85c95249 --- /dev/null +++ b/bundle/Resources/public/js/ckeditor-plugin/utils/locations.js @@ -0,0 +1,134 @@ +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(); + +/** 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)); +}; + +/** + * 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. 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(); + + 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 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 = (form = null) => { + const referenced = getReferencedLocations(); + const requests = []; + + getEditors(form).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); +}; + +/** + * 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. + */ +export const deleteUnusedLocationsOnSubmit = (editor) => { + const form = editor.sourceElement?.closest?.('form'); + if (!form) { + return; + } + + form.addEventListener('submit', (event) => { + if (!event.defaultPrevented) { + deleteUnusedLocations(form); + } + }); +}; diff --git a/bundle/Resources/translations/ngremotemedia.en.yaml b/bundle/Resources/translations/ngremotemedia.en.yaml index eaa5a169..c889455c 100644 --- a/bundle/Resources/translations/ngremotemedia.en.yaml +++ b/bundle/Resources/translations/ngremotemedia.en.yaml @@ -30,6 +30,10 @@ 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_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..2981c13a 100644 --- a/bundle/Resources/translations/ngremotemedia.hr.yaml +++ b/bundle/Resources/translations/ngremotemedia.hr.yaml @@ -30,6 +30,10 @@ 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_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..352e6730 100644 --- a/bundle/Resources/translations/ngremotemedia.no.yaml +++ b/bundle/Resources/translations/ngremotemedia.no.yaml @@ -30,6 +30,10 @@ 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_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..70d0af0d 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,5 +1,27 @@ # Netgen Remote Media Bundle changelog +## 3.2.0 + +### Added + +* 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(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 + +* 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 + +* 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