VectorInputBox.tsx 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import { useRef, useEffect, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { EditorState, Compartment } from '@codemirror/state';
  4. import { EditorView, keymap, placeholder } from '@codemirror/view';
  5. import { insertTab } from '@codemirror/commands';
  6. import { indentUnit } from '@codemirror/language';
  7. import { minimalSetup } from 'codemirror';
  8. import { javascript } from '@codemirror/lang-javascript';
  9. import { linter, Diagnostic } from '@codemirror/lint';
  10. import { CollectionFullObject, FieldObject } from '@server/types';
  11. import { CollectionService } from '@/http';
  12. import { DataTypeStringEnum } from '@/consts';
  13. import { SearchSingleParams } from '../../types';
  14. import { isSparseVector, transformObjStrToJSONStr } from '@/utils';
  15. import { getQueryStyles } from './Styles';
  16. import { useTheme } from '@mui/material';
  17. import { githubLight } from '@ddietr/codemirror-themes/github-light';
  18. import { githubDark } from '@ddietr/codemirror-themes/github-dark';
  19. const floatVectorValidator = (text: string, field: FieldObject) => {
  20. try {
  21. const value = JSON.parse(text);
  22. const dim = field.dimension;
  23. if (!Array.isArray(value)) {
  24. return {
  25. valid: false,
  26. message: `Not an array`,
  27. };
  28. }
  29. if (Array.isArray(value) && value.length !== dim) {
  30. return {
  31. valid: false,
  32. value: undefined,
  33. message: `Dimension ${value.length} is not equal to ${dim} `,
  34. };
  35. }
  36. return { valid: true, message: ``, value: value };
  37. } catch (e: any) {
  38. return {
  39. valid: false,
  40. message: `Wrong Float Vector format, it should be an array of ${field.dimension} numbers`,
  41. };
  42. }
  43. };
  44. const binaryVectorValidator = (text: string, field: FieldObject) => {
  45. try {
  46. const value = JSON.parse(text);
  47. const dim = field.dimension;
  48. if (!Array.isArray(value)) {
  49. return {
  50. valid: false,
  51. message: `Not an array`,
  52. };
  53. }
  54. if (Array.isArray(value) && value.length !== dim / 8) {
  55. return {
  56. valid: false,
  57. value: undefined,
  58. message: `Dimension ${value.length} is not equal to ${dim / 8} `,
  59. };
  60. }
  61. return { valid: true, message: ``, value: value };
  62. } catch (e: any) {
  63. return {
  64. valid: false,
  65. message: `Wrong Binary Vector format, it should be an array of ${
  66. field.dimension / 8
  67. } numbers`,
  68. };
  69. }
  70. };
  71. const sparseVectorValidator = (text: string, field: FieldObject) => {
  72. if (!isSparseVector(text)) {
  73. return {
  74. valid: false,
  75. value: undefined,
  76. message: `Incorrect Sparse Vector format, it should be like {1: 0.1, 3: 0.2}`,
  77. };
  78. }
  79. try {
  80. JSON.parse(transformObjStrToJSONStr(text));
  81. return {
  82. valid: true,
  83. message: ``,
  84. };
  85. } catch (e: any) {
  86. return {
  87. valid: false,
  88. message: `Wrong Sparse Vector format`,
  89. };
  90. }
  91. };
  92. const Validator = {
  93. [DataTypeStringEnum.FloatVector]: floatVectorValidator,
  94. [DataTypeStringEnum.BinaryVector]: binaryVectorValidator,
  95. [DataTypeStringEnum.Float16Vector]: floatVectorValidator,
  96. [DataTypeStringEnum.BFloat16Vector]: floatVectorValidator,
  97. [DataTypeStringEnum.SparseFloatVector]: sparseVectorValidator,
  98. };
  99. export type VectorInputBoxProps = {
  100. onChange: (anns_field: string, value: string) => void;
  101. searchParams: SearchSingleParams;
  102. collection: CollectionFullObject;
  103. };
  104. let queryTimeout: NodeJS.Timeout;
  105. export default function VectorInputBox(props: VectorInputBoxProps) {
  106. const theme = useTheme();
  107. const { t: searchTrans } = useTranslation('search');
  108. // props
  109. const { searchParams, onChange, collection } = props;
  110. const { field, data } = searchParams;
  111. // UI states
  112. const [isFocused, setIsFocused] = useState(false);
  113. // classes
  114. const classes = getQueryStyles();
  115. // refs
  116. const editorEl = useRef<HTMLDivElement>(null);
  117. const editor = useRef<EditorView>();
  118. const onChangeRef = useRef(onChange);
  119. const dataRef = useRef(data);
  120. const fieldRef = useRef(field);
  121. const searchParamsRef = useRef(searchParams);
  122. const themeCompartment = new Compartment();
  123. // get validator
  124. const validator = Validator[field.data_type as keyof typeof Validator];
  125. useEffect(() => {
  126. // update dataRef and onChangeRef when data changes
  127. dataRef.current = data;
  128. onChangeRef.current = onChange;
  129. fieldRef.current = field;
  130. searchParamsRef.current = searchParams;
  131. if (editor.current) {
  132. // only data replace should trigger this, otherwise, let cm handle the state
  133. if (editor.current.state.doc.toString() !== data) {
  134. editor.current.dispatch({
  135. changes: {
  136. from: 0,
  137. to: data.length + 1,
  138. insert: data,
  139. },
  140. });
  141. }
  142. }
  143. }, [JSON.stringify(searchParams), onChange]);
  144. const getVectorById = (text: string) => {
  145. if (queryTimeout) {
  146. clearTimeout(queryTimeout);
  147. }
  148. // only search for text that doesn't have space, comma, or brackets or curly brackets
  149. if (!text.trim().match(/[\s,{}]/)) {
  150. const isVarChar =
  151. collection.schema.primaryField.data_type === DataTypeStringEnum.VarChar;
  152. if (!isVarChar && isNaN(Number(text))) {
  153. return;
  154. }
  155. queryTimeout = setTimeout(() => {
  156. try {
  157. CollectionService.queryData(collection.collection_name, {
  158. expr: isVarChar
  159. ? `${collection.schema.primaryField.name} == '${text}'`
  160. : `${collection.schema.primaryField.name} == ${text}`,
  161. output_fields: [searchParamsRef.current.anns_field],
  162. })
  163. .then(res => {
  164. if (res.data && res.data.length === 1) {
  165. onChangeRef.current(
  166. searchParamsRef.current.anns_field,
  167. JSON.stringify(
  168. res.data[0][searchParamsRef.current.anns_field]
  169. )
  170. );
  171. }
  172. })
  173. .catch(e => {
  174. console.log(0, e);
  175. });
  176. } catch (e) {}
  177. }, 300);
  178. }
  179. };
  180. // create editor
  181. useEffect(() => {
  182. if (!editor.current) {
  183. const startState = EditorState.create({
  184. doc: data,
  185. extensions: [
  186. minimalSetup,
  187. javascript(),
  188. placeholder('vector or entity id'),
  189. linter(view => {
  190. const text = view.state.doc.toString();
  191. // ignore empty text
  192. if (!text) return [];
  193. // validate
  194. const { valid, message } = validator(text, field);
  195. // if invalid, draw a red line
  196. if (!valid) {
  197. let diagnostics: Diagnostic[] = [];
  198. diagnostics.push({
  199. from: 0,
  200. to: view.state.doc.line(view.state.doc.lines).to,
  201. severity: 'error',
  202. message: message,
  203. actions: [
  204. {
  205. name: 'Remove',
  206. apply(view, from, to) {
  207. view.dispatch({ changes: { from, to } });
  208. },
  209. },
  210. ],
  211. });
  212. return diagnostics;
  213. } else {
  214. // onChangeRef.current(searchParams.anns_field, value);
  215. return [];
  216. }
  217. }),
  218. keymap.of([{ key: 'Tab', run: insertTab }]), // fix tab behaviour
  219. indentUnit.of(' '), // fix tab indentation
  220. EditorView.theme({
  221. '&.cm-editor': {
  222. '&.cm-focused': {
  223. outline: 'none',
  224. },
  225. },
  226. '.cm-content': {
  227. fontSize: '12px',
  228. minHeight: '124px',
  229. },
  230. '.cm-gutters': {
  231. display: 'none',
  232. },
  233. }),
  234. EditorView.lineWrapping,
  235. EditorView.updateListener.of(update => {
  236. if (update.docChanged) {
  237. if (queryTimeout) {
  238. clearTimeout(queryTimeout);
  239. }
  240. const text = update.state.doc.toString();
  241. const { valid } = validator(text, fieldRef.current);
  242. if (valid || text === '') {
  243. onChangeRef.current(searchParams.anns_field, text);
  244. } else {
  245. getVectorById(text);
  246. }
  247. }
  248. if (update.focusChanged) {
  249. setIsFocused(update.view.hasFocus);
  250. }
  251. }),
  252. ],
  253. });
  254. const view = new EditorView({
  255. state: startState,
  256. parent: editorEl.current!,
  257. });
  258. editor.current = view;
  259. // focus editor, the cursor will be at the end of the text
  260. const endPos = editor.current.state.doc.length;
  261. editor.current.dispatch({
  262. selection: { anchor: endPos },
  263. });
  264. editor.current.focus();
  265. return () => {
  266. view.destroy();
  267. editor.current = undefined;
  268. };
  269. }
  270. }, [JSON.stringify(field), getVectorById]);
  271. useEffect(() => {
  272. // dispatch dark mode change to editor
  273. if (editor.current) {
  274. editor.current.dispatch({
  275. effects: themeCompartment.reconfigure(
  276. themeCompartment.of(
  277. theme.palette.mode === 'light' ? githubLight : githubDark
  278. )
  279. ),
  280. });
  281. }
  282. }, [theme.palette.mode]);
  283. return (
  284. <div
  285. className={`${classes.vectorInputBox} ${isFocused ? 'focused' : ''}`}
  286. ref={editorEl}
  287. ></div>
  288. );
  289. }