@atlaskit/node-data-provider 2.0.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.
Files changed (60) hide show
  1. package/.eslintrc.js +14 -0
  2. package/CHANGELOG.md +24 -0
  3. package/LICENSE.md +11 -0
  4. package/README.md +48 -0
  5. package/cache/package.json +15 -0
  6. package/content/package.json +15 -0
  7. package/dist/cjs/cache.js +145 -0
  8. package/dist/cjs/consumption/_global-ndp-caches.js +21 -0
  9. package/dist/cjs/consumption/_internal-context.js +77 -0
  10. package/dist/cjs/consumption/_lru-cache.js +44 -0
  11. package/dist/cjs/consumption/content.js +53 -0
  12. package/dist/cjs/get-providers/confluence-page.js +15 -0
  13. package/dist/cjs/index.js +234 -0
  14. package/dist/cjs/internal-types.js +5 -0
  15. package/dist/cjs/plugin-hooks.js +97 -0
  16. package/dist/cjs/providers/emoji.js +54 -0
  17. package/dist/es2019/cache.js +96 -0
  18. package/dist/es2019/consumption/_global-ndp-caches.js +13 -0
  19. package/dist/es2019/consumption/_internal-context.js +71 -0
  20. package/dist/es2019/consumption/_lru-cache.js +28 -0
  21. package/dist/es2019/consumption/content.js +46 -0
  22. package/dist/es2019/get-providers/confluence-page.js +10 -0
  23. package/dist/es2019/index.js +193 -0
  24. package/dist/es2019/internal-types.js +1 -0
  25. package/dist/es2019/plugin-hooks.js +66 -0
  26. package/dist/es2019/providers/emoji.js +26 -0
  27. package/dist/esm/cache.js +141 -0
  28. package/dist/esm/consumption/_global-ndp-caches.js +13 -0
  29. package/dist/esm/consumption/_internal-context.js +71 -0
  30. package/dist/esm/consumption/_lru-cache.js +37 -0
  31. package/dist/esm/consumption/content.js +46 -0
  32. package/dist/esm/get-providers/confluence-page.js +9 -0
  33. package/dist/esm/index.js +230 -0
  34. package/dist/esm/internal-types.js +1 -0
  35. package/dist/esm/plugin-hooks.js +90 -0
  36. package/dist/esm/providers/emoji.js +47 -0
  37. package/dist/types/cache.d.ts +61 -0
  38. package/dist/types/consumption/_global-ndp-caches.d.ts +8 -0
  39. package/dist/types/consumption/_internal-context.d.ts +32 -0
  40. package/dist/types/consumption/_lru-cache.d.ts +7 -0
  41. package/dist/types/consumption/content.d.ts +65 -0
  42. package/dist/types/get-providers/confluence-page.d.ts +6 -0
  43. package/dist/types/index.d.ts +136 -0
  44. package/dist/types/internal-types.d.ts +2 -0
  45. package/dist/types/plugin-hooks.d.ts +32 -0
  46. package/dist/types/providers/emoji.d.ts +10 -0
  47. package/dist/types-ts4.5/cache.d.ts +61 -0
  48. package/dist/types-ts4.5/consumption/_global-ndp-caches.d.ts +8 -0
  49. package/dist/types-ts4.5/consumption/_internal-context.d.ts +32 -0
  50. package/dist/types-ts4.5/consumption/_lru-cache.d.ts +7 -0
  51. package/dist/types-ts4.5/consumption/content.d.ts +65 -0
  52. package/dist/types-ts4.5/get-providers/confluence-page.d.ts +6 -0
  53. package/dist/types-ts4.5/index.d.ts +136 -0
  54. package/dist/types-ts4.5/internal-types.d.ts +2 -0
  55. package/dist/types-ts4.5/plugin-hooks.d.ts +32 -0
  56. package/dist/types-ts4.5/providers/emoji.d.ts +10 -0
  57. package/emoji-provider/package.json +15 -0
  58. package/get-confluence-page-providers/package.json +15 -0
  59. package/package.json +73 -0
  60. package/plugin-hooks/package.json +15 -0
