Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add Create Collection button to Collections page #223

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 184 additions & 0 deletions src/components/CreateCollection/CreateCollectionForm.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { StepContent, Stepper, Typography, Box, StepLabel, Step, Paper, Button, TextField } from '@mui/material';
import VectorConfig from './VectorConfig';
import { useClient } from '../../context/client-context';

const CreateCollectionForm = ({ collections, onComplete, sx, handleCreated }) => {
const { client: qdrantClient } = useClient();
const [activeStep, setActiveStep] = useState(0);
const [collectionName, setCollectionName] = useState('');
const [vectors, setVectors] = useState([{ dimension: '', distance: '', name: '' }]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);

const handleNext = () => {
setActiveStep((prevActiveStep) => prevActiveStep + 1);
};

const handleBack = () => {
setActiveStep((prevActiveStep) => prevActiveStep - 1);
};

useEffect(() => {
if (activeStep === 2) {
setLoading(true);
const VectorConfig =
vectors.length === 1
? {
vectors: { size: parseInt(vectors[0].dimension), distance: vectors[0].distance },
}
: {
vectors: vectors.reduce((acc, vector) => {
acc[vector.name] = { size: parseInt(vector.dimension), distance: vector.distance };
return acc;
}, {}),
};

qdrantClient
.createCollection(collectionName, VectorConfig)
.then(() => {
setLoading(false);
setError(null);
onComplete();
handleCreated();
})
.catch((error) => {
setLoading(false);
setError(error);
});
}
}, [activeStep]);

return (
<Box sx={{ ...sx }}>
<Stepper activeStep={activeStep} orientation="vertical">
{/* Step 1 start - enter a collection name*/}
<Step key={'Step 1 - enter a collection name'}>
<StepLabel>{activeStep === 0 ? 'Enter a collection name' : `Collection name: ${collectionName}`}</StepLabel>
<CollectionNameTextBox
collectionName={collectionName}
setCollectionName={setCollectionName}
collections={collections}
handleNext={handleNext}
activeStep={activeStep}
/>
</Step>
{/* Step 1 end - enter a collection name*/}
{/* Step 2 start - vector config */}
<Step key={'Step 2 - vector config'}>
<StepLabel>Step 2 - Vector config</StepLabel>
<VectorConfig handleNext={handleNext} handleBack={handleBack} vectors={vectors} setVectors={setVectors} />
</Step>
{/* Step 2 end - vector config */}
</Stepper>
{activeStep === 2 && (
<Paper square elevation={0} sx={{ p: 3 }}>
{loading ? (
<Typography>Creating collection...</Typography>
) : error ? (
<Typography color="error">{error.message}</Typography>
) : (
<Typography>Collection created successfully 🎉</Typography>
)}
</Paper>
)}
</Box>
);
};

// props validation
CreateCollectionForm.propTypes = {
collections: PropTypes.array,
onComplete: PropTypes.func.isRequired,
sx: PropTypes.object,
handleCreated: PropTypes.func,
};

export default CreateCollectionForm;

const CollectionNameTextBox = ({ collectionName, setCollectionName, collections, handleNext, activeStep }) => {
const [formError, setFormError] = useState(false);
const [formMessage, setFormMessage] = useState('');
const textFieldRef = useRef(null);

function validateCollectionName(value) {
const INVALID_CHARS = ['<', '>', ':', '"', '/', '\\', '|', '?', '*', '\0', '\u{1F}'];

const invalidChar = INVALID_CHARS.find((c) => value.includes(c));

if (invalidChar !== undefined) {
return `Collection name cannot contain "${invalidChar}" char`;
} else {
return null;
}
}

function collectionExists(name) {
if (collections?.some((collection) => collection.name === name)) {
return `Collection with name "${name}" already exists`;
}
return null;
}

const MAX_COLLECTION_NAME_LENGTH = 255;

useEffect(() => {
if (activeStep === 0) {
textFieldRef.current.focus();
}
return () => {};
}, [activeStep]);

const handleTextChange = (event) => {
// if there will be more forms use schema validation instead
const newCollectionName = event.target.value;
const hasForbiddenSymbolsMessage = validateCollectionName(newCollectionName);
const hasForbiddenSymbols = hasForbiddenSymbolsMessage !== null;
const collectionExistsMessage = collectionExists(newCollectionName);
const collectionExistsError = collectionExistsMessage !== null;
const isTooShort = newCollectionName?.length < 1;
const isTooLong = newCollectionName?.length > MAX_COLLECTION_NAME_LENGTH;

setCollectionName(newCollectionName);
setFormError(isTooShort || isTooLong || hasForbiddenSymbols || collectionExistsError);
setFormMessage(
isTooShort
? 'Collection name is too short'
: isTooLong
? 'Collection name is too long'
: (hasForbiddenSymbolsMessage || collectionExistsMessage) ?? ''
);
};

return (
<StepContent>
<Box sx={{ mb: 2 }}>
<Typography mb={2}>Collection name must be new</Typography>
<TextField
inputRef={textFieldRef}
label="Collection name"
variant="outlined"
value={collectionName}
onChange={handleTextChange}
error={formError}
helperText={formMessage}
fullWidth
/>
</Box>
<Box sx={{ mb: 2 }}>
<Button variant="contained" onClick={handleNext} sx={{ mt: 1, mr: 1 }} disabled={!collectionName || formError}>
Continue
</Button>
</Box>
</StepContent>
);
};

