@atlaskit/node-data-provider 4.1.2 → 4.3.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.
- package/CHANGELOG.md +22 -0
- package/dist/cjs/index.js +13 -226
- package/dist/cjs/node-data-provider.js +252 -0
- package/dist/cjs/utils/find-nodes-to-prefetch.js +68 -0
- package/dist/cjs/utils/prefetch-node-data-providers-data.js +165 -0
- package/dist/es2019/index.js +3 -190
- package/dist/es2019/node-data-provider.js +216 -0
- package/dist/es2019/utils/find-nodes-to-prefetch.js +57 -0
- package/dist/es2019/utils/prefetch-node-data-providers-data.js +128 -0
- package/dist/esm/index.js +3 -226
- package/dist/esm/node-data-provider.js +248 -0
- package/dist/esm/utils/find-nodes-to-prefetch.js +61 -0
- package/dist/esm/utils/prefetch-node-data-providers-data.js +161 -0
- package/dist/types/index.d.ts +2 -134
- package/dist/types/node-data-provider.d.ts +125 -0
- package/dist/types/utils/find-nodes-to-prefetch.d.ts +21 -0
- package/dist/types/utils/prefetch-node-data-providers-data.d.ts +107 -0
- package/dist/types-ts4.5/index.d.ts +2 -134
- package/dist/types-ts4.5/node-data-provider.d.ts +125 -0
- package/dist/types-ts4.5/utils/find-nodes-to-prefetch.d.ts +21 -0
- package/dist/types-ts4.5/utils/prefetch-node-data-providers-data.d.ts +107 -0
- package/package.json +6 -13
- package/cache/package.json +0 -15
- package/content/package.json +0 -15
- package/dist/cjs/cache.js +0 -145
- package/dist/cjs/consumption/_global-ndp-caches.js +0 -21
- package/dist/cjs/consumption/_internal-context.js +0 -77
- package/dist/cjs/consumption/_lru-cache.js +0 -45
- package/dist/cjs/consumption/content.js +0 -56
- package/dist/cjs/get-providers/confluence-page.js +0 -15
- package/dist/cjs/internal-types.js +0 -5
- package/dist/cjs/plugin-hooks.js +0 -100
- package/dist/cjs/providers/emoji.js +0 -54
- package/dist/es2019/cache.js +0 -96
- package/dist/es2019/consumption/_global-ndp-caches.js +0 -13
- package/dist/es2019/consumption/_internal-context.js +0 -71
- package/dist/es2019/consumption/_lru-cache.js +0 -30
- package/dist/es2019/consumption/content.js +0 -49
- package/dist/es2019/get-providers/confluence-page.js +0 -10
- package/dist/es2019/internal-types.js +0 -1
- package/dist/es2019/plugin-hooks.js +0 -69
- package/dist/es2019/providers/emoji.js +0 -26
- package/dist/esm/cache.js +0 -141
- package/dist/esm/consumption/_global-ndp-caches.js +0 -13
- package/dist/esm/consumption/_internal-context.js +0 -71
- package/dist/esm/consumption/_lru-cache.js +0 -38
- package/dist/esm/consumption/content.js +0 -49
- package/dist/esm/get-providers/confluence-page.js +0 -9
- package/dist/esm/internal-types.js +0 -1
- package/dist/esm/plugin-hooks.js +0 -93
- package/dist/esm/providers/emoji.js +0 -47
- package/dist/types/cache.d.ts +0 -61
- package/dist/types/consumption/_global-ndp-caches.d.ts +0 -8
- package/dist/types/consumption/_internal-context.d.ts +0 -32
- package/dist/types/consumption/_lru-cache.d.ts +0 -7
- package/dist/types/consumption/content.d.ts +0 -65
- package/dist/types/get-providers/confluence-page.d.ts +0 -6
- package/dist/types/internal-types.d.ts +0 -2
- package/dist/types/plugin-hooks.d.ts +0 -32
- package/dist/types/providers/emoji.d.ts +0 -10
- package/dist/types-ts4.5/cache.d.ts +0 -61
- package/dist/types-ts4.5/consumption/_global-ndp-caches.d.ts +0 -8
- package/dist/types-ts4.5/consumption/_internal-context.d.ts +0 -32
- package/dist/types-ts4.5/consumption/_lru-cache.d.ts +0 -7
- package/dist/types-ts4.5/consumption/content.d.ts +0 -65
- package/dist/types-ts4.5/get-providers/confluence-page.d.ts +0 -6
- package/dist/types-ts4.5/internal-types.d.ts +0 -2
- package/dist/types-ts4.5/plugin-hooks.d.ts +0 -32
- package/dist/types-ts4.5/providers/emoji.d.ts +0 -10
- package/emoji-provider/package.json +0 -15
- package/get-confluence-page-providers/package.json +0 -15
- package/plugin-hooks/package.json +0 -15
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
|
4
|
+
Object.defineProperty(exports, "__esModule", {
|
|
5
|
+
value: true
|
|
6
|
+
});
|
|
7
|
+
exports.prefetchNodeDataProvidersData = prefetchNodeDataProvidersData;
|
|
8
|
+
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
|
|
9
|
+
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
|
|
10
|
+
var _findNodesToPrefetch = require("./find-nodes-to-prefetch");
|
|
11
|
+
/**
|
|
12
|
+
* Represents the SSR data for a single provider.
|
|
13
|
+
* It's a map where each key is a unique node data key and the value is the prefetched data for that node.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* {
|
|
17
|
+
* 'node-id-1': { value: 'some data' },
|
|
18
|
+
* 'node-id-2': { value: 'other data' }
|
|
19
|
+
* }
|
|
20
|
+
*/
|
|
21
|
+
/**
|
|
22
|
+
* Represents the aggregated SSR data for all node data providers.
|
|
23
|
+
* It's a map where each key is a provider's name and the value is the {@link SsrData} for that provider.
|
|
24
|
+
* This structure is used to hydrate the client-side caches.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* {
|
|
28
|
+
* 'mentionProvider': { 'mention-1': { id: '1', name: 'John Doe' } },
|
|
29
|
+
* 'emojiProvider': { 'emoji-123': { shortName: ':smile:', representation: '😊' } }
|
|
30
|
+
* }
|
|
31
|
+
*/
|
|
32
|
+
/**
|
|
33
|
+
* Fetches data for nodes in the document that are supported by the given providers.
|
|
34
|
+
* This function will traverse the document and call the `fetchData` method for each node that is supported by the providers.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```
|
|
38
|
+
* const doc = JSON.parse('{"type": "doc", "content": [...] }');
|
|
39
|
+
* const providers = [
|
|
40
|
+
* {
|
|
41
|
+
* provider: new EditorCardProvider(),
|
|
42
|
+
* maxNodesToPrefetch: 10,
|
|
43
|
+
* timeout: 500,
|
|
44
|
+
* },
|
|
45
|
+
* {
|
|
46
|
+
* provider: new EditorMentionsProvider(),
|
|
47
|
+
* maxNodesToPrefetch: 50,
|
|
48
|
+
* timeout: 500,
|
|
49
|
+
* },
|
|
50
|
+
* ];
|
|
51
|
+
*
|
|
52
|
+
* window['__SSR_EDITOR_NODE_DATA_PROVIDERS_DATA__'] = await prefetchNodeDataProvidersData({
|
|
53
|
+
* providers,
|
|
54
|
+
* doc,
|
|
55
|
+
* timeout: 1_000,
|
|
56
|
+
* maxNodesToVisit: 2_000
|
|
57
|
+
* });
|
|
58
|
+
* ```
|
|
59
|
+
*
|
|
60
|
+
* @param props The properties for prefetching node data.
|
|
61
|
+
* @returns Record of provider names to their respective SSR data,
|
|
62
|
+
* where each SSR data is a record of node data keys to the fetched data.
|
|
63
|
+
*/
|
|
64
|
+
function prefetchNodeDataProvidersData(_x) {
|
|
65
|
+
return _prefetchNodeDataProvidersData.apply(this, arguments);
|
|
66
|
+
}
|
|
67
|
+
function _prefetchNodeDataProvidersData() {
|
|
68
|
+
_prefetchNodeDataProvidersData = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(_ref) {
|
|
69
|
+
var providers, doc, timeout, _ref$maxNodesToVisit, maxNodesToVisit, providersWithDefaults, providerTimeouts, nodesWithProviders, promises, results;
|
|
70
|
+
return _regenerator.default.wrap(function _callee2$(_context2) {
|
|
71
|
+
while (1) switch (_context2.prev = _context2.next) {
|
|
72
|
+
case 0:
|
|
73
|
+
providers = _ref.providers, doc = _ref.doc, timeout = _ref.timeout, _ref$maxNodesToVisit = _ref.maxNodesToVisit, maxNodesToVisit = _ref$maxNodesToVisit === void 0 ? Infinity : _ref$maxNodesToVisit;
|
|
74
|
+
providersWithDefaults = providers.map(function (_ref2) {
|
|
75
|
+
var provider = _ref2.provider,
|
|
76
|
+
_ref2$maxNodesToPrefe = _ref2.maxNodesToPrefetch,
|
|
77
|
+
maxNodesToPrefetch = _ref2$maxNodesToPrefe === void 0 ? Infinity : _ref2$maxNodesToPrefe,
|
|
78
|
+
_ref2$timeout = _ref2.timeout,
|
|
79
|
+
providerTimeout = _ref2$timeout === void 0 ? Infinity : _ref2$timeout;
|
|
80
|
+
return {
|
|
81
|
+
provider: provider,
|
|
82
|
+
maxNodesToPrefetch: maxNodesToPrefetch,
|
|
83
|
+
// Use the minimum of the global timeout and the provider-specific timeout
|
|
84
|
+
timeout: Math.min(providerTimeout, timeout)
|
|
85
|
+
};
|
|
86
|
+
});
|
|
87
|
+
providerTimeouts = providersWithDefaults.reduce(function (acc, _ref3) {
|
|
88
|
+
var provider = _ref3.provider,
|
|
89
|
+
timeout = _ref3.timeout;
|
|
90
|
+
acc[provider.name] = timeout;
|
|
91
|
+
return acc;
|
|
92
|
+
}, {});
|
|
93
|
+
nodesWithProviders = (0, _findNodesToPrefetch.findNodesToPrefetch)(doc, providersWithDefaults, maxNodesToVisit).map(function (_ref4) {
|
|
94
|
+
var provider = _ref4.provider,
|
|
95
|
+
nodes = _ref4.nodes;
|
|
96
|
+
return {
|
|
97
|
+
provider: provider,
|
|
98
|
+
nodes: nodes,
|
|
99
|
+
timeout: providerTimeouts[provider.name]
|
|
100
|
+
};
|
|
101
|
+
});
|
|
102
|
+
promises = nodesWithProviders.map( /*#__PURE__*/function () {
|
|
103
|
+
var _ref6 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(_ref5) {
|
|
104
|
+
var nodes, provider, timeout, timeoutPromise, data;
|
|
105
|
+
return _regenerator.default.wrap(function _callee$(_context) {
|
|
106
|
+
while (1) switch (_context.prev = _context.next) {
|
|
107
|
+
case 0:
|
|
108
|
+
nodes = _ref5.nodes, provider = _ref5.provider, timeout = _ref5.timeout;
|
|
109
|
+
_context.prev = 1;
|
|
110
|
+
timeoutPromise = new Promise(function (resolve) {
|
|
111
|
+
setTimeout(function () {
|
|
112
|
+
resolve([]);
|
|
113
|
+
}, timeout);
|
|
114
|
+
});
|
|
115
|
+
_context.next = 5;
|
|
116
|
+
return Promise.race([provider.fetchNodesData(nodes), timeoutPromise]);
|
|
117
|
+
case 5:
|
|
118
|
+
data = _context.sent;
|
|
119
|
+
return _context.abrupt("return", {
|
|
120
|
+
provider: provider,
|
|
121
|
+
nodes: nodes,
|
|
122
|
+
data: data
|
|
123
|
+
});
|
|
124
|
+
case 9:
|
|
125
|
+
_context.prev = 9;
|
|
126
|
+
_context.t0 = _context["catch"](1);
|
|
127
|
+
return _context.abrupt("return", {
|
|
128
|
+
provider: provider,
|
|
129
|
+
nodes: nodes,
|
|
130
|
+
data: []
|
|
131
|
+
});
|
|
132
|
+
case 12:
|
|
133
|
+
case "end":
|
|
134
|
+
return _context.stop();
|
|
135
|
+
}
|
|
136
|
+
}, _callee, null, [[1, 9]]);
|
|
137
|
+
}));
|
|
138
|
+
return function (_x2) {
|
|
139
|
+
return _ref6.apply(this, arguments);
|
|
140
|
+
};
|
|
141
|
+
}());
|
|
142
|
+
_context2.next = 7;
|
|
143
|
+
return Promise.all(promises);
|
|
144
|
+
case 7:
|
|
145
|
+
results = _context2.sent;
|
|
146
|
+
return _context2.abrupt("return", results.reduce(function (acc, _ref7) {
|
|
147
|
+
var provider = _ref7.provider,
|
|
148
|
+
nodes = _ref7.nodes,
|
|
149
|
+
data = _ref7.data;
|
|
150
|
+
acc[provider.name] = data.reduce(function (providerSsrData, nodeData, nodeIndex) {
|
|
151
|
+
var node = nodes[nodeIndex];
|
|
152
|
+
var nodeDataKey = provider.nodeDataKey(node);
|
|
153
|
+
providerSsrData[nodeDataKey] = nodeData;
|
|
154
|
+
return providerSsrData;
|
|
155
|
+
}, {});
|
|
156
|
+
return acc;
|
|
157
|
+
}, {}));
|
|
158
|
+
case 9:
|
|
159
|
+
case "end":
|
|
160
|
+
return _context2.stop();
|
|
161
|
+
}
|
|
162
|
+
}, _callee2);
|
|
163
|
+
}));
|
|
164
|
+
return _prefetchNodeDataProvidersData.apply(this, arguments);
|
|
165
|
+
}
|
package/dist/es2019/index.js
CHANGED
|
@@ -1,191 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
/**
|
|
3
|
-
* This is the base class for creating a node data provider for an editor plugin.
|
|
4
|
-
*
|
|
5
|
-
* ## Usage
|
|
6
|
-
*
|
|
7
|
-
* ### Create a provider
|
|
8
|
-
*
|
|
9
|
-
* @example
|
|
10
|
-
* ```ts
|
|
11
|
-
* class EmojiNodeDataProvider extends NodeDataProvider<
|
|
12
|
-
* { attrs: EmojiAttributes },
|
|
13
|
-
* { resolvedData: string }
|
|
14
|
-
* > {
|
|
15
|
-
* constructor({ existingCache }?: { existingCache: Record<string, { resolvedData: string }> }) {
|
|
16
|
-
* super({ existingCache, nodeName: 'emoji' });
|
|
17
|
-
* }
|
|
18
|
-
* nodeToKey(node: { attrs: EmojiAttributes }): string {
|
|
19
|
-
* return `${node.attrs.shortName}-${node.attrs.text}-${node.attrs.id}`;
|
|
20
|
-
* }
|
|
21
|
-
* resolve(node: { attrs: EmojiAttributes }, _?: { signal: AbortSignal }) {
|
|
22
|
-
* return Promise.resolve({ resolvedData: 'resolved' });
|
|
23
|
-
* }
|
|
24
|
-
* }
|
|
25
|
-
* ```
|
|
26
|
-
*
|
|
27
|
-
* ### Use the provider
|
|
28
|
-
*
|
|
29
|
-
* @example
|
|
30
|
-
* ```ts
|
|
31
|
-
* const emojiNodeDataProvider = new EmojiNodeDataProvider();
|
|
32
|
-
* ```
|
|
33
|
-
*
|
|
34
|
-
* ### Caching
|
|
35
|
-
*
|
|
36
|
-
* @see {@link buildCaches} for more information on building caches.
|
|
37
|
-
*
|
|
38
|
-
* #### Load an existing provider with a cache
|
|
39
|
-
*
|
|
40
|
-
* @example
|
|
41
|
-
* ```
|
|
42
|
-
* await buildCaches({
|
|
43
|
-
* adf: docFromSomewhere,
|
|
44
|
-
* nodeDataProviders: [emojiNodeDataProvider],
|
|
45
|
-
* signal: AbortSignal.timeout(5000),
|
|
46
|
-
* });
|
|
47
|
-
* emojiNodeDataProvider // { 'key': 'value' }
|
|
48
|
-
* ```
|
|
49
|
-
*
|
|
50
|
-
* ### Load an new provider with an existing cache
|
|
51
|
-
*
|
|
52
|
-
* @example
|
|
53
|
-
* ```
|
|
54
|
-
* const provider1 = new ExampleNodeDataProvider();
|
|
55
|
-
* await buildCaches({adf, nodeDataProviders: [provider1]})
|
|
56
|
-
* provider1.cache // { 'key': 'value' }
|
|
57
|
-
*
|
|
58
|
-
* const provider2 = new ExampleNodeDataProvider({existingCache: provider1.cache});
|
|
59
|
-
* ```
|
|
60
|
-
*/
|
|
61
|
-
export class NodeDataProvider {
|
|
62
|
-
/**
|
|
63
|
-
* This takes a node and returns a key that can be used to cache the result of the resolve function.
|
|
64
|
-
*/
|
|
1
|
+
/* eslint-disable @atlaskit/editor/no-re-export */
|
|
65
2
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
*
|
|
69
|
-
* If unresolvable, this method will throw an error.
|
|
70
|
-
*
|
|
71
|
-
* If signal is aborted, this method will return undefined.
|
|
72
|
-
*/
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* The adf node name this provider is responsible for.
|
|
76
|
-
*/
|
|
77
|
-
|
|
78
|
-
constructor({
|
|
79
|
-
existingCache = {},
|
|
80
|
-
nodeName,
|
|
81
|
-
nodeToKey,
|
|
82
|
-
resolve
|
|
83
|
-
}) {
|
|
84
|
-
/**
|
|
85
|
-
* This is added to ease building types
|
|
86
|
-
*/
|
|
87
|
-
// @ts-ignore
|
|
88
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
89
|
-
_defineProperty(this, "__node", {});
|
|
90
|
-
_defineProperty(this, "pending", {});
|
|
91
|
-
this.__cache = existingCache;
|
|
92
|
-
this.nodeName = nodeName;
|
|
93
|
-
this.nodeToKey = nodeToKey;
|
|
94
|
-
this.resolve = resolve;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Updates the providers cache.
|
|
99
|
-
*
|
|
100
|
-
* Useful in scenarios such as SSR where the cache is built on the server and then passed to the client.
|
|
101
|
-
*
|
|
102
|
-
* Avoids the need to provide the cache to the constructor (to allow decoupling creation of node data providers from cache building),
|
|
103
|
-
* and allow for caching to be managed at a group level across multiple providers.
|
|
104
|
-
*
|
|
105
|
-
* This is not expected to be used by consumers, for internal consumption examples;
|
|
106
|
-
* @see {@link buildCaches}
|
|
107
|
-
*
|
|
108
|
-
*/
|
|
109
|
-
updateCache(cache, options) {
|
|
110
|
-
switch (options.strategy) {
|
|
111
|
-
case 'merge-override':
|
|
112
|
-
this.__cache = {
|
|
113
|
-
...this.__cache,
|
|
114
|
-
...cache
|
|
115
|
-
};
|
|
116
|
-
return;
|
|
117
|
-
case 'replace':
|
|
118
|
-
this.__cache = cache;
|
|
119
|
-
return;
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* This is the cache for the provider.
|
|
125
|
-
*/
|
|
126
|
-
get cache() {
|
|
127
|
-
return this.__cache;
|
|
128
|
-
}
|
|
129
|
-
get(node, _) {
|
|
130
|
-
const key = this.nodeToKey(node);
|
|
131
|
-
const cached = this.cache[key];
|
|
132
|
-
if (cached) {
|
|
133
|
-
return cached;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// Get could be called from a variety of sources;
|
|
137
|
-
// - a Node Data Provider
|
|
138
|
-
// - a cache build
|
|
139
|
-
// - something else
|
|
140
|
-
//
|
|
141
|
-
// We want to avoid triggering multiple resolves for the same node -- so we keep track of pending requests
|
|
142
|
-
// and share them across any overlapping gets.
|
|
143
|
-
//
|
|
144
|
-
// When a get is cancelled -- we only want to cancel the shared resolve if all signals are aborted
|
|
145
|
-
// so we keep track of all signals that are not aborted.
|
|
146
|
-
|
|
147
|
-
const originalSignal = (_ === null || _ === void 0 ? void 0 : _.signal) || new AbortController().signal;
|
|
148
|
-
if (!this.pending[key]) {
|
|
149
|
-
const abortController = new AbortController();
|
|
150
|
-
this.pending[key] = {
|
|
151
|
-
// eslint-disable-next-line no-async-promise-executor
|
|
152
|
-
resolving: new Promise(async (res, rej) => {
|
|
153
|
-
try {
|
|
154
|
-
const result = await this.resolve(node, {
|
|
155
|
-
signal: abortController.signal
|
|
156
|
-
}).catch(res => res(undefined));
|
|
157
|
-
res(result);
|
|
158
|
-
} catch {
|
|
159
|
-
res(undefined);
|
|
160
|
-
}
|
|
161
|
-
}),
|
|
162
|
-
abortController,
|
|
163
|
-
activeSignals: [originalSignal]
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
const handleAbort = () => {
|
|
167
|
-
this.pending[key].activeSignals = this.pending[key].activeSignals.filter(activeSignal => activeSignal !== originalSignal);
|
|
168
|
-
if (this.pending[key].activeSignals.length === 0) {
|
|
169
|
-
// abort the resolution if all signals are aborted
|
|
170
|
-
this.pending[key].abortController.abort();
|
|
171
|
-
}
|
|
172
|
-
};
|
|
173
|
-
|
|
174
|
-
// eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
|
|
175
|
-
originalSignal === null || originalSignal === void 0 ? void 0 : originalSignal.addEventListener('abort', handleAbort);
|
|
176
|
-
this.pending[key].resolving.then(resolvedValue => {
|
|
177
|
-
if (resolvedValue) {
|
|
178
|
-
this.cache[key] = resolvedValue;
|
|
179
|
-
}
|
|
180
|
-
// eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
|
|
181
|
-
originalSignal === null || originalSignal === void 0 ? void 0 : originalSignal.removeEventListener('abort', handleAbort);
|
|
182
|
-
return resolvedValue;
|
|
183
|
-
});
|
|
184
|
-
return this.pending[key].resolving;
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// The purpose of this type is to ensure that either a DocNode or a PMNode is passed in
|
|
189
|
-
// to the provider.
|
|
190
|
-
// It is not opinionated about which nodes are used, so `any` is used here to allow
|
|
191
|
-
// compatibility with both DocNodes and PMNodes.
|
|
3
|
+
export { NodeDataProvider } from './node-data-provider';
|
|
4
|
+
export { prefetchNodeDataProvidersData } from './utils/prefetch-node-data-providers-data';
|
|
@@ -0,0 +1,216 @@
|
|
|
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
|
+
* A Node Data Provider is responsible for fetching and caching data associated with specific ProseMirror nodes.
|
|
29
|
+
* It supports a cache-first-then-network strategy, with initial data potentially provided via SSR.
|
|
30
|
+
*
|
|
31
|
+
* @template Node The specific type of JSONNode this provider supports.
|
|
32
|
+
* @template Data The type of data this provider fetches and manages.
|
|
33
|
+
*/
|
|
34
|
+
export class NodeDataProvider {
|
|
35
|
+
/**
|
|
36
|
+
* A unique name for the provider. Used for identification in SSR.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* A type guard to check if a given JSONNode is supported by this provider.
|
|
41
|
+
* Used to ensure that the provider can handle the node type before attempting to fetch data.
|
|
42
|
+
*
|
|
43
|
+
* @param node The node to check.
|
|
44
|
+
* @returns `true` if the node is of the type supported by this provider, otherwise `false`.
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Generates a unique key for a given node to be used for caching.
|
|
49
|
+
*
|
|
50
|
+
* @param node The node for which to generate a data key.
|
|
51
|
+
* @returns A unique string key for the node's data.
|
|
52
|
+
*/
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Fetches data for a batch of nodes from the network or another asynchronous source.
|
|
56
|
+
*
|
|
57
|
+
* @param nodes An array of nodes for which to fetch data.
|
|
58
|
+
* @returns A promise that resolves to an array of data corresponding to the input nodes.
|
|
59
|
+
*/
|
|
60
|
+
|
|
61
|
+
constructor() {
|
|
62
|
+
this.cacheVersion = 0;
|
|
63
|
+
this.cache = {};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Sets the SSR data for the provider.
|
|
68
|
+
* This pre-populates the cache with data rendered on the server, preventing redundant network requests on the client.
|
|
69
|
+
* Calling this method will invalidate the existing cache.
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* ```
|
|
73
|
+
* const ssrData = window.__SSR_NODE_DATA__ || {};
|
|
74
|
+
* nodeDataProvider.setSSRData(ssrData);
|
|
75
|
+
* ```
|
|
76
|
+
*
|
|
77
|
+
* @param ssrData A map of node data keys to their corresponding data.
|
|
78
|
+
*/
|
|
79
|
+
setSSRData(ssrData = {}) {
|
|
80
|
+
this.cacheVersion++;
|
|
81
|
+
this.cache = Object.entries(ssrData).reduce((acc, [key, data]) => {
|
|
82
|
+
acc[key] = {
|
|
83
|
+
source: 'ssr',
|
|
84
|
+
data
|
|
85
|
+
};
|
|
86
|
+
return acc;
|
|
87
|
+
}, {});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Clears all cached data.
|
|
92
|
+
* This increments the internal cache version, invalidating any pending network requests.
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* ```
|
|
96
|
+
* function useMyNodeDataProvider(contentId: string) {
|
|
97
|
+
* const nodeDataProvider = new MyNodeDataProvider();
|
|
98
|
+
*
|
|
99
|
+
* // Reset the cache when the contentId changes (e.g., when the user navigates to a different page).
|
|
100
|
+
* useEffect(() => {
|
|
101
|
+
* nodeDataProvider.resetCache();
|
|
102
|
+
* }, [contentId]);
|
|
103
|
+
*
|
|
104
|
+
* return nodeDataProvider;
|
|
105
|
+
* }
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
resetCache() {
|
|
109
|
+
this.cacheVersion++;
|
|
110
|
+
this.cache = {};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Fetches data for a given node using a cache-first-then-network strategy.
|
|
115
|
+
*
|
|
116
|
+
* The provided callback may be called multiple times:
|
|
117
|
+
* 1. Immediately with data from the SSR cache, if available.
|
|
118
|
+
* 2. Asynchronously with data fetched from the network.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* ```
|
|
122
|
+
* const nodeDataProvider = new MyNodeDataProvider();
|
|
123
|
+
*
|
|
124
|
+
* nodeDataProvider.getData(node, (data) => {
|
|
125
|
+
* console.log('Node data:', data);
|
|
126
|
+
* });
|
|
127
|
+
* ```
|
|
128
|
+
*
|
|
129
|
+
* @param node The node (or its ProseMirror representation) for which to fetch data.
|
|
130
|
+
* @param callback The function to call when data is available.
|
|
131
|
+
*/
|
|
132
|
+
getData(node, callback) {
|
|
133
|
+
// Move implementation to a separate async method
|
|
134
|
+
// to keep this method synchronous and avoid async/await in the public API.
|
|
135
|
+
void this.getDataAsync(node, callback);
|
|
136
|
+
}
|
|
137
|
+
async getDataAsync(node, callback) {
|
|
138
|
+
const jsonNode = 'toJSON' in node ? node.toJSON() : node;
|
|
139
|
+
if (!this.isNodeSupported(jsonNode)) {
|
|
140
|
+
// eslint-disable-next-line no-console
|
|
141
|
+
console.error(`The ${this.constructor.name} doesn't support Node ${jsonNode.type}.`);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const dataKey = this.nodeDataKey(jsonNode);
|
|
145
|
+
const dataFromCache = this.cache[dataKey];
|
|
146
|
+
if (dataFromCache !== undefined) {
|
|
147
|
+
// If we have the data in the SSR data, we can use it directly
|
|
148
|
+
if (isPromise(dataFromCache.data)) {
|
|
149
|
+
callback(await dataFromCache.data);
|
|
150
|
+
} else {
|
|
151
|
+
callback(dataFromCache.data);
|
|
152
|
+
}
|
|
153
|
+
if (isSSR()) {
|
|
154
|
+
// If we are in SSR, we don't want to fetch the data again, as it is already available in the SSR data
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// If no data is available in the cache or the data is from the network,
|
|
160
|
+
// we need to fetch it from the network.
|
|
161
|
+
if ((dataFromCache === null || dataFromCache === void 0 ? void 0 : dataFromCache.source) !== 'network') {
|
|
162
|
+
// Store the current cache version before making the request,
|
|
163
|
+
// so we can check if the cache has changed while we are waiting for the network response.
|
|
164
|
+
const cacheVersionBeforeRequest = this.cacheVersion;
|
|
165
|
+
const dataPromise = this.fetchNodesData([jsonNode]).then(([value]) => value);
|
|
166
|
+
// Store the promise in the cache to avoid multiple requests for the same data
|
|
167
|
+
this.cache[dataKey] = {
|
|
168
|
+
source: 'network',
|
|
169
|
+
data: dataPromise
|
|
170
|
+
};
|
|
171
|
+
const data = await dataPromise;
|
|
172
|
+
// We need to call the callback with the data with result even if the cache version has changed,
|
|
173
|
+
// so all promises that are waiting for the data can resolve.
|
|
174
|
+
callback(data);
|
|
175
|
+
|
|
176
|
+
// If the cache version has changed, we don't want to use the data from the network
|
|
177
|
+
// because it could be stale data.
|
|
178
|
+
if (cacheVersionBeforeRequest === this.cacheVersion) {
|
|
179
|
+
// Replace promise with the resolved data in the cache
|
|
180
|
+
this.cache[dataKey] = {
|
|
181
|
+
source: 'network',
|
|
182
|
+
data
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Fetches data for a given node and returns it as a Promise.
|
|
190
|
+
* This is a convenience wrapper around the `data` method for use with async/await.
|
|
191
|
+
*
|
|
192
|
+
* Note: This promise resolves with the *first* available data, which could be from the SSR cache or the network.
|
|
193
|
+
* It may not provide the most up-to-date data if a network fetch is in progress.
|
|
194
|
+
*
|
|
195
|
+
* Note: This method is only for migration purposes. Use {@link getData} in new code instead.
|
|
196
|
+
*
|
|
197
|
+
* @private
|
|
198
|
+
* @deprecated Don't use this method, use {@link getData} method instead.
|
|
199
|
+
* This method is only for migration purposes.
|
|
200
|
+
*
|
|
201
|
+
* @param node The node (or its ProseMirror representation) for which to fetch data.
|
|
202
|
+
* @returns A promise that resolves with the node's data.
|
|
203
|
+
*/
|
|
204
|
+
getDataAsPromise_DO_NOT_USE_OUTSIDE_MIGRATIONS(node) {
|
|
205
|
+
return new Promise((resolve, reject) => {
|
|
206
|
+
try {
|
|
207
|
+
return this.getData(node, resolve);
|
|
208
|
+
} catch (error) {
|
|
209
|
+
reject(error);
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
function isPromise(value) {
|
|
215
|
+
return typeof value === 'object' && value !== null && 'then' in value && typeof value.then === 'function';
|
|
216
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
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
|
+
let totalVisitedNodesCount = 0;
|
|
11
|
+
const resultMap = providers.reduce((acc, {
|
|
12
|
+
provider
|
|
13
|
+
}) => {
|
|
14
|
+
acc[provider.name] = {
|
|
15
|
+
provider,
|
|
16
|
+
nodes: []
|
|
17
|
+
};
|
|
18
|
+
return acc;
|
|
19
|
+
}, {});
|
|
20
|
+
|
|
21
|
+
// It doesn't use `filter` function from `@atlaskit/adf-utils/traverse` because it does not support early stopping.
|
|
22
|
+
// We need to stop traversing when we reach the maximum number of nodes to visit to support large documents.
|
|
23
|
+
|
|
24
|
+
const providersToLookup = providers.filter(({
|
|
25
|
+
maxNodesToPrefetch
|
|
26
|
+
}) => maxNodesToPrefetch > 0).map(({
|
|
27
|
+
provider,
|
|
28
|
+
maxNodesToPrefetch
|
|
29
|
+
}) => ({
|
|
30
|
+
provider,
|
|
31
|
+
maxNodesToPrefetch,
|
|
32
|
+
foundNodes: 0
|
|
33
|
+
}));
|
|
34
|
+
const nodesToVisit = [doc];
|
|
35
|
+
let currentIndex = 0;
|
|
36
|
+
while (currentIndex < nodesToVisit.length && providersToLookup.length > 0 && totalVisitedNodesCount < maxNodesToVisit) {
|
|
37
|
+
totalVisitedNodesCount += 1;
|
|
38
|
+
const currentNode = nodesToVisit[currentIndex];
|
|
39
|
+
currentIndex++;
|
|
40
|
+
|
|
41
|
+
// Using reverse loop to avoid issues with array mutation
|
|
42
|
+
for (let i = providersToLookup.length - 1; i >= 0; i--) {
|
|
43
|
+
const providerToFind = providersToLookup[i];
|
|
44
|
+
if (providerToFind.provider.isNodeSupported(currentNode)) {
|
|
45
|
+
resultMap[providerToFind.provider.name].nodes.push(currentNode);
|
|
46
|
+
providerToFind.foundNodes += 1;
|
|
47
|
+
if (providerToFind.foundNodes >= providerToFind.maxNodesToPrefetch) {
|
|
48
|
+
providersToLookup.splice(i, 1);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (currentNode.content) {
|
|
53
|
+
nodesToVisit.push(...currentNode.content.filter(node => node !== undefined));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return Object.values(resultMap);
|
|
57
|
+
}
|