@@ -0,0 +1,234 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.NodeDataProvider = void 0;
8
+ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
9
+ var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
10
+ var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
11
+ var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
12
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
13
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
14
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
15
+ // re exported to avoid type issues
16
+ // this type is only used in jsdoc comments in this file.
17
+ /**
18
+ * This is the base class for creating a node data provider for an editor plugin.
19
+ *
20
+ * ## Usage
21
+ *
22
+ * ### Create a provider
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * class EmojiNodeDataProvider extends NodeDataProvider<
27
+ * { attrs: EmojiAttributes },
28
+ * { resolvedData: string }
29
+ * > {
30
+ * constructor({ existingCache }?: { existingCache: Record<string, { resolvedData: string }> }) {
31
+ * super({ existingCache, nodeName: 'emoji' });
32
+ * }
33
+ * nodeToKey(node: { attrs: EmojiAttributes }): string {
34
+ * return `${node.attrs.shortName}-${node.attrs.text}-${node.attrs.id}`;
35
+ * }
36
+ * resolve(node: { attrs: EmojiAttributes }, _?: { signal: AbortSignal }) {
37
+ * return Promise.resolve({ resolvedData: 'resolved' });
38
+ * }
39
+ * }
40
+ * ```
41
+ *
42
+ * ### Use the provider
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * const emojiNodeDataProvider = new EmojiNodeDataProvider();
47
+ * ```
48
+ *
49
+ * ### Caching
50
+ *
51
+ * @see {@link buildCaches} for more information on building caches.
52
+ *
53
+ * #### Load an existing provider with a cache
54
+ *
55
+ * @example
56
+ * ```
57
+ * await buildCaches({
58
+ * adf: docFromSomewhere,
59
+ * nodeDataProviders: [emojiNodeDataProvider],
60
+ * signal: AbortSignal.timeout(5000),
61
+ * });
62
+ * emojiNodeDataProvider // { 'key': 'value' }
63
+ * ```
64
+ *
65
+ * ### Load an new provider with an existing cache
66
+ *
67
+ * @example
68
+ * ```
69
+ * const provider1 = new ExampleNodeDataProvider();
70
+ * await buildCaches({adf, nodeDataProviders: [provider1]})
71
+ * provider1.cache // { 'key': 'value' }
72
+ *
73
+ * const provider2 = new ExampleNodeDataProvider({existingCache: provider1.cache});
74
+ * ```
75
+ */
76
+ var NodeDataProvider = exports.NodeDataProvider = /*#__PURE__*/function () {
77
+ /**
78
+ * This takes a node and returns a key that can be used to cache the result of the resolve function.
79
+ */
80
+
81
+ /**
82
+ * This returns the information required to render a node.
83
+ *
84
+ * If unresolvable, this method will throw an error.
85
+ *
86
+ * If signal is aborted, this method will return undefined.
87
+ */
88
+
89
+ /**
90
+ * The adf node name this provider is responsible for.
91
+ */
92
+
93
+ function NodeDataProvider(_ref) {
94
+ var _ref$existingCache = _ref.existingCache,
95
+ existingCache = _ref$existingCache === void 0 ? {} : _ref$existingCache,
96
+ nodeName = _ref.nodeName,
97
+ nodeToKey = _ref.nodeToKey,
98
+ resolve = _ref.resolve;
99
+ (0, _classCallCheck2.default)(this, NodeDataProvider);
100
+ /**
101
+ * This is added to ease building types
102
+ */
103
+ // @ts-ignore
104
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
105
+ (0, _defineProperty2.default)(this, "__node", {});
106
+ (0, _defineProperty2.default)(this, "pending", {});
107
+ this.__cache = existingCache;
108
+ this.nodeName = nodeName;
109
+ this.nodeToKey = nodeToKey;
110
+ this.resolve = resolve;
111
+ }
112
+
113
+ /**
114
+ * Updates the providers cache.
115
+ *
116
+ * Useful in scenarios such as SSR where the cache is built on the server and then passed to the client.
117
+ *
118
+ * Avoids the need to provide the cache to the constructor (to allow decoupling creation of node data providers from cache building),
119
+ * and allow for caching to be managed at a group level across multiple providers.
120
+ *
121
+ * This is not expected to be used by consumers, for internal consumption examples;
122
+ * @see {@link buildCaches}
123
+ *
124
+ */
125
+ (0, _createClass2.default)(NodeDataProvider, [{
126
+ key: "updateCache",
127
+ value: function updateCache(cache, options) {
128
+ switch (options.strategy) {
129
+ case 'merge-override':
130
+ this.__cache = _objectSpread(_objectSpread({}, this.__cache), cache);
131
+ return;
132
+ case 'replace':
133
+ this.__cache = cache;
134
+ return;
135
+ }
136
+ }
137
+
138
+ /**
139
+ * This is the cache for the provider.
140
+ */
141
+ }, {
142
+ key: "cache",
143
+ get: function get() {
144
+ return this.__cache;
145
+ }
146
+ }, {
147
+ key: "get",
148
+ value: function get(node, _) {
149
+ var _this = this;
150
+ var key = this.nodeToKey(node);
151
+ var cached = this.cache[key];
152
+ if (cached) {
153
+ return cached;
154
+ }
155
+
156
+ // Get could be called from a variety of sources;
157
+ // - a Node Data Provider
158
+ // - a cache build
159
+ // - something else
160
+ //
161
+ // We want to avoid triggering multiple resolves for the same node -- so we keep track of pending requests
162
+ // and share them across any overlapping gets.
163
+ //
164
+ // When a get is cancelled -- we only want to cancel the shared resolve if all signals are aborted
165
+ // so we keep track of all signals that are not aborted.
166
+
167
+ var originalSignal = (_ === null || _ === void 0 ? void 0 : _.signal) || new AbortController().signal;
168
+ if (!this.pending[key]) {
169
+ var abortController = new AbortController();
170
+ this.pending[key] = {
171
+ resolving: new Promise( /*#__PURE__*/function () {
172
+ var _ref2 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(res, rej) {
173
+ var result;
174
+ return _regenerator.default.wrap(function _callee$(_context) {
175
+ while (1) switch (_context.prev = _context.next) {
176
+ case 0:
177
+ _context.prev = 0;
178
+ _context.next = 3;
179
+ return _this.resolve(node, {
180
+ signal: abortController.signal
181
+ }).catch(function (res) {
182
+ return res(undefined);
183
+ });
184
+ case 3:
185
+ result = _context.sent;
186
+ res(result);
187
+ _context.next = 10;
188
+ break;
189
+ case 7:
190
+ _context.prev = 7;
191
+ _context.t0 = _context["catch"](0);
192
+ res(undefined);
193
+ case 10:
194
+ case "end":
195
+ return _context.stop();
196
+ }
197
+ }, _callee, null, [[0, 7]]);
198
+ }));
199
+ return function (_x, _x2) {
200
+ return _ref2.apply(this, arguments);
201
+ };
202
+ }()),
203
+ abortController: abortController,
204
+ activeSignals: [originalSignal]
205
+ };
206
+ }
207
+ var handleAbort = function handleAbort() {
208
+ _this.pending[key].activeSignals = _this.pending[key].activeSignals.filter(function (activeSignal) {
209
+ return activeSignal !== originalSignal;
210
+ });
211
+ if (_this.pending[key].activeSignals.length === 0) {
212
+ // abort the resolution if all signals are aborted
213
+ _this.pending[key].abortController.abort();
214
+ }
215
+ };
216
+
217
+ // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
218
+ originalSignal === null || originalSignal === void 0 || originalSignal.addEventListener('abort', handleAbort);
219
+ this.pending[key].resolving.then(function (resolvedValue) {
220
+ if (resolvedValue) {
221
+ _this.cache[key] = resolvedValue;
222
+ }
223
+ // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
224
+ originalSignal === null || originalSignal === void 0 || originalSignal.removeEventListener('abort', handleAbort);
225
+ return resolvedValue;
226
+ });
227
+ return this.pending[key].resolving;
228
+ }
229
+ }]);
230
+ return NodeDataProvider;
231
+ }(); // The purpose of this type is to ensure that either a DocNode or a PMNode is passed in
232
+ // to the provider.
233
+ // It is not opinionated about which nodes are used, so `any` is used here to allow
234
+ // compatibility with both DocNodes and PMNodes.
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.useNodeDataProviderGet = useNodeDataProviderGet;
8
+ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
9
+ var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
10
+ var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
11
+ var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
12
+ var _react = require("react");
13
+ /**
14
+ *
15
+ *
16
+ * This hook is intended to simplify accessing data via the one tick providers.
17
+ *
18
+ * ```ts
19
+ * const value = useNodeDataProviderGet(emojiProvider, emojiNode);
20
+ *
21
+ * if (value.state === 'loading') {
22
+ * return <Loading />;
23
+ * }
24
+ * if (value.state === 'failed') {
25
+ * return <Fallback />;
26
+ * }
27
+ * return <Emoji properties=(value.result) />
28
+ * ```
29
+ */
30
+ function useNodeDataProviderGet(options) {
31
+ var getResult = (0, _react.useMemo)(function () {
32
+ return options.provider.get(options.node);
33
+ }, [options.provider, options.node]);
34
+ var _useState = (0, _react.useState)(getResult !== undefined && !isPromise(getResult) ? getResult : undefined),
35
+ _useState2 = (0, _slicedToArray2.default)(_useState, 2),
36
+ resolved = _useState2[0],
37
+ setResolved = _useState2[1];
38
+ (0, _react.useEffect)(function () {
39
+ if (!isPromise(getResult)) {
40
+ return;
41
+ }
42
+ var cancelled = false;
43
+ (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() {
44
+ var _resolved;
45
+ return _regenerator.default.wrap(function _callee$(_context) {
46
+ while (1) switch (_context.prev = _context.next) {
47
+ case 0:
48
+ _context.prev = 0;
49
+ _context.next = 3;
50
+ return getResult;
51
+ case 3:
52
+ _resolved = _context.sent;
53
+ if (!cancelled) {
54
+ if (_resolved === undefined) {
55
+ setResolved('error');
56
+ } else {
57
+ setResolved(_resolved);
58
+ }
59
+ }
60
+ _context.next = 10;
61
+ break;
62
+ case 7:
63
+ _context.prev = 7;
64
+ _context.t0 = _context["catch"](0);
65
+ setResolved('error');
66
+ case 10:
67
+ case "end":
68
+ return _context.stop();
69
+ }
70
+ }, _callee, null, [[0, 7]]);
71
+ }))();
72
+ return function () {
73
+ cancelled = true;
74
+ };
75
+ }, [getResult]);
76
+ if (resolved === undefined) {
77
+ return {
78
+ state: 'loading',
79
+ result: undefined
80
+ };
81
+ }
82
+ if (resolved === 'error') {
83
+ return {
84
+ state: 'failed',
85
+ result: undefined
86
+ };
87
+ }
88
+ return {
89
+ state: 'resolved',
90
+ result: resolved
91
+ };
92
+ }
93
+ function isPromise(obj) {
94
+ return !!obj && ((0, _typeof2.default)(obj) === 'object' || typeof obj === 'function') &&
95
+ // @ts-ignore
96
+ typeof obj.then === 'function';
97
+ }
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.createEmojiNodeDataProvider = createEmojiNodeDataProvider;
8
+ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
9
+ var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
10
+ var _index = require("../index");
11
+ function createEmojiNodeDataProvider(_ref) {
12
+ var emojiProvider = _ref.emojiProvider,
13
+ existingCache = _ref.existingCache;
14
+ var emojiNodeDataProvider = new _index.NodeDataProvider({
15
+ existingCache: existingCache,
16
+ nodeName: 'emoji',
17
+ nodeToKey: function nodeToKey(node) {
18
+ var key = "".concat(node.attrs.id, "-").concat(node.attrs.shortName, "-").concat(node.attrs.text);
19
+ return key;
20
+ },
21
+ resolve: function resolve(node, _resolveOptions) {
22
+ return (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() {
23
+ var emojiDescriptionWithVariations;
24
+ return _regenerator.default.wrap(function _callee$(_context) {
25
+ while (1) switch (_context.prev = _context.next) {
26
+ case 0:
27
+ _context.next = 2;
28
+ return emojiProvider;
29
+ case 2:
30
+ _context.next = 4;
31
+ return _context.sent.fetchByEmojiId({
32
+ id: node.attrs.id,
33
+ shortName: node.attrs.shortName,
34
+ fallback: node.attrs.text
35
+ }, true);
36
+ case 4:
37
+ emojiDescriptionWithVariations = _context.sent;
38
+ if (emojiDescriptionWithVariations) {
39
+ _context.next = 7;
40
+ break;
41
+ }
42
+ throw new Error('Could not resolve emoji');
43
+ case 7:
44
+ return _context.abrupt("return", emojiDescriptionWithVariations);
45
+ case 8:
46
+ case "end":
47
+ return _context.stop();
48
+ }
49
+ }, _callee);
50
+ }))();
51
+ }
52
+ });
53
+ return emojiNodeDataProvider;
54
+ }
@@ -0,0 +1,96 @@
1
+ import { traverse } from '@atlaskit/adf-utils/traverse';
2
+
3
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
4
+
5
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6
+
7
+ /**
8
+ * Builds {@link NodeDataProvider}s caches for a document.
9
+ *
10
+ * It will traverse the document and call the resolve method for each node.
11
+ * When all promises are resolved, NodeDataProviders will have their caches populated.
12
+ *
13
+ * The providers will then be ready for use with an Editor.
14
+ *
15
+ * To limit the time spent building the cache, a signal can be provided to abort the request.
16
+ *
17
+ * ## Usage
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * buildCaches({
22
+ * adf: doc,
23
+ * nodeDataProviders: { emoji: emojiNodeDataProvider, ... },
24
+ * signal: AbortSignal.timeout(5000),
25
+ * });
26
+ * ```
27
+ *
28
+ * ### Using caches
29
+ *
30
+ * To make use of a cache in another provider (ie. for a cache created on the server), you can retrieve the cache
31
+ * from the provider and pass it to the new provider.
32
+ *
33
+ * @example
34
+ * ```tsx
35
+ * // SSR env
36
+ * const ssrProvidersCaches = await buildCaches({adf, nodeDataProviders: { emoji }})
37
+ *
38
+ * // Client env (providersCaches is the cache from the server)
39
+ * <ContentNodeDataProviders ... existingProvidersCache={ssrProvidersCaches} />
40
+ * ```
41
+ *
42
+ * *Note:* On the client - buildCache is not expected to be used directly.
43
+ *
44
+ * @see {@link ContentNodeDataProviders} for expected client usage.
45
+ */
46
+ export async function buildCaches({
47
+ adf,
48
+ nodeDataProviders,
49
+ signal = new AbortController().signal,
50
+ existingProvidersCache
51
+ }) {
52
+ let visitors = {};
53
+ let promises = [];
54
+ for (const _nodeDataProvider of Object.values(nodeDataProviders)) {
55
+ // widen type to avoid typescript errors with the specific node data provider types
56
+ const nodeDataProvider = _nodeDataProvider;
57
+ if (existingProvidersCache && existingProvidersCache[nodeDataProvider.nodeName]) {
58
+ nodeDataProvider.updateCache(existingProvidersCache[nodeDataProvider.nodeName], {
59
+ strategy: 'merge-override'
60
+ });
61
+ }
62
+ visitors[nodeDataProvider.nodeName] = node => {
63
+ const result = nodeDataProvider.get(node, {
64
+ signal
65
+ });
66
+ if (!isPromise(result)) {
67
+ nodeDataProvider.cache[nodeDataProvider.nodeToKey(node)] = result;
68
+ return;
69
+ }
70
+ promises.push(result);
71
+ result.then(resolvedValue => {
72
+ const signalAborted = signal ? signal.aborted : false;
73
+ if (!signalAborted && resolvedValue !== undefined) {
74
+ nodeDataProvider.cache[nodeDataProvider.nodeToKey(node)] = resolvedValue;
75
+ }
76
+ });
77
+ return undefined;
78
+ };
79
+ }
80
+ if (adf) {
81
+ traverse(adf, visitors);
82
+ await Promise.all(promises);
83
+ } else {
84
+ await Promise.resolve();
85
+ }
86
+ const caches = {};
87
+ for (const nodeDataProvider of Object.values(nodeDataProviders)) {
88
+ caches[nodeDataProvider.nodeName] = nodeDataProvider.cache;
89
+ }
90
+ return caches;
91
+ }
92
+ function isPromise(obj) {
93
+ return !!obj && (typeof obj === 'object' || typeof obj === 'function') &&
94
+ // @ts-ignore
95
+ typeof obj.then === 'function';
96
+ }
@@ -0,0 +1,13 @@
1
+ import React from 'react';
2
+ let GlobalNdpCachesContext = /*#__PURE__*/React.createContext({});
3
+ export function useGlobalNdpCachesContext() {
4
+ const globalNdpCachesContextValue = React.useContext(GlobalNdpCachesContext);
5
+ return globalNdpCachesContextValue;
6
+ }
7
+
8
+ // The ndp caches currently use module scope to store the caches. This is not ideal, and a global provider
9
+ // will avoid the need for this.
10
+ // This function is used to reset the global ndp caches context in tests.
11
+ export function _resetGlobalNdpCachesContext() {
12
+ GlobalNdpCachesContext = /*#__PURE__*/React.createContext({});
13
+ }
@@ -0,0 +1,71 @@
1
+ import React from 'react';
2
+ import { buildCaches } from '../cache';
3
+ import { useGlobalNdpCachesContext } from './_global-ndp-caches';
4
+ import { LRUCache } from './_lru-cache';
5
+
6
+ /**
7
+ * The settings for the data providers lru cache,
8
+ * increasing the value will increase the number of data providers that can be stored in the cache.
9
+ */
10
+ const lruCacheSettings = {
11
+ page: 5,
12
+ default: 1
13
+ };
14
+
15
+ /**
16
+ * Sets up nodeview data providers for a content node.
17
+ *
18
+ * This will return the cached node data providers if they exist, otherwise it will call the provided getNodeDataProviders function.
19
+ *
20
+ * Note: Calling this has side effects where caches for the nodeview data providers will continue to be built
21
+ * in the background after this resolves to a set of nodeview data providers that can be used.
22
+ */
23
+ export function useContentNodeDataProvidersSetup(content,
24
+ /**
25
+ * Note: changes to this object will not be reflected in the cache.
26
+ */
27
+ setupOptions) {
28
+ const _globalNdpCachesContextValue = useGlobalNdpCachesContext();
29
+ // Create a cache for the content type if it doesn't exist
30
+ // While this will not result in any existing context consumers getting the updated value.
31
+ // It will ensure that the cache is available for future consumers.
32
+ if (_globalNdpCachesContextValue[content.contentType] === undefined) {
33
+ var _lruCacheSettings$con;
34
+ _globalNdpCachesContextValue[content.contentType] = new LRUCache((_lruCacheSettings$con = lruCacheSettings[content.contentType]) !== null && _lruCacheSettings$con !== void 0 ? _lruCacheSettings$con : lruCacheSettings.default);
35
+ }
36
+ const contentTypeNdpCaches = _globalNdpCachesContextValue[content.contentType];
37
+
38
+ // The node data providers should only be rebuilt if the content changes
39
+ // to avoid unnecessary rebuilding of the cache.
40
+ // useRef is used over useMemo as use memo is not a guarantee that the value will be reused
41
+ // - in development it can be called twice
42
+ // - react have made clear that in future versions useMemo may add features that throw away the cache, and [recommend refs](https://react.dev/reference/react/useMemo#caveats) for this use case.
43
+ const currentContentKey = `${content.contentType}-${content.contentId}`;
44
+ const contentKeyRef = React.useRef();
45
+ const nodeDataProvidersRef = React.useRef();
46
+ if (contentKeyRef.current !== currentContentKey) {
47
+ contentKeyRef.current = currentContentKey;
48
+ const cachedContentNdps = contentTypeNdpCaches === null || contentTypeNdpCaches === void 0 ? void 0 : contentTypeNdpCaches.get(content.contentId);
49
+ let nodeDataProviders = cachedContentNdps || setupOptions.getNodeDataProviders();
50
+
51
+ /**
52
+ * Note: while this will remove old NodeDataProviders from the cache -- these are passed directly to consumers,
53
+ * so removing from the cache will not result in actively used NodeDataProviders being deleted in some way.
54
+ *
55
+ */
56
+ contentTypeNdpCaches.set(content.contentId, nodeDataProviders);
57
+ buildCaches({
58
+ adf: setupOptions.adfToUpdateWith,
59
+ nodeDataProviders: nodeDataProviders,
60
+ existingProvidersCache: setupOptions.existingProvidersCache
61
+ }).then(warmedNodeDataProvidersCache => {
62
+ var _setupOptions$onCache;
63
+ (_setupOptions$onCache = setupOptions.onCacheWarmed) === null || _setupOptions$onCache === void 0 ? void 0 : _setupOptions$onCache.call(setupOptions, {
64
+ warmedNodeDataProvidersCache,
65
+ nodeDataProviders
66
+ });
67
+ });
68
+ nodeDataProvidersRef.current = nodeDataProviders;
69
+ }
70
+ return nodeDataProvidersRef.current;
71
+ }
@@ -0,0 +1,28 @@
1
+ export class LRUCache {
2
+ constructor(capacity) {
3
+ this.capacity = capacity;
4
+ this.cache = new Map();
5
+ }
6
+ get(key) {
7
+ if (!this.cache.has(key)) {
8
+ return undefined;
9
+ }
10
+
11
+ // Move the used key to the end to mark it as most recently used
12
+ const value = this.cache.get(key);
13
+ this.cache.delete(key);
14
+ this.cache.set(key, value);
15
+ return value;
16
+ }
17
+ set(key, value) {
18
+ // Check if the key already exists and delete it to update its position
19
+ if (this.cache.has(key)) {
20
+ this.cache.delete(key);
21
+ } else if (this.cache.size >= this.capacity) {
22
+ // Remove the first (least recently used) cache item if we're at capacity
23
+ const firstKey = this.cache.keys().next().value;
24
+ this.cache.delete(firstKey);
25
+ }
26
+ this.cache.set(key, value);
27
+ }
28
+ }
@@ -0,0 +1,46 @@
1
+ import React from 'react';
2
+ import { _resetGlobalNdpCachesContext } from './_global-ndp-caches';
3
+ import { useContentNodeDataProvidersSetup } from './_internal-context';
4
+ const ContentNodeDataProvidersContext = /*#__PURE__*/React.createContext(undefined);
5
+
6
+ /**
7
+ *
8
+ * @example
9
+ * ```tsx
10
+ * <ContentNodeDataProviders
11
+ * contentType="page" contentId="9001"
12
+ * adf={doc}
13
+ * placeholder={<Spinner />}
14
+ * existingProvidersCache={ssrProvidersCache}
15
+ * getNodeDataProviders={getPageNodeDataProviders}
16
+ * onCacheWarmed={trackCacheWarmed}
17
+ * >
18
+ * <Editor />
19
+ * </ContentNodeDataProviders>
20
+ * ```
21
+ */
22
+ export function ContentNodeDataProviders(props) {
23
+ const contentNodeDataProviders = useContentNodeDataProvidersSetup({
24
+ contentType: props.contentType,
25
+ contentId: props.contentId
26
+ }, {
27
+ adfToUpdateWith: props.adf,
28
+ existingProvidersCache: props.existingProvidersCache,
29
+ getNodeDataProviders: props.getNodeDataProviders,
30
+ onCacheWarmed: props.onCacheWarmed
31
+ });
32
+ return /*#__PURE__*/React.createElement(ContentNodeDataProvidersContext.Provider, {
33
+ value: contentNodeDataProviders
34
+ }, props.children);
35
+ }
36
+ export function useContentNodeDataProviders() {
37
+ const contentNodeDataProvidersContext = React.useContext(ContentNodeDataProvidersContext);
38
+ return contentNodeDataProvidersContext;
39
+ }
40
+ export {
41
+ /**
42
+ * Exported for testing purposes only.
43
+ *
44
+ * This API will change.
45
+ */
46
+ _resetGlobalNdpCachesContext as __testOnly_resetGlobalNdpCachesContext };
@@ -0,0 +1,10 @@
1
+ import { createEmojiNodeDataProvider } from '../providers/emoji';
2
+ export function getConfluencePageProviders({
3
+ emojiProvider
4
+ }) {
5
+ return {
6
+ emoji: createEmojiNodeDataProvider({
7
+ emojiProvider
8
+ })
9
+ };
10
+ }