2025-08-04 12:58:42 +03:00
|
|
|
import { useRef } from "preact/hooks";
|
|
|
|
|
import { t } from "../../services/i18n";
|
2025-08-04 16:05:04 +03:00
|
|
|
import { useEffect } from "react";
|
2025-08-04 18:54:17 +03:00
|
|
|
import note_autocomplete, { Options, type Suggestion } from "../../services/note_autocomplete";
|
2025-08-04 16:05:04 +03:00
|
|
|
import type { RefObject } from "preact";
|
2025-08-04 12:58:42 +03:00
|
|
|
|
|
|
|
|
interface NoteAutocompleteProps {
|
2025-08-04 16:05:04 +03:00
|
|
|
inputRef?: RefObject<HTMLInputElement>;
|
2025-08-04 12:58:42 +03:00
|
|
|
text?: string;
|
2025-08-04 18:54:17 +03:00
|
|
|
placeholder?: string;
|
|
|
|
|
container?: RefObject<HTMLDivElement>;
|
|
|
|
|
opts?: Omit<Options, "container">;
|
2025-08-04 12:58:42 +03:00
|
|
|
onChange?: (suggestion: Suggestion) => void;
|
2025-08-04 18:54:17 +03:00
|
|
|
onTextChange?: (text: string) => void;
|
2025-08-04 12:58:42 +03:00
|
|
|
}
|
|
|
|
|
|
2025-08-04 18:54:17 +03:00
|
|
|
export default function NoteAutocomplete({ inputRef: _ref, text, placeholder, onChange, onTextChange, container, opts }: NoteAutocompleteProps) {
|
2025-08-04 16:05:04 +03:00
|
|
|
const ref = _ref ?? useRef<HTMLInputElement>(null);
|
2025-08-04 12:58:42 +03:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
if (!ref.current) return;
|
|
|
|
|
const $autoComplete = $(ref.current);
|
|
|
|
|
|
2025-08-04 18:54:17 +03:00
|
|
|
// clear any event listener added in previous invocation of this function
|
|
|
|
|
$autoComplete
|
|
|
|
|
.off("autocomplete:noteselected")
|
|
|
|
|
.off("autocomplete:commandselected")
|
|
|
|
|
|
2025-08-04 12:58:42 +03:00
|
|
|
note_autocomplete.initNoteAutocomplete($autoComplete, {
|
2025-08-04 18:54:17 +03:00
|
|
|
...opts,
|
|
|
|
|
container: container?.current
|
2025-08-04 12:58:42 +03:00
|
|
|
});
|
|
|
|
|
if (onChange) {
|
2025-08-04 18:54:17 +03:00
|
|
|
const listener = (_e, suggestion) => onChange(suggestion);
|
|
|
|
|
$autoComplete
|
|
|
|
|
.on("autocomplete:noteselected", listener)
|
|
|
|
|
.on("autocomplete:externallinkselected", listener)
|
|
|
|
|
.on("autocomplete:commandselected", listener);
|
|
|
|
|
}
|
|
|
|
|
if (onTextChange) {
|
|
|
|
|
$autoComplete.on("input", () => onTextChange($autoComplete[0].value));
|
|
|
|
|
}
|
|
|
|
|
}, [opts, container?.current]);
|
2025-08-04 12:58:42 +03:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
if (!ref.current) return;
|
|
|
|
|
if (text) {
|
|
|
|
|
const $autoComplete = $(ref.current);
|
|
|
|
|
note_autocomplete.setText($autoComplete, text);
|
|
|
|
|
} else {
|
|
|
|
|
ref.current.value = "";
|
|
|
|
|
}
|
|
|
|
|
}, [text]);
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
<div className="input-group">
|
|
|
|
|
<input
|
|
|
|
|
ref={ref}
|
|
|
|
|
className="note-autocomplete form-control"
|
2025-08-04 18:54:17 +03:00
|
|
|
placeholder={placeholder ?? t("add_link.search_note")} />
|
2025-08-04 12:58:42 +03:00
|
|
|
</div>
|
|
|
|
|
);
|
|
|
|
|
}
|