@atlaskit/editor-plugin-card
Version:
Card plugin for @atlaskit/editor-core
58 lines • 1.69 kB
JavaScript
/**
* Creates a registry of resolved cards, for use with editor actions.
* Registration changes (insertion, deletion, and id/title/url updates) notify subscribers; live position changes do not.
*
* @returns A registry object with the following methods:
* - `getCardRegistrations`: Returns the current registrations, keyed by card ID.
* - `registerCard`: Adds or updates a card.
* - `removeCard`: Removes a card by ID.
* - `subscribe`: Registers a change listener and returns an unsubscribe function.
*/
export const createCardRegistry = () => {
// Replace registrations on each change to notify subscribers and trigger React updates.
let registrations = {};
const listeners = new Set();
const getCardRegistrations = () => registrations;
const notify = () => {
Array.from(listeners).forEach(listener => listener());
};
const registerCard = info => {
if (info.getPos() === undefined) {
return;
}
const previous = registrations[info.id];
if (previous && previous.getPos === info.getPos && previous.title === info.title && previous.url === info.url) {
return; // Don't mutate registrations if no change
}
registrations = {
...registrations,
[info.id]: {
...info
}
};
notify();
};
const removeCard = id => {
if (!registrations[id]) {
return;
}
const next = {
...registrations
};
delete next[id];
registrations = next;
notify();
};
const subscribe = listener => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
};
return {
registerCard,
removeCard,
subscribe,
getCardRegistrations
};
};