File size: 6,897 Bytes
ec4551b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | 'use client';
import React, { FC, useEffect, useImperativeHandle, useState } from 'react';
import { computePosition, flip, shift } from '@floating-ui/dom';
import { posToDOMRect, ReactRenderer } from '@tiptap/react';
// Debounce utility for TipTap
const debounce = <T extends any[]>(
func: (...args: any[]) => Promise<T>,
wait: number
) => {
let timeout: NodeJS.Timeout;
return (...args: any[]): Promise<T> => {
clearTimeout(timeout);
return new Promise((resolve) => {
timeout = setTimeout(async () => {
try {
const result = await func(...args);
resolve(result);
} catch (error) {
console.error('Debounced function error:', error);
resolve([] as T);
}
}, wait);
});
};
};
const MentionList: FC = (props: any) => {
const [selectedIndex, setSelectedIndex] = useState(0);
const selectItem = (index: number) => {
const item = props.items[index];
if (item) {
props.command(item);
}
};
const upHandler = () => {
setSelectedIndex(
(selectedIndex + props.items.length - 1) % props.items.length
);
};
const downHandler = () => {
setSelectedIndex((selectedIndex + 1) % props.items.length);
};
const enterHandler = () => {
selectItem(selectedIndex);
};
useEffect(() => setSelectedIndex(0), [props.items]);
useImperativeHandle(props.ref, () => ({
onKeyDown: ({ event }: { event: any }) => {
if (event.key === 'ArrowUp') {
upHandler();
return true;
}
if (event.key === 'ArrowDown') {
downHandler();
return true;
}
if (event.key === 'Enter') {
enterHandler();
return true;
}
return false;
},
}));
if (props?.stop) {
return null;
}
return (
<div className="dropdown-menu bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto p-2">
{props?.items?.none ? (
<div className="flex items-center justify-center p-2 text-gray-500">
We don't have autocomplete for this social media
</div>
) : props?.loading ? (
<div className="flex items-center justify-center p-2 text-gray-500">
Loading...
</div>
) : props?.items ? (
props.items.length === 0 ? (
<div className="p-2 text-gray-500 text-center">No results found</div>
) : (
props?.items?.map((item: any, index: any) => (
<button
className={`flex gap-[10px] w-full p-2 text-start rounded hover:bg-gray-100 ${
index === selectedIndex ? 'bg-blue-100' : ''
}`}
key={item.id || index}
onClick={() => selectItem(index)}
>
<img
src={item.image || '/no-picture.jpg'}
alt={item.label}
className="w-[30px] h-[30px] rounded-full object-cover"
/>
<div className="flex-1 text-gray-800">{item.label}</div>
</button>
))
)
) : (
<div className="p-2 text-gray-500 text-center">Loading...</div>
)}
</div>
);
};
const updatePosition = (editor: any, element: any) => {
if (!editor?.view || !element) {
return;
}
const virtualElement = {
getBoundingClientRect: () =>
posToDOMRect(
editor.view,
editor.state.selection.from,
editor.state.selection.to
),
};
computePosition(virtualElement, element, {
placement: 'bottom-start',
strategy: 'absolute',
middleware: [shift(), flip()],
}).then(({ x, y, strategy }) => {
element.style.width = 'max-content';
element.style.position = strategy;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
element.style.zIndex = '1000';
});
};
export const suggestion = (
loadList: (
query: string
) => Promise<{ image: string; label: string; id: string }[]>
) => {
// Create debounced version of loadList once
const debouncedLoadList = debounce(loadList, 500);
let component: any;
return {
allowSpaces: true,
items: async ({ query }: { query: string }) => {
if (!query || query.length < 2) {
component.updateProps({ loading: true, stop: true });
return [];
}
try {
component.updateProps({ loading: true, stop: false });
const result = await debouncedLoadList(query);
return result;
} catch (error) {
return [];
}
},
render: () => {
let currentQuery = '';
let isLoadingQuery = false;
return {
onBeforeStart: (props: any) => {
component = new ReactRenderer(MentionList, {
props: {
...props,
loading: true,
},
editor: props.editor,
});
component.updateProps({ ...props, loading: true, stop: false });
updatePosition(props.editor, component.element);
},
onStart: (props: any) => {
currentQuery = props.query || '';
isLoadingQuery = currentQuery.length >= 2;
if (!props.clientRect) {
return;
}
component.element.style.position = 'absolute';
component.element.style.zIndex = '1000';
const container =
document.querySelector('.mantine-Paper-root') || document.body;
container.appendChild(component.element);
updatePosition(props.editor, component.element);
component.updateProps({ ...props, loading: true });
},
onUpdate(props: any) {
const newQuery = props.query || '';
const queryChanged = newQuery !== currentQuery;
currentQuery = newQuery;
// If query changed and is valid, we're loading until results come in
if (queryChanged && newQuery.length >= 2) {
isLoadingQuery = true;
}
// If we have results, we're no longer loading
if (props.items && props.items.length > 0) {
isLoadingQuery = false;
}
// Show loading if we have a valid query but no results yet
const shouldShowLoading =
isLoadingQuery &&
newQuery.length >= 2 &&
(!props.items || props.items.length === 0);
component.updateProps({ ...props, loading: false, stop: false });
if (!props.clientRect) {
return;
}
updatePosition(props.editor, component.element);
},
onKeyDown(props: any) {
if (props.event.key === 'Escape') {
component.destroy();
return true;
}
return component.ref?.onKeyDown(props);
},
onExit() {
component.element.remove();
component.destroy();
},
};
},
};
};
|