@atlaskit/editor-plugin-autocomplete 3.3.0 → 3.4.1

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.
@@ -1,4 +1,8 @@
1
1
  import _defineProperty from "@babel/runtime/helpers/defineProperty";
2
+ import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
3
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
4
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
5
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
2
6
  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; }
3
7
  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) { _defineProperty(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; }
4
8
  import { ACTION, ACTION_SUBJECT, EVENT_TYPE } from '@atlaskit/editor-common/analytics';
@@ -7,12 +11,26 @@ import { SafePlugin } from '@atlaskit/editor-common/safe-plugin';
7
11
  import { keydownHandler } from '@atlaskit/editor-prosemirror/keymap';
8
12
  import { PluginKey } from '@atlaskit/editor-prosemirror/state';
9
13
  import { DecorationSet } from '@atlaskit/editor-prosemirror/view';
14
+ import { isAutocompleteDebugEnabled } from './debug-mode';
10
15
  import { createGhostTextDecorationSet } from './ghost-text-decoration';
11
16
  import { createLocalSlowLaneClient } from './local-slow-lane-client';
12
17
  import { createSlowLaneClient, setDefaultSlowLaneClient, isWordBoundary } from './slow-lane-client';
13
18
  import { predict, loadDefaultVocabulary, loadVectorsAsync, incrementSessionFreq, ingestDocumentPage } from './text-predictor';
14
19
  export var autocompletePluginKey = new PluginKey('autocomplete');
15
20
  var DEBOUNCE_MS = 150;
21
+ var NETWORK_SLOW_LANE_DEBOUNCE_MS = 300;
22
+ var LOCAL_SLOW_LANE_DEBOUNCE_MS = 100;
23
+ var CONTEXT_REFRESH_THROTTLE_MS = 1000;
24
+ // Caps the dedup Set so long editing sessions don't retain every distinct
25
+ // version of the (potentially hundreds-of-KB) page content for the plugin's
26
+ // lifetime. Eviction is FIFO; a re-ingest of an evicted text is harmless.
27
+ var MAX_INGESTED_CONTEXT_TEXTS = 50;
28
+ // Caps how many times the word-boundary path will retry getContext() while the
29
+ // parent comment is still missing. Combined with the 1s throttle this gives a
30
+ // ~5s window to cover a still-loading comment thread, then stops permanently so
31
+ // non-comment editors (where parentCommentContent never arrives) don't refetch
32
+ // on every word boundary for the plugin's lifetime.
33
+ var MAX_CONTEXT_REFRESH_ATTEMPTS = 5;
16
34
  var hasDestroy = function hasDestroy(client) {
17
35
  return 'destroy' in client && typeof client.destroy === 'function';
18
36
  };
@@ -177,6 +195,12 @@ export var createAutocompletePlugin = function createAutocompletePlugin(options,
177
195
  var debounceTimer = null;
178
196
  var hasIngestedPage = false;
179
197
  var resolvedContext;
198
+ /**
199
+ * Kept in sync with the live EditorView so the async getContext() promise
200
+ * can re-trigger a slow-lane update the moment context arrives, even if the
201
+ * user has already typed several words before the promise resolved.
202
+ */
203
+ var currentView = null;
180
204
  /**
181
205
  * Set after accepting a suggestion so the next doc-change update
182
206
  * skips scheduling a new prediction for the just-inserted text.
@@ -192,6 +216,18 @@ export var createAutocompletePlugin = function createAutocompletePlugin(options,
192
216
  var dismissedContext = null;
193
217
  var lastSuggestionTypedLength = 0;
194
218
  var lastSuggestionLength = 0;
219
+
220
+ /**
221
+ * cold → no slow-lane vector received yet; frequency-only trie scoring
222
+ * server → server slow-lane API returned the context vector
223
+ * localLlm → on-device WebGPU/MLC model returned the context vector
224
+ */
225
+ var getCompletionSource = function getCompletionSource() {
226
+ if (!slowLaneClient.getContextVector()) {
227
+ return 'cold';
228
+ }
229
+ return options !== null && options !== void 0 && options.useLocalModel ? 'localLlm' : 'server';
230
+ };
195
231
  var fireSuggestionDismissedAnalytics = function fireSuggestionDismissedAnalytics(reason) {
196
232
  var _api$analytics;
197
233
  api === null || api === void 0 || (_api$analytics = api.analytics) === null || _api$analytics === void 0 || _api$analytics.actions.fireAnalyticsEvent({
@@ -199,6 +235,7 @@ export var createAutocompletePlugin = function createAutocompletePlugin(options,
199
235
  actionSubject: ACTION_SUBJECT.CONTEXTUAL_TYPEAHEAD,
200
236
  eventType: EVENT_TYPE.TRACK,
201
237
  attributes: {
238
+ completionSource: getCompletionSource(),
202
239
  reason: reason
203
240
  }
204
241
  });
@@ -213,6 +250,7 @@ export var createAutocompletePlugin = function createAutocompletePlugin(options,
213
250
  actionSubject: ACTION_SUBJECT.CONTEXTUAL_TYPEAHEAD,
214
251
  eventType: EVENT_TYPE.TRACK,
215
252
  attributes: {
253
+ completionSource: getCompletionSource(),
216
254
  suggestionLength: suggestionLength,
217
255
  typedLength: typedLength,
218
256
  kssDelta: kssDelta
@@ -220,12 +258,125 @@ export var createAutocompletePlugin = function createAutocompletePlugin(options,
220
258
  });
221
259
  };
222
260
  var slowLaneClient = options !== null && options !== void 0 && options.useLocalModel ? createLocalSlowLaneClient({
223
- debounceMs: 300
261
+ debounceMs: LOCAL_SLOW_LANE_DEBOUNCE_MS
224
262
  }) : createSlowLaneClient({
225
263
  baseUrl: '',
226
- debounceMs: 300
264
+ debounceMs: NETWORK_SLOW_LANE_DEBOUNCE_MS
227
265
  });
228
266
  setDefaultSlowLaneClient(slowLaneClient);
267
+ var contextRequestInFlight = false;
268
+ var lastContextRefreshAt = 0;
269
+ // Bounds the word-boundary retry loop so it terminates even when the editor is
270
+ // not in a comment thread (parentCommentContent never resolves).
271
+ var wordBoundaryRefreshAttempts = 0;
272
+ // Set when the plugin is torn down so in-flight getContext() resolutions don't
273
+ // mutate the global text-predictor state after destruction.
274
+ var destroyed = false;
275
+ var ingestedContextTexts = new Set();
276
+ var logContextResolved = function logContextResolved(source, context) {
277
+ var _context$parentCommen, _context$siblingComme4, _context$siblingComme5;
278
+ if (!isAutocompleteDebugEnabled()) {
279
+ return;
280
+ }
281
+
282
+ // eslint-disable-next-line no-console
283
+ console.log('%c[Autocomplete] %cgetContext resolved', 'color: #00b8d9; font-weight: bold;', 'color: inherit;', {
284
+ source: source,
285
+ hasParentComment: !!(context !== null && context !== void 0 && context.parentCommentContent),
286
+ parentCommentPreview: context === null || context === void 0 || (_context$parentCommen = context.parentCommentContent) === null || _context$parentCommen === void 0 ? void 0 : _context$parentCommen.slice(0, 80),
287
+ siblingCount: (_context$siblingComme4 = context === null || context === void 0 || (_context$siblingComme5 = context.siblingCommentsContents) === null || _context$siblingComme5 === void 0 ? void 0 : _context$siblingComme5.length) !== null && _context$siblingComme4 !== void 0 ? _context$siblingComme4 : 0,
288
+ hasFullPage: !!(context !== null && context !== void 0 && context.fullPageContent)
289
+ });
290
+ };
291
+ var applyContext = function applyContext(context) {
292
+ var _context$siblingComme6;
293
+ // Merge rather than replace: the word-boundary retry may resolve only a
294
+ // late-arriving field (e.g. parentCommentContent) without re-sending
295
+ // fullPageContent, so replacing would drop previously resolved context.
296
+ // Strip undefined values first so a field explicitly set to undefined by
297
+ // getContext doesn't overwrite a previously resolved value.
298
+ var definedContext = Object.fromEntries(Object.entries(context).filter(function (_ref) {
299
+ var _ref2 = _slicedToArray(_ref, 2),
300
+ value = _ref2[1];
301
+ return value !== undefined;
302
+ }));
303
+ resolvedContext = _objectSpread(_objectSpread({}, resolvedContext), definedContext);
304
+ var ingestContextText = function ingestContextText(text) {
305
+ if (!text || ingestedContextTexts.has(text)) {
306
+ return;
307
+ }
308
+ ingestedContextTexts.add(text);
309
+ // Evict oldest entries (Set preserves insertion order) to bound memory.
310
+ while (ingestedContextTexts.size > MAX_INGESTED_CONTEXT_TEXTS) {
311
+ var oldest = ingestedContextTexts.values().next().value;
312
+ if (oldest === undefined) {
313
+ break;
314
+ }
315
+ ingestedContextTexts.delete(oldest);
316
+ }
317
+ ingestDocumentPage(text);
318
+ };
319
+ ingestContextText(context.fullPageContent);
320
+ ingestContextText(context.parentCommentContent);
321
+ var _iterator = _createForOfIteratorHelper((_context$siblingComme6 = context.siblingCommentsContents) !== null && _context$siblingComme6 !== void 0 ? _context$siblingComme6 : []),
322
+ _step;
323
+ try {
324
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
325
+ var siblingCommentContent = _step.value;
326
+ ingestContextText(siblingCommentContent);
327
+ }
328
+
329
+ // Context arrived after word boundaries may already have fired. Re-send
330
+ // slow-lane context immediately so the next inference includes the thread.
331
+ } catch (err) {
332
+ _iterator.e(err);
333
+ } finally {
334
+ _iterator.f();
335
+ }
336
+ if (currentView) {
337
+ slowLaneClient.updateContext(buildSlowLaneText(currentView.state.doc.textContent, resolvedContext));
338
+ }
339
+ };
340
+
341
+ /**
342
+ * Returns true when a fetch was actually started, false when it was skipped
343
+ * (no getContext, a request already in flight, or throttled). Callers that
344
+ * track a retry budget should only count attempts where this returns true.
345
+ */
346
+ var refreshContext = function refreshContext(_ref3) {
347
+ var source = _ref3.source,
348
+ _ref3$allowThrottle = _ref3.allowThrottle,
349
+ allowThrottle = _ref3$allowThrottle === void 0 ? true : _ref3$allowThrottle;
350
+ if (!(options !== null && options !== void 0 && options.getContext) || contextRequestInFlight) {
351
+ return false;
352
+ }
353
+ var now = Date.now();
354
+ if (allowThrottle && now - lastContextRefreshAt < CONTEXT_REFRESH_THROTTLE_MS) {
355
+ return false;
356
+ }
357
+ contextRequestInFlight = true;
358
+ lastContextRefreshAt = now;
359
+ options.getContext().then(function (context) {
360
+ // Bail if the plugin was destroyed while the fetch was in flight —
361
+ // applyContext mutates global text-predictor state we must not touch
362
+ // after teardown.
363
+ if (destroyed) {
364
+ return;
365
+ }
366
+ logContextResolved(source, context);
367
+ if (!context) {
368
+ return;
369
+ }
370
+ applyContext(context);
371
+ }).catch(function (error) {
372
+ logException(error, {
373
+ location: 'editor-plugin-autocomplete/getContext'
374
+ });
375
+ }).finally(function () {
376
+ contextRequestInFlight = false;
377
+ });
378
+ return true;
379
+ };
229
380
 
230
381
  /**
231
382
  * Schedule a prediction after a short debounce.
@@ -266,7 +417,10 @@ export var createAutocompletePlugin = function createAutocompletePlugin(options,
266
417
  api === null || api === void 0 || (_api$analytics3 = api.analytics) === null || _api$analytics3 === void 0 || _api$analytics3.actions.fireAnalyticsEvent({
267
418
  action: ACTION.SUGGESTION_VIEWED,
268
419
  actionSubject: ACTION_SUBJECT.CONTEXTUAL_TYPEAHEAD,
269
- eventType: EVENT_TYPE.TRACK
420
+ eventType: EVENT_TYPE.TRACK,
421
+ attributes: {
422
+ completionSource: getCompletionSource()
423
+ }
270
424
  });
271
425
  }
272
426
  }
@@ -397,26 +551,10 @@ export var createAutocompletePlugin = function createAutocompletePlugin(options,
397
551
  });
398
552
  if (!hasIngestedPage) {
399
553
  hasIngestedPage = true;
400
- if (options !== null && options !== void 0 && options.getContext) {
401
- options.getContext().then(function (context) {
402
- var _context$siblingComme4;
403
- if (!context) {
404
- return;
405
- }
406
- resolvedContext = context;
407
- if (context.fullPageContent) {
408
- ingestDocumentPage(context.fullPageContent);
409
- }
410
- if (context.parentCommentContent) {
411
- ingestDocumentPage(context.parentCommentContent);
412
- }
413
- (_context$siblingComme4 = context.siblingCommentsContents) === null || _context$siblingComme4 === void 0 || _context$siblingComme4.forEach(ingestDocumentPage);
414
- }).catch(function (error) {
415
- logException(error, {
416
- location: 'editor-plugin-autocomplete/getContext'
417
- });
418
- });
419
- }
554
+ refreshContext({
555
+ source: 'focus',
556
+ allowThrottle: false
557
+ });
420
558
  }
421
559
  return false;
422
560
  }
@@ -425,6 +563,7 @@ export var createAutocompletePlugin = function createAutocompletePlugin(options,
425
563
  view: function view() {
426
564
  return {
427
565
  update: function update(view, prevState) {
566
+ currentView = view;
428
567
  if (!prevState.doc.eq(view.state.doc)) {
429
568
  if (justAccepted) {
430
569
  justAccepted = false;
@@ -440,18 +579,36 @@ export var createAutocompletePlugin = function createAutocompletePlugin(options,
440
579
  maybeUpdateSessionFrequency(view, prevState);
441
580
  var textBefore = getTextBeforeCursor(view.state);
442
581
  if (isWordBoundary(textBefore)) {
582
+ var _resolvedContext;
443
583
  slowLaneClient.updateContext(buildSlowLaneText(view.state.doc.textContent, resolvedContext));
584
+
585
+ // Context may not have resolved on first focus (e.g. comment
586
+ // thread still loading). Retry on word boundaries until we have
587
+ // the parent comment, throttled so we don't refetch constantly
588
+ // and capped so non-comment editors stop retrying entirely.
589
+ if (!((_resolvedContext = resolvedContext) !== null && _resolvedContext !== void 0 && _resolvedContext.parentCommentContent) && wordBoundaryRefreshAttempts < MAX_CONTEXT_REFRESH_ATTEMPTS) {
590
+ // Only count the attempt when a fetch actually started, so an
591
+ // in-flight or throttled no-op doesn't burn the retry budget.
592
+ if (refreshContext({
593
+ source: 'word-boundary'
594
+ })) {
595
+ wordBoundaryRefreshAttempts++;
596
+ }
597
+ }
444
598
  }
445
599
  schedulePrediction(view);
446
600
  }
447
601
  },
448
602
  destroy: function destroy() {
603
+ destroyed = true;
604
+ currentView = null;
449
605
  if (debounceTimer) {
450
606
  clearTimeout(debounceTimer);
451
607
  }
452
608
  if (hasDestroy(slowLaneClient)) {
453
609
  slowLaneClient.destroy();
454
610
  }
611
+ ingestedContextTexts.clear();
455
612
  setDefaultSlowLaneClient(null);
456
613
  }
457
614
  };
@@ -612,6 +612,14 @@ export var createLocalSlowLaneClient = function createLocalSlowLaneClient() {
612
612
  var lastRequestedText = '';
613
613
  var requestCounter = 0;
614
614
  var latestRequestId = -1;
615
+ var inferenceInFlight = false;
616
+ var activeInferenceText = null;
617
+ // The requestId of the inference currently in flight. Tracked so the
618
+ // in-flight dedup path can restore `latestRequestId` to it — otherwise an
619
+ // intermediate keystroke that bumped `latestRequestId` would cause the
620
+ // in-flight (still-current) result to be discarded as stale.
621
+ var activeInferenceRequestId = -1;
622
+ var pendingInference = null;
615
623
  var ready = false;
616
624
  var destroyed = false;
617
625
  var initFailed = false;
@@ -890,7 +898,7 @@ export var createLocalSlowLaneClient = function createLocalSlowLaneClient() {
890
898
  case 5:
891
899
  _context3.prev = 5;
892
900
  _t2 = _context3["catch"](2);
893
- if (!(requestId < latestRequestId)) {
901
+ if (!(requestId < latestRequestId || destroyed)) {
894
902
  _context3.next = 6;
895
903
  break;
896
904
  }
@@ -921,10 +929,48 @@ export var createLocalSlowLaneClient = function createLocalSlowLaneClient() {
921
929
 
922
930
  // ── Context update (debounced) ─────────────────────────────────────────
923
931
 
932
+ var _startInference = function startInference(text, requestId) {
933
+ // Self-contained guard: never start a new inference cycle after teardown,
934
+ // regardless of caller discipline.
935
+ if (destroyed) {
936
+ return;
937
+ }
938
+ inferenceInFlight = true;
939
+ activeInferenceText = text;
940
+ activeInferenceRequestId = requestId;
941
+ void ensureEngineInitialized().then(function () {
942
+ return runInference(text, requestId);
943
+ }).catch(function () {}).finally(function () {
944
+ inferenceInFlight = false;
945
+ activeInferenceText = null;
946
+ activeInferenceRequestId = -1;
947
+ var next = pendingInference;
948
+ pendingInference = null;
949
+ if (next && !destroyed) {
950
+ _startInference(next.text, next.requestId);
951
+ }
952
+ });
953
+ };
924
954
  var doUpdateContext = function doUpdateContext(text) {
955
+ var _pendingInference;
925
956
  if (destroyed || !text || text.trim().length === 0) {
926
957
  return;
927
958
  }
959
+ if (inferenceInFlight && text === activeInferenceText) {
960
+ // The latest desired text already matches the in-flight inference, so
961
+ // re-running it would be wasted work. But an intermediate keystroke may
962
+ // have bumped `latestRequestId` past the in-flight request (and then been
963
+ // coalesced away), which would cause runInference to discard the
964
+ // still-current result as stale. Pin `latestRequestId` back to the active
965
+ // request so its result is accepted, and drop any now-superseded pending
966
+ // request.
967
+ latestRequestId = activeInferenceRequestId;
968
+ pendingInference = null;
969
+ return;
970
+ }
971
+ if (inferenceInFlight && ((_pendingInference = pendingInference) === null || _pendingInference === void 0 ? void 0 : _pendingInference.text) === text) {
972
+ return;
973
+ }
928
974
  var requestId = ++requestCounter;
929
975
  latestRequestId = requestId;
930
976
  if (isAutocompleteDebugEnabled()) {
@@ -938,14 +984,27 @@ export var createLocalSlowLaneClient = function createLocalSlowLaneClient() {
938
984
  // eslint-disable-next-line no-console
939
985
  console.groupEnd();
940
986
  }
941
- void ensureEngineInitialized().then(function () {
942
- return runInference(text, requestId);
943
- }).catch(function () {});
987
+ if (inferenceInFlight) {
988
+ pendingInference = {
989
+ text: text,
990
+ requestId: requestId
991
+ };
992
+ return;
993
+ }
994
+ _startInference(text, requestId);
944
995
  };
945
996
  var updateContextDebounced = function updateContextDebounced(text) {
946
997
  if (debounceTimer) {
947
998
  clearTimeout(debounceTimer);
948
999
  }
1000
+ if (inferenceInFlight) {
1001
+ pendingInference = null;
1002
+ if (text === activeInferenceText) {
1003
+ latestRequestId = activeInferenceRequestId;
1004
+ lastRequestedText = text;
1005
+ return;
1006
+ }
1007
+ }
949
1008
  lastRequestedText = text;
950
1009
  debounceTimer = setTimeout(function () {
951
1010
  debounceTimer = null;
@@ -984,6 +1043,10 @@ export var createLocalSlowLaneClient = function createLocalSlowLaneClient() {
984
1043
  unloadEngine(engineToUnload);
985
1044
  }
986
1045
  engineInitPromise = null;
1046
+ inferenceInFlight = false;
1047
+ activeInferenceText = null;
1048
+ activeInferenceRequestId = -1;
1049
+ pendingInference = null;
987
1050
  storedContextVector = null;
988
1051
  storedLmLogits = null;
989
1052
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atlaskit/editor-plugin-autocomplete",
3
- "version": "3.3.0",
3
+ "version": "3.4.1",
4
4
  "description": "Client-side text autocomplete plugin for @atlaskit/editor-core",
5
5
  "author": "Atlassian Pty Ltd",
6
6
  "license": "Apache-2.0",
@@ -35,7 +35,7 @@
35
35
  "wink-nlp": "^2.4.0"
36
36
  },
37
37
  "peerDependencies": {
38
- "@atlaskit/editor-common": "^115.6.0",
38
+ "@atlaskit/editor-common": "^115.8.0",
39
39
  "@atlaskit/editor-plugin-analytics": "^11.0.0",
40
40
  "react": "^18.2.0"
41
41
  },