Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
+32
@@ -0,0 +1,32 @@
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { ColumnDto } from "~/application/dtos/data/ColumnDto";
|
||||
import RowCard from "./RowCard";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import clsx from "clsx";
|
||||
|
||||
export default function RenderCard({
|
||||
layout,
|
||||
item,
|
||||
entity,
|
||||
columns,
|
||||
allEntities,
|
||||
routes,
|
||||
actions,
|
||||
href,
|
||||
}: {
|
||||
layout: "table" | "grid" | "board" | "card";
|
||||
item: RowWithDetails;
|
||||
entity: EntityWithDetails;
|
||||
columns: ColumnDto[];
|
||||
allEntities: EntityWithDetails[];
|
||||
routes: EntitiesApi.Routes | undefined;
|
||||
actions?: (row: RowWithDetails) => { title?: string; href?: string; onClick?: () => void; isLoading?: boolean; render?: React.ReactNode }[];
|
||||
href?: string | undefined;
|
||||
}) {
|
||||
return (
|
||||
<div className={clsx("border-border bg-background rounded-md border p-3 shadow-2xs", href && "hover:border-border hover:shadow-md")}>
|
||||
<RowCard layout={layout} item={item} entity={entity} columns={columns} allEntities={allEntities} routes={routes} actions={actions} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
import { FormEvent, useEffect, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Form, useLocation, useSubmit, useNavigation } from "react-router";
|
||||
import { DefaultLogActions } from "~/application/dtos/shared/DefaultLogActions";
|
||||
import UserAvatarBadge from "~/components/core/users/UserAvatarBadge";
|
||||
import UserBadge from "~/components/core/users/UserBadge";
|
||||
import CalendarFilledIcon from "~/components/ui/icons/CalendarFilledIcon";
|
||||
import ChatAltIcon from "~/components/ui/icons/ChatAltIcon";
|
||||
import PencilIcon from "~/components/ui/icons/PencilIcon";
|
||||
import QuestionMarkFilledIcon from "~/components/ui/icons/QuestionMarkFilledIcon";
|
||||
import { LogWithDetails } from "~/utils/db/logs.db.server";
|
||||
import RowLogComment from "./RowLogComment";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import clsx from "clsx";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
interface Props {
|
||||
items: LogWithDetails[];
|
||||
hasActivity?: boolean;
|
||||
hasComments?: boolean;
|
||||
onSubmit?: (formData: FormData) => void;
|
||||
withTitle?: boolean;
|
||||
autoFocus?: boolean;
|
||||
}
|
||||
|
||||
export default function RowActivity({ items, hasActivity = true, hasComments, onSubmit, withTitle = true, autoFocus }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const transition = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const isAdding = transition.state === "submitting" && transition.formData?.get("action") === "comment";
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const location = useLocation();
|
||||
|
||||
useEffect(() => {
|
||||
formRef.current?.reset();
|
||||
}, [isAdding]);
|
||||
|
||||
const sortedItems = () => {
|
||||
const filteredItems = items.filter((item) => {
|
||||
if (item.commentId && !hasComments) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return filteredItems.slice().sort((x, y) => {
|
||||
if (x.createdAt && y.createdAt) {
|
||||
return x.createdAt > y.createdAt ? 1 : -1;
|
||||
}
|
||||
return 1;
|
||||
});
|
||||
};
|
||||
|
||||
function getActionDescription(item: LogWithDetails) {
|
||||
return item.action;
|
||||
}
|
||||
|
||||
function handleSubmit(e: FormEvent<HTMLFormElement>) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
const formData = new FormData(e.currentTarget);
|
||||
appendCSRFToken(formData);
|
||||
if (onSubmit !== undefined) {
|
||||
onSubmit(formData);
|
||||
} else {
|
||||
submit(formData, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="relative">
|
||||
<div className="space-y-3">
|
||||
<div className="divide-border divide-y ">
|
||||
{withTitle && (
|
||||
<div className="pb-2">
|
||||
<h2 id="activity-title" className="text-foreground text-sm font-medium">
|
||||
{t("app.shared.activity.title")}
|
||||
</h2>
|
||||
</div>
|
||||
)}
|
||||
<div className={clsx("space-y-6 text-xs", withTitle && "pt-4")}>
|
||||
{/* Activity feed*/}
|
||||
<div className="">
|
||||
<ul className="-mb-8 space-y-6 pb-6">
|
||||
{sortedItems().map((item, idx) => (
|
||||
<li key={item.id}>
|
||||
<div className="relative">
|
||||
{idx !== sortedItems().length - 1 ? <span className="absolute left-5 top-5 -ml-px h-full w-0.5 bg-gray-200" aria-hidden="true" /> : null}
|
||||
<div className="relative flex items-start space-x-3">
|
||||
{item.comment ? (
|
||||
<>{hasComments && <RowLogComment item={item} />}</>
|
||||
) : (
|
||||
<>
|
||||
<div>
|
||||
<div className="relative px-1">
|
||||
<div className="relative">
|
||||
<UserAvatarBadge className="h-9 w-9" avatar={item.user?.avatar} />
|
||||
|
||||
<span className="bg-secondary absolute -bottom-0.5 -right-1 rounded-tl px-0.5 py-px">
|
||||
{/* <TagIcon className="h-4 w-4 text-muted-foreground" aria-hidden="true" /> */}
|
||||
{item.action === DefaultLogActions.Created ? (
|
||||
<CalendarFilledIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
) : item.action === DefaultLogActions.Updated ? (
|
||||
<PencilIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
) : (
|
||||
<QuestionMarkFilledIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 py-0">
|
||||
<div className=" text-muted-foreground">
|
||||
<span className="mr-0.5 flex items-center space-x-1 text-sm">
|
||||
<div className="text-foreground font-medium">
|
||||
{item.user && (
|
||||
<span>
|
||||
<UserBadge item={item.user} withEmail={false} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</span>
|
||||
|
||||
<span className="mr-0.5" title={JSON.stringify(item.details) !== JSON.stringify("{}") ? item.details?.toString() : ""}>
|
||||
{getActionDescription(item)}
|
||||
</span>
|
||||
<span className="whitespace-nowrap pt-1">
|
||||
<time dateTime={new Date(item.createdAt).toISOString()} title={formatters.dateTime(item.createdAt, { timeStyle: "medium" })}>
|
||||
{formatters.relativeDate(item.createdAt)}
|
||||
</time>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{hasComments && (
|
||||
<div className="">
|
||||
<div className="flex space-x-3">
|
||||
<div className="shrink-0">
|
||||
<div className="relative px-1">
|
||||
<UserAvatarBadge className="h-9 w-9" avatar={appOrAdminData.user?.avatar} />
|
||||
|
||||
<span className="bg-secondary absolute -bottom-0.5 -right-1 rounded-tl px-0.5 py-px">
|
||||
<ChatAltIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<Form ref={formRef} onSubmit={handleSubmit} method="post" className="space-y-2">
|
||||
<div>
|
||||
<input hidden readOnly name="action" value="comment" />
|
||||
<label htmlFor="comment" className="sr-only">
|
||||
{t("shared.comment")}
|
||||
</label>
|
||||
<textarea
|
||||
autoFocus={autoFocus}
|
||||
required
|
||||
id="comment"
|
||||
name="comment"
|
||||
rows={3}
|
||||
className={clsx(
|
||||
"border-border block w-full rounded-md border shadow-2xs focus:border-gray-900 focus:ring-gray-900 sm:text-sm",
|
||||
(isAdding || !appOrAdminData.user) && "bg-secondary/90 cursor-not-allowed"
|
||||
)}
|
||||
placeholder={t("shared.addComment")}
|
||||
defaultValue={""}
|
||||
disabled={isAdding || !appOrAdminData.user}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-end space-x-4">
|
||||
<Button variant="outline" disabled={isAdding || !appOrAdminData.user} type="submit">
|
||||
{t("shared.comment")}
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
import clsx from "clsx";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ColumnDto } from "~/application/dtos/data/ColumnDto";
|
||||
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import RowDisplayHeaderHelper from "~/utils/helpers/RowDisplayHeaderHelper";
|
||||
import RowDisplayValueHelper from "~/utils/helpers/RowDisplayValueHelper";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
|
||||
interface Props {
|
||||
entity: EntityWithDetails;
|
||||
item: RowWithDetails;
|
||||
layout: string;
|
||||
columns?: ColumnDto[];
|
||||
allEntities: EntityWithDetails[];
|
||||
routes?: EntitiesApi.Routes;
|
||||
actions?: (row: RowWithDetails) => {
|
||||
title?: string;
|
||||
href?: string;
|
||||
onClick?: () => void;
|
||||
isLoading?: boolean;
|
||||
render?: React.ReactNode;
|
||||
}[];
|
||||
}
|
||||
export default function RowCard({ entity, item, columns, layout, allEntities, routes, actions }: Props) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [headers, setHeaders] = useState<RowHeaderDisplayDto<RowWithDetails>[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
setHeaders(RowDisplayHeaderHelper.getDisplayedHeaders({ entity, columns, layout, allEntities: allEntities, t, i18n, routes }));
|
||||
}, [entity, columns, layout, allEntities, t, i18n, routes]);
|
||||
|
||||
return (
|
||||
<div className="text-muted-foreground flex flex-col space-y-2 text-sm whitespace-nowrap">
|
||||
{headers.map((header, idx) => {
|
||||
return (
|
||||
<div key={idx} className={clsx("flex flex-col", header.className)}>
|
||||
<div className="text-muted-foreground text-xs font-medium">{translateLabel(t, i18n, header.title)}</div>
|
||||
<div>{RowDisplayValueHelper.displayRowValue(t, header, item, idx)}</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{actions && (
|
||||
<div className="flex flex-col space-y-2">
|
||||
{actions(item).map((action, idx) => {
|
||||
return (
|
||||
<Fragment key={idx}>
|
||||
{action.render ?? (
|
||||
<ButtonSecondary
|
||||
className="w-full"
|
||||
to={action.href}
|
||||
isLoading={action.isLoading}
|
||||
onClick={(e) => {
|
||||
if (action.onClick) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
action.onClick();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex w-full justify-center">{action.title}</div>
|
||||
</ButtonSecondary>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import { RowWithCreatedBy } from "~/utils/db/entities/rows.db.server";
|
||||
import { DateDisplay } from "~/utils/shared/DateUtils";
|
||||
import RowCreatedByBadge from "./RowCreatedByBadge";
|
||||
|
||||
interface Props {
|
||||
row: RowWithCreatedBy;
|
||||
by?: { withEmail?: boolean };
|
||||
date?: { displays?: DateDisplay[] };
|
||||
}
|
||||
export default function RowCreatedBadge({ row, by = { withEmail: true }, date = { displays: ["ymd"] } }: Props) {
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
{date && <DateCell displays={date.displays} date={row.createdAt} />}
|
||||
{by && <RowCreatedByBadge row={row} withEmail={by.withEmail} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { RowWithCreatedBy } from "~/utils/db/entities/rows.db.server";
|
||||
|
||||
interface Props {
|
||||
row: RowWithCreatedBy;
|
||||
withEmail?: boolean;
|
||||
}
|
||||
export default function RowCreatedByBadge({ row, withEmail = true }: Props) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex items-center space-x-1">
|
||||
{row.createdByUser && (
|
||||
<div className="text-muted-foreground flex items-baseline space-x-1 text-xs">
|
||||
<div className="font-normal">
|
||||
{t("shared.by")} {row.createdByUser.firstName} {row.createdByUser.lastName}
|
||||
</div>{" "}
|
||||
{withEmail && <span className="italic">({row.createdByUser.email})</span>}
|
||||
</div>
|
||||
)}{" "}
|
||||
{row.createdByApiKey && (
|
||||
<div className="text-muted-foreground flex items-baseline space-x-1">
|
||||
<div className="font-normal">
|
||||
{t("shared.by")} {t("models.apiKey.object")}
|
||||
</div>{" "}
|
||||
<span className="text-xs italic">({row.createdByApiKey.alias})</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+985
@@ -0,0 +1,985 @@
|
||||
import { RowWithDetails, RowWithValues } from "~/utils/db/entities/rows.db.server";
|
||||
import { EntityWithDetails, PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { Dispatch, forwardRef, Fragment, ReactNode, Ref, SetStateAction, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { updateItemByIdx } from "~/utils/shared/ObjectUtils";
|
||||
import { useNavigation, useParams, useSearchParams, useSubmit } from "react-router";
|
||||
import { RowValueDto } from "~/application/dtos/entities/RowValueDto";
|
||||
import FormGroup, { RefFormGroup } from "~/components/ui/forms/FormGroup";
|
||||
import InputGroup from "~/components/ui/forms/InputGroup";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import RowValueInput, { RefRowValueInput } from "./RowValueInput";
|
||||
import PropertyAttributeHelper from "~/utils/helpers/PropertyAttributeHelper";
|
||||
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { EntityRelationshipWithDetails } from "~/utils/db/entities/entityRelationships.db.server";
|
||||
import RowListFetcher from "../../../modules/rows/fetchers/RowListFetcher";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
|
||||
import RelationshipHelper from "~/utils/helpers/RelationshipHelper";
|
||||
import RowsList from "./RowsList";
|
||||
import { EntityViewWithDetails } from "~/utils/db/entities/entityViews.db.server";
|
||||
import { RowDisplayDefaultProperty } from "~/utils/helpers/PropertyHelper";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import RowUrlHelper from "~/utils/helpers/RowUrlHelper";
|
||||
import { translateEntityTitle } from "~/utils/i18n/translateLabel";
|
||||
|
||||
export interface RefRowForm {
|
||||
save: () => void;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
entity: EntityWithDetails;
|
||||
allEntities: EntityWithDetails[];
|
||||
routes?: EntitiesApi.Routes;
|
||||
item?: RowWithDetails | null;
|
||||
editing?: boolean;
|
||||
adding?: boolean;
|
||||
onSubmit?: (formData: FormData) => void;
|
||||
canUpdate?: boolean;
|
||||
canDelete?: boolean;
|
||||
canSubmit?: boolean;
|
||||
children?: ReactNode;
|
||||
parentEntity?: EntityWithDetails;
|
||||
onCreatedRedirect?: string;
|
||||
onDelete?: () => void;
|
||||
relationshipRows?: RowsApi.GetRelationshipRowsData;
|
||||
hiddenProperties?: string[];
|
||||
hiddenFields?: {
|
||||
[key: string]: string | null | undefined;
|
||||
};
|
||||
state?: { loading?: boolean; submitting?: boolean };
|
||||
createdRow?: RowWithDetails;
|
||||
onCancel?: () => void;
|
||||
onChange?: (values: RowValueDto[]) => void;
|
||||
customSearchParams?: URLSearchParams;
|
||||
template?: { title: string; config: string } | null;
|
||||
}
|
||||
|
||||
const RowForm = (
|
||||
{
|
||||
entity,
|
||||
routes,
|
||||
item,
|
||||
editing = false,
|
||||
adding,
|
||||
onSubmit,
|
||||
canUpdate,
|
||||
canDelete,
|
||||
canSubmit = true,
|
||||
children,
|
||||
parentEntity,
|
||||
onCreatedRedirect,
|
||||
allEntities,
|
||||
onDelete,
|
||||
relationshipRows,
|
||||
hiddenProperties,
|
||||
hiddenFields,
|
||||
state,
|
||||
createdRow,
|
||||
onCancel,
|
||||
onChange,
|
||||
customSearchParams,
|
||||
template,
|
||||
}: Props,
|
||||
ref: Ref<RefRowForm>
|
||||
) => {
|
||||
const { t, i18n } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const params = useParams();
|
||||
// const actionData = useActionData<{ newRow?: RowWithDetails }>();
|
||||
|
||||
const formGroup = useRef<RefFormGroup>(null);
|
||||
|
||||
const [searchParams] = useSearchParams();
|
||||
const [searchingRelationshipRows, setSearchingRelationshipRows] = useState<EntityRelationshipWithDetails>();
|
||||
const [selectedRelatedEntity, setSelectedRelatedEntity] = useState<{
|
||||
entity: { slug: string; onEdit: string | null };
|
||||
view: EntityViewWithDetails | null;
|
||||
multiple: boolean;
|
||||
}>();
|
||||
const [relatedRows, setRelatedRows] = useState<{ relationship: EntityRelationshipWithDetails; rows: RowWithValues[] }[]>([]);
|
||||
|
||||
const [headers, setHeaders] = useState<RowValueDto[]>([]);
|
||||
|
||||
const [childrenEntities, setChildrenEntities] = useState<{ visible: EntityRelationshipWithDetails[]; hidden: EntityRelationshipWithDetails[] }>({
|
||||
visible: [],
|
||||
hidden: [],
|
||||
});
|
||||
const [parentEntities, setParentEntities] = useState<{ visible: EntityRelationshipWithDetails[]; hidden: EntityRelationshipWithDetails[] }>({
|
||||
visible: [],
|
||||
hidden: [],
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
loadInitialFields();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [params.entity, params.group, customSearchParams, template]);
|
||||
|
||||
useEffect(() => {
|
||||
if (onChange) {
|
||||
onChange(headers);
|
||||
}
|
||||
}, [headers, onChange]);
|
||||
|
||||
// useEffect(() => {
|
||||
// if (headers.length > 0) {
|
||||
// rowValueInput.current?.focus();
|
||||
// }
|
||||
// }, [headers])
|
||||
|
||||
// useEffect(() => {
|
||||
// if (actionData?.newRow && onCreated) {
|
||||
// onCreated(actionData.newRow);
|
||||
// }
|
||||
// // eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
// }, [actionData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (searchingRelationshipRows?.parentId === entity.id) {
|
||||
setSelectedRelatedEntity({
|
||||
entity: searchingRelationshipRows.child,
|
||||
view: searchingRelationshipRows.childEntityView,
|
||||
multiple: true,
|
||||
});
|
||||
} else if (searchingRelationshipRows?.childId === entity.id) {
|
||||
setSelectedRelatedEntity({
|
||||
entity: searchingRelationshipRows.parent,
|
||||
view: searchingRelationshipRows.parentEntityView,
|
||||
multiple: false,
|
||||
});
|
||||
}
|
||||
}, [entity.id, searchingRelationshipRows]);
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
save,
|
||||
}));
|
||||
function save() {
|
||||
formGroup.current?.submitForm();
|
||||
}
|
||||
|
||||
function loadInitialFields() {
|
||||
const initial: RowValueDto[] = [];
|
||||
if (template && !customSearchParams) {
|
||||
const config = JSON.parse(template.config);
|
||||
const defaultValues: { [key: string]: any } = {};
|
||||
Object.keys(config).forEach((key) => {
|
||||
defaultValues[key] = config[key];
|
||||
});
|
||||
customSearchParams = new URLSearchParams(defaultValues);
|
||||
}
|
||||
entity.properties
|
||||
?.filter((f) => isPropertyVisible(f))
|
||||
.forEach((property) => {
|
||||
const existing = item?.values?.find((f) => f?.propertyId === property.id);
|
||||
|
||||
let urlSearchParams = customSearchParams ?? searchParams;
|
||||
const defaultValueString =
|
||||
RowUrlHelper.getString({ urlSearchParams, property }) ??
|
||||
PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.DefaultValue);
|
||||
const defaultValueNumber =
|
||||
RowUrlHelper.getNumber({ urlSearchParams, property }) ??
|
||||
PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.DefaultValue);
|
||||
const defaultValueBoolean =
|
||||
RowUrlHelper.getBoolean({ urlSearchParams, property }) ??
|
||||
PropertyAttributeHelper.getPropertyAttributeValue_Boolean(property, PropertyAttributeName.DefaultValue);
|
||||
|
||||
let defaultDate = RowUrlHelper.getDate({ urlSearchParams, property }) ?? undefined;
|
||||
const defaultRange = RowUrlHelper.getRange({ urlSearchParams, property }) ?? undefined;
|
||||
|
||||
const defaultMultiple = RowUrlHelper.getMultiple({ urlSearchParams, property }) ?? undefined;
|
||||
|
||||
initial.push({
|
||||
propertyId: property.id,
|
||||
property: property,
|
||||
textValue: existing?.textValue ?? defaultValueString ?? undefined,
|
||||
numberValue: existing?.numberValue ? Number(existing?.numberValue) : defaultValueNumber,
|
||||
dateValue: existing?.dateValue ?? defaultDate,
|
||||
booleanValue: existing ? Boolean(existing?.booleanValue) : defaultValueBoolean,
|
||||
selectedOption: existing?.textValue ?? defaultValueString ?? undefined,
|
||||
media: existing?.media ?? [],
|
||||
multiple: existing?.multiple.sort((a: RowValueMultipleDto, b: RowValueMultipleDto) => a.order - b.order) ?? defaultMultiple ?? [],
|
||||
range: existing?.range ?? defaultRange,
|
||||
});
|
||||
});
|
||||
|
||||
const relatedRows: { relationship: EntityRelationshipWithDetails; rows: RowWithValues[] }[] = [];
|
||||
if (item) {
|
||||
entity.parentEntities.forEach((relationship) => {
|
||||
if (item.parentRows?.length > 0) {
|
||||
relatedRows.push({
|
||||
relationship,
|
||||
rows: item.parentRows.filter((f) => f.relationshipId === relationship.id).map((i) => i.parent),
|
||||
});
|
||||
}
|
||||
});
|
||||
entity.childEntities.forEach((relationship) => {
|
||||
if (item.childRows?.length > 0) {
|
||||
relatedRows.push({
|
||||
relationship,
|
||||
rows: item.childRows.filter((f) => f.relationshipId === relationship.id).map((i) => i.child),
|
||||
});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
entity.parentEntities.forEach((relationship) => {
|
||||
const rowId = customSearchParams?.get(relationship.parent.name) ?? searchParams.get(relationship.parent.name);
|
||||
if (rowId) {
|
||||
const foundRow = relationshipRows
|
||||
?.filter((f) => f.relationship.id === relationship.id)
|
||||
.map((m) => m.rows)
|
||||
.flat()
|
||||
.find((f) => f.id === rowId);
|
||||
relatedRows.push({
|
||||
relationship,
|
||||
rows: foundRow ? [foundRow] : [],
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const allChildren = entity.childEntities.filter((f) => childEntityVisible(f) && allEntities.find((x) => x.id === f.childId));
|
||||
setChildrenEntities(getVisibleRelatedEntities(allChildren, relatedRows));
|
||||
const allParents = entity.parentEntities.filter((f) => f.parentId !== parentEntity?.id && allEntities.find((x) => x.id === f.parentId));
|
||||
setParentEntities(getVisibleRelatedEntities(allParents, relatedRows));
|
||||
|
||||
setHeaders(initial);
|
||||
setRelatedRows(relatedRows);
|
||||
}
|
||||
|
||||
function onFindEntityRows(relationship: EntityRelationshipWithDetails) {
|
||||
if (!routes) {
|
||||
return;
|
||||
}
|
||||
setSearchingRelationshipRows(relationship);
|
||||
}
|
||||
|
||||
function addRelationshipRow(relationship: EntityRelationshipWithDetails, rows: RowWithDetails[]) {
|
||||
const newRelatedRows = [...relatedRows];
|
||||
const existing = newRelatedRows.find((f) => f.relationship.id === relationship.id);
|
||||
if (existing) {
|
||||
if (relationship.parentId === entity.id) {
|
||||
const nonExistingRows = rows.filter((f) => !existing.rows.find((ff) => ff.id === f.id));
|
||||
existing.rows = [...existing.rows, ...nonExistingRows];
|
||||
} else {
|
||||
existing.rows = rows;
|
||||
}
|
||||
} else {
|
||||
newRelatedRows.push({ relationship, rows });
|
||||
}
|
||||
setRelatedRows(newRelatedRows);
|
||||
}
|
||||
|
||||
function setRelationshipRows(relationship: EntityRelationshipWithDetails, rows: RowWithDetails[]) {
|
||||
const newRelatedRows = [...relatedRows];
|
||||
const existing = newRelatedRows.find((f) => f.relationship.id === relationship.id);
|
||||
if (existing) {
|
||||
existing.rows = rows;
|
||||
} else {
|
||||
newRelatedRows.push({ relationship, rows });
|
||||
}
|
||||
setRelatedRows(newRelatedRows);
|
||||
}
|
||||
|
||||
function onRemoveRelatedRow(relationship: EntityRelationshipWithDetails, row: RowWithValues) {
|
||||
const newRelatedRows = [...relatedRows];
|
||||
const existing = newRelatedRows.find((f) => f.relationship.id === relationship.id);
|
||||
if (existing) {
|
||||
existing.rows = existing.rows.filter((f) => f.id !== row.id);
|
||||
}
|
||||
setRelatedRows(newRelatedRows);
|
||||
}
|
||||
|
||||
function submitForm(formData: FormData) {
|
||||
if (onSubmit) {
|
||||
onSubmit(formData);
|
||||
} else {
|
||||
submit(formData, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function isPropertyVisible(f: PropertyWithDetails) {
|
||||
if (f.isHidden || (!item && !f.showInCreate) || (!item && f.isReadOnly) || (item && editing && f.isReadOnly)) {
|
||||
return false;
|
||||
} else if (hiddenProperties?.includes(f.name)) {
|
||||
return false;
|
||||
}
|
||||
if (item && editing && !f.canUpdate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function childEntityVisible(f: EntityRelationshipWithDetails) {
|
||||
if (f.readOnly) {
|
||||
if (!item) {
|
||||
return false;
|
||||
}
|
||||
if (item && editing) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function canSubmitForm() {
|
||||
if (!canSubmit) {
|
||||
return false;
|
||||
}
|
||||
const required = headers.filter((f) => f.property.isRequired);
|
||||
let hasError = false;
|
||||
required.forEach((f) => {
|
||||
if (f.property.type === PropertyType.MEDIA) {
|
||||
if (f.media?.length === 0) {
|
||||
hasError = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
return !hasError;
|
||||
}
|
||||
|
||||
function isAddingOrEditing() {
|
||||
if (adding) {
|
||||
return true;
|
||||
}
|
||||
if (editing && item && canUpdate && navigation.state === "idle") {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function onSaveIfAllSet() {
|
||||
return;
|
||||
// if (item) {
|
||||
// return;
|
||||
// }
|
||||
// const missingValues = headers
|
||||
// .filter((f) => isPropertyVisible(f.property))
|
||||
// .map((header) => {
|
||||
// if ([PropertyType.TEXT, PropertyType.SELECT].includes(header.property.type) && !header.textValue) {
|
||||
// return header;
|
||||
// } else if ([PropertyType.NUMBER].includes(header.property.type) && !header.numberValue) {
|
||||
// return header;
|
||||
// } else if ([PropertyType.DATE].includes(header.property.type) && !header.dateValue) {
|
||||
// return header;
|
||||
// }
|
||||
// // else if ([PropertyType.MEDIA].includes(header.property.type) && (!header.media || header.media.length === 0)) {
|
||||
// // return header;
|
||||
// // }
|
||||
// else if ([PropertyType.MULTI_SELECT].includes(header.property.type) && (!header.multiple || header.multiple.length === 0)) {
|
||||
// return header;
|
||||
// }
|
||||
// return null;
|
||||
// });
|
||||
// const rowValues = missingValues.filter((f) => f !== null);
|
||||
|
||||
// if (rowValues.length === 0) {
|
||||
// formGroup.current?.submitForm();
|
||||
// }
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<FormGroup
|
||||
ref={formGroup}
|
||||
id={item?.id}
|
||||
editing={editing}
|
||||
canDelete={canDelete}
|
||||
onSubmit={submitForm}
|
||||
onDelete={onDelete}
|
||||
canUpdate={canUpdate}
|
||||
canSubmit={canSubmit}
|
||||
onCancel={onCancel}
|
||||
submitDisabled={!canSubmitForm()}
|
||||
onCreatedRedirect={onCreatedRedirect}
|
||||
deleteRedirect={EntityHelper.getRoutes({ routes, entity })?.list}
|
||||
state={state}
|
||||
message={
|
||||
createdRow
|
||||
? { success: t("shared.created") + ": " + RowHelper.getTextDescription({ entity, item: createdRow, t, defaultsToFolio: true }) }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{hiddenFields &&
|
||||
Object.keys(hiddenFields).map((f) => {
|
||||
return <Fragment key={f}>{hiddenFields[f] && <input type="hidden" name={f} value={hiddenFields[f] ?? ""} hidden readOnly />}</Fragment>;
|
||||
})}
|
||||
{!onSubmit && (
|
||||
<>
|
||||
{!item ? (
|
||||
<input type="hidden" name="redirect" value={EntityHelper.getRoutes({ routes, entity })?.list} hidden readOnly />
|
||||
) : (
|
||||
<input type="hidden" name="redirect" value={EntityHelper.getRoutes({ routes, entity, item })?.overview} hidden readOnly />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{onCreatedRedirect && <input type="hidden" name="onCreatedRedirect" value={onCreatedRedirect} hidden readOnly />}
|
||||
<RowGroups
|
||||
item={item}
|
||||
entity={entity}
|
||||
rowValues={headers}
|
||||
parentEntity={parentEntity}
|
||||
allEntities={allEntities}
|
||||
relatedRows={relatedRows}
|
||||
editing={editing}
|
||||
canUpdate={canUpdate}
|
||||
routes={routes}
|
||||
relationshipRows={relationshipRows}
|
||||
setHeaders={setHeaders}
|
||||
addRelationshipRow={addRelationshipRow}
|
||||
setRelationshipRows={setRelationshipRows}
|
||||
onFindEntityRows={onFindEntityRows}
|
||||
onRemoveRelatedRow={onRemoveRelatedRow}
|
||||
isPropertyVisible={isPropertyVisible}
|
||||
children={children}
|
||||
canSubmit={canSubmit}
|
||||
isAddingOrEditing={isAddingOrEditing()}
|
||||
parentEntities={{
|
||||
visible: parentEntities.visible,
|
||||
hidden: parentEntities.hidden,
|
||||
onAddParentEntity: (rel) => {
|
||||
setParentEntities((prev) => {
|
||||
return {
|
||||
visible: [...prev.visible, rel],
|
||||
hidden: prev.hidden.filter((f) => f.id !== rel.id),
|
||||
};
|
||||
});
|
||||
},
|
||||
}}
|
||||
onSaveIfAllSet={onSaveIfAllSet}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-12">
|
||||
{childrenEntities.visible.map((relationship) => (
|
||||
<div key={relationship.id} className="col-span-12">
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-foreground text-sm leading-3 font-medium">
|
||||
<div className="flex items-center space-x-1">
|
||||
<div>
|
||||
<span className="font-light italic"></span> {t(RelationshipHelper.getTitle({ fromEntityId: entity.id, relationship }))}
|
||||
{/* {relationship.required && <span className="ml-1 text-red-500">*</span>} */}
|
||||
</div>
|
||||
</div>
|
||||
</h3>
|
||||
<RelationshipSelector
|
||||
fromEntity={entity}
|
||||
type="child"
|
||||
relationship={relationship}
|
||||
relatedRows={relatedRows}
|
||||
onFindEntityRows={onFindEntityRows}
|
||||
allEntities={allEntities}
|
||||
onRemoveRelatedRow={onRemoveRelatedRow}
|
||||
readOnly={item?.id !== undefined && (!editing || !canUpdate)}
|
||||
routes={routes}
|
||||
relationshipRows={relationshipRows}
|
||||
addRelationshipRow={addRelationshipRow}
|
||||
setRelationshipRows={setRelationshipRows}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{isAddingOrEditing() && (
|
||||
<AddHiddenRelationshipEntities
|
||||
items={childrenEntities.hidden}
|
||||
onClick={(rel) => {
|
||||
setChildrenEntities((prev) => {
|
||||
return {
|
||||
visible: [...prev.visible, rel],
|
||||
hidden: prev.hidden.filter((f) => f.id !== rel.id),
|
||||
};
|
||||
});
|
||||
}}
|
||||
type="child"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{relatedRows.map(({ relationship, rows }) => (
|
||||
<Fragment key={relationship.id}>
|
||||
{rows.map((row) => (
|
||||
// <>
|
||||
<input
|
||||
key={row.id}
|
||||
type="hidden"
|
||||
readOnly
|
||||
hidden
|
||||
name={`${relationship.childId === entity.id ? `parents[${relationship.parent.name}]` : `children[${relationship.child.name}]`}`}
|
||||
value={row.id}
|
||||
/>
|
||||
// </>
|
||||
))}
|
||||
</Fragment>
|
||||
))}
|
||||
</FormGroup>
|
||||
{/* // <OpenModal className="sm:max-w-4xl" onClose={() => setSearchingRelationshipRows(undefined)}> */}
|
||||
<SlideOverWideEmpty
|
||||
withTitle={false}
|
||||
withClose={false}
|
||||
title={t("shared.select")}
|
||||
open={searchingRelationshipRows !== undefined}
|
||||
onClose={() => setSearchingRelationshipRows(undefined)}
|
||||
>
|
||||
{selectedRelatedEntity && searchingRelationshipRows && (
|
||||
<RowListFetcher
|
||||
currentView={selectedRelatedEntity.view}
|
||||
listUrl={EntityHelper.getRoutes({ routes, entity: selectedRelatedEntity.entity })?.list + "?view=null"}
|
||||
newUrl={EntityHelper.getRoutes({ routes, entity: selectedRelatedEntity.entity })?.new ?? ""}
|
||||
parentEntity={entity}
|
||||
onSelected={(rows) => {
|
||||
addRelationshipRow(searchingRelationshipRows, rows);
|
||||
setSearchingRelationshipRows(undefined);
|
||||
}}
|
||||
multipleSelection={selectedRelatedEntity.multiple}
|
||||
allEntities={allEntities}
|
||||
/>
|
||||
)}
|
||||
</SlideOverWideEmpty>
|
||||
{/* // </OpenModal> */}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
function RelationshipSelector({
|
||||
fromEntity,
|
||||
routes,
|
||||
type,
|
||||
relationship,
|
||||
relatedRows,
|
||||
onFindEntityRows,
|
||||
className,
|
||||
allEntities,
|
||||
onRemoveRelatedRow,
|
||||
readOnly,
|
||||
relationshipRows,
|
||||
addRelationshipRow,
|
||||
setRelationshipRows,
|
||||
}: {
|
||||
fromEntity: EntityWithDetails;
|
||||
type: "child" | "parent";
|
||||
relationship: EntityRelationshipWithDetails;
|
||||
relatedRows: { relationship: EntityRelationshipWithDetails; rows: RowWithValues[] }[];
|
||||
onFindEntityRows: (relationship: EntityRelationshipWithDetails) => void;
|
||||
className?: string;
|
||||
allEntities: EntityWithDetails[];
|
||||
onRemoveRelatedRow: (relationship: EntityRelationshipWithDetails, row: RowWithValues) => void;
|
||||
readOnly: boolean;
|
||||
routes?: EntitiesApi.Routes;
|
||||
relationshipRows?: RowsApi.GetRelationshipRowsData;
|
||||
addRelationshipRow: (relationship: EntityRelationshipWithDetails, rows: RowWithDetails[]) => void;
|
||||
setRelationshipRows: (relationship: EntityRelationshipWithDetails, rows: RowWithDetails[]) => void;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [entity] = useState(
|
||||
type === "parent"
|
||||
? {
|
||||
entity: getChildEntity(relationship)!,
|
||||
view: relationship.parentEntityView,
|
||||
}
|
||||
: {
|
||||
entity: getParentEntity(relationship)!,
|
||||
view: relationship.childEntityView,
|
||||
}
|
||||
);
|
||||
|
||||
function getRows(relationship: EntityRelationshipWithDetails) {
|
||||
const existing = relatedRows.find((f) => f.relationship.id === relationship.id);
|
||||
return existing?.rows.sort((a, b) => (a.order ?? 0) - (b.order ?? 0)) ?? [];
|
||||
}
|
||||
function getParentEntity(relationship: EntityRelationshipWithDetails) {
|
||||
return allEntities.find((f) => f.id === relationship.childId);
|
||||
}
|
||||
function getChildEntity(relationship: EntityRelationshipWithDetails) {
|
||||
return allEntities.find((f) => f.id === relationship.parentId);
|
||||
}
|
||||
return (
|
||||
<div className={className}>
|
||||
{/* <div>selectedRow: {getSelectedRow()}</div>
|
||||
<div>
|
||||
options:{" "}
|
||||
{getOptions()
|
||||
.map((f) => f.value)
|
||||
.join(",")}
|
||||
</div>
|
||||
<div>
|
||||
{relatedRows.filter((f) => f.relationship.id === relationship.id).length > 0 &&
|
||||
relatedRows
|
||||
.filter((f) => f.relationship.id === relationship.id)[0]
|
||||
.rows.map((f) => f.id)
|
||||
.join(",")}
|
||||
</div> */}
|
||||
{/* {RelationshipHelper.getInputType({ fromEntityId: fromEntity.id, relationship }) === "single-select" ? (
|
||||
<InputSelector
|
||||
className="mt-1"
|
||||
name={relationship.parent.name}
|
||||
disabled={readOnly}
|
||||
value={getSelectedRow()}
|
||||
options={getOptions()}
|
||||
setValue={(value) => {
|
||||
const row = relationshipRows?.find((f) => f.relationship.id === relationship.id)?.rows.find((f) => f.id === value);
|
||||
if (row) {
|
||||
setRelationshipRows(relationship, [row]);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : RelationshipHelper.getInputType({ fromEntityId: fromEntity.id, relationship }) === "multi-select" ? (
|
||||
<> */}
|
||||
{getRows(relationship).length === 0 ? (
|
||||
<button
|
||||
onClick={() => onFindEntityRows(relationship)}
|
||||
type="button"
|
||||
disabled={readOnly}
|
||||
className={clsx(
|
||||
"border-border relative block w-full rounded-lg border-2 border-dashed p-4 text-center",
|
||||
readOnly ? "bg-secondary/90 cursor-not-allowed" : "bg-background hover:border-border focus:ring-2 focus:ring-gray-500 focus:outline-hidden"
|
||||
)}
|
||||
>
|
||||
<span className="text-muted-foreground flex items-center space-x-1 text-xs font-normal">
|
||||
{readOnly ? (
|
||||
<div>{t("shared.notSet")}</div>
|
||||
) : (
|
||||
<>
|
||||
{type === "parent" && (
|
||||
<>
|
||||
<div>{t("shared.select")}</div>
|
||||
<div className="lowercase">{translateEntityTitle(t, i18n, relationship.parent)}</div>
|
||||
</>
|
||||
)}
|
||||
{type === "child" && (
|
||||
<>
|
||||
<div>{t("shared.add")}</div>
|
||||
<div className="lowercase">{translateEntityTitle(t, i18n, relationship.child)}</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<div className="relative space-y-2 overflow-visible">
|
||||
<RowsList
|
||||
entity={entity.entity}
|
||||
items={getRows(relationship) as RowWithDetails[]}
|
||||
currentView={entity.view}
|
||||
view={(entity.view?.layout ?? "card") as "table" | "board" | "grid" | "card"}
|
||||
readOnly={readOnly}
|
||||
onRemove={readOnly ? undefined : (row) => onRemoveRelatedRow(relationship, row)}
|
||||
ignoreColumns={!readOnly ? [RowDisplayDefaultProperty.FOLIO, "parent." + relationship.parent.name, "child." + relationship.child.name] : []}
|
||||
routes={routes}
|
||||
/>
|
||||
{/* {getRows(relationship).map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className={clsx(
|
||||
"group relative w-full overflow-visible truncate rounded-md border border-border px-4 py-3 text-left text-sm",
|
||||
!readOnly ? "bg-background hover:border-border" : "bg-secondary/90"
|
||||
)}
|
||||
>
|
||||
<button
|
||||
onClick={() => onRemoveRelatedRow(relationship, item)}
|
||||
type="button"
|
||||
disabled={readOnly}
|
||||
className={clsx(
|
||||
"absolute right-0 top-0 mr-2 mt-2 hidden origin-top-right justify-center rounded-full bg-background text-muted-foreground",
|
||||
readOnly ? "cursor-not-allowed" : "hover:text-red-500 group-hover:flex"
|
||||
)}
|
||||
>
|
||||
<svg className="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M15 12H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
</button>
|
||||
<div className="grid grid-cols-2 gap-1">
|
||||
<div>{RowHelper.getTextDescription({ entity, item, t, defaultsToFolio: true })}</div>
|
||||
</div>
|
||||
</div>
|
||||
))} */}
|
||||
<button
|
||||
onClick={() => onFindEntityRows(relationship)}
|
||||
type="button"
|
||||
className={clsx(
|
||||
"hover:bg-secondary border-border text-muted-foreground hover:border-border relative flex space-x-1 rounded-md border border-dashed px-2 py-1 text-center text-xs focus:ring-1 focus:ring-gray-500 focus:outline-hidden",
|
||||
readOnly && "hidden"
|
||||
)}
|
||||
>
|
||||
{type === "parent" && (
|
||||
<>
|
||||
<div>{t("shared.select")}</div>
|
||||
<div className="lowercase">{translateEntityTitle(t, i18n, relationship.parent)}</div>
|
||||
</>
|
||||
)}
|
||||
{type === "child" && (
|
||||
<>
|
||||
<div>{t("shared.add")}</div>
|
||||
<div className="lowercase">{translateEntityTitle(t, i18n, relationship.child)}</div>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{/* </>
|
||||
) : null} */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RowGroups({
|
||||
item,
|
||||
entity,
|
||||
rowValues,
|
||||
parentEntity,
|
||||
allEntities,
|
||||
relatedRows,
|
||||
editing,
|
||||
canUpdate,
|
||||
routes,
|
||||
relationshipRows,
|
||||
setHeaders,
|
||||
addRelationshipRow,
|
||||
setRelationshipRows,
|
||||
onFindEntityRows,
|
||||
onRemoveRelatedRow,
|
||||
isPropertyVisible,
|
||||
children,
|
||||
canSubmit,
|
||||
isAddingOrEditing,
|
||||
parentEntities,
|
||||
onSaveIfAllSet,
|
||||
}: {
|
||||
item?: RowWithDetails | null;
|
||||
entity: EntityWithDetails;
|
||||
rowValues: RowValueDto[];
|
||||
parentEntity?: EntityWithDetails;
|
||||
allEntities: EntityWithDetails[];
|
||||
relatedRows: { relationship: EntityRelationshipWithDetails; rows: RowWithValues[] }[];
|
||||
editing?: boolean;
|
||||
canUpdate?: boolean;
|
||||
routes?: EntitiesApi.Routes;
|
||||
relationshipRows?: RowsApi.GetRelationshipRowsData;
|
||||
setHeaders: Dispatch<SetStateAction<RowValueDto[]>>;
|
||||
addRelationshipRow: (relationship: EntityRelationshipWithDetails, rows: RowWithDetails[]) => void;
|
||||
setRelationshipRows: (relationship: EntityRelationshipWithDetails, rows: RowWithDetails[]) => void;
|
||||
onFindEntityRows: (relationship: EntityRelationshipWithDetails) => void;
|
||||
onRemoveRelatedRow: (relationship: EntityRelationshipWithDetails, row: RowWithValues) => void;
|
||||
isPropertyVisible: (property: PropertyWithDetails) => boolean;
|
||||
children?: ReactNode;
|
||||
canSubmit?: boolean;
|
||||
isAddingOrEditing: boolean;
|
||||
parentEntities: {
|
||||
visible: EntityRelationshipWithDetails[];
|
||||
hidden: EntityRelationshipWithDetails[];
|
||||
onAddParentEntity: (item: EntityRelationshipWithDetails) => void;
|
||||
};
|
||||
onSaveIfAllSet: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const rowValueInput = useRef<RefRowValueInput>(null);
|
||||
|
||||
const groups = useMemo(() => {
|
||||
const groups: { group?: string; headers: RowValueDto[] }[] = [];
|
||||
rowValues.forEach((header) => {
|
||||
const groupName = PropertyAttributeHelper.getPropertyAttributeValue_String(header.property, PropertyAttributeName.Group);
|
||||
let found = groups.find((f) => f.group === groupName);
|
||||
if (!found) {
|
||||
found = groups.find((f) => !f.group && !groupName);
|
||||
}
|
||||
if (found) {
|
||||
found.headers.push(header);
|
||||
} else {
|
||||
groups.push({
|
||||
group: groupName,
|
||||
headers: [header],
|
||||
});
|
||||
}
|
||||
});
|
||||
if (groups.length === 0) {
|
||||
groups.push({ headers: rowValues });
|
||||
}
|
||||
return groups;
|
||||
}, [rowValues]);
|
||||
|
||||
function getPropertyColumnSpan(property: PropertyWithDetails) {
|
||||
const columns = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Columns);
|
||||
if (columns === undefined || isNaN(columns) || (columns < 1 && columns > 12)) {
|
||||
return "col-span-12";
|
||||
}
|
||||
return `col-span-${columns}`;
|
||||
}
|
||||
function onChange(rowValue: RowValueDto) {
|
||||
setHeaders((prev) => {
|
||||
return prev.map((f) => {
|
||||
if (f.propertyId === rowValue.propertyId) {
|
||||
return rowValue;
|
||||
}
|
||||
return f;
|
||||
});
|
||||
});
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{groups.map(({ group, headers }, idx) => {
|
||||
return (
|
||||
<InputGroup key={idx} title={group ? t(group) : t("shared.details")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
{headers.map((detailValue, idxDetailValue) => {
|
||||
return (
|
||||
<div key={detailValue.propertyId} className={clsx("w-full", getPropertyColumnSpan(detailValue.property))}>
|
||||
<RowValueInput
|
||||
ref={rowValueInput}
|
||||
entity={entity}
|
||||
textValue={detailValue.textValue}
|
||||
numberValue={detailValue.numberValue}
|
||||
dateValue={detailValue.dateValue}
|
||||
booleanValue={detailValue.booleanValue}
|
||||
multiple={detailValue.multiple}
|
||||
range={detailValue.range}
|
||||
initialOption={detailValue.selectedOption}
|
||||
selected={detailValue.property}
|
||||
initialMedia={detailValue.media}
|
||||
onChange={(e) => {
|
||||
onChange({
|
||||
...detailValue,
|
||||
...RowHelper.updateFieldValueTypeArray(detailValue, e),
|
||||
});
|
||||
}}
|
||||
onChangeOption={(e) => {
|
||||
onChange({
|
||||
...detailValue,
|
||||
selectedOption: e,
|
||||
textValue: e,
|
||||
});
|
||||
}}
|
||||
onChangeMedia={(media) => {
|
||||
onChange({
|
||||
...detailValue,
|
||||
media: media as any,
|
||||
});
|
||||
if (media.filter((f) => f.type).length > 0) {
|
||||
onSaveIfAllSet();
|
||||
}
|
||||
}}
|
||||
onChangeMultiple={(e) => {
|
||||
onChange({
|
||||
...detailValue,
|
||||
multiple: e as any[],
|
||||
});
|
||||
}}
|
||||
onChangeRange={(e) => {
|
||||
onChange({
|
||||
...detailValue,
|
||||
range: e as any,
|
||||
});
|
||||
}}
|
||||
readOnly={
|
||||
(editing && !detailValue.property.canUpdate) || (item?.id !== undefined && (!editing || !canUpdate)) || detailValue.property?.isReadOnly
|
||||
}
|
||||
autoFocus={idx === 0 && idxDetailValue === 0 && canSubmit}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{/* Show parent entities in Default Properties Group */}
|
||||
{!group && (
|
||||
<>
|
||||
{parentEntities.visible.map((relationship) => (
|
||||
<div key={relationship.id} className="col-span-12">
|
||||
<label htmlFor={relationship.id} className="text-muted-foreground flex items-center justify-between space-x-2 text-xs font-medium">
|
||||
<span className="truncate">
|
||||
{t(RelationshipHelper.getTitle({ fromEntityId: entity.id, relationship }))}
|
||||
{relationship.required && <span className="ml-1 text-red-500">*</span>}
|
||||
</span>
|
||||
</label>
|
||||
<RelationshipSelector
|
||||
fromEntity={entity}
|
||||
className="mt-1"
|
||||
type="parent"
|
||||
relationship={relationship}
|
||||
relatedRows={relatedRows}
|
||||
onFindEntityRows={onFindEntityRows}
|
||||
allEntities={allEntities}
|
||||
onRemoveRelatedRow={onRemoveRelatedRow}
|
||||
readOnly={item?.id !== undefined && (!editing || !canUpdate)}
|
||||
routes={routes}
|
||||
relationshipRows={relationshipRows}
|
||||
addRelationshipRow={addRelationshipRow}
|
||||
setRelationshipRows={setRelationshipRows}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{isAddingOrEditing && (
|
||||
<AddHiddenRelationshipEntities items={parentEntities.hidden} onClick={parentEntities.onAddParentEntity} type="parent" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{/* Show custom properties in Default Properties Group */}
|
||||
{!group && <>{children}</>}
|
||||
</div>
|
||||
</InputGroup>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AddHiddenRelationshipEntities({
|
||||
items,
|
||||
onClick,
|
||||
type,
|
||||
}: {
|
||||
items: EntityRelationshipWithDetails[];
|
||||
onClick: (item: EntityRelationshipWithDetails) => void;
|
||||
type: "parent" | "child";
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
return (
|
||||
<Fragment>
|
||||
{items.length > 0 && (
|
||||
<div className="col-span-12 flex flex-wrap items-center">
|
||||
{items.map((relationship) => (
|
||||
<button
|
||||
key={relationship.id}
|
||||
type="button"
|
||||
onClick={() => onClick(relationship)}
|
||||
className="text-muted-foreground bg-secondary/90 m-0.5 w-auto rounded-md px-2 py-1 text-xs font-medium hover:bg-gray-200"
|
||||
>
|
||||
{t("shared.add")} {type === "parent" ? translateEntityTitle(t, i18n, relationship.parent) : translateEntityTitle(t, i18n, relationship.child)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
function getVisibleRelatedEntities(
|
||||
entityRelationships: EntityRelationshipWithDetails[],
|
||||
relatedRows: { relationship: EntityRelationshipWithDetails; rows: RowWithValues[] }[]
|
||||
) {
|
||||
const visible = entityRelationships.filter((f) => !f.hiddenIfEmpty);
|
||||
const hidden: EntityRelationshipWithDetails[] = [];
|
||||
|
||||
entityRelationships
|
||||
.filter((f) => f.hiddenIfEmpty)
|
||||
.forEach((relationship) => {
|
||||
const rows = relatedRows.filter((f) => f.relationship.id === relationship.id).flatMap((f) => f.rows);
|
||||
if (rows.length > 0) {
|
||||
visible.push(relationship);
|
||||
} else {
|
||||
hidden.push(relationship);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
visible,
|
||||
hidden,
|
||||
};
|
||||
}
|
||||
|
||||
export default forwardRef(RowForm);
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
import { useLocation, useSubmit, useNavigation } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ApiKeyBadge from "~/components/core/users/ApiKeyBadge";
|
||||
import UserAvatarBadge from "~/components/core/users/UserAvatarBadge";
|
||||
import UserBadge from "~/components/core/users/UserBadge";
|
||||
import ChatAltIcon from "~/components/ui/icons/ChatAltIcon";
|
||||
import ThumbsUpEmptyIcon from "~/components/ui/icons/ThumbsUpEmptyIcon";
|
||||
import ThumbsUpFilledIcon from "~/components/ui/icons/ThumbsUpFilledIcon";
|
||||
import TrashEmptyIcon from "~/components/ui/icons/TrashEmptyIcon";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { LogWithDetails } from "~/utils/db/logs.db.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { renderSanitizedMarkdown } from "~/utils/html-sanitizer";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
interface Props {
|
||||
item: LogWithDetails;
|
||||
}
|
||||
export default function RowLogComment({ item }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const submit = useSubmit();
|
||||
const { user } = useAppOrAdminData();
|
||||
const navigation = useNavigation();
|
||||
const location = useLocation();
|
||||
const isAdding = navigation.state === "submitting" && navigation.formData?.get("action") === "comment-reaction";
|
||||
const isDeleting = navigation.state === "submitting" && navigation.formData?.get("action") === "comment-delete";
|
||||
|
||||
function onReacted(reaction: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "comment-reaction");
|
||||
form.set("comment-id", item.comment?.id ?? "");
|
||||
form.set("reaction", reaction);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
|
||||
function onDeleted() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "comment-delete");
|
||||
form.set("comment-id", item.comment?.id ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
|
||||
function getReactions(reaction: string) {
|
||||
return item.comment?.reactions.filter((f) => f.reaction === reaction) ?? [];
|
||||
}
|
||||
function hasMyReaction(reaction: string) {
|
||||
return item.comment?.reactions.find((f) => f.createdByUserId === user?.id && f.reaction === reaction);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{item.comment && (
|
||||
<>
|
||||
<div className="relative px-1">
|
||||
<UserAvatarBadge className="h-9 w-9" avatar={item.user?.avatar} />
|
||||
|
||||
<span className="bg-secondary absolute -bottom-0.5 -right-1 rounded-tl px-0.5 py-px">
|
||||
<ChatAltIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
</span>
|
||||
</div>
|
||||
<div className="group min-w-0 flex-1 space-y-0.5">
|
||||
<div>
|
||||
<div className="text-sm">
|
||||
<div className="text-foreground font-medium">
|
||||
{item.user && <UserBadge item={item.user} withEmail={false} />}
|
||||
{item.apiKey && <ApiKeyBadge item={item.apiKey} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-muted-foreground text-sm font-normal">
|
||||
{item.comment.isDeleted ? (
|
||||
<p className="text-muted-foreground italic">{t("shared.commentDeleted")}</p>
|
||||
) : (
|
||||
<div className="prose border-border rounded-md border border-dashed p-2 text-sm">
|
||||
<div dangerouslySetInnerHTML={{ __html: renderSanitizedMarkdown(item.comment.value) }} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-muted-foreground flex items-center justify-between space-x-1 font-medium">
|
||||
<time dateTime={new Date(item.createdAt).toISOString()} title={formatters.dateTime(item.createdAt, { timeStyle: "medium" })}>
|
||||
{formatters.relativeDate(item.createdAt)}
|
||||
</time>
|
||||
<div className="group flex items-center space-x-2">
|
||||
{!item.comment.isDeleted && item.comment.createdByUserId === user?.id && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={isDeleting}
|
||||
onClick={() => onDeleted()}
|
||||
className="text-muted-foreground hover:text-muted-foreground invisible p-0.5 focus:outline-hidden group-hover:visible"
|
||||
>
|
||||
<div className="flex items-center space-x-1">
|
||||
<TrashEmptyIcon className="h-4 w-4" />
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={isAdding}
|
||||
onClick={() => onReacted("like")}
|
||||
className={clsx(
|
||||
"text-muted-foreground hover:text-muted-foreground p-0.5 focus:outline-hidden",
|
||||
getReactions("like").length === 0 && "invisible group-hover:visible"
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className="flex items-center space-x-1"
|
||||
title={
|
||||
getReactions("like")
|
||||
?.map((f) => `${f.createdByUser?.firstName} ${f.createdByUser?.lastName}`)
|
||||
.join(", ") ?? ""
|
||||
}
|
||||
>
|
||||
{(getReactions("like")?.length ?? 0) > 0 && <div className="">{getReactions("like")?.length ?? 0}</div>}
|
||||
{hasMyReaction("like") ? <ThumbsUpFilledIcon className="h-4 w-4" /> : <ThumbsUpEmptyIcon className="h-4 w-4" />}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import clsx from "clsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LogWithDetails } from "~/utils/db/logs.db.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { CalendarIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface Props {
|
||||
items: LogWithDetails[];
|
||||
}
|
||||
|
||||
export default function RowLogs({ items }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
const sortedItems = () => {
|
||||
return items.slice().sort((x, y) => {
|
||||
if (x.createdAt && y.createdAt) {
|
||||
return x.createdAt > y.createdAt ? -1 : 1;
|
||||
}
|
||||
return -1;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-foreground text-sm font-medium leading-3">
|
||||
<div className="flex items-center space-x-1">
|
||||
<div>
|
||||
<span className=" font-light italic"></span> {t("app.shared.activity.title")}
|
||||
</div>
|
||||
</div>
|
||||
</h3>
|
||||
<div className="bg-background border-border rounded-md border px-4 py-5 shadow-xs">
|
||||
<div className="flow-root">
|
||||
<ul className="-mb-8">
|
||||
{sortedItems().length === 0 && <div className=" text-muted-foreground mb-6 flex justify-center text-sm italic">{t("models.row.logs.noEvents")}</div>}
|
||||
{sortedItems().map((activity, idxActivity) => {
|
||||
return (
|
||||
<li key={idxActivity}>
|
||||
<div className="relative pb-8">
|
||||
{items.length > 0 && idxActivity + 1 < items.length && (
|
||||
<span className="absolute left-4 top-4 -ml-px h-full w-0.5 bg-gray-200" aria-hidden="true"></span>
|
||||
)}
|
||||
|
||||
<div className="relative flex space-x-3">
|
||||
<div>
|
||||
<span className={clsx("bg-secondary/90 flex h-8 w-8 items-center justify-center rounded-full ring-8 ring-white")}>
|
||||
<CalendarIcon className="text-muted-foreground h-4 w-4" />
|
||||
</span>
|
||||
</div>
|
||||
<div className="grow">
|
||||
<div className="flex min-w-0 flex-1 justify-between space-x-4">
|
||||
<div className="truncate">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
<div className="text-foreground truncate">
|
||||
<span title={activity.action}>{activity.action}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-muted-foreground truncate whitespace-nowrap text-right text-xs lowercase">
|
||||
{activity.createdAt && (
|
||||
<time dateTime={new Date(activity.createdAt).toISOString()} title={formatters.dateTime(activity.createdAt, { timeStyle: "medium" })}>
|
||||
{formatters.date(activity.createdAt, { month: "short", day: "numeric" })}, {formatters.date(activity.createdAt, { timeStyle: "medium" })}
|
||||
</time>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 justify-between space-x-4">
|
||||
{activity.user && <div className="text-xs font-light">{activity.user.email}</div>}
|
||||
{activity.apiKey && <div className="text-xs font-light">{activity.apiKey.alias}</div>}
|
||||
{!activity.user && !activity.apiKey && <div className="text-xs font-light">{t("shared.anonymousUser")}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import clsx from "clsx";
|
||||
import { useSubmit, useNavigation } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ChevronUpIcon, ChevronDownIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface Props {
|
||||
id: string;
|
||||
order: number;
|
||||
editable?: boolean;
|
||||
}
|
||||
export default function RowOrderButtons({ id, order, editable = true }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const loading = navigation.state === "submitting";
|
||||
function changeOrder(forward: boolean) {
|
||||
const form = new FormData();
|
||||
form.set("action", forward ? "move-down" : "move-up");
|
||||
form.set("id", id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
return (
|
||||
<div className="flex items-center space-x-1 truncate">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => changeOrder(false)}
|
||||
className={clsx(
|
||||
!editable || loading ? " bg-secondary/90 cursor-not-allowed text-gray-300" : "hover:text-foreground hover:bg-secondary/90",
|
||||
"text-muted-foreground bg-secondary h-4 w-4 px-0.5 py-0.5 focus:outline-hidden"
|
||||
)}
|
||||
disabled={!editable || loading}
|
||||
aria-label={t("shared.moveUp")}
|
||||
>
|
||||
<ChevronUpIcon className="h-3 w-3" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => changeOrder(true)}
|
||||
className={clsx(
|
||||
!editable || loading ? " bg-secondary/90 cursor-not-allowed text-gray-300" : "hover:text-foreground hover:bg-secondary/90",
|
||||
"text-muted-foreground bg-secondary h-4 w-4 px-0.5 py-0.5 focus:outline-hidden"
|
||||
)}
|
||||
disabled={!editable || loading}
|
||||
aria-label={t("shared.moveDown")}
|
||||
>
|
||||
<ChevronDownIcon className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
import { Fragment, ReactNode, useRef } from "react";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import TrashEmptyIcon from "~/components/ui/icons/TrashEmptyIcon";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import RowTitle from "./RowTitle";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { useNavigation, useSubmit } from "react-router";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import { getUserHasPermission, getEntityPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import ShareIcon from "~/components/ui/icons/ShareIcon";
|
||||
import PencilIcon from "~/components/ui/icons/PencilIcon";
|
||||
import clsx from "clsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export default function RowOverviewHeader({
|
||||
rowData,
|
||||
item,
|
||||
canUpdate,
|
||||
isEditing,
|
||||
routes,
|
||||
title,
|
||||
options,
|
||||
buttons,
|
||||
customActions,
|
||||
truncate = true,
|
||||
}: {
|
||||
rowData: RowsApi.GetRowData;
|
||||
item: RowWithDetails;
|
||||
canUpdate: boolean;
|
||||
isEditing: boolean;
|
||||
routes: EntitiesApi.Routes | undefined;
|
||||
title?: React.ReactNode;
|
||||
options?: {
|
||||
hideTitle?: boolean;
|
||||
hideMenu?: boolean;
|
||||
hideShare?: boolean;
|
||||
hideTags?: boolean;
|
||||
hideTasks?: boolean;
|
||||
hideActivity?: boolean;
|
||||
disableUpdate?: boolean;
|
||||
disableDelete?: boolean;
|
||||
};
|
||||
buttons?: ReactNode;
|
||||
customActions?: { entity: string; label: string; action: string }[];
|
||||
truncate?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
function getEditRoute() {
|
||||
if (isEditing) {
|
||||
return EntityHelper.getRoutes({ routes, entity: rowData.entity, item })?.overview;
|
||||
} else {
|
||||
return EntityHelper.getRoutes({ routes, entity: rowData.entity, item })?.edit;
|
||||
}
|
||||
}
|
||||
function canDelete() {
|
||||
return !options?.disableDelete && getUserHasPermission(appOrAdminData, getEntityPermission(rowData.entity, "delete")) && rowData.rowPermissions.canDelete;
|
||||
}
|
||||
|
||||
function onDelete() {
|
||||
confirmDelete.current?.show(t("shared.confirmDelete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
function onDeleteConfirm() {
|
||||
const form = new FormData();
|
||||
form.set("action", "delete");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border-border relative items-center justify-between space-y-2 border-b pb-4 sm:flex sm:space-x-4 sm:space-y-0">
|
||||
<div className={clsx(truncate && "truncate", "flex flex-col")}>
|
||||
<div className={clsx(truncate && "truncate", "flex items-center space-x-2 text-xl font-bold")}>
|
||||
{title ?? <RowTitle entity={rowData.entity} item={item} />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 items-center space-x-2 sm:justify-end">
|
||||
<div className="flex items-end space-x-2 space-y-0">
|
||||
{canUpdate || item.createdByUserId === appOrAdminData?.user?.id || appOrAdminData?.isSuperUser ? (
|
||||
<Fragment>
|
||||
{customActions
|
||||
?.filter((f) => f.entity === rowData.entity.name)
|
||||
.map((customAction) => {
|
||||
return (
|
||||
<ButtonSecondary
|
||||
key={customAction.action}
|
||||
isLoading={navigation.state === "submitting" && navigation.formData?.get("action") === customAction.action}
|
||||
onClick={() => {
|
||||
const form = new FormData();
|
||||
form.set("action", customAction.action);
|
||||
form.set("id", item.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}}
|
||||
>
|
||||
<span className="text-xs">{customAction.label}</span>
|
||||
</ButtonSecondary>
|
||||
);
|
||||
})}
|
||||
{buttons}
|
||||
{!options?.hideShare && (item.createdByUserId === appOrAdminData?.user?.id || appOrAdminData.isSuperAdmin) && (
|
||||
<ButtonSecondary to="share" ariaLabel={t("shared.share")}>
|
||||
<ShareIcon className="text-muted-foreground h-4 w-4" />
|
||||
</ButtonSecondary>
|
||||
)}
|
||||
{rowData.entity.onEdit !== "overviewAlwaysEditable" && (
|
||||
<ButtonSecondary disabled={!EntityHelper.getRoutes({ routes, entity: rowData.entity, item })?.edit} to={getEditRoute()} ariaLabel={t("shared.edit")}>
|
||||
<PencilIcon className="text-muted-foreground h-4 w-4" />
|
||||
</ButtonSecondary>
|
||||
)}
|
||||
{isEditing && (
|
||||
<ButtonSecondary onClick={onDelete} disabled={!canDelete()} ariaLabel={t("shared.delete")}>
|
||||
<TrashEmptyIcon className="text-muted-foreground h-4 w-4" />
|
||||
</ButtonSecondary>
|
||||
)}
|
||||
</Fragment>
|
||||
) : appOrAdminData.isSuperAdmin ? (
|
||||
<ButtonSecondary to="share" ariaLabel={t("shared.share")}>
|
||||
<ShareIcon className="text-muted-foreground h-4 w-4" />
|
||||
</ButtonSecondary>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmModal ref={confirmDelete} destructive onYes={onDeleteConfirm} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import { EntityWithDetails, PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import RowValueInput from "./RowValueInput";
|
||||
import clsx from "clsx";
|
||||
import PropertyAttributeHelper from "~/utils/helpers/PropertyAttributeHelper";
|
||||
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
|
||||
import { useState } from "react";
|
||||
import { updateItemByIdx } from "~/utils/shared/ObjectUtils";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import { RowValueDto } from "~/application/dtos/entities/RowValueDto";
|
||||
import { getFormProperties } from "~/utils/helpers/PropertyHelper";
|
||||
import { RowDto } from "~/modules/rows/repositories/RowDto";
|
||||
|
||||
export default function RowProperties({
|
||||
entity,
|
||||
item,
|
||||
readOnly,
|
||||
properties,
|
||||
gridColumns,
|
||||
}: {
|
||||
entity: EntityWithDetails;
|
||||
item: RowDto | null;
|
||||
readOnly?: boolean;
|
||||
properties?: string[];
|
||||
gridColumns?: "grid-cols-4" | "grid-cols-3" | "grid-cols-2";
|
||||
}) {
|
||||
const [values, setValues] = useState<RowValueDto[]>(
|
||||
getFormProperties({ mode: item ? "edit" : "create", entity, properties }).map((property) => {
|
||||
const existing = item?.values.find((f) => f.propertyId === property.id);
|
||||
return {
|
||||
propertyId: property.id,
|
||||
property,
|
||||
...existing,
|
||||
textValue: existing?.textValue ?? undefined,
|
||||
numberValue: existing?.numberValue ? Number(existing?.numberValue) : undefined,
|
||||
dateValue: existing?.dateValue ?? undefined,
|
||||
booleanValue: existing ? Boolean(existing?.booleanValue) : undefined,
|
||||
selectedOption: existing?.textValue ?? undefined,
|
||||
media: existing?.media ?? [],
|
||||
multiple: existing?.multiple.sort((a: { order: number }, b: { order: number }) => a.order - b.order) ?? [],
|
||||
range: existing?.range ?? undefined,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
function getPropertyColumnSpan(property: PropertyWithDetails) {
|
||||
const columns = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Columns);
|
||||
if (!columns || columns === undefined) {
|
||||
return "col-span-12";
|
||||
}
|
||||
return `col-span-${columns}`;
|
||||
}
|
||||
// function getValue(property: PropertyWithDetails) {
|
||||
// return values.find((f) => f.propertyId === property.id);
|
||||
// }
|
||||
// function getInitialOption(property: PropertyWithDetails) {
|
||||
// const defaultValueString = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.DefaultValue);
|
||||
// const textValue = getValue(property)?.textValue;
|
||||
// const selectedOption = property.options?.find((f) => f.value === (textValue ?? defaultValueString));
|
||||
// return selectedOption?.value;
|
||||
// }
|
||||
return (
|
||||
<div className={clsx("grid gap-2", gridColumns)}>
|
||||
{values.map((detailValue, idxDetailValue) => {
|
||||
return (
|
||||
<div key={idxDetailValue} className={clsx("w-full", !gridColumns && getPropertyColumnSpan(detailValue.property))}>
|
||||
{/* {prop.type === PropertyType.MULTI_SELECT && <>multiple: {JSON.stringify(value?.multiple)}</>} */}
|
||||
<RowValueInput
|
||||
entity={entity}
|
||||
textValue={values[idxDetailValue].textValue}
|
||||
numberValue={values[idxDetailValue].numberValue}
|
||||
dateValue={values[idxDetailValue].dateValue}
|
||||
booleanValue={values[idxDetailValue].booleanValue}
|
||||
multiple={values[idxDetailValue].multiple}
|
||||
range={values[idxDetailValue].range}
|
||||
initialOption={detailValue.selectedOption}
|
||||
selected={detailValue.property}
|
||||
initialMedia={detailValue.media}
|
||||
onChange={(e) => {
|
||||
updateItemByIdx(values, setValues, idxDetailValue, RowHelper.updateFieldValueTypeArray(values[idxDetailValue], e));
|
||||
}}
|
||||
onChangeOption={(e) => {
|
||||
updateItemByIdx(values, setValues, idxDetailValue, {
|
||||
textValue: e,
|
||||
selectedOption: e,
|
||||
});
|
||||
}}
|
||||
onChangeMedia={(media) => {
|
||||
updateItemByIdx(values, setValues, idxDetailValue, {
|
||||
media,
|
||||
});
|
||||
}}
|
||||
onChangeMultiple={(e) => {
|
||||
updateItemByIdx(values, setValues, idxDetailValue, {
|
||||
multiple: e,
|
||||
});
|
||||
}}
|
||||
onChangeRange={(e) => {
|
||||
updateItemByIdx(values, setValues, idxDetailValue, {
|
||||
range: e,
|
||||
});
|
||||
}}
|
||||
readOnly={readOnly || detailValue.property.isReadOnly}
|
||||
autoFocus={idxDetailValue === 0}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+290
@@ -0,0 +1,290 @@
|
||||
import { RowPermission, Tenant } from "@toolctrl/db/prisma-browser";
|
||||
import { Form, useLocation, useSubmit, useNavigation, useActionData } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ErrorBanner from "~/components/ui/banners/ErrorBanner";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { UserWithDetails } from "~/utils/db/users.db.server";
|
||||
|
||||
type PermissionDto = {
|
||||
tenantId: string | null;
|
||||
userId: string | null;
|
||||
groupId: string | null;
|
||||
roleId: string | null;
|
||||
};
|
||||
export default function RowSettingsPermissions({
|
||||
item,
|
||||
items,
|
||||
tenants,
|
||||
users,
|
||||
withTitle,
|
||||
}: {
|
||||
item: RowWithDetails;
|
||||
items: RowPermission[];
|
||||
tenants: Tenant[];
|
||||
users: UserWithDetails[];
|
||||
withTitle?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const rootData = useRootData();
|
||||
const location = useLocation();
|
||||
const submit = useSubmit();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const actionData = useActionData<{ error: string; success: string }>();
|
||||
|
||||
const [adding, setAdding] = useState(false);
|
||||
|
||||
function getTypeOrder(permission: PermissionDto) {
|
||||
if (permission.tenantId) {
|
||||
return 1;
|
||||
} else if (permission.userId) {
|
||||
return 2;
|
||||
} else if (permission.roleId) {
|
||||
return 3;
|
||||
} else if (permission.groupId) {
|
||||
return 4;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
function getName(permission: PermissionDto) {
|
||||
if (permission.tenantId) {
|
||||
return tenants.find((x) => x.id === permission.tenantId)?.name;
|
||||
} else if (permission.userId) {
|
||||
return users.find((x) => x.id === permission.userId)?.email;
|
||||
} else if (permission.roleId) {
|
||||
return appOrAdminData.allRoles.find((x) => x.id === permission.roleId)?.name;
|
||||
} else if (permission.groupId) {
|
||||
return appOrAdminData.myGroups.find((x) => x.id === permission.groupId)?.name;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
function getTypes() {
|
||||
const options: { name: string; value: string; color: Colors }[] = [];
|
||||
if (users.length > 0) {
|
||||
options.push({ name: t("models.user.object") + "...", value: "user", color: Colors.BLUE });
|
||||
}
|
||||
if (tenants.length > 0) {
|
||||
options.push({ name: t("models.tenant.users") + "...", value: "tenant", color: Colors.GREEN });
|
||||
}
|
||||
if (appOrAdminData.myGroups.length > 0 && rootData.featureFlags?.includes("row-groups")) {
|
||||
options.push({ name: t("models.group.object") + "...", value: "group", color: Colors.INDIGO });
|
||||
}
|
||||
if (appOrAdminData.allRoles.length > 0) {
|
||||
options.push({ name: t("models.role.object") + "...", value: "role", color: Colors.RED });
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function sortedItems() {
|
||||
return items.filter((permission) => !permission.public).sort((a, b) => {
|
||||
const aOrder = getTypeOrder(a);
|
||||
const bOrder = getTypeOrder(b);
|
||||
if (aOrder === bOrder) {
|
||||
return getName(a)?.localeCompare(getName(b) ?? "") ?? 0;
|
||||
}
|
||||
return aOrder - bOrder;
|
||||
});
|
||||
}
|
||||
return (
|
||||
<div className="text-foreground space-y-2">
|
||||
{withTitle && <div className="text-foreground text-sm font-medium">{t("shared.shareWith")}...</div>}
|
||||
{(sortedItems().length > 0 || item.createdByUser) && (
|
||||
<ul className="border-border bg-secondary/70 divide-border divide-y rounded-md border border-dashed">
|
||||
{item.createdByUser && (
|
||||
<div className="flex justify-between space-x-2 truncate px-2 py-2">
|
||||
<div className="flex w-full space-x-2 truncate">
|
||||
<div className="flex flex-col truncate">
|
||||
<div className="text-muted-foreground text-xs font-bold uppercase">
|
||||
<span>{t("models.row.permissionLabels.creator")}</span>
|
||||
</div>
|
||||
<div className="text-foreground truncate text-sm">{item.createdByUser.email}</div>
|
||||
</div>
|
||||
</div>
|
||||
<InputSelect className="w-32 shrink-0" disabled options={[{ name: t("models.row.permissionLabels.owner"), value: "owner" }]} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{sortedItems().map((item, idx) => {
|
||||
return (
|
||||
<div key={idx} className="flex justify-between space-x-2 px-2 py-2">
|
||||
<div className="flex w-1/2 flex-col">
|
||||
<div className="text-muted-foreground text-xs font-bold uppercase">
|
||||
{item.tenantId ? (
|
||||
<span>{t("models.tenant.object")}</span>
|
||||
) : item.roleId ? (
|
||||
<span>{t("models.role.object")}</span>
|
||||
) : item.groupId ? (
|
||||
<span>{t("models.group.object")}</span>
|
||||
) : item.userId ? (
|
||||
<span>{t("models.user.object")}</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="text-foreground truncate text-sm">{getName(item)}</div>
|
||||
</div>
|
||||
<InputSelect
|
||||
className="w-1/2"
|
||||
value={item.access}
|
||||
options={[
|
||||
{ name: t("shared.permissions.canView"), value: "view" },
|
||||
{ name: t("shared.permissions.canComment"), value: "comment" },
|
||||
{ name: t("shared.permissions.canEdit"), value: "edit" },
|
||||
{ name: t("shared.permissions.canDelete"), value: "delete" },
|
||||
{ name: t("shared.remove"), value: "remove" },
|
||||
]}
|
||||
setValue={(value) => {
|
||||
if (value === "remove") {
|
||||
const form = new FormData();
|
||||
form.set("action", "remove");
|
||||
form.set("id", item?.id ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
} else {
|
||||
const form = new FormData();
|
||||
form.set("action", "set-access");
|
||||
form.set("id", item?.id ?? "");
|
||||
form.set("access", value?.toString() ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
{!adding && getTypes().length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAdding(true)}
|
||||
className="border-border hover:border-border relative block w-full rounded-lg border-2 border-dashed p-2 text-center focus:outline-hidden focus:ring-2 focus:ring-gray-500 focus:ring-offset-2"
|
||||
>
|
||||
<PlusIcon className="text-muted-foreground mx-auto h-4" />
|
||||
<span className="text-foreground mt-2 block text-sm font-medium">{t("shared.shareWith")}...</span>
|
||||
</button>
|
||||
)}
|
||||
{adding && <NewPermissionForm tenants={tenants} users={users} onClose={() => setAdding(false)} types={getTypes()} />}
|
||||
{actionData?.error && <ErrorBanner title={t("shared.error")} text={actionData?.error} />}
|
||||
{/* {actionData?.success && <InfoBanner title={t("shared.success")} text={actionData?.success} />} */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NewPermissionForm({
|
||||
tenants,
|
||||
users,
|
||||
types,
|
||||
onClose,
|
||||
}: {
|
||||
tenants: Tenant[];
|
||||
users: UserWithDetails[];
|
||||
types: { name: string; value: string; color: Colors }[];
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const appData = useAppData();
|
||||
const location = useLocation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const navigation = useNavigation();
|
||||
const isAdding = navigation.state === "submitting" && navigation.formData?.get("action") === "share";
|
||||
|
||||
const [type, setType] = useState<string>("");
|
||||
const [id, setId] = useState<string>("");
|
||||
const [access, setAccess] = useState<string>("view");
|
||||
|
||||
useEffect(() => {
|
||||
if (isAdding) {
|
||||
onClose();
|
||||
}
|
||||
}, [isAdding, onClose]);
|
||||
|
||||
useEffect(() => {
|
||||
if (users.length > 0) {
|
||||
setType("user");
|
||||
} else if (tenants.length > 0) {
|
||||
setType("tenant");
|
||||
} else if (appOrAdminData.allRoles.length > 0) {
|
||||
setType("role");
|
||||
} else if (appOrAdminData.myGroups.length > 0) {
|
||||
setType("group");
|
||||
}
|
||||
}, [appOrAdminData.allRoles.length, appOrAdminData.myGroups.length, tenants.length, users.length]);
|
||||
|
||||
function getOptionValues() {
|
||||
if (type === "user") {
|
||||
return users.map((i) => {
|
||||
return { name: i.email + ` (${i.firstName} ${i.lastName})` + (appOrAdminData.user?.id === i.id ? ` (${t("shared.you")})` : ""), value: i.id };
|
||||
});
|
||||
} else if (type === "tenant") {
|
||||
return tenants.map((i) => {
|
||||
return { name: i.name + (appData.currentTenant?.id === i.id ? ` (${t("shared.current")})` : ""), value: i.id };
|
||||
});
|
||||
} else if (type === "role") {
|
||||
return appOrAdminData.allRoles.map((i) => {
|
||||
return { name: i.name, value: i.id };
|
||||
});
|
||||
} else if (type === "group") {
|
||||
return appOrAdminData.myGroups.map((i) => {
|
||||
return { name: i.name, value: i.id };
|
||||
});
|
||||
}
|
||||
return [];
|
||||
}
|
||||
function missingFields() {
|
||||
return !type || !id || !access;
|
||||
}
|
||||
return (
|
||||
<Form method="post" action={location.pathname + location.search}>
|
||||
<input type="hidden" name="action" value="share" hidden readOnly />
|
||||
|
||||
<div className="space-y-2">
|
||||
<InputSelector
|
||||
name="type"
|
||||
withSearch={false}
|
||||
withColors={false}
|
||||
className="w-full"
|
||||
title={t("shared.shareWith") + "..."}
|
||||
value={type}
|
||||
setValue={(e) => setType(e?.toString() ?? "")}
|
||||
options={types}
|
||||
/>
|
||||
<InputSelector name="id" withSearch={true} className="col-span-2" value={id} setValue={(e) => setId(e?.toString() ?? "")} options={getOptionValues()} />
|
||||
|
||||
<InputSelector
|
||||
name="access"
|
||||
withSearch={false}
|
||||
value={access}
|
||||
setValue={(e) => setAccess(e?.toString() ?? "")}
|
||||
options={[
|
||||
{ name: t("shared.permissions.canView"), value: "view" },
|
||||
{ name: t("shared.permissions.canComment"), value: "comment" },
|
||||
{ name: t("shared.permissions.canEdit"), value: "edit" },
|
||||
{ name: t("shared.permissions.canDelete"), value: "delete" },
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<div className="flex space-x-2">
|
||||
<ButtonSecondary onClick={onClose}>{t("shared.cancel")}</ButtonSecondary>
|
||||
<ButtonPrimary type="submit" disabled={missingFields()}>
|
||||
{t("shared.share")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
import { useLocation } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import IconHistory from "~/components/layouts/icons/IconHistory";
|
||||
import ShareIcon from "~/components/ui/icons/crud/ShareIcon";
|
||||
import TagsIcon from "~/components/ui/icons/crud/TagsIcon";
|
||||
import TabsWithIcons, { TabWithIcon } from "~/components/ui/tabs/TabsWithIcons";
|
||||
|
||||
export default function RowSettingsTabs({ canUpdate, isOwner, hasTags = true }: { canUpdate: boolean; isOwner: boolean; hasTags: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const location = useLocation();
|
||||
function isCurrent(name: string) {
|
||||
return location.pathname.endsWith(name);
|
||||
}
|
||||
function getTabs() {
|
||||
const tabs: TabWithIcon[] = [
|
||||
{
|
||||
name: t("shared.activity"),
|
||||
className: "flex justify-center",
|
||||
current: isCurrent("activity"),
|
||||
href: "activity",
|
||||
icon: <IconHistory className="h-6 w-6" />,
|
||||
},
|
||||
];
|
||||
if (canUpdate && hasTags) {
|
||||
tabs.push({
|
||||
name: t("models.row.tags"),
|
||||
className: "flex justify-center",
|
||||
current: isCurrent("tags"),
|
||||
href: "tags",
|
||||
icon: <TagsIcon className="h-5 w-5" />,
|
||||
});
|
||||
}
|
||||
if (isOwner) {
|
||||
tabs.push({
|
||||
name: t("shared.share"),
|
||||
className: "flex justify-center",
|
||||
current: isCurrent("share"),
|
||||
href: "share",
|
||||
icon: <ShareIcon className="h-5 w-5" />,
|
||||
});
|
||||
}
|
||||
return tabs;
|
||||
}
|
||||
return <>{getTabs().length > 1 && <TabsWithIcons justify="center" tabs={getTabs()} />}</>;
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
import { EntityTag } from "@toolctrl/db/prisma-browser";
|
||||
import { Form, useLocation, useNavigation, useSubmit } from "react-router";
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import EmptyState from "~/components/ui/emptyState/EmptyState";
|
||||
import CheckEmptyCircle from "~/components/ui/icons/CheckEmptyCircleIcon";
|
||||
import CheckFilledCircleIcon from "~/components/ui/icons/CheckFilledCircleIcon";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
import TrashEmptyIcon from "~/components/ui/icons/TrashEmptyIcon";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { getColors } from "~/utils/shared/ColorUtils";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
export default function RowSettingsTags({ item, tags }: { item: RowWithDetails; tags: EntityTag[] }) {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const location = useLocation();
|
||||
const rootData = useRootData();
|
||||
const isAdding = navigation.state === "submitting" && navigation.formData?.get("action") === "new-tag";
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
const [tagName, setTagName] = useState("");
|
||||
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAdding) {
|
||||
formRef.current?.reset();
|
||||
setTagName("");
|
||||
}
|
||||
}, [isAdding]);
|
||||
|
||||
function onChangeTag(tag: EntityTag, value: string, color: Colors) {
|
||||
if (tag.value === value && tag.color === color) {
|
||||
return;
|
||||
}
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "edit-tag");
|
||||
form.set("tag-id", tag.id);
|
||||
form.set("tag-name", value);
|
||||
form.set("tag-color", color.toString());
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
|
||||
function onSetRowTag(id: string, add: any) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "set-tag");
|
||||
form.set("tag-id", id);
|
||||
form.set("tag-action", add === true ? "add" : "remove");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
|
||||
function sortedItems() {
|
||||
return tags.sort((x, y) => {
|
||||
if (x.id && y.id) {
|
||||
return x.id > y.id ? -1 : 1;
|
||||
}
|
||||
return -1;
|
||||
});
|
||||
}
|
||||
function onDeleteTag(tag: EntityTag) {
|
||||
confirmDelete.current?.setValue(tag);
|
||||
confirmDelete.current?.show(t("shared.tagDelete", { 0: tag.value }), t("shared.delete"), t("shared.cancel"));
|
||||
}
|
||||
function onConfirmDelete(tag: EntityTag) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete-tag");
|
||||
form.set("tag-id", tag.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Form ref={formRef} method="post" action={location.pathname + location.search}>
|
||||
<input hidden readOnly name="action" value="new-tag" />
|
||||
{rootData.csrf && <input hidden readOnly name="csrf" value={rootData.csrf} />}
|
||||
<div className="flex space-x-2">
|
||||
<InputText
|
||||
autoFocus
|
||||
className="w-full"
|
||||
name="tag-name"
|
||||
title={t("shared.newTag")}
|
||||
withLabel={false}
|
||||
placeholder={t("shared.tagNamePlaceholder")}
|
||||
autoComplete="off"
|
||||
required
|
||||
value={tagName}
|
||||
setValue={setTagName}
|
||||
button={
|
||||
<div className="absolute inset-y-0 right-0 flex py-1.5 pr-1.5 ">
|
||||
<kbd className="border-border text-muted-foreground bg-background inline-flex items-center rounded border px-1 font-sans text-sm font-medium">
|
||||
<button type="submit">
|
||||
<PlusIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</kbd>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</Form>
|
||||
|
||||
{tags.length === 0 && (
|
||||
<div>
|
||||
<EmptyState
|
||||
captions={{
|
||||
thereAreNo: t("shared.noTags"),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{sortedItems().map((tag) => {
|
||||
return (
|
||||
<div key={tag.id} className="flex space-x-2">
|
||||
<InputText
|
||||
className="w-full"
|
||||
name={"tag-name-" + tag.id}
|
||||
title={t("shared.tag")}
|
||||
withLabel={false}
|
||||
value={tag.value}
|
||||
setValue={(value) => onChangeTag(tag, value.toString(), tag.color)}
|
||||
/>
|
||||
<InputSelector
|
||||
className="w-36"
|
||||
name="color"
|
||||
title={t("models.group.color")}
|
||||
withSearch={false}
|
||||
withLabel={false}
|
||||
value={tag.color}
|
||||
setValue={(e) => onChangeTag(tag, tag.value, Number(e))}
|
||||
options={
|
||||
getColors().map((color) => {
|
||||
return {
|
||||
name: (
|
||||
<div className="flex items-center space-x-2">
|
||||
<ColorBadge color={color} />
|
||||
{/* <div>{t("app.shared.colors." + Colors[color])}</div> */}
|
||||
</div>
|
||||
),
|
||||
value: color,
|
||||
};
|
||||
}) ?? []
|
||||
}
|
||||
></InputSelector>
|
||||
{/* <InputCheckbox
|
||||
name={"tag-checked-" + tag.id}
|
||||
title=""
|
||||
value={data.item.tags.find((f) => f.tagId === tag.id) !== undefined}
|
||||
setValue={(e) => onSetRowTag(tag.id, e)}
|
||||
/> */}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t(item.tags.filter((f) => f.tagId === tag.id).length > 0 ? "shared.remove" : "shared.add")}
|
||||
onClick={() => onSetRowTag(tag.id, item.tags.filter((f) => f.tagId === tag.id).length === 0)}
|
||||
className="focus:outline-hidden"
|
||||
>
|
||||
{item.tags.filter((f) => f.tagId === tag.id).length > 0 ? (
|
||||
<CheckFilledCircleIcon className="h-4 w-4 text-teal-500 hover:text-teal-600" />
|
||||
) : (
|
||||
<CheckEmptyCircle className="text-muted-foreground hover:text-muted-foreground h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
<button type="button" aria-label={t("shared.delete")} onClick={() => onDeleteTag(tag)} className="focus:outline-hidden">
|
||||
<TrashEmptyIcon className="text-muted-foreground h-4 w-4 hover:text-red-600" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={onConfirmDelete} destructive />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
import clsx from "clsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
import TagFilledIcon from "~/components/ui/icons/TagFilledIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import { RowTagWithDetails } from "~/utils/db/entities/rowTags.db.server";
|
||||
import { getBackgroundColor } from "~/utils/shared/ColorUtils";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
|
||||
interface Props {
|
||||
items: RowTagWithDetails[];
|
||||
onRemove?: (item: RowTagWithDetails) => void;
|
||||
onSetTagsRoute?: string;
|
||||
}
|
||||
|
||||
export default function RowTags({ items, onRemove, onSetTagsRoute }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
|
||||
const sortedItems = () => {
|
||||
return items.slice().sort((x, y) => {
|
||||
if (x.tag.id && y.tag.id) {
|
||||
return x.tag.id > y.tag.id ? -1 : 1;
|
||||
}
|
||||
return -1;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between">
|
||||
<h3 className="text-foreground text-sm font-medium leading-3">
|
||||
<div className="flex items-center space-x-1">
|
||||
<TagFilledIcon className="text-muted-foreground h-4 w-4" />
|
||||
<div>
|
||||
<span className=" font-light italic"></span> {t("models.tag.plural")}
|
||||
</div>
|
||||
</div>
|
||||
</h3>
|
||||
{items.length > 0 && appOrAdminData.user !== undefined && onSetTagsRoute && (
|
||||
<div className="inline text-xs">
|
||||
<Link to={onSetTagsRoute} className="text-muted-foreground flex items-center space-x-1 text-sm hover:underline">
|
||||
<PlusIcon className="h-3 w-3" />
|
||||
<div>{t("shared.setTags")}</div>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{items.length === 0 && (
|
||||
<>
|
||||
{appOrAdminData.user && onSetTagsRoute ? (
|
||||
<Link
|
||||
to={onSetTagsRoute}
|
||||
className="border-border hover:border-border relative block w-full rounded-lg border-2 border-dashed p-4 text-center focus:outline-hidden focus:ring-2 focus:ring-gray-500"
|
||||
>
|
||||
<span className="text-muted-foreground block text-xs font-normal">{t("shared.noTags")}</span>
|
||||
</Link>
|
||||
) : (
|
||||
<div className="border-border relative block w-full rounded-lg border-2 border-dashed p-4 text-center">
|
||||
<span className="text-muted-foreground block text-xs font-normal">{t("shared.noTags")}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<ul className="leading-8">
|
||||
{sortedItems().map((item) => {
|
||||
return (
|
||||
<li key={item.tag.value} className="inline select-none p-0.5">
|
||||
<span className="border-border relative inline-flex items-center rounded-full border px-3 py-0.5">
|
||||
<div className="absolute flex shrink-0 items-center justify-center">
|
||||
<span className={clsx("h-1.5 w-1.5 rounded-full", getBackgroundColor(item.tag.color))} aria-hidden="true" />
|
||||
</div>
|
||||
<div className="text-foreground ml-3.5 text-sm font-medium">{item.tag.value}</div>
|
||||
{onRemove && (
|
||||
<div className="absolute flex shrink-0 items-center justify-center">
|
||||
<XIcon className="h-3 w-3"></XIcon>
|
||||
</div>
|
||||
)}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Form, useSubmit, useNavigation } from "react-router";
|
||||
import CheckEmptyCircle from "~/components/ui/icons/CheckEmptyCircleIcon";
|
||||
import CheckFilledCircleIcon from "~/components/ui/icons/CheckFilledCircleIcon";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
import TrashIcon from "~/components/ui/icons/TrashIcon";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { RowTaskWithDetails } from "~/utils/db/entities/rowTasks.db.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
interface Props {
|
||||
items: RowTaskWithDetails[];
|
||||
}
|
||||
|
||||
export default function RowTasks({ items }: Props) {
|
||||
const submit = useSubmit();
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const isAdding = navigation.state === "submitting" && navigation.formData?.get("action") === "task-new";
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const rootData = useRootData();
|
||||
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
|
||||
const [showAddTask, setShowAddTask] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAdding) {
|
||||
formRef.current?.reset();
|
||||
}
|
||||
}, [isAdding]);
|
||||
|
||||
function onToggleTaskCompleted(id: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "task-complete-toggle");
|
||||
form.set("task-id", id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
function onDeleteTask(id: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "task-delete");
|
||||
form.set("task-id", id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
function canDelete(item: RowTaskWithDetails) {
|
||||
return appOrAdminData.isSuperUser || (!item.completed && item.createdByUserId === appOrAdminData.user?.id);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between">
|
||||
<h3 className="text-foreground text-sm font-medium leading-3">
|
||||
<div className="flex items-center space-x-1">
|
||||
<CheckFilledCircleIcon className="text-muted-foreground h-4 w-4" />
|
||||
<div>
|
||||
<span className=" font-light italic"></span> {t("models.rowTask.plural")}
|
||||
</div>
|
||||
</div>
|
||||
</h3>
|
||||
{items.length > 0 && appOrAdminData.user !== undefined && (
|
||||
<div className="inline text-xs">
|
||||
<button type="button" onClick={() => setShowAddTask(true)} className="text-muted-foreground flex items-center space-x-1 text-sm hover:underline">
|
||||
<PlusIcon className="h-3 w-3" />
|
||||
<div>{t("shared.addTask")}</div>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{items.length === 0 && !showAddTask && (
|
||||
<>
|
||||
{appOrAdminData.user !== undefined ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAddTask(true)}
|
||||
className="border-border hover:border-border relative block w-full rounded-lg border-2 border-dashed p-4 text-center focus:outline-hidden focus:ring-2 focus:ring-gray-500"
|
||||
>
|
||||
<span className="text-muted-foreground block text-xs font-normal">{t("shared.noTasks")}</span>
|
||||
</button>
|
||||
) : (
|
||||
<div className="border-border relative block w-full rounded-lg border-2 border-dashed p-4 text-center">
|
||||
<span className="text-muted-foreground block text-xs font-normal">{t("shared.noTasks")}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{items.length > 0 && (
|
||||
<ul className="border-border rounded-lg border-2 border-dashed p-2">
|
||||
{items.map((item) => {
|
||||
return (
|
||||
<li key={item.id} className="inline py-2">
|
||||
{/* <Link to={"tasks/" + item.id} className="relative inline-flex items-center rounded-md border border-border px-3 py-0.5">
|
||||
<span className="text-sm leading-5 font-medium text-foreground">{item.title}</span>
|
||||
</Link>{" "} */}
|
||||
<div className="group flex items-center justify-between space-x-1 truncate">
|
||||
<div className="flex grow items-center space-x-1 truncate">
|
||||
<button
|
||||
disabled={!appOrAdminData.user}
|
||||
type="button"
|
||||
onClick={() => onToggleTaskCompleted(item.id)}
|
||||
className="text-muted-foreground hover:text-foreground/80 shrink-0 focus:outline-hidden"
|
||||
>
|
||||
{item.completed ? <CheckFilledCircleIcon className="h-5 w-5 text-teal-500" /> : <CheckEmptyCircle className="h-5 w-5" />}
|
||||
</button>
|
||||
<div className="text-muted-foreground truncate text-sm">{item.title}</div>
|
||||
</div>
|
||||
{canDelete(item) && (
|
||||
<button
|
||||
disabled={!canDelete(item) || !appOrAdminData.user}
|
||||
type="button"
|
||||
onClick={() => onDeleteTask(item.id)}
|
||||
className={clsx(
|
||||
"hover:text-muted-foreground text-muted-foreground invisible shrink-0 focus:outline-hidden group-hover:visible",
|
||||
!canDelete(item) && "cursor-not-allowed opacity-50"
|
||||
)}
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{showAddTask && (
|
||||
<Form ref={formRef} method="post">
|
||||
<input hidden readOnly name="action" value="task-new" />
|
||||
{rootData.csrf && <input hidden readOnly name="csrf" value={rootData.csrf} />}
|
||||
<div className={clsx("relative flex w-full rounded-md")}>
|
||||
<input
|
||||
autoFocus
|
||||
type="text"
|
||||
className={clsx("focus:border-border focus:ring-ring border-border block w-full min-w-0 flex-1 rounded-md sm:text-sm")}
|
||||
name="task-title"
|
||||
placeholder={t("shared.newTask") + "..."}
|
||||
autoComplete="off"
|
||||
required
|
||||
/>
|
||||
<div className="absolute inset-y-0 right-0 flex py-1.5 pr-1.5 ">
|
||||
<kbd className="border-border text-muted-foreground bg-background inline-flex items-center rounded border px-1 font-sans text-sm font-medium">
|
||||
<button type="submit">
|
||||
<PlusIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</kbd>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { useState, useEffect, Fragment } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowWithValues } from "~/utils/db/entities/rows.db.server";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
|
||||
export default function RowTitle({ entity, item }: { entity: EntityWithDetails; item: RowWithValues }) {
|
||||
const { t } = useTranslation();
|
||||
const [folio, setFolio] = useState<string | undefined>(undefined);
|
||||
const [description, setDescription] = useState<string | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
setFolio(RowHelper.getRowFolio(entity, item));
|
||||
let description = RowHelper.getTextDescription({ entity, item, t }) ?? "";
|
||||
if (description.length > 160) {
|
||||
description = description.substring(0, 160) + "...";
|
||||
}
|
||||
setDescription(description);
|
||||
}, [entity, item, t]);
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
{!description || folio === description ? (
|
||||
<div className="truncate">{RowHelper.getRowFolio(entity, item)}</div>
|
||||
) : (
|
||||
<div className="flex items-baseline space-x-1 truncate">
|
||||
<div className="truncate">
|
||||
{description} <span className="text-muted-foreground text-xs font-medium uppercase">({RowHelper.getRowFolio(entity, item)})</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
+492
@@ -0,0 +1,492 @@
|
||||
import { RowMedia, RowValueMultiple, RowValueRange } from "@toolctrl/db/prisma-browser";
|
||||
import { Ref, useImperativeHandle, useRef, useState, useEffect, forwardRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { MediaDto } from "~/application/dtos/entities/MediaDto";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import InputDate, { RefInputDate } from "~/components/ui/input/InputDate";
|
||||
import InputNumber, { RefInputNumber } from "~/components/ui/input/InputNumber";
|
||||
import InputText, { RefInputText } from "~/components/ui/input/InputText";
|
||||
import { PropertyWithDetails, EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import InputCheckbox from "~/components/ui/input/InputCheckbox";
|
||||
import InputMedia from "~/components/ui/input/InputMedia";
|
||||
import PropertyAttributeHelper from "~/utils/helpers/PropertyAttributeHelper";
|
||||
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
|
||||
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
|
||||
import InputMultiText, { RefInputMultiText } from "~/components/ui/input/InputMultiText";
|
||||
import PropertyMultiSelector from "../properties/PropertyMultiSelector";
|
||||
import InputRangeNumber from "~/components/ui/input/ranges/InputRangeNumber";
|
||||
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
|
||||
import InputRangeDate from "~/components/ui/input/ranges/InputRangeDate";
|
||||
import { getSeparator } from "~/utils/shared/SeparatorUtils";
|
||||
import InputTextSubtype from "~/components/ui/input/subtypes/InputTextSubtype";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputRadioGroupCards from "~/components/ui/input/InputRadioGroupCards";
|
||||
import { renderSanitizedMarkdown } from "~/utils/html-sanitizer";
|
||||
import { translatePropertyTitle, translateSelectOptionLabel } from "~/utils/i18n/translateLabel";
|
||||
|
||||
export interface RefRowValueInput {
|
||||
focus: () => void;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
selected: PropertyWithDetails | undefined;
|
||||
entity: EntityWithDetails;
|
||||
textValue: string | undefined;
|
||||
numberValue: number | undefined;
|
||||
dateValue: Date | undefined;
|
||||
booleanValue: boolean | undefined;
|
||||
multiple: RowValueMultiple[] | undefined;
|
||||
range: RowValueRange | undefined;
|
||||
initialMedia?: RowMedia[] | undefined;
|
||||
initialOption?: string | undefined;
|
||||
onChange?: (value: string | number | Date | boolean | undefined | null) => void;
|
||||
onChangeOption?: (option: string | undefined) => void;
|
||||
onChangeMedia?: (option: MediaDto[]) => void;
|
||||
onChangeMultiple?: (option: RowValueMultipleDto[]) => void;
|
||||
onChangeRange?: (option: RowValueRangeDto | undefined) => void;
|
||||
readOnly: boolean;
|
||||
className?: string;
|
||||
autoFocus?: boolean;
|
||||
}
|
||||
|
||||
const RowValueInput = (
|
||||
{
|
||||
entity,
|
||||
selected,
|
||||
textValue,
|
||||
numberValue,
|
||||
dateValue,
|
||||
booleanValue,
|
||||
multiple,
|
||||
range,
|
||||
initialMedia,
|
||||
initialOption,
|
||||
onChange,
|
||||
onChangeOption,
|
||||
onChangeMedia,
|
||||
onChangeMultiple,
|
||||
onChangeRange,
|
||||
className,
|
||||
readOnly,
|
||||
autoFocus,
|
||||
}: Props,
|
||||
ref: Ref<RefRowValueInput>
|
||||
) => {
|
||||
useImperativeHandle(ref, () => ({ focus }));
|
||||
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
const numberInput = useRef<RefInputNumber>(null);
|
||||
const textInput = useRef<RefInputText>(null);
|
||||
const dateInput = useRef<RefInputDate>(null);
|
||||
const multipleInput = useRef<RefInputMultiText>(null);
|
||||
|
||||
const [media, setMedia] = useState<MediaDto[]>([]);
|
||||
|
||||
function focus() {
|
||||
if (selected?.type === PropertyType.TEXT) {
|
||||
textInput.current?.input.current?.focus();
|
||||
} else if (selected?.type === PropertyType.NUMBER) {
|
||||
numberInput.current?.input.current?.focus();
|
||||
} else if (selected?.type === PropertyType.DATE) {
|
||||
dateInput.current?.input.current?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function getSelectedTitle() {
|
||||
return selected ? translatePropertyTitle(t, i18n, entity.name, selected) : "";
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (selected?.type === PropertyType.MEDIA) {
|
||||
if (onChangeMedia) {
|
||||
onChangeMedia(media);
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [media]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{selected?.type === PropertyType.TEXT ? (
|
||||
<>
|
||||
{["monaco", "wysiwyg", "iframe"].includes(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Editor) ?? "") &&
|
||||
readOnly ? (
|
||||
<></>
|
||||
) : (
|
||||
<>
|
||||
<InputTextSubtype
|
||||
subtype={selected.subtype as any}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
value={textValue}
|
||||
setValue={(e) => (onChange ? onChange(e.toString()) : undefined)}
|
||||
required={selected.isRequired}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
disabled={readOnly}
|
||||
pattern={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Pattern)}
|
||||
minLength={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Min)}
|
||||
maxLength={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Max)}
|
||||
rows={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Rows)}
|
||||
placeholder={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Placeholder)}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
uppercase={PropertyAttributeHelper.getPropertyAttributeValue_Boolean(selected, PropertyAttributeName.Uppercase)}
|
||||
lowercase={PropertyAttributeHelper.getPropertyAttributeValue_Boolean(selected, PropertyAttributeName.Lowercase)}
|
||||
password={PropertyAttributeHelper.getPropertyAttributeValue_Boolean(selected, PropertyAttributeName.Password)}
|
||||
editor={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Editor)}
|
||||
editorLanguage={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.EditorLanguage)}
|
||||
editorSize={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.EditorSize) as any}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{["iframe"].includes(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Editor) ?? "") && readOnly && (
|
||||
<div className="overflow-auto">
|
||||
{getSafeIframePreviewUrl(textValue) ? (
|
||||
<iframe title={getSelectedTitle()} src={getSafeIframePreviewUrl(textValue)} sandbox="allow-scripts" className="h-96 w-full" />
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
{["monaco", "wysiwyg"].includes(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Editor) ?? "") &&
|
||||
readOnly && (
|
||||
<div className="overflow-auto">
|
||||
<label className="mb-1 flex justify-between space-x-2 truncate text-xs font-medium">
|
||||
<span>{getSelectedTitle()}</span>
|
||||
</label>
|
||||
<div className="prose border-border bg-secondary h-auto rounded-md border p-3">
|
||||
<div
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: renderSanitizedMarkdown(textValue),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : selected?.type === PropertyType.NUMBER ? (
|
||||
<InputNumber
|
||||
ref={numberInput}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
required={selected.isRequired}
|
||||
value={numberValue}
|
||||
setValue={(e) => (onChange ? onChange(Number(e)) : undefined)}
|
||||
disabled={readOnly}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
min={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Min)}
|
||||
max={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Max)}
|
||||
step={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Step)}
|
||||
placeholder={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Placeholder)}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
autoFocus={autoFocus}
|
||||
canUnset={true}
|
||||
/>
|
||||
) : selected?.type === PropertyType.DATE ? (
|
||||
<>
|
||||
<InputDate
|
||||
ref={dateInput}
|
||||
required={selected.isRequired}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
value={dateValue}
|
||||
onChange={(e) => (onChange ? onChange(e) : undefined)}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
</>
|
||||
) : selected?.type === PropertyType.SELECT ? (
|
||||
<>
|
||||
{/* <PropertyOptionSelector
|
||||
property={selected}
|
||||
initial={initialOption}
|
||||
onSelected={(e) => {
|
||||
if (onChange) {
|
||||
onChange(e ?? "");
|
||||
}
|
||||
if (onChangeOption) {
|
||||
onChangeOption(e);
|
||||
}
|
||||
}}
|
||||
className={className}
|
||||
disabled={readOnly}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
display={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.SelectOptions) as SelectOptionsDisplay}
|
||||
autoFocus={autoFocus}
|
||||
/> */}
|
||||
{!selected.subtype || selected.subtype === "dropdown" ? (
|
||||
<InputSelect
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
required={selected.isRequired}
|
||||
value={initialOption}
|
||||
defaultValue={textValue}
|
||||
setValue={(e) => {
|
||||
if (onChange) {
|
||||
onChange(e?.toString() ?? "");
|
||||
}
|
||||
if (onChangeOption) {
|
||||
onChangeOption(e?.toString());
|
||||
}
|
||||
}}
|
||||
disabled={readOnly}
|
||||
className={className}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
autoFocus={autoFocus}
|
||||
options={selected.options.map((f) => ({
|
||||
name: translateSelectOptionLabel(t, i18n, entity.name, selected.name, f),
|
||||
value: f.value,
|
||||
}))}
|
||||
/>
|
||||
) : selected.subtype === "radioGroupCards" ? (
|
||||
<InputRadioGroupCards
|
||||
title={getSelectedTitle()}
|
||||
name={selected.name}
|
||||
value={initialOption}
|
||||
defaultValue={textValue}
|
||||
disabled={readOnly}
|
||||
required={selected.isRequired}
|
||||
options={selected.options.map((f) => {
|
||||
return {
|
||||
value: f.value,
|
||||
name: translateSelectOptionLabel(t, i18n, entity.name, selected.name, f),
|
||||
};
|
||||
})}
|
||||
onChange={(e) => {
|
||||
if (onChange) {
|
||||
onChange(e);
|
||||
}
|
||||
if (onChangeOption) {
|
||||
onChangeOption(e);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : selected?.type === PropertyType.BOOLEAN ? (
|
||||
<>
|
||||
<InputCheckbox
|
||||
asToggle={true}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
required={selected.isRequired}
|
||||
value={booleanValue}
|
||||
setValue={(e) => (onChange ? onChange(e as boolean) : undefined)}
|
||||
disabled={readOnly}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
</>
|
||||
) : selected?.type === PropertyType.MEDIA ? (
|
||||
<InputMedia
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
initialMedia={initialMedia}
|
||||
className={className}
|
||||
disabled={readOnly}
|
||||
onSelected={(e) => setMedia(e)}
|
||||
readOnly={readOnly}
|
||||
required={selected.isRequired || (PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Min) ?? 0) > 0}
|
||||
min={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Min)}
|
||||
max={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Max)}
|
||||
accept={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.AcceptFileTypes)}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
) : selected?.type === PropertyType.MULTI_SELECT ? (
|
||||
<>
|
||||
<PropertyMultiSelector
|
||||
subtype={selected.subtype as any}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
required={selected.isRequired}
|
||||
options={selected.options}
|
||||
value={multiple}
|
||||
onSelected={(e) => (onChangeMultiple ? onChangeMultiple(e) : undefined)}
|
||||
disabled={readOnly}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
</>
|
||||
) : selected?.type === PropertyType.MULTI_TEXT ? (
|
||||
<>
|
||||
<InputMultiText
|
||||
ref={multipleInput}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
value={multiple}
|
||||
// onSelected={(e) => (onChangeMultiple ? onChangeMultiple(e) : undefined)}
|
||||
required={selected.isRequired}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
disabled={readOnly}
|
||||
pattern={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Pattern)}
|
||||
minLength={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Min)}
|
||||
maxLength={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Max)}
|
||||
rows={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Rows)}
|
||||
placeholder={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Placeholder)}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
uppercase={PropertyAttributeHelper.getPropertyAttributeValue_Boolean(selected, PropertyAttributeName.Uppercase)}
|
||||
lowercase={PropertyAttributeHelper.getPropertyAttributeValue_Boolean(selected, PropertyAttributeName.Lowercase)}
|
||||
autoFocus={autoFocus}
|
||||
separator={getSeparator(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Separator))}
|
||||
/>
|
||||
</>
|
||||
) : selected?.type === PropertyType.RANGE_NUMBER ? (
|
||||
<>
|
||||
<InputRangeNumber
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
required={selected.isRequired}
|
||||
valueMin={range?.numberMin ? Number(range.numberMin) : undefined}
|
||||
valueMax={range?.numberMax ? Number(range.numberMax) : undefined}
|
||||
onChangeMin={(e) => {
|
||||
if (onChangeRange) {
|
||||
onChangeRange({
|
||||
dateMin: null,
|
||||
dateMax: null,
|
||||
numberMin: Number(e),
|
||||
numberMax: range?.numberMax ? Number(range.numberMax) : null,
|
||||
});
|
||||
}
|
||||
}}
|
||||
onChangeMax={(e) => {
|
||||
if (onChangeRange) {
|
||||
onChangeRange({
|
||||
dateMin: null,
|
||||
dateMax: null,
|
||||
numberMax: Number(e),
|
||||
numberMin: range?.numberMin ? Number(range.numberMin) : null,
|
||||
});
|
||||
}
|
||||
}}
|
||||
disabled={readOnly}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
min={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Min)}
|
||||
max={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Max)}
|
||||
step={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Step)}
|
||||
placeholder={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Placeholder)}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
</>
|
||||
) : selected?.type === PropertyType.RANGE_DATE ? (
|
||||
<>
|
||||
<InputRangeDate
|
||||
required={selected.isRequired}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
valueMin={range?.dateMin ?? undefined}
|
||||
valueMax={range?.dateMax ?? undefined}
|
||||
onChangeMin={(e) => {
|
||||
if (onChangeRange) {
|
||||
onChangeRange({
|
||||
dateMin: e,
|
||||
dateMax: range?.dateMax ?? null,
|
||||
numberMin: null,
|
||||
numberMax: null,
|
||||
});
|
||||
}
|
||||
}}
|
||||
onChangeMax={(e) => {
|
||||
if (onChangeRange) {
|
||||
onChangeRange({
|
||||
dateMin: range?.dateMin ?? null,
|
||||
dateMax: e,
|
||||
numberMin: null,
|
||||
numberMax: null,
|
||||
});
|
||||
}
|
||||
}}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
</>
|
||||
) : selected?.type === PropertyType.FORMULA ? (
|
||||
<>
|
||||
{!selected.formula ? (
|
||||
<div className="text-red-500">{t("models.row.values.unknownFormula")}</div>
|
||||
) : (
|
||||
<InputFormulaValue
|
||||
property={selected}
|
||||
title={translatePropertyTitle(t, i18n, entity.name, selected)}
|
||||
textValue={textValue}
|
||||
numberValue={numberValue}
|
||||
dateValue={dateValue}
|
||||
booleanValue={booleanValue}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className={className}>{t("models.row.values.notSupported")}</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
function InputFormulaValue(props: {
|
||||
property: PropertyWithDetails;
|
||||
title: string;
|
||||
textValue?: string;
|
||||
numberValue?: number;
|
||||
dateValue?: Date;
|
||||
booleanValue?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{props.property.formula?.resultAs === "string" ? (
|
||||
<InputText name={props.property.name} title={props.title} defaultValue={props.textValue} readOnly={true} />
|
||||
) : props.property.formula?.resultAs === "number" ? (
|
||||
<InputNumber name={props.property.name} title={props.title} defaultValue={props.numberValue} readOnly={true} canUnset={true} />
|
||||
) : props.property.formula?.resultAs === "date" ? (
|
||||
<InputDate name={props.property.name} title={props.title} value={props.dateValue} readOnly={true} />
|
||||
) : props.property.formula?.resultAs === "boolean" ? (
|
||||
<InputCheckbox asToggle={true} name={props.property.name} title={props.title} value={props.booleanValue} readOnly={true} />
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function getSafeIframePreviewUrl(value: string | undefined) {
|
||||
if (!value) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(value.trim());
|
||||
return url.protocol === "https:" ? url.toString() : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export default forwardRef(RowValueInput);
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import { useEffect, useState } from "react";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import clsx from "clsx";
|
||||
import { Property } from "@toolctrl/db/prisma-browser";
|
||||
import { Link } from "react-router";
|
||||
|
||||
interface Props {
|
||||
entity: EntityWithDetails;
|
||||
items: RowWithDetails[];
|
||||
className?: string;
|
||||
}
|
||||
export default function RowsKanban({ entity, items, className }: Props) {
|
||||
const [columns, setColumns] = useState<{ name: string; title: string; color?: Colors }[]>([]);
|
||||
const [columnsProperty, setColumnsProperty] = useState<Property>();
|
||||
|
||||
useEffect(() => {
|
||||
const optionsField = entity.properties.find((f) => [PropertyType.SELECT, PropertyType.MULTI_SELECT].includes(f.type));
|
||||
if (optionsField) {
|
||||
setColumns(
|
||||
optionsField.options
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((option) => {
|
||||
return {
|
||||
name: option.value,
|
||||
title: option.value,
|
||||
color: Colors.BLUE,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
setColumnsProperty(optionsField);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
function getItems(columnName: string) {
|
||||
return items.filter((f) => f.values.find((f) => f.propertyId === columnsProperty?.id && f.textValue === columnName));
|
||||
}
|
||||
return (
|
||||
<div className={clsx(className, "flex space-x-4 overflow-x-auto")}>
|
||||
{columns.map((column) => {
|
||||
return (
|
||||
<div key={column.name} className="border-border bg-secondary h-96 w-64 shrink-0 overflow-y-auto rounded-md border p-2 text-sm shadow-2xs">
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-between space-x-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
{column.color && (
|
||||
<div>
|
||||
<ColorBadge color={column.color} />
|
||||
</div>
|
||||
)}
|
||||
<div>{column.title}</div>
|
||||
</div>
|
||||
{/* <button type="button" onClick={onNew(column.name)}>
|
||||
<PlusIcon className="h-3 w-3" />
|
||||
</button> */}
|
||||
</div>
|
||||
{getItems(column.name).map((item) => {
|
||||
return (
|
||||
<div key={item.id} className="hover:bg-secondary border-border bg-background group rounded-md border p-2 shadow-2xs">
|
||||
<Link to={item.id} className="space-y-0.5 text-xs">
|
||||
{entity.properties
|
||||
.filter((f) => !f.isDefault && f.id !== columnsProperty?.id)
|
||||
.map((property, idxProp) => {
|
||||
return (
|
||||
<div key={property.name}>
|
||||
<span className={clsx(idxProp === 0 && "font-bold")}>{RowHelper.getCellValue({ entity, item, property })}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+534
@@ -0,0 +1,534 @@
|
||||
import RowsListAndTable from "./RowsListAndTable";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { EntityWithDetails, PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { ColumnDto } from "~/application/dtos/data/ColumnDto";
|
||||
import KanbanSimple, { KanbanColumn } from "~/components/ui/lists/KanbanSimple";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import { Link, useParams } from "react-router";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import GridContainer from "~/components/ui/lists/GridContainer";
|
||||
import { EntityViewWithDetails } from "~/utils/db/entities/entityViews.db.server";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import clsx from "clsx";
|
||||
import EntityViewHelper from "~/utils/helpers/EntityViewHelper";
|
||||
import RowColumnsHelper from "~/utils/helpers/RowColumnsHelper";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
|
||||
import EmptyState from "~/components/ui/emptyState/EmptyState";
|
||||
import RenderCard from "./RenderCard";
|
||||
import RowsLoadMoreCard from "~/components/ui/tables/RowsLoadMoreCard";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
import { MinusIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface Props {
|
||||
view: "table" | "board" | "grid" | "card";
|
||||
items: RowWithDetails[];
|
||||
routes?: EntitiesApi.Routes;
|
||||
pagination?: PaginationDto;
|
||||
onEditRow?: (row: RowWithDetails) => void;
|
||||
currentView?: EntityViewWithDetails | null;
|
||||
selectedRows?: RowWithDetails[];
|
||||
onSelected?: (item: RowWithDetails[]) => void;
|
||||
readOnly?: boolean;
|
||||
onClickRoute?: (row: RowWithDetails) => string;
|
||||
onRemove?: (row: RowWithDetails) => void;
|
||||
ignoreColumns?: string[];
|
||||
columns?: ColumnDto[];
|
||||
actions?: (row: RowWithDetails) => {
|
||||
title?: string;
|
||||
href?: string;
|
||||
onClick?: () => void;
|
||||
isLoading?: boolean;
|
||||
render?: React.ReactNode;
|
||||
}[];
|
||||
leftHeaders?: RowHeaderDisplayDto<RowWithDetails>[];
|
||||
rightHeaders?: RowHeaderDisplayDto<RowWithDetails>[];
|
||||
}
|
||||
export default function RowsList(props: Props & { entity: EntityWithDetails | string }) {
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
|
||||
const [entity, setEntity] = useState<EntityWithDetails>();
|
||||
const [columns, setColumns] = useState<ColumnDto[]>([]);
|
||||
const [groupBy, setGroupBy] = useState<{ property?: PropertyWithDetails } | undefined>();
|
||||
|
||||
useEffect(() => {
|
||||
let entity: EntityWithDetails | undefined = undefined;
|
||||
let columns: ColumnDto[] = [];
|
||||
let groupBy: { property?: PropertyWithDetails } | undefined = undefined;
|
||||
|
||||
if (typeof props.entity === "string") {
|
||||
entity = appOrAdminData.entities.find((e) => e.name === props.entity);
|
||||
} else {
|
||||
entity = props.entity;
|
||||
}
|
||||
|
||||
if (entity) {
|
||||
const systemView = entity.views.find((f) => f.isSystem);
|
||||
let view = props.currentView ?? systemView;
|
||||
if (!view) {
|
||||
columns = RowColumnsHelper.getDefaultEntityColumns(entity);
|
||||
if (props.view === "board") {
|
||||
columns = columns.filter((f) => f.name !== groupBy?.property?.name);
|
||||
}
|
||||
if (props.ignoreColumns) {
|
||||
columns = columns.filter((f) => !props.ignoreColumns?.includes(f.name));
|
||||
}
|
||||
|
||||
if (props.view === "board") {
|
||||
const property = entity.properties.find((f) => f.type === PropertyType.SELECT && !f.isHidden);
|
||||
if (property) {
|
||||
groupBy = { property };
|
||||
}
|
||||
}
|
||||
} else {
|
||||
columns = view.properties
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((f) => {
|
||||
return { name: f.name ?? "", title: "", visible: true };
|
||||
});
|
||||
if (props.ignoreColumns) {
|
||||
columns = columns.filter((f) => !props.ignoreColumns?.includes(f.name));
|
||||
}
|
||||
|
||||
if (view.layout === "board") {
|
||||
columns = columns.filter((f) => f.name !== groupBy?.property?.name);
|
||||
}
|
||||
|
||||
if (view.groupByPropertyId) {
|
||||
const property = entity.properties.find((f) => f.id === view?.groupByPropertyId);
|
||||
if (property) {
|
||||
groupBy = { property };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if (props.readOnly) {
|
||||
// columns = columns.filter((f) => ![RowDisplayDefaultProperty.FOLIO.toString()].includes(f.name));
|
||||
// }
|
||||
|
||||
if (props.columns !== undefined) {
|
||||
columns = props.columns;
|
||||
}
|
||||
|
||||
setEntity(entity);
|
||||
setColumns(columns);
|
||||
setGroupBy(groupBy);
|
||||
}, [appOrAdminData.entities, props]);
|
||||
|
||||
if (!entity) {
|
||||
return null;
|
||||
} else if (columns.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <RowsListWrapped {...props} entity={entity} columns={columns} groupBy={groupBy} />;
|
||||
}
|
||||
|
||||
function RowsListWrapped({
|
||||
view,
|
||||
entity,
|
||||
items,
|
||||
routes,
|
||||
columns,
|
||||
pagination,
|
||||
groupBy,
|
||||
onEditRow,
|
||||
currentView,
|
||||
selectedRows,
|
||||
onSelected,
|
||||
readOnly,
|
||||
onClickRoute,
|
||||
onRemove,
|
||||
actions,
|
||||
leftHeaders,
|
||||
rightHeaders,
|
||||
}: Props & {
|
||||
entity: EntityWithDetails;
|
||||
columns: ColumnDto[];
|
||||
groupBy?: { property?: PropertyWithDetails };
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const params = useParams();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const entityLabel = translateLabel(t, i18n, entity.titlePlural);
|
||||
|
||||
const [options, setOptions] = useState<KanbanColumn<RowWithDetails>[]>([]);
|
||||
useEffect(() => {
|
||||
if (groupBy?.property) {
|
||||
setOptions(
|
||||
groupBy.property.options.map((option) => {
|
||||
return {
|
||||
name: option.value,
|
||||
color: option.color,
|
||||
title: (
|
||||
<div className="flex items-center space-x-1">
|
||||
{option.name ? <div className="font-bold">{option.name}</div> : <div className="font-bold">{option.value}</div>}
|
||||
</div>
|
||||
),
|
||||
value: (item: RowWithDetails) => (
|
||||
<RenderCard layout={view} item={item} entity={entity} columns={columns} allEntities={appOrAdminData.entities} routes={routes} actions={actions} />
|
||||
),
|
||||
onClickRoute: (i: RowWithDetails) => EntityHelper.getRoutes({ routes, entity, item: i })?.edit ?? "",
|
||||
onNewRoute: (columnValue: string) => {
|
||||
let newRoute = EntityHelper.getRoutes({ routes, entity })?.new;
|
||||
if (newRoute) {
|
||||
return newRoute + `?${groupBy?.property?.name}=${columnValue}`;
|
||||
}
|
||||
return "";
|
||||
},
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [groupBy]);
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
{view == "table" && (
|
||||
<RowsListAndTable
|
||||
columns={columns}
|
||||
entity={entity}
|
||||
items={items}
|
||||
pagination={pagination}
|
||||
routes={routes}
|
||||
onFolioClick={onEditRow}
|
||||
onEditClick={onEditRow}
|
||||
onRelatedRowClick={onEditRow}
|
||||
allEntities={appOrAdminData.entities}
|
||||
editable={!readOnly}
|
||||
selectedRows={selectedRows}
|
||||
onSelected={onSelected}
|
||||
onRemove={onRemove}
|
||||
leftHeaders={leftHeaders}
|
||||
rightHeaders={rightHeaders}
|
||||
/>
|
||||
)}
|
||||
{view === "board" && groupBy && (
|
||||
<KanbanSimple
|
||||
className="pt-2"
|
||||
items={items}
|
||||
classNameWidth={clsx("")}
|
||||
filterValue={(item, column) => {
|
||||
if (groupBy.property) {
|
||||
const value = RowHelper.getPropertyValue({ entity, item, property: groupBy.property });
|
||||
if (column === null && !value) {
|
||||
return true;
|
||||
}
|
||||
return value === column?.name;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
columns={options}
|
||||
undefinedColumn={{
|
||||
name: "__unset",
|
||||
color: Colors.UNDEFINED,
|
||||
title: (
|
||||
<div className="flex items-center space-x-1">
|
||||
<div className="font-bold">{t("shared.notSet")}</div>
|
||||
</div>
|
||||
),
|
||||
value: (item: RowWithDetails) => {
|
||||
return (
|
||||
<div className="bg-background rounded-md">
|
||||
<RenderCard
|
||||
layout={view}
|
||||
item={item}
|
||||
entity={entity}
|
||||
columns={columns}
|
||||
allEntities={appOrAdminData.entities}
|
||||
routes={routes}
|
||||
actions={actions}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
onClickRoute: (i: RowWithDetails) => EntityHelper.getRoutes({ routes, entity, item: i })?.edit ?? "",
|
||||
}}
|
||||
column={groupBy.property?.name ?? ""}
|
||||
renderEmpty={<EmptyCard className="w-full" />}
|
||||
/>
|
||||
)}
|
||||
{view === "grid" && (
|
||||
<Fragment>
|
||||
{items.length === 0 ? (
|
||||
<EmptyState
|
||||
className="w-full py-8"
|
||||
// to={EntityHelper.getRoutes({ routes, entity })?.new ?? ""}
|
||||
captions={{
|
||||
// new: "Add",
|
||||
thereAreNo: t("shared.emptyEntityList", { entity: entityLabel }),
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{/* {pagination && (
|
||||
<GridPagination
|
||||
defaultPageSize={currentView?.pageSize ?? undefined}
|
||||
totalItems={pagination.totalItems}
|
||||
totalPages={pagination.totalPages}
|
||||
page={pagination.page}
|
||||
pageSize={pagination.pageSize}
|
||||
/>
|
||||
)} */}
|
||||
<GridContainer {...(currentView ? EntityViewHelper.getGridLayout(currentView) : { columns: 3, gap: "xs" })}>
|
||||
{items.map((item) => {
|
||||
const href = onClickRoute ? onClickRoute(item) : EntityHelper.getRoutes({ routes, entity, item })?.overview ?? undefined;
|
||||
if (onSelected && selectedRows !== undefined) {
|
||||
return (
|
||||
<ButtonSelectWrapper key={item.id} item={item} onSelected={onSelected} selectedRows={selectedRows}>
|
||||
<RenderCard
|
||||
layout={view}
|
||||
item={item}
|
||||
entity={entity}
|
||||
columns={columns}
|
||||
allEntities={appOrAdminData.entities}
|
||||
routes={routes}
|
||||
actions={actions}
|
||||
/>
|
||||
</ButtonSelectWrapper>
|
||||
);
|
||||
}
|
||||
const card = (
|
||||
<div className={clsx("bg-background group relative rounded-md text-left", href && "hover:bg-secondary")}>
|
||||
<RemoveButton item={item} readOnly={readOnly} onRemove={onRemove} />
|
||||
<RenderCard
|
||||
layout={view}
|
||||
item={item}
|
||||
entity={entity}
|
||||
columns={columns}
|
||||
allEntities={appOrAdminData.entities}
|
||||
routes={routes}
|
||||
actions={actions}
|
||||
href={href}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
return href ? (
|
||||
<Link key={item.id} to={href}>
|
||||
{card}
|
||||
</Link>
|
||||
) : (
|
||||
card
|
||||
);
|
||||
// return (
|
||||
// <Fragment key={item.id}>
|
||||
// <Link to={item.id}>
|
||||
// <div className="group w-full truncate rounded-md border border-border bg-background p-3 text-left shadow-2xs hover:bg-secondary">
|
||||
// <RenderCard layout={view} item={item} entity={entity} columns={columns} allEntities={appOrAdminData.entities} routes={routes} actions={actions} />
|
||||
// </div>
|
||||
// </Link>
|
||||
// </Fragment>
|
||||
// );
|
||||
})}
|
||||
{items.length === 0 ? (
|
||||
<Fragment>{readOnly ? <EmptyCard className="w-full" /> : <AddMoreCard entity={entity} routes={routes} />}</Fragment>
|
||||
) : (
|
||||
<Fragment>
|
||||
<RowsLoadMoreCard pagination={pagination} currentView={currentView} />
|
||||
</Fragment>
|
||||
)}
|
||||
</GridContainer>
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
)}
|
||||
{view === "card" && (
|
||||
<Fragment>
|
||||
{items.length === 0 ? (
|
||||
<EmptyState
|
||||
className="w-full py-8"
|
||||
// to={EntityHelper.getRoutes({ routes, entity })?.new ?? ""}
|
||||
captions={{
|
||||
// new: "Add",
|
||||
thereAreNo: t("shared.emptyEntityList", { entity: entityLabel }),
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex space-x-2 overflow-x-scroll">
|
||||
{items.map((item) => {
|
||||
let className = clsx("w-64");
|
||||
if (onSelected && selectedRows !== undefined) {
|
||||
return (
|
||||
<ButtonSelectWrapper className={clsx("group relative")} key={item.id} item={item} onSelected={onSelected} selectedRows={selectedRows}>
|
||||
<div className={className}>
|
||||
<RemoveButton item={item} readOnly={readOnly} onRemove={onRemove} />
|
||||
<RenderCard
|
||||
layout={view}
|
||||
item={item}
|
||||
entity={entity}
|
||||
columns={columns}
|
||||
allEntities={appOrAdminData.entities}
|
||||
routes={routes}
|
||||
actions={actions}
|
||||
/>
|
||||
</div>
|
||||
</ButtonSelectWrapper>
|
||||
);
|
||||
}
|
||||
const href = onClickRoute ? onClickRoute(item) : EntityHelper.getRoutes({ routes, entity, item })?.overview ?? undefined;
|
||||
const card = (
|
||||
<div className={clsx(className, "group relative rounded-md text-left", href && "hover:bg-secondary")}>
|
||||
<div className={className}>
|
||||
<RemoveButton item={item} readOnly={readOnly} onRemove={onRemove} />
|
||||
<RenderCard
|
||||
layout={view}
|
||||
item={item}
|
||||
entity={entity}
|
||||
columns={columns}
|
||||
allEntities={appOrAdminData.entities}
|
||||
routes={routes}
|
||||
actions={actions}
|
||||
href={href}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return href ? (
|
||||
<Link to={`${EntityHelper.getEntityRoute({ entity, params, appOrAdminData })}/${item.id}`} key={item.id} className="group relative">
|
||||
{/* <RowLinkButton entityName={entity.name} id={item.id} /> */}
|
||||
{card}
|
||||
</Link>
|
||||
) : (
|
||||
card
|
||||
);
|
||||
})}
|
||||
{items.length === 0 ? (
|
||||
<Fragment>{readOnly ? <EmptyCard className="w-full" /> : <AddMoreCard className="w-64" entity={entity} routes={routes} />}</Fragment>
|
||||
) : (
|
||||
<Fragment>
|
||||
{!readOnly && <AddMoreCard className="w-64" entity={entity} routes={routes} />}
|
||||
<RowsLoadMoreCard className="w-64" pagination={pagination} currentView={currentView} />
|
||||
</Fragment>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
export function AddMoreCard({ entity, routes, className }: { entity: EntityWithDetails; routes?: EntitiesApi.Routes; className?: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Fragment>
|
||||
<div className={className}>
|
||||
{routes && (
|
||||
<Link
|
||||
className={clsx(
|
||||
"border-border hover:border-border group flex h-full items-center rounded-md border-2 border-dashed p-2 text-left align-middle shadow-2xs hover:border-dotted hover:bg-slate-100",
|
||||
className
|
||||
)}
|
||||
to={EntityHelper.getRoutes({ routes, entity })?.new ?? ""}
|
||||
>
|
||||
<div className="text-foreground/80 mx-auto flex justify-center text-center align-middle text-sm font-medium">{t("shared.add")}</div>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptyCard({ className }: { className?: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Fragment>
|
||||
<div className={className}>
|
||||
<div className="bg-background border-border group inline-block h-full w-full truncate rounded-md border-2 border-dashed p-12 text-left align-middle shadow-2xs">
|
||||
<div className="text-foreground/80 mx-auto flex justify-center text-center align-middle text-sm font-medium">{t("shared.noRecords")}</div>
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
function ButtonSelectWrapper({
|
||||
item,
|
||||
onSelected,
|
||||
selectedRows,
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
item: RowWithDetails;
|
||||
selectedRows: RowWithDetails[];
|
||||
onSelected: (item: RowWithDetails[]) => void;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
const isSelected = selectedRows.find((f) => f.id === item.id);
|
||||
return (
|
||||
<div className={clsx(className, "group relative rounded-md text-left", isSelected ? "bg-theme-50 hover:bg-theme-50" : "hover:bg-secondary bg-background")}>
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-0 top-0 mr-2 mt-2 origin-top-right justify-center"
|
||||
onClick={() => {
|
||||
if (isSelected) {
|
||||
onSelected(selectedRows.filter((f) => f.id !== item.id));
|
||||
} else {
|
||||
onSelected([...(selectedRows ?? []), item]);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{isSelected ? (
|
||||
<svg
|
||||
fill="currentColor"
|
||||
className="h-5 w-5 text-teal-700"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
x="0px"
|
||||
y="0px"
|
||||
width="50"
|
||||
height="50"
|
||||
viewBox="0 0 50 50"
|
||||
>
|
||||
<path d="M 39 4 L 11 4 C 7.140625 4 4 7.140625 4 11 L 4 39 C 4 42.859375 7.140625 46 11 46 L 39 46 C 42.859375 46 46 42.859375 46 39 L 46 11 C 46 7.140625 42.859375 4 39 4 Z M 23.085938 34.445313 L 13.417969 25.433594 L 14.78125 23.96875 L 22.914063 31.554688 L 36.238281 15.832031 L 37.761719 17.125 Z"></path>
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
fill="currentColor"
|
||||
className="h-5 w-5 text-teal-700"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
x="0px"
|
||||
y="0px"
|
||||
width="50"
|
||||
height="50"
|
||||
viewBox="0 0 50 50"
|
||||
>
|
||||
<path d="M 39 4 L 11 4 C 7.101563 4 4 7.101563 4 11 L 4 39 C 4 42.898438 7.101563 46 11 46 L 39 46 C 42.898438 46 46 42.898438 46 39 L 46 11 C 46 7.101563 42.898438 4 39 4 Z M 42 39 C 42 40.699219 40.699219 42 39 42 L 11 42 C 9.300781 42 8 40.699219 8 39 L 8 11 C 8 9.300781 9.300781 8 11 8 L 39 8 C 40.699219 8 42 9.300781 42 11 Z"></path>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RemoveButton({ item, readOnly, onRemove }: { item: RowWithDetails; readOnly?: boolean; onRemove?: (item: RowWithDetails) => void }) {
|
||||
return (
|
||||
<Fragment>
|
||||
{onRemove && (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
onRemove(item);
|
||||
}}
|
||||
type="button"
|
||||
disabled={readOnly}
|
||||
className={clsx(
|
||||
"text-muted-foreground bg-background absolute right-0 top-0 mr-2 mt-2 hidden origin-top-right justify-center rounded-full",
|
||||
readOnly ? "cursor-not-allowed" : "hover:text-red-500 group-hover:flex"
|
||||
)}
|
||||
>
|
||||
<MinusIcon className="h-6 w-6" />
|
||||
</button>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useEffect, useState } from "react";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { ColumnDto } from "~/application/dtos/data/ColumnDto";
|
||||
import RowDisplayHeaderHelper from "~/utils/helpers/RowDisplayHeaderHelper";
|
||||
import { RowHeaderActionDto } from "~/application/dtos/data/RowHeaderActionDto";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import TrashIcon from "~/components/ui/icons/TrashIcon";
|
||||
|
||||
interface Props {
|
||||
entity: EntityWithDetails;
|
||||
items: RowWithDetails[];
|
||||
routes?: EntitiesApi.Routes;
|
||||
columns?: ColumnDto[];
|
||||
pagination?: PaginationDto;
|
||||
className?: string;
|
||||
editable?: boolean;
|
||||
selectedRows?: RowWithDetails[];
|
||||
onSelected?: (item: RowWithDetails[]) => void;
|
||||
onFolioClick?: (item: RowWithDetails) => void;
|
||||
onEditClick?: (item: RowWithDetails) => void;
|
||||
onRelatedRowClick?: (item: RowWithDetails) => void;
|
||||
leftHeaders?: RowHeaderDisplayDto<RowWithDetails>[];
|
||||
rightHeaders?: RowHeaderDisplayDto<RowWithDetails>[];
|
||||
allEntities: EntityWithDetails[];
|
||||
onRemove?: (item: RowWithDetails) => void;
|
||||
}
|
||||
|
||||
export default function RowsListAndTable({
|
||||
entity,
|
||||
routes,
|
||||
items,
|
||||
pagination,
|
||||
className = "",
|
||||
columns,
|
||||
editable = true,
|
||||
selectedRows,
|
||||
onSelected,
|
||||
onFolioClick,
|
||||
onEditClick,
|
||||
onRelatedRowClick,
|
||||
leftHeaders,
|
||||
rightHeaders,
|
||||
allEntities,
|
||||
onRemove,
|
||||
}: Props) {
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
const [headers, setHeaders] = useState<RowHeaderDisplayDto<RowWithDetails>[]>([]);
|
||||
const [actions, setActions] = useState<RowHeaderActionDto<RowWithDetails>[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
let headers = RowDisplayHeaderHelper.getDisplayedHeaders({
|
||||
routes,
|
||||
entity,
|
||||
columns,
|
||||
layout: "table",
|
||||
allEntities,
|
||||
onFolioClick,
|
||||
onEditClick,
|
||||
onRelatedRowClick,
|
||||
t,
|
||||
i18n,
|
||||
});
|
||||
if (leftHeaders) {
|
||||
headers = [...leftHeaders, ...headers];
|
||||
}
|
||||
if (rightHeaders) {
|
||||
headers = [...headers, ...rightHeaders];
|
||||
}
|
||||
setHeaders(headers);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [entity, columns]);
|
||||
|
||||
useEffect(() => {
|
||||
const actions: RowHeaderActionDto<RowWithDetails>[] = [];
|
||||
if (editable) {
|
||||
actions.push({
|
||||
title: t("shared.edit"),
|
||||
onClickRoute: (_, item) => (onEditClick !== undefined ? undefined : (EntityHelper.getRoutes({ routes, entity, item })?.edit ?? "")),
|
||||
onClick: (_, item) => (onEditClick !== undefined ? onEditClick(item) : undefined),
|
||||
hidden: (item) => !editable || !EntityHelper.getRoutes({ routes, entity, item })?.edit,
|
||||
});
|
||||
}
|
||||
if (onRemove) {
|
||||
actions.push({
|
||||
title: (
|
||||
<div>
|
||||
<TrashIcon className="hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
</div>
|
||||
),
|
||||
onClick: (_, item) => onRemove(item),
|
||||
firstColumn: true,
|
||||
});
|
||||
}
|
||||
setActions(actions);
|
||||
}, [editable, entity, onEditClick, onRemove, routes, t]);
|
||||
|
||||
function getHref(item: RowWithDetails) {
|
||||
return EntityHelper.getRoutes({ routes, entity, item })?.overview;
|
||||
}
|
||||
return (
|
||||
<div className={className}>
|
||||
<TableSimple
|
||||
headers={headers}
|
||||
items={items}
|
||||
pagination={pagination}
|
||||
selectedRows={selectedRows}
|
||||
onSelected={onSelected}
|
||||
actions={actions}
|
||||
onClickRoute={(_, item) => getHref(item)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import { useFetcher, useSearchParams } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import Kanban from "~/components/ui/lists/Kanban";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import { translateEntityTitlePlural } from "~/utils/i18n/translateLabel";
|
||||
|
||||
// type EntityWithRows = {
|
||||
// entity: EntityWithDetails;
|
||||
// rows: RowWithDetails[];
|
||||
// };
|
||||
export default function RowsRelationships({ entities }: { entities: string[] }) {
|
||||
return (
|
||||
<div className="flex overflow-hidden overflow-x-auto">
|
||||
{entities.map((entity) => (
|
||||
<EntityRowsRelationships className="w-full" key={entity} entity={entity} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EntityRowsRelationships({ entity, className, withTitle }: { entity: string; className?: string; withTitle?: boolean }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const fetcher = useFetcher<{ entity: EntityWithDetails; items: RowWithDetails[] }>();
|
||||
const [data, setData] = useState<{ entity: EntityWithDetails; items: RowWithDetails[] }>();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
useEffect(() => {
|
||||
fetcher.load(`relationships?entity=${encodeURIComponent(entity)}&${searchParams}`);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [entity, searchParams]);
|
||||
|
||||
useEffect(() => {
|
||||
setData(fetcher.data);
|
||||
}, [fetcher.data]);
|
||||
|
||||
function isSelected(item: RowWithDetails) {
|
||||
return searchParams.getAll(`${entity}[id]`).includes(item.id);
|
||||
}
|
||||
return (
|
||||
<div className={clsx(className)}>
|
||||
{data?.entity && (
|
||||
<Kanban
|
||||
withTitle={withTitle}
|
||||
columns={[
|
||||
{
|
||||
name: "entity",
|
||||
title: translateEntityTitlePlural(t, i18n, data.entity),
|
||||
items: data?.items ?? [],
|
||||
card: (item) => (
|
||||
<div className="hover:bg-secondary border-border bg-background group w-full truncate rounded-md border p-3 text-left shadow-2xs">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<button
|
||||
className="grow truncate text-left"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (isSelected(item)) {
|
||||
const rows = searchParams.getAll(`${entity}[id]`).filter((id) => id !== item.id);
|
||||
searchParams.delete(`${entity}[id]`);
|
||||
for (const row of rows) searchParams.append(`${entity}[id]`, row);
|
||||
} else {
|
||||
searchParams.append(`${entity}[id]`, item.id);
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
>
|
||||
<div>{RowHelper.getTextDescription({ entity: data.entity!, item, t })}</div>
|
||||
</button>
|
||||
<div className="w-4 shrink-0">{isSelected(item) ? <CheckIcon className="text-muted-foreground h-4 w-4" /> : null}</div>
|
||||
{/* <button type="button" onClick={() => alert("edit: " + item.id)}>
|
||||
Edit
|
||||
</button> */}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import { TFunction, t as i18nT } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import { BooleanFormatType } from "~/utils/shared/BooleanUtils";
|
||||
|
||||
export function getBooleanAsStringValue({ value, format, t }: { value?: boolean; format?: BooleanFormatType; t?: TFunction }) {
|
||||
const translate = t ?? i18nT;
|
||||
return !format || format === "yesNo"
|
||||
? value
|
||||
? translate("shared.yes")
|
||||
: translate("shared.no")
|
||||
: format === "trueFalse"
|
||||
? value
|
||||
? translate("shared.true")
|
||||
: translate("shared.false")
|
||||
: format === "enabledDisabled"
|
||||
? value
|
||||
? translate("shared.enabled")
|
||||
: translate("shared.disabled")
|
||||
: format === "onOff"
|
||||
? value
|
||||
? translate("shared.on")
|
||||
: translate("shared.off")
|
||||
: format === "activeInactive"
|
||||
? value
|
||||
? translate("shared.active")
|
||||
: translate("shared.inactive")
|
||||
: "";
|
||||
}
|
||||
export default function RowBooleanCell({ value, format }: { value?: boolean; format?: BooleanFormatType }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
{!format ? (
|
||||
<div>{value ? <CheckIcon className="h-4 w-4 text-teal-500" /> : <XIcon className="text-muted-foreground h-4 w-4" />}</div>
|
||||
) : (
|
||||
<SimpleBadge title={getBooleanAsStringValue({ value, format, t })} color={value ? Colors.GREEN : Colors.GRAY} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export default function RowCreatedByCell({
|
||||
user,
|
||||
apiKey,
|
||||
}: {
|
||||
user?: { firstName: string; lastName: string; email: string } | null;
|
||||
apiKey?: { alias: string } | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div>
|
||||
{user ? (
|
||||
<div className="flex flex-col text-xs">
|
||||
<div className="font-medium">
|
||||
{user?.firstName} {user?.lastName}
|
||||
</div>
|
||||
<div>{user?.email}</div>
|
||||
</div>
|
||||
) : apiKey ? (
|
||||
<div>
|
||||
{t("models.apiKey.object")}: {apiKey.alias}
|
||||
</div>
|
||||
) : (
|
||||
<div></div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import { createLocaleFormatters, type LocaleFormatters, useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
export type DateFormatType = "YYYY-MM-DD" | "DD-MM-YYYY" | "MM-DD-YYYY" | "diff";
|
||||
|
||||
const fallbackFormatters = createLocaleFormatters("en");
|
||||
|
||||
function padDatePart(value: number) {
|
||||
return value.toString().padStart(2, "0");
|
||||
}
|
||||
|
||||
function formatExplicitDate(value: Date, pattern: Exclude<DateFormatType, "diff">) {
|
||||
const year = value.getFullYear();
|
||||
const month = padDatePart(value.getMonth() + 1);
|
||||
const day = padDatePart(value.getDate());
|
||||
if (pattern === "YYYY-MM-DD") {
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
if (pattern === "DD-MM-YYYY") {
|
||||
return `${day}-${month}-${year}`;
|
||||
}
|
||||
return `${month}-${day}-${year}`;
|
||||
}
|
||||
|
||||
export function getDateAsString({
|
||||
value,
|
||||
format,
|
||||
formatters = fallbackFormatters,
|
||||
}: {
|
||||
value?: Date | null;
|
||||
format?: DateFormatType;
|
||||
formatters?: LocaleFormatters;
|
||||
}) {
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
|
||||
switch (format) {
|
||||
case "YYYY-MM-DD":
|
||||
case "DD-MM-YYYY":
|
||||
case "MM-DD-YYYY":
|
||||
return formatExplicitDate(value, format);
|
||||
case "diff":
|
||||
return formatters.relativeDate(value);
|
||||
default:
|
||||
return formatters.date(value, { dateStyle: "medium" });
|
||||
}
|
||||
}
|
||||
|
||||
export default function RowDateCell({ value, format }: { value?: Date | null; format?: DateFormatType }) {
|
||||
const formatters = useLocaleFormatters();
|
||||
const text = getDateAsString({ value, format, formatters });
|
||||
return <>{!value ? <div></div> : <div>{text}</div>}</>;
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
import { Link } from "react-router";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
export default function RowFolioCell({ prefix, folio, href, onClick }: { prefix: string; folio: number; href?: string; onClick?: () => void }) {
|
||||
const formatters = useLocaleFormatters();
|
||||
const folioText = formatters.number(folio ?? 0, {
|
||||
maximumFractionDigits: 0,
|
||||
minimumIntegerDigits: 4,
|
||||
useGrouping: false,
|
||||
});
|
||||
const text = `${prefix}-${folioText}`;
|
||||
|
||||
return (
|
||||
<>
|
||||
{href ? (
|
||||
<Link
|
||||
to={href}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
className="hover border-border text-muted-foreground hover:text-foreground bg-secondary rounded-md border border-b px-1 py-0.5 text-center text-sm hover:underline"
|
||||
>
|
||||
{text}
|
||||
</Link>
|
||||
) : onClick ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onClick();
|
||||
}}
|
||||
className="hover border-border text-muted-foreground hover:text-foreground bg-secondary rounded-md border border-b px-1 py-0.5 text-center text-sm hover:underline"
|
||||
>
|
||||
{text}
|
||||
</button>
|
||||
) : (
|
||||
<div>{text}</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import clsx from "clsx";
|
||||
import { Fragment } from "react";
|
||||
import { MediaDto } from "~/application/dtos/entities/MediaDto";
|
||||
import DownloadIcon from "~/components/ui/icons/DownloadIcon";
|
||||
|
||||
export default function RowMediaCell({ media, layout = "table" }: { media: MediaDto[] | undefined; layout?: string }) {
|
||||
const onDownload = (media: MediaDto) => {
|
||||
const downloadLink = document.createElement("a");
|
||||
downloadLink.href = media.publicUrl ?? media.file;
|
||||
downloadLink.download = media.name;
|
||||
downloadLink.click();
|
||||
};
|
||||
function getFileName(name: string) {
|
||||
let fileName = name;
|
||||
if (name.includes("/")) {
|
||||
fileName = name.split("/").pop() ?? name;
|
||||
}
|
||||
if (name.includes("\\")) {
|
||||
fileName = name.split("\\").pop() ?? name;
|
||||
}
|
||||
return fileName;
|
||||
}
|
||||
return (
|
||||
<Fragment>
|
||||
<div className={clsx(layout === "table" ? "flex max-h-12 items-center space-x-2 overflow-x-visible truncate" : "grid max-h-60 gap-1 overflow-auto")}>
|
||||
{media
|
||||
?.filter((f) => f.type.includes("image"))
|
||||
.map((item) => {
|
||||
return <img key={item.name} className={clsx("object-cover", layout === "table" ? "h-10" : "")} src={item.publicUrl ?? item.file} alt={item.name} />;
|
||||
})}
|
||||
|
||||
{media
|
||||
?.filter((f) => !f.type.includes("image"))
|
||||
.map((item, idx) => {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={idx}
|
||||
onClick={() => onDownload(item)}
|
||||
className={
|
||||
"hover:border-border text-muted-foreground hover:text-foreground flex items-center space-x-1 border-b border-transparent text-xs hover:border-dashed"
|
||||
}
|
||||
>
|
||||
<div className="font-normal">{getFileName(item.title)}</div>
|
||||
<DownloadIcon className="h-3 w-3" />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import RatingBadge from "~/components/ui/badges/RatingBadge";
|
||||
import { createLocaleFormatters, type LocaleFormatters, useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
export type NumberFormatType = "integer" | "decimal" | "currency" | "percentage" | "rating";
|
||||
|
||||
const fallbackFormatters = createLocaleFormatters("en");
|
||||
const defaultCurrency = "USD";
|
||||
type NumberOptions = Parameters<LocaleFormatters["number"]>[1];
|
||||
const fixedDecimalOptions: NumberOptions = { minimumFractionDigits: 2, maximumFractionDigits: 2 };
|
||||
|
||||
export function getNumberAsStringValue({
|
||||
value,
|
||||
format,
|
||||
currencySymbol,
|
||||
formatters = fallbackFormatters,
|
||||
}: {
|
||||
value?: number | null;
|
||||
format?: NumberFormatType;
|
||||
currencySymbol?: string;
|
||||
formatters?: LocaleFormatters;
|
||||
}) {
|
||||
if (value === null || value === undefined) {
|
||||
return "";
|
||||
}
|
||||
switch (format) {
|
||||
case "integer":
|
||||
return formatters.number(value, { maximumFractionDigits: 0 });
|
||||
case "decimal":
|
||||
return formatters.number(value, fixedDecimalOptions);
|
||||
case "currency":
|
||||
return currencySymbol ? `${currencySymbol}${formatters.number(value, fixedDecimalOptions)}` : formatters.currency(value, defaultCurrency, fixedDecimalOptions);
|
||||
case "percentage":
|
||||
return formatters.percent(value / 100, fixedDecimalOptions);
|
||||
default:
|
||||
return formatters.number(value);
|
||||
}
|
||||
}
|
||||
export default function RowNumberCell({ value, format, currencySymbol }: { value?: number | null; format?: NumberFormatType; currencySymbol?: string }) {
|
||||
const formatters = useLocaleFormatters();
|
||||
const formattedValue = getNumberAsStringValue({ value, format, currencySymbol, formatters });
|
||||
|
||||
return (
|
||||
<>
|
||||
{value === null || value === undefined ? (
|
||||
<div></div>
|
||||
) : (
|
||||
<div>
|
||||
{format === "rating" ? (
|
||||
<span>
|
||||
<RatingBadge value={value} />
|
||||
</span>
|
||||
) : (
|
||||
<span>{formattedValue}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
|
||||
import RowDateCell from "./RowDateCell";
|
||||
import { DateFormatType } from "~/utils/shared/DateUtils";
|
||||
|
||||
interface Props {
|
||||
value: RowValueRangeDto;
|
||||
format?: DateFormatType;
|
||||
}
|
||||
export default function RowRangeDateCell({ value, format }: Props) {
|
||||
return (
|
||||
<div className="flex items-center space-x-1">
|
||||
<RowDateCell value={value?.dateMin ?? undefined} format={format} />
|
||||
<div className="text-muted-foreground">-</div>
|
||||
<RowDateCell value={value?.dateMax ?? undefined} format={format} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
|
||||
import { NumberFormatType } from "~/utils/shared/NumberUtils";
|
||||
import RowNumberCell from "./RowNumberCell";
|
||||
|
||||
interface Props {
|
||||
value: RowValueRangeDto;
|
||||
format?: NumberFormatType;
|
||||
currencySymbol?: string;
|
||||
}
|
||||
export default function RowRangeNumberCell({ value, format, currencySymbol }: Props) {
|
||||
return (
|
||||
<div className="flex items-center space-x-1">
|
||||
<RowNumberCell value={Number(value?.numberMin) ?? undefined} format={format} currencySymbol={currencySymbol} />
|
||||
<div className="text-muted-foreground">-</div>
|
||||
<RowNumberCell value={Number(value?.numberMax) ?? undefined} format={format} currencySymbol={currencySymbol} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
import { Link } from "react-router";
|
||||
import { Fragment } from "react";
|
||||
import { TFunction } from "i18next";
|
||||
import { RowDto } from "~/modules/rows/repositories/RowDto";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
|
||||
export default function RowRelationshipRow({
|
||||
entity,
|
||||
item,
|
||||
onRelatedRowClick,
|
||||
routes,
|
||||
t,
|
||||
}: {
|
||||
entity: EntityWithDetails;
|
||||
item: RowDto;
|
||||
onRelatedRowClick?: () => void;
|
||||
routes?: EntitiesApi.Routes;
|
||||
t: TFunction;
|
||||
}) {
|
||||
return (
|
||||
<Fragment>
|
||||
{onRelatedRowClick !== undefined ? (
|
||||
<button type="button" onClick={onRelatedRowClick} className="hover truncate text-left text-sm hover:underline">
|
||||
{RowHelper.getTextDescription({ entity: entity, item, t })}
|
||||
</button>
|
||||
) : !routes || !EntityHelper.getRoutes({ routes, entity: entity, item })?.overview ? (
|
||||
<div className="hover truncate text-left text-sm hover:underline">{RowHelper.getTextDescription({ entity: entity, item, t })}</div>
|
||||
) : (
|
||||
<Link
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
to={EntityHelper.getRoutes({ routes, entity: entity, item })?.overview ?? ""}
|
||||
className="hover truncate text-left text-sm hover:underline"
|
||||
>
|
||||
{RowHelper.getTextDescription({ entity: entity, item, t })}
|
||||
</Link>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { RowDto } from "~/modules/rows/repositories/RowDto";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import RowRelationshipRow from "./RowRelationshipRow";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { translateEntityTitle } from "~/utils/i18n/translateLabel";
|
||||
|
||||
export default function RowRelationshipRowsByEntity({
|
||||
entity,
|
||||
item,
|
||||
allEntities,
|
||||
onRelatedRowClick,
|
||||
routes,
|
||||
type,
|
||||
}: {
|
||||
entity: EntityWithDetails;
|
||||
item: RowWithDetails;
|
||||
allEntities: EntityWithDetails[];
|
||||
onRelatedRowClick?: () => void;
|
||||
routes?: EntitiesApi.Routes;
|
||||
type: "parents" | "children";
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const relatedEntities = type === "children" ? entity.childEntities.filter((f) => f.hiddenIfEmpty) : entity.parentEntities.filter((f) => f.hiddenIfEmpty);
|
||||
let relatedRows: any[] = [];
|
||||
if (type === "children") {
|
||||
relatedRows = item.childRows?.filter((f) => relatedEntities.some((p) => p.id === f.relationshipId)) ?? [];
|
||||
} else {
|
||||
relatedRows = item.parentRows?.filter((f) => relatedEntities.some((p) => p.id === f.relationshipId)) ?? [];
|
||||
}
|
||||
const relatedRowsByEntity: { entity: EntityWithDetails; rows: RowDto[] }[] = [];
|
||||
relatedRows?.forEach((row) => {
|
||||
const entity = type === "children" ? allEntities.find((f) => f.id === row.child.entityId) : allEntities.find((f) => f.id === row.parent.entityId);
|
||||
if (!entity) {
|
||||
return null;
|
||||
}
|
||||
const existing = relatedRowsByEntity.find((f) => f.entity.id === entity.id);
|
||||
if (existing) {
|
||||
existing.rows.push(type === "children" ? row.child : row.parent);
|
||||
} else {
|
||||
relatedRowsByEntity.push({ entity, rows: [type === "children" ? row.child : row.parent] });
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
{relatedRows.length === 0 ? (
|
||||
<div className="text-muted-foreground px-1 pt-1 pb-0.5 text-center text-sm italic">{t("shared.none")}</div>
|
||||
) : (
|
||||
<ul className="flex max-h-20 max-w-lg flex-col space-y-1 overflow-auto">
|
||||
{relatedRowsByEntity.map(({ entity, rows }) => {
|
||||
return (
|
||||
<div className="space-y-1" key={entity.id}>
|
||||
<div className="text-muted-foreground text-xs font-medium">{translateEntityTitle(t, i18n, entity)}</div>
|
||||
{rows.map((row) => {
|
||||
return (
|
||||
<li key={row.id}>
|
||||
<RowRelationshipRow entity={entity} item={row} onRelatedRowClick={onRelatedRowClick} routes={routes} t={t} />
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import RowSelectedOptionCell from "./RowSelectedOptionCell";
|
||||
|
||||
const translations: Record<string, string> = {
|
||||
"models.contact.status.options.customer": "Kunde",
|
||||
};
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => translations[key] ?? key,
|
||||
i18n: {
|
||||
exists: (key: string) => key in translations,
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("RowSelectedOptionCell", () => {
|
||||
it("renders seed select option labels through model translation fallbacks", () => {
|
||||
render(
|
||||
<RowSelectedOptionCell
|
||||
value="customer"
|
||||
entityName="contact"
|
||||
propertyName="status"
|
||||
display="Name"
|
||||
options={[{ value: "customer", name: "Customer", color: Colors.GREEN }]}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("Kunde")).toBeTruthy();
|
||||
expect(screen.queryByText("Customer")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps custom option labels literal when no model translation exists", () => {
|
||||
render(
|
||||
<RowSelectedOptionCell
|
||||
value="vip"
|
||||
entityName="contact"
|
||||
propertyName="status"
|
||||
display="Name"
|
||||
options={[{ value: "vip", name: "VIP customer", color: Colors.YELLOW }]}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("VIP customer")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import RenderOption from "../../properties/select/RenderOption";
|
||||
import { SelectOptionsDisplay } from "~/utils/shared/SelectOptionsUtils";
|
||||
import { translateSelectOptionLabel } from "~/utils/i18n/translateLabel";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
type ItemDto = { value: string; name: string | null; color: Colors };
|
||||
export default function RowSelectedOptionCell({
|
||||
value,
|
||||
options,
|
||||
display = "Name",
|
||||
entityName,
|
||||
propertyName,
|
||||
}: {
|
||||
value: string;
|
||||
options: ItemDto[];
|
||||
display: SelectOptionsDisplay;
|
||||
entityName?: string;
|
||||
propertyName?: string;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const selected = options.find((f) => f.value === value);
|
||||
if (options.length === 0 || !selected) {
|
||||
return value;
|
||||
}
|
||||
const translatedSelected =
|
||||
entityName && propertyName ? { ...selected, name: translateSelectOptionLabel(t, i18n, entityName, propertyName, selected) } : selected;
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RenderOption option={translatedSelected} display={display} hasColors={true} />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { clsx } from "clsx";
|
||||
import { RowTagWithDetails } from "~/utils/db/entities/rowTags.db.server";
|
||||
import { getBackgroundColor } from "~/utils/shared/ColorUtils";
|
||||
|
||||
export default function RowTagsCell({ items }: { items: RowTagWithDetails[] }) {
|
||||
return (
|
||||
<div>
|
||||
{items?.map((rowTag) => {
|
||||
return (
|
||||
<div
|
||||
key={rowTag.id}
|
||||
className="border-border bg-secondary relative mx-0.5 inline-flex max-w-sm select-none items-center space-x-0.5 overflow-x-auto rounded-full border px-2 py-0.5"
|
||||
>
|
||||
<div className="absolute flex shrink-0 items-center justify-center">
|
||||
<span className={clsx("h-1.5 w-1.5 rounded-full", getBackgroundColor(rowTag.tag.color))} aria-hidden="true" />
|
||||
</div>
|
||||
<div className="text-muted-foreground pl-2 text-xs font-medium">{rowTag.tag.value}</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { Link, useParams } from "react-router";
|
||||
import { ExternalLinkIcon } from "~/components/ui/icons/vendor";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
|
||||
export default function RowLinkButton({ entityName, id }: { entityName: string; id: string }) {
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const params = useParams();
|
||||
const entity = appOrAdminData.entities.find((f) => f.name === entityName)!;
|
||||
return (
|
||||
<Link
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
to={`${EntityHelper.getEntityRoute({ entity, params, appOrAdminData })}/${id}`}
|
||||
className="border-border bg-background hover:border-border absolute right-2 top-2 z-10 hidden rounded-md border p-2 opacity-80 hover:opacity-100 group-hover:block"
|
||||
>
|
||||
<ExternalLinkIcon className="text-foreground/80 h-4 w-4" />
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import type { TFunction } from "i18next";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getDateAsString } from "./cells/RowDateCell";
|
||||
import { getNumberAsStringValue } from "./cells/RowNumberCell";
|
||||
import { getBooleanAsStringValue } from "./cells/RowBooleanCell";
|
||||
import { createLocaleFormatters } from "~/locale/format";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
|
||||
const cellsRoot = path.resolve(process.cwd(), "apps/web/app/components/entities/rows/cells");
|
||||
|
||||
function readCell(relativePath: string) {
|
||||
return fs.readFileSync(path.join(cellsRoot, relativePath), "utf8");
|
||||
}
|
||||
|
||||
describe("row cell formatting i18n", () => {
|
||||
it("keeps visible date, number, and folio formatting on locale formatters", () => {
|
||||
const numberSource = readCell("RowNumberCell.tsx");
|
||||
const sources = [readCell("RowDateCell.tsx"), numberSource, readCell("RowFolioCell.tsx")].join("\n");
|
||||
|
||||
expect(sources).toContain("~/locale/format");
|
||||
expect(sources).toContain("useLocaleFormatters");
|
||||
expect(sources).toContain("formatters.date");
|
||||
expect(sources).toContain("formatters.number");
|
||||
expect(sources).toContain("formatters.currency");
|
||||
expect(sources).toContain("formatters.percent");
|
||||
expect(sources).toContain("formatters.relativeDate");
|
||||
expect(numberSource).not.toContain("value.toString()");
|
||||
expect(sources).not.toContain("DateUtils");
|
||||
expect(sources).not.toContain("NumberUtils");
|
||||
expect(sources).not.toContain("Intl");
|
||||
expect(sources).not.toContain("toLocaleString");
|
||||
expect(sources).not.toContain("ui.autogenerated");
|
||||
});
|
||||
|
||||
it("formats default row numbers through locale formatters", () => {
|
||||
expect(getNumberAsStringValue({ value: 1234567.89, formatters: createLocaleFormatters("en") })).toBe("1,234,567.89");
|
||||
expect(getNumberAsStringValue({ value: 1234567.89, formatters: createLocaleFormatters("de") })).toBe("1.234.567,89");
|
||||
});
|
||||
|
||||
it("keeps explicit row date patterns stable", () => {
|
||||
const value = new Date("2026-05-26T10:20:30.000Z");
|
||||
|
||||
expect(getDateAsString({ value, format: "YYYY-MM-DD" })).toBe("2026-05-26");
|
||||
expect(getDateAsString({ value, format: "DD-MM-YYYY" })).toBe("26-05-2026");
|
||||
expect(getDateAsString({ value, format: "MM-DD-YYYY" })).toBe("05-26-2026");
|
||||
});
|
||||
|
||||
it("formats boolean labels through shared translation keys", () => {
|
||||
const keys: string[] = [];
|
||||
const t = ((key: string) => {
|
||||
keys.push(key);
|
||||
return `translated:${key}`;
|
||||
}) as TFunction;
|
||||
|
||||
expect(getBooleanAsStringValue({ value: true, format: "yesNo", t })).toBe("translated:shared.yes");
|
||||
expect(getBooleanAsStringValue({ value: false, format: "yesNo", t })).toBe("translated:shared.no");
|
||||
expect(getBooleanAsStringValue({ value: true, format: "trueFalse", t })).toBe("translated:shared.true");
|
||||
expect(getBooleanAsStringValue({ value: false, format: "trueFalse", t })).toBe("translated:shared.false");
|
||||
expect(getBooleanAsStringValue({ value: true, format: "enabledDisabled", t })).toBe("translated:shared.enabled");
|
||||
expect(getBooleanAsStringValue({ value: false, format: "enabledDisabled", t })).toBe("translated:shared.disabled");
|
||||
expect(getBooleanAsStringValue({ value: true, format: "onOff", t })).toBe("translated:shared.on");
|
||||
expect(getBooleanAsStringValue({ value: false, format: "onOff", t })).toBe("translated:shared.off");
|
||||
expect(getBooleanAsStringValue({ value: true, format: "activeInactive", t })).toBe("translated:shared.active");
|
||||
expect(getBooleanAsStringValue({ value: false, format: "activeInactive", t })).toBe("translated:shared.inactive");
|
||||
expect(keys).toEqual([
|
||||
"shared.yes",
|
||||
"shared.no",
|
||||
"shared.true",
|
||||
"shared.false",
|
||||
"shared.enabled",
|
||||
"shared.disabled",
|
||||
"shared.on",
|
||||
"shared.off",
|
||||
"shared.active",
|
||||
"shared.inactive",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps RowHelper fallback values on translation keys", () => {
|
||||
const t = ((key: string) => `translated:${key}`) as TFunction;
|
||||
const source = fs.readFileSync(path.resolve(process.cwd(), "apps/web/app/utils/helpers/RowHelper.tsx"), "utf8");
|
||||
|
||||
expect(RowHelper.getFormattedValue(true, PropertyType.BOOLEAN, t)).toBe("translated:shared.yes");
|
||||
expect(RowHelper.getFormattedValue(false, PropertyType.BOOLEAN, t)).toBe("translated:shared.no");
|
||||
expect(RowHelper.getFormattedValue("value", "unsupported" as PropertyType, t)).toBe("translated:models.row.values.notSupported");
|
||||
expect(source).not.toContain('return "Not supported"');
|
||||
expect(source).not.toContain('return value ? "t" : "f"');
|
||||
});
|
||||
});
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const rowsRoot = path.resolve(process.cwd(), "apps/web/app/components/entities/rows");
|
||||
|
||||
function readRowComponent(relativePath: string) {
|
||||
return fs.readFileSync(path.join(rowsRoot, relativePath), "utf8");
|
||||
}
|
||||
|
||||
describe("row empty and error states i18n", () => {
|
||||
it("uses semantic translation keys for logs and unsupported values", () => {
|
||||
const sources = [readRowComponent("RowLogs.tsx"), readRowComponent("RowValueInput.tsx")].join("\n");
|
||||
|
||||
expect(sources).toContain("models.row.logs.noEvents");
|
||||
expect(sources).toContain("models.row.values.unknownFormula");
|
||||
expect(sources).toContain("models.row.values.notSupported");
|
||||
expect(sources).not.toContain("no_events_e339ba73");
|
||||
expect(sources).not.toContain("unknown_formula_f4bd1420");
|
||||
expect(sources).not.toContain("not_supported_8e635455");
|
||||
});
|
||||
|
||||
it("keeps row tag form copy on translated labels", () => {
|
||||
const source = readRowComponent("RowSettingsTags.tsx");
|
||||
|
||||
expect(source).toContain("shared.tagNamePlaceholder");
|
||||
expect(source).toContain('title={t("shared.tag")}');
|
||||
expect(source).not.toContain('title="shared.tag"');
|
||||
expect(source).not.toContain('t("shared.tagName") + "..."');
|
||||
});
|
||||
|
||||
it("keeps row activity timestamps on locale-aware formatters", () => {
|
||||
const sources = [readRowComponent("RowLogs.tsx"), readRowComponent("RowActivity.tsx"), readRowComponent("RowLogComment.tsx")].join("\n");
|
||||
|
||||
expect(sources).toContain("useLocaleFormatters");
|
||||
expect(sources).toContain("formatters.relativeDate");
|
||||
expect(sources).toContain("formatters.dateTime");
|
||||
expect(sources).not.toContain("DateUtils");
|
||||
});
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const sourcePath = path.resolve(process.cwd(), "apps/web/app/components/entities/rows/RowSettingsPermissions.tsx");
|
||||
|
||||
describe("row permissions i18n", () => {
|
||||
it("uses semantic translation keys for creator and owner labels", () => {
|
||||
const source = fs.readFileSync(sourcePath, "utf8");
|
||||
|
||||
expect(source).toContain("models.row.permissionLabels.creator");
|
||||
expect(source).toContain("models.row.permissionLabels.owner");
|
||||
expect(source).not.toContain("<span>Creator</span>");
|
||||
expect(source).not.toContain('name: "Owner"');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user