@atlaskit/node-data-provider 4.2.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,237 @@
1
+ import { isSSR } from '@atlaskit/editor-common/core-utils';
2
+
3
+ /**
4
+ * Represents the SSR data for a single provider.
5
+ * It's a map where each key is a unique node data key and the value is the prefetched data for that node.
6
+ *
7
+ * @example
8
+ * {
9
+ * 'node-id-1': { value: 'some data' },
10
+ * 'node-id-2': { value: 'other data' }
11
+ * }
12
+ */
13
+
14
+ /**
15
+ * Represents the cached data for a Node Data Provider.
16
+ * Each key is a unique node data key, and the value is an object containing:
17
+ * - `source`: Indicates whether the data was fetched from SSR or the network.
18
+ * - `data`: The actual data, which can be either a resolved value or a Promise.
19
+ *
20
+ * @example
21
+ * {
22
+ * 'node-id-1': { source: 'ssr', data: { value: 'some data' } },
23
+ * 'node-id-2': { source: 'network', data: Promise.resolve({ value: 'other data' }) }
24
+ * }
25
+ */
26
+
27
+ /**
28
+ * Represents the payload passed to the callback function when data is fetched.
29
+ * It can either contain an error or the fetched data.
30
+ */
31
+
32
+ /**
33
+ * A Node Data Provider is responsible for fetching and caching data associated with specific ProseMirror nodes.
34
+ * It supports a cache-first-then-network strategy, with initial data potentially provided via SSR.
35
+ *
36
+ * @template Node The specific type of JSONNode this provider supports.
37
+ * @template Data The type of data this provider fetches and manages.
38
+ */
39
+ export class NodeDataProvider {
40
+ /**
41
+ * A unique name for the provider. Used for identification in SSR.
42
+ */
43
+
44
+ /**
45
+ * A type guard to check if a given JSONNode is supported by this provider.
46
+ * Used to ensure that the provider can handle the node type before attempting to fetch data.
47
+ *
48
+ * @param node The node to check.
49
+ * @returns `true` if the node is of the type supported by this provider, otherwise `false`.
50
+ */
51
+
52
+ /**
53
+ * Generates a unique key for a given node to be used for caching.
54
+ *
55
+ * @param node The node for which to generate a data key.
56
+ * @returns A unique string key for the node's data.
57
+ */
58
+
59
+ /**
60
+ * Fetches data for a batch of nodes from the network or another asynchronous source.
61
+ *
62
+ * @param nodes An array of nodes for which to fetch data.
63
+ * @returns A promise that resolves to an array of data corresponding to the input nodes.
64
+ */
65
+
66
+ constructor() {
67
+ this.cacheVersion = 0;
68
+ this.cache = {};
69
+ }
70
+
71
+ /**
72
+ * Sets the SSR data for the provider.
73
+ * This pre-populates the cache with data rendered on the server, preventing redundant network requests on the client.
74
+ * Calling this method will invalidate the existing cache.
75
+ *
76
+ * @example
77
+ * ```
78
+ * const ssrData = window.__SSR_NODE_DATA__ || {};
79
+ * nodeDataProvider.setSSRData(ssrData);
80
+ * ```
81
+ *
82
+ * @param ssrData A map of node data keys to their corresponding data.
83
+ */
84
+ setSSRData(ssrData = {}) {
85
+ this.cacheVersion++;
86
+ this.cache = Object.fromEntries(Object.entries(ssrData).map(([key, data]) => [key, {
87
+ data,
88
+ source: 'ssr'
89
+ }]));
90
+ }
91
+
92
+ /**
93
+ * Clears all cached data.
94
+ * This increments the internal cache version, invalidating any pending network requests.
95
+ *
96
+ * @example
97
+ * ```
98
+ * function useMyNodeDataProvider(contentId: string) {
99
+ * const nodeDataProvider = new MyNodeDataProvider();
100
+ *
101
+ * // Reset the cache when the contentId changes (e.g., when the user navigates to a different page).
102
+ * useEffect(() => {
103
+ * nodeDataProvider.resetCache();
104
+ * }, [contentId]);
105
+ *
106
+ * return nodeDataProvider;
107
+ * }
108
+ * ```
109
+ */
110
+ resetCache() {
111
+ this.cacheVersion++;
112
+ this.cache = {};
113
+ }
114
+
115
+ /**
116
+ * Fetches data for a given node using a cache-first-then-network strategy.
117
+ *
118
+ * The provided callback may be called multiple times:
119
+ * 1. Immediately with data from the SSR cache, if available.
120
+ * 2. Asynchronously with data fetched from the network.
121
+ *
122
+ * @example
123
+ * ```
124
+ * const nodeDataProvider = new MyNodeDataProvider();
125
+ *
126
+ * nodeDataProvider.getData(node, (data) => {
127
+ * console.log('Node data:', data);
128
+ * });
129
+ * ```
130
+ *
131
+ * @param node The node (or its ProseMirror representation) for which to fetch data.
132
+ * @param callback The callback function to call with the fetched data or an error.
133
+ */
134
+ getData(node, callback) {
135
+ // Move implementation to a separate async method
136
+ // to keep this method synchronous and avoid async/await in the public API.
137
+ void this.getDataAsync(node, callback);
138
+ }
139
+ async getDataAsync(node, callback) {
140
+ try {
141
+ const jsonNode = 'toJSON' in node ? node.toJSON() : node;
142
+ if (!this.isNodeSupported(jsonNode)) {
143
+ // eslint-disable-next-line no-console
144
+ console.error(`The ${this.constructor.name} doesn't support Node ${jsonNode.type}.`);
145
+ return;
146
+ }
147
+ const dataKey = this.nodeDataKey(jsonNode);
148
+ const dataFromCache = this.cache[dataKey];
149
+ if (dataFromCache !== undefined) {
150
+ // If we have the data in the SSR data, we can use it directly
151
+ if (isPromise(dataFromCache.data)) {
152
+ callback({
153
+ data: await dataFromCache.data
154
+ });
155
+ } else {
156
+ callback({
157
+ data: dataFromCache.data
158
+ });
159
+ }
160
+ if (isSSR()) {
161
+ // If we are in SSR, we don't want to fetch the data again, as it is already available in the SSR data
162
+ return;
163
+ }
164
+ }
165
+
166
+ // If no data is available in the cache or the data is from the network,
167
+ // we need to fetch it from the network.
168
+ if ((dataFromCache === null || dataFromCache === void 0 ? void 0 : dataFromCache.source) !== 'network') {
169
+ // Store the current cache version before making the request,
170
+ // so we can check if the cache has changed while we are waiting for the network response.
171
+ const cacheVersionBeforeRequest = this.cacheVersion;
172
+ const dataPromise = this.fetchNodesData([jsonNode]).then(([value]) => value);
173
+ // Store the promise in the cache to avoid multiple requests for the same data
174
+ this.cache[dataKey] = {
175
+ source: 'network',
176
+ data: dataPromise
177
+ };
178
+ const data = await dataPromise;
179
+ // We need to call the callback with the data with result even if the cache version has changed,
180
+ // so all promises that are waiting for the data can resolve.
181
+ callback({
182
+ data
183
+ });
184
+
185
+ // If the cache version has changed, we don't want to use the data from the network
186
+ // because it could be stale data.
187
+ if (cacheVersionBeforeRequest === this.cacheVersion) {
188
+ // Replace promise with the resolved data in the cache
189
+ this.cache[dataKey] = {
190
+ source: 'network',
191
+ data
192
+ };
193
+ }
194
+ }
195
+ } catch (error) {
196
+ // If an error occurs, we call the callback with the error
197
+ callback({
198
+ error: error instanceof Error ? error : new Error(String(error))
199
+ });
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Fetches data for a given node and returns it as a Promise.
205
+ * This is a convenience wrapper around the `data` method for use with async/await.
206
+ *
207
+ * Note: This promise resolves with the *first* available data, which could be from the SSR cache or the network.
208
+ * It may not provide the most up-to-date data if a network fetch is in progress.
209
+ *
210
+ * Note: This method is only for migration purposes. Use {@link getData} in new code instead.
211
+ *
212
+ * @private
213
+ * @deprecated Don't use this method, use {@link getData} method instead.
214
+ * This method is only for migration purposes.
215
+ *
216
+ * @param node The node (or its ProseMirror representation) for which to fetch data.
217
+ * @returns A promise that resolves with the node's data.
218
+ */
219
+ getDataAsPromise_DO_NOT_USE_OUTSIDE_MIGRATIONS(node) {
220
+ return new Promise((resolve, reject) => {
221
+ try {
222
+ this.getData(node, payload => {
223
+ if (payload.error) {
224
+ reject(payload.error);
225
+ } else {
226
+ resolve(payload.data);
227
+ }
228
+ });
229
+ } catch (error) {
230
+ reject(error);
231
+ }
232
+ });
233
+ }
234
+ }
235
+ function isPromise(value) {
236
+ return typeof value === 'object' && value !== null && 'then' in value && typeof value.then === 'function';
237
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Finds nodes in the document that are supported by the given providers, up to a maximum number of nodes.
3
+ *
4
+ * @param doc The document to search for nodes.
5
+ * @param providers An array of providers with their maximum nodes to prefetch.
6
+ * @param maxNodesToVisit The maximum number of nodes to visit in the document.
7
+ * @returns An array of objects, each containing a provider and the nodes that are supported by that provider.
8
+ */
9
+ export function findNodesToPrefetch(doc, providers, maxNodesToVisit) {
10
+ // Counter for the total number of visited nodes to limit the traversal.
11
+ let totalVisitedNodesCount = 0;
12
+ // A map to store the results, with the provider name as the key.
13
+ const resultMap = providers.reduce((acc, {
14
+ provider
15
+ }) => {
16
+ acc[provider.name] = {
17
+ provider,
18
+ nodes: []
19
+ };
20
+ return acc;
21
+ }, {});
22
+
23
+ // It doesn't use `filter` function from `@atlaskit/adf-utils/traverse` because it does not support early stopping.
24
+ // We need to stop traversing when we reach the maximum number of nodes to visit to support large documents.
25
+
26
+ // Create a list of providers for which we still need to find nodes.
27
+ const providersToLookup = providers.filter(({
28
+ maxNodesToPrefetch
29
+ }) => maxNodesToPrefetch > 0).map(({
30
+ provider,
31
+ maxNodesToPrefetch
32
+ }) => ({
33
+ provider,
34
+ maxNodesToPrefetch,
35
+ foundNodes: 0 // Counter for nodes found for each provider.
36
+ }));
37
+
38
+ // Queue for the breadth-first search (BFS), starting with the root document node.
39
+ const nodesToVisit = [doc];
40
+ let currentIndex = 0;
41
+ // The loop continues as long as there are nodes to visit, providers to look for,
42
+ // and the visited nodes limit has not been reached.
43
+ while (currentIndex < nodesToVisit.length && providersToLookup.length > 0 && totalVisitedNodesCount < maxNodesToVisit) {
44
+ totalVisitedNodesCount += 1;
45
+ const currentNode = nodesToVisit[currentIndex];
46
+ currentIndex++;
47
+
48
+ // Using a reverse loop to avoid issues with array mutation (when removing elements).
49
+ for (let i = providersToLookup.length - 1; i >= 0; i--) {
50
+ const providerToFind = providersToLookup[i];
51
+
52
+ // Check if the current provider supports this node.
53
+ if (providerToFind.provider.isNodeSupported(currentNode)) {
54
+ // If provider supports the node, add it to the result map.
55
+ resultMap[providerToFind.provider.name].nodes.push(currentNode);
56
+ // Increment the count of found nodes for this provider.
57
+ providerToFind.foundNodes += 1;
58
+
59
+ // If the provider has found enough nodes, remove it from the lookup list.
60
+ if (providerToFind.foundNodes >= providerToFind.maxNodesToPrefetch) {
61
+ providersToLookup.splice(i, 1);
62
+ }
63
+ }
64
+ }
65
+
66
+ // If the current node has children, add them to the queue to be visited.
67
+ if (currentNode.content) {
68
+ nodesToVisit.push(...currentNode.content.filter(node => node !== undefined));
69
+ }
70
+ }
71
+
72
+ // Return an array of the found nodes, grouped by provider.
73
+ return Object.values(resultMap);
74
+ }
@@ -0,0 +1,128 @@
1
+ import { findNodesToPrefetch } from './find-nodes-to-prefetch';
2
+
3
+ /**
4
+ * Represents the SSR data for a single provider.
5
+ * It's a map where each key is a unique node data key and the value is the prefetched data for that node.
6
+ *
7
+ * @example
8
+ * {
9
+ * 'node-id-1': { value: 'some data' },
10
+ * 'node-id-2': { value: 'other data' }
11
+ * }
12
+ */
13
+
14
+ /**
15
+ * Represents the aggregated SSR data for all node data providers.
16
+ * It's a map where each key is a provider's name and the value is the {@link SsrData} for that provider.
17
+ * This structure is used to hydrate the client-side caches.
18
+ *
19
+ * @example
20
+ * {
21
+ * 'mentionProvider': { 'mention-1': { id: '1', name: 'John Doe' } },
22
+ * 'emojiProvider': { 'emoji-123': { shortName: ':smile:', representation: '😊' } }
23
+ * }
24
+ */
25
+
26
+ /**
27
+ * Fetches data for nodes in the document that are supported by the given providers.
28
+ * This function will traverse the document and call the `fetchData` method for each node that is supported by the providers.
29
+ *
30
+ * @example
31
+ * ```
32
+ * const doc = JSON.parse('{"type": "doc", "content": [...] }');
33
+ * const providers = [
34
+ * {
35
+ * provider: new EditorCardProvider(),
36
+ * maxNodesToPrefetch: 10,
37
+ * timeout: 500,
38
+ * },
39
+ * {
40
+ * provider: new EditorMentionsProvider(),
41
+ * maxNodesToPrefetch: 50,
42
+ * timeout: 500,
43
+ * },
44
+ * ];
45
+ *
46
+ * window['__SSR_EDITOR_NODE_DATA_PROVIDERS_DATA__'] = await prefetchNodeDataProvidersData({
47
+ * providers,
48
+ * doc,
49
+ * timeout: 1_000,
50
+ * maxNodesToVisit: 2_000
51
+ * });
52
+ * ```
53
+ *
54
+ * @param props The properties for prefetching node data.
55
+ * @returns Record of provider names to their respective SSR data,
56
+ * where each SSR data is a record of node data keys to the fetched data.
57
+ */
58
+ export async function prefetchNodeDataProvidersData({
59
+ providers,
60
+ doc,
61
+ timeout,
62
+ maxNodesToVisit = Infinity
63
+ }) {
64
+ const providersWithDefaults = providers.map(({
65
+ provider,
66
+ maxNodesToPrefetch = Infinity,
67
+ timeout: providerTimeout = Infinity
68
+ }) => ({
69
+ provider,
70
+ maxNodesToPrefetch,
71
+ // Use the minimum of the global timeout and the provider-specific timeout
72
+ timeout: Math.min(providerTimeout, timeout)
73
+ }));
74
+ const providerTimeouts = providersWithDefaults.reduce((acc, {
75
+ provider,
76
+ timeout
77
+ }) => {
78
+ acc[provider.name] = timeout;
79
+ return acc;
80
+ }, {});
81
+ const nodesWithProviders = findNodesToPrefetch(doc, providersWithDefaults, maxNodesToVisit).map(({
82
+ provider,
83
+ nodes
84
+ }) => ({
85
+ provider,
86
+ nodes,
87
+ timeout: providerTimeouts[provider.name]
88
+ }));
89
+ const promises = nodesWithProviders.map(async ({
90
+ nodes,
91
+ provider,
92
+ timeout
93
+ }) => {
94
+ try {
95
+ const timeoutPromise = new Promise(resolve => {
96
+ setTimeout(() => {
97
+ resolve([]);
98
+ }, timeout);
99
+ });
100
+ const data = await Promise.race([provider.fetchNodesData(nodes), timeoutPromise]);
101
+ return {
102
+ provider,
103
+ nodes,
104
+ data
105
+ };
106
+ } catch {
107
+ return {
108
+ provider,
109
+ nodes,
110
+ data: []
111
+ };
112
+ }
113
+ });
114
+ const results = await Promise.all(promises);
115
+ return results.reduce((acc, {
116
+ provider,
117
+ nodes,
118
+ data
119
+ }) => {
120
+ acc[provider.name] = data.reduce((providerSsrData, nodeData, nodeIndex) => {
121
+ const node = nodes[nodeIndex];
122
+ const nodeDataKey = provider.nodeDataKey(node);
123
+ providerSsrData[nodeDataKey] = nodeData;
124
+ return providerSsrData;
125
+ }, {});
126
+ return acc;
127
+ }, {});
128
+ }
package/dist/esm/index.js CHANGED
@@ -0,0 +1,4 @@
1
+ /* eslint-disable @atlaskit/editor/no-re-export */
2
+
3
+ export { NodeDataProvider } from './node-data-provider';
4
+ export { prefetchNodeDataProvidersData } from './utils/prefetch-node-data-providers-data';