CollectionNameTextBox.propTypes = {
collectionName: PropTypes.string.isRequired,
setCollectionName: PropTypes.func.isRequired,
collections: PropTypes.array,
handleNext: PropTypes.func.isRequired,
activeStep: PropTypes.number.isRequired,
};
177 changes: 177 additions & 0 deletions src/components/CreateCollection/VectorConfig.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import React, { useState } from 'react';
import {
Box,
Button,
TextField,
StepContent,
InputLabel,
FormControl,
Select,
MenuItem,
FormHelperText,
IconButton,
Tooltip,
} from '@mui/material';
import PropTypes from 'prop-types';
import { AddCircleOutline, RemoveCircleOutline } from '@mui/icons-material';

const distancesOptions = ['Cosine', 'Euclid', 'Dot', 'Manhattan'];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ideally, this should be coming from OpenAPI


const VectorRow = ({ vectors, index, setVectors, errors, length, setErrors }) => {
const handleAddVector = () => {
setVectors([...vectors, { dimension: '', distance: '', name: '' }]);
setErrors([...errors, { dimension: '', distance: '' }]); // Add corresponding error object
};

const handleRemoveVector = (index) => {
const newVectors = vectors.filter((_, i) => i !== index);
const newErrors = errors.filter((_, i) => i !== index);
setVectors(newVectors);
setErrors(newErrors);
};

const validate = (index, field, value) => {
const newErrors = [...errors];
if (!value) {
newErrors[index][field] = `${field} is required`;
} else if (field === 'dimension' && isNaN(value)) {
newErrors[index][field] = 'Dimension must be a number';
} else {
newErrors[index][field] = '';
}
setErrors(newErrors);
};

const handleVectorChange = (index, field, value) => {
const newVectors = [...vectors];
newVectors[index][field] = value;
setVectors(newVectors);
validate(index, field, value);
};

return (
<Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
<FormControl sx={{ mr: 2, width: '150px' }} error={!!errors[index].distance}>
<InputLabel>Distance</InputLabel>
<Select
value={vectors[index].distance}
onChange={(e) => handleVectorChange(index, 'distance', e.target.value)}
label="Distance"
>
{distancesOptions.map((option) => (
<MenuItem key={option} value={option}>
{option}
</MenuItem>
))}
</Select>
<FormHelperText>{errors[index].distance}</FormHelperText>
</FormControl>
<TextField
label="Dimension"
value={vectors[index].dimension}
onChange={(e) => handleVectorChange(index, 'dimension', e.target.value)}
error={!!errors[index].dimension}
helperText={errors[index].dimension}
sx={{ mr: 2 }}
/>
{length > 1 && (
<>
<TextField
label="Name"
value={vectors[index].name}
onChange={(e) => handleVectorChange(index, 'name', e.target.value)}
error={!!errors[index].name}
helperText={errors[index].name}
sx={{ mr: 2 }}
/>
<Tooltip title="Remove vector" placement="top" sx={{ mr: 1 }}>
<IconButton onClick={() => handleRemoveVector(index)} color="error">
<RemoveCircleOutline />
</IconButton>
</Tooltip>
</>
)}
{length - 1 === index && (
<Tooltip title="Add vector" placement="top">
<IconButton onClick={handleAddVector} color="success">
<AddCircleOutline />
</IconButton>
</Tooltip>
)}
</Box>
);
};

VectorRow.propTypes = {
vectors: PropTypes.array.isRequired,
errors: PropTypes.array.isRequired,
index: PropTypes.number.isRequired,
length: PropTypes.number.isRequired,
setVectors: PropTypes.func.isRequired,
setErrors: PropTypes.func.isRequired,
};

const VectorConfig = ({ handleNext, handleBack, vectors, setVectors }) => {
const [errors, setErrors] = useState([{ dimension: '', distance: '', name: '' }]);

const validateAll = () => {
const newErrors = vectors.map((vector) => {
const error = {};
if (!vector.dimension) {
error.dimension = 'Dimension is required';
} else if (isNaN(vector.dimension)) {
error.dimension = 'Dimension must be a number';
}
if (!vector.distance) {
error.distance = 'Distance is required';
}
if (vectors.length > 1 && !vector.name) {
error.name = 'Vector name is required';
}
return error;
});
setErrors(newErrors);
return newErrors.every((error) => !Object.values(error).length);
};

const handleContinue = () => {
if (validateAll()) {
handleNext();
}
};

return (
<StepContent>
<Box sx={{ mb: 2 }}>
{vectors.map((_, index) => (
<VectorRow
key={index}
index={index}
vectors={vectors}
setVectors={setVectors}
errors={errors}
length={vectors.length}
setErrors={setErrors}
/>
))}
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>
<Button variant="contained" onClick={handleContinue}>
Create collection
</Button>
<Button variant="text" onClick={handleBack}>
Back
</Button>
</Box>
</StepContent>
);
};

VectorConfig.propTypes = {
handleNext: PropTypes.func.isRequired,
handleBack: PropTypes.func.isRequired,
vectors: PropTypes.array.isRequired,
setVectors: PropTypes.func.isRequired,
};

export default VectorConfig;
Loading
Loading