📝 (1f4d6df60295_add_default_fields_column.py): remove unused variable table_names to improve code readability

📝 (1f4d6df60295_add_default_fields_column.py): remove unused variable `table_names` to improve code readability
✨ (c153816fd85f_set_name_and_value_to_not_nullable.py): add migration to set `name` and `value` columns in the `variable` table to be not nullable
📝 (AzureOpenAIModel.py): remove unused import `BaseLanguageModel` from `langchain.llms.base`
📝 (ChatLiteLLMModel.py): remove unused import `BaseLanguageModel` from `langflow.field_typing`
📝 (schema.py): remove unused import `BaseMessage` from `langchain_core.messages`
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required and remove `Optional` type
♻️ (model.py): change `name` and `value` fields in `VariableBase` model to be required

📝 (App.tsx): Remove unused import statement
♻️ (App.tsx): Refactor code to use destructuring assignment for imported functions
♻️ (App.tsx): Refactor code to use arrow function syntax for event handlers
♻️ (App.tsx): Refactor code to use template literals for console log message
📝 (addNewVariableButton.tsx): Remove unused import statement
♻️ (addNewVariableButton.tsx): Refactor code to use destructuring assignment for imported functions
♻️ (addNewVariableButton.tsx): Refactor code to use arrow function syntax for event handlers
♻️ (addNewVariableButton.tsx): Refactor code to use template literals for console log message
♻️ (dropdownComponent/index.tsx): Refactor code to use destructuring assignment for useRef
♻️ (dropdownComponent/index.tsx): Refactor code to use ternary operator for PopoverContentDropdown
♻️ (dropdownComponent/index.tsx): Refactor code to use template literals for style property
♻️ (index.ts): Refactor code to use destructuring assignment for imported functions
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters
♻️ (index.ts): Refactor code to use template literals for URL
♻️ (index.ts): Refactor code to use destructuring assignment for function parameters

📝 (index.tsx): update CardDescription in ShortcutsPage to improve code readability and remove unnecessary line break
📝 (routes.tsx): remove unused import of ProfileSettingsPage in routes.tsx
♻️ (flowsManagerStore.ts): refactor useFlowsManagerStore to improve code readability and maintainability by extracting common code into a separate function
♻️ (globalVariables.ts): refactor useGlobalVariablesStore to improve code readability and maintainability by removing unused code and using object instead of Set for unavaliableFields
♻️ (typesStore.ts): refactor useTypesStore to improve code readability and maintainability by removing unused imports and formatting code
♻️ (globalVariables/index.ts): refactor GlobalVariablesStore to use object instead of Set for unavaliableFields
♻️ (reactflowUtils.ts): refactor extractFieldsFromComponenents to improve code readability and maintainability by using object instead of Set for fields

✨ (utils.ts): add new function getUnavailableFields to retrieve unavailable fields from variables object
📝 (utils.ts): add comments to explain the purpose of the upperCaseWords and checkUpperWords functions
This commit is contained in:
cristhianzl 2024-04-30 15:10:04 -03:00
commit 2326ae9a0f
24 changed files with 222 additions and 81 deletions

View file

@ -22,7 +22,6 @@ depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: def upgrade() -> None:
conn = op.get_bind() conn = op.get_bind()
inspector = Inspector.from_engine(conn) # type: ignore inspector = Inspector.from_engine(conn) # type: ignore
table_names = inspector.get_table_names()
# ### commands auto generated by Alembic - please adjust! ### # ### commands auto generated by Alembic - please adjust! ###
column_names = [column["name"] for column in inspector.get_columns("variable")] column_names = [column["name"] for column in inspector.get_columns("variable")]
with op.batch_alter_table("variable", schema=None) as batch_op: with op.batch_alter_table("variable", schema=None) as batch_op:
@ -35,7 +34,6 @@ def upgrade() -> None:
def downgrade() -> None: def downgrade() -> None:
conn = op.get_bind() conn = op.get_bind()
inspector = Inspector.from_engine(conn) # type: ignore inspector = Inspector.from_engine(conn) # type: ignore
table_names = inspector.get_table_names()
# ### commands auto generated by Alembic - please adjust! ### # ### commands auto generated by Alembic - please adjust! ###
column_names = [column["name"] for column in inspector.get_columns("variable")] column_names = [column["name"] for column in inspector.get_columns("variable")]
with op.batch_alter_table("variable", schema=None) as batch_op: with op.batch_alter_table("variable", schema=None) as batch_op:

