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