Sorry, no results found for "".

Plugin SDK > Asset sources

Asset sources

By default, to add new assets to the Media Area through the interface, you can upload files from your computer. But plugins can define custom asset sources to allow contributors to upload assets from external providers.

For example, the Unsplash plugin in our Marketplace allows to upload royalty-free high-resolution images:

Define custom asset sources

Within a plugin you can define the assetSources hook to expose new asset sources. Every source must specify an internal ID, and a name and a representative icon that will be shown in the interface.

import { connect } from 'datocms-plugin-sdk';
connect({
assetSources() {
return [
{
id: 'unsplash',
name: 'Unsplash',
icon: {
type: 'svg',
viewBox: '0 0 448 512',
content:
'<path fill="currentColor" d="M448,230.17V480H0V230.17H141.13V355.09H306.87V230.17ZM306.87,32H141.13V156.91H306.87Z" class=""></path>',
},
modal: {
width: 'm',
},
},
];
},
});

Rendering the custom asset source

When the user selects the custom source, a modal will be opened with the size you specified, and the renderAssetSource hook will be called. Inside of this hook we initialize React and render a custom component called AssetBrowser, passing down as a prop the second ctx argument, which provides a series of information and methods for interacting with the main application:

import { connect } from 'datocms-plugin-sdk';
connect({
assetSources() {
return [{...}];
},
renderAssetSource(sourceId: string, ctx: RenderAssetSourceCtx) {
render(<AssetBrowser ctx={ctx} />);
},
});

As we just saw, a plugin might offer different asset sources, so we can use the sourceId argument to know which one we are requested to render, and write a specific React component for each of them.

import { Canvas, RenderAssetSourceCtx } from 'datocms-react-ui';
type PropTypes = {
ctx: RenderAssetSourceCtx;
};
function AssetBrowser({ ctx }: PropTypes) {
return (
<Canvas ctx={ctx}>
Hello from the sidebar!
</Canvas>
);
}
Always use the canvas!

It is important to wrap the content inside the Canvas component, so that the iframe will continuously auto-adjust its size based on the content we're rendering, and to give our app the look and feel of the DatoCMS web app.

We can use this component to render whatever we want. The important thing is to call the ctx.select method to communicate to the main DatoCMS app the selected asset URL:

import { ButtonLink } from 'datocms-react-ui';
function AssetBrowser({ ctx }: PropTypes) {
const handleSelect = () => {
ctx.select({
resource: {
url: 'https://unsplash.com/photos/yf8qPXQFDJE',
filename: `sky.jpg`,
},
});
}
return (
<Canvas ctx={ctx}>
<Button onClick={handleSelect}>Select</Button>
</Canvas>
);
}

If you're generating your asset on the fly (ie. by rendering on a canvas), instead of a regular URL you can also pass a base64-encoded data URI:

ctx.select({
resource: {
base64: 'data:image/png;base64,PD94bWwgd..',
filename: `generated-image.png`,
},
});

You can also optionally specify some metadata to associate with the newly created upload:

ctx.select({
resource: {
url:
'https://images.unsplash.com/photo-1416339306562-f3d12fefd36f',
filename: 'man-drinking-coffee.jpg',
},
copyright: 'Royalty free (Unsplash)',
author: 'Jeff Sheldon',
notes: 'A man drinking a coffee',
tags: ['man', 'coffee'],
});

assetSources(ctx)

Use this function to declare additional sources to be shown when users want to upload new assets.

Return value

The function must return: AssetSource[] | undefined.

Context object

The following properties and methods are available in the ctx argument:

Every hook available in the Plugin SDK shares the same minumum set of properties and methods.

Information about the current user using the CMS.

The current DatoCMS user. It can either be the owner or one of the collaborators (regular or SSO).

View on Github

The role for the current DatoCMS user.

View on Github

The access token to perform API calls on behalf of the current user. Only available if currentUserAccessToken additional permission is granted.

View on Github
These methods can be used to open custom dialogs/confirmation panels.

Opens a custom modal. Returns a promise resolved with what the modal itself returns calling the resolve() function.

View on Github
const result = await ctx.openModal({
id: 'regular',
title: 'Custom title!',
width: 'l',
parameters: { foo: 'bar' },
});
if (result) {
ctx.notice(`Success! ${JSON.stringify(result)}`);
} else {
ctx.alert('Closed!');
}

Opens a UI-consistent confirmation dialog. Returns a promise resolved with the value of the choice made by the user.

