Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions bundle/Controller/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
];
}

Expand Down
3 changes: 3 additions & 0 deletions bundle/Resources/public/js/ckeditor-plugin/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import alignment from './alignment';
import remove from './remove';

export { alignment, remove };
export { alignment };

This file was deleted.

Original file line number Diff line number Diff line change
@@ -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;

This file was deleted.

Original file line number Diff line number Diff line change
@@ -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;
Original file line number Diff line number Diff line change
@@ -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;
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/**
Expand Down
43 changes: 11 additions & 32 deletions bundle/Resources/public/js/ckeditor-plugin/conversion/upcast.js
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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;
},
});
Expand Down
13 changes: 12 additions & 1 deletion bundle/Resources/public/js/ckeditor-plugin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
13 changes: 13 additions & 0 deletions bundle/Resources/public/js/ckeditor-plugin/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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));
Expand All @@ -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;
Loading
Loading