📝 (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:
conn = op.get_bind()
inspector = Inspector.from_engine(conn) # type: ignore
table_names = inspector.get_table_names()
# ### commands auto generated by Alembic - please adjust! ###
column_names = [column["name"] for column in inspector.get_columns("variable")]
with op.batch_alter_table("variable", schema=None) as batch_op:
@ -35,7 +34,6 @@ def upgrade() -> None:
def downgrade() -> None:
conn = op.get_bind()
inspector = Inspector.from_engine(conn) # type: ignore
table_names = inspector.get_table_names()
# ### commands auto generated by Alembic - please adjust! ###
column_names = [column["name"] for column in inspector.get_columns("variable")]
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 langchain.llms.base import BaseLanguageModel
from langchain_openai import AzureChatOpenAI
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.models.model import LCModelComponent
from langflow.field_typing import BaseLanguageModel, Text
from langflow.field_typing import Text
class ChatLiteLLMModelComponent(LCModelComponent):

View file

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

View file

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

View file

@ -133,7 +133,7 @@ class DatabaseService(Service):
alembic_cfg = Config(stdout=buffer)
# alembic_cfg.attributes["connection"] = session
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
with Session(self.engine) as session:

View file

@ -30,7 +30,14 @@ class VariableService(Service):
if var in os.environ:
logger.debug(f"Creating {var} variable from environment.")
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:
logger.error(f"Error creating {var} variable: {e}")
@ -91,6 +98,7 @@ class VariableService(Service):
user_id: Union[UUID, str],
name: str,
value: str,
default_fields: list[str] = [],
_type: str = "Generic",
session: Session = Depends(get_session),
):
@ -98,6 +106,7 @@ class VariableService(Service):
name=name,
type=_type,
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})
session.add(variable)

View file

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

View file

@ -72,7 +72,7 @@
"start": "vite",
"build": "vite build",
"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"
},
"eslintConfig": {

View file

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

View file

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

View file

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

View file

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

View file

@ -16,16 +16,16 @@ export default function SettingsPage(): JSX.Element {
const sidebarNavItems = [
{
title: "General",
href: "/settings/general",
icon: (
<ForwardedIconComponent
name="SlidersHorizontal"
className="mx-[0.08rem] w-[1.1rem] stroke-[1.5]"
/>
),
},
/* {
title: "General",
href: "/settings/general",
icon: (
<ForwardedIconComponent
name="SlidersHorizontal"
className="mx-[0.08rem] w-[1.1rem] stroke-[1.5]"
/>
),
},
/* {
title: "Theme",
href: "/settings/theme",
icon: (

View file

@ -37,17 +37,29 @@ export default function GlobalVariablesPage() {
<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(() => {
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) => {
const globalVariableObj = globalVariables[e];
rows.push({
type: globalVariableObj.type,
id: globalVariableObj.id,
default_fields: (globalVariableObj.default_fields ?? []).join(", "),
name: e,
});
});
@ -81,15 +93,15 @@ export default function GlobalVariablesPage() {
flex: 1,
editable: false,
},
{
field: "value",
cellEditor: "agLargeTextCellEditor",
flex: 2,
editable: false,
},
// {
// field: "value",
// cellEditor: "agLargeTextCellEditor",
// flex: 2,
// editable: false,
// },
{
headerName: "Apply To Fields",
field: "defaultFields",
field: "default_fields",
flex: 1,
editable: false,
},

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,14 +1,31 @@
export type GlobalVariablesStore = {
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: {
[name: string]: { id: string; type?: string, default_fields?: string[]};
[name: string]: {
id: string;
type?: string;
default_fields?: string[];
value?: string;
};
}) => 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>;
getVariableId: (name: string) => string | undefined;
unavaliableFields: Set<string>;
setUnavaliableFields: (fields: Set<string>) => void;
addUnavaliableField: (field: string) => void;
unavaliableFields: {[name: string]: string};
setUnavaliableFields: (fields: {[name: string]: 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>();
Object.keys(data).forEach((key) => {
Object.keys(data[key]).forEach((kind) => {
Object.keys(data[key][kind].template).forEach((field) => {
if(data[key][kind].template[field].display_name && data[key][kind].template[field].show)
fields.add(data[key][kind].template[field].display_name!);
if (
data[key][kind].template[field].display_name &&
data[key][kind].template[field].show
)
fields.add(data[key][kind].template[field].display_name!);
});
});
});
console.log(fields);
return fields;
}

View file

@ -91,6 +91,20 @@ export function toTitleCase(
.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 function checkUpperWords(str: string): string {
const words = str.split(" ").map((word) => {