mentionize 0.0.4 → 0.0.6

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/dist/cjs/index.js CHANGED
@@ -1,939 +1,51 @@
1
- var __create = Object.create;
2
- var __getProtoOf = Object.getPrototypeOf;
3
1
  var __defProp = Object.defineProperty;
4
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __toESM = (mod, isNodeMode, target) => {
8
- target = mod != null ? __create(__getProtoOf(mod)) : {};
9
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
- for (let key of __getOwnPropNames(mod))
11
- if (!__hasOwnProp.call(to, key))
12
- __defProp(to, key, {
13
- get: () => mod[key],
14
- enumerable: true
15
- });
16
- return to;
17
- };
18
- var __moduleCache = /* @__PURE__ */ new WeakMap;
5
+ function __accessProp(key) {
6
+ return this[key];
7
+ }
19
8
  var __toCommonJS = (from) => {
20
- var entry = __moduleCache.get(from), desc;
9
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
21
10
  if (entry)
22
11
  return entry;
23
12
  entry = __defProp({}, "__esModule", { value: true });
24
- if (from && typeof from === "object" || typeof from === "function")
25
- __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
26
- get: () => from[key],
27
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
28
- }));
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (var key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(entry, key))
16
+ __defProp(entry, key, {
17
+ get: __accessProp.bind(from, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
29
21
  __moduleCache.set(from, entry);
30
22
  return entry;
31
23
  };
24
+ var __moduleCache;
25
+ var __returnValue = (v) => v;
26
+ function __exportSetter(name, newValue) {
27
+ this[name] = __returnValue.bind(null, newValue);
28
+ }
32
29
  var __export = (target, all) => {
33
30
  for (var name in all)
34
31
  __defProp(target, name, {
35
32
  get: all[name],
36
33
  enumerable: true,
37
34
  configurable: true,
38
- set: (newValue) => all[name] = () => newValue
35
+ set: __exportSetter.bind(all, name)
39
36
  });
40
37
  };
41
38
 
42
39
  // src/index.ts
43
40
  var exports_src = {};
44
41
  __export(exports_src, {
45
- useMentionEngine: () => useMentionEngine,
46
- useCaretPosition: () => useCaretPosition,
47
- MentionInput: () => MentionInput,
48
- MentionHighlighter: () => MentionHighlighter,
49
- MentionDropdown: () => MentionDropdown
42
+ useMentionEngine: () => import_useMentionEngine.useMentionEngine,
43
+ useCaretPosition: () => import_useCaretPosition.useCaretPosition,
44
+ MentionInput: () => import_MentionInput.MentionInput,
45
+ MentionHighlighter: () => import_MentionHighlighter.MentionHighlighter,
46
+ MentionDropdown: () => import_MentionDropdown.MentionDropdown
50
47
  });
51
48
  module.exports = __toCommonJS(exports_src);
52
49
 
53
- // src/MentionInput.tsx
54
- var import_react5 = require("react");
55
-
56
- // src/MentionDropdown.tsx
57
- var import_react = require("react");
58
- var jsx_dev_runtime = require("react/jsx-dev-runtime");
59
- var MentionDropdown = ({
60
- items,
61
- trigger,
62
- highlightedIndex,
63
- onHighlight,
64
- onSelect,
65
- onLoadMore,
66
- loading,
67
- loadingContent,
68
- position,
69
- width,
70
- className
71
- }) => {
72
- const listRef = import_react.useRef(null);
73
- const sentinelRef = import_react.useRef(null);
74
- import_react.useEffect(() => {
75
- if (!onLoadMore || !sentinelRef.current)
76
- return;
77
- const sentinel = sentinelRef.current;
78
- const observer = new IntersectionObserver((entries) => {
79
- if (entries[0]?.isIntersecting) {
80
- onLoadMore();
81
- }
82
- }, { root: listRef.current, threshold: 0.1 });
83
- observer.observe(sentinel);
84
- return () => observer.disconnect();
85
- }, [onLoadMore]);
86
- import_react.useEffect(() => {
87
- const container = listRef.current;
88
- if (!container)
89
- return;
90
- const highlighted = container.querySelector(`[data-mentionize-option-index="${highlightedIndex}"]`);
91
- if (highlighted) {
92
- highlighted.scrollIntoView({ block: "nearest" });
93
- }
94
- }, [highlightedIndex]);
95
- const maxHeight = 240;
96
- const gap = 4;
97
- const spaceBelow = window.innerHeight - position.top - gap;
98
- const flipAbove = spaceBelow < maxHeight && position.top > maxHeight;
99
- const style = {
100
- position: "fixed",
101
- width,
102
- maxHeight,
103
- overflowY: "auto",
104
- zIndex: 50,
105
- ...flipAbove ? { bottom: window.innerHeight - position.top + gap, left: position.left } : { top: position.top + gap, left: position.left }
106
- };
107
- const handleMouseDown = import_react.useCallback((e) => {
108
- e.preventDefault();
109
- }, []);
110
- if (!items.length && !loading)
111
- return null;
112
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV("div", {
113
- ref: listRef,
114
- role: "listbox",
115
- className,
116
- style,
117
- "data-mentionize-dropdown": "",
118
- onMouseDown: handleMouseDown,
119
- children: [
120
- items.map((item, i) => {
121
- const isHighlighted = i === highlightedIndex;
122
- const optCls = typeof trigger.optionClassName === "function" ? trigger.optionClassName(item) : trigger.optionClassName;
123
- if (trigger.renderOption) {
124
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV("div", {
125
- role: "option",
126
- "aria-selected": isHighlighted,
127
- className: optCls,
128
- "data-mentionize-option-index": i,
129
- "data-mentionize-option-highlighted": isHighlighted || undefined,
130
- onMouseEnter: () => onHighlight(i),
131
- onClick: () => onSelect(item),
132
- children: trigger.renderOption(item, isHighlighted)
133
- }, i, false, undefined, this);
134
- }
135
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV("div", {
136
- role: "option",
137
- "aria-selected": isHighlighted,
138
- className: optCls,
139
- "data-mentionize-option-index": i,
140
- "data-mentionize-option": "",
141
- "data-mentionize-option-highlighted": isHighlighted || undefined,
142
- onMouseEnter: () => onHighlight(i),
143
- onClick: () => onSelect(item),
144
- children: trigger.displayText(item)
145
- }, i, false, undefined, this);
146
- }),
147
- loading && /* @__PURE__ */ jsx_dev_runtime.jsxDEV("div", {
148
- "data-mentionize-loading": "",
149
- children: loadingContent ?? "Loading..."
150
- }, undefined, false, undefined, this),
151
- onLoadMore && !loading && /* @__PURE__ */ jsx_dev_runtime.jsxDEV("div", {
152
- ref: sentinelRef,
153
- style: { height: 1 },
154
- "aria-hidden": true
155
- }, undefined, false, undefined, this)
156
- ]
157
- }, undefined, true, undefined, this);
158
- };
159
-
160
- // src/MentionHighlighter.tsx
161
- var import_react2 = __toESM(require("react"));
162
- function textToNodes(text) {
163
- const parts = text.split(`
164
- `);
165
- const nodes = [];
166
- for (let i = 0;i < parts.length; i++) {
167
- if (i > 0)
168
- nodes.push(import_react2.default.createElement("br", { key: `br-${i}` }));
169
- if (parts[i])
170
- nodes.push(parts[i]);
171
- }
172
- return nodes;
173
- }
174
- var MentionHighlighter = ({
175
- visible,
176
- mentions,
177
- triggers,
178
- textareaRef,
179
- getItemForMention,
180
- className,
181
- style
182
- }) => {
183
- const ref = import_react2.useRef(null);
184
- import_react2.useEffect(() => {
185
- const textarea = textareaRef.current;
186
- const highlighter = ref.current;
187
- if (!textarea || !highlighter)
188
- return;
189
- const onScroll = () => {
190
- highlighter.scrollTop = textarea.scrollTop;
191
- highlighter.scrollLeft = textarea.scrollLeft;
192
- };
193
- textarea.addEventListener("scroll", onScroll);
194
- return () => textarea.removeEventListener("scroll", onScroll);
195
- }, [textareaRef]);
196
- const children = import_react2.useMemo(() => {
197
- const sorted = mentions.slice().sort((a, b) => a.start - b.start);
198
- if (!sorted.length)
199
- return textToNodes(visible);
200
- const triggerMap = new Map;
201
- for (const t of triggers) {
202
- triggerMap.set(t.trigger, t);
203
- }
204
- const nodes = [];
205
- let last = 0;
206
- for (let i = 0;i < sorted.length; i++) {
207
- const m = sorted[i];
208
- if (last < m.start) {
209
- nodes.push(...textToNodes(visible.slice(last, m.start)));
210
- }
211
- const mentionText = visible.slice(m.start, m.end);
212
- const t = triggerMap.get(m.trigger);
213
- let cls = "mentionize-mention";
214
- if (t) {
215
- if (typeof t.mentionClassName === "function") {
216
- const item = getItemForMention?.(m.trigger, m.key) ?? null;
217
- cls = t.mentionClassName({
218
- key: m.key,
219
- displayText: m.displayText,
220
- trigger: m.trigger,
221
- item
222
- });
223
- } else if (t.mentionClassName) {
224
- cls = t.mentionClassName;
225
- }
226
- }
227
- nodes.push(import_react2.default.createElement("span", {
228
- key: `mention-${i}`,
229
- className: cls,
230
- "data-mentionize-trigger": m.trigger,
231
- "data-mentionize-key": m.key
232
- }, mentionText));
233
- last = m.end;
234
- }
235
- if (last < visible.length) {
236
- nodes.push(...textToNodes(visible.slice(last)));
237
- }
238
- return nodes;
239
- }, [visible, mentions, triggers, getItemForMention]);
240
- import_react2.useLayoutEffect(() => {
241
- const el = ref.current;
242
- if (!el)
243
- return;
244
- const spans = el.querySelectorAll("[data-mentionize-trigger]");
245
- for (let i = 0;i < spans.length; i++) {
246
- const span = spans[i];
247
- span.style.marginLeft = "";
248
- span.style.marginRight = "";
249
- const cs = getComputedStyle(span);
250
- const extraLeft = parseFloat(cs.paddingLeft) + parseFloat(cs.borderLeftWidth) + parseFloat(cs.marginLeft);
251
- const extraRight = parseFloat(cs.paddingRight) + parseFloat(cs.borderRightWidth) + parseFloat(cs.marginRight);
252
- if (extraLeft)
253
- span.style.marginLeft = `${-extraLeft}px`;
254
- if (extraRight)
255
- span.style.marginRight = `${-extraRight}px`;
256
- }
257
- });
258
- return import_react2.default.createElement("div", {
259
- ref,
260
- className,
261
- style: {
262
- position: "absolute",
263
- inset: 0,
264
- pointerEvents: "none",
265
- overflow: "auto",
266
- ...style
267
- },
268
- "aria-hidden": true,
269
- "data-mentionize-highlighter": ""
270
- }, ...children);
271
- };
272
-
273
- // src/useCaretPosition.ts
274
- var import_react3 = require("react");
275
- var SHARED_STYLE_PROPS = [
276
- "whiteSpace",
277
- "overflowWrap",
278
- "wordBreak",
279
- "padding",
280
- "paddingTop",
281
- "paddingRight",
282
- "paddingBottom",
283
- "paddingLeft",
284
- "fontFamily",
285
- "fontSize",
286
- "fontWeight",
287
- "lineHeight",
288
- "letterSpacing",
289
- "tabSize",
290
- "boxSizing",
291
- "borderWidth",
292
- "borderStyle"
293
- ];
294
- function useCaretPosition(dropdownWidth) {
295
- const mirrorRef = import_react3.useRef(null);
296
- const getCaretPosition = import_react3.useCallback((textarea, caretIndex, textOverride) => {
297
- const mirror = mirrorRef.current;
298
- if (!mirror)
299
- return null;
300
- const caret = caretIndex ?? textarea.selectionStart;
301
- const source = textOverride ?? textarea.value;
302
- const before = source.slice(0, caret);
303
- const computed = getComputedStyle(textarea);
304
- for (const prop of SHARED_STYLE_PROPS) {
305
- mirror.style[prop] = computed[prop];
306
- }
307
- mirror.style.width = `${textarea.offsetWidth}px`;
308
- mirror.textContent = before;
309
- const span = document.createElement("span");
310
- span.textContent = "​";
311
- mirror.appendChild(span);
312
- mirror.scrollTop = textarea.scrollTop;
313
- const spanRect = span.getBoundingClientRect();
314
- const mirrorRect = mirror.getBoundingClientRect();
315
- const textareaRect = textarea.getBoundingClientRect();
316
- const top = textareaRect.top + (spanRect.top - mirrorRect.top) - textarea.scrollTop + span.offsetHeight;
317
- let left = textareaRect.left + (spanRect.left - mirrorRect.left);
318
- if (left + dropdownWidth > window.innerWidth - 8) {
319
- left = window.innerWidth - dropdownWidth - 8;
320
- }
321
- if (left < 8)
322
- left = 8;
323
- mirror.innerHTML = "";
324
- return {
325
- top: Math.min(Math.max(top, 8), window.innerHeight - 8),
326
- left
327
- };
328
- }, [dropdownWidth]);
329
- return { mirrorRef, getCaretPosition };
330
- }
331
-
332
- // src/useMentionEngine.ts
333
- var import_react4 = require("react");
334
-
335
- // src/utils.ts
336
- function escapeRegex(s) {
337
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
338
- }
339
-
340
- // src/useMentionEngine.ts
341
- function detectMentionsInText(visibleText, triggers, getCache) {
342
- const all = [];
343
- for (const t of triggers) {
344
- const triggerChar = t.trigger;
345
- if (!visibleText.includes(triggerChar))
346
- continue;
347
- const cache = getCache(triggerChar);
348
- const knownItems = [];
349
- if (t.options) {
350
- for (const item of t.options) {
351
- knownItems.push({
352
- displayText: t.displayText(item),
353
- key: getItemKey(t, item),
354
- item
355
- });
356
- }
357
- }
358
- for (const [key, item] of cache.entries()) {
359
- if (item !== null) {
360
- const dt = t.displayText(item);
361
- if (!knownItems.some((k) => k.key === key)) {
362
- knownItems.push({ displayText: dt, key, item });
363
- }
364
- }
365
- }
366
- if (!knownItems.length)
367
- continue;
368
- const compiled = knownItems.map((ki) => {
369
- const pat = "^" + escapeRegex(ki.displayText).replace(/\s+/g, "\\s+");
370
- return { ...ki, re: new RegExp(pat, "i") };
371
- });
372
- const positions = [];
373
- let idx = visibleText.indexOf(triggerChar);
374
- while (idx !== -1) {
375
- positions.push(idx);
376
- idx = visibleText.indexOf(triggerChar, idx + 1);
377
- }
378
- const candidates = [];
379
- for (const pos of positions) {
380
- const after = visibleText.slice(pos + triggerChar.length);
381
- for (const c of compiled) {
382
- const match = c.re.exec(after);
383
- if (!match)
384
- continue;
385
- const matched = match[0];
386
- const end = pos + triggerChar.length + matched.length;
387
- const next = visibleText[end];
388
- if (next && !/[\s,.:;!?)}\]]/.test(next))
389
- continue;
390
- candidates.push({
391
- trigger: triggerChar,
392
- displayText: matched,
393
- key: c.key,
394
- start: pos,
395
- end
396
- });
397
- }
398
- }
399
- candidates.sort((a, b) => a.start !== b.start ? a.start - b.start : b.end - b.start - (a.end - a.start));
400
- for (const c of candidates) {
401
- const overlaps = all.some((f) => Math.max(f.start, c.start) < Math.min(f.end, c.end));
402
- if (!overlaps)
403
- all.push(c);
404
- }
405
- }
406
- return all;
407
- }
408
- function mentionsEqual(a, b) {
409
- if (a.length !== b.length)
410
- return false;
411
- for (let i = 0;i < a.length; i++) {
412
- const ai = a[i];
413
- const bi = b[i];
414
- if (ai.start !== bi.start || ai.end !== bi.end || ai.key !== bi.key)
415
- return false;
416
- }
417
- return true;
418
- }
419
- function useMentionEngine(options) {
420
- const {
421
- triggers,
422
- value: controlledValue,
423
- defaultValue,
424
- onChange,
425
- onMentionsChange
426
- } = options;
427
- const lastRawRef = import_react4.useRef(controlledValue ?? defaultValue ?? "");
428
- const suppressEmitRef = import_react4.useRef(false);
429
- const caretPosRef = import_react4.useRef(null);
430
- const prevMentionsRef = import_react4.useRef([]);
431
- const cacheRef = import_react4.useRef(new Map);
432
- function getCache(triggerChar) {
433
- let map = cacheRef.current.get(triggerChar);
434
- if (!map) {
435
- map = new Map;
436
- cacheRef.current.set(triggerChar, map);
437
- }
438
- return map;
439
- }
440
- import_react4.useEffect(() => {
441
- for (const t of triggers) {
442
- if (t.options) {
443
- const cache = getCache(t.trigger);
444
- for (const item of t.options) {
445
- const serialized = t.serialize(item);
446
- const re = new RegExp(t.pattern.source, t.pattern.flags.replace("g", ""));
447
- const m = re.exec(serialized);
448
- if (m) {
449
- const { key } = t.parseMatch(m);
450
- cache.set(key, item);
451
- }
452
- }
453
- }
454
- }
455
- }, [triggers]);
456
- const rawToVisible = import_react4.useCallback((raw) => {
457
- let result = raw;
458
- for (const t of triggers) {
459
- const globalRe = new RegExp(t.pattern.source, t.pattern.flags.includes("g") ? t.pattern.flags : t.pattern.flags + "g");
460
- const parts = [];
461
- let lastIndex = 0;
462
- let m;
463
- globalRe.lastIndex = 0;
464
- while ((m = globalRe.exec(result)) !== null) {
465
- parts.push(result.slice(lastIndex, m.index));
466
- const parsed = t.parseMatch(m);
467
- const cache = getCache(t.trigger);
468
- if (parsed.item !== undefined) {
469
- if (!cache.has(parsed.key) || cache.get(parsed.key) === null) {
470
- cache.set(parsed.key, parsed.item);
471
- }
472
- } else if (!cache.has(parsed.key)) {
473
- cache.set(parsed.key, null);
474
- }
475
- parts.push(t.trigger + parsed.displayText);
476
- lastIndex = m.index + m[0].length;
477
- if (!t.pattern.flags.includes("g"))
478
- break;
479
- }
480
- parts.push(result.slice(lastIndex));
481
- result = parts.join("");
482
- }
483
- return result;
484
- }, [triggers]);
485
- const [visible, setVisible] = import_react4.useState(() => rawToVisible(controlledValue ?? defaultValue ?? ""));
486
- const mentions = import_react4.useMemo(() => {
487
- const newMentions = detectMentionsInText(visible, triggers, getCache);
488
- if (mentionsEqual(prevMentionsRef.current, newMentions)) {
489
- return prevMentionsRef.current;
490
- }
491
- prevMentionsRef.current = newMentions;
492
- return newMentions;
493
- }, [visible, triggers]);
494
- const visibleToRaw = import_react4.useCallback((vis, mentionsList) => {
495
- if (!mentionsList.length)
496
- return vis;
497
- const ordered = mentionsList.slice().sort((a, b) => a.start - b.start);
498
- let raw = "";
499
- let last = 0;
500
- for (const m of ordered) {
501
- raw += vis.slice(last, m.start);
502
- const t = triggers.find((tr) => tr.trigger === m.trigger);
503
- if (t) {
504
- const cache = getCache(t.trigger);
505
- const item = cache.get(m.key);
506
- if (item !== null && item !== undefined) {
507
- raw += t.serialize(item);
508
- } else {
509
- raw += vis.slice(m.start, m.end);
510
- }
511
- } else {
512
- raw += vis.slice(m.start, m.end);
513
- }
514
- last = m.end;
515
- }
516
- raw += vis.slice(last);
517
- return raw;
518
- }, [triggers]);
519
- const emitSync = import_react4.useCallback((newVisible) => {
520
- const newMentions = detectMentionsInText(newVisible, triggers, getCache);
521
- if (!mentionsEqual(prevMentionsRef.current, newMentions)) {
522
- prevMentionsRef.current = newMentions;
523
- }
524
- const raw = visibleToRaw(newVisible, prevMentionsRef.current);
525
- if (raw !== lastRawRef.current) {
526
- lastRawRef.current = raw;
527
- onChange?.(raw);
528
- }
529
- onMentionsChange?.(prevMentionsRef.current);
530
- }, [triggers, visibleToRaw, onChange, onMentionsChange]);
531
- import_react4.useEffect(() => {
532
- if (controlledValue === undefined)
533
- return;
534
- if (controlledValue === lastRawRef.current)
535
- return;
536
- lastRawRef.current = controlledValue;
537
- suppressEmitRef.current = true;
538
- setVisible(rawToVisible(controlledValue));
539
- }, [controlledValue, rawToVisible]);
540
- const [activeTrigger, setActiveTrigger] = import_react4.useState(null);
541
- const [searchState, setSearchState] = import_react4.useState({
542
- items: [],
543
- page: 0,
544
- hasMore: false,
545
- loading: false
546
- });
547
- const [highlightIndex, setHighlightIndex] = import_react4.useState(0);
548
- const searchAbortRef = import_react4.useRef(null);
549
- const detectActiveTrigger = import_react4.useCallback((text, caretPos) => {
550
- const prefix = text.slice(0, caretPos);
551
- for (const t of triggers) {
552
- const triggerChar = t.trigger;
553
- const re = new RegExp(escapeRegex(triggerChar) + "([^\\n" + escapeRegex(triggerChar) + "]*)$");
554
- const match = re.exec(prefix);
555
- if (match && match[1] !== undefined) {
556
- const query = match[1];
557
- if (/\s/.test(query))
558
- continue;
559
- return {
560
- trigger: t,
561
- query,
562
- startPos: match.index
563
- };
564
- }
565
- }
566
- return null;
567
- }, [triggers]);
568
- const filteredOptions = import_react4.useMemo(() => {
569
- if (!activeTrigger)
570
- return [];
571
- const t = activeTrigger.trigger;
572
- const q = activeTrigger.query.toLowerCase();
573
- if (t.onSearch) {
574
- return searchState.items;
575
- }
576
- if (t.options) {
577
- if (!q)
578
- return t.options;
579
- return t.options.filter((item) => t.displayText(item).toLowerCase().includes(q));
580
- }
581
- return [];
582
- }, [activeTrigger, searchState.items]);
583
- import_react4.useEffect(() => {
584
- if (!activeTrigger?.trigger.onSearch)
585
- return;
586
- const t = activeTrigger.trigger;
587
- const query = activeTrigger.query;
588
- searchAbortRef.current?.abort();
589
- const controller = new AbortController;
590
- searchAbortRef.current = controller;
591
- setSearchState((s) => ({ ...s, loading: true, page: 0 }));
592
- const timer = setTimeout(async () => {
593
- try {
594
- const result = await t.onSearch(query, 0);
595
- if (controller.signal.aborted)
596
- return;
597
- setSearchState({
598
- items: result.items,
599
- page: 0,
600
- hasMore: result.hasMore,
601
- loading: false
602
- });
603
- } catch {
604
- if (controller.signal.aborted)
605
- return;
606
- setSearchState((s) => ({ ...s, loading: false }));
607
- }
608
- }, 150);
609
- return () => {
610
- clearTimeout(timer);
611
- controller.abort();
612
- };
613
- }, [activeTrigger?.trigger, activeTrigger?.query]);
614
- const loadMore = import_react4.useCallback(async () => {
615
- if (!activeTrigger?.trigger.onSearch || searchState.loading || !searchState.hasMore)
616
- return;
617
- const t = activeTrigger.trigger;
618
- const nextPage = searchState.page + 1;
619
- setSearchState((s) => ({ ...s, loading: true }));
620
- try {
621
- const result = await t.onSearch(activeTrigger.query, nextPage);
622
- setSearchState((s) => ({
623
- items: [...s.items, ...result.items],
624
- page: nextPage,
625
- hasMore: result.hasMore,
626
- loading: false
627
- }));
628
- } catch {
629
- setSearchState((s) => ({ ...s, loading: false }));
630
- }
631
- }, [activeTrigger, searchState]);
632
- const handleTextChange = import_react4.useCallback((newText, caretPos) => {
633
- caretPosRef.current = caretPos;
634
- setVisible(newText);
635
- emitSync(newText);
636
- const detected = detectActiveTrigger(newText, caretPos);
637
- if (detected) {
638
- setActiveTrigger(detected);
639
- setHighlightIndex(0);
640
- } else {
641
- setActiveTrigger(null);
642
- }
643
- }, [detectActiveTrigger, emitSync]);
644
- const getItemForMention = import_react4.useCallback((triggerChar, key) => {
645
- const cache = getCache(triggerChar);
646
- return cache.get(key) ?? null;
647
- }, []);
648
- const selectOption = import_react4.useCallback((item, textarea) => {
649
- if (!activeTrigger)
650
- return;
651
- const t = activeTrigger.trigger;
652
- if (t.onSelect) {
653
- const before2 = visible.slice(0, activeTrigger.startPos);
654
- const after2 = visible.slice(textarea.selectionStart);
655
- const savedStartPos = activeTrigger.startPos;
656
- setActiveTrigger(null);
657
- const result = t.onSelect(item);
658
- const applyResult = (value) => {
659
- if (value !== null) {
660
- const newVis2 = before2 + value + after2;
661
- const pos2 = savedStartPos + value.length;
662
- caretPosRef.current = pos2;
663
- setVisible(newVis2);
664
- emitSync(newVis2);
665
- } else {
666
- const newVis2 = before2 + after2;
667
- caretPosRef.current = savedStartPos;
668
- setVisible(newVis2);
669
- emitSync(newVis2);
670
- }
671
- };
672
- if (result instanceof Promise) {
673
- result.then(applyResult);
674
- } else {
675
- applyResult(result);
676
- }
677
- return;
678
- }
679
- const cache = getCache(t.trigger);
680
- const key = getItemKey(t, item);
681
- cache.set(key, item);
682
- const displayText = t.displayText(item);
683
- const mentionText = t.trigger + displayText;
684
- const before = visible.slice(0, activeTrigger.startPos);
685
- const after = visible.slice(textarea.selectionStart);
686
- const newVis = before + mentionText + " " + after;
687
- const pos = before.length + mentionText.length + 1;
688
- caretPosRef.current = pos;
689
- setVisible(newVis);
690
- emitSync(newVis);
691
- setActiveTrigger(null);
692
- }, [activeTrigger, visible, emitSync]);
693
- const closeSuggestions = import_react4.useCallback(() => {
694
- setActiveTrigger(null);
695
- setSearchState({ items: [], page: 0, hasMore: false, loading: false });
696
- }, []);
697
- const handleKeyDown = import_react4.useCallback((e, textarea) => {
698
- if (!activeTrigger)
699
- return false;
700
- const len = filteredOptions.length;
701
- if (!len && !searchState.loading)
702
- return false;
703
- if (e.key === "ArrowDown") {
704
- e.preventDefault();
705
- const next = (highlightIndex + 1) % Math.max(len, 1);
706
- setHighlightIndex(next);
707
- if (len - 1 - next <= 3 && searchState.hasMore && !searchState.loading) {
708
- loadMore();
709
- }
710
- return true;
711
- }
712
- if (e.key === "ArrowUp") {
713
- e.preventDefault();
714
- setHighlightIndex((highlightIndex - 1 + Math.max(len, 1)) % Math.max(len, 1));
715
- return true;
716
- }
717
- if (e.key === "Enter") {
718
- e.preventDefault();
719
- const item = filteredOptions[highlightIndex];
720
- if (item)
721
- selectOption(item, textarea);
722
- return true;
723
- }
724
- if (e.key === "Escape") {
725
- e.preventDefault();
726
- closeSuggestions();
727
- return true;
728
- }
729
- return false;
730
- }, [
731
- activeTrigger,
732
- filteredOptions,
733
- highlightIndex,
734
- searchState,
735
- selectOption,
736
- closeSuggestions,
737
- loadMore
738
- ]);
739
- return {
740
- visible,
741
- setVisible,
742
- mentions,
743
- activeTrigger,
744
- filteredOptions,
745
- highlightIndex,
746
- setHighlightIndex,
747
- searchLoading: searchState.loading,
748
- searchHasMore: searchState.hasMore,
749
- handleTextChange,
750
- handleKeyDown,
751
- selectOption,
752
- closeSuggestions,
753
- loadMore,
754
- rawToVisible,
755
- visibleToRaw,
756
- caretPosRef,
757
- getItemForMention
758
- };
759
- }
760
- function getItemKey(trigger, item) {
761
- const serialized = trigger.serialize(item);
762
- const re = new RegExp(trigger.pattern.source, trigger.pattern.flags.replace("g", ""));
763
- const m = re.exec(serialized);
764
- if (m) {
765
- return trigger.parseMatch(m).key;
766
- }
767
- return serialized;
768
- }
769
-
770
- // src/MentionInput.tsx
771
- var jsx_dev_runtime2 = require("react/jsx-dev-runtime");
772
- var SHARED_STYLE = {
773
- whiteSpace: "pre-wrap",
774
- overflowWrap: "anywhere",
775
- wordBreak: "break-word",
776
- padding: "0.5rem 0.75rem",
777
- fontFamily: "inherit",
778
- fontSize: "inherit",
779
- lineHeight: "inherit",
780
- letterSpacing: "normal",
781
- boxSizing: "border-box"
782
- };
783
- var MentionInput = import_react5.forwardRef(({
784
- triggers,
785
- value,
786
- defaultValue,
787
- onChange,
788
- onMentionsChange,
789
- placeholder,
790
- disabled,
791
- rows = 4,
792
- className,
793
- inputClassName,
794
- highlighterClassName,
795
- dropdownClassName,
796
- dropdownWidth = 250,
797
- loadingContent,
798
- renderDropdown,
799
- "aria-label": ariaLabel,
800
- "aria-describedby": ariaDescribedBy
801
- }, ref) => {
802
- const textareaRef = import_react5.useRef(null);
803
- import_react5.useImperativeHandle(ref, () => textareaRef.current);
804
- const engine = useMentionEngine({
805
- triggers,
806
- value,
807
- defaultValue,
808
- onChange,
809
- onMentionsChange
810
- });
811
- import_react5.useLayoutEffect(() => {
812
- const pos = engine.caretPosRef.current;
813
- const ta = textareaRef.current;
814
- if (pos !== null && ta && document.activeElement === ta) {
815
- ta.setSelectionRange(pos, pos);
816
- engine.caretPosRef.current = null;
817
- }
818
- });
819
- const { mirrorRef, getCaretPosition } = useCaretPosition(dropdownWidth);
820
- const [dropdownPos, setDropdownPos] = import_react5.useState(null);
821
- import_react5.useEffect(() => {
822
- if (engine.activeTrigger && textareaRef.current) {
823
- requestAnimationFrame(() => {
824
- const pos = getCaretPosition(textareaRef.current);
825
- if (pos)
826
- setDropdownPos(pos);
827
- });
828
- } else {
829
- setDropdownPos(null);
830
- }
831
- }, [engine.activeTrigger, engine.visible, getCaretPosition]);
832
- const handleChange = import_react5.useCallback((e) => {
833
- engine.handleTextChange(e.target.value, e.target.selectionStart);
834
- }, [engine.handleTextChange]);
835
- const handleKeyDown = import_react5.useCallback((e) => {
836
- if (textareaRef.current) {
837
- engine.handleKeyDown(e, textareaRef.current);
838
- }
839
- }, [engine.handleKeyDown]);
840
- const handlePaste = import_react5.useCallback((e) => {
841
- const ta = textareaRef.current;
842
- if (!ta)
843
- return;
844
- const txt = e.clipboardData.getData("text");
845
- const start = ta.selectionStart;
846
- const end = ta.selectionEnd;
847
- const newText = engine.visible.slice(0, start) + txt + engine.visible.slice(end);
848
- e.preventDefault();
849
- engine.handleTextChange(newText, start + txt.length);
850
- }, [engine.visible, engine.handleTextChange]);
851
- const handleBlur = import_react5.useCallback(() => {
852
- setTimeout(() => engine.closeSuggestions(), 150);
853
- }, [engine.closeSuggestions]);
854
- const handleSelect = import_react5.useCallback((item) => {
855
- if (textareaRef.current) {
856
- engine.selectOption(item, textareaRef.current);
857
- }
858
- }, [engine.selectOption]);
859
- const showDropdown = engine.activeTrigger !== null && dropdownPos !== null;
860
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("div", {
861
- className,
862
- style: { position: "relative" },
863
- "data-mentionize-container": "",
864
- children: [
865
- /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(MentionHighlighter, {
866
- visible: engine.visible,
867
- mentions: engine.mentions,
868
- triggers,
869
- textareaRef,
870
- getItemForMention: engine.getItemForMention,
871
- className: highlighterClassName,
872
- style: SHARED_STYLE
873
- }, undefined, false, undefined, this),
874
- /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("textarea", {
875
- ref: textareaRef,
876
- value: engine.visible,
877
- onChange: handleChange,
878
- onKeyDown: handleKeyDown,
879
- onPaste: handlePaste,
880
- onBlur: handleBlur,
881
- rows,
882
- placeholder,
883
- disabled,
884
- "aria-label": ariaLabel,
885
- "aria-describedby": ariaDescribedBy,
886
- "aria-autocomplete": "list",
887
- "aria-expanded": showDropdown,
888
- className: inputClassName,
889
- style: {
890
- ...SHARED_STYLE,
891
- position: "relative",
892
- width: "100%",
893
- resize: "vertical",
894
- background: "transparent",
895
- color: "transparent",
896
- caretColor: "CanvasText",
897
- zIndex: 10
898
- },
899
- "data-mentionize-input": ""
900
- }, undefined, false, undefined, this),
901
- /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("div", {
902
- ref: mirrorRef,
903
- "aria-hidden": true,
904
- style: {
905
- position: "absolute",
906
- top: 0,
907
- left: -9999,
908
- visibility: "hidden",
909
- ...SHARED_STYLE
910
- },
911
- "data-mentionize-mirror": ""
912
- }, undefined, false, undefined, this),
913
- showDropdown && engine.activeTrigger && (renderDropdown ? renderDropdown({
914
- items: engine.filteredOptions,
915
- highlightedIndex: engine.highlightIndex,
916
- onSelect: handleSelect,
917
- onHighlight: engine.setHighlightIndex,
918
- loading: engine.searchLoading,
919
- onLoadMore: engine.searchHasMore ? engine.loadMore : undefined
920
- }) : /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(MentionDropdown, {
921
- items: engine.filteredOptions,
922
- trigger: engine.activeTrigger.trigger,
923
- highlightedIndex: engine.highlightIndex,
924
- onHighlight: engine.setHighlightIndex,
925
- onSelect: handleSelect,
926
- onLoadMore: engine.searchHasMore ? engine.loadMore : undefined,
927
- loading: engine.searchLoading,
928
- loadingContent,
929
- position: dropdownPos,
930
- width: dropdownWidth,
931
- className: dropdownClassName
932
- }, undefined, false, undefined, this))
933
- ]
934
- }, undefined, true, undefined, this);
935
- });
936
- MentionInput.displayName = "MentionInput";
937
-
938
- //# debugId=C3CB6047238D072664756E2164756E21
50
+ //# debugId=00144F398F840CEA64756E2164756E21
939
51
  //# sourceMappingURL=index.js.map