Merge branch 'develop' into status-bug-fix

This commit is contained in:
Shams
2023-05-04 19:31:38 +02:00
committed by GitHub
118 changed files with 3441 additions and 616 deletions

View File

@@ -23,10 +23,22 @@ to start.
## Working on existing issues
Before you get started working on an
[issue](https://github.com/rowyio/rowy/issues), please make sure to share that
you are working on it by commenting on the issue and posting a message on
#contributions channel in Rowy's
[Discord](https://discord.com/invite/fjBugmvzZP). The maintainers will then
assign the issue to you after making sure any relevant information or context in
addition is provided before you can start on the task.
Before you get started working on an [issue](https://github.com/rowyio/rowy/issues), please make sure to share that you are working on it by commenting on the issue and posting a message on #contributions channel in Rowy's [Discord](https://rowy.io/discord). The maintainers will then assign the issue to you after making sure any relevant information or context in addition is provided before you can start on the task.
Once you are assigned a task, please provide periodic updates or share any
questions or roadblocks on either discord or the Github issue, so that the
commmunity or the project maintainers can provide you any feedback or guidance
as needed. If you are inactive for more than 1-2 week on a issue that was
assigned to you, then we will assume you have stopped working on it and we will
unassign it from you - so that we can give a chance to others in the community
to work on it.
Once you are assigned a task, please provide periodic updates or share any questions or roadblocks on either discord or the Github issue, so that the commmunity or the project maintainers can provide you any feedback or guidance as needed. If you are inactive for more than 1-2 week on a issue that was assigned to you, then we will assume you have stopped working on it and we will unassign it from you - so that we can give a chance to others in the community to work on it.
## File a feature request

View File

@@ -33,6 +33,7 @@ Low-code for Firebase and Google Cloud.
## Features ✨
<!-- <table>
<tr>
<th>

View File

@@ -23,6 +23,7 @@ import useKeyPressWithAtom from "@src/hooks/useKeyPressWithAtom";
import TableGroupRedirectPage from "./pages/TableGroupRedirectPage";
import SignOutPage from "@src/pages/Auth/SignOutPage";
import ProvidedArraySubTablePage from "./pages/Table/ProvidedArraySubTablePage";
// prettier-ignore
const AuthPage = lazy(() => import("@src/pages/Auth/AuthPage" /* webpackChunkName: "AuthPage" */));
@@ -134,6 +135,27 @@ export default function App() {
}
/>
</Route>
<Route path={ROUTES.arraySubTable}>
<Route index element={<NotFound />} />
<Route
path=":docPath/:subTableKey"
element={
<Suspense
fallback={
<Backdrop
key="sub-table-modal-backdrop"
open
sx={{ zIndex: "modal" }}
>
<Loading />
</Backdrop>
}
>
<ProvidedArraySubTablePage />
</Suspense>
}
/>
</Route>
</Route>
</Route>

View File

@@ -0,0 +1,9 @@
import SvgIcon, { SvgIconProps } from "@mui/material/SvgIcon";
export function ArraySubTable(props: SvgIconProps) {
return (
<SvgIcon {...props}>
<path d="M1 4C1 2.34315 2.34315 1 4 1H18C19.6569 1 21 2.34315 21 4V11H19H12V15V17H4C2.34315 17 1 15.6569 1 14V4ZM10 15V11H3V14C3 14.5523 3.44772 15 4 15H10ZM12 9H19V5H12V9ZM10 5H3V9H10V5ZM15 13H14V14V22V23H15H17V21H16V15H17V13H15ZM21 13H22V14V22V23H21H19V21H20V15H19V13H21Z" />
</SvgIcon>
);
}

View File

@@ -133,3 +133,16 @@ export const FunctionsIndexAtom = atom<FunctionSettings[]>([]);
export const updateFunctionAtom = atom<
UpdateCollectionDocFunction<FunctionSettings> | undefined
>(undefined);
export interface ISecretNames {
loading: boolean;
secretNames: null | string[];
}
export const secretNamesAtom = atom<ISecretNames>({
loading: true,
secretNames: null,
});
export const updateSecretNamesAtom = atom<
((clearSecretNames?: boolean) => Promise<void>) | undefined
>(undefined);

View File

@@ -147,10 +147,6 @@ export const tableSettingsDialogSchemaAtom = atom(async (get) => {
/** Open the Get Started checklist from anywhere */
export const getStartedChecklistAtom = atom(false);
/** Persist the state of the add row ID type */
export const tableAddRowIdTypeAtom = atomWithStorage<
"decrement" | "random" | "custom"
>("__ROWY__ADD_ROW_ID_TYPE", "decrement");
/** Persist when the user dismissed the row out of order warning */
export const tableOutOfOrderDismissedAtom = atomWithStorage(
"__ROWY__OUT_OF_ORDER_TOOLTIP_DISMISSED",

View File

@@ -494,7 +494,11 @@ describe("deleteRow", () => {
} = renderHook(() => useSetAtom(deleteRowAtom, tableScope));
expect(deleteRow).toBeDefined();
await act(() => deleteRow(TEST_COLLECTION + "/row2"));
await act(() =>
deleteRow({
path: TEST_COLLECTION + "/row2",
})
);
const {
result: { current: tableRows },
@@ -510,7 +514,11 @@ describe("deleteRow", () => {
} = renderHook(() => useSetAtom(deleteRowAtom, tableScope));
expect(deleteRow).toBeDefined();
await act(() => deleteRow(TEST_COLLECTION + "/rowLocal2"));
await act(() =>
deleteRow({
path: TEST_COLLECTION + "/rowLocal2",
})
);
const {
result: { current: tableRows },
@@ -527,9 +535,9 @@ describe("deleteRow", () => {
expect(deleteRow).toBeDefined();
await act(() =>
deleteRow(
["row1", "row2", "row8"].map((id) => TEST_COLLECTION + "/" + id)
)
deleteRow({
path: ["row1", "row2", "row8"].map((id) => TEST_COLLECTION + "/" + id),
})
);
const {
@@ -548,7 +556,11 @@ describe("deleteRow", () => {
} = renderHook(() => useSetAtom(deleteRowAtom, tableScope));
expect(deleteRow).toBeDefined();
await act(() => deleteRow(generatedRows.map((row) => row._rowy_ref.path)));
await act(() =>
deleteRow({
path: generatedRows.map((row) => row._rowy_ref.path),
})
);
const {
result: { current: tableRows },
@@ -563,7 +575,11 @@ describe("deleteRow", () => {
} = renderHook(() => useSetAtom(deleteRowAtom, tableScope));
expect(deleteRow).toBeDefined();
await act(() => deleteRow("nonExistent"));
await act(() =>
deleteRow({
path: "nonExistent",
})
);
const {
result: { current: tableRows },
@@ -578,7 +594,11 @@ describe("deleteRow", () => {
} = renderHook(() => useSetAtom(deleteRowAtom, tableScope));
expect(deleteRow).toBeDefined();
await act(() => deleteRow("nonExistent"));
await act(() =>
deleteRow({
path: "nonExistent",
})
);
const {
result: { current: tableRows },

View File

@@ -22,7 +22,11 @@ import {
_bulkWriteDbAtom,
} from "./table";
import { TableRow, BulkWriteFunction } from "@src/types/table";
import {
TableRow,
BulkWriteFunction,
ArrayTableRowData,
} from "@src/types/table";
import {
rowyUser,
generateId,
@@ -211,7 +215,17 @@ export const addRowAtom = atom(
*/
export const deleteRowAtom = atom(
null,
async (get, set, path: string | string[]) => {
async (
get,
set,
{
path,
options,
}: {
path: string | string[];
options?: ArrayTableRowData;
}
) => {
const deleteRowDb = get(_deleteRowDbAtom);
if (!deleteRowDb) throw new Error("Cannot write to database");
@@ -223,9 +237,9 @@ export const deleteRowAtom = atom(
find(tableRowsLocal, ["_rowy_ref.path", path])
);
if (isLocalRow) set(tableRowsLocalAtom, { type: "delete", path });
// Always delete from db in case it exists
await deleteRowDb(path);
// *options* are passed in case of array table to target specific row
await deleteRowDb(path, options);
if (auditChange) auditChange("DELETE_ROW", path);
};
@@ -242,10 +256,15 @@ export interface IBulkAddRowsOptions {
rows: Partial<TableRow[]>;
collection: string;
onBatchCommit?: Parameters<BulkWriteFunction>[1];
type?: "add";
}
export const bulkAddRowsAtom = atom(
null,
async (get, _, { rows, collection, onBatchCommit }: IBulkAddRowsOptions) => {
async (
get,
_,
{ rows, collection, onBatchCommit, type }: IBulkAddRowsOptions
) => {
const bulkWriteDb = get(_bulkWriteDbAtom);
if (!bulkWriteDb) throw new Error("Cannot write to database");
const tableSettings = get(tableSettingsAtom);
@@ -277,7 +296,11 @@ export const bulkAddRowsAtom = atom(
// Assign a random ID to each row
const operations = rows.map((row) => ({
type: row?._rowy_ref?.id ? ("update" as "update") : ("add" as "add"),
type: type
? type
: row?._rowy_ref?.id
? ("update" as "update")
: ("add" as "add"),
path: `${collection}/${row?._rowy_ref?.id ?? generateId()}`,
data: { ...initialValues, ...omitRowyFields(row) },
}));
@@ -312,6 +335,8 @@ export interface IUpdateFieldOptions {
useArrayUnion?: boolean;
/** Optionally, uses firestore's arrayRemove with the given value. Removes given value items from the existing array */
useArrayRemove?: boolean;
/** Optionally, used to locate the row in ArraySubTable. */
arrayTableData?: ArrayTableRowData;
}
/**
* Set function updates or deletes a field in a row.
@@ -339,6 +364,7 @@ export const updateFieldAtom = atom(
disableCheckEquality,
useArrayUnion,
useArrayRemove,
arrayTableData,
}: IUpdateFieldOptions
) => {
const updateRowDb = get(_updateRowDbAtom);
@@ -352,9 +378,17 @@ export const updateFieldAtom = atom(
const tableRows = get(tableRowsAtom);
const tableRowsLocal = get(tableRowsLocalAtom);
const row = find(tableRows, ["_rowy_ref.path", path]);
const row = find(
tableRows,
arrayTableData?.index !== undefined
? ["_rowy_ref.arrayTableData.index", arrayTableData?.index]
: ["_rowy_ref.path", path]
);
if (!row) throw new Error("Could not find row");
const isLocalRow = Boolean(find(tableRowsLocal, ["_rowy_ref.path", path]));
const isLocalRow =
fieldName.startsWith("_rowy_formulaValue_") ||
Boolean(find(tableRowsLocal, ["_rowy_ref.path", path]));
const update: Partial<TableRow> = {};
@@ -387,7 +421,12 @@ export const updateFieldAtom = atom(
...(row[fieldName] ?? []),
...localUpdate[fieldName],
];
dbUpdate[fieldName] = arrayUnion(...dbUpdate[fieldName]);
// if we are updating a row of ArraySubTable
if (arrayTableData?.index !== undefined) {
dbUpdate[fieldName] = localUpdate[fieldName];
} else {
dbUpdate[fieldName] = arrayUnion(...dbUpdate[fieldName]);
}
}
//apply arrayRemove
@@ -400,8 +439,15 @@ export const updateFieldAtom = atom(
row[fieldName] ?? [],
(el) => !find(localUpdate[fieldName], el)
);
dbUpdate[fieldName] = arrayRemove(...dbUpdate[fieldName]);
// if we are updating a row of ArraySubTable
if (arrayTableData?.index !== undefined) {
dbUpdate[fieldName] = localUpdate[fieldName];
} else {
dbUpdate[fieldName] = arrayRemove(...dbUpdate[fieldName]);
}
}
// need to pass the index of the row to updateRowDb
// Check for required fields
const newRowValues = updateRowData(cloneDeep(row), dbUpdate);
@@ -423,6 +469,14 @@ export const updateFieldAtom = atom(
deleteFields: deleteField ? [fieldName] : [],
});
// TODO(han): Formula field persistence
// const config = find(tableColumnsOrdered, (c) => {
// const [, key] = fieldName.split("_rowy_formulaValue_");
// return c.key === key;
// });
// if(!config.persist) return;
if (fieldName.startsWith("_rowy_formulaValue")) return;
// If it has no missingRequiredFields, also write to db
// And write entire row to handle the case where it doesnt exist in db yet
if (missingRequiredFields.length === 0) {
@@ -431,7 +485,8 @@ export const updateFieldAtom = atom(
await updateRowDb(
row._rowy_ref.path,
omitRowyFields(newRowValues),
deleteField ? [fieldName] : []
deleteField ? [fieldName] : [],
arrayTableData
);
}
}
@@ -440,7 +495,8 @@ export const updateFieldAtom = atom(
await updateRowDb(
row._rowy_ref.path,
omitRowyFields(dbUpdate),
deleteField ? [fieldName] : []
deleteField ? [fieldName] : [],
arrayTableData
);
}

View File

@@ -134,6 +134,7 @@ export type SelectedCell = {
path: string | "_rowy_header";
columnKey: string | "_rowy_row_actions";
focusInside: boolean;
arrayIndex?: number; // for array sub table
};
/** Store selected cell in table. Used in side drawer and context menu */
export const selectedCellAtom = atom<SelectedCell | null>(null);

View File

@@ -19,8 +19,7 @@ import firebaseStorageDefs from "!!raw-loader!./firebaseStorage.d.ts";
import utilsDefs from "!!raw-loader!./utils.d.ts";
import rowyUtilsDefs from "!!raw-loader!./rowy.d.ts";
import extensionsDefs from "!!raw-loader!./extensions.d.ts";
import { runRoutes } from "@src/constants/runRoutes";
import { rowyRunAtom, projectScope } from "@src/atoms/projectScope";
import { projectScope, secretNamesAtom } from "@src/atoms/projectScope";
import { getFieldProp } from "@src/components/fields";
export interface IUseMonacoCustomizationsProps {
@@ -53,8 +52,8 @@ export default function useMonacoCustomizations({
const theme = useTheme();
const monaco = useMonaco();
const [tableRows] = useAtom(tableRowsAtom, tableScope);
const [rowyRun] = useAtom(rowyRunAtom, projectScope);
const [tableColumnsOrdered] = useAtom(tableColumnsOrderedAtom, tableScope);
const [secretNames] = useAtom(secretNamesAtom, projectScope);
useEffect(() => {
return () => {
@@ -206,26 +205,6 @@ export default function useMonacoCustomizations({
//}
};
const setSecrets = async () => {
// set secret options
try {
const listSecrets = await rowyRun({
route: runRoutes.listSecrets,
});
const secretsDef = `type SecretNames = ${listSecrets
.map((secret: string) => `"${secret}"`)
.join(" | ")}
enum secrets {
${listSecrets
.map((secret: string) => `${secret} = "${secret}"`)
.join("\n")}
}
`;
monaco?.languages.typescript.javascriptDefaults.addExtraLib(secretsDef);
} catch (error) {
console.error("Could not set secret definitions: ", error);
}
};
//TODO: types
const setBaseDefinitions = () => {
const rowDefinition =
@@ -275,14 +254,24 @@ export default function useMonacoCustomizations({
} catch (error) {
console.error("Could not set basic", error);
}
// set available secrets from secretManager
try {
setSecrets();
} catch (error) {
console.error("Could not set secrets: ", error);
}
}, [monaco, tableColumnsOrdered]);
useEffect(() => {
if (!monaco) return;
if (secretNames.loading) return;
if (!secretNames.secretNames) return;
const secretsDef = `type SecretNames = ${secretNames.secretNames
.map((secret: string) => `"${secret}"`)
.join(" | ")}
enum secrets {
${secretNames.secretNames
.map((secret: string) => `${secret} = "${secret}"`)
.join("\n")}
}
`;
monaco?.languages.typescript.javascriptDefaults.addExtraLib(secretsDef);
}, [monaco, secretNames]);
let boxSx: SystemStyleObject<Theme> = {
minWidth: 400,
minHeight,

View File

@@ -43,6 +43,7 @@ export default function ColorPickerInput({
const [localValue, setLocalValue] = useState(value);
const [width, setRef] = useResponsiveWidth();
const theme = useTheme();
const isDark = theme.palette.mode === "dark" ? true : false;
return (
<Box
@@ -61,6 +62,9 @@ export default function ColorPickerInput({
boxSizing: "unset",
},
},
".rcp-dark": {
"--rcp-background": "transparent",
},
},
]}
>
@@ -70,6 +74,7 @@ export default function ColorPickerInput({
color={localValue}
onChange={(color) => setLocalValue(color)}
onChangeComplete={onChangeComplete}
dark={isDark}
/>
</Box>
);

View File

@@ -78,7 +78,7 @@ export default function ColumnConfigModal({
) {
setShowRebuildPrompt(true);
}
const updatedConfig = set({ ...newConfig }, key, update);
const updatedConfig = set(newConfig, key, update); // Modified by @devsgnr, spread operator `{...newConfig}` instead of just `newConfig` was preventing multiple calls from running properly
setNewConfig(updatedConfig);
validateSettings();
};

View File

@@ -54,22 +54,24 @@ function CodeEditor({ type, column, handleChange }: ICodeEditorProps) {
dynamicValueFn = column.config?.defaultValue?.dynamicValueFn;
} else if (column.config?.defaultValue?.script) {
dynamicValueFn = `const dynamicValueFn: DefaultValue = async ({row,ref,db,storage,auth,logging})=>{
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("dynamicValueFn started")
${column.config?.defaultValue.script}
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`;
} else {
dynamicValueFn = `const dynamicValueFn: DefaultValue = async ({row,ref,db,storage,auth,logging})=>{
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("dynamicValueFn started")
dynamicValueFn = `// Import any NPM package needed
// import _ from "lodash";
const defaultValue: DefaultValue = async ({ row, ref, db, storage, auth, logging }) => {
logging.log("dynamicValueFn started");
// Example: generate random hex color
// const color = "#" + Math.floor(Math.random() * 16777215).toString(16);
// return color;
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`;
};
export default defaultValue;
`;
}
return (

View File

@@ -11,6 +11,7 @@ import {
projectSettingsAtom,
rowyRunModalAtom,
} from "@src/atoms/projectScope";
import { tableScope, tableSettingsAtom } from "@src/atoms/tableScope";
export interface IFieldsDropdownProps {
value: FieldType | "";
@@ -35,17 +36,22 @@ export default function FieldsDropdown({
}: IFieldsDropdownProps) {
const [projectSettings] = useAtom(projectSettingsAtom, projectScope);
const openRowyRunModal = useSetAtom(rowyRunModalAtom, projectScope);
const [tableSettings] = useAtom(tableSettingsAtom, tableScope);
const fieldTypesToDisplay = optionsProp
? FIELDS.filter((fieldConfig) => optionsProp.indexOf(fieldConfig.type) > -1)
: FIELDS;
const options = fieldTypesToDisplay.map((fieldConfig) => {
const requireCloudFunctionSetup =
fieldConfig.requireCloudFunction && !projectSettings.rowyRunUrl;
const requireCollectionTable =
tableSettings.isCollection === false &&
fieldConfig.requireCollectionTable === true;
return {
label: fieldConfig.name,
value: fieldConfig.type,
disabled: requireCloudFunctionSetup,
disabled: requireCloudFunctionSetup || requireCollectionTable,
requireCloudFunctionSetup,
requireCollectionTable,
};
});
@@ -82,7 +88,18 @@ export default function FieldsDropdown({
{getFieldProp("icon", option.value as FieldType)}
</ListItemIcon>
<Typography>{option.label}</Typography>
{option.requireCloudFunctionSetup && (
{option.requireCollectionTable ? (
<Typography
color="error"
variant="inherit"
component="span"
marginLeft={1}
className={"require-cloud-function"}
>
{" "}
Unavailable
</Typography>
) : option.requireCloudFunctionSetup ? (
<Typography
color="error"
variant="inherit"
@@ -107,7 +124,7 @@ export default function FieldsDropdown({
Cloud Function
</span>
</Typography>
)}
) : null}
</>
)}
label={label || "Field type"}

View File

@@ -1,26 +1,39 @@
import { Chip, ChipProps } from "@mui/material";
import palette, { paletteToMui } from "@src/theme/palette";
import { useTheme } from "@mui/material";
import { isEqual } from "lodash-es";
export const VARIANTS = ["yes", "no", "maybe"] as const;
const paletteColor = {
yes: "success",
maybe: "warning",
no: "error",
yes: paletteToMui(palette.green),
maybe: paletteToMui(palette.yellow),
no: paletteToMui(palette.aRed),
} as const;
// TODO: Create a more generalised solution for this
// Switched to a more generalized solution - adding backwards compatibility to maintain [Yes, No, Maybe] colors even if no color is selected
// Modified by @devsgnr
export default function FormattedChip(props: ChipProps) {
const defaultColor = paletteToMui(palette.aGray);
const { mode } = useTheme().palette;
const fallback = { backgroundColor: defaultColor[mode] };
const { sx, ...newProps } = props;
const label =
typeof props.label === "string" ? props.label.toLowerCase() : "";
const inVariant = VARIANTS.includes(label as any);
if (VARIANTS.includes(label as any)) {
return (
<Chip
size="small"
color={paletteColor[label as typeof VARIANTS[number]]}
{...props}
/>
);
}
return <Chip size="small" {...props} />;
return (
<Chip
size="small"
sx={
inVariant && isEqual(props.sx, fallback)
? {
backgroundColor:
paletteColor[label as typeof VARIANTS[number]][mode],
}
: props.sx
}
{...newProps}
/>
);
}

View File

@@ -80,6 +80,9 @@ export default function GetStartedChecklist({
marginRight: `max(env(safe-area-inset-right), 8px)`,
width: 360,
},
".MuiStepLabel-iconContainer.Mui-active svg": {
transform: "rotate(0deg) !important",
},
},
]}
>

View File

@@ -0,0 +1,109 @@
import { FC, useEffect, useState } from "react";
import Button from "@mui/material/Button";
import Box from "@mui/material/Box";
import Grid from "@mui/material/Grid";
import { Chip, Typography } from "@mui/material";
import Modal from "@src/components/Modal";
import ColorPickerInput from "@src/components/ColorPickerInput";
import { toColor } from "react-color-palette";
import { SelectColorThemeOptions } from ".";
interface CustomizeColor {
currentColor: SelectColorThemeOptions;
onChange: (value: SelectColorThemeOptions) => void;
}
const CustomizeColorModal: FC<CustomizeColor> = ({
currentColor,
onChange,
}) => {
const [color, setColor] = useState<SelectColorThemeOptions>(currentColor);
/* Update color value onFocus */
useEffect(() => {
setColor(currentColor);
}, [currentColor]);
/* Pass value to the onChange function */
const handleChange = (color: SelectColorThemeOptions) => {
setColor(color);
onChange(color);
};
/* MUI Specific state */
const [open, setOpen] = useState<boolean>(false);
/* MUI Menu event handlers */
const handleClick = () => setOpen(true);
const handleClose = () => setOpen(false);
return (
<div>
<Button size="small" color="success" variant="text" onClick={handleClick}>
Customise
</Button>
<Modal
title="Customize Color"
aria-labelledby="custom-color-picker-modal"
aria-describedby="custom-color-picker-modal"
open={open}
onClose={handleClose}
disableBackdropClick
>
<Box display="grid" gridTemplateColumns="repeat(6, 1fr)" gap={1}>
{/* Light Theme Customize Color */}
<Box gridColumn="span 3">
<ColorPickerInput
value={toColor("hex", color.light)}
onChangeComplete={(value) =>
handleChange({ ...color, ...{ light: value.hex } })
}
/>
<Grid container gap={1} py={1} px={2} alignItems="center">
<Grid item>
<Typography fontSize={13} fontWeight="light">
Light Theme
</Typography>
</Grid>
<Grid item>
<Chip
component="small"
size="small"
label="Option 1"
sx={{ backgroundColor: color.light, color: "black" }}
/>
</Grid>
</Grid>
</Box>
{/* Dark Theme Customize Color */}
<Box gridColumn="span 3">
<ColorPickerInput
value={toColor("hex", color.dark)}
onChangeComplete={(value) =>
handleChange({ ...color, ...{ dark: value.hex } })
}
/>
<Grid container gap={1} py={1} px={2} alignItems="center">
<Grid item>
<Typography fontSize={13} fontWeight="light">
Dark Theme
</Typography>
</Grid>
<Grid item>
<Chip
component="small"
size="small"
label="Option 1"
sx={{ backgroundColor: color.dark, color: "white" }}
/>
</Grid>
</Grid>
</Box>
</Box>
</Modal>
</div>
);
};
export default CustomizeColorModal;

View File

@@ -0,0 +1,192 @@
import { FC, useState } from "react";
import Button from "@mui/material/Button";
import Box from "@mui/material/Box";
import Menu from "@mui/material/Menu";
import Grid from "@mui/material/Grid";
import { Chip, Divider, Typography, useTheme } from "@mui/material";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import FormatColorResetIcon from "@mui/icons-material/FormatColorReset";
import { paletteToMui, palette } from "@src/theme/palette";
import CustomizeColorModal from "./CustomizeColorModal";
export interface SelectColorThemeOptions {
light: string;
dark: string;
}
interface IColorSelect {
handleChange: (value: SelectColorThemeOptions) => void;
initialValue: SelectColorThemeOptions;
}
const ColorSelect: FC<IColorSelect> = ({ handleChange, initialValue }) => {
/* Get current theme */
const theme = useTheme();
const mode = theme.palette.mode;
/* Palette - reset paletter to object */
const palettes = Object({
gray: palette.aGray,
blue: palette.blue,
red: palette.aRed,
green: palette.green,
yellow: palette.yellow,
pink: palette.pink,
teal: palette.teal,
tangerine: palette.tangerine,
orange: palette.orange,
cyan: palette.cyan,
amber: palette.amber,
lightGreen: palette.lightGreen,
lightBlue: palette.lightBlue,
purple: palette.purple,
});
/* Hold the current state of a given option defaults to `gray` from the color palette */
const [color, setColor] = useState<SelectColorThemeOptions>(
initialValue || paletteToMui(palette["gray"])
);
const onChange = (color: SelectColorThemeOptions) => {
setColor(color);
handleChange(color);
};
/* MUI Specific state for color context menu */
const [colorSelectAnchor, setColorSelectAnchor] =
useState<null | HTMLElement>(null);
const open = Boolean(colorSelectAnchor);
/* MUI Menu event handlers for color context menu */
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setColorSelectAnchor(event.currentTarget);
};
const handleClose = () => {
setColorSelectAnchor(null);
};
return (
<div>
<Button
sx={{ margin: "7.5px 0", width: "auto" }}
size="small"
id="color-picker-btn"
aria-controls={open ? "color-picker-menu" : undefined}
aria-haspopup="true"
aria-expanded={open ? "true" : undefined}
variant="outlined"
disableElevation
onClick={handleClick}
endIcon={<KeyboardArrowDownIcon />}
>
<Box
m={0.5}
sx={{
width: 20,
height: 20,
borderRadius: 100,
backgroundColor: color[mode],
}}
/>
</Button>
{/* Menu */}
<Menu
sx={{ marginTop: 0.5 }}
anchorOrigin={{
vertical: "bottom",
horizontal: "left",
}}
transformOrigin={{
vertical: "top",
horizontal: "left",
}}
id="color-picker-menu"
MenuListProps={{
"aria-labelledby": "color-pick-btn",
}}
anchorEl={colorSelectAnchor}
open={open}
onClose={handleClose}
>
<Typography
fontSize={11}
color="secondary"
py={1}
px={2}
fontWeight="bold"
>
COLOURS
</Typography>
<Grid
container
py={1}
px={2}
rowGap={2}
columnGap={2}
display="grid"
gridTemplateColumns="repeat(7, auto)"
>
{Object.keys(palettes).map((key: string, index: number) => (
<Grid item xs sx={{ maxWidth: "fit-content" }}>
<Button
sx={{
minWidth: "25px",
minHeight: "25px",
backgroundColor: paletteToMui(palettes[key])[mode],
borderRadius: 100,
"&:hover": {
backgroundColor: paletteToMui(palettes[key])[mode],
},
}}
size="small"
onClick={() => onChange(paletteToMui(palettes[key]))}
key={index}
/>
</Grid>
))}
</Grid>
<Box pt={1} px={2}>
<CustomizeColorModal
currentColor={color}
onChange={(color) => onChange(color)}
/>
</Box>
<Box px={2} py={2}>
<Button
size="small"
sx={{ borderRadius: 100 }}
fullWidth
startIcon={<FormatColorResetIcon />}
onClick={() => onChange(paletteToMui(palettes["gray"]))}
>
Reset
</Button>
</Box>
<Divider />
<Grid container gap={1} py={1} px={2} alignItems="center">
<Grid item>
<Typography fontSize={13} fontWeight="light">
Preview
</Typography>
</Grid>
<Grid item>
<Chip
component="small"
size="small"
label="Option 1"
sx={{ backgroundColor: color[mode] }}
/>
</Grid>
</Grid>
</Menu>
</div>
);
};
export default ColorSelect;

View File

@@ -46,15 +46,18 @@ export default function UserItem({
const [value, setValue] = useState(Array.isArray(rolesProp) ? rolesProp : []);
const allRoles = new Set(["ADMIN", ...(projectRoles ?? []), ...value]);
const hasRowyRun = !!projectSettings.rowyRunUrl;
const handleSave = async () => {
if (!hasRowyRun) {
openRowyRunModal({ feature: "User Management" });
return;
}
try {
if (!user) throw new Error("User is not defined");
if (JSON.stringify(value) === JSON.stringify(rolesProp)) return;
const loadingSnackbarId = enqueueSnackbar("Setting roles…");
const res = await rowyRun?.({
const res = await rowyRun({
route: runRoutes.setUserRoles,
body: { email: user!.email, roles: value },
});
@@ -91,7 +94,7 @@ export default function UserItem({
);
const handleDelete = async () => {
if (!projectSettings.rowyRunUrl) {
if (!hasRowyRun) {
openRowyRunModal({ feature: "User Management" });
return;
}

View File

@@ -35,6 +35,7 @@ export interface IFieldWrapperProps {
fieldName?: string;
label?: React.ReactNode;
debugText?: React.ReactNode;
debugValue?: React.ReactNode;
disabled?: boolean;
hidden?: boolean;
index?: number;
@@ -46,6 +47,7 @@ export default function FieldWrapper({
fieldName,
label,
debugText,
debugValue,
disabled,
hidden,
index,
@@ -100,7 +102,7 @@ export default function FieldWrapper({
<ErrorBoundary FallbackComponent={InlineErrorFallback}>
<Suspense fallback={<FieldSkeleton />}>
{children ??
(!debugText && (
(!debugValue && (
<Typography
variant="body2"
color="text.secondary"
@@ -112,7 +114,7 @@ export default function FieldWrapper({
</Suspense>
</ErrorBoundary>
{debugText && (
{debugValue && (
<Stack direction="row" alignItems="center">
<Typography
variant="body2"
@@ -131,7 +133,7 @@ export default function FieldWrapper({
</Typography>
<IconButton
onClick={() => {
copyToClipboard(debugText as string);
copyToClipboard(debugValue as string);
enqueueSnackbar("Copied!");
}}
>
@@ -139,7 +141,7 @@ export default function FieldWrapper({
</IconButton>
<IconButton
href={`https://console.firebase.google.com/project/${projectId}/firestore/data/~2F${(
debugText as string
debugValue as string
).replace(/\//g, "~2F")}`}
target="_blank"
rel="noopener"

View File

@@ -6,6 +6,7 @@ import FieldWrapper from "./FieldWrapper";
import { IFieldConfig } from "@src/components/fields/types";
import { getFieldProp } from "@src/components/fields";
import { ColumnConfig, TableRowRef } from "@src/types/table";
import { TableRow } from "@src/types/table";
export interface IMemoizedFieldProps {
field: ColumnConfig;
@@ -16,6 +17,7 @@ export interface IMemoizedFieldProps {
isDirty: boolean;
onDirty: (fieldName: string) => void;
onSubmit: (fieldName: string, value: any) => void;
row: TableRow;
}
export const MemoizedField = memo(
@@ -28,6 +30,7 @@ export const MemoizedField = memo(
isDirty,
onDirty,
onSubmit,
row,
...props
}: IMemoizedFieldProps) {
const [localValue, setLocalValue, localValueRef] = useStateRef(value);
@@ -40,11 +43,7 @@ export const MemoizedField = memo(
onSubmit(field.fieldName, localValueRef.current);
}, [field.fieldName, localValueRef, onSubmit]);
// Derivative/aggregate field support
let type = field.type;
if (field.config && field.config.renderFieldType) {
type = field.config.renderFieldType;
}
const fieldComponent: IFieldConfig["SideDrawerField"] = getFieldProp(
"SideDrawerField",
@@ -78,6 +77,7 @@ export const MemoizedField = memo(
},
onSubmit: handleSubmit,
disabled,
row,
})}
</FieldWrapper>
);

View File

@@ -30,11 +30,21 @@ export default function SideDrawer() {
const [cell, setCell] = useAtom(selectedCellAtom, tableScope);
const [open, setOpen] = useAtom(sideDrawerOpenAtom, tableScope);
const selectedRow = find(tableRows, ["_rowy_ref.path", cell?.path]);
const selectedCellRowIndex = findIndex(tableRows, [
"_rowy_ref.path",
cell?.path,
]);
const selectedRow = find(
tableRows,
cell?.arrayIndex === undefined
? ["_rowy_ref.path", cell?.path]
: // if the table is an array table, we need to use the array index to find the row
["_rowy_ref.arrayTableData.index", cell?.arrayIndex]
);
const selectedCellRowIndex = findIndex(
tableRows,
cell?.arrayIndex === undefined
? ["_rowy_ref.path", cell?.path]
: // if the table is an array table, we need to use the array index to find the row
["_rowy_ref.arrayTableData.index", cell?.arrayIndex]
);
const handleNavigate = (direction: "up" | "down") => () => {
if (!tableRows || !cell) return;
@@ -45,8 +55,9 @@ export default function SideDrawer() {
setCell((cell) => ({
columnKey: cell!.columnKey,
path: newPath,
path: cell?.arrayIndex !== undefined ? cell.path : newPath,
focusInside: false,
arrayIndex: cell?.arrayIndex !== undefined ? rowIndex : undefined,
}));
};

View File

@@ -66,7 +66,16 @@ export default function SideDrawerFields({ row }: ISideDrawerFieldsProps) {
setSaveState("saving");
try {
await updateField({ path: selectedCell!.path, fieldName, value });
await updateField({
path: selectedCell!.path,
fieldName,
value,
deleteField: undefined,
arrayTableData: {
index: selectedCell.arrayIndex,
},
});
setSaveState("saved");
} catch (e) {
enqueueSnackbar((e as Error).message, { variant: "error" });
@@ -121,6 +130,7 @@ export default function SideDrawerFields({ row }: ISideDrawerFieldsProps) {
onDirty={onDirty}
onSubmit={onSubmit}
isDirty={dirtyField === field.key}
row={row}
/>
))}
@@ -128,7 +138,17 @@ export default function SideDrawerFields({ row }: ISideDrawerFieldsProps) {
type="debug"
fieldName="_rowy_ref.path"
label="Document path"
debugText={row._rowy_ref.path ?? row._rowy_ref.id ?? "No ref"}
debugText={
row._rowy_ref.arrayTableData
? row._rowy_ref.path +
" → " +
row._rowy_ref.arrayTableData.parentField +
"[" +
row._rowy_ref.arrayTableData.index +
"]"
: row._rowy_ref.path
}
debugValue={row._rowy_ref.path ?? row._rowy_ref.id ?? "No ref"}
/>
{userDocHiddenFields.length > 0 && (

View File

@@ -3,12 +3,19 @@ import { Copy as CopyCells } from "@src/assets/icons";
import Paste from "@mui/icons-material/ContentPaste";
import { IFieldConfig } from "@src/components/fields/types";
import { useMenuAction } from "@src/components/Table/useMenuAction";
import { useAtom } from "jotai";
import { tableSchemaAtom, tableScope } from "@src/atoms/tableScope";
import { SUPPORTED_TYPES_PASTE } from "@src/components/Table/useMenuAction";
// TODO: Remove this and add `handlePaste` function to column config
export const BasicContextMenuActions: IFieldConfig["contextMenuActions"] = (
selectedCell,
reset
) => {
const [tableSchema] = useAtom(tableSchemaAtom, tableScope);
const selectedCol = tableSchema.columns?.[selectedCell.columnKey];
const handleClose = async () => await reset?.();
const { handleCopy, handlePaste, cellValue } = useMenuAction(
selectedCell,
@@ -24,9 +31,17 @@ export const BasicContextMenuActions: IFieldConfig["contextMenuActions"] = (
disabled:
cellValue === undefined || cellValue === null || cellValue === "",
},
{ label: "Paste", icon: <Paste />, onClick: handlePaste },
];
if (SUPPORTED_TYPES_PASTE.has(selectedCol?.type)) {
contextMenuActions.push({
label: "Paste",
icon: <Paste />,
onClick: handlePaste,
disabled: false,
});
}
return contextMenuActions;
};

View File

@@ -21,7 +21,6 @@ import {
projectIdAtom,
userRolesAtom,
altPressAtom,
tableAddRowIdTypeAtom,
confirmDialogAtom,
} from "@src/atoms/projectScope";
import {
@@ -34,6 +33,7 @@ import {
deleteRowAtom,
updateFieldAtom,
tableFiltersPopoverAtom,
_updateRowDbAtom,
} from "@src/atoms/tableScope";
import { FieldType } from "@src/constants/fields";
@@ -45,7 +45,6 @@ export default function MenuContents({ onClose }: IMenuContentsProps) {
const [projectId] = useAtom(projectIdAtom, projectScope);
const [userRoles] = useAtom(userRolesAtom, projectScope);
const [altPress] = useAtom(altPressAtom, projectScope);
const [addRowIdType] = useAtom(tableAddRowIdTypeAtom, projectScope);
const confirm = useSetAtom(confirmDialogAtom, projectScope);
const [tableSettings] = useAtom(tableSettingsAtom, tableScope);
const [tableSchema] = useAtom(tableSchemaAtom, tableScope);
@@ -54,27 +53,94 @@ export default function MenuContents({ onClose }: IMenuContentsProps) {
const addRow = useSetAtom(addRowAtom, tableScope);
const deleteRow = useSetAtom(deleteRowAtom, tableScope);
const updateField = useSetAtom(updateFieldAtom, tableScope);
const [updateRowDb] = useAtom(_updateRowDbAtom, tableScope);
const openTableFiltersPopover = useSetAtom(
tableFiltersPopoverAtom,
tableScope
);
const addRowIdType = tableSchema.idType || "decrement";
if (!tableSchema.columns || !selectedCell) return null;
const selectedColumn = tableSchema.columns[selectedCell.columnKey];
const row = find(tableRows, ["_rowy_ref.path", selectedCell.path]);
const row = find(
tableRows,
selectedCell?.arrayIndex === undefined
? ["_rowy_ref.path", selectedCell.path]
: // if the table is an array table, we need to use the array index to find the row
["_rowy_ref.arrayTableData.index", selectedCell.arrayIndex]
);
if (!row) return null;
const actionGroups: IContextMenuItem[][] = [];
const handleDuplicate = () => {
addRow({
row,
setId: addRowIdType === "custom" ? "decrement" : addRowIdType,
});
const _duplicate = () => {
if (row._rowy_ref.arrayTableData !== undefined) {
if (!updateRowDb) return;
return updateRowDb("", {}, undefined, {
index: row._rowy_ref.arrayTableData.index,
operation: {
addRow: "bottom",
base: row,
},
});
}
return addRow({
row: row,
setId: addRowIdType === "custom" ? "decrement" : addRowIdType,
});
};
if (altPress || row._rowy_ref.arrayTableData !== undefined) {
_duplicate();
} else {
confirm({
title: "Duplicate row?",
body: (
<>
Row path:
<br />
<code style={{ userSelect: "all", wordBreak: "break-all" }}>
{row._rowy_ref.path}
</code>
</>
),
confirm: "Duplicate",
handleConfirm: _duplicate,
});
}
};
const handleDelete = () => {
const _delete = () =>
deleteRow({
path: row._rowy_ref.path,
options: row._rowy_ref.arrayTableData,
});
if (altPress || row._rowy_ref.arrayTableData !== undefined) {
_delete();
} else {
confirm({
title: "Delete row?",
body: (
<>
Row path:
<br />
<code style={{ userSelect: "all", wordBreak: "break-all" }}>
{row._rowy_ref.path}
</code>
</>
),
confirm: "Delete",
confirmColor: "error",
handleConfirm: _delete,
});
}
};
const handleDelete = () => deleteRow(row._rowy_ref.path);
const rowActions: IContextMenuItem[] = [
{
label: "Copy ID",
@@ -112,51 +178,14 @@ export default function MenuContents({ onClose }: IMenuContentsProps) {
disabled:
tableSettings.tableType === "collectionGroup" ||
(!userRoles.includes("ADMIN") && tableSettings.readOnly),
onClick: altPress
? handleDuplicate
: () => {
confirm({
title: "Duplicate row?",
body: (
<>
Row path:
<br />
<code style={{ userSelect: "all", wordBreak: "break-all" }}>
{row._rowy_ref.path}
</code>
</>
),
confirm: "Duplicate",
handleConfirm: handleDuplicate,
});
onClose();
},
onClick: handleDuplicate,
},
{
label: altPress ? "Delete" : "Delete…",
color: "error",
icon: <DeleteIcon />,
disabled: !userRoles.includes("ADMIN") && tableSettings.readOnly,
onClick: altPress
? handleDelete
: () => {
confirm({
title: "Delete row?",
body: (
<>
Row path:
<br />
<code style={{ userSelect: "all", wordBreak: "break-all" }}>
{row._rowy_ref.path}
</code>
</>
),
confirm: "Delete",
confirmColor: "error",
handleConfirm: handleDelete,
});
onClose();
},
onClick: handleDelete,
},
];

View File

@@ -34,7 +34,7 @@ export default function EmptyTable() {
: false;
let contents = <></>;
if (hasData) {
if (tableSettings.isCollection !== false && hasData) {
contents = (
<>
<div>
@@ -72,47 +72,56 @@ export default function EmptyTable() {
Get started
</Typography>
<Typography>
There is no data in the Firestore collection:
{tableSettings.isCollection === false
? "There is no data in this Array Sub Table:"
: "There is no data in the Firestore collection:"}
<br />
<code>{tableSettings.collection}</code>
<code>
{tableSettings.collection}
{tableSettings.subTableKey?.length &&
`.${tableSettings.subTableKey}`}
</code>
</Typography>
</div>
<Grid container spacing={1}>
<Grid item xs>
<Typography paragraph>
You can import data from an external source:
</Typography>
{tableSettings.isCollection !== false && (
<>
<Grid item xs>
<Typography paragraph>
You can import data from an external source:
</Typography>
<ImportData
render={(onClick) => (
<Button
variant="contained"
color="primary"
startIcon={<ImportIcon />}
onClick={onClick}
>
Import data
</Button>
)}
PopoverProps={{
anchorOrigin: {
vertical: "bottom",
horizontal: "center",
},
transformOrigin: {
vertical: "top",
horizontal: "center",
},
}}
/>
</Grid>
<ImportData
render={(onClick) => (
<Button
variant="contained"
color="primary"
startIcon={<ImportIcon />}
onClick={onClick}
>
Import data
</Button>
)}
PopoverProps={{
anchorOrigin: {
vertical: "bottom",
horizontal: "center",
},
transformOrigin: {
vertical: "top",
horizontal: "center",
},
}}
/>
</Grid>
<Grid item>
<Divider orientation="vertical">
<Typography variant="overline">or</Typography>
</Divider>
</Grid>
<Grid item>
<Divider orientation="vertical">
<Typography variant="overline">or</Typography>
</Divider>
</Grid>
</>
)}
<Grid item xs>
<Typography paragraph>

View File

@@ -10,7 +10,6 @@ import MenuIcon from "@mui/icons-material/MoreHoriz";
import {
projectScope,
userRolesAtom,
tableAddRowIdTypeAtom,
altPressAtom,
confirmDialogAtom,
} from "@src/atoms/projectScope";
@@ -20,28 +19,90 @@ import {
addRowAtom,
deleteRowAtom,
contextMenuTargetAtom,
_updateRowDbAtom,
tableSchemaAtom,
} from "@src/atoms/tableScope";
export const FinalColumn = memo(function FinalColumn({
row,
focusInsideCell,
}: IRenderedTableCellProps) {
const [userRoles] = useAtom(userRolesAtom, projectScope);
const [addRowIdType] = useAtom(tableAddRowIdTypeAtom, projectScope);
const confirm = useSetAtom(confirmDialogAtom, projectScope);
const [tableSettings] = useAtom(tableSettingsAtom, tableScope);
const [updateRowDb] = useAtom(_updateRowDbAtom, tableScope);
const [tableSchema] = useAtom(tableSchemaAtom, tableScope);
const addRow = useSetAtom(addRowAtom, tableScope);
const deleteRow = useSetAtom(deleteRowAtom, tableScope);
const setContextMenuTarget = useSetAtom(contextMenuTargetAtom, tableScope);
const confirm = useSetAtom(confirmDialogAtom, projectScope);
const [altPress] = useAtom(altPressAtom, projectScope);
const handleDelete = () => deleteRow(row.original._rowy_ref.path);
const handleDelete = () => {
const _delete = () =>
deleteRow({
path: row.original._rowy_ref.path,
options: row.original._rowy_ref.arrayTableData,
});
if (altPress || row.original._rowy_ref.arrayTableData !== undefined) {
_delete();
} else {
confirm({
title: "Delete row?",
body: (
<>
Row path:
<br />
<code style={{ userSelect: "all", wordBreak: "break-all" }}>
{row.original._rowy_ref.path}
</code>
</>
),
confirm: "Delete",
confirmColor: "error",
handleConfirm: _delete,
});
}
};
const addRowIdType = tableSchema.idType || "decrement";
const handleDuplicate = () => {
addRow({
row: row.original,
setId: addRowIdType === "custom" ? "decrement" : addRowIdType,
});
const _duplicate = () => {
if (row.original._rowy_ref.arrayTableData !== undefined) {
if (!updateRowDb) return;
return updateRowDb("", {}, undefined, {
index: row.original._rowy_ref.arrayTableData.index,
operation: {
addRow: "bottom",
base: row.original,
},
});
}
return addRow({
row: row.original,
setId: addRowIdType === "custom" ? "decrement" : addRowIdType,
});
};
if (altPress || row.original._rowy_ref.arrayTableData !== undefined) {
_duplicate();
} else {
confirm({
title: "Duplicate row?",
body: (
<>
Row path:
<br />
<code style={{ userSelect: "all", wordBreak: "break-all" }}>
{row.original._rowy_ref.path}
</code>
</>
),
confirm: "Duplicate",
handleConfirm: _duplicate,
});
}
};
if (!userRoles.includes("ADMIN") && tableSettings.readOnly === true)
@@ -73,28 +134,7 @@ export const FinalColumn = memo(function FinalColumn({
size="small"
color="inherit"
disabled={tableSettings.tableType === "collectionGroup"}
onClick={
altPress
? handleDuplicate
: () => {
confirm({
title: "Duplicate row?",
body: (
<>
Row path:
<br />
<code
style={{ userSelect: "all", wordBreak: "break-all" }}
>
{row.original._rowy_ref.path}
</code>
</>
),
confirm: "Duplicate",
handleConfirm: handleDuplicate,
});
}
}
onClick={handleDuplicate}
className="row-hover-iconButton"
tabIndex={focusInsideCell ? 0 : -1}
>
@@ -106,29 +146,7 @@ export const FinalColumn = memo(function FinalColumn({
<IconButton
size="small"
color="inherit"
onClick={
altPress
? handleDelete
: () => {
confirm({
title: "Delete row?",
body: (
<>
Row path:
<br />
<code
style={{ userSelect: "all", wordBreak: "break-all" }}
>
{row.original._rowy_ref.path}
</code>
</>
),
confirm: "Delete",
confirmColor: "error",
handleConfirm: handleDelete,
});
}
}
onClick={handleDelete}
className="row-hover-iconButton"
tabIndex={focusInsideCell ? 0 : -1}
sx={{

View File

@@ -7,6 +7,7 @@ import EmptyState from "@src/components/EmptyState";
import { FieldType } from "@src/constants/fields";
import { getFieldProp } from "@src/components/fields";
import { DEFAULT_ROW_HEIGHT } from "@src/components/Table";
import useConverter from "@src/components/TableModals/ImportCsvWizard/useConverter";
export interface ICellProps
extends Partial<
@@ -25,12 +26,14 @@ export interface ICellProps
export default function Cell({
field,
type,
value,
value: value_,
name,
rowHeight = DEFAULT_ROW_HEIGHT,
...props
}: ICellProps) {
const tableCell = type ? getFieldProp("TableCell", type) : null;
const { checkAndConvert } = useConverter();
const value = checkAndConvert(value_, type);
return (
<StyledTable>

View File

@@ -211,8 +211,6 @@ export default function Table({
if (result.destination?.index === undefined || !result.draggableId)
return;
console.log(result.draggableId, result.destination.index);
updateColumn({
key: result.draggableId,
index: result.destination.index,

View File

@@ -83,7 +83,7 @@ export const TableBody = memo(function TableBody({
return (
<StyledRow
key={row.id}
key={row.id + row.original._rowy_ref.arrayTableData?.index}
role="row"
aria-rowindex={row.index + 2}
style={{
@@ -102,7 +102,10 @@ export const TableBody = memo(function TableBody({
const isSelectedCell =
selectedCell?.path === row.original._rowy_ref.path &&
selectedCell?.columnKey === cell.column.id;
selectedCell?.columnKey === cell.column.id &&
// if the table is an array sub table, we need to check the array index as well
selectedCell?.arrayIndex ===
row.original._rowy_ref.arrayTableData?.index;
const fieldTypeGroup = getFieldProp(
"group",

View File

@@ -66,6 +66,7 @@ export default function EditorCellController({
fieldName: props.column.fieldName,
value: localValueRef.current,
deleteField: localValueRef.current === undefined,
arrayTableData: props.row?._rowy_ref.arrayTableData,
});
} catch (e) {
enqueueSnackbar((e as Error).message, { variant: "error" });

View File

@@ -123,6 +123,7 @@ export const TableCell = memo(function TableCell({
focusInsideCell,
setFocusInsideCell: (focusInside: boolean) =>
setSelectedCell({
arrayIndex: row.original._rowy_ref.arrayTableData?.index,
path: row.original._rowy_ref.path,
columnKey: cell.column.id,
focusInside,
@@ -166,6 +167,7 @@ export const TableCell = memo(function TableCell({
}}
onClick={(e) => {
setSelectedCell({
arrayIndex: row.original._rowy_ref.arrayTableData?.index,
path: row.original._rowy_ref.path,
columnKey: cell.column.id,
focusInside: false,
@@ -174,6 +176,7 @@ export const TableCell = memo(function TableCell({
}}
onDoubleClick={(e) => {
setSelectedCell({
arrayIndex: row.original._rowy_ref.arrayTableData?.index,
path: row.original._rowy_ref.path,
columnKey: cell.column.id,
focusInside: true,
@@ -183,6 +186,7 @@ export const TableCell = memo(function TableCell({
onContextMenu={(e) => {
e.preventDefault();
setSelectedCell({
arrayIndex: row.original._rowy_ref.arrayTableData?.index,
path: row.original._rowy_ref.path,
columnKey: cell.column.id,
focusInside: false,

View File

@@ -46,8 +46,12 @@ export const TableHeader = memo(function TableHeader({
return (
<DragDropContext onDragEnd={handleDropColumn}>
{headerGroups.map((headerGroup) => (
<Droppable droppableId="droppable-column" direction="horizontal">
{headerGroups.map((headerGroup, _i) => (
<Droppable
key={_i}
droppableId="droppable-column"
direction="horizontal"
>
{(provided) => (
<StyledRow
key={headerGroup.id}

View File

@@ -128,6 +128,11 @@ export function useKeyboardNavigation({
? tableRows[newRowIndex]._rowy_ref.path
: "_rowy_header",
columnKey: leafColumns[newColIndex].id! || leafColumns[0].id!,
arrayIndex:
newRowIndex > -1
? tableRows[newRowIndex]._rowy_ref.arrayTableData?.index
: undefined,
// When selected cell changes, exit current cell
focusInside: false,
};

View File

@@ -15,16 +15,66 @@ import { ColumnConfig } from "@src/types/table";
import { FieldType } from "@src/constants/fields";
const SUPPORTED_TYPES = new Set([
import { format } from "date-fns";
import { DATE_FORMAT, DATE_TIME_FORMAT } from "@src/constants/dates";
import { isDate, isFunction } from "lodash-es";
import { getDurationString } from "@src/components/fields/Duration/utils";
export const SUPPORTED_TYPES_COPY = new Set([
// TEXT
FieldType.shortText,
FieldType.longText,
FieldType.number,
FieldType.email,
FieldType.percentage,
FieldType.phone,
FieldType.richText,
FieldType.email,
FieldType.phone,
FieldType.url,
// SELECT
FieldType.singleSelect,
FieldType.multiSelect,
// NUMERIC
FieldType.checkbox,
FieldType.number,
FieldType.percentage,
FieldType.rating,
FieldType.slider,
FieldType.color,
FieldType.geoPoint,
// DATE & TIME
FieldType.date,
FieldType.dateTime,
FieldType.duration,
// FILE
FieldType.image,
FieldType.file,
// CODE
FieldType.json,
FieldType.code,
FieldType.markdown,
FieldType.array,
// AUDIT
FieldType.createdBy,
FieldType.updatedBy,
FieldType.createdAt,
FieldType.updatedAt,
]);
export const SUPPORTED_TYPES_PASTE = new Set([
// TEXT
FieldType.shortText,
FieldType.longText,
FieldType.richText,
FieldType.email,
FieldType.phone,
FieldType.url,
// NUMERIC
FieldType.number,
FieldType.percentage,
FieldType.rating,
FieldType.slider,
// CODE
FieldType.json,
FieldType.code,
FieldType.markdown,
]);
export function useMenuAction(
@@ -35,15 +85,14 @@ export function useMenuAction(
const [tableSchema] = useAtom(tableSchemaAtom, tableScope);
const [tableRows] = useAtom(tableRowsAtom, tableScope);
const updateField = useSetAtom(updateFieldAtom, tableScope);
const [cellValue, setCellValue] = useState<string | undefined>();
const [cellValue, setCellValue] = useState<any>();
const [selectedCol, setSelectedCol] = useState<ColumnConfig>();
const handleCopy = useCallback(async () => {
try {
if (cellValue !== undefined && cellValue !== null && cellValue !== "") {
await navigator.clipboard.writeText(
typeof cellValue === "object" ? JSON.stringify(cellValue) : cellValue
);
const value = getValue(cellValue);
await navigator.clipboard.writeText(value);
enqueueSnackbar("Copied");
} else {
await navigator.clipboard.writeText("");
@@ -56,21 +105,30 @@ export function useMenuAction(
const handleCut = useCallback(async () => {
try {
if (!selectedCell || !selectedCol || !cellValue) return;
if (!selectedCell || !selectedCol) return;
if (cellValue !== undefined && cellValue !== null && cellValue !== "") {
await navigator.clipboard.writeText(
typeof cellValue === "object" ? JSON.stringify(cellValue) : cellValue
);
const value = getValue(cellValue);
await navigator.clipboard.writeText(value);
enqueueSnackbar("Copied");
} else {
await navigator.clipboard.writeText("");
}
if (cellValue !== undefined)
if (
cellValue !== undefined &&
selectedCol.type !== FieldType.createdAt &&
selectedCol.type !== FieldType.updatedAt &&
selectedCol.type !== FieldType.createdBy &&
selectedCol.type !== FieldType.updatedBy &&
selectedCol.type !== FieldType.checkbox
)
updateField({
path: selectedCell.path,
fieldName: selectedCol.fieldName,
value: undefined,
deleteField: true,
arrayTableData: {
index: selectedCell.arrayIndex,
},
});
} catch (error) {
enqueueSnackbar(`Failed to cut: ${error}`, { variant: "error" });
@@ -92,7 +150,7 @@ export function useMenuAction(
try {
text = await navigator.clipboard.readText();
} catch (e) {
enqueueSnackbar(`Read clilboard permission denied.`, {
enqueueSnackbar(`Read clipboard permission denied.`, {
variant: "error",
});
return;
@@ -111,10 +169,29 @@ export function useMenuAction(
parsed = JSON.parse(text);
break;
}
if (selectedCol.type === FieldType.slider) {
if (parsed < selectedCol.config?.min) parsed = selectedCol.config?.min;
else if (parsed > selectedCol.config?.max)
parsed = selectedCol.config?.max;
}
if (selectedCol.type === FieldType.rating) {
if (parsed < 0) parsed = 0;
if (parsed > (selectedCol.config?.max || 5))
parsed = selectedCol.config?.max || 5;
}
if (selectedCol.type === FieldType.percentage) {
parsed = parsed / 100;
}
updateField({
path: selectedCell.path,
fieldName: selectedCol.fieldName,
value: parsed,
arrayTableData: {
index: selectedCell.arrayIndex,
},
});
} catch (error) {
enqueueSnackbar(
@@ -130,32 +207,129 @@ export function useMenuAction(
const selectedCol = tableSchema.columns?.[selectedCell.columnKey];
if (!selectedCol) return setCellValue("");
setSelectedCol(selectedCol);
const selectedRow = find(tableRows, ["_rowy_ref.path", selectedCell.path]);
const selectedRow = find(
tableRows,
selectedCell.arrayIndex === undefined
? ["_rowy_ref.path", selectedCell.path]
: // if the table is an array table, we need to use the array index to find the row
["_rowy_ref.arrayTableData.index", selectedCell.arrayIndex]
);
setCellValue(get(selectedRow, selectedCol.fieldName));
}, [selectedCell, tableSchema, tableRows]);
const checkEnabled = useCallback(
const checkEnabledCopy = useCallback(
(func: Function) => {
if (!selectedCol) {
return function () {
enqueueSnackbar(`No selected cell`, {
variant: "error",
});
};
}
const fieldType = getFieldType(selectedCol);
return function () {
if (SUPPORTED_TYPES.has(selectedCol?.type)) {
if (SUPPORTED_TYPES_COPY.has(fieldType)) {
return func();
} else {
enqueueSnackbar(`${fieldType} field cannot be copied`, {
variant: "error",
});
}
};
},
[enqueueSnackbar, selectedCol?.type]
);
const checkEnabledPaste = useCallback(
(func: Function) => {
if (!selectedCol) {
return function () {
enqueueSnackbar(`No selected cell`, {
variant: "error",
});
};
}
const fieldType = getFieldType(selectedCol);
return function () {
if (SUPPORTED_TYPES_PASTE.has(fieldType)) {
return func();
} else {
enqueueSnackbar(
`${selectedCol?.type} field cannot be copied using keyboard shortcut`,
`${fieldType} field does not support paste functionality`,
{
variant: "info",
variant: "error",
}
);
}
};
},
[selectedCol]
[enqueueSnackbar, selectedCol?.type]
);
const getValue = useCallback(
(cellValue: any) => {
switch (selectedCol?.type) {
case FieldType.percentage:
return cellValue * 100;
case FieldType.json:
case FieldType.color:
case FieldType.geoPoint:
return JSON.stringify(cellValue);
case FieldType.date:
if (
(!!cellValue && isFunction(cellValue.toDate)) ||
isDate(cellValue)
) {
try {
return format(
isDate(cellValue) ? cellValue : cellValue.toDate(),
selectedCol.config?.format || DATE_FORMAT
);
} catch (e) {
return;
}
}
return;
case FieldType.dateTime:
case FieldType.createdAt:
case FieldType.updatedAt:
if (
(!!cellValue && isFunction(cellValue.toDate)) ||
isDate(cellValue)
) {
try {
return format(
isDate(cellValue) ? cellValue : cellValue.toDate(),
selectedCol.config?.format || DATE_TIME_FORMAT
);
} catch (e) {
return;
}
}
return;
case FieldType.duration:
return getDurationString(
cellValue.start.toDate(),
cellValue.end.toDate()
);
case FieldType.image:
case FieldType.file:
return cellValue[0].downloadURL;
case FieldType.createdBy:
case FieldType.updatedBy:
return cellValue.displayName;
default:
return cellValue;
}
},
[cellValue, selectedCol]
);
return {
handleCopy: checkEnabled(handleCopy),
handleCut: checkEnabled(handleCut),
handlePaste: handlePaste,
handleCopy: checkEnabledCopy(handleCopy),
handleCut: checkEnabledCopy(handleCut),
handlePaste: checkEnabledPaste(handlePaste),
cellValue,
};
}

View File

@@ -33,6 +33,27 @@ const selectedColumnsJsonReducer =
(doc: TableRow) =>
(accumulator: Record<string, any>, currentColumn: ColumnConfig) => {
const value = get(doc, currentColumn.key);
if (
currentColumn.type === FieldType.file ||
currentColumn.type === FieldType.image
) {
return {
...accumulator,
[currentColumn.key]: value
? value
.map((item: { downloadURL: string }) => item.downloadURL)
.join()
: "",
};
}
if (currentColumn.type === FieldType.reference) {
return {
...accumulator,
[currentColumn.key]: value ? value.path : "",
};
}
return {
...accumulator,
[currentColumn.key]: value,

View File

@@ -62,7 +62,7 @@ export const triggerTypes: ExtensionTrigger[] = ["create", "update", "delete"];
const extensionBodyTemplate = {
task: `const extensionBody: TaskBody = async({row, db, change, ref, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("extensionBody started")
// Import any NPM package needed
@@ -90,10 +90,10 @@ const extensionBodyTemplate = {
else console.error(result)
})
*/
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
docSync: `const extensionBody: DocSyncBody = async({row, db, change, ref, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("extensionBody started")
return ({
@@ -101,20 +101,20 @@ const extensionBodyTemplate = {
row: row, // object of data to sync, usually the row itself
targetPath: "", // fill in the path here
})
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
historySnapshot: `const extensionBody: HistorySnapshotBody = async({row, db, change, ref, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("extensionBody started")
return ({
trackedFields: [], // a list of string of column names
collectionId: "historySnapshots", // optionally change the sub-collection id of where the history snapshots are stored
})
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
algoliaIndex: `const extensionBody: AlgoliaIndexBody = async({row, db, change, ref, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("extensionBody started")
return ({
@@ -123,34 +123,34 @@ const extensionBodyTemplate = {
index: "", // algolia index to sync to
objectID: ref.id, // algolia object ID, ref.id is one possible choice
})
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
meiliIndex: `const extensionBody: MeiliIndexBody = async({row, db, change, ref, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("extensionBody started")
return({
fieldsToSync: [], // a list of string of column names
row: row, // object of data to sync, usually the row itself
index: "", // algolia index to sync to
objectID: ref.id, // algolia object ID, ref.id is one possible choice
index: "", // meili search index to sync to
objectID: ref.id, // meili search object ID, ref.id is one possible choice
})
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
bigqueryIndex: `const extensionBody: BigqueryIndexBody = async({row, db, change, ref, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("extensionBody started")
return ({
fieldsToSync: [], // a list of string of column names
row: row, // object of data to sync, usually the row itself
index: "", // algolia index to sync to
objectID: ref.id, // algolia object ID, ref.id is one possible choice
index: "", // bigquery dataset to sync to
objectID: ref.id, // bigquery object ID, ref.id is one possible choice
})
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
slackMessage: `const extensionBody: SlackMessageBody = async({row, db, change, ref, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("extensionBody started")
// Import any NPM package needed
@@ -162,10 +162,10 @@ const extensionBodyTemplate = {
text: "", // the text parameter to pass in to slack api
attachments: [], // the attachments parameter to pass in to slack api
})
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
sendgridEmail: `const extensionBody: SendgridEmailBody = async({row, db, change, ref, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("extensionBody started")
// Import any NPM package needed
@@ -187,10 +187,10 @@ const extensionBodyTemplate = {
// add any other custom args you want to pass to sendgrid events here
},
})
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
apiCall: `const extensionBody: ApiCallBody = async({row, db, change, ref, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("extensionBody started")
// Import any NPM package needed
@@ -202,10 +202,10 @@ const extensionBodyTemplate = {
method: "",
callback: ()=>{},
})
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
twilioMessage: `const extensionBody: TwilioMessageBody = async({row, db, change, ref, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("extensionBody started")
// Import any NPM package needed
@@ -218,10 +218,10 @@ const extensionBodyTemplate = {
to: "", // recipient phone number - eg: row.<fieldname>
body: "Hi there!" // message text
})
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
pushNotification: `const extensionBody: PushNotificationBody = async({row, db, change, ref, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("extensionBody started")
// Import any NPM package needed
@@ -259,7 +259,7 @@ const extensionBodyTemplate = {
// topic: topicName, // add topic send to subscribers
// token: FCMtoken // add FCM token to send to specific user
}]
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
};
@@ -276,11 +276,11 @@ export function emptyExtensionObject(
requiredFields: [],
trackedFields: [],
conditions: `const condition: Condition = async({row, change, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("condition started")
return true;
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
lastEditor: user,
};

View File

@@ -28,6 +28,8 @@ import { fieldParser } from "@src/components/TableModals/ImportAirtableWizard/ut
import Step1Columns from "./Step1Columns";
import Step2NewColumns from "./Step2NewColumns";
import Step3Preview from "./Step3Preview";
import useConverter from "@src/components/TableModals/ImportCsvWizard/useConverter";
import useUploadFileFromURL from "@src/components/TableModals/ImportCsvWizard/useUploadFileFromURL";
export type AirtableConfig = {
pairs: { fieldKey: string; columnKey: string }[];
@@ -65,6 +67,8 @@ export default function ImportAirtableWizard({ onClose }: ITableModalProps) {
newColumns: [],
documentId: "recordId",
});
const { needsUploadTypes, getConverter } = useConverter();
const { addTask, runBatchedUpload, hasUploadJobs } = useUploadFileFromURL();
const updateConfig: IStepProps["updateConfig"] = useCallback((value) => {
setConfig((prev) => {
@@ -99,10 +103,24 @@ export default function ImportAirtableWizard({ onClose }: ITableModalProps) {
const matchingColumn =
columns[pair.columnKey] ??
find(config.newColumns, { key: pair.columnKey });
const parser = fieldParser(matchingColumn.type);
const parser =
getConverter(matchingColumn.type) || fieldParser(matchingColumn.type);
const value = parser
? parser(record.fields[pair.fieldKey])
: record.fields[pair.fieldKey];
if (needsUploadTypes(matchingColumn.type)) {
if (value && value.length > 0) {
addTask({
docRef: {
path: `${tableSettings.collection}/${record.id}`,
id: record.id,
},
fieldName: pair.columnKey,
files: value,
});
}
}
return config.documentId === "recordId"
? { ...a, [pair.columnKey]: value, _rowy_ref: { id: record.id } }
: { ...a, [pair.columnKey]: value };
@@ -196,6 +214,10 @@ export default function ImportAirtableWizard({ onClose }: ITableModalProps) {
`Imported ${Number(countRef.current).toLocaleString()} rows`,
{ variant: "success" }
);
if (hasUploadJobs()) {
await runBatchedUpload();
}
} catch (e) {
enqueueSnackbar((e as Error).message, { variant: "error" });
} finally {

View File

@@ -57,7 +57,6 @@ export default function Step1Columns({
config.pairs.map((pair) => pair.fieldKey)
);
const fieldKeys = Object.keys(airtableData.records[0].fields);
// When a field is selected to be imported
@@ -128,8 +127,8 @@ export default function Step1Columns({
const handleSelectAll = () => {
if (selectedFields.length !== fieldKeys.length) {
setSelectedFields(fieldKeys)
fieldKeys.forEach(field => {
setSelectedFields(fieldKeys);
fieldKeys.forEach((field) => {
// Try to match each field to a column in the table
const match =
find(tableColumns, (column) =>
@@ -158,15 +157,13 @@ export default function Step1Columns({
];
}
updateConfig(columnConfig);
})
});
} else {
setSelectedFields([])
setConfig((config) => ({ ...config, newColumns: [], pairs: [] }))
setSelectedFields([]);
setConfig((config) => ({ ...config, newColumns: [], pairs: [] }));
}
};
// When a field is mapped to a new column
const handleChange = (fieldKey: string) => (value: string) => {
if (!value) return;
@@ -236,7 +233,13 @@ export default function Step1Columns({
color="default"
/>
}
label={selectedFields.length == fieldKeys.length ? "Clear all" : "Select all"}
label={
selectedFields.length === fieldKeys.length
? "Clear all"
: "Select all"
}
sx={{
height: 42,
mr: 0,
@@ -251,8 +254,8 @@ export default function Step1Columns({
find(config.pairs, { fieldKey: field })?.columnKey ?? null;
const matchingColumn = columnKey
? tableSchema.columns?.[columnKey] ??
find(config.newColumns, { key: columnKey }) ??
null
find(config.newColumns, { key: columnKey }) ??
null
: null;
const isNewColumn = !!find(config.newColumns, { key: columnKey });
return (

View File

@@ -67,7 +67,7 @@ export const fieldParser = (fieldType: FieldType) => {
case FieldType.dateTime:
return (v: string) => {
const date = parseISO(v);
return isValidDate(date) ? date.getTime() : null;
return isValidDate(date) ? new Date(date) : null;
};
default:
return (v: any) => v;

View File

@@ -37,7 +37,10 @@ import {
import { ColumnConfig } from "@src/types/table";
import { getFieldProp } from "@src/components/fields";
import { analytics, logEvent } from "@src/analytics";
import { generateId } from "@src/utils/table";
import { isValidDocId } from "./utils";
import useUploadFileFromURL from "./useUploadFileFromURL";
import useConverter from "./useConverter";
export type CsvConfig = {
pairs: { csvKey: string; columnKey: string }[];
@@ -65,6 +68,8 @@ export default function ImportCsvWizard({ onClose }: ITableModalProps) {
const theme = useTheme();
const isXs = useMediaQuery(theme.breakpoints.down("sm"));
const snackbarProgressRef = useRef<ISnackbarProgressRef>();
const { addTask, runBatchedUpload } = useUploadFileFromURL();
const { needsUploadTypes, needsConverter, getConverter } = useConverter();
const columns = useMemoValue(tableSchema.columns ?? {}, isEqual);
@@ -74,6 +79,7 @@ export default function ImportCsvWizard({ onClose }: ITableModalProps) {
documentId: "auto",
documentIdCsvKey: null,
});
const updateConfig: IStepProps["updateConfig"] = useCallback((value) => {
setConfig((prev) => {
const pairs = uniqBy([...prev.pairs, ...(value.pairs ?? [])], "csvKey");
@@ -123,6 +129,36 @@ export default function ImportCsvWizard({ onClose }: ITableModalProps) {
)
: { validRows: parsedRows, invalidRows: [] };
const { requiredConverts, requiredUploads } = useMemo(() => {
const columns = config.pairs.map(({ csvKey, columnKey }) => ({
csvKey,
columnKey,
...(tableSchema.columns?.[columnKey] ??
find(config.newColumns, { key: columnKey }) ??
{}),
}));
let requiredConverts: any = {};
let requiredUploads: any = {};
columns.forEach((column, index) => {
if (needsConverter(column.type)) {
requiredConverts[index] = getConverter(column.type);
// console.log({ needsUploadTypes }, column.type);
if (needsUploadTypes(column.type)) {
requiredUploads[column.fieldName + ""] = true;
}
}
});
return { requiredConverts, requiredUploads };
}, [
config.newColumns,
config.pairs,
getConverter,
needsConverter,
needsUploadTypes,
tableSchema.columns,
]);
const handleFinish = async () => {
if (!parsedRows) return;
console.time("importCsv");
@@ -176,12 +212,48 @@ export default function ImportCsvWizard({ onClose }: ITableModalProps) {
{ variant: "warning" }
);
}
const newValidRows = validRows.map((row) => {
// Convert required values
Object.keys(row).forEach((key, i) => {
if (requiredConverts[i]) {
row[key] = requiredConverts[i](row[key]);
}
});
const id = generateId();
const newRow = {
_rowy_ref: {
path: `${tableSettings.collection}/${row?._rowy_ref?.id ?? id}`,
id,
},
...row,
};
return newRow;
});
promises.push(
bulkAddRows({
rows: validRows,
type: "add",
rows: newValidRows,
collection: tableSettings.collection,
onBatchCommit: (batchNumber: number) =>
snackbarProgressRef.current?.setProgress(batchNumber),
onBatchCommit: async (batchNumber: number) => {
if (Object.keys(requiredUploads).length > 0) {
newValidRows
.slice((batchNumber - 1) * 500, batchNumber * 500 - 1)
.forEach((row) => {
Object.keys(requiredUploads).forEach((key) => {
if (requiredUploads[key]) {
addTask({
docRef: row._rowy_ref,
fieldName: key,
files: row[key],
});
}
});
});
}
snackbarProgressRef.current?.setProgress(batchNumber);
},
})
);
@@ -192,6 +264,9 @@ export default function ImportCsvWizard({ onClose }: ITableModalProps) {
`Imported ${Number(validRows.length).toLocaleString()} rows`,
{ variant: "success" }
);
if (Object.keys(requiredUploads).length > 0) {
await runBatchedUpload();
}
} catch (e) {
enqueueSnackbar((e as Error).message, { variant: "error" });
} finally {

View File

@@ -67,7 +67,7 @@ export default function Step1Columns({
const handleSelectAll = () => {
if (selectedFields.length !== csvData.columns.length) {
setSelectedFields(csvData.columns);
csvData.columns.forEach(field => {
csvData.columns.forEach((field) => {
// Try to match each field to a column in the table
const match =
find(tableColumns, (column) =>
@@ -89,10 +89,10 @@ export default function Step1Columns({
];
}
updateConfig(columnConfig);
})
});
} else {
setSelectedFields([])
setConfig((config) => ({ ...config, newColumns: [], pairs: [] }))
setSelectedFields([]);
setConfig((config) => ({ ...config, newColumns: [], pairs: [] }));
}
};
@@ -232,7 +232,11 @@ export default function Step1Columns({
color="default"
/>
}
label={selectedFields.length == csvData.columns.length ? "Clear all" : "Select all"}
label={
selectedFields.length === csvData.columns.length
? "Clear all"
: "Select all"
}
sx={{
height: 42,
mr: 0,
@@ -247,8 +251,8 @@ export default function Step1Columns({
find(config.pairs, { csvKey: field })?.columnKey ?? null;
const matchingColumn = columnKey
? tableSchema.columns?.[columnKey] ??
find(config.newColumns, { key: columnKey }) ??
null
find(config.newColumns, { key: columnKey }) ??
null
: null;
const isNewColumn = !!find(config.newColumns, { key: columnKey });

View File

@@ -0,0 +1,160 @@
import { projectScope } from "@src/atoms/projectScope";
import { FieldType } from "@src/constants/fields";
import { firebaseDbAtom } from "@src/sources/ProjectSourceFirebase";
import {
doc,
DocumentReference as Reference,
GeoPoint,
} from "firebase/firestore";
import { useAtom } from "jotai";
const needsConverter = (type: FieldType) =>
[
FieldType.image,
FieldType.reference,
FieldType.file,
FieldType.geoPoint,
].includes(type);
const needsUploadTypes = (type: FieldType) =>
[FieldType.image, FieldType.file].includes(type);
export default function useConverter() {
const [firebaseDb] = useAtom(firebaseDbAtom, projectScope);
const referenceConverter = (value: string): Reference | null => {
if (!value) return null;
if (value.charAt(value.length - 1) === "/") {
value = value.slice(0, -1);
}
if (value.split("/").length % 2 === 0) {
try {
return doc(firebaseDb, value);
} catch (e) {
console.log("error", e);
}
}
return null;
};
const imageOrFileConverter = (urls: any): RowyFile[] => {
try {
if (!urls) return [];
if (Array.isArray(urls)) {
return urls
.map((url) => {
if (typeof url === "string") {
url = url.trim();
if (url !== "") {
return {
downloadURL: url,
name: url.split("/").pop() || "",
lastModifiedTS: +new Date(),
type: "",
};
}
} else if (url && typeof url === "object" && url.downloadURL) {
return url;
} else {
if (url.url) {
return {
downloadURL: url.url,
name: url.filename || url.url.split("/").pop() || "",
lastModifiedTS: +new Date(),
type: "",
};
}
}
return null;
})
.filter((val) => val !== null) as RowyFile[];
}
if (typeof urls === "string") {
return urls
.split(",")
.map((url) => {
url = url.trim();
if (url !== "") {
return {
downloadURL: url,
name: url.split("/").pop() || "",
lastModifiedTS: +new Date(),
type: "",
};
}
return null;
})
.filter((val) => val !== null) as RowyFile[];
}
return [];
} catch (e) {
return [];
}
};
const geoPointConverter = (value: any) => {
if (!value) return null;
if (typeof value === "string") {
let latitude, longitude;
// covered cases:
// [3.2, 32.3]
// {latitude: 3.2, longitude: 32.3}
// "3.2, 32.3"
try {
const parsed = JSON.parse(value);
if (Array.isArray(parsed)) {
[latitude, longitude] = parsed;
} else {
latitude = parsed.latitude;
longitude = parsed.longitude;
}
if (latitude && longitude) {
latitude = parseFloat(latitude);
longitude = parseFloat(longitude);
}
} catch (e) {
[latitude, longitude] = value
.split(",")
.map((val) => parseFloat(val.trim()));
}
if (latitude && longitude) {
return new GeoPoint(latitude, longitude);
}
}
return null;
};
const getConverter = (type: FieldType) => {
switch (type) {
case FieldType.image:
case FieldType.file:
return imageOrFileConverter;
case FieldType.reference:
return referenceConverter;
case FieldType.geoPoint:
return geoPointConverter;
default:
return null;
}
};
const checkAndConvert = (value: any, type: FieldType) => {
if (needsConverter(type)) {
const converter = getConverter(type);
if (converter) return converter(value);
}
return value;
};
return {
needsConverter,
referenceConverter,
imageOrFileConverter,
getConverter,
checkAndConvert,
needsUploadTypes,
};
}

View File

@@ -0,0 +1,176 @@
import { useCallback, useRef } from "react";
import { useSetAtom } from "jotai";
import { SnackbarKey, useSnackbar } from "notistack";
import Button from "@mui/material/Button";
import useUploader from "@src/hooks/useFirebaseStorageUploader";
import { tableScope, updateFieldAtom } from "@src/atoms/tableScope";
import { TableRowRef } from "@src/types/table";
import SnackbarProgress from "@src/components/SnackbarProgress";
const MAX_CONCURRENT_TASKS = 1000;
type UploadParamTypes = {
docRef: TableRowRef;
fieldName: string;
files: RowyFile[];
};
export default function useUploadFileFromURL() {
const { upload } = useUploader();
const updateField = useSetAtom(updateFieldAtom, tableScope);
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const jobs = useRef<UploadParamTypes[]>([]);
const askPermission = useCallback(async (): Promise<boolean> => {
return new Promise((resolve) => {
enqueueSnackbar("Upload files to firebase storage?", {
persist: true,
preventDuplicate: true,
action: (
<>
<Button
variant="contained"
color="primary"
onClick={() => {
closeSnackbar();
resolve(true);
}}
style={{
marginRight: 8,
}}
>
Yes
</Button>
<Button
variant="contained"
color="secondary"
onClick={() => {
closeSnackbar();
resolve(false);
}}
>
No
</Button>
</>
),
});
});
}, [enqueueSnackbar, closeSnackbar]);
const handleUpload = useCallback(
async ({
docRef,
fieldName,
files,
}: UploadParamTypes): Promise<boolean> => {
try {
const files_ = await getFileFromURL(
files.map((file) => file.downloadURL)
);
const { uploads, failures } = await upload({
docRef,
fieldName,
files: files_,
});
if (failures.length > 0) {
return false;
}
await updateField({
path: docRef.path,
fieldName,
value: uploads,
useArrayUnion: false,
});
return true;
} catch (error) {
return false;
}
},
[upload, updateField]
);
const batchUpload = useCallback(
async (batch: UploadParamTypes[]) => {
await Promise.all(
batch.map((job) =>
handleUpload(job).then(() => {
snackbarProgressRef.current?.setProgress((p: number) => p + 1);
})
)
);
},
[handleUpload]
);
const snackbarProgressRef = useRef<any>(null);
const snackbarProgressId = useRef<SnackbarKey | null>(null);
const showProgress = useCallback(
(totalJobs: number) => {
snackbarProgressId.current = enqueueSnackbar(
`Uploading files form ${Number(
totalJobs
).toLocaleString()} cells. This might take a while.`,
{
persist: true,
action: (
<SnackbarProgress
stateRef={snackbarProgressRef}
target={totalJobs}
label=" completed"
/>
),
}
);
},
[enqueueSnackbar]
);
const runBatchedUpload = useCallback(async () => {
if (!snackbarProgressId.current) {
showProgress(jobs.current.length);
}
let currentJobs: UploadParamTypes[] = [];
while (
currentJobs.length < MAX_CONCURRENT_TASKS &&
jobs.current.length > 0
) {
const job = jobs.current.shift();
if (job) {
currentJobs.push(job);
}
}
await batchUpload(currentJobs);
if (jobs.current.length > 0) {
await runBatchedUpload();
}
if (snackbarProgressId.current) {
closeSnackbar(snackbarProgressId.current);
}
}, [batchUpload, closeSnackbar, showProgress, snackbarProgressId]);
const addTask = useCallback((job: UploadParamTypes) => {
jobs.current.push(job);
}, []);
const hasUploadJobs = () => jobs.current.length > 0;
return {
addTask,
runBatchedUpload,
askPermission,
hasUploadJobs,
};
}
function getFileFromURL(urls: string[]): Promise<File[]> {
const promises = urls.map((url) => {
return fetch(url)
.then((response) => response.blob())
.then((blob) => new File([blob], +new Date() + "", { type: blob.type }));
});
return Promise.all(promises);
}

View File

@@ -117,7 +117,11 @@ export default function Step1Columns({ config, setConfig }: IStepProps) {
color="default"
/>
}
label={selectedFields.length == allFields.length ? "Clear all" : "Select all"}
label={
selectedFields.length === allFields.length
? "Clear all"
: "Select all"
}
sx={{
height: 42,
mr: 0,

View File

@@ -18,14 +18,21 @@ export const SELECTABLE_TYPES = [
FieldType.url,
FieldType.rating,
FieldType.image,
FieldType.file,
FieldType.singleSelect,
FieldType.multiSelect,
FieldType.json,
FieldType.code,
FieldType.geoPoint,
FieldType.color,
FieldType.slider,
FieldType.reference,
];
export const REGEX_EMAIL =

View File

@@ -1,10 +1,7 @@
import { Typography } from "@mui/material";
import WarningIcon from "@mui/icons-material/WarningAmber";
import { TableSettings } from "@src/types/table";
import {
IWebhook,
ISecret,
} from "@src/components/TableModals/WebhooksModal/utils";
import { IWebhook } from "@src/components/TableModals/WebhooksModal/utils";
const requestType = [
"declare type WebHookRequest {",
@@ -101,11 +98,7 @@ export const webhookBasic = {
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
},
auth: (
webhookObject: IWebhook,
setWebhookObject: (w: IWebhook) => void,
secrets: ISecret
) => {
Auth: (webhookObject: IWebhook, setWebhookObject: (w: IWebhook) => void) => {
return (
<Typography color="text.disabled">
<WarningIcon aria-label="Warning" style={{ verticalAlign: "bottom" }} />

View File

@@ -0,0 +1,60 @@
import { Typography, Link, TextField } from "@mui/material";
import InlineOpenInNewIcon from "@src/components/InlineOpenInNewIcon";
import { TableSettings } from "@src/types/table";
import { IWebhook } from "@src/components/TableModals/WebhooksModal/utils";
export const webhookFirebaseAuth = {
name: "firebaseAuth",
parser: {
additionalVariables: null,
extraLibs: null,
template: (
table: TableSettings
) => `const firebaseAuthParser: Parser = async({req, db, ref, logging}) =>{
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("firebaseAuthParser started")
/**
* This is a sample parser for firebase authentication
* creates a user document in the collection if it doesn't exist
// check if document exists,
const userDoc = await ref.doc(user.uid).get()
if(!userDoc.exists){
await ref.doc(user.uid).set({email:user.email})
}
*/
return;
};`,
},
condition: {
additionalVariables: null,
extraLibs: null,
template: (
table: TableSettings
) => `const condition: Condition = async({ref, req, db, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("condition started")
return true;
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
},
Auth: (webhookObject: IWebhook, setWebhookObject: (w: IWebhook) => void) => {
return (
<>
<Typography variant="inherit" paragraph>
For Firebase authentication, you need to include the following header
in your request:
<br />
<code>Authorization: Bear ACCESS_TOKEN</code>
</Typography>
<Typography variant="inherit" paragraph>
Once enabled requests without a valid token will return{" "}
<code>401</code> response.
</Typography>
</>
);
},
};
export default webhookFirebaseAuth;

View File

@@ -1,7 +1,8 @@
import basic from "./basic";
import firebaseAuth from "./firebaseAuth";
import typeform from "./typeform";
import sendgrid from "./sendgrid";
import webform from "./webform";
import stripe from "./stripe";
export { basic, typeform, sendgrid, webform, stripe };
export { basic, typeform, sendgrid, webform, stripe, firebaseAuth };

View File

@@ -1,10 +1,7 @@
import { Typography, Link, TextField } from "@mui/material";
import InlineOpenInNewIcon from "@src/components/InlineOpenInNewIcon";
import { TableSettings } from "@src/types/table";
import {
IWebhook,
ISecret,
} from "@src/components/TableModals/WebhooksModal/utils";
import { IWebhook } from "@src/components/TableModals/WebhooksModal/utils";
export const webhookSendgrid = {
name: "SendGrid",
@@ -51,11 +48,7 @@ export const webhookSendgrid = {
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
},
auth: (
webhookObject: IWebhook,
setWebhookObject: (w: IWebhook) => void,
secrets: ISecret
) => {
Auth: (webhookObject: IWebhook, setWebhookObject: (w: IWebhook) => void) => {
return (
<>
<Typography gutterBottom>

View File

@@ -1,14 +1,18 @@
import { Typography, Link, TextField, Alert } from "@mui/material";
import { useAtom } from "jotai";
import { Typography, Link, TextField, Alert, Box } from "@mui/material";
import InlineOpenInNewIcon from "@src/components/InlineOpenInNewIcon";
import { TableSettings } from "@src/types/table";
import { IWebhook } from "@src/components/TableModals/WebhooksModal/utils";
import {
IWebhook,
ISecret,
} from "@src/components/TableModals/WebhooksModal/utils";
projectScope,
secretNamesAtom,
updateSecretNamesAtom,
} from "@src/atoms/projectScope";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
import LoadingButton from "@mui/lab/LoadingButton";
export const webhookStripe = {
name: "Stripe",
@@ -49,11 +53,10 @@ export const webhookStripe = {
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
},
auth: (
webhookObject: IWebhook,
setWebhookObject: (w: IWebhook) => void,
secrets: ISecret
) => {
Auth: (webhookObject: IWebhook, setWebhookObject: (w: IWebhook) => void) => {
const [secretNames] = useAtom(secretNamesAtom, projectScope);
const [updateSecretNames] = useAtom(updateSecretNamesAtom, projectScope);
return (
<>
<Typography gutterBottom>
@@ -77,8 +80,9 @@ export const webhookStripe = {
</Typography>
{webhookObject.auth.secretKey &&
!secrets.loading &&
!secrets.keys.includes(webhookObject.auth.secretKey) && (
!secretNames.loading &&
secretNames.secretNames &&
!secretNames.secretNames.includes(webhookObject.auth.secretKey) && (
<Alert severity="error" sx={{ height: "auto!important" }}>
Your previously selected key{" "}
<code>{webhookObject.auth.secretKey}</code> does not exist in
@@ -86,34 +90,55 @@ export const webhookStripe = {
</Alert>
)}
<FormControl fullWidth margin={"normal"}>
<InputLabel id="stripe-secret-key">Secret key</InputLabel>
<Select
labelId="stripe-secret-key"
id="stripe-secret-key"
label="Secret key"
variant="filled"
value={webhookObject.auth.secretKey}
onChange={(e) => {
setWebhookObject({
...webhookObject,
auth: { ...webhookObject.auth, secretKey: e.target.value },
});
}}
>
{secrets.keys.map((secret) => {
return <MenuItem value={secret}>{secret}</MenuItem>;
})}
<MenuItem
onClick={() => {
const secretManagerLink = `https://console.cloud.google.com/security/secret-manager/create?project=${secrets.projectId}`;
window?.open?.(secretManagerLink, "_blank")?.focus();
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
marginY: 1,
}}
>
<FormControl fullWidth>
<InputLabel id="stripe-secret-key">Secret key</InputLabel>
<Select
labelId="stripe-secret-key"
id="stripe-secret-key"
label="Secret key"
variant="filled"
value={webhookObject.auth.secretKey}
onChange={(e) => {
setWebhookObject({
...webhookObject,
auth: { ...webhookObject.auth, secretKey: e.target.value },
});
}}
>
Add a key in Secret Manager
</MenuItem>
</Select>
</FormControl>
{secretNames.secretNames?.map((secret) => {
return <MenuItem value={secret}>{secret}</MenuItem>;
})}
<MenuItem
onClick={() => {
const secretManagerLink = `https://console.cloud.google.com/security/secret-manager/create`;
window?.open?.(secretManagerLink, "_blank")?.focus();
}}
>
Add a key in Secret Manager
</MenuItem>
</Select>
</FormControl>
<LoadingButton
sx={{
height: "100%",
marginLeft: 1,
}}
loading={secretNames.loading}
onClick={() => {
updateSecretNames?.();
}}
>
Refresh
</LoadingButton>
</Box>
<TextField
id="stripe-signing-secret"
label="Signing key"

View File

@@ -1,10 +1,7 @@
import { Typography, Link, TextField } from "@mui/material";
import InlineOpenInNewIcon from "@src/components/InlineOpenInNewIcon";
import { TableSettings } from "@src/types/table";
import {
IWebhook,
ISecret,
} from "@src/components/TableModals/WebhooksModal/utils";
import { IWebhook } from "@src/components/TableModals/WebhooksModal/utils";
export const webhookTypeform = {
name: "Typeform",
@@ -83,11 +80,7 @@ export const webhookTypeform = {
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
},
auth: (
webhookObject: IWebhook,
setWebhookObject: (w: IWebhook) => void,
secrets: ISecret
) => {
Auth: (webhookObject: IWebhook, setWebhookObject: (w: IWebhook) => void) => {
return (
<>
<Typography gutterBottom>

View File

@@ -1,10 +1,7 @@
import { Typography, Link, TextField } from "@mui/material";
import InlineOpenInNewIcon from "@src/components/InlineOpenInNewIcon";
import { TableSettings } from "@src/types/table";
import {
IWebhook,
ISecret,
} from "@src/components/TableModals/WebhooksModal/utils";
import { IWebhook } from "@src/components/TableModals/WebhooksModal/utils";
export const webhook = {
name: "Web Form",
@@ -51,11 +48,7 @@ export const webhook = {
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`,
},
auth: (
webhookObject: IWebhook,
setWebhookObject: (w: IWebhook) => void,
secrets: ISecret
) => {
Auth: (webhookObject: IWebhook, setWebhookObject: (w: IWebhook) => void) => {
return (
<>
<Typography gutterBottom>

View File

@@ -1,41 +1,13 @@
import { useAtom } from "jotai";
import { useEffect, useState } from "react";
import { IWebhookModalStepProps } from "./WebhookModal";
import { FormControlLabel, Checkbox, Typography } from "@mui/material";
import {
projectIdAtom,
projectScope,
rowyRunAtom,
} from "@src/atoms/projectScope";
import { runRoutes } from "@src/constants/runRoutes";
import { webhookSchemas, ISecret } from "./utils";
import { webhookSchemas } from "./utils";
export default function Step1Endpoint({
webhookObject,
setWebhookObject,
}: IWebhookModalStepProps) {
const [rowyRun] = useAtom(rowyRunAtom, projectScope);
const [projectId] = useAtom(projectIdAtom, projectScope);
const [secrets, setSecrets] = useState<ISecret>({
loading: true,
keys: [],
projectId,
});
useEffect(() => {
rowyRun({
route: runRoutes.listSecrets,
}).then((secrets) => {
setSecrets({
loading: false,
keys: secrets as string[],
projectId,
});
});
}, []);
return (
<>
<Typography variant="inherit" paragraph>
@@ -63,10 +35,9 @@ export default function Step1Endpoint({
/>
{webhookObject.auth?.enabled &&
webhookSchemas[webhookObject.type].auth(
webhookSchemas[webhookObject.type].Auth(
webhookObject,
setWebhookObject,
secrets
setWebhookObject
)}
{}
</>

View File

@@ -1,12 +1,20 @@
import { TableSettings } from "@src/types/table";
import { generateId } from "@src/utils/table";
import { typeform, basic, sendgrid, webform, stripe } from "./Schemas";
import {
typeform,
basic,
sendgrid,
webform,
stripe,
firebaseAuth,
} from "./Schemas";
export const webhookTypes = [
"basic",
"typeform",
"sendgrid",
"webform",
"firebaseAuth",
//"shopify",
//"twitter",
"stripe",
@@ -35,6 +43,18 @@ export const parserExtraLibs = [
send: (v:any)=>void;
sendStatus: (status:number)=>void
};
user: {
uid: string;
email: string;
email_verified: boolean;
exp: number;
iat: number;
iss: string;
aud: string;
auth_time: number;
phone_number: string;
picture: string;
} | undefined;
logging: RowyLogging;
auth:firebaseauth.BaseAuth;
storage:firebasestorage.Storage;
@@ -71,6 +91,7 @@ export type WebhookType = typeof webhookTypes[number];
export const webhookNames: Record<WebhookType, string> = {
sendgrid: "SendGrid",
typeform: "Typeform",
firebaseAuth: "Firebase Auth",
//github:"GitHub",
// shopify: "Shopify",
// twitter: "Twitter",
@@ -98,18 +119,13 @@ export interface IWebhook {
auth?: any;
}
export interface ISecret {
loading: boolean;
keys: string[];
projectId: string;
}
export const webhookSchemas = {
basic,
typeform,
sendgrid,
webform,
stripe,
firebaseAuth,
};
export function emptyWebhookObject(

View File

@@ -12,16 +12,21 @@ export interface ITableNameProps extends IShortTextComponentProps {
export default function TableName({ watchedField, ...props }: ITableNameProps) {
const {
field: { onChange },
field: { onChange, value },
useFormMethods: { control },
disabled,
} = props;
const watchedValue = useWatch({ control, name: watchedField } as any);
useEffect(() => {
if (!disabled && typeof watchedValue === "string" && !!watchedValue)
onChange(startCase(watchedValue));
}, [watchedValue, disabled]);
if (!disabled) {
if (typeof value === "string" && value.trim() !== "") {
onChange(value);
} else if (typeof watchedValue === "string" && !!watchedValue) {
onChange(startCase(watchedValue));
}
}
}, [watchedValue, disabled, onChange, value]);
return <ShortTextComponent {...props} />;
}

View File

@@ -16,33 +16,42 @@ import {
ChevronDown as ArrowDropDownIcon,
} from "@src/assets/icons";
import {
projectScope,
userRolesAtom,
tableAddRowIdTypeAtom,
} from "@src/atoms/projectScope";
import { projectScope, userRolesAtom } from "@src/atoms/projectScope";
import {
tableScope,
tableSettingsAtom,
tableFiltersAtom,
tableSortsAtom,
addRowAtom,
_updateRowDbAtom,
tableColumnsOrderedAtom,
tableSchemaAtom,
updateTableSchemaAtom,
} from "@src/atoms/tableScope";
import { TableIdType } from "@src/types/table";
export default function AddRow() {
const [userRoles] = useAtom(userRolesAtom, projectScope);
const [tableSettings] = useAtom(tableSettingsAtom, tableScope);
const [tableSchema] = useAtom(tableSchemaAtom, tableScope);
const [tableFilters] = useAtom(tableFiltersAtom, tableScope);
const [tableSorts] = useAtom(tableSortsAtom, tableScope);
const [updateTableSchema] = useAtom(updateTableSchemaAtom, tableScope);
const addRow = useSetAtom(addRowAtom, tableScope);
const [idType, setIdType] = useAtom(tableAddRowIdTypeAtom, projectScope);
const anchorEl = useRef<HTMLDivElement>(null);
const [open, setOpen] = useState(false);
const [openIdModal, setOpenIdModal] = useState(false);
const idType = tableSchema.idType || "decrement";
const forceRandomId = tableFilters.length > 0 || tableSorts.length > 0;
const handleSetIdType = async (idType: TableIdType) => {
// TODO(han): refactor atom - error handler
await updateTableSchema!({
idType,
});
};
const handleClick = () => {
if (idType === "random" || (forceRandomId && idType === "decrement")) {
addRow({
@@ -118,7 +127,7 @@ export default function AddRow() {
label="Row add position"
style={{ display: "none" }}
value={forceRandomId && idType === "decrement" ? "random" : idType}
onChange={(e) => setIdType(e.target.value as typeof idType)}
onChange={(e) => handleSetIdType(e.target.value as typeof idType)}
MenuProps={{
anchorEl: anchorEl.current,
MenuListProps: { "aria-labelledby": "add-row-menu-button" },
@@ -207,3 +216,100 @@ export default function AddRow() {
</>
);
}
export function AddRowArraySubTable() {
const [updateRowDb] = useAtom(_updateRowDbAtom, tableScope);
const [open, setOpen] = useState(false);
const anchorEl = useRef<HTMLDivElement>(null);
const [addRowAt, setAddNewRowAt] = useState<"top" | "bottom">("bottom");
const [tableColumnsOrdered] = useAtom(tableColumnsOrderedAtom, tableScope);
if (!updateRowDb) return null;
const handleClick = () => {
const initialValues: Record<string, any> = {};
// Set initial values based on default values
for (const column of tableColumnsOrdered) {
if (column.config?.defaultValue?.type === "static")
initialValues[column.key] = column.config.defaultValue.value!;
else if (column.config?.defaultValue?.type === "null")
initialValues[column.key] = null;
}
updateRowDb("", initialValues, undefined, {
index: 0,
operation: {
addRow: addRowAt,
},
});
};
return (
<>
<ButtonGroup
variant="contained"
color="primary"
aria-label="Split button"
ref={anchorEl}
>
<Button
variant="contained"
color="primary"
onClick={handleClick}
startIcon={addRowAt === "top" ? <AddRowTopIcon /> : <AddRowIcon />}
>
Add row to {addRowAt}
</Button>
<Button
variant="contained"
color="primary"
aria-label="Select row add position"
aria-haspopup="menu"
style={{ padding: 0 }}
onClick={() => setOpen(true)}
id="add-row-menu-button"
aria-controls={open ? "add-row-menu" : undefined}
aria-expanded={open ? "true" : "false"}
>
<ArrowDropDownIcon />
</Button>
</ButtonGroup>
<Select
id="add-row-menu"
open={open}
onClose={() => setOpen(false)}
label="Row add position"
style={{ display: "none" }}
value={addRowAt}
onChange={(e) => setAddNewRowAt(e.target.value as typeof addRowAt)}
MenuProps={{
anchorEl: anchorEl.current,
MenuListProps: { "aria-labelledby": "add-row-menu-button" },
anchorOrigin: { horizontal: "left", vertical: "bottom" },
transformOrigin: { horizontal: "left", vertical: "top" },
}}
>
<MenuItem value="top">
<ListItemText
primary="To top"
secondary="Adds a new row to the top of this table"
secondaryTypographyProps={{ variant: "caption" }}
/>
</MenuItem>
<MenuItem value="bottom">
<ListItemText
primary="To bottom"
secondary={"Adds a new row to the bottom of this table"}
secondaryTypographyProps={{
variant: "caption",
whiteSpace: "pre-line",
}}
/>
</MenuItem>
</Select>
</>
);
}

View File

@@ -132,20 +132,6 @@ export default function ImportFromFile() {
};
}, [setImportCsv]);
const parseFile = useCallback((rawData: string) => {
if (importTypeRef.current === "json") {
if (!hasProperJsonStructure(rawData)) {
return setError("Invalid Structure! It must be an Array");
}
const converted = convertJSONToCSV(rawData);
if (!converted) {
return setError("No columns detected");
}
rawData = converted;
}
parseCsv(rawData);
}, []);
const parseCsv = useCallback(
(csvString: string) =>
parse(csvString, { delimiter: [",", "\t"] }, (err, rows) => {
@@ -162,7 +148,7 @@ export default function ImportFromFile() {
{}
)
);
console.log(mappedRows);
// console.log(mappedRows);
setImportCsv({
importType: importTypeRef.current,
csvData: { columns, rows: mappedRows },
@@ -174,6 +160,23 @@ export default function ImportFromFile() {
[setImportCsv]
);
const parseFile = useCallback(
(rawData: string) => {
if (importTypeRef.current === "json") {
if (!hasProperJsonStructure(rawData)) {
return setError("Invalid Structure! It must be an Array");
}
const converted = convertJSONToCSV(rawData);
if (!converted) {
return setError("No columns detected");
}
rawData = converted;
}
parseCsv(rawData);
},
[parseCsv]
);
const onDrop = useCallback(
async (acceptedFiles: File[]) => {
try {

View File

@@ -1,17 +1,19 @@
import { lazy, Suspense } from "react";
import { useAtom, useSetAtom } from "jotai";
import { Stack } from "@mui/material";
import { Button, Stack } from "@mui/material";
import WebhookIcon from "@mui/icons-material/Webhook";
import {
Export as ExportIcon,
Extension as ExtensionIcon,
CloudLogs as CloudLogsIcon,
Import as ImportIcon,
} from "@src/assets/icons";
import TableToolbarButton from "./TableToolbarButton";
import { ButtonSkeleton } from "./TableToolbarSkeleton";
import AddRow from "./AddRow";
import AddRow, { AddRowArraySubTable } from "./AddRow";
import LoadedRowsStatus from "./LoadedRowsStatus";
import TableSettings from "./TableSettings";
import HiddenFields from "./HiddenFields";
@@ -32,6 +34,8 @@ import {
tableModalAtom,
} from "@src/atoms/tableScope";
import { FieldType } from "@src/constants/fields";
import { TableToolsType } from "@src/types/table";
import FilterIcon from "@mui/icons-material/FilterList";
// prettier-ignore
const Filters = lazy(() => import("./Filters" /* webpackChunkName: "Filters" */));
@@ -43,7 +47,11 @@ const ReExecute = lazy(() => import("./ReExecute" /* webpackChunkName: "ReExecut
export const TABLE_TOOLBAR_HEIGHT = 44;
export default function TableToolbar() {
export default function TableToolbar({
disabledTools,
}: {
disabledTools?: TableToolsType[];
}) {
const [projectSettings] = useAtom(projectSettingsAtom, projectScope);
const [userRoles] = useAtom(userRolesAtom, projectScope);
const [compatibleRowyRunVersion] = useAtom(
@@ -54,7 +62,6 @@ export default function TableToolbar() {
const [tableSettings] = useAtom(tableSettingsAtom, tableScope);
const [tableSchema] = useAtom(tableSchemaAtom, tableScope);
const openTableModal = useSetAtom(tableModalAtom, tableScope);
const hasDerivatives =
Object.values(tableSchema.columns ?? {}).filter(
(column) => column.type === FieldType.derivative
@@ -64,6 +71,7 @@ export default function TableToolbar() {
tableSchema.compiledExtension &&
tableSchema.compiledExtension.replace(/\W/g, "")?.length > 0;
disabledTools = disabledTools ?? [];
return (
<Stack
direction="row"
@@ -87,29 +95,61 @@ export default function TableToolbar() {
},
}}
>
<AddRow />
{tableSettings.isCollection === false ? (
<AddRowArraySubTable />
) : (
<AddRow />
)}
<div /> {/* Spacer */}
<HiddenFields />
<Suspense fallback={<ButtonSkeleton />}>
<Filters />
</Suspense>
{tableSettings.isCollection === false ? (
<Button
variant="outlined"
color="primary"
startIcon={<FilterIcon />}
disabled={true}
>
Filter
</Button>
) : (
<Suspense fallback={<ButtonSkeleton />}>
<Filters />
</Suspense>
)}
<div /> {/* Spacer */}
<LoadedRowsStatus />
<div style={{ flexGrow: 1, minWidth: 64 }} />
<RowHeight />
<div /> {/* Spacer */}
{tableSettings.tableType !== "collectionGroup" && (
<Suspense fallback={<ButtonSkeleton />}>
<ImportData />
{disabledTools.includes("import") ? (
<TableToolbarButton
title="Import data"
icon={<ImportIcon />}
disabled={true}
/>
) : (
tableSettings.tableType !== "collectionGroup" && (
<Suspense fallback={<ButtonSkeleton />}>
<ImportData />
</Suspense>
)
)}
{(!projectSettings.exporterRoles ||
projectSettings.exporterRoles.length === 0 ||
userRoles.some((role) =>
projectSettings.exporterRoles?.includes(role)
)) && (
<Suspense fallback={<ButtonSkeleton />}>
<TableToolbarButton
title="Export/Download"
onClick={() => openTableModal("export")}
icon={<ExportIcon />}
disabled={disabledTools.includes("export")}
/>
</Suspense>
)}
<Suspense fallback={<ButtonSkeleton />}>
<TableToolbarButton
title="Export/Download"
onClick={() => openTableModal("export")}
icon={<ExportIcon />}
/>
</Suspense>
{userRoles.includes("ADMIN") && (
<>
<div /> {/* Spacer */}
@@ -123,6 +163,7 @@ export default function TableToolbar() {
}
}}
icon={<WebhookIcon />}
disabled={disabledTools.includes("webhooks")}
/>
<TableToolbarButton
title="Extensions"
@@ -131,6 +172,7 @@ export default function TableToolbar() {
else openRowyRunModal({ feature: "Extensions" });
}}
icon={<ExtensionIcon />}
disabled={disabledTools.includes("extensions")}
/>
<TableToolbarButton
title="Cloud logs"
@@ -139,6 +181,7 @@ export default function TableToolbar() {
if (projectSettings.rowyRunUrl) openTableModal("cloudLogs");
else openRowyRunModal({ feature: "Cloud logs" });
}}
disabled={disabledTools.includes("cloud_logs")}
/>
{(hasDerivatives || hasExtensions) && (
<Suspense fallback={<ButtonSkeleton />}>

View File

@@ -31,6 +31,7 @@ export const config: IFieldConfig = {
settings: Settings,
requireConfiguration: true,
requireCloudFunction: true,
requireCollectionTable: true,
sortKey: "status",
};
export default config;

View File

@@ -1,67 +1,69 @@
export const RUN_ACTION_TEMPLATE = `const action:Action = async ({row,ref,db,storage,auth,actionParams,user,logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("action started")
// Import any NPM package needed
// const lodash = require('lodash');
// Example:
/*
const authToken = await rowy.secrets.get("service")
try {
const resp = await fetch('https://example.com/api/v1/users/'+ref.id,{
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': authToken
},
body: JSON.stringify(row)
})
return {
success: true,
message: 'User updated successfully on example service',
status: "upto date"
}
} catch (error) {
return {
success: false,
message: 'User update failed on example service',
}
}
*/
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`;
export const RUN_ACTION_TEMPLATE = `// Import any NPM package needed
// import _ from "lodash";
const action: Action = async ({ row, ref, db, storage, auth, actionParams, user, logging }) => {
logging.log("action started");
export const UNDO_ACTION_TEMPLATE = `const action : Action = async ({row,ref,db,storage,auth,actionParams,user,logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("action started")
// Import any NPM package needed
// const lodash = require('lodash');
// Example:
/*
const authToken = await rowy.secrets.get("service")
// Example:
const authToken = await rowy.secrets.get("service");
try {
const resp = await fetch('https://example.com/api/v1/users/'+ref.id,{
method: 'DELETE',
const resp = await fetch("https://example.com/api/v1/users/" + ref.id, {
method: "PUT",
headers: {
'Content-Type': 'application/json',
'Authorization': authToken
"Content-Type": "application/json",
Authorization: authToken,
},
body: JSON.stringify(row)
})
body: JSON.stringify(row),
});
return {
success: true,
message: 'User deleted successfully on example service',
status: null
}
message: "User updated successfully on example service",
status: "upto date",
};
} catch (error) {
return {
success: false,
message: 'User delete failed on example service',
}
message: "User update failed on example service",
};
}
*/
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`;
};
export default action;
`;
export const UNDO_ACTION_TEMPLATE = `// Import any NPM package needed
// import _ from "lodash";
const action: Action = async ({ row, ref, db, storage, auth, actionParams, user, logging }) => {
logging.log("action started");
/*
// Example:
const authToken = await rowy.secrets.get("service");
try {
const resp = await fetch("https://example.com/api/v1/users/" + ref.id, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: authToken,
},
body: JSON.stringify(row),
});
return {
success: true,
message: "User deleted successfully on example service",
status: null,
};
} catch (error) {
return {
success: false,
message: "User delete failed on example service",
};
}
*/
};
export default action;
`;

View File

@@ -11,7 +11,7 @@ import DragIndicatorOutlinedIcon from "@mui/icons-material/DragIndicatorOutlined
import DeleteIcon from "@mui/icons-material/DeleteOutline";
import { FieldType, ISideDrawerFieldProps } from "@src/components/fields/types";
import { TableRowRef } from "@src/types/table";
import { TableRow, TableRowRef } from "@src/types/table";
import AddButton from "./AddButton";
import { getPseudoColumn } from "./utils";
@@ -29,6 +29,7 @@ function ArrayFieldInput({
onRemove,
onSubmit,
id,
row,
}: {
index: number;
onRemove: (index: number) => void;
@@ -37,6 +38,7 @@ function ArrayFieldInput({
onSubmit: () => void;
_rowy_ref: TableRowRef;
id: string;
row: TableRow;
}) {
const typeDetected = detectType(value);
@@ -80,6 +82,7 @@ function ArrayFieldInput({
column={getPseudoColumn(typeDetected, index, value)}
value={value}
_rowy_ref={_rowy_ref}
row={row}
/>
</Stack>
<Box
@@ -174,6 +177,7 @@ export default function ArraySideDrawerField({
onRemove={handleRemove}
index={index}
onSubmit={onSubmit}
row={props.row}
/>
))}
{provided.placeholder}

View File

@@ -6,6 +6,8 @@ import withRenderTableCell from "@src/components/Table/TableCell/withRenderTable
import DisplayCell from "./DisplayCell";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const SideDrawerField = lazy(
() =>
import("./SideDrawerField" /* webpackChunkName: "SideDrawerField-Array" */)
@@ -26,5 +28,6 @@ export const config: IFieldConfig = {
}),
SideDrawerField,
requireConfiguration: false,
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -0,0 +1,46 @@
import { IDisplayCellProps } from "@src/components/fields/types";
import { Link } from "react-router-dom";
import { Stack, IconButton } from "@mui/material";
import OpenIcon from "@mui/icons-material/OpenInBrowser";
import { useSubTableData } from "./utils";
export default function ArraySubTable({
column,
row,
_rowy_ref,
tabIndex,
}: IDisplayCellProps) {
const { documentCount, label, subTablePath } = useSubTableData(
column as any,
row,
_rowy_ref
);
if (!_rowy_ref) return null;
return (
<Stack
direction="row"
alignItems="center"
justifyContent="space-between"
style={{ paddingLeft: "var(--cell-padding)", width: "100%" }}
>
<div style={{ flexGrow: 1, overflow: "hidden" }}>
{documentCount} {column.name as string}: {label}
</div>
<IconButton
component={Link}
to={subTablePath}
className="row-hover-iconButton end"
size="small"
disabled={!subTablePath}
tabIndex={tabIndex}
>
<OpenIcon />
</IconButton>
</Stack>
);
}

View File

@@ -0,0 +1,32 @@
import { useAtom } from "jotai";
import { ISettingsProps } from "@src/components/fields/types";
import MultiSelect from "@rowy/multiselect";
import { FieldType } from "@src/constants/fields";
import { tableScope, tableColumnsOrderedAtom } from "@src/atoms/tableScope";
const Settings = ({ config, onChange }: ISettingsProps) => {
const [tableOrderedColumns] = useAtom(tableColumnsOrderedAtom, tableScope);
const columnOptions = tableOrderedColumns
.filter((column) =>
[
FieldType.shortText,
FieldType.singleSelect,
FieldType.email,
FieldType.phone,
].includes(column.type)
)
.map((c) => ({ label: c.name, value: c.key }));
return (
<MultiSelect
label="Parent label"
options={columnOptions}
value={config.parentLabel ?? []}
onChange={onChange("parentLabel")}
/>
);
};
export default Settings;

View File

@@ -0,0 +1,56 @@
import { useMemo } from "react";
import { useAtom } from "jotai";
import { selectAtom } from "jotai/utils";
import { find, isEqual } from "lodash-es";
import { ISideDrawerFieldProps } from "@src/components/fields/types";
import { Link } from "react-router-dom";
import { Box, Stack, IconButton } from "@mui/material";
import OpenIcon from "@mui/icons-material/OpenInBrowser";
import { tableScope, tableRowsAtom } from "@src/atoms/tableScope";
import { fieldSx, getFieldId } from "@src/components/SideDrawer/utils";
import { useSubTableData } from "./utils";
export default function ArraySubTable({
column,
_rowy_ref,
}: ISideDrawerFieldProps) {
const [row] = useAtom(
useMemo(
() =>
selectAtom(
tableRowsAtom,
(tableRows) => find(tableRows, ["_rowy_ref.path", _rowy_ref.path]),
isEqual
),
[_rowy_ref.path]
),
tableScope
);
const { documentCount, label, subTablePath } = useSubTableData(
column as any,
row as any,
_rowy_ref
);
return (
<Stack direction="row" id={getFieldId(column.key)}>
<Box sx={fieldSx}>
{documentCount} {column.name as string}: {label}
</Box>
<IconButton
component={Link}
to={subTablePath}
edge="end"
size="small"
sx={{ ml: 1 }}
disabled={!subTablePath}
>
<OpenIcon />
</IconButton>
</Stack>
);
}

View File

@@ -0,0 +1,35 @@
import { lazy } from "react";
import { IFieldConfig, FieldType } from "@src/components/fields/types";
import withRenderTableCell from "@src/components/Table/TableCell/withRenderTableCell";
import { ArraySubTable as ArraySubTableIcon } from "@src/assets/icons/ArraySubTable";
import DisplayCell from "./DisplayCell";
const SideDrawerField = lazy(
() =>
import(
"./SideDrawerField" /* webpackChunkName: "SideDrawerField-ArraySubTable" */
)
);
const Settings = lazy(
() => import("./Settings" /* webpackChunkName: "Settings-ArraySubTable" */)
);
export const config: IFieldConfig = {
type: FieldType.arraySubTable,
name: "Array SubTable (Alpha)",
group: "Connection",
dataType: "undefined",
initialValue: null,
icon: <ArraySubTableIcon />,
settings: Settings,
description: "A sub-table representing an array of objects in the row",
TableCell: withRenderTableCell(DisplayCell, null, "focus", {
usesRowData: true,
disablePadding: true,
}),
SideDrawerField,
initializable: false,
requireConfiguration: true,
requireCollectionTable: true,
};
export default config;

View File

@@ -0,0 +1,34 @@
import { useLocation } from "react-router-dom";
import { ROUTES } from "@src/constants/routes";
import { ColumnConfig, TableRow, TableRowRef } from "@src/types/table";
export const useSubTableData = (
column: ColumnConfig,
row: TableRow,
_rowy_ref: TableRowRef
) => {
const label = (column.config?.parentLabel ?? []).reduce((acc, curr) => {
if (acc !== "") return `${acc} - ${row[curr]}`;
else return row[curr];
}, "");
const documentCount: string = row[column.fieldName]?.count ?? "";
const location = useLocation();
const rootTablePath = decodeURIComponent(
location.pathname.split("/" + ROUTES.subTable)[0]
);
// Get params from URL: /table/:tableId/arraySubTable/:docPath/:arraySubTableKey
let subTablePath = [
rootTablePath,
ROUTES.arraySubTable,
encodeURIComponent(_rowy_ref.path),
column.key,
].join("/");
subTablePath += "?parentLabel=" + encodeURIComponent(label ?? "");
return { documentCount, label, subTablePath };
};

View File

@@ -5,6 +5,8 @@ import withRenderTableCell from "@src/components/Table/TableCell/withRenderTable
import CheckboxIcon from "@mui/icons-material/ToggleOnOutlined";
import DisplayCell from "./DisplayCell";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const EditorCell = lazy(
() => import("./EditorCell" /* webpackChunkName: "EditorCell-Checkbox" */)
);
@@ -42,5 +44,6 @@ export const config: IFieldConfig = {
defaultValue: false,
},
SideDrawerField,
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -5,6 +5,8 @@ import withRenderTableCell from "@src/components/Table/TableCell/withRenderTable
import CodeIcon from "@mui/icons-material/Code";
import DisplayCell from "./DisplayCell";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const Settings = lazy(
() => import("./Settings" /* webpackChunkName: "Settings-Code" */)
);
@@ -31,5 +33,6 @@ export const config: IFieldConfig = {
}),
SideDrawerField,
settings: Settings,
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -7,6 +7,8 @@ import ColorIcon from "@mui/icons-material/Colorize";
import DisplayCell from "./DisplayCell";
import { filterOperators, valueFormatter } from "./filters";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const EditorCell = lazy(
() => import("./EditorCell" /* webpackChunkName: "EditorCell-Color" */)
);
@@ -41,5 +43,6 @@ export const config: IFieldConfig = {
return null;
}
},
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -108,7 +108,7 @@ export default function PopupContents({
onChange={(e) => setQuery(e.target.value)}
fullWidth
variant="filled"
label="Search items"
// label="Search items"
hiddenLabel
placeholder="Search items"
InputProps={{

View File

@@ -11,16 +11,19 @@ export const replacer = (data: any) => (m: string, key: string) => {
return get(data, objKey, defaultValue);
};
export const baseFunction = `const connectorFn: Connector = async ({query, row, user, logging}) => {
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("connectorFn started")
// Import any NPM package needed
// const lodash = require('lodash');
return [];
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
};`;
export const baseFunction = `// Import any NPM package needed
// import _ from "lodash";
const connector: Connector = async ({ query, row, user, logging }) => {
logging.log("connector started");
// return [
// { id: "a", name: "Apple" },
// { id: "b", name: "Banana" },
// ];
};
export default connector;
`;
export const getLabel = (config: any, row: TableRow) => {
if (!config.labelFormatter) {

View File

@@ -4,6 +4,7 @@ import withRenderTableCell from "@src/components/Table/TableCell/withRenderTable
import { CreatedAt as CreatedAtIcon } from "@src/assets/icons";
import DisplayCell from "./DisplayCell";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const SideDrawerField = lazy(
() =>
@@ -27,5 +28,7 @@ export const config: IFieldConfig = {
TableCell: withRenderTableCell(DisplayCell, null),
SideDrawerField,
settings: Settings,
requireCollectionTable: true,
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -4,6 +4,7 @@ import withRenderTableCell from "@src/components/Table/TableCell/withRenderTable
import { CreatedBy as CreatedByIcon } from "@src/assets/icons";
import DisplayCell from "./DisplayCell";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const SideDrawerField = lazy(
() =>
@@ -28,5 +29,7 @@ export const config: IFieldConfig = {
TableCell: withRenderTableCell(DisplayCell, null),
SideDrawerField,
settings: Settings,
requireCollectionTable: true,
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -7,6 +7,7 @@ import { DATE_FORMAT } from "@src/constants/dates";
import DateIcon from "@mui/icons-material/TodayOutlined";
import DisplayCell from "./DisplayCell";
import { filterOperators, valueFormatter } from "./filters";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const EditorCell = lazy(
() => import("./EditorCell" /* webpackChunkName: "EditorCell-Date" */)
@@ -35,8 +36,14 @@ export const config: IFieldConfig = {
filter: { operators: filterOperators, valueFormatter },
settings: Settings,
csvImportParser: (value, config) => parse(value, DATE_FORMAT, new Date()),
csvExportFormatter: (value: any, config?: any) =>
format(value.toDate(), DATE_FORMAT),
csvExportFormatter: (value: any, config?: any) => {
if (typeof value === "number") {
return format(new Date(value), DATE_FORMAT);
} else {
return format(value.toDate(), DATE_FORMAT);
}
},
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -7,6 +7,7 @@ import { DATE_TIME_FORMAT } from "@src/constants/dates";
import DateTimeIcon from "@mui/icons-material/AccessTime";
import DisplayCell from "./DisplayCell";
import { filterOperators, valueFormatter } from "./filters";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const EditorCell = lazy(
() => import("./EditorCell" /* webpackChunkName: "EditorCell-DateTime" */)
@@ -47,8 +48,14 @@ export const config: IFieldConfig = {
},
settings: Settings,
csvImportParser: (value) => new Date(value),
csvExportFormatter: (value: any, config?: any) =>
format(value.toDate(), DATE_TIME_FORMAT),
csvExportFormatter: (value: any, config?: any) => {
if (typeof value === "number") {
return format(new Date(value), DATE_TIME_FORMAT);
} else {
return format(value.toDate(), DATE_TIME_FORMAT);
}
},
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -66,27 +66,26 @@ export default function Settings({
? config.derivativeFn
: config?.script
? `const derivative:Derivative = async ({row,ref,db,storage,auth,logging})=>{
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("derivative started")
// Import any NPM package needed
// const lodash = require('lodash');
${config.script.replace(/utilFns.getSecret/g, "rowy.secrets.get")}
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`
: `const derivative:Derivative = async ({row,ref,db,storage,auth,logging})=>{
// WRITE YOUR CODE ONLY BELOW THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
logging.log("derivative started")
// Import any NPM package needed
// const lodash = require('lodash');
: `// Import any NPM package needed
// import _ from "lodash";
const derivative: Derivative = async ({ row, ref, db, storage, auth, logging }) => {
logging.log("derivative started");
// Example:
// const sum = row.a + row.b;
// return sum;
// WRITE YOUR CODE ONLY ABOVE THIS LINE. DO NOT WRITE CODE/COMMENTS OUTSIDE THE FUNCTION BODY
}`;
};
export default derivative;
`;
return (
<>

View File

@@ -22,5 +22,6 @@ export const config: IFieldConfig = {
settingsValidator,
requireConfiguration: true,
requireCloudFunction: true,
requireCollectionTable: true,
};
export default config;

View File

@@ -4,6 +4,7 @@ import withRenderTableCell from "@src/components/Table/TableCell/withRenderTable
import DurationIcon from "@mui/icons-material/TimerOutlined";
import DisplayCell from "./DisplayCell";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const SideDrawerField = lazy(
() =>
@@ -24,5 +25,6 @@ export const config: IFieldConfig = {
popoverProps: { PaperProps: { sx: { p: 1 } } },
}),
SideDrawerField,
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -0,0 +1,83 @@
import { useAtom } from "jotai";
import { find, get } from "lodash-es";
import { useSnackbar } from "notistack";
import OpenIcon from "@mui/icons-material/OpenInNewOutlined";
import { Copy } from "@src/assets/icons";
import { FileIcon } from ".";
import {
tableScope,
tableSchemaAtom,
tableRowsAtom,
} from "@src/atoms/tableScope";
import { IFieldConfig } from "@src/components/fields/types";
export interface IContextMenuActions {
label: string;
icon: React.ReactNode;
onClick: () => void;
}
export const ContextMenuActions: IFieldConfig["contextMenuActions"] = (
selectedCell,
reset
) => {
const [tableSchema] = useAtom(tableSchemaAtom, tableScope);
const [tableRows] = useAtom(tableRowsAtom, tableScope);
const { enqueueSnackbar } = useSnackbar();
const selectedCol = tableSchema.columns?.[selectedCell.columnKey];
if (!selectedCol) return [];
const selectedRow = find(tableRows, ["_rowy_ref.path", selectedCell.path]);
const cellValue = get(selectedRow, selectedCol.fieldName) || [];
const isEmpty =
cellValue === "" ||
cellValue === null ||
cellValue === undefined ||
cellValue.length === 0;
const isSingleValue = isEmpty || cellValue?.length === 1;
const handleCopyFileURL = (fileObj: RowyFile) => () => {
navigator.clipboard.writeText(fileObj.downloadURL);
enqueueSnackbar("Copied file URL");
reset();
};
const handleViewFile = (fileObj: RowyFile) => () => {
window.open(fileObj.downloadURL, "_blank");
reset();
};
return [
{
label: "Copy file URL",
icon: <Copy />,
onClick: isSingleValue ? handleCopyFileURL(cellValue[0]) : undefined,
disabled: isEmpty,
subItems: isSingleValue
? []
: cellValue.map((fileObj: RowyFile, index: number) => ({
label: fileObj.name || "File " + (index + 1),
icon: <FileIcon />,
onClick: handleCopyFileURL(fileObj),
})),
},
{
label: "View file",
icon: <OpenIcon />,
onClick: isSingleValue ? handleViewFile(cellValue[0]) : undefined,
disabled: isEmpty,
subItems: isSingleValue
? []
: cellValue.map((fileObj: RowyFile, index: number) => ({
label: fileObj.name || "File " + (index + 1),
icon: <FileIcon />,
onClick: handleViewFile(fileObj),
})),
},
];
};
export default ContextMenuActions;

View File

@@ -4,6 +4,7 @@ import withRenderTableCell from "@src/components/Table/TableCell/withRenderTable
import FileIcon from "@mui/icons-material/AttachFile";
import DisplayCell from "./DisplayCell";
import ContextMenuActions from "./ContextMenuActions";
const EditorCell = lazy(
() => import("./EditorCell" /* webpackChunkName: "EditorCell-File" */)
@@ -26,6 +27,7 @@ export const config: IFieldConfig = {
disablePadding: true,
}),
SideDrawerField,
contextMenuActions: ContextMenuActions,
};
export default config;

View File

@@ -47,7 +47,9 @@ export default function useFileUpload(
async (files: File[]) => {
const { uploads, failures } = await upload({
docRef,
fieldName,
fieldName: docRef.arrayTableData
? `${docRef.arrayTableData?.parentField}/${docRef.arrayTableData?.index}/${fieldName}`
: fieldName,
files,
});
updateField({
@@ -55,6 +57,7 @@ export default function useFileUpload(
fieldName,
value: uploads,
useArrayUnion: true,
arrayTableData: docRef.arrayTableData,
});
return { uploads, failures };
},
@@ -69,10 +72,11 @@ export default function useFileUpload(
value: [file],
useArrayRemove: true,
disableCheckEquality: true,
arrayTableData: docRef.arrayTableData,
});
deleteUpload(file);
},
[deleteUpload, docRef, fieldName, updateField]
[deleteUpload, docRef.arrayTableData, docRef.path, fieldName, updateField]
);
// Drag and Drop

View File

@@ -6,6 +6,7 @@ import { defaultFn, getDisplayCell } from "./util";
export default function Formula(props: IDisplayCellProps) {
const { result, error, loading } = useFormula({
column: props.column,
row: props.row,
ref: props._rowy_ref,
listenerFields: props.column.config?.listenerFields || [],

View File

@@ -0,0 +1,46 @@
import { ISideDrawerFieldProps } from "@src/components/fields/types";
import { IFieldConfig } from "@src/components/fields/types";
import { getFieldProp } from "@src/components/fields";
import { isEmpty } from "lodash-es";
import { createElement } from "react";
export default function Formula({
column,
onChange,
onSubmit,
_rowy_ref,
onDirty,
row,
}: ISideDrawerFieldProps) {
const value = row[`_rowy_formulaValue_${column.key}`];
let type = column.type;
if (column.config && column.config.renderFieldType) {
type = column.config.renderFieldType;
}
const fieldComponent: IFieldConfig["SideDrawerField"] = getFieldProp(
"SideDrawerField",
type
);
// Should not reach this state
if (isEmpty(fieldComponent)) {
console.error("Could not find SideDrawerField component", column);
return null;
}
return (
<>
{createElement(fieldComponent, {
column,
_rowy_ref,
value,
onDirty,
onChange,
onSubmit,
disabled: true,
row,
})}
</>
);
}

View File

@@ -1,9 +1,16 @@
import { lazy } from "react";
import FormulaIcon from "@mui/icons-material/Functions";
import { IFieldConfig, FieldType } from "@src/components/fields/types";
import withRenderTableCell from "@src/components/Table/TableCell/withRenderTableCell";
import DisplayCell from "./DisplayCell";
import Settings, { settingsValidator } from "./Settings";
const SideDrawerField = lazy(
() =>
import(
"./SideDrawerField" /* webpackChunkName: "SideDrawerField-Formula" */
)
);
export const config: IFieldConfig = {
type: FieldType.formula,
@@ -16,7 +23,7 @@ export const config: IFieldConfig = {
TableCell: withRenderTableCell(DisplayCell as any, null, undefined, {
usesRowData: true,
}),
SideDrawerField: () => null as any,
SideDrawerField,
settings: Settings,
settingsValidator: settingsValidator,
requireConfiguration: true,

View File

@@ -1,9 +1,13 @@
import { useEffect, useMemo, useState } from "react";
import { pick, zipObject } from "lodash-es";
import { useAtom } from "jotai";
import { useAtom, useSetAtom } from "jotai";
import { TableRow, TableRowRef } from "@src/types/table";
import { tableColumnsOrderedAtom, tableScope } from "@src/atoms/tableScope";
import { TableRow, TableRowRef, ColumnConfig } from "@src/types/table";
import {
tableColumnsOrderedAtom,
tableScope,
updateFieldAtom,
} from "@src/atoms/tableScope";
import {
listenerFieldTypes,
@@ -12,11 +16,13 @@ import {
} from "./util";
export const useFormula = ({
column,
row,
ref,
listenerFields,
formulaFn,
}: {
column: ColumnConfig;
row: TableRow;
ref: TableRowRef;
listenerFields: string[];
@@ -78,5 +84,14 @@ export const useFormula = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [useDeepCompareMemoize(listeners), formulaFn]);
const updateField = useSetAtom(updateFieldAtom, tableScope);
useEffect(() => {
updateField({
path: row._rowy_ref.path,
fieldName: `_rowy_formulaValue_${column.key}`,
value: result,
});
}, [result, column.key, row._rowy_ref.path, updateField]);
return { result, error, loading };
};

View File

@@ -1,10 +1,10 @@
import { lazy } from "react";
import { GeoPoint } from "firebase/firestore";
import { IFieldConfig, FieldType } from "@src/components/fields/types";
import withRenderTableCell from "@src/components/Table/TableCell/withRenderTableCell";
import GeoPointIcon from "@mui/icons-material/PinDropOutlined";
import DisplayCell from "./DisplayCell";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const SideDrawerField = lazy(
() =>
@@ -15,7 +15,7 @@ const SideDrawerField = lazy(
export const config: IFieldConfig = {
type: FieldType.geoPoint,
name: "GeoPoint (Alpha)",
name: "GeoPoint",
group: "Numeric",
dataType: "{latitude:number; longitude:number}",
initialValue: {},
@@ -25,17 +25,6 @@ export const config: IFieldConfig = {
popoverProps: { PaperProps: { sx: { p: 1, pt: 0 } } },
}),
SideDrawerField,
csvImportParser: (value: string) => {
try {
const { latitude, longitude } = JSON.parse(value);
if (latitude && longitude) {
return new GeoPoint(latitude, longitude);
}
throw new Error();
} catch (e) {
console.error("Invalid GeoPoint value");
return null;
}
},
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -4,6 +4,7 @@ import withRenderTableCell from "@src/components/Table/TableCell/withRenderTable
import { Markdown as MarkdownIcon } from "@src/assets/icons";
import DisplayCell from "./DisplayCell";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const SideDrawerField = lazy(
() =>
@@ -23,5 +24,6 @@ export const config: IFieldConfig = {
description: "Markdown editor with preview",
TableCell: withRenderTableCell(DisplayCell, SideDrawerField, "popover"),
SideDrawerField,
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -1,12 +1,16 @@
import { IDisplayCellProps } from "@src/components/fields/types";
import { ButtonBase, Grid, Tooltip } from "@mui/material";
import { ButtonBase, Grid, Tooltip, useTheme } from "@mui/material";
import WarningIcon from "@mui/icons-material/WarningAmber";
import { ChevronDown } from "@src/assets/icons";
import { sanitiseValue } from "./utils";
import ChipList from "@src/components/Table/TableCell/ChipList";
import FormattedChip from "@src/components/FormattedChip";
import {
getColors,
IColors,
} from "@src/components/fields/SingleSelect/Settings";
export default function MultiSelect({
value,
@@ -14,7 +18,11 @@ export default function MultiSelect({
disabled,
tabIndex,
rowHeight,
column,
}: IDisplayCellProps) {
const colors: IColors[] = column?.config?.colors ?? [];
const { mode } = useTheme().palette;
const rendered =
typeof value === "string" && value !== "" ? (
<div style={{ flexGrow: 1, paddingLeft: "var(--cell-padding)" }}>
@@ -30,7 +38,12 @@ export default function MultiSelect({
(item) =>
typeof item === "string" && (
<Grid item key={item}>
<FormattedChip label={item} />
<FormattedChip
label={item}
sx={{
backgroundColor: getColors(colors, item)[mode],
}}
/>
</Grid>
)
)}

View File

@@ -1,12 +1,14 @@
import { ISideDrawerFieldProps } from "@src/components/fields/types";
import { Grid, Button, Tooltip } from "@mui/material";
import { Grid, Button, Tooltip, useTheme } from "@mui/material";
import WarningIcon from "@mui/icons-material/WarningAmber";
import MultiSelectComponent from "@rowy/multiselect";
import FormattedChip from "@src/components/FormattedChip";
import { fieldSx } from "@src/components/SideDrawer/utils";
import { sanitiseValue } from "./utils";
import { getColors } from "@src/components/fields/SingleSelect/Settings";
import palette, { paletteToMui } from "@src/theme/palette";
export default function MultiSelect({
column,
@@ -15,7 +17,10 @@ export default function MultiSelect({
onSubmit,
disabled,
}: ISideDrawerFieldProps) {
const defaultColor = paletteToMui(palette.aGray);
const config = column.config ?? {};
const colors = column.config?.colors ?? [];
const { mode } = useTheme().palette;
const handleDelete = (index: number) => () => {
const newValues = [...value];
@@ -75,6 +80,10 @@ export default function MultiSelect({
<FormattedChip
label={item}
onDelete={disabled ? undefined : handleDelete(i)}
sx={{
backgroundColor:
getColors(colors, item)[mode] || defaultColor[mode],
}}
/>
</Grid>
)

View File

@@ -5,6 +5,7 @@ import withRenderTableCell from "@src/components/Table/TableCell/withRenderTable
import { MultiSelect as MultiSelectIcon } from "@src/assets/icons";
import DisplayCell from "./DisplayCell";
import { filterOperators } from "./Filter";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const EditorCell = lazy(
() => import("./EditorCell" /* webpackChunkName: "EditorCell-MultiSelect" */)
@@ -48,5 +49,6 @@ export const config: IFieldConfig = {
filter: {
operators: filterOperators,
},
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -6,6 +6,7 @@ import RatingIcon from "@mui/icons-material/StarBorder";
import DisplayCell from "./DisplayCell";
import EditorCell from "./EditorCell";
import { filterOperators } from "@src/components/fields/Number/Filter";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const SideDrawerField = lazy(
() =>
@@ -44,5 +45,6 @@ export const config: IFieldConfig = {
return null;
}
},
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -29,5 +29,6 @@ export const config: IFieldConfig = {
}),
SideDrawerField,
filter: { operators: filterOperators, valueFormatter: valueFormatter },
csvExportFormatter: (value: any) => value?.path,
};
export default config;

View File

@@ -1,16 +1,24 @@
import { IDisplayCellProps } from "@src/components/fields/types";
import { ButtonBase } from "@mui/material";
import { ButtonBase, Chip } from "@mui/material";
import { ChevronDown } from "@src/assets/icons";
import { useTheme } from "@mui/material";
import { sanitiseValue } from "./utils";
import ChipList from "@src/components/Table/TableCell/ChipList";
import { getColors, IColors } from "./Settings";
export default function SingleSelect({
value,
showPopoverCell,
disabled,
tabIndex,
column,
rowHeight,
}: IDisplayCellProps) {
const colors: IColors[] = column?.config?.colors ?? [];
const { mode } = useTheme().palette;
const rendered = (
<div
style={{
@@ -19,7 +27,17 @@ export default function SingleSelect({
paddingLeft: "var(--cell-padding)",
}}
>
{sanitiseValue(value)}
<ChipList rowHeight={rowHeight}>
{value && (
<Chip
size="small"
label={sanitiseValue(value)}
sx={{
backgroundColor: getColors(colors, value)[mode],
}}
/>
)}
</ChipList>
</div>
);

View File

@@ -14,6 +14,9 @@ import {
} from "@mui/material";
import AddIcon from "@mui/icons-material/AddCircle";
import RemoveIcon from "@mui/icons-material/CancelRounded";
import ColorSelect, {
SelectColorThemeOptions,
} from "@src/components/SelectColors";
import {
DragDropContext,
@@ -23,6 +26,7 @@ import {
NotDraggingStyle,
} from "react-beautiful-dnd";
import DragIndicatorOutlinedIcon from "@mui/icons-material/DragIndicatorOutlined";
import palette, { paletteToMui } from "@src/theme/palette";
const getItemStyle = (
isDragging: boolean,
@@ -33,10 +37,29 @@ const getItemStyle = (
...draggableStyle,
});
export interface IColors extends SelectColorThemeOptions {
name: string;
}
export const getColors = (
list: IColors[],
option: string
): SelectColorThemeOptions => {
const defaultColor = paletteToMui(palette.aGray);
const key = option.toLocaleLowerCase().replace(" ", "_").trim();
const color = list.find((opt: IColors) => opt.name === key);
// Null check in return
return color || defaultColor;
};
export default function Settings({ onChange, config }: ISettingsProps) {
const listEndRef: any = useRef(null);
const options = config.options ?? [];
const [newOption, setNewOption] = useState("");
/* State for holding Chip Colors for Select and MultiSelect */
let colors = config.colors ?? [];
const handleAdd = () => {
if (newOption.trim() !== "") {
if (options.includes(newOption)) {
@@ -49,6 +72,38 @@ export default function Settings({ onChange, config }: ISettingsProps) {
}
};
const handleChipColorChange = (
type: "save" | "delete",
key: string,
color?: SelectColorThemeOptions
) => {
const _key = key.toLocaleLowerCase().replace(" ", "_").trim();
const exists = colors.findIndex((option: IColors) => option.name === _key);
// If saving Check if object with the `color.name` is equal to `_key` and replace value at the index of `exists`
// Else save new value with `_key` as `color.name`
if (type === "save") {
if (exists !== -1) {
colors[exists] = { name: _key, ...{ ...color } };
onChange("colors")(colors);
} else {
onChange("colors")([...colors, { name: _key, ...{ ...color } }]);
}
}
// If deleting Filter out object that has `color.name` equals to `_key`
if (type === "delete") {
const updatedColors = colors.filter(
(option: IColors) => option.name !== _key
);
onChange("colors")(updatedColors);
}
};
const handleItemDelete = (option: string) => {
onChange("options")(options.filter((o: string) => o !== option));
handleChipColorChange("delete", option);
};
const handleOnDragEnd = (result: any) => {
if (!result.destination) return;
const [removed] = options.splice(result.source.index, 1);
@@ -92,6 +147,7 @@ export default function Settings({ onChange, config }: ISettingsProps) {
{...provided.dragHandleProps}
item
sx={{ display: "flex" }}
alignItems="center"
>
<DragIndicatorOutlinedIcon
color="disabled"
@@ -101,16 +157,26 @@ export default function Settings({ onChange, config }: ISettingsProps) {
},
]}
/>
<Typography>{option}</Typography>
<Grid
container
direction="row"
alignItems="center"
gap={2}
>
<ColorSelect
key={option}
initialValue={getColors(colors, option)}
handleChange={(color) =>
handleChipColorChange("save", option, color)
}
/>
<Typography>{option}</Typography>
</Grid>
</Grid>
<Grid item>
<IconButton
aria-label="Remove"
onClick={() =>
onChange("options")(
options.filter((o: string) => o !== option)
)
}
onClick={() => handleItemDelete(option)}
>
{<RemoveIcon />}
</IconButton>

View File

@@ -6,6 +6,7 @@ import { SingleSelect as SingleSelectIcon } from "@src/assets/icons";
import DisplayCell from "./DisplayCell";
import EditorCell from "./EditorCell";
import { filterOperators } from "@src/components/fields/ShortText/Filter";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const SideDrawerField = lazy(
() =>
@@ -21,7 +22,7 @@ export const config: IFieldConfig = {
type: FieldType.singleSelect,
name: "Single Select",
group: "Select",
dataType: "string | null",
dataType: "string",
initialValue: null,
initializable: true,
icon: <SingleSelectIcon />,
@@ -35,5 +36,6 @@ export const config: IFieldConfig = {
settings: Settings,
filter: { operators: filterOperators },
requireConfiguration: true,
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -5,6 +5,7 @@ import withRenderTableCell from "@src/components/Table/TableCell/withRenderTable
import { Slider as SliderIcon } from "@src/assets/icons";
import DisplayCell from "./DisplayCell";
import { filterOperators } from "@src/components/fields/Number/Filter";
import BasicContextMenuActions from "@src/components/Table/ContextMenu/BasicCellContextMenuActions";
const SideDrawerField = lazy(
() =>
@@ -44,5 +45,6 @@ export const config: IFieldConfig = {
return null;
}
},
contextMenuActions: BasicContextMenuActions,
};
export default config;

View File

@@ -31,5 +31,6 @@ export const config: IFieldConfig = {
SideDrawerField,
initializable: false,
requireConfiguration: true,
requireCollectionTable: true,
};
export default config;

View File

@@ -2,6 +2,7 @@ import { useLocation } from "react-router-dom";
import { ROUTES } from "@src/constants/routes";
import { ColumnConfig, TableRow, TableRowRef } from "@src/types/table";
import get from "lodash-es/get";
export const useSubTableData = (
column: ColumnConfig,
@@ -9,8 +10,8 @@ export const useSubTableData = (
_rowy_ref: TableRowRef
) => {
const label = (column.config?.parentLabel ?? []).reduce((acc, curr) => {
if (acc !== "") return `${acc} - ${row[curr]}`;
else return row[curr];
if (acc !== "") return `${acc} - ${get(row, curr)}`;
else return get(row, curr);
}, "");
const documentCount: string = row[column.fieldName]?.count ?? "";

Some files were not shown because too many files have changed in this diff Show More