mentionize 0.0.1

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