mentionize 0.0.6 → 0.0.7

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