View on Github
const result = await ctx.openConfirm({
title: 'Custom title',
content:
'Lorem Ipsum is simply dummy text of the printing and typesetting industry',
choices: [
{
label: 'Positive',
value: 'positive',
intent: 'positive',
},
{
label: 'Negative',
value: 'negative',
intent: 'negative',
},
],
cancel: {
label: 'Cancel',
value: false,
},
});
if (result) {
ctx.notice(`Success! ${result}`);
} else {
ctx.alert('Cancelled!');
}
These properties provide access to "entity repos", that is, the collection of resources of a particular type that have been loaded by the CMS up to this moment. The entity repos are objects, indexed by the ID of the entity itself.

All the models of the current DatoCMS project, indexed by ID.

View on Github

All the fields currently loaded for the current DatoCMS project, indexed by ID. If some fields you need are not present, use the loadItemTypeFields function to load them.

View on Github

All the fieldsets currently loaded for the current DatoCMS project, indexed by ID. If some fields you need are not present, use the loadItemTypeFieldsets function to load them.

View on Github

All the regular users currently loaded for the current DatoCMS project, indexed by ID. It will always contain the current user. If some users you need are not present, use the loadUsers function to load them.

View on Github

All the SSO users currently loaded for the current DatoCMS project, indexed by ID. It will always contain the current user. If some users you need are not present, use the loadSsoUsers function to load them.

View on Github
These methods let you open the standard DatoCMS dialogs needed to interact with records.

Opens a dialog for creating a new record. It returns a promise resolved with the newly created record or null if the user closes the dialog without creating anything.

View on Github
const itemTypeId = prompt('Please insert a model ID:');
const item = await ctx.createNewItem(itemTypeId);
if (item) {
ctx.notice(`Success! ${item.id}`);
} else {
ctx.alert('Closed!');
}

Opens a dialog for selecting one (or multiple) record(s) from a list of existing records of type itemTypeId. It returns a promise resolved with the selected record(s), or null if the user closes the dialog without choosing any record.

View on Github
const itemTypeId = prompt('Please insert a model ID:');
const items = await ctx.selectItem(itemTypeId, { multiple: true });
if (items) {
ctx.notice(`Success! ${items.map((i) => i.id).join(', ')}`);
} else {
ctx.alert('Closed!');
}

Opens a dialog for editing an existing record. It returns a promise resolved with the edited record, or null if the user closes the dialog without persisting any change.

View on Github
const itemId = prompt('Please insert a record ID:');
const item = await ctx.editItem(itemId);
if (item) {
ctx.notice(`Success! ${item.id}`);
} else {
ctx.alert('Closed!');
}
These methods can be used to asyncronously load additional information your plugin needs to work.

Loads all the fields for a specific model (or block). Fields will be returned and will also be available in the the fields property.

View on Github
const itemTypeId = prompt('Please insert a model ID:');
const fields = await ctx.loadItemTypeFields(itemTypeId);
ctx.notice(
`Success! ${fields
.map((field) => field.attributes.api_key)
.join(', ')}`,
);

Loads all the fieldsets for a specific model (or block). Fieldsets will be returned and will also be available in the the fieldsets property.

View on Github
const itemTypeId = prompt('Please insert a model ID:');
const fieldsets = await ctx.loadItemTypeFieldsets(itemTypeId);
ctx.notice(
`Success! ${fieldsets
.map((fieldset) => fieldset.attributes.title)
.join(', ')}`,
);

Loads all the fields in the project that are currently using the plugin for one of its manual field extensions.

View on Github
const fields = await ctx.loadFieldsUsingPlugin();
ctx.notice(
`Success! ${fields
.map((field) => field.attributes.api_key)
.join(', ')}`,
);

Loads all regular users. Users will be returned and will also be available in the the users property.

View on Github
const users = await ctx.loadUsers();
ctx.notice(`Success! ${users.map((user) => user.id).join(', ')}`);

Loads all SSO users. Users will be returned and will also be available in the the ssoUsers property.

View on Github
const users = await ctx.loadSsoUsers();
ctx.notice(`Success! ${users.map((user) => user.id).join(', ')}`);
These methods can be used to take the user to different pages.

Moves the user to another URL internal to the backend.

View on Github
await ctx.navigateTo('/');
Information about the current plugin. Useful to access the plugin's global configuration object.

The current plugin.

View on Github

The current DatoCMS project.

View on Github

The ID of the current environment.

View on Github

The account/organization that is the project owner.

View on Github

UI preferences of the current user (right now, only the preferred locale is available).

View on Github

An object containing the theme colors for the current DatoCMS project.

View on Github
These methods can be used to show UI-consistent toast notifications to the end-user.

Triggers an "error" toast displaying the selected message.

