Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: add Relation Field Card plus button in Show Page #3229

Merged
merged 1 commit into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { useCallback, useContext, useState } from 'react';
import { useQuery } from '@apollo/client';

import { useObjectMetadataItem } from '@/object-metadata/hooks/useObjectMetadataItem';
import { CoreObjectNameSingular } from '@/object-metadata/types/CoreObjectNameSingular';
import { NewButton } from '@/object-record/record-board/components/NewButton';
import { BoardColumnContext } from '@/object-record/record-board/contexts/BoardColumnContext';
Expand Down Expand Up @@ -54,18 +52,10 @@ export const NewOpportunityButton = () => {
setIsCreatingCard(false);
};

const { relationPickerSearchFilter } = useRelationPicker();

// TODO: refactor useFilteredSearchEntityQuery
const { findManyRecordsQuery } = useObjectMetadataItem({
objectNameSingular: CoreObjectNameSingular.Company,
});
const useFindManyQuery = (options: any) =>
useQuery(findManyRecordsQuery, options);
const { identifiersMapper, searchQuery } = useRelationPicker();
const { relationPickerSearchFilter, identifiersMapper, searchQuery } =
useRelationPicker();

const filteredSearchEntityResults = useFilteredSearchEntityQuery({
queryHook: useFindManyQuery,
filters: [
{
fieldNames: searchQuery?.computeFilterFields?.('company') ?? [],
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useQuery } from '@apollo/client';
import { useRecoilValue } from 'recoil';

import { useObjectMetadataItem } from '@/object-metadata/hooks/useObjectMetadataItem';
import { CoreObjectNameSingular } from '@/object-metadata/types/CoreObjectNameSingular';
import { SingleEntitySelectBase } from '@/object-record/relation-picker/components/SingleEntitySelectBase';
import { SingleEntitySelectMenuItems } from '@/object-record/relation-picker/components/SingleEntitySelectMenuItems';
import { useEntitySelectSearch } from '@/object-record/relation-picker/hooks/useEntitySelectSearch';
import { useRelationPicker } from '@/object-record/relation-picker/hooks/useRelationPicker';
import { EntityForSelect } from '@/object-record/relation-picker/types/EntityForSelect';
Expand Down Expand Up @@ -36,16 +34,9 @@ export const OpportunityPicker = ({

const { searchFilter, handleSearchFilterChange } = useEntitySelectSearch();

// TODO: refactor useFilteredSearchEntityQuery
const { findManyRecordsQuery: findManyCompanies } = useObjectMetadataItem({
objectNameSingular: CoreObjectNameSingular.Company,
});
const useFindManyQuery = (options: any) =>
useQuery(findManyCompanies, options);
const { identifiersMapper, searchQuery } = useRelationPicker();

const filteredSearchEntityResults = useFilteredSearchEntityQuery({
queryHook: useFindManyQuery,
filters: [
{
fieldNames: searchQuery?.computeFilterFields?.('company') ?? [],
Expand Down Expand Up @@ -127,7 +118,7 @@ export const OpportunityPicker = ({
/>
<DropdownMenuSeparator />
<RecoilScope>
<SingleEntitySelectBase
<SingleEntitySelectMenuItems
entitiesToSelect={filteredSearchEntityResults.entitiesToSelect}
loading={filteredSearchEntityResults.loading}
onCancel={onCancel}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export const usePersistField = () => {
where: { id: entityId },
updateOneRecordInput: {
[`${fieldName}Id`]: valueToPersist?.id ?? null,
[`${fieldName}`]: valueToPersist ?? null,
[fieldName]: valueToPersist ?? null,
},
},
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useRecoilCallback } from 'recoil';

import { entityFieldsFamilySelector } from '@/object-record/field/states/selectors/entityFieldsFamilySelector';
import { isDeeplyEqual } from '~/utils/isDeeplyEqual';

export const useUpsertRecordFieldFromState = () =>
useRecoilCallback(
({ set }) =>
<T extends { id: string }, F extends keyof T>({
record,
fieldName,
}: {
record: T;
fieldName: F extends string ? F : never;
}) =>
set(
entityFieldsFamilySelector({ entityId: record.id, fieldName }),
(previousField) =>
isDeeplyEqual(previousField, record[fieldName])
? previousField
: record[fieldName],
),
[],
);
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,10 @@ import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
// TODO: refactor with scoped state later
export const useUpsertRecordFromState = () =>
useRecoilCallback(
({ set, snapshot }) =>
<T extends { id: string }>(entity: T) => {
const currentEntity = snapshot
.getLoadable(entityFieldsFamilyState(entity.id))
.valueOrThrow();

if (!isDeeplyEqual(currentEntity, entity)) {
set(entityFieldsFamilyState(entity.id), entity);
}
},
({ set }) =>
<T extends { id: string }>(record: T) =>
set(entityFieldsFamilyState(record.id), (previousRecord) =>
isDeeplyEqual(previousRecord, record) ? previousRecord : record,
),
[],
);
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useEffect, useState } from 'react';

import { useFilterDropdown } from '@/object-record/object-filter-dropdown/hooks/useFilterDropdown';
import { EntitiesForMultipleEntitySelect } from '@/object-record/relation-picker/components/MultipleEntitySelect';
import { SingleEntitySelectBase } from '@/object-record/relation-picker/components/SingleEntitySelectBase';
import { SingleEntitySelectMenuItems } from '@/object-record/relation-picker/components/SingleEntitySelectMenuItems';
import { EntityForSelect } from '@/object-record/relation-picker/types/EntityForSelect';
import { useDropdown } from '@/ui/layout/dropdown/hooks/useDropdown';
import { ViewFilterOperand } from '@/views/types/ViewFilterOperand';
Expand Down Expand Up @@ -99,18 +99,16 @@ export const ObjectFilterDropdownEntitySearchSelect = ({
]);

return (
<>
<SingleEntitySelectBase
entitiesToSelect={entitiesForSelect.entitiesToSelect}
selectedEntity={entitiesForSelect.selectedEntities[0]}
loading={entitiesForSelect.loading}
onEntitySelected={handleRecordSelected}
SelectAllIcon={filterDefinitionUsedInDropdown?.SelectAllIcon}
selectAllLabel={filterDefinitionUsedInDropdown?.selectAllLabel}
isAllEntitySelected={isAllEntitySelected}
isAllEntitySelectShown={isAllEntitySelectShown}
onAllEntitySelected={handleAllEntitySelectClick}
/>
</>
<SingleEntitySelectMenuItems
entitiesToSelect={entitiesForSelect.entitiesToSelect}
selectedEntity={entitiesForSelect.selectedEntities[0]}
loading={entitiesForSelect.loading}
onEntitySelected={handleRecordSelected}
SelectAllIcon={filterDefinitionUsedInDropdown?.SelectAllIcon}
selectAllLabel={filterDefinitionUsedInDropdown?.selectAllLabel}
isAllEntitySelected={isAllEntitySelected}
isAllEntitySelectShown={isAllEntitySelectShown}
onAllEntitySelected={handleAllEntitySelectClick}
/>
);
};
Original file line number Diff line number Diff line change
@@ -1,31 +1,73 @@
import { useContext, useEffect, useMemo } from 'react';
import { useCallback, useContext, useEffect, useMemo } from 'react';
import { css } from '@emotion/react';
import styled from '@emotion/styled';
import { useRecoilValue } from 'recoil';

import { useObjectMetadataItem } from '@/object-metadata/hooks/useObjectMetadataItem';
import { FieldContext } from '@/object-record/field/contexts/FieldContext';
import { usePersistField } from '@/object-record/field/hooks/usePersistField';
import { entityFieldsFamilyState } from '@/object-record/field/states/entityFieldsFamilyState';
import { entityFieldsFamilySelector } from '@/object-record/field/states/selectors/entityFieldsFamilySelector';
import { FieldRelationMetadata } from '@/object-record/field/types/FieldMetadata';
import { useFindManyRecords } from '@/object-record/hooks/useFindManyRecords';
import { useFindOneRecord } from '@/object-record/hooks/useFindOneRecord';
import { useUpdateOneRecord } from '@/object-record/hooks/useUpdateOneRecord';
import { useUpsertRecordFromState } from '@/object-record/hooks/useUpsertRecordFromState';
import { RecordRelationFieldCardContent } from '@/object-record/record-relation-card/components/RecordRelationFieldCardContent';
import { SingleEntitySelectMenuItemsWithSearch } from '@/object-record/relation-picker/components/SingleEntitySelectMenuItemsWithSearch';
import { useRelationPicker } from '@/object-record/relation-picker/hooks/useRelationPicker';
import { EntityForSelect } from '@/object-record/relation-picker/types/EntityForSelect';
import { useFilteredSearchEntityQuery } from '@/search/hooks/useFilteredSearchEntityQuery';
import { IconForbid, IconPlus } from '@/ui/display/icon';
import { LightIconButton } from '@/ui/input/button/components/LightIconButton';
import { Card } from '@/ui/layout/card/components/Card';
import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
import { useDropdown } from '@/ui/layout/dropdown/hooks/useDropdown';
import { DropdownScope } from '@/ui/layout/dropdown/scopes/DropdownScope';
import { Section } from '@/ui/layout/section/components/Section';

const StyledAddDropdown = styled(Dropdown)`
margin-left: auto;
`;

const StyledHeader = styled.header<{ isDropdownOpen?: boolean }>`
align-items: center;
display: flex;
margin-bottom: ${({ theme }) => theme.spacing(2)};

${({ isDropdownOpen, theme }) =>
isDropdownOpen
? ''
: css`
.displayOnHover {
opacity: 0;
pointer-events: none;
transition: opacity ${theme.animation.duration.instant}s ease;
}
`}

&:hover {
.displayOnHover {
opacity: 1;
pointer-events: auto;
}
}
`;

const StyledTitle = styled.div`
font-weight: ${({ theme }) => theme.font.weight.medium};
margin-bottom: ${({ theme }) => theme.spacing(2)};
padding: ${({ theme }) => theme.spacing(0, 1)};
`;

export const RecordRelationFieldCardSection = () => {
const { entityId, fieldDefinition } = useContext(FieldContext);
const {
fieldName,
relationFieldMetadataId,
relationObjectMetadataNameSingular,
relationType,
} = fieldDefinition.metadata as FieldRelationMetadata;
const record = useRecoilValue(entityFieldsFamilyState(entityId));

const {
labelIdentifierFieldMetadata: relationLabelIdentifierFieldMetadata,
Expand All @@ -40,16 +82,11 @@ export const RecordRelationFieldCardSection = () => {

const fieldValue = useRecoilValue<
({ id: string } & Record<string, any>) | null
>(
entityFieldsFamilySelector({
entityId,
fieldName: fieldDefinition.metadata.fieldName,
}),
);
>(entityFieldsFamilySelector({ entityId, fieldName }));

const isToOneObject = relationType === 'TO_ONE_OBJECT';

const { record: recordFromFieldValue } = useFindOneRecord({
const { record: relationRecordFromFieldValue } = useFindOneRecord({
objectNameSingular: relationObjectMetadataNameSingular,
objectRecordId: fieldValue?.id,
skip: !relationLabelIdentifierFieldMetadata || !isToOneObject,
Expand All @@ -58,9 +95,8 @@ export const RecordRelationFieldCardSection = () => {
// ONE_TO_MANY records cannot be retrieved from the field value,
// as the record's field is an empty "Connection" object.
// TODO: maybe the backend could return an array of related records instead?
const { records } = useFindManyRecords({
const { records: relationRecordsFromQuery } = useFindManyRecords({
objectNameSingular: relationObjectMetadataNameSingular,
limit: 5,
filter: {
// TODO: this won't work for MANY_TO_MANY relations.
[`${relationFieldMetadataItem?.name}Id`]: {
Expand All @@ -74,28 +110,120 @@ export const RecordRelationFieldCardSection = () => {
});

const relationRecords = useMemo(
() => (recordFromFieldValue ? [recordFromFieldValue] : records),
[recordFromFieldValue, records],
() =>
relationRecordFromFieldValue
? [relationRecordFromFieldValue]
: relationRecordsFromQuery,
[relationRecordFromFieldValue, relationRecordsFromQuery],
);
const relationRecordIds = useMemo(
() => relationRecords.map(({ id }) => id),
[relationRecords],
);

const upsertRecordFromState = useUpsertRecordFromState();

useEffect(() => {
if (!relationRecords.length) return;

relationRecords.forEach((relationRecord) =>
upsertRecordFromState(relationRecord),
);
}, [relationRecords, upsertRecordFromState]);

const dropdownScopeId = `record-field-card-relation-picker-${fieldDefinition.label}`;

const { closeDropdown, isDropdownOpen } = useDropdown(dropdownScopeId);

const {
identifiersMapper,
relationPickerSearchFilter,
searchQuery,
setRelationPickerSearchFilter,
} = useRelationPicker();

const entities = useFilteredSearchEntityQuery({
filters: [
{
fieldNames:
searchQuery?.computeFilterFields?.(
relationObjectMetadataNameSingular,
) ?? [],
filter: relationPickerSearchFilter,
},
],
orderByField: 'createdAt',
mappingFunction: (recordToMap: any) =>
identifiersMapper?.(recordToMap, relationObjectMetadataNameSingular),
selectedIds: relationRecordIds,
excludeEntityIds: relationRecordIds,
objectNameSingular: relationObjectMetadataNameSingular,
});

const handleCloseRelationPickerDropdown = useCallback(() => {
setRelationPickerSearchFilter('');
}, [setRelationPickerSearchFilter]);

const persistField = usePersistField();
const { updateOneRecord } = useUpdateOneRecord({
objectNameSingular: relationObjectMetadataNameSingular,
});

const handleRelationPickerEntitySelected = (
selectedRelationEntity?: EntityForSelect,
) => {
closeDropdown();

if (!selectedRelationEntity?.id) return;

if (isToOneObject) {
persistField(selectedRelationEntity.record);
return;
}

if (!relationFieldMetadataItem?.name) return;

updateOneRecord({
idToUpdate: selectedRelationEntity.id,
updateOneRecordInput: {
[`${relationFieldMetadataItem.name}Id`]: entityId,
[relationFieldMetadataItem.name]: record,
},
});
};

if (!relationLabelIdentifierFieldMetadata) return null;

return (
<Section>
<StyledTitle>{fieldDefinition.label}</StyledTitle>
<StyledHeader isDropdownOpen={isDropdownOpen}>
<StyledTitle>{fieldDefinition.label}</StyledTitle>
<DropdownScope dropdownScopeId={dropdownScopeId}>
<StyledAddDropdown
dropdownPlacement="right-start"
onClose={handleCloseRelationPickerDropdown}
clickableComponent={
<LightIconButton
className="displayOnHover"
Icon={IconPlus}
accent="tertiary"
/>
}
dropdownComponents={
<SingleEntitySelectMenuItemsWithSearch
EmptyIcon={IconForbid}
entitiesToSelect={entities.entitiesToSelect}
loading={entities.loading}
onEntitySelected={handleRelationPickerEntitySelected}
/>
}
dropdownHotkeyScope={{
scope: dropdownScopeId,
}}
/>
</DropdownScope>
</StyledHeader>
{!!relationRecords.length && (
<Card>
{relationRecords.map((relationRecord, index) => (
{relationRecords.slice(0, 5).map((relationRecord, index) => (
<RecordRelationFieldCardContent
key={`${relationRecord.id}${relationLabelIdentifierFieldMetadata?.id}`}
divider={index < relationRecords.length - 1}
Expand Down
Loading
Loading