View file

@ -0,0 +1,52 @@
"""Set name and value to not nullable
Revision ID: c153816fd85f
Revises: 1f4d6df60295
Create Date: 2024-04-30 14:31:23.898995
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
from sqlalchemy.engine.reflection import Inspector
# revision identifiers, used by Alembic.
revision: str = "c153816fd85f"
down_revision: Union[str, None] = "1f4d6df60295"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
conn = op.get_bind()
inspector = Inspector.from_engine(conn) # type: ignore
# ### commands auto generated by Alembic - please adjust! ###
columns = inspector.get_columns("variable")
with op.batch_alter_table("variable", schema=None) as batch_op:
name_column = [column for column in columns if column["name"] == "name"][0]
if name_column and name_column["nullable"]:
batch_op.alter_column("name", existing_type=sa.VARCHAR(), nullable=False)
value_column = [column for column in columns if column["name"] == "value"][0]
if value_column and value_column["nullable"]:
batch_op.alter_column("value", existing_type=sa.VARCHAR(), nullable=False)
# ### end Alembic commands ###
def downgrade() -> None:
conn = op.get_bind()
inspector = Inspector.from_engine(conn) # type: ignore
columns = inspector.get_columns("variable")
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("variable", schema=None) as batch_op:
name_column = [column for column in columns if column["name"] == "name"][0]
if name_column and not name_column["nullable"]:
batch_op.alter_column("name", existing_type=sa.VARCHAR(), nullable=True)
value_column = [column for column in columns if column["name"] == "value"][0]
if value_column and not value_column["nullable"]:
batch_op.alter_column("name", existing_type=sa.VARCHAR(), nullable=True)
# ### end Alembic commands ###

View file

@ -1,6 +1,5 @@
from typing import Optional from typing import Optional
from langchain.llms.base import BaseLanguageModel
from langchain_openai import AzureChatOpenAI from langchain_openai import AzureChatOpenAI
from pydantic.v1 import SecretStr from pydantic.v1 import SecretStr

View file

@ -4,7 +4,7 @@ from langchain_community.chat_models.litellm import ChatLiteLLM, ChatLiteLLMExce
from langflow.base.constants import STREAM_INFO_TEXT from langflow.base.constants import STREAM_INFO_TEXT
from langflow.base.models.model import LCModelComponent from langflow.base.models.model import LCModelComponent
from langflow.field_typing import BaseLanguageModel, Text from langflow.field_typing import Text
class ChatLiteLLMModelComponent(LCModelComponent): class ChatLiteLLMModelComponent(LCModelComponent):

View file

@ -4,7 +4,7 @@ from typing import Literal, Optional
from langchain_core.documents import Document from langchain_core.documents import Document
from langchain_core.messages import BaseMessage from langchain_core.messages import BaseMessage
from pydantic import BaseModel, model_validator from pydantic import BaseModel, model_validator
from langchain_core.messages import HumanMessage, AIMessage, BaseMessage from langchain_core.messages import HumanMessage, AIMessage
class Record(BaseModel): class Record(BaseModel):

View file

@ -13,8 +13,8 @@ def utc_now():
class VariableBase(SQLModel): class VariableBase(SQLModel):
name: Optional[str] = Field(None, description="Name of the variable") name: str = Field(description="Name of the variable")
value: Optional[str] = Field(None, description="Encrypted value of the variable") value: str = Field(description="Encrypted value of the variable")
default_fields: Optional[List[str]] = Field(sa_column=Column(JSON)) default_fields: Optional[List[str]] = Field(sa_column=Column(JSON))
type: Optional[str] = Field(None, description="Type of the variable") type: Optional[str] = Field(None, description="Type of the variable")
@ -52,6 +52,7 @@ class VariableRead(SQLModel):
id: UUID id: UUID
name: Optional[str] = Field(None, description="Name of the variable") name: Optional[str] = Field(None, description="Name of the variable")
type: Optional[str] = Field(None, description="Type of the variable") type: Optional[str] = Field(None, description="Type of the variable")
default_fields: Optional[List[str]] = Field(None, description="Default fields for the variable")
class VariableUpdate(SQLModel): class VariableUpdate(SQLModel):

View file

@ -133,7 +133,7 @@ class DatabaseService(Service):
alembic_cfg = Config(stdout=buffer) alembic_cfg = Config(stdout=buffer)
# alembic_cfg.attributes["connection"] = session # alembic_cfg.attributes["connection"] = session
alembic_cfg.set_main_option("script_location", str(self.script_location)) alembic_cfg.set_main_option("script_location", str(self.script_location))
alembic_cfg.set_main_option("sqlalchemy.url", self.database_url.replace('%', '%%')) alembic_cfg.set_main_option("sqlalchemy.url", self.database_url.replace("%", "%%"))
should_initialize_alembic = False should_initialize_alembic = False
with Session(self.engine) as session: with Session(self.engine) as session:

View file

@ -30,7 +30,14 @@ class VariableService(Service):
if var in os.environ: if var in os.environ:
logger.debug(f"Creating {var} variable from environment.") logger.debug(f"Creating {var} variable from environment.")
try: try:
self.create_variable(user_id, var, os.environ[var], _type="Credential", session=session) self.create_variable(
user_id=user_id,
name=var,
value=os.environ[var],
default_fields=[],
_type="Credential",
session=session,
)
except Exception as e: except Exception as e:
logger.error(f"Error creating {var} variable: {e}") logger.error(f"Error creating {var} variable: {e}")
@ -91,6 +98,7 @@ class VariableService(Service):
user_id: Union[UUID, str], user_id: Union[UUID, str],
name: str, name: str,
value: str, value: str,
default_fields: list[str] = [],
_type: str = "Generic", _type: str = "Generic",
session: Session = Depends(get_session), session: Session = Depends(get_session),
): ):
@ -98,6 +106,7 @@ class VariableService(Service):
name=name, name=name,
type=_type, type=_type,
value=auth_utils.encrypt_api_key(value, settings_service=self.settings_service), value=auth_utils.encrypt_api_key(value, settings_service=self.settings_service),
default_fields=default_fields,
) )
variable = Variable.model_validate(variable_base, from_attributes=True, update={"user_id": user_id}) variable = Variable.model_validate(variable_base, from_attributes=True, update={"user_id": user_id})
session.add(variable) session.add(variable)

View file

@ -0,0 +1 @@
build/*

View file

@ -72,7 +72,7 @@
"start": "vite", "start": "vite",
"build": "vite build", "build": "vite build",
"serve": "vite preview", "serve": "vite preview",
"format": "npx prettier --write \"./**/*.{js,jsx,ts,tsx,json,md}\"", "format": "npx prettier --write \"./**/*.{js,jsx,ts,tsx,json,md}\" --ignore-path .prettierignore",
"type-check": "tsc --noEmit --pretty --project tsconfig.json && vite" "type-check": "tsc --noEmit --pretty --project tsconfig.json && vite"
}, },
"eslintConfig": { "eslintConfig": {

View file

@ -22,7 +22,6 @@ import useFlowsManagerStore from "./stores/flowsManagerStore";
import { useGlobalVariablesStore } from "./stores/globalVariables"; import { useGlobalVariablesStore } from "./stores/globalVariables";
import { useStoreStore } from "./stores/storeStore"; import { useStoreStore } from "./stores/storeStore";
import { useTypesStore } from "./stores/typesStore"; import { useTypesStore } from "./stores/typesStore";
export default function App() { export default function App() {
const removeFromTempNotificationList = useAlertStore( const removeFromTempNotificationList = useAlertStore(
(state) => state.removeFromTempNotificationList (state) => state.removeFromTempNotificationList
@ -48,6 +47,9 @@ export default function App() {
const setGlobalVariables = useGlobalVariablesStore( const setGlobalVariables = useGlobalVariablesStore(
(state) => state.setGlobalVariables (state) => state.setGlobalVariables
); );
const setUnavailableFields = useGlobalVariablesStore(
(state) => state.setUnavaliableFields
);
const checkHasStore = useStoreStore((state) => state.checkHasStore); const checkHasStore = useStoreStore((state) => state.checkHasStore);
const navigate = useNavigate(); const navigate = useNavigate();
const dark = useDarkStore((state) => state.dark); const dark = useDarkStore((state) => state.dark);

View file

@ -3,6 +3,7 @@ import { registerGlobalVariable } from "../../controllers/API";
import BaseModal from "../../modals/baseModal"; import BaseModal from "../../modals/baseModal";
import useAlertStore from "../../stores/alertStore"; import useAlertStore from "../../stores/alertStore";
import { useGlobalVariablesStore } from "../../stores/globalVariables"; import { useGlobalVariablesStore } from "../../stores/globalVariables";
import { useTypesStore } from "../../stores/typesStore";
import { ResponseErrorDetailAPI } from "../../types/api"; import { ResponseErrorDetailAPI } from "../../types/api";
import ForwardedIconComponent from "../genericIconComponent"; import ForwardedIconComponent from "../genericIconComponent";
import InputComponent from "../inputComponent"; import InputComponent from "../inputComponent";
@ -10,27 +11,39 @@ import { Button } from "../ui/button";
import { Input } from "../ui/input"; import { Input } from "../ui/input";
import { Label } from "../ui/label"; import { Label } from "../ui/label";
import { Textarea } from "../ui/textarea"; import { Textarea } from "../ui/textarea";
import { useTypesStore } from "../../stores/typesStore";
//TODO IMPLEMENT FORM LOGIC //TODO IMPLEMENT FORM LOGIC
export default function AddNewVariableButton({ children }): JSX.Element { export default function AddNewVariableButton({ children }): JSX.Element {
const [key, setKey] = useState(""); const [key, setKey] = useState("");
const [value, setValue] = useState(""); const [value, setValue] = useState("");
const [type, setType] = useState(""); const [type, setType] = useState("Generic");
const [fields, setFields] = useState<string[]>([]); const [fields, setFields] = useState<string[]>([]);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const setErrorData = useAlertStore((state) => state.setErrorData); const setErrorData = useAlertStore((state) => state.setErrorData);
const componentFields = useTypesStore((state) => state.ComponentFields); const componentFields = useTypesStore((state) => state.ComponentFields);
const unavaliableFields =new Set(Object.keys(useGlobalVariablesStore(
(state) => state.unavaliableFields
)));
const availableFields = Array.from(componentFields).filter(
(field) => !unavaliableFields.has(field)
);
const addGlobalVariable = useGlobalVariablesStore( const addGlobalVariable = useGlobalVariablesStore(
(state) => state.addGlobalVariable (state) => state.addGlobalVariable
); );
function handleSaveVariable() { function handleSaveVariable() {
let data: { name: string; value: string; type?: string; default_fields?: string[] } = { let data: {
name: string;
value: string;
type?: string;
default_fields?: string[];
} = {
name: key, name: key,
type, type,
value, value,
default_fields: fields default_fields: fields,
}; };
registerGlobalVariable(data) registerGlobalVariable(data)
.then((res) => { .then((res) => {
@ -39,6 +52,7 @@ export default function AddNewVariableButton({ children }): JSX.Element {
setKey(""); setKey("");
setValue(""); setValue("");
setType(""); setType("");
setFields([]);
setOpen(false); setOpen(false);
}) })
.catch((error) => { .catch((error) => {
@ -98,8 +112,8 @@ export default function AddNewVariableButton({ children }): JSX.Element {
setSelectedOptions={(value) => setFields(value)} setSelectedOptions={(value) => setFields(value)}
selectedOptions={fields} selectedOptions={fields}
password={false} password={false}
options={Array.from(componentFields)} options={availableFields}
placeholder="Choose a type for the variable..." placeholder="Choose a field for the variable..."
></InputComponent> ></InputComponent>
</div> </div>
</BaseModal.Content> </BaseModal.Content>

View file

@ -33,7 +33,9 @@ export default function Dropdown({
const refButton = useRef<HTMLButtonElement>(null); const refButton = useRef<HTMLButtonElement>(null);
const PopoverContentDropdown = children ? PopoverContent : PopoverContentWithoutPortal; const PopoverContentDropdown = children
? PopoverContent
: PopoverContentWithoutPortal;
return ( return (
<> <>
@ -77,7 +79,11 @@ export default function Dropdown({
)} )}
<PopoverContentDropdown <PopoverContentDropdown
className="nocopy nowheel nopan nodelete nodrag noundo p-0" className="nocopy nowheel nopan nodelete nodrag noundo p-0"
style={children ? {} : { minWidth: refButton?.current?.clientWidth ?? "200px" }} style={
children
? {}
: { minWidth: refButton?.current?.clientWidth ?? "200px" }
}
> >
<Command> <Command>
<CommandInput placeholder="Search options..." className="h-9" /> <CommandInput placeholder="Search options..." className="h-9" />

View file

@ -860,13 +860,14 @@ export async function requestLogout() {
} }
export async function getGlobalVariables(): Promise<{ export async function getGlobalVariables(): Promise<{
[key: string]: { id: string; type: string }; [key: string]: { id: string; type: string; default_fields: string[] };
}> { }> {
const globalVariables = {}; const globalVariables = {};
(await api.get(`${BASE_URL_API}variables/`)).data.forEach((element) => { (await api.get(`${BASE_URL_API}variables/`)).data.forEach((element) => {
globalVariables[element.name] = { globalVariables[element.name] = {
id: element.id, id: element.id,
type: element.type, type: element.type,
default_fields: element.default_fields,
}; };
}); });
return globalVariables; return globalVariables;
@ -876,34 +877,31 @@ export async function registerGlobalVariable({
name, name,
value, value,
type, type,
default_fields=[], default_fields = [],
}: { }: {
name: string; name: string;
value: string; value: string;
type?: string; type?: string;
default_fields?: string[]; default_fields?: string[];
}): Promise<AxiosResponse<{ name: string; id: string; type: string }>> { }): Promise<AxiosResponse<{ name: string; id: string; type: string }>> {
try{ try {
const response = await api.post(`${BASE_URL_API}variables/`, { const response = await api.post(`${BASE_URL_API}variables/`, {
name, name,
value, value,
type, type,
default_fields:default_fields default_fields: default_fields,
}); });
return response; return response;
} } catch (error) {
catch(error){
throw error; throw error;
} }
} }
export async function deleteGlobalVariable(id: string) { export async function deleteGlobalVariable(id: string) {
try{ try {
const response = await api.delete(`${BASE_URL_API}variables/${id}`); const response = await api.delete(`${BASE_URL_API}variables/${id}`);
return response; return response;
} } catch (error) {
catch(error){
throw error; throw error;
} }
} }
@ -913,18 +911,16 @@ export async function updateGlobalVariable(
value: string, value: string,
id: string id: string
) { ) {
try{ try {
const response = api.patch(`${BASE_URL_API}variables/${id}`, { const response = api.patch(`${BASE_URL_API}variables/${id}`, {
name, name,
value, value,
}); });
return response; return response;
} } catch (error) {
catch(error){
throw error; throw error;
} }
} }
export async function getVerticesOrder( export async function getVerticesOrder(

View file

@ -37,17 +37,29 @@ export default function GlobalVariablesPage() {
<div></div> <div></div>
); );
}; };
const [rowData, setRowData] =
useState<{ type: string | undefined; id: string; name: string }[]>(); const [rowData, setRowData] = useState<
{
type: string | undefined;
id: string;
name: string;
default_fields: string | undefined;
}[]
>();
useEffect(() => { useEffect(() => {
const rows: Array<{ type: string | undefined; id: string; name: string }> = const rows: Array<{
[]; type: string | undefined;
id: string;
name: string;
default_fields: string | undefined;
}> = [];
globalVariablesEntries.forEach((e) => { globalVariablesEntries.forEach((e) => {
const globalVariableObj = globalVariables[e]; const globalVariableObj = globalVariables[e];
rows.push({ rows.push({
type: globalVariableObj.type, type: globalVariableObj.type,
id: globalVariableObj.id, id: globalVariableObj.id,
default_fields: (globalVariableObj.default_fields ?? []).join(", "),
name: e, name: e,
}); });
}); });
@ -81,15 +93,15 @@ export default function GlobalVariablesPage() {
flex: 1, flex: 1,
editable: false, editable: false,
}, },
{ // {
field: "value", // field: "value",
cellEditor: "agLargeTextCellEditor", // cellEditor: "agLargeTextCellEditor",
flex: 2, // flex: 2,
editable: false, // editable: false,
}, // },
{ {
headerName: "Apply To Fields", headerName: "Apply To Fields",
field: "defaultFields", field: "default_fields",
flex: 1, flex: 1,
editable: false, editable: false,
}, },

View file

@ -124,9 +124,7 @@ export default function ShortcutsPage() {
<Card x-chunk="dashboard-04-chunk-2"> <Card x-chunk="dashboard-04-chunk-2">
<CardHeader> <CardHeader>
<CardTitle>Flow</CardTitle> <CardTitle>Flow</CardTitle>
<CardDescription> <CardDescription>Shortcuts relating to the flow.</CardDescription>
Shortcuts relating to the flow.
</CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<TableComponent <TableComponent

View file

@ -11,7 +11,6 @@ import ApiKeysPage from "./pages/ApiKeysPage";
import FlowPage from "./pages/FlowPage"; import FlowPage from "./pages/FlowPage";
import HomePage from "./pages/MainPage"; import HomePage from "./pages/MainPage";
import ComponentsComponent from "./pages/MainPage/components/components"; import ComponentsComponent from "./pages/MainPage/components/components";
import ProfileSettingsPage from "./pages/ProfileSettingsPage";
import SettingsPage from "./pages/SettingsPage"; import SettingsPage from "./pages/SettingsPage";
import GeneralPage from "./pages/SettingsPage/pages/GeneralPage"; import GeneralPage from "./pages/SettingsPage/pages/GeneralPage";
import GlobalVariablesPage from "./pages/SettingsPage/pages/GlobalVariablesPage"; import GlobalVariablesPage from "./pages/SettingsPage/pages/GlobalVariablesPage";

View file

@ -83,7 +83,10 @@ const useFlowsManagerStore = create<FlowsManagerStoreType>((set, get) => ({
); );
useTypesStore.setState((state) => ({ useTypesStore.setState((state) => ({
data: { ...state.data, ["saved_components"]: data }, data: { ...state.data, ["saved_components"]: data },
ComponentFields: extractFieldsFromComponenents({...state.data, ["saved_components"]: data }), ComponentFields: extractFieldsFromComponenents({
...state.data,
["saved_components"]: data,
}),
})); }));
set({ isLoading: false }); set({ isLoading: false });
resolve(); resolve();
@ -199,7 +202,10 @@ const useFlowsManagerStore = create<FlowsManagerStoreType>((set, get) => ({
set({ isLoading: false }); set({ isLoading: false });
useTypesStore.setState((state) => ({ useTypesStore.setState((state) => ({
data: { ...state.data, ["saved_components"]: data }, data: { ...state.data, ["saved_components"]: data },
ComponentFields: extractFieldsFromComponenents({...state.data, ["saved_components"]: data }), ComponentFields: extractFieldsFromComponenents({
...state.data,
["saved_components"]: data,
}),
})); }));
}, 200); }, 200);
// addFlowToLocalState(newFlow); // addFlowToLocalState(newFlow);
@ -222,7 +228,10 @@ const useFlowsManagerStore = create<FlowsManagerStoreType>((set, get) => ({
set({ isLoading: false }); set({ isLoading: false });
useTypesStore.setState((state) => ({ useTypesStore.setState((state) => ({
data: { ...state.data, ["saved_components"]: data }, data: { ...state.data, ["saved_components"]: data },
ComponentFields: extractFieldsFromComponenents({...state.data, ["saved_components"]: data }), ComponentFields: extractFieldsFromComponenents({
...state.data,
["saved_components"]: data,
}),
})); }));
// Return the id // Return the id
@ -252,7 +261,10 @@ const useFlowsManagerStore = create<FlowsManagerStoreType>((set, get) => ({
set({ isLoading: false }); set({ isLoading: false });
useTypesStore.setState((state) => ({ useTypesStore.setState((state) => ({
data: { ...state.data, ["saved_components"]: data }, data: { ...state.data, ["saved_components"]: data },
ComponentFields: extractFieldsFromComponenents({...state.data, ["saved_components"]: data }), ComponentFields: extractFieldsFromComponenents({
...state.data,
["saved_components"]: data,
}),
})); }));
resolve(); resolve();
}); });

View file

@ -1,17 +1,17 @@
import { create } from "zustand"; import { create } from "zustand";
import { GlobalVariablesStore } from "../types/zustand/globalVariables"; import { GlobalVariablesStore } from "../types/zustand/globalVariables";
import { getUnavailableFields } from "../utils/utils";
export const useGlobalVariablesStore = create<GlobalVariablesStore>( export const useGlobalVariablesStore = create<GlobalVariablesStore>(
(set, get) => ({ (set, get) => ({
unavaliableFields: new Set(), unavaliableFields: {},
setUnavaliableFields: (fields) => { setUnavaliableFields: (fields) => {
set({ unavaliableFields: fields }); set({ unavaliableFields: fields });
}, },
addUnavaliableField: (field) => {
set({ unavaliableFields: get().unavaliableFields.add(field) });
},
removeUnavaliableField: (field) => { removeUnavaliableField: (field) => {
get().unavaliableFields.delete(field); const newFields = get().unavaliableFields;
delete newFields[field];
set({ unavaliableFields: newFields });
}, },
globalVariablesEntries: [], globalVariablesEntries: [],
globalVariables: {}, globalVariables: {},
@ -19,6 +19,7 @@ export const useGlobalVariablesStore = create<GlobalVariablesStore>(
set({ set({
globalVariables: variables, globalVariables: variables,
globalVariablesEntries: Object.keys(variables), globalVariablesEntries: Object.keys(variables),
unavaliableFields: getUnavailableFields(variables),
}); });
}, },
addGlobalVariable: (name, id, type, default_fields) => { addGlobalVariable: (name, id, type, default_fields) => {
@ -27,17 +28,18 @@ export const useGlobalVariablesStore = create<GlobalVariablesStore>(
set({ set({
globalVariables: newVariables, globalVariables: newVariables,
globalVariablesEntries: Object.keys(newVariables), globalVariablesEntries: Object.keys(newVariables),
unavaliableFields: getUnavailableFields(newVariables),
}); });
}, },
removeGlobalVariable: async (name) => { removeGlobalVariable: async (name) => {
const id = get().globalVariables[name]?.id; const id = get().globalVariables[name]?.id;
if (id === undefined) return; if (id === undefined) return;
const newVariables = { ...get().globalVariables }; const newVariables = { ...get().globalVariables };
delete newVariables[name]; delete newVariables[name];
set({ set({
globalVariables: newVariables, globalVariables: newVariables,
globalVariablesEntries: Object.keys(newVariables), globalVariablesEntries: Object.keys(newVariables),
unavaliableFields: getUnavailableFields(newVariables),
}); });
}, },
getVariableId: (name) => { getVariableId: (name) => {

View file

@ -2,7 +2,11 @@ import { create } from "zustand";
import { getAll } from "../controllers/API"; import { getAll } from "../controllers/API";
import { APIDataType } from "../types/api"; import { APIDataType } from "../types/api";
import { TypesStoreType } from "../types/zustand/types"; import { TypesStoreType } from "../types/zustand/types";
import { extractFieldsFromComponenents, templatesGenerator, typesGenerator } from "../utils/reactflowUtils"; import {
extractFieldsFromComponenents,
templatesGenerator,
typesGenerator,
} from "../utils/reactflowUtils";
import useAlertStore from "./alertStore"; import useAlertStore from "./alertStore";
import useFlowsManagerStore from "./flowsManagerStore"; import useFlowsManagerStore from "./flowsManagerStore";
@ -28,7 +32,10 @@ export const useTypesStore = create<TypesStoreType>((set, get) => ({
set((old) => ({ set((old) => ({
types: typesGenerator(data), types: typesGenerator(data),
data: { ...old.data, ...data }, data: { ...old.data, ...data },
ComponentFields: extractFieldsFromComponenents({ ...old.data, ...data }), ComponentFields: extractFieldsFromComponenents({
...old.data,
...data,
}),
templates: templatesGenerator(data), templates: templatesGenerator(data),
})); }));
setLoading(false); setLoading(false);
@ -50,7 +57,7 @@ export const useTypesStore = create<TypesStoreType>((set, get) => ({
}, },
setData: (change: APIDataType | ((old: APIDataType) => APIDataType)) => { setData: (change: APIDataType | ((old: APIDataType) => APIDataType)) => {
let newChange = typeof change === "function" ? change(get().data) : change; let newChange = typeof change === "function" ? change(get().data) : change;
set({ data: newChange}); set({ data: newChange });
get().setComponentFields(extractFieldsFromComponenents(newChange)); get().setComponentFields(extractFieldsFromComponenents(newChange));
}, },
})); }));

View file

@ -1,14 +1,31 @@
export type GlobalVariablesStore = { export type GlobalVariablesStore = {
globalVariablesEntries: Array<string>; globalVariablesEntries: Array<string>;
globalVariables: { [name: string]: { id: string; type?: string, default_fields?: string[] } }; globalVariables: {
[name: string]: {
id: string;
type?: string;
default_fields?: string[];
value?: string;
};
};
setGlobalVariables: (variables: { setGlobalVariables: (variables: {
[name: string]: { id: string; type?: string, default_fields?: string[]}; [name: string]: {
id: string;
type?: string;
default_fields?: string[];
value?: string;
};
}) => void; }) => void;
addGlobalVariable: (name: string, id: string, type?: string, default_fields?: string[]) => void; addGlobalVariable: (
name: string,
id: string,
type?: string,
default_fields?: string[],
value?: string
) => void;
removeGlobalVariable: (name: string) => Promise<void>; removeGlobalVariable: (name: string) => Promise<void>;
getVariableId: (name: string) => string | undefined; getVariableId: (name: string) => string | undefined;
unavaliableFields: Set<string>; unavaliableFields: {[name: string]: string};
setUnavaliableFields: (fields: Set<string>) => void; setUnavaliableFields: (fields: {[name: string]: string}) => void;
addUnavaliableField: (field: string) => void;
removeUnavaliableField: (field: string) => void; removeUnavaliableField: (field: string) => void;
}; };

View file

@ -1234,17 +1234,19 @@ export function templatesGenerator(data: APIObjectType) {
}, {}); }, {});
} }
export function extractFieldsFromComponenents(data:APIObjectType ) { export function extractFieldsFromComponenents(data: APIObjectType) {
const fields = new Set<string>(); const fields = new Set<string>();
Object.keys(data).forEach((key) => { Object.keys(data).forEach((key) => {
Object.keys(data[key]).forEach((kind) => { Object.keys(data[key]).forEach((kind) => {
Object.keys(data[key][kind].template).forEach((field) => { Object.keys(data[key][kind].template).forEach((field) => {
if(data[key][kind].template[field].display_name && data[key][kind].template[field].show) if (
data[key][kind].template[field].display_name &&
data[key][kind].template[field].show
)
fields.add(data[key][kind].template[field].display_name!); fields.add(data[key][kind].template[field].display_name!);
}); });
}); });
}); });
console.log(fields);
return fields; return fields;
} }

View file

@ -91,6 +91,20 @@ export function toTitleCase(
.join(" "); .join(" ");
} }
export function getUnavailableFields(variables: {
[key: string]: { default_fields?: string[] };
}): {[name: string]: string} {
const unVariables:{[name: string]: string} = {};
Object.keys(variables).forEach((key) => {
if (variables[key].default_fields) {
variables[key].default_fields!.forEach((field) => {
unVariables[field] = key;
});
}
});
return unVariables;
}
export const upperCaseWords: string[] = ["llm", "uri"]; export const upperCaseWords: string[] = ["llm", "uri"];
export function checkUpperWords(str: string): string { export function checkUpperWords(str: string): string {
const words = str.split(" ").map((word) => { const words = str.split(" ").map((word) => {