View on Github
const message = prompt(
'Please insert a message:',
'This is an alert message!',
);
await ctx.alert(message);

Triggers a "success" toast displaying the selected message.

View on Github
const message = prompt(
'Please insert a message:',
'This is a notice message!',
);
await ctx.notice(message);

Triggers a custom toast displaying the selected message (and optionally a CTA).

View on Github
const result = await ctx.customToast({
type: 'warning',
message: 'Just a sample warning notification!',
dismissOnPageChange: true,
dismissAfterTimeout: 5000,
cta: {
label: 'Execute call-to-action',
value: 'cta',
},
});
if (result === 'cta') {
ctx.notice(`Clicked CTA!`);
}
These methods can be used to update both plugin parameters and manual field extensions configuration.

Updates the plugin parameters.

Always check ctx.currentRole.meta.final_permissions.can_edit_schema before calling this, as the user might not have the permission to perform the operation.

View on Github
await ctx.updatePluginParameters({ debugMode: true });
await ctx.notice('Plugin parameters successfully updated!');

Performs changes in the appearance of a field. You can install/remove a manual field extension, or tweak their parameters. If multiple changes are passed, they will be applied sequencially.

Always check ctx.currentRole.meta.final_permissions.can_edit_schema before calling this, as the user might not have the permission to perform the operation.

View on Github
const fields = await ctx.loadFieldsUsingPlugin();
if (fields.length === 0) {
ctx.alert('No field is using this plugin as a manual extension!');
return;
}
for (const field of fields) {
const { appearance } = field.attributes;
const operations = [];
if (appearance.editor === ctx.plugin.id) {
operations.push({
operation: 'updateEditor',
newParameters: {
...appearance.parameters,
foo: 'bar',
},
});
}
appearance.addons.forEach((addon, i) => {
if (addon.id !== ctx.plugin.id) {
return;
}
operations.push({
operation: 'updateAddon',
index: i,
newParameters: { ...addon.parameters, foo: 'bar' },
});
});
await ctx.updateFieldAppearance(field.id, operations);
ctx.notice(`Successfully edited field ${field.attributes.api_key}`);
}
These methods let you open the standard DatoCMS dialogs needed to interact with Media Area assets.

Opens a dialog for selecting one (or multiple) existing asset(s). It returns a promise resolved with the selected asset(s), or null if the user closes the dialog without selecting any upload.

View on Github
const item = await ctx.selectUpload({ multiple: false });
if (item) {
ctx.notice(`Success! ${item.id}`);
} else {
ctx.alert('Closed!');
}

Opens a dialog for editing a Media Area asset. It returns a promise resolved with:

  • The updated asset, if the user persists some changes to the asset itself
  • null, if the user closes the dialog without persisting any change
  • An asset structure with an additional deleted property set to true, if the user deletes the asset.
View on Github
const uploadId = prompt('Please insert an asset ID:');
const item = await ctx.editUpload(uploadId);
if (item) {
ctx.notice(`Success! ${item.id}`);
} else {
ctx.alert('Closed!');
}

Opens a dialog for editing a "single asset" field structure. It returns a promise resolved with the updated structure, or null if the user closes the dialog without persisting any change.

View on Github
const uploadId = prompt('Please insert an asset ID:');
const result = await ctx.editUploadMetadata({
upload_id: uploadId,
alt: null,
title: null,
custom_data: {},
focal_point: null,
});
if (result) {
ctx.notice(`Success! ${JSON.stringify(result)}`);
} else {
ctx.alert('Closed!');
}

renderAssetSource(assetSourceId: string, ctx)

This function will be called when the user selects one of the plugin's asset sources to upload a new media file.

Context object

The following properties and methods are available in the ctx argument:

This hook exposes additional information and operations specific to the context in which it operates.

The ID of the assetSource that needs to be rendered.

View on Github

Function to be called when the user selects the asset: it will trigger the creation of a new Upload that will be added in the Media Area.

View on Github
await ctx.select({
resource: {
url: 'https://images.unsplash.com/photo-1416339306562-f3d12fefd36f',
filename: 'man-drinking-coffee.jpg',
},
copyright: 'Royalty free (Unsplash)',
author: 'Jeff Sheldon',
notes: 'A man drinking a coffee',
tags: ['man', 'coffee'],
});

Every hook available in the Plugin SDK shares the same minumum set of properties and methods.

Information about the current user using the CMS.

The current DatoCMS user. It can either be the owner or one of the collaborators (regular or SSO).

View on Github

The role for the current DatoCMS user.

View on Github

The access token to perform API calls on behalf of the current user. Only available if currentUserAccessToken additional permission is granted.

View on Github
These methods can be used to open custom dialogs/confirmation panels.

Opens a custom modal. Returns a promise resolved with what the modal itself returns calling the resolve() function.

View on Github
const result = await ctx.openModal({
id: 'regular',
title: 'Custom title!',
width: 'l',
parameters: { foo: 'bar' },
});
if (result) {
ctx.notice(`Success! ${JSON.stringify(result)}`);
} else {
ctx.alert('Closed!');
}

Opens a UI-consistent confirmation dialog. Returns a promise resolved with the value of the choice made by the user.

View on Github
const result = await ctx.openConfirm({
title: 'Custom title',
content:
'Lorem Ipsum is simply dummy text of the printing and typesetting industry',
choices: [
{
label: 'Positive',
value: 'positive',
intent: 'positive',
},
{
label: 'Negative',
value: 'negative',
intent: 'negative',
},
],
cancel: {
label: 'Cancel',
value: false,
},
});
if (result) {
ctx.notice(`Success! ${result}`);
} else {
ctx.alert('Cancelled!');
}
These properties provide access to "entity repos", that is, the collection of resources of a particular type that have been loaded by the CMS up to this moment. The entity repos are objects, indexed by the ID of the entity itself.

All the models of the current DatoCMS project, indexed by ID.

View on Github

All the fields currently loaded for the current DatoCMS project, indexed by ID. If some fields you need are not present, use the loadItemTypeFields function to load them.

View on Github

All the fieldsets currently loaded for the current DatoCMS project, indexed by ID. If some fields you need are not present, use the loadItemTypeFieldsets function to load them.

View on Github

All the regular users currently loaded for the current DatoCMS project, indexed by ID. It will always contain the current user. If some users you need are not present, use the loadUsers function to load them.

View on Github

All the SSO users currently loaded for the current DatoCMS project, indexed by ID. It will always contain the current user. If some users you need are not present, use the loadSsoUsers function to load them.

View on Github
These methods let you open the standard DatoCMS dialogs needed to interact with records.

Opens a dialog for creating a new record. It returns a promise resolved with the newly created record or null if the user closes the dialog without creating anything.

View on Github
const itemTypeId = prompt('Please insert a model ID:');
const item = await ctx.createNewItem(itemTypeId);
if (item) {
ctx.notice(`Success! ${item.id}`);
} else {
ctx.alert('Closed!');
}

Opens a dialog for selecting one (or multiple) record(s) from a list of existing records of type itemTypeId. It returns a promise resolved with the selected record(s), or null if the user closes the dialog without choosing any record.

View on Github
const itemTypeId = prompt('Please insert a model ID:');
const items = await ctx.selectItem(itemTypeId, { multiple: true });
if (items) {
ctx.notice(`Success! ${items.map((i) => i.id).join(', ')}`);
} else {
ctx.alert('Closed!');
}

Opens a dialog for editing an existing record. It returns a promise resolved with the edited record, or null if the user closes the dialog without persisting any change.

View on Github
const itemId = prompt('Please insert a record ID:');
const item = await ctx.editItem(itemId);
if (item) {
ctx.notice(`Success! ${item.id}`);
} else {
ctx.alert('Closed!');
}
These methods can be used to asyncronously load additional information your plugin needs to work.

Loads all the fields for a specific model (or block). Fields will be returned and will also be available in the the fields property.

View on Github
const itemTypeId = prompt('Please insert a model ID:');
const fields = await ctx.loadItemTypeFields(itemTypeId);
ctx.notice(
`Success! ${fields
.map((field) => field.attributes.api_key)
.join(', ')}`,
);

Loads all the fieldsets for a specific model (or block). Fieldsets will be returned and will also be available in the the fieldsets property.

View on Github
const itemTypeId = prompt('Please insert a model ID:');
const fieldsets = await ctx.loadItemTypeFieldsets(itemTypeId);
ctx.notice(
`Success! ${fieldsets
.map((fieldset) => fieldset.attributes.title)
.join(', ')}`,
);

Loads all the fields in the project that are currently using the plugin for one of its manual field extensions.

View on Github
const fields = await ctx.loadFieldsUsingPlugin();
ctx.notice(
`Success! ${fields
.map((field) => field.attributes.api_key)
.join(', ')}`,
);

Loads all regular users. Users will be returned and will also be available in the the users property.

View on Github
const users = await ctx.loadUsers();
ctx.notice(`Success! ${users.map((user) => user.id).join(', ')}`);

Loads all SSO users. Users will be returned and will also be available in the the ssoUsers property.

View on Github
const users = await ctx.loadSsoUsers();
ctx.notice(`Success! ${users.map((user) => user.id).join(', ')}`);
These methods can be used to take the user to different pages.

Moves the user to another URL internal to the backend.

View on Github
await ctx.navigateTo('/');
Information about the current plugin. Useful to access the plugin's global configuration object.

The current plugin.

View on Github

The current DatoCMS project.

View on Github

The ID of the current environment.

View on Github

The account/organization that is the project owner.

View on Github

UI preferences of the current user (right now, only the preferred locale is available).

View on Github

An object containing the theme colors for the current DatoCMS project.

View on Github
A number of methods that you can use to control the size of the plugin frame.

Listens for DOM changes and automatically calls setHeight when it detects a change. If you're using datocms-react-ui package, the <Canvas /> component already takes care of calling this method for you.

View on Github

Stops resizing the iframe automatically.

View on Github

Triggers a change in the size of the iframe. If you don't explicitely pass a newHeight it will be automatically calculated using the iframe content at the moment.

View on Github
These methods can be used to show UI-consistent toast notifications to the end-user.

Triggers an "error" toast displaying the selected message.

View on Github
const message = prompt(
'Please insert a message:',
'This is an alert message!',
);
await ctx.alert(message);

Triggers a "success" toast displaying the selected message.

View on Github
const message = prompt(
'Please insert a message:',
'This is a notice message!',
);
await ctx.notice(message);

Triggers a custom toast displaying the selected message (and optionally a CTA).

View on Github
const result = await ctx.customToast({
type: 'warning',
message: 'Just a sample warning notification!',
dismissOnPageChange: true,
dismissAfterTimeout: 5000,
cta: {
label: 'Execute call-to-action',
value: 'cta',
},
});
if (result === 'cta') {
ctx.notice(`Clicked CTA!`);
}
These methods can be used to update both plugin parameters and manual field extensions configuration.

Updates the plugin parameters.

Always check ctx.currentRole.meta.final_permissions.can_edit_schema before calling this, as the user might not have the permission to perform the operation.

View on Github
await ctx.updatePluginParameters({ debugMode: true });
await ctx.notice('Plugin parameters successfully updated!');

Performs changes in the appearance of a field. You can install/remove a manual field extension, or tweak their parameters. If multiple changes are passed, they will be applied sequencially.

Always check ctx.currentRole.meta.final_permissions.can_edit_schema before calling this, as the user might not have the permission to perform the operation.

View on Github
const fields = await ctx.loadFieldsUsingPlugin();
if (fields.length === 0) {
ctx.alert('No field is using this plugin as a manual extension!');
return;
}
for (const field of fields) {
const { appearance } = field.attributes;
const operations = [];
if (appearance.editor === ctx.plugin.id) {
operations.push({
operation: 'updateEditor',
newParameters: {
...appearance.parameters,
foo: 'bar',
},
});
}
appearance.addons.forEach((addon, i) => {
if (addon.id !== ctx.plugin.id) {
return;
}
operations.push({
operation: 'updateAddon',
index: i,
newParameters: { ...addon.parameters, foo: 'bar' },
});
});
await ctx.updateFieldAppearance(field.id, operations);
ctx.notice(`Successfully edited field ${field.attributes.api_key}`);
}
These methods let you open the standard DatoCMS dialogs needed to interact with Media Area assets.

Opens a dialog for selecting one (or multiple) existing asset(s). It returns a promise resolved with the selected asset(s), or null if the user closes the dialog without selecting any upload.

View on Github
const item = await ctx.selectUpload({ multiple: false });
if (item) {
ctx.notice(`Success! ${item.id}`);
} else {
ctx.alert('Closed!');
}

Opens a dialog for editing a Media Area asset. It returns a promise resolved with:

  • The updated asset, if the user persists some changes to the asset itself
  • null, if the user closes the dialog without persisting any change
  • An asset structure with an additional deleted property set to true, if the user deletes the asset.
View on Github
const uploadId = prompt('Please insert an asset ID:');
const item = await ctx.editUpload(uploadId);
if (item) {
ctx.notice(`Success! ${item.id}`);
} else {
ctx.alert('Closed!');
}

Opens a dialog for editing a "single asset" field structure. It returns a promise resolved with the updated structure, or null if the user closes the dialog without persisting any change.

View on Github
const uploadId = prompt('Please insert an asset ID:');
const result = await ctx.editUploadMetadata({
upload_id: uploadId,
alt: null,
title: null,
custom_data: {},
focal_point: null,
});
if (result) {
ctx.notice(`Success! ${JSON.stringify(result)}`);
} else {
ctx.alert('Closed!');
}