Skip to content

The open alternative to Salesforce, designed for AI.

Build inbox thread details and sharing (#28565)

Raphaël Bosi242e0412931c
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsDropdown.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsDropdown.tsx
index 4bd8cdffe3f..a258a969c60 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsDropdown.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsDropdown.tsx
@@ -2,11 +2,11 @@ import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
import { useRef } from 'react';
import { CoreObjectNameSingular } from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { DetailsRow } from 'twenty-ui/components/data-display';
import { LightIconButton } from 'twenty-ui/components/input';
import { Dropdown } from 'twenty-ui/components/navigation';
import {
- IconBell,
IconHash,
IconLink,
IconListSearch,
@@ -18,13 +18,14 @@ import { themeCssVariables, useTheme } from 'twenty-ui/theme';
import { AgentChatChannelIcon } from '@/ai/components/AgentChatChannelIcon';
import { AiChatThreadChannelPicker } from '@/ai/components/AiChatThreadChannelPicker';
-import { AiChatThreadDetailsRow } from '@/ai/components/AiChatThreadDetailsRow';
+import { AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX } from '@/ai/constants/AiChatThreadDetailsLabelWidthInPx';
import { agentChatChannelsState } from '@/ai/states/agentChatChannelsState';
-import { useAgentChatThreadMembers } from '@/ai/hooks/useAgentChatThreadMembers';
import { useAiChatThreadRecordTargets } from '@/ai/hooks/useAiChatThreadRecordTargets';
import { useChatTargetNavigation } from '@/ai/hooks/useChatTargetNavigation';
import { useIsAiChatArtifactSurface } from '@/ai/hooks/useIsAiChatArtifactSurface';
import { agentChatThreadRecordFamilySelector } from '@/ai/states/selectors/agentChatThreadRecordFamilySelector';
+import { agentChatThreadPermissionsFamilySelector } from '@/ai/states/selectors/agentChatThreadPermissionsFamilySelector';
+import { useOpenAssignAiChatInSidePanel } from '@/side-panel/hooks/useOpenAssignAiChatInSidePanel';
import { RecordChip } from '@/object-record/components/RecordChip';
import { MultipleRecordPicker } from '@/object-record/record-picker/multiple-record-picker/components/MultipleRecordPicker';
import { multipleRecordPickerSearchFilterComponentState } from '@/object-record/record-picker/multiple-record-picker/states/multipleRecordPickerSearchFilterComponentState';
@@ -55,10 +56,11 @@ const StyledChannel = styled.span`
gap: ${themeCssVariables.spacing[1]};
`;
-const StyledDetails = styled.div`
+const StyledDetails = styled.dl`
display: flex;
flex-direction: column;
gap: ${themeCssVariables.spacing[2]};
+ margin: 0;
padding: ${themeCssVariables.spacing[2]};
`;
@@ -78,7 +80,13 @@ export const AiChatThreadDetailsDropdown = ({
agentChatThreadRecordFamilySelector,
threadId,
);
- const followers = useAgentChatThreadMembers(thread);
+ const permissions = useAtomFamilySelectorValue(
+ agentChatThreadPermissionsFamilySelector,
+ threadId,
+ );
+ const canChangeAssignee =
+ (permissions?.canUpdate ?? false) && !isDefined(thread?.deletedAt);
+ const { openAssignAiChatInSidePanel } = useOpenAssignAiChatInSidePanel();
const currentWorkspaceMembers = useAtomStateValue(
currentWorkspaceMembersState,
);
@@ -111,7 +119,7 @@ export const AiChatThreadDetailsDropdown = ({
multipleRecordPickerSearchFilterComponentState,
recordPickerDropdownId,
);
- const hasTargetRecords = targetRecords.length > 0;
+ const hasTargetRecords = isNonEmptyArray(targetRecords);
const editRecordTargetsLabel = hasTargetRecords
? t`Edit linked records`
: t`Link to a record`;
@@ -149,13 +157,14 @@ export const AiChatThreadDetailsDropdown = ({
// The details are read first, so focus stays off the first chip
initialFocus={() => dropdownContentRef.current}
align="start"
- width={GenericDropdownContentWidth.ExtraLarge}
+ width={GenericDropdownContentWidth.ExtraExtraLarge}
aria-label={t`Chat details`}
>
<StyledDetails>
{areRecordTargetsAvailable && (
- <AiChatThreadDetailsRow
- Icon={IconLink}
+ <DetailsRow
+ labelWidth={AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX}
+ startIcon={<IconLink size={themeCssVariables.icon.size.md} />}
label={t`Linked to`}
action={
canEditRecordTargets && (
@@ -193,62 +202,62 @@ export const AiChatThreadDetailsDropdown = ({
) : (
<StyledEmptyValue>{t`None`}</StyledEmptyValue>
)}
- </AiChatThreadDetailsRow>
- )}
- {isAiChatInboxEnabled && (
- <>
- <AiChatThreadDetailsRow
- Icon={IconHash}
- label={t`Channel`}
- action={
- isDefined(thread) && (
- <AiChatThreadChannelPicker
- thread={thread}
- dropdownId={`${dropdownId}-channel-picker`}
- />
- )
- }
- >
- {isDefined(channel) ? (
- <StyledChannel>
- <AgentChatChannelIcon
- channel={channel}
- size={theme.icon.size.sm}
- />
- {channel.name}
- </StyledChannel>
- ) : (
- <StyledEmptyValue>{t`None`}</StyledEmptyValue>
- )}
- </AiChatThreadDetailsRow>
- <AiChatThreadDetailsRow Icon={IconUsers} label={t`Assignee`}>
- {isDefined(assignee) ? (
- <RecordChip
- objectNameSingular={
- CoreObjectNameSingular.WorkspaceMember
- }
- record={{ ...assignee, __typename: 'WorkspaceMember' }}
- />
- ) : (
- <StyledEmptyValue>{t`None`}</StyledEmptyValue>
- )}
- </AiChatThreadDetailsRow>
- <AiChatThreadDetailsRow Icon={IconBell} label={t`Following`}>
- {followers.map((workspaceMember) => (
- <RecordChip
- key={workspaceMember.id}
- objectNameSingular={
- CoreObjectNameSingular.WorkspaceMember
- }
- record={{
- ...workspaceMember,
- __typename: 'WorkspaceMember',
- }}
- />
- ))}
- </AiChatThreadDetailsRow>
- </>
+ </DetailsRow>
)}
+ <DetailsRow
+ labelWidth={AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX}
+ startIcon={<IconHash size={themeCssVariables.icon.size.md} />}
+ label={t`Channel`}
+ action={
+ isDefined(thread) && (
+ <AiChatThreadChannelPicker
+ thread={thread}
+ dropdownId={`${dropdownId}-channel-picker`}
+ />
+ )
+ }
+ >
+ {isDefined(channel) ? (
+ <StyledChannel>
+ <AgentChatChannelIcon
+ channel={channel}
+ size={theme.icon.size.sm}
+ />
+ {channel.name}
+ </StyledChannel>
+ ) : (
+ <StyledEmptyValue>{t`None`}</StyledEmptyValue>
+ )}
+ </DetailsRow>
+ <DetailsRow
+ labelWidth={AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX}
+ startIcon={<IconUsers size={themeCssVariables.icon.size.md} />}
+ label={t`Assignee`}
+ action={
+ canChangeAssignee && (
+ <LightIconButton
+ aria-label={t`Change assignee`}
+ title={t`Change assignee`}
+ emphasis="subtle"
+ onClick={() => {
+ closeDropdown(dropdownId);
+ openAssignAiChatInSidePanel([threadId]);
+ }}
+ >
+ <IconPencil />
+ </LightIconButton>
+ )
+ }
+ >
+ {isDefined(assignee) ? (
+ <RecordChip
+ objectNameSingular={CoreObjectNameSingular.WorkspaceMember}
+ record={{ ...assignee, __typename: 'WorkspaceMember' }}
+ />
+ ) : (
+ <StyledEmptyValue>{t`None`}</StyledEmptyValue>
+ )}
+ </DetailsRow>
</StyledDetails>
</DropdownContent>
</DropdownRoot>
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsRow.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsRow.tsx
deleted file mode 100644
index b4dda8a8d41..00000000000
--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsRow.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import { styled } from '@linaria/react';
-import { type ReactNode } from 'react';
-import { type IconComponent } from 'twenty-ui/icon';
-import { themeCssVariables, useTheme } from 'twenty-ui/theme';
-
-const StyledRow = styled.div`
- align-items: flex-start;
- display: flex;
- gap: ${themeCssVariables.spacing[2]};
-`;
-
-const StyledLabel = styled.div`
- align-items: center;
- color: ${themeCssVariables.font.color.tertiary};
- display: flex;
- flex-shrink: 0;
- font-size: ${themeCssVariables.font.size.sm};
- gap: ${themeCssVariables.spacing[1]};
- height: ${themeCssVariables.spacing[6]};
- width: ${themeCssVariables.spacing[24]};
-`;
-
-const StyledLabelText = styled.span`
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-`;
-
-const StyledValue = styled.div`
- align-items: center;
- display: flex;
- flex: 1;
- flex-wrap: wrap;
- gap: ${themeCssVariables.spacing[1]};
- min-height: ${themeCssVariables.spacing[6]};
- min-width: 0;
-`;
-
-type AiChatThreadDetailsRowProps = {
- Icon: IconComponent;
- label: string;
- action?: ReactNode;
- children: ReactNode;
-};
-
-export const AiChatThreadDetailsRow = ({
- Icon,
- label,
- action,
- children,
-}: AiChatThreadDetailsRowProps) => {
- const theme = useTheme();
-
- return (
- <StyledRow>
- <StyledLabel>
- <Icon size={theme.icon.size.sm} />
- <StyledLabelText>{label}</StyledLabelText>
- </StyledLabel>
- <StyledValue>{children}</StyledValue>
- {action}
- </StyledRow>
- );
-};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadFollowersField.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadFollowersField.tsx
new file mode 100644
index 00000000000..ff07d023c75
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadFollowersField.tsx
@@ -0,0 +1,70 @@
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { DetailsRow } from 'twenty-ui/components/data-display';
+import { LightIconButton } from 'twenty-ui/components/input';
+import { IconBell, IconBellOff } from 'twenty-ui/icon';
+import { Avatar, Chip } from 'twenty-ui/primitives/data-display';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX } from '@/ai/constants/AiChatThreadDetailsLabelWidthInPx';
+
+const StyledEmptyValue = styled.span`
+ color: ${themeCssVariables.font.color.light};
+ font-size: ${themeCssVariables.font.size.sm};
+`;
+
+type AiChatThreadFollowersFieldProps = {
+ followers: { id: string; name: string; avatarUrl?: string | null }[];
+ isFollowing: boolean;
+ isSaving?: boolean;
+ onFollowingChange?: (isFollowing: boolean) => void;
+};
+
+export const AiChatThreadFollowersField = ({
+ followers,
+ isFollowing,
+ isSaving = false,
+ onFollowingChange,
+}: AiChatThreadFollowersFieldProps) => {
+ const { t } = useLingui();
+ const actionLabel = isFollowing ? t`Unfollow for me` : t`Follow for me`;
+ const ActionIcon = isFollowing ? IconBellOff : IconBell;
+
+ return (
+ <DetailsRow
+ labelWidth={AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX}
+ startIcon={<IconBell size={themeCssVariables.icon.size.md} />}
+ label={t`Following`}
+ action={
+ isDefined(onFollowingChange) && (
+ <LightIconButton
+ aria-label={actionLabel}
+ title={actionLabel}
+ disabled={isSaving}
+ emphasis="subtle"
+ onClick={() => onFollowingChange(!isFollowing)}
+ >
+ <ActionIcon />
+ </LightIconButton>
+ )
+ }
+ >
+ {isNonEmptyArray(followers) ? (
+ followers.map(({ id, name, avatarUrl }) => (
+ <Chip
+ key={id}
+ variant="soft"
+ startElement={
+ <Avatar name={name} src={avatarUrl} size="sm" shape="circle" />
+ }
+ >
+ {name}
+ </Chip>
+ ))
+ ) : (
+ <StyledEmptyValue>{t`None`}</StyledEmptyValue>
+ )}
+ </DetailsRow>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadLabelsField.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadLabelsField.tsx
new file mode 100644
index 00000000000..519d6a55f93
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadLabelsField.tsx
@@ -0,0 +1,97 @@
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { DetailsRow } from 'twenty-ui/components/data-display';
+import { LightIconButton } from 'twenty-ui/components/input';
+import { Dropdown } from 'twenty-ui/components/navigation';
+import { IconPencil, IconTag } from 'twenty-ui/icon';
+import { Tag } from 'twenty-ui/primitives/data-display';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX } from '@/ai/constants/AiChatThreadDetailsLabelWidthInPx';
+import { type AiChatThreadLabel } from '@/ai/types/AiChatThreadLabel';
+
+const StyledEmptyValue = styled.span`
+ color: ${themeCssVariables.font.color.light};
+ font-size: ${themeCssVariables.font.size.sm};
+`;
+
+type AiChatThreadLabelsFieldProps = {
+ labels: AiChatThreadLabel[];
+ selectedLabelIds: string[];
+ isSaving?: boolean;
+ onLabelsChange?: (labelIds: string[]) => void;
+};
+
+export const AiChatThreadLabelsField = ({
+ labels,
+ selectedLabelIds,
+ isSaving = false,
+ onLabelsChange,
+}: AiChatThreadLabelsFieldProps) => {
+ const { t } = useLingui();
+ const selectedLabels = labels.filter(({ id }) =>
+ selectedLabelIds.includes(id),
+ );
+
+ return (
+ <DetailsRow
+ labelWidth={AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX}
+ startIcon={<IconTag size={themeCssVariables.icon.size.md} />}
+ label={t`Labels`}
+ action={
+ isDefined(onLabelsChange) && (
+ <Dropdown.Root type="menu" multiple>
+ <Dropdown.Trigger
+ render={
+ <LightIconButton
+ aria-label={t`Edit shared labels`}
+ title={t`Edit shared labels`}
+ disabled={isSaving}
+ emphasis="subtle"
+ >
+ <IconPencil />
+ </LightIconButton>
+ }
+ />
+ <Dropdown.Content aria-label={t`Shared conversation labels`}>
+ <Dropdown.Section label={t`Shared conversation labels`}>
+ {!isNonEmptyArray(labels) && (
+ <Dropdown.Empty>{t`No labels available`}</Dropdown.Empty>
+ )}
+ {labels.map(({ id, label, color }) => (
+ <Dropdown.OptionItem
+ key={id}
+ selected={selectedLabelIds.includes(id)}
+ disabled={isSaving}
+ onSelect={() =>
+ onLabelsChange(
+ selectedLabelIds.includes(id)
+ ? selectedLabelIds.filter(
+ (selectedId) => selectedId !== id,
+ )
+ : [...selectedLabelIds, id],
+ )
+ }
+ >
+ <Tag color={color}>{label}</Tag>
+ </Dropdown.OptionItem>
+ ))}
+ </Dropdown.Section>
+ </Dropdown.Content>
+ </Dropdown.Root>
+ )
+ }
+ >
+ {isNonEmptyArray(selectedLabels) ? (
+ selectedLabels.map(({ id, label, color }) => (
+ <Tag key={id} color={color}>
+ {label}
+ </Tag>
+ ))
+ ) : (
+ <StyledEmptyValue>{t`None`}</StyledEmptyValue>
+ )}
+ </DetailsRow>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadShareButton.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadShareButton.tsx
new file mode 100644
index 00000000000..7a3c0e6f7aa
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadShareButton.tsx
@@ -0,0 +1,75 @@
+import { useLingui } from '@lingui/react/macro';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+import { AvatarGroup } from 'twenty-ui/components/data-display';
+import { IconShare } from 'twenty-ui/icon';
+import { Avatar } from 'twenty-ui/primitives/data-display';
+import { Button } from 'twenty-ui/primitives/input';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+const MAX_VISIBLE_ACCESS_MEMBERS = 3;
+
+type AiChatThreadShareButtonProps = {
+ accessMembers?: {
+ id: string;
+ name: string;
+ avatarUrl?: string | null;
+ }[];
+ onClick: () => void;
+ label?: string;
+ accessibleLabel?: string;
+ disabled?: boolean;
+ loading?: boolean;
+ shortcut?: string[];
+};
+
+export const AiChatThreadShareButton = ({
+ accessMembers = [],
+ onClick,
+ label,
+ accessibleLabel,
+ disabled = false,
+ loading = false,
+ shortcut,
+}: AiChatThreadShareButtonProps) => {
+ const { t } = useLingui();
+ const getStartIcon = () => {
+ if (!isNonEmptyArray(accessMembers)) {
+ return <IconShare />;
+ }
+
+ return (
+ <AvatarGroup
+ render={<span />}
+ maxVisible={MAX_VISIBLE_ACCESS_MEMBERS}
+ overlapOffset={themeCssVariables.spacing[1]}
+ overflowShape="circle"
+ avatars={accessMembers.map(({ id, name, avatarUrl }) => (
+ <Avatar
+ key={id}
+ colorSeed={id}
+ name={name}
+ src={avatarUrl}
+ size="sm"
+ shape="circle"
+ ring
+ />
+ ))}
+ />
+ );
+ };
+
+ return (
+ <Button
+ aria-label={accessibleLabel ?? t`Share`}
+ size="sm"
+ variant="outline"
+ disabled={disabled}
+ loading={loading}
+ shortcut={shortcut}
+ onClick={onClick}
+ startIcon={getStartIcon()}
+ >
+ {label ?? t`Share`}
+ </Button>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadStatusField.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadStatusField.tsx
new file mode 100644
index 00000000000..100fb03cc35
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadStatusField.tsx
@@ -0,0 +1,108 @@
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { isDefined } from 'twenty-shared/utils';
+import { DetailsRow } from 'twenty-ui/components/data-display';
+import { LightIconButton } from 'twenty-ui/components/input';
+import { Dropdown } from 'twenty-ui/components/navigation';
+import {
+ IconCheck,
+ IconCircleDashed,
+ IconPencil,
+ IconZzz,
+} from 'twenty-ui/icon';
+import { Tag } from 'twenty-ui/primitives/data-display';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX } from '@/ai/constants/AiChatThreadDetailsLabelWidthInPx';
+import { type AiChatThreadStatusScope } from '@/ai/types/AiChatThreadStatusScope';
+
+const StyledScope = styled.span`
+ color: ${themeCssVariables.font.color.tertiary};
+ font-size: ${themeCssVariables.font.size.sm};
+`;
+
+type AiChatThreadStatusFieldProps = {
+ status: 'open' | 'snoozed' | 'done';
+ scope: AiChatThreadStatusScope;
+ isSaving?: boolean;
+ onStatusChange?: (change: {
+ status: AiChatThreadStatusFieldProps['status'];
+ scope: AiChatThreadStatusScope;
+ }) => void;
+};
+
+export const AiChatThreadStatusField = ({
+ status,
+ scope,
+ isSaving = false,
+ onStatusChange,
+}: AiChatThreadStatusFieldProps) => {
+ const { t } = useLingui();
+ const scopeLabel =
+ scope.type === 'personal' ? t`Your inbox` : scope.channelName;
+ const statusLabels = {
+ open: t`Open`,
+ snoozed: t`Snoozed`,
+ done: t`Done`,
+ };
+ const editLabel = t`Change status in ${scopeLabel}`;
+
+ return (
+ <DetailsRow
+ labelWidth={AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX}
+ startIcon={<IconCircleDashed size={themeCssVariables.icon.size.md} />}
+ label={t`Status`}
+ action={
+ isDefined(onStatusChange) && (
+ <Dropdown.Root type="menu">
+ <Dropdown.Trigger
+ render={
+ <LightIconButton
+ aria-label={editLabel}
+ title={editLabel}
+ disabled={isSaving}
+ emphasis="subtle"
+ >
+ <IconPencil />
+ </LightIconButton>
+ }
+ />
+ <Dropdown.Content aria-label={editLabel}>
+ <Dropdown.Section label={scopeLabel}>
+ <Dropdown.OptionItem
+ selected={status === 'open'}
+ startIcon={<IconCircleDashed />}
+ disabled={isSaving}
+ onSelect={() => onStatusChange({ status: 'open', scope })}
+ >
+ {statusLabels.open}
+ </Dropdown.OptionItem>
+ <Dropdown.OptionItem
+ selected={status === 'snoozed'}
+ startIcon={<IconZzz />}
+ disabled={isSaving}
+ onSelect={() => onStatusChange({ status: 'snoozed', scope })}
+ >
+ {statusLabels.snoozed}
+ </Dropdown.OptionItem>
+ <Dropdown.OptionItem
+ selected={status === 'done'}
+ startIcon={<IconCheck />}
+ disabled={isSaving}
+ onSelect={() => onStatusChange({ status: 'done', scope })}
+ >
+ {statusLabels.done}
+ </Dropdown.OptionItem>
+ </Dropdown.Section>
+ </Dropdown.Content>
+ </Dropdown.Root>
+ )
+ }
+ >
+ <Tag color={status === 'open' ? 'sky' : 'gray'}>
+ {statusLabels[status]}
+ </Tag>
+ <StyledScope>{scopeLabel}</StyledScope>
+ </DetailsRow>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatThreadDetailsFields.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatThreadDetailsFields.stories.tsx
new file mode 100644
index 00000000000..104146ec87d
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatThreadDetailsFields.stories.tsx
@@ -0,0 +1,247 @@
+import { styled } from '@linaria/react';
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { type ComponentProps, useState } from 'react';
+import { expect, fn, userEvent, within } from 'storybook/test';
+import { DetailsRow } from 'twenty-ui/components/data-display';
+import { IconLink, IconUsers } from 'twenty-ui/icon';
+import { Avatar, Chip } from 'twenty-ui/primitives/data-display';
+import { ComponentDecorator } from 'twenty-ui/testing';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX } from '@/ai/constants/AiChatThreadDetailsLabelWidthInPx';
+import { AiChatThreadFollowersField } from '@/ai/components/AiChatThreadFollowersField';
+import { AiChatThreadLabelsField } from '@/ai/components/AiChatThreadLabelsField';
+import { AiChatThreadStatusField } from '@/ai/components/AiChatThreadStatusField';
+import { type AiChatThreadLabel } from '@/ai/types/AiChatThreadLabel';
+import { type AiChatThreadStatusScope } from '@/ai/types/AiChatThreadStatusScope';
+
+const StyledFields = styled.dl`
+ background: ${themeCssVariables.background.primary};
+ border: 1px solid ${themeCssVariables.border.color.medium};
+ border-radius: ${themeCssVariables.border.radius.md};
+ box-sizing: border-box;
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[2]};
+ margin: 0;
+ padding: ${themeCssVariables.spacing[2]};
+ width: 100%;
+`;
+
+const LABELS: AiChatThreadLabel[] = [
+ { id: 'pipeline', label: 'Pipeline', color: 'blue' },
+ { id: 'quarter', label: 'Q4', color: 'purple' },
+];
+const CURRENT_MEMBER = { id: 'thomas', name: 'Thomas' };
+const OTHER_FOLLOWER = { id: 'marco', name: 'Marco Rossi' };
+const onStatusChange = fn();
+const onLabelsChange = fn();
+const onFollowingChange = fn();
+
+type AiChatThreadDetailsFieldsStoryProps = {
+ scope: AiChatThreadStatusScope;
+ isReadOnly?: boolean;
+ isSaving?: boolean;
+ isEmpty?: boolean;
+};
+
+const AiChatThreadDetailsFieldsStory = ({
+ scope,
+ isReadOnly = false,
+ isSaving = false,
+ isEmpty = false,
+}: AiChatThreadDetailsFieldsStoryProps) => {
+ const [status, setStatus] =
+ useState<ComponentProps<typeof AiChatThreadStatusField>['status']>('open');
+ const [selectedLabelIds, setSelectedLabelIds] = useState(
+ isEmpty ? [] : ['pipeline', 'quarter'],
+ );
+ const [isFollowing, setIsFollowing] = useState(!isEmpty);
+ const followers = [
+ ...(isFollowing ? [CURRENT_MEMBER] : []),
+ ...(isEmpty ? [] : [OTHER_FOLLOWER]),
+ ];
+ const handleStatusChange: NonNullable<
+ ComponentProps<typeof AiChatThreadStatusField>['onStatusChange']
+ > = (change) => {
+ onStatusChange(change);
+ setStatus(change.status);
+ };
+ const handleLabelsChange = (labelIds: string[]) => {
+ onLabelsChange(labelIds);
+ setSelectedLabelIds(labelIds);
+ };
+ const handleFollowingChange = (nextIsFollowing: boolean) => {
+ onFollowingChange(nextIsFollowing);
+ setIsFollowing(nextIsFollowing);
+ };
+
+ return (
+ <StyledFields>
+ <AiChatThreadStatusField
+ status={status}
+ scope={scope}
+ isSaving={isSaving}
+ onStatusChange={isReadOnly ? undefined : handleStatusChange}
+ />
+ <DetailsRow
+ labelWidth={AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX}
+ startIcon={<IconLink size={themeCssVariables.icon.size.md} />}
+ label="Linked to"
+ >
+ {['Anthropic', 'Open AI', 'Google'].map((name) => (
+ <Chip
+ key={name}
+ variant="soft"
+ startElement={<Avatar name={name} size="sm" shape="square" />}
+ >
+ {name}
+ </Chip>
+ ))}
+ </DetailsRow>
+ <DetailsRow
+ labelWidth={AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX}
+ startIcon={<IconUsers size={themeCssVariables.icon.size.md} />}
+ label="Assignee"
+ >
+ <Chip
+ variant="soft"
+ startElement={<Avatar name="Thomas" size="sm" shape="circle" />}
+ >
+ Thomas
+ </Chip>
+ </DetailsRow>
+ <AiChatThreadLabelsField
+ labels={LABELS}
+ selectedLabelIds={selectedLabelIds}
+ isSaving={isSaving}
+ onLabelsChange={isReadOnly ? undefined : handleLabelsChange}
+ />
+ <AiChatThreadFollowersField
+ followers={followers}
+ isFollowing={isFollowing}
+ isSaving={isSaving}
+ onFollowingChange={isReadOnly ? undefined : handleFollowingChange}
+ />
+ </StyledFields>
+ );
+};
+
+const meta = {
+ title: 'Modules/AI/AiChatThreadDetailsFields',
+ component: AiChatThreadDetailsFieldsStory,
+ decorators: [ComponentDecorator],
+ parameters: { container: { width: 400 } },
+ args: { scope: { type: 'personal' } },
+ beforeEach: () => {
+ onStatusChange.mockClear();
+ onLabelsChange.mockClear();
+ onFollowingChange.mockClear();
+ },
+} satisfies Meta<typeof AiChatThreadDetailsFieldsStory>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const PersonalInbox: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Change status in Your inbox' }),
+ );
+ await userEvent.click(
+ await body.findByRole('menuitemradio', { name: 'Done' }),
+ );
+ await expect(onStatusChange).toHaveBeenLastCalledWith({
+ status: 'done',
+ scope: { type: 'personal' },
+ });
+ await expect(canvas.getByText('Done')).toBeVisible();
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Edit shared labels' }),
+ );
+ await userEvent.click(
+ await body.findByRole('menuitemcheckbox', { name: 'Q4' }),
+ );
+ await expect(onLabelsChange).toHaveBeenLastCalledWith(['pipeline']);
+ await userEvent.keyboard('{Escape}');
+ await expect(canvas.queryByText('Q4')).not.toBeInTheDocument();
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Unfollow for me' }),
+ );
+ await expect(onFollowingChange).toHaveBeenLastCalledWith(false);
+ await expect(canvas.getByText('Marco Rossi')).toBeVisible();
+ await expect(canvas.getAllByText('Thomas')).toHaveLength(1);
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Follow for me' }),
+ );
+ await expect(onFollowingChange).toHaveBeenLastCalledWith(true);
+ await expect(canvas.getAllByText('Thomas')).toHaveLength(2);
+ },
+};
+
+export const ChannelConversation: Story = {
+ args: {
+ scope: { type: 'channel', channelId: 'sales', channelName: 'Sales' },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Change status in Sales' }),
+ );
+ await userEvent.click(
+ await body.findByRole('menuitemradio', { name: 'Snoozed' }),
+ );
+ await expect(onStatusChange).toHaveBeenLastCalledWith({
+ status: 'snoozed',
+ scope: { type: 'channel', channelId: 'sales', channelName: 'Sales' },
+ });
+ },
+};
+
+export const ReadOnly: Story = {
+ args: { isReadOnly: true },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(canvas.queryByRole('button')).not.toBeInTheDocument();
+ await expect(canvas.getByText('Pipeline')).toBeVisible();
+ await expect(canvas.getByText('Marco Rossi')).toBeVisible();
+ },
+};
+
+export const Saving: Story = {
+ args: { isSaving: true },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ for (const button of canvas.getAllByRole('button')) {
+ await expect(button).toBeDisabled();
+ }
+ },
+};
+
+export const Empty: Story = {
+ args: { isEmpty: true },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(canvas.getAllByText('None')).toHaveLength(2);
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Follow for me' }),
+ );
+ await expect(onFollowingChange).toHaveBeenCalledWith(true);
+ await expect(canvas.getAllByText('None')).toHaveLength(1);
+ },
+};
+
+export const Narrow: Story = {
+ args: { isReadOnly: true },
+ parameters: { container: { width: 320 } },
+};
diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatThreadShareButton.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatThreadShareButton.stories.tsx
new file mode 100644
index 00000000000..d1959a967b9
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatThreadShareButton.stories.tsx
@@ -0,0 +1,81 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, fn, userEvent, within } from 'storybook/test';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+import { AiChatThreadShareButton } from '@/ai/components/AiChatThreadShareButton';
+
+const meta = {
+ title: 'Modules/AI/AiChatThreadShareButton',
+ component: AiChatThreadShareButton,
+ decorators: [ComponentDecorator],
+ parameters: { container: { width: 400 } },
+ args: { onClick: fn() },
+} satisfies Meta<typeof AiChatThreadShareButton>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const WithoutAccessProjection: Story = {
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+
+ await userEvent.click(canvas.getByRole('button', { name: 'Share' }));
+ await expect(args.onClick).toHaveBeenCalledTimes(1);
+ },
+};
+
+export const WithAccessMembers: Story = {
+ args: {
+ accessMembers: [
+ { id: 'thomas', name: 'Thomas' },
+ { id: 'sarah', name: 'Sarah Lin' },
+ { id: 'marco', name: 'Marco Rossi' },
+ ],
+ },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const button = canvas.getByRole('button', { name: 'Share' });
+
+ await userEvent.tab();
+ await expect(button).toHaveFocus();
+ await userEvent.keyboard('{Enter}');
+ await expect(args.onClick).toHaveBeenCalledTimes(1);
+ },
+};
+
+export const MoreAccessMembers: Story = {
+ args: {
+ accessMembers: [
+ { id: 'thomas', name: 'Thomas' },
+ { id: 'sarah', name: 'Sarah Lin' },
+ { id: 'marco', name: 'Marco Rossi' },
+ { id: 'alex', name: 'Alex' },
+ { id: 'maria', name: 'Maria' },
+ ],
+ },
+};
+
+export const Disabled: Story = {
+ args: { disabled: true },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const button = canvas.getByRole('button', { name: 'Share' });
+
+ await expect(button).toBeDisabled();
+ await userEvent.click(button);
+ await expect(args.onClick).not.toHaveBeenCalled();
+ },
+};
+
+export const Loading: Story = {
+ args: { loading: true },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const button = canvas.getByRole('button', { name: 'Share' });
+
+ await expect(button).toBeDisabled();
+ await expect(button).toHaveAttribute('aria-busy', 'true');
+ await userEvent.click(button);
+ await expect(args.onClick).not.toHaveBeenCalled();
+ },
+};
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatThreadDetailsDropdown.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatThreadDetailsDropdown.test.tsx
index 5d63305f69f..a5f20108650 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatThreadDetailsDropdown.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatThreadDetailsDropdown.test.tsx
@@ -175,10 +175,12 @@ const renderDetails = async ({
permissions = EDITABLE_PERMISSIONS,
isAiChatInboxEnabled = true,
shouldOpenDetails = true,
+ deletedAt = null,
}: {
permissions?: typeof EDITABLE_PERMISSIONS;
isAiChatInboxEnabled?: boolean;
shouldOpenDetails?: boolean;
+ deletedAt?: string | null;
} = {}) => {
const MetadataAndApolloMocksWrapper = getJestMetadataAndApolloMocksWrapper({
objectMetadataItems: [
@@ -200,7 +202,7 @@ const renderDetails = async ({
__typename: 'AgentChatThread',
id: THREAD_ID,
title: 'Pricing questions',
- deletedAt: null,
+ deletedAt,
workspaceMemberId: OWNER_ID,
writerWorkspaceMemberIds: [WRITER_ID, OWNER_ID],
});
@@ -240,11 +242,12 @@ describe('AiChatThreadDetailsDropdown', () => {
mockThread.current = buildThread();
});
- it('shows the members following the chat', async () => {
+ it('does not present the creator and writers as followers', async () => {
await renderDetails();
- expect(await screen.findByText('Owner Member')).toBeVisible();
- expect(screen.getByText('Writer Member')).toBeVisible();
+ expect(screen.queryByText('Following')).not.toBeInTheDocument();
+ expect(screen.queryByText('Owner Member')).not.toBeInTheDocument();
+ expect(screen.queryByText('Writer Member')).not.toBeInTheDocument();
});
it('opens the record picker on the linked records, searching the objects a conversation can be linked to', async () => {
@@ -363,6 +366,32 @@ describe('AiChatThreadDetailsDropdown', () => {
).not.toBeInTheDocument();
});
+ it('offers to change the assignee to a conversation editor', async () => {
+ await renderDetails();
+
+ expect(
+ await screen.findByRole('button', { name: 'Change assignee' }),
+ ).toBeVisible();
+ });
+
+ it.each([
+ [
+ 'a shared viewer',
+ { permissions: { ...EDITABLE_PERMISSIONS, canUpdate: false } },
+ ],
+ ['a deleted conversation', { deletedAt: '2026-01-01T00:00:00.000Z' }],
+ ])(
+ 'does not offer to change the assignee for %s',
+ async (_description, options) => {
+ await renderDetails(options);
+
+ expect(await screen.findByText('Assignee')).toBeVisible();
+ expect(
+ screen.queryByRole('button', { name: 'Change assignee' }),
+ ).not.toBeInTheDocument();
+ },
+ );
+
it('reads the links again when one is written elsewhere', async () => {
await renderDetails();
diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatThreadDetailsLabelWidthInPx.ts b/packages/twenty-front/src/modules/ai/constants/AiChatThreadDetailsLabelWidthInPx.ts
new file mode 100644
index 00000000000..ac9fc6e555c
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/AiChatThreadDetailsLabelWidthInPx.ts
@@ -0,0 +1 @@
+export const AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX = 110;
diff --git a/packages/twenty-front/src/modules/ai/types/AiChatThreadLabel.ts b/packages/twenty-front/src/modules/ai/types/AiChatThreadLabel.ts
new file mode 100644
index 00000000000..fb5aebb039a
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/types/AiChatThreadLabel.ts
@@ -0,0 +1,7 @@
+import { type TagColor } from 'twenty-ui/primitives/data-display';
+
+export type AiChatThreadLabel = {
+ id: string;
+ label: string;
+ color: TagColor;
+};
diff --git a/packages/twenty-front/src/modules/ai/types/AiChatThreadStatusScope.ts b/packages/twenty-front/src/modules/ai/types/AiChatThreadStatusScope.ts
new file mode 100644
index 00000000000..bbe359a9ae0
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/types/AiChatThreadStatusScope.ts
@@ -0,0 +1,3 @@
+export type AiChatThreadStatusScope =
+ | { type: 'personal' }
+ | { type: 'channel'; channelId: string; channelName: string };
diff --git a/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContextProviderContent.tsx b/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContextProviderContent.tsx
index 5a53f13a461..ae796a2c1d3 100644
--- a/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContextProviderContent.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContextProviderContent.tsx
@@ -104,6 +104,12 @@ export const CommandMenuContextProviderContent = ({
? (commandMenuItemsDraft ?? commandMenuItems)
: commandMenuItems;
+ const isAiChatInboxHeader =
+ containerType === CommandMenuItemContainerType.ShowPageHeader &&
+ commandMenuContextApi.objectMetadataItem.nameSingular ===
+ CoreObjectNameSingular.AgentChatThread &&
+ (commandMenuContextApi.featureFlags.IS_AI_CHAT_INBOX_ENABLED ?? false);
+
const contextCommandMenuItems = commandMenuItemsToDisplay
.filter(
(item) =>
@@ -140,7 +146,13 @@ export const CommandMenuContextProviderContent = ({
)
.map((item) =>
resolveCommandMenuItemPinning(
- item,
+ {
+ ...item,
+ isPinned:
+ item.isPinned ||
+ (isAiChatInboxHeader &&
+ item.engineComponentKey === EngineComponentKey.SHARE_RECORD),
+ },
commandMenuContextApiForAvailability,
),
);
@@ -154,6 +166,7 @@ export const CommandMenuContextProviderContent = ({
shouldDisplayGlobalRecordCreationCommands,
});
}, [
+ containerType,
commandMenuContextApi,
commandMenuContextApiForAvailability,
globalRecordCreationCommandMenuItems,
diff --git a/packages/twenty-front/src/modules/command-menu-item/contexts/__stories__/CommandMenuContextProviderContent.chatSharing.stories.tsx b/packages/twenty-front/src/modules/command-menu-item/contexts/__stories__/CommandMenuContextProviderContent.chatSharing.stories.tsx
new file mode 100644
index 00000000000..cfaa844e2d2
--- /dev/null
+++ b/packages/twenty-front/src/modules/command-menu-item/contexts/__stories__/CommandMenuContextProviderContent.chatSharing.stories.tsx
@@ -0,0 +1,130 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { useContext } from 'react';
+import { expect, within } from 'storybook/test';
+import {
+ type CommandMenuContextApi,
+ ContextStorePageType,
+ CoreObjectNameSingular,
+} from 'twenty-shared/types';
+import { Badge } from 'twenty-ui/primitives/data-display';
+
+import { EMPTY_COMMAND_MENU_CONTEXT_API } from '@/command-menu-item/constants/EmptyCommandMenuContextApi';
+import { CommandMenuContext } from '@/command-menu-item/contexts/CommandMenuContext';
+import { CommandMenuContextProviderContent } from '@/command-menu-item/contexts/CommandMenuContextProviderContent';
+import { CommandMenuItemContainerType } from '@/command-menu-item/types/CommandMenuItemContainerType';
+import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';
+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';
+import { EngineComponentKey } from '~/generated-metadata/graphql';
+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';
+import { mockedCommandMenuItems } from '~/testing/mock-data/generated/metadata/command-menu-items/mock-command-menu-items-data';
+
+const SharePinState = () => {
+ const { commandMenuItems } = useContext(CommandMenuContext);
+
+ return commandMenuItems.map((item) => (
+ <Badge key={item.id}>
+ {item.isPinned ? 'Pinned share' : 'Unpinned share'}
+ </Badge>
+ ));
+};
+
+const CHAT_SHARING_CONTEXT_API: CommandMenuContextApi = {
+ ...EMPTY_COMMAND_MENU_CONTEXT_API,
+ pageType: ContextStorePageType.Record,
+ numberOfSelectedRecords: 1,
+ selectedRecords: [{ id: 'chat' }],
+ objectMetadataItem: {
+ nameSingular: CoreObjectNameSingular.AgentChatThread,
+ },
+ featureFlags: { IS_AI_CHAT_INBOX_ENABLED: true },
+};
+
+const meta: Meta<typeof CommandMenuContextProviderContent> = {
+ title: 'Modules/CommandMenu/CommandMenuContextProviderContent/ChatSharing',
+ component: CommandMenuContextProviderContent,
+ decorators: [MemoryRouterDecorator],
+ args: {
+ displayType: 'button',
+ containerType: CommandMenuItemContainerType.ShowPageHeader,
+ isInPreviewMode: false,
+ commandMenuContextApi: CHAT_SHARING_CONTEXT_API,
+ children: <SharePinState />,
+ },
+ beforeEach: ({ parameters }) => {
+ jotaiStore.set(metadataStoreState.atomFamily('commandMenuItems'), {
+ current: [
+ {
+ ...mockedCommandMenuItems[0],
+ engineComponentKey: EngineComponentKey.SHARE_RECORD,
+ isPinned: false,
+ conditionalAvailabilityExpression:
+ parameters.isSharingAvailable === false ? 'false' : null,
+ conditionalPinnedExpression: null,
+ availabilityObjectMetadataId: null,
+ },
+ ],
+ draft: [],
+ status: 'up-to-date',
+ });
+ },
+};
+
+export default meta;
+
+type Story = StoryObj<typeof CommandMenuContextProviderContent>;
+
+const expectUnpinnedShare: Story['play'] = async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ expect(canvas.getByText('Unpinned share')).toBeVisible();
+ expect(canvas.queryByText('Pinned share')).not.toBeInTheDocument();
+};
+
+export const InboxHeader: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ expect(canvas.getAllByText('Pinned share')).toHaveLength(1);
+ expect(canvas.queryByText('Unpinned share')).not.toBeInTheDocument();
+ },
+};
+
+export const UnavailableSharing: Story = {
+ parameters: { isSharingAvailable: false },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ expect(canvas.queryByText('Pinned share')).not.toBeInTheDocument();
+ expect(canvas.queryByText('Unpinned share')).not.toBeInTheDocument();
+ },
+};
+
+export const CompanyHeader: Story = {
+ args: {
+ commandMenuContextApi: {
+ ...CHAT_SHARING_CONTEXT_API,
+ objectMetadataItem: { nameSingular: CoreObjectNameSingular.Company },
+ },
+ },
+ play: expectUnpinnedShare,
+};
+
+export const SidePanelFooter: Story = {
+ args: { containerType: CommandMenuItemContainerType.SidePanelFooter },
+ play: expectUnpinnedShare,
+};
+
+export const CommandMenuList: Story = {
+ args: { containerType: CommandMenuItemContainerType.CommandMenuList },
+ play: expectUnpinnedShare,
+};
+
+export const InboxDisabled: Story = {
+ args: {
+ commandMenuContextApi: {
+ ...CHAT_SHARING_CONTEXT_API,
+ featureFlags: { IS_AI_CHAT_INBOX_ENABLED: false },
+ },
+ },
+ play: expectUnpinnedShare,
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingAccessLevelOptions.tsx b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingAccessLevelOptions.tsx
index c17326c2f2d..380148ac57d 100644
--- a/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingAccessLevelOptions.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingAccessLevelOptions.tsx
@@ -1,14 +1,29 @@
import { useLingui } from '@lingui/react/macro';
import { Dropdown } from 'twenty-ui/components/navigation';
+import {
+ IconEye,
+ IconKey,
+ IconLock,
+ IconPencil,
+ IconTrash,
+} from 'twenty-ui/icon';
import { RECORD_SHARE_ACCESS_LEVEL_OPTIONS } from '@/object-record/record-sharing/constants/RecordShareAccessLevelOptions';
-import { type RecordShareAccessLevel } from '~/generated-metadata/graphql';
+import { RecordShareAccessLevel } from '~/generated-metadata/graphql';
+
+const ACCESS_LEVEL_ICONS = {
+ [RecordShareAccessLevel.NONE]: IconLock,
+ [RecordShareAccessLevel.READ]: IconEye,
+ [RecordShareAccessLevel.READ_WRITE]: IconPencil,
+ [RecordShareAccessLevel.FULL]: IconKey,
+};
type RecordSharingAccessLevelOptionsProps = {
value: RecordShareAccessLevel;
onChange: (value: RecordShareAccessLevel) => void;
onRemove?: () => void;
closeOnSelect?: boolean;
+ shouldExcludeFullAccess?: boolean;
};
export const RecordSharingAccessLevelOptions = ({
@@ -16,28 +31,42 @@ export const RecordSharingAccessLevelOptions = ({
onChange,
onRemove,
closeOnSelect,
+ shouldExcludeFullAccess = false,
}: RecordSharingAccessLevelOptionsProps) => {
const { t } = useLingui();
+ const options = RECORD_SHARE_ACCESS_LEVEL_OPTIONS.filter(
+ (option) =>
+ !shouldExcludeFullAccess || option.value !== RecordShareAccessLevel.FULL,
+ );
return (
<>
<Dropdown.Section>
- {RECORD_SHARE_ACCESS_LEVEL_OPTIONS.map((option) => (
- <Dropdown.OptionItem
- key={option.value}
- selected={option.value === value}
- closeOnSelect={closeOnSelect}
- onSelect={() => onChange(option.value)}
- >
- {t(option.label)}
- </Dropdown.OptionItem>
- ))}
+ {options.map((option) => {
+ const Icon = ACCESS_LEVEL_ICONS[option.value];
+
+ return (
+ <Dropdown.OptionItem
+ key={option.value}
+ startIcon={<Icon />}
+ selected={option.value === value}
+ closeOnSelect={closeOnSelect}
+ onSelect={() => onChange(option.value)}
+ >
+ {t(option.label)}
+ </Dropdown.OptionItem>
+ );
+ })}
</Dropdown.Section>
{onRemove && (
<>
<Dropdown.Separator />
<Dropdown.Section>
- <Dropdown.ActionItem color="danger" onClick={onRemove}>
+ <Dropdown.ActionItem
+ startIcon={<IconTrash />}
+ color="danger"
+ onClick={onRemove}
+ >
{t`Remove access`}
</Dropdown.ActionItem>
</Dropdown.Section>
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingAccessSelect.tsx b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingAccessSelect.tsx
deleted file mode 100644
index 70585451e4b..00000000000
--- a/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingAccessSelect.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { useLingui } from '@lingui/react/macro';
-import { type ReactElement } from 'react';
-import { Dropdown } from 'twenty-ui/components/navigation';
-
-import { RecordSharingAccessLevelOptions } from '@/object-record/record-sharing/components/RecordSharingAccessLevelOptions';
-import { RECORD_SHARE_ACCESS_LEVEL_OPTIONS } from '@/object-record/record-sharing/constants/RecordShareAccessLevelOptions';
-import { type RecordShareAccessLevel } from '~/generated-metadata/graphql';
-
-type RecordSharingAccessSelectProps = {
- label: string;
- text: string;
- startIcon?: ReactElement;
- value: RecordShareAccessLevel;
- disabled?: boolean;
- onChange: (value: RecordShareAccessLevel) => void;
- closeOnSelect?: boolean;
-};
-
-export const RecordSharingAccessSelect = ({
- label,
- text,
- startIcon,
- value,
- disabled,
- onChange,
- closeOnSelect,
-}: RecordSharingAccessSelectProps) => {
- const { t } = useLingui();
- const selectedOption = RECORD_SHARE_ACCESS_LEVEL_OPTIONS.find(
- (option) => option.value === value,
- );
-
- return (
- <Dropdown.Submenu>
- <Dropdown.SubmenuTrigger
- aria-label={label}
- startIcon={startIcon}
- description={selectedOption ? t(selectedOption.label) : undefined}
- disabled={disabled}
- >
- {text}
- </Dropdown.SubmenuTrigger>
- <Dropdown.Content aria-label={label}>
- <RecordSharingAccessLevelOptions
- value={value}
- onChange={onChange}
- closeOnSelect={closeOnSelect}
- />
- </Dropdown.Content>
- </Dropdown.Submenu>
- );
-};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingInvitation.tsx b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingInvitation.tsx
new file mode 100644
index 00000000000..0f920c64bd0
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingInvitation.tsx
@@ -0,0 +1,91 @@
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { type Ref } from 'react';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+import { Button, Input } from 'twenty-ui/primitives/input';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { type RecordSharingInvitationRecipient } from '@/object-record/record-sharing/types/RecordSharingInvitationRecipient';
+
+const StyledHeader = styled.div`
+ align-items: center;
+ border-bottom: 1px solid ${themeCssVariables.border.color.light};
+ box-sizing: border-box;
+ display: flex;
+ flex-shrink: 0;
+ gap: ${themeCssVariables.spacing[1]};
+ height: ${themeCssVariables.spacing[10]};
+ padding: 0 ${themeCssVariables.spacing[3]};
+`;
+
+const StyledSearch = styled.div`
+ flex: 1;
+ min-width: 0;
+`;
+
+const StyledError = styled.div`
+ color: ${themeCssVariables.color.red};
+ font-size: ${themeCssVariables.font.size.sm};
+ padding: ${themeCssVariables.spacing[2]} ${themeCssVariables.spacing[3]};
+`;
+
+type RecordSharingInvitationProps = {
+ searchInputRef?: Ref<HTMLInputElement>;
+ search: string;
+ selectedRecipients: RecordSharingInvitationRecipient[];
+ hasInvalidAccessLevel: boolean;
+ canInvite: boolean;
+ isSubmitting?: boolean;
+ onSearchChange: (search: string) => void;
+ onInvite: () => void;
+};
+
+export const RecordSharingInvitation = ({
+ searchInputRef,
+ search,
+ selectedRecipients,
+ hasInvalidAccessLevel,
+ canInvite,
+ isSubmitting = false,
+ onSearchChange,
+ onInvite,
+}: RecordSharingInvitationProps) => {
+ const { t } = useLingui();
+ const isDisabled = !canInvite || isSubmitting;
+ const hasSelection = isNonEmptyArray(selectedRecipients);
+ const selectedRecipientCount = selectedRecipients.length;
+
+ return (
+ <div aria-busy={isSubmitting}>
+ <StyledHeader>
+ <StyledSearch>
+ <Input
+ ref={searchInputRef}
+ role="searchbox"
+ aria-label={t`Add people or everyone`}
+ placeholder={t`Add people or everyone`}
+ value={search}
+ variant="plain"
+ disabled={isDisabled}
+ onValueChange={onSearchChange}
+ />
+ </StyledSearch>
+ <Button
+ size="sm"
+ variant="solid"
+ color="accent"
+ disabled={isDisabled || !hasSelection || hasInvalidAccessLevel}
+ loading={isSubmitting}
+ onClick={onInvite}
+ >
+ {hasSelection ? t`Invite ${selectedRecipientCount}` : t`Invite`}
+ </Button>
+ </StyledHeader>
+ {hasInvalidAccessLevel && hasSelection && (
+ <StyledError role="alert">
+ {t`Choose an access level available to all selected recipients.`}
+ </StyledError>
+ )}
+ </div>
+ );
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingInvitationAccessPicker.tsx b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingInvitationAccessPicker.tsx
new file mode 100644
index 00000000000..207daacf9a1
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingInvitationAccessPicker.tsx
@@ -0,0 +1,70 @@
+import { useLingui } from '@lingui/react/macro';
+import { useId } from 'react';
+import { Dropdown, ListItemButton } from 'twenty-ui/components/navigation';
+import { IconChevronRight, IconUserPlus } from 'twenty-ui/icon';
+import { useTheme } from 'twenty-ui/theme';
+
+import { RecordSharingAccessLevelOptions } from '@/object-record/record-sharing/components/RecordSharingAccessLevelOptions';
+import { RECORD_SHARING_ACCESS_MENU_SIDE_OFFSET_IN_PX } from '@/object-record/record-sharing/constants/RecordSharingAccessMenuSideOffsetInPx';
+import { getRecordShareAccessLevelLabel } from '@/object-record/record-sharing/utils/getRecordShareAccessLevelLabel';
+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
+import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
+import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';
+import { ListItemIconContainer } from '@/ui/navigation/list-item/components/ListItemIconContainer';
+import { type RecordShareAccessLevel } from '~/generated-metadata/graphql';
+
+type RecordSharingInvitationAccessPickerProps = {
+ value: RecordShareAccessLevel;
+ hasEveryoneRecipient: boolean;
+ disabled: boolean;
+ onChange: (value: RecordShareAccessLevel) => void;
+};
+
+export const RecordSharingInvitationAccessPicker = ({
+ value,
+ hasEveryoneRecipient,
+ disabled,
+ onChange,
+}: RecordSharingInvitationAccessPickerProps) => {
+ const { t } = useLingui();
+ const theme = useTheme();
+ const dropdownId = useId();
+
+ return (
+ <DropdownRoot dropdownId={dropdownId} type="menu">
+ <Dropdown.Trigger
+ disabled={disabled}
+ aria-label={t`Invite as ${getRecordShareAccessLevelLabel(value)}`}
+ render={
+ <ListItemButton
+ startIcon={
+ <ListItemIconContainer>
+ <IconUserPlus
+ size={theme.icon.size.md}
+ stroke={theme.icon.stroke.sm}
+ />
+ </ListItemIconContainer>
+ }
+ description={getRecordShareAccessLevelLabel(value)}
+ descriptionPlacement="end"
+ endIcon={<IconChevronRight />}
+ >
+ {t`Invite as`}
+ </ListItemButton>
+ }
+ />
+ <DropdownContent
+ aria-label={t`Invitation access`}
+ align="end"
+ sideOffset={RECORD_SHARING_ACCESS_MENU_SIDE_OFFSET_IN_PX}
+ width={GenericDropdownContentWidth.Narrow}
+ >
+ <RecordSharingAccessLevelOptions
+ value={value}
+ onChange={onChange}
+ shouldExcludeFullAccess={hasEveryoneRecipient}
+ />
+ </DropdownContent>
+ </DropdownRoot>
+ );
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingInvitationRecipientIcon.tsx b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingInvitationRecipientIcon.tsx
new file mode 100644
index 00000000000..33ff05b577c
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingInvitationRecipientIcon.tsx
@@ -0,0 +1,38 @@
+import { IconLock, IconUsers } from 'twenty-ui/icon';
+import { Avatar } from 'twenty-ui/primitives/data-display';
+import { useTheme } from 'twenty-ui/theme';
+
+import { type RecordSharingInvitationRecipient } from '@/object-record/record-sharing/types/RecordSharingInvitationRecipient';
+import { ListItemIconContainer } from '@/ui/navigation/list-item/components/ListItemIconContainer';
+
+type RecordSharingInvitationRecipientIconProps = {
+ recipient: RecordSharingInvitationRecipient;
+};
+
+export const RecordSharingInvitationRecipientIcon = ({
+ recipient,
+}: RecordSharingInvitationRecipientIconProps) => {
+ const theme = useTheme();
+
+ if (recipient.kind === 'workspaceMember') {
+ return (
+ <ListItemIconContainer>
+ <Avatar
+ name={recipient.label}
+ src={recipient.avatarUrl}
+ colorSeed={recipient.id}
+ size="md"
+ shape="circle"
+ />
+ </ListItemIconContainer>
+ );
+ }
+
+ const Icon = recipient.kind === 'role' ? IconLock : IconUsers;
+
+ return (
+ <ListItemIconContainer>
+ <Icon size={theme.icon.size.md} stroke={theme.icon.stroke.sm} />
+ </ListItemIconContainer>
+ );
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingInvitationRecipientPicker.tsx b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingInvitationRecipientPicker.tsx
new file mode 100644
index 00000000000..f9d59cb7a20
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingInvitationRecipientPicker.tsx
@@ -0,0 +1,111 @@
+import { styled } from '@linaria/react';
+import { isNonEmptyString } from '@sniptt/guards';
+import { useId } from 'react';
+import { Checkbox } from 'twenty-ui/primitives/input';
+import { ListItem } from 'twenty-ui/primitives/navigation';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { RecordSharingInvitationRecipientIcon } from '@/object-record/record-sharing/components/RecordSharingInvitationRecipientIcon';
+import { type RecordSharingInvitationRecipient } from '@/object-record/record-sharing/types/RecordSharingInvitationRecipient';
+import { isSameRecordSharingInvitationRecipient } from '@/object-record/record-sharing/utils/isSameRecordSharingInvitationRecipient';
+
+const StyledContent = styled.span`
+ align-items: baseline;
+ display: flex;
+ gap: ${themeCssVariables.spacing[1]};
+ min-width: 0;
+`;
+
+const StyledLabel = styled.span`
+ flex-shrink: 0;
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+`;
+
+const StyledDescription = styled.span`
+ color: ${themeCssVariables.font.color.light};
+ overflow: hidden;
+ text-overflow: ellipsis;
+`;
+
+const StyledSeparator = styled.span`
+ color: ${themeCssVariables.font.color.light};
+ flex-shrink: 0;
+`;
+
+type RecordSharingInvitationRecipientPickerProps = {
+ recipients: RecordSharingInvitationRecipient[];
+ selectedRecipients: RecordSharingInvitationRecipient[];
+ disabled: boolean;
+ onRecipientsChange: (recipients: RecordSharingInvitationRecipient[]) => void;
+};
+
+export const RecordSharingInvitationRecipientPicker = ({
+ recipients,
+ selectedRecipients,
+ disabled,
+ onRecipientsChange,
+}: RecordSharingInvitationRecipientPickerProps) => {
+ const pickerId = useId();
+ const isSelected = (recipient: RecordSharingInvitationRecipient) =>
+ selectedRecipients.some((selectedRecipient) =>
+ isSameRecordSharingInvitationRecipient({
+ recipient,
+ otherRecipient: selectedRecipient,
+ }),
+ );
+
+ return (
+ <>
+ {recipients.map((recipient) => {
+ const checkboxId = `${pickerId}-${recipient.kind}-${recipient.id}`;
+
+ return (
+ <ListItem
+ key={`${recipient.kind}-${recipient.id}`}
+ disabled={disabled}
+ render={<label htmlFor={checkboxId} />}
+ startIcon={
+ <RecordSharingInvitationRecipientIcon recipient={recipient} />
+ }
+ endIcon={
+ <Checkbox
+ id={checkboxId}
+ aria-label={recipient.label}
+ checked={isSelected(recipient)}
+ disabled={disabled}
+ onCheckedChange={(checked) => {
+ if (!checked) {
+ onRecipientsChange(
+ selectedRecipients.filter(
+ (selectedRecipient) =>
+ !isSameRecordSharingInvitationRecipient({
+ recipient,
+ otherRecipient: selectedRecipient,
+ }),
+ ),
+ );
+ return;
+ }
+
+ onRecipientsChange([...selectedRecipients, recipient]);
+ }}
+ />
+ }
+ >
+ <StyledContent>
+ <StyledLabel>{recipient.label}</StyledLabel>
+ {isNonEmptyString(recipient.description) && (
+ <>
+ <StyledSeparator>·</StyledSeparator>
+ <StyledDescription>{recipient.description}</StyledDescription>
+ </>
+ )}
+ </StyledContent>
+ </ListItem>
+ );
+ })}
+ </>
+ );
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/components/__stories__/RecordSharingInvitation.stories.tsx b/packages/twenty-front/src/modules/object-record/record-sharing/components/__stories__/RecordSharingInvitation.stories.tsx
new file mode 100644
index 00000000000..7b580ff64c4
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/components/__stories__/RecordSharingInvitation.stories.tsx
@@ -0,0 +1,134 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { type ComponentProps, useState } from 'react';
+import { expect, fn, userEvent, within } from 'storybook/test';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+import { RecordSharingInvitation } from '@/object-record/record-sharing/components/RecordSharingInvitation';
+import { type RecordSharingInvitationRecipient } from '@/object-record/record-sharing/types/RecordSharingInvitationRecipient';
+
+const RECIPIENTS: RecordSharingInvitationRecipient[] = [
+ { kind: 'workspaceMember', id: 'sarah', label: 'Sarah Lin' },
+ { kind: 'workspaceMember', id: 'marco', label: 'Marco Rossi' },
+ { kind: 'role', id: 'sales', label: 'Sales' },
+ { kind: 'everyone', id: 'workspace', label: 'Everyone with access to Chats' },
+];
+
+const InvitationStory = ({
+ selectedRecipients,
+ hasInvalidAccessLevel,
+ canInvite,
+ isSubmitting,
+ search: initialSearch,
+ onSearchChange,
+ onInvite,
+}: ComponentProps<typeof RecordSharingInvitation>) => {
+ const [search, setSearch] = useState(initialSearch);
+
+ return (
+ <RecordSharingInvitation
+ selectedRecipients={selectedRecipients}
+ hasInvalidAccessLevel={hasInvalidAccessLevel}
+ canInvite={canInvite}
+ isSubmitting={isSubmitting}
+ search={search}
+ onSearchChange={(nextSearch) => {
+ setSearch(nextSearch);
+ onSearchChange(nextSearch);
+ }}
+ onInvite={onInvite}
+ />
+ );
+};
+
+const meta = {
+ title: 'Modules/ObjectRecord/RecordSharing/RecordSharingInvitation',
+ component: RecordSharingInvitation,
+ render: InvitationStory,
+ decorators: [ComponentDecorator],
+ parameters: { container: { width: 400 } },
+ args: {
+ search: '',
+ selectedRecipients: [],
+ hasInvalidAccessLevel: false,
+ canInvite: true,
+ onSearchChange: fn(),
+ onInvite: fn(),
+ },
+} satisfies Meta<typeof RecordSharingInvitation>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const Empty: Story = {
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const input = canvas.getByPlaceholderText('Add people or everyone');
+
+ await expect(canvas.getByRole('button', { name: 'Invite' })).toBeDisabled();
+ await userEvent.type(input, 'Sarah');
+ await expect(input).toHaveValue('Sarah');
+ await expect(args.onSearchChange).toHaveBeenLastCalledWith('Sarah');
+ await expect(args.onInvite).not.toHaveBeenCalled();
+ },
+};
+
+export const StageAndInvite: Story = {
+ args: { selectedRecipients: [RECIPIENTS[0], RECIPIENTS[2]] },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+
+ await userEvent.click(canvas.getByRole('button', { name: 'Invite 2' }));
+ await expect(args.onInvite).toHaveBeenCalledTimes(1);
+ },
+};
+
+export const Submitting: Story = {
+ args: { selectedRecipients: [RECIPIENTS[0]], isSubmitting: true },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+
+ await expect(
+ canvas.getByRole('button', { name: 'Invite 1' }),
+ ).toBeDisabled();
+ await expect(
+ canvas.getByPlaceholderText('Add people or everyone'),
+ ).toBeDisabled();
+ await expect(args.onInvite).not.toHaveBeenCalled();
+ },
+};
+
+export const ReadOnly: Story = {
+ args: { selectedRecipients: [RECIPIENTS[0]], canInvite: false },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+
+ await expect(
+ canvas.getByRole('button', { name: 'Invite 1' }),
+ ).toBeDisabled();
+ await expect(
+ canvas.getByPlaceholderText('Add people or everyone'),
+ ).toBeDisabled();
+ await userEvent.click(canvas.getByRole('button', { name: 'Invite 1' }));
+ await expect(args.onInvite).not.toHaveBeenCalled();
+ await expect(args.onSearchChange).not.toHaveBeenCalled();
+ },
+};
+
+export const EveryoneCannotReceiveFullAccess: Story = {
+ args: {
+ selectedRecipients: [RECIPIENTS[3]],
+ hasInvalidAccessLevel: true,
+ },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+
+ await expect(
+ canvas.getByRole('button', { name: 'Invite 1' }),
+ ).toBeDisabled();
+ await expect(canvas.getByRole('alert')).toHaveTextContent(
+ 'Choose an access level available to all selected recipients.',
+ );
+ await userEvent.click(canvas.getByRole('button', { name: 'Invite 1' }));
+ await expect(args.onInvite).not.toHaveBeenCalled();
+ },
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/constants/RecordSharingAccessMenuSideOffsetInPx.ts b/packages/twenty-front/src/modules/object-record/record-sharing/constants/RecordSharingAccessMenuSideOffsetInPx.ts
new file mode 100644
index 00000000000..8b3c86ef02b
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/constants/RecordSharingAccessMenuSideOffsetInPx.ts
@@ -0,0 +1 @@
+export const RECORD_SHARING_ACCESS_MENU_SIDE_OFFSET_IN_PX = 4;
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/hooks/__tests__/useRecordSharing.test.tsx b/packages/twenty-front/src/modules/object-record/record-sharing/hooks/__tests__/useRecordSharing.test.tsx
index 0695b189991..41423b22aec 100644
--- a/packages/twenty-front/src/modules/object-record/record-sharing/hooks/__tests__/useRecordSharing.test.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/hooks/__tests__/useRecordSharing.test.tsx
@@ -135,10 +135,12 @@ describe('useRecordSharing', () => {
expect(result.current.sharing?.canManageSharing).toBe(true),
);
await act(async () => {
- await result.current.setShare({
- principal: { workspaceMemberId: 'member' },
- accessLevel: RecordShareAccessLevel.READ,
- });
+ await expect(
+ result.current.setShare({
+ principal: { workspaceMemberId: 'member' },
+ accessLevel: RecordShareAccessLevel.READ,
+ }),
+ ).resolves.toEqual(SHARED_WITH_MEMBER);
});
expect(request.mock.calls.map(([operationName]) => operationName)).toEqual([
'GetRecordSharing',
@@ -163,7 +165,9 @@ describe('useRecordSharing', () => {
expect(result.current.sharing?.canManageSharing).toBe(true),
);
await act(async () => {
- await result.current.setGeneralAccess(RecordShareAccessLevel.READ);
+ await expect(
+ result.current.setGeneralAccess(RecordShareAccessLevel.READ),
+ ).resolves.toEqual(OPEN_TO_VIEWERS);
});
expect(request).toHaveBeenLastCalledWith('SetRecordGeneralAccess', {
target: RECORD_TARGET,
@@ -181,9 +185,11 @@ describe('useRecordSharing', () => {
});
expect(result.current.sharing?.shares).toHaveLength(1);
await act(async () => {
- await result.current.removeShare({
- principal: { workspaceMemberId: 'member' },
- });
+ await expect(
+ result.current.removeShare({
+ principal: { workspaceMemberId: 'member' },
+ }),
+ ).resolves.toEqual(SHARING);
});
expect(request).toHaveBeenLastCalledWith('RemoveRecordShare', {
target: RECORD_TARGET,
@@ -233,10 +239,12 @@ describe('useRecordSharing', () => {
throw new Error('Save failed');
});
await act(async () => {
- await result.current.setShare({
- principal: { workspaceMemberId: 'member' },
- accessLevel: RecordShareAccessLevel.READ,
- });
+ await expect(
+ result.current.setShare({
+ principal: { workspaceMemberId: 'member' },
+ accessLevel: RecordShareAccessLevel.READ,
+ }),
+ ).resolves.toBeUndefined();
});
expect(result.current.sharing?.shares).toEqual([]);
expect(readStoredPermissions()).toBeUndefined();
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/hooks/useRecordSharing.ts b/packages/twenty-front/src/modules/object-record/record-sharing/hooks/useRecordSharing.ts
index dce7126162b..8cd3deeb38f 100644
--- a/packages/twenty-front/src/modules/object-record/record-sharing/hooks/useRecordSharing.ts
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/hooks/useRecordSharing.ts
@@ -70,8 +70,12 @@ export const useRecordSharing = ({
if (isDefined(sharing)) {
setRecordPermissions(recordTarget, sharing.permissions);
}
+
+ return sharing;
} catch (mutationError) {
enqueueToast(getToastOptionsFromError({ error: mutationError }));
+
+ return undefined;
}
};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/types/RecordSharingInvitationRecipient.ts b/packages/twenty-front/src/modules/object-record/record-sharing/types/RecordSharingInvitationRecipient.ts
new file mode 100644
index 00000000000..c006f1c808a
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/types/RecordSharingInvitationRecipient.ts
@@ -0,0 +1,9 @@
+export type RecordSharingInvitationRecipient = {
+ id: string;
+ label: string;
+ description?: string;
+} & (
+ | { kind: 'workspaceMember'; avatarUrl?: string | null }
+ | { kind: 'role' }
+ | { kind: 'everyone' }
+);
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/utils/__tests__/getRecordSharingGeneralAccess.test.ts b/packages/twenty-front/src/modules/object-record/record-sharing/utils/__tests__/getRecordSharingGeneralAccess.test.ts
new file mode 100644
index 00000000000..a7cb8e721fb
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/utils/__tests__/getRecordSharingGeneralAccess.test.ts
@@ -0,0 +1,50 @@
+import { i18n } from '@lingui/core';
+
+import { getRecordSharingGeneralAccess } from '@/object-record/record-sharing/utils/getRecordSharingGeneralAccess';
+import { RecordShareAccessLevel } from '~/generated-metadata/graphql';
+
+describe('getRecordSharingGeneralAccess', () => {
+ it('includes application-managed access without an explicit workspace grant', () => {
+ const generalAccess = getRecordSharingGeneralAccess({
+ sharing: {
+ generalAccessLevel: RecordShareAccessLevel.NONE,
+ hasManagedGeneralAccess: true,
+ },
+ objectLabelPlural: 'Companies',
+ });
+
+ expect(generalAccess.hasGeneralAccess).toBe(true);
+ expect(i18n._(generalAccess.label)).toBe(
+ 'Everyone with access to Companies',
+ );
+ });
+
+ it('includes an explicit workspace grant without application-managed access', () => {
+ expect(
+ getRecordSharingGeneralAccess({
+ sharing: {
+ generalAccessLevel: RecordShareAccessLevel.READ,
+ hasManagedGeneralAccess: false,
+ },
+ objectLabelPlural: 'Companies',
+ }).hasGeneralAccess,
+ ).toBe(true);
+ });
+
+ it('keeps restricted and unknown sharing without general access', () => {
+ for (const sharing of [
+ undefined,
+ {
+ generalAccessLevel: RecordShareAccessLevel.NONE,
+ hasManagedGeneralAccess: false,
+ },
+ ]) {
+ expect(
+ getRecordSharingGeneralAccess({
+ sharing,
+ objectLabelPlural: 'Companies',
+ }).hasGeneralAccess,
+ ).toBe(false);
+ }
+ });
+});
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/utils/__tests__/getRecordSharingInvitationRecipients.test.ts b/packages/twenty-front/src/modules/object-record/record-sharing/utils/__tests__/getRecordSharingInvitationRecipients.test.ts
new file mode 100644
index 00000000000..fcec0c47852
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/utils/__tests__/getRecordSharingInvitationRecipients.test.ts
@@ -0,0 +1,73 @@
+import { getRecordSharingInvitationRecipients } from '@/object-record/record-sharing/utils/getRecordSharingInvitationRecipients';
+import { type PartialWorkspaceMember } from '@/settings/roles/types/RoleWithPartialMembers';
+import {
+ RecordShareAccessLevel,
+ RecordSharePrincipalType,
+ RecordShareRowCause,
+} from '~/generated-metadata/graphql';
+
+const MEMBER: PartialWorkspaceMember = {
+ id: 'member',
+ userId: 'user',
+ name: { firstName: 'Sarah', lastName: 'Lin' },
+ userEmail: '[email protected]',
+};
+
+describe('getRecordSharingInvitationRecipients', () => {
+ it('excludes existing grants by principal type when role and member IDs overlap', () => {
+ const recipients = getRecordSharingInvitationRecipients({
+ workspaceMembers: [MEMBER, { ...MEMBER, id: 'role' }],
+ shares: [
+ {
+ id: 'member-share',
+ principalId: MEMBER.id,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ accessLevel: RecordShareAccessLevel.READ,
+ rowCause: RecordShareRowCause.MANUAL,
+ },
+ {
+ id: 'role-share',
+ principalId: 'role',
+ principalType: RecordSharePrincipalType.ROLE,
+ accessLevel: RecordShareAccessLevel.READ,
+ rowCause: RecordShareRowCause.MANUAL,
+ },
+ ],
+ roles: [
+ { id: MEMBER.id, label: 'Sales' },
+ { id: 'role', label: 'Support' },
+ ],
+ roleLabel: 'Role',
+ });
+
+ expect(recipients).toEqual([
+ expect.objectContaining({ kind: 'workspaceMember', id: 'role' }),
+ { kind: 'role', id: MEMBER.id, label: 'Sales', description: 'Role' },
+ ]);
+ });
+
+ it('shows the email once and keeps the avatar when a member has no display name', () => {
+ expect(
+ getRecordSharingInvitationRecipients({
+ workspaceMembers: [
+ {
+ ...MEMBER,
+ name: { firstName: '', lastName: '' },
+ avatarUrl: 'https://example.com/avatar.png',
+ },
+ ],
+ shares: [],
+ roles: [],
+ roleLabel: 'Role',
+ }),
+ ).toEqual([
+ {
+ kind: 'workspaceMember',
+ id: MEMBER.id,
+ label: MEMBER.userEmail,
+ description: undefined,
+ avatarUrl: 'https://example.com/avatar.png',
+ },
+ ]);
+ });
+});
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/utils/__tests__/getRecordSharingSearchResults.test.ts b/packages/twenty-front/src/modules/object-record/record-sharing/utils/__tests__/getRecordSharingSearchResults.test.ts
new file mode 100644
index 00000000000..cc96bc09cfb
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/utils/__tests__/getRecordSharingSearchResults.test.ts
@@ -0,0 +1,234 @@
+import { type RecordSharingInvitationRecipient } from '@/object-record/record-sharing/types/RecordSharingInvitationRecipient';
+import { getRecordSharingSearchResults } from '@/object-record/record-sharing/utils/getRecordSharingSearchResults';
+import { type PartialWorkspaceMember } from '@/settings/roles/types/RoleWithPartialMembers';
+import {
+ RecordShareAccessLevel,
+ RecordSharePrincipalType,
+ RecordShareRowCause,
+ type RecordSharingFieldsFragment,
+} from '~/generated-metadata/graphql';
+
+const MEMBER: PartialWorkspaceMember = {
+ id: 'member',
+ userId: 'user',
+ name: { firstName: 'Sarah', lastName: 'Lin' },
+ userEmail: '[email protected]',
+};
+
+const MEMBER_SHARE: RecordSharingFieldsFragment['shares'][number] = {
+ id: 'member-share',
+ principalId: MEMBER.id,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ accessLevel: RecordShareAccessLevel.READ,
+ rowCause: RecordShareRowCause.MANUAL,
+};
+
+const SELECTED_RECIPIENT: RecordSharingInvitationRecipient = {
+ kind: 'workspaceMember',
+ id: MEMBER.id,
+ label: 'Sarah Lin',
+ description: '[email protected]',
+};
+
+const getSearchResults = (
+ overrides: Partial<Parameters<typeof getRecordSharingSearchResults>[0]> = {},
+) =>
+ getRecordSharingSearchResults({
+ search: '',
+ sharing: { shares: [], roles: [] },
+ workspaceMembers: [],
+ currentWorkspaceMember: null,
+ recipients: [],
+ selectedRecipients: [],
+ generalAccess: {
+ hasGeneralAccess: true,
+ label: 'Everyone with access to Companies',
+ workspaceName: 'Apple',
+ },
+ ...overrides,
+ });
+
+describe('getRecordSharingSearchResults', () => {
+ it('keeps recipient order when an access update returns grants in a different order', () => {
+ const otherMember: PartialWorkspaceMember = {
+ ...MEMBER,
+ id: 'other-member',
+ name: { firstName: 'David', lastName: 'Phillips' },
+ };
+ const otherShare = {
+ ...MEMBER_SHARE,
+ id: 'other-share',
+ principalId: otherMember.id,
+ };
+ const initialResults = getSearchResults({
+ workspaceMembers: [MEMBER, otherMember],
+ sharing: { shares: [MEMBER_SHARE, otherShare], roles: [] },
+ });
+ const updatedResults = getSearchResults({
+ workspaceMembers: [MEMBER, otherMember],
+ sharing: {
+ shares: [
+ otherShare,
+ {
+ ...MEMBER_SHARE,
+ id: 'replacement-member-share',
+ accessLevel: RecordShareAccessLevel.READ_WRITE,
+ },
+ ],
+ roles: [],
+ },
+ });
+
+ expect(
+ updatedResults.matchingShares.map(({ share }) => share.principalId),
+ ).toEqual(
+ initialResults.matchingShares.map(({ share }) => share.principalId),
+ );
+ });
+
+ it('lists the owner and current member before other recipients in alphabetical order', () => {
+ const results = getSearchResults({
+ currentWorkspaceMember: { ...MEMBER, colorScheme: 'Light', locale: 'en' },
+ workspaceMembers: [
+ MEMBER,
+ {
+ ...MEMBER,
+ id: 'david',
+ name: { firstName: 'David', lastName: 'Phillips' },
+ },
+ {
+ ...MEMBER,
+ id: 'alice',
+ name: { firstName: 'Alice', lastName: 'Smith' },
+ },
+ ],
+ sharing: {
+ shares: [
+ { ...MEMBER_SHARE, id: 'david-share', principalId: 'david' },
+ MEMBER_SHARE,
+ { ...MEMBER_SHARE, id: 'alice-share', principalId: 'alice' },
+ {
+ ...MEMBER_SHARE,
+ id: 'owner-share',
+ principalId: 'owner',
+ rowCause: RecordShareRowCause.OWNER,
+ },
+ ],
+ roles: [],
+ },
+ });
+
+ expect(
+ results.matchingShares.map(({ share }) => share.principalId),
+ ).toEqual(['owner', MEMBER.id, 'alice', 'david']);
+ });
+
+ it('keeps recipients with identical names in a stable order', () => {
+ const results = getSearchResults({
+ workspaceMembers: [MEMBER, { ...MEMBER, id: 'other-member' }],
+ sharing: {
+ shares: [
+ {
+ ...MEMBER_SHARE,
+ id: 'first-grant',
+ principalId: 'other-member',
+ },
+ { ...MEMBER_SHARE, id: 'replacement-grant' },
+ ],
+ roles: [],
+ },
+ });
+
+ expect(
+ results.matchingShares.map(({ share }) => share.principalId),
+ ).toEqual([MEMBER.id, 'other-member']);
+ });
+
+ it('matches the current member email without confusing a role with the same ID', () => {
+ const results = getSearchResults({
+ search: ' [email protected] ',
+ workspaceMembers: [MEMBER],
+ currentWorkspaceMember: { ...MEMBER, colorScheme: 'Light', locale: 'en' },
+ sharing: {
+ shares: [
+ MEMBER_SHARE,
+ {
+ ...MEMBER_SHARE,
+ id: 'role-share',
+ principalType: RecordSharePrincipalType.ROLE,
+ },
+ ],
+ roles: [{ id: MEMBER.id, label: 'Sales' }],
+ },
+ });
+
+ expect(results.matchingShares).toEqual([
+ { share: MEMBER_SHARE, label: 'You', member: MEMBER },
+ ]);
+ });
+
+ it('matches the current member by full name even though their label is You', () => {
+ const results = getSearchResults({
+ search: 'sarah lin',
+ workspaceMembers: [MEMBER],
+ currentWorkspaceMember: { ...MEMBER, colorScheme: 'Light', locale: 'en' },
+ sharing: { shares: [MEMBER_SHARE], roles: [] },
+ });
+
+ expect(results.matchingShares).toEqual([
+ { share: MEMBER_SHARE, label: 'You', member: MEMBER },
+ ]);
+ });
+
+ it('matches labels and email descriptions while excluding only the selected principal', () => {
+ const roleRecipient: RecordSharingInvitationRecipient = {
+ kind: 'role',
+ id: MEMBER.id,
+ label: 'Sales',
+ };
+ const otherMemberRecipient: RecordSharingInvitationRecipient = {
+ kind: 'workspaceMember',
+ id: 'other-member',
+ label: 'Marco Rossi',
+ description: '[email protected]',
+ };
+ const results = getSearchResults({
+ search: ' SALES ',
+ recipients: [SELECTED_RECIPIENT, roleRecipient, otherMemberRecipient],
+ selectedRecipients: [SELECTED_RECIPIENT],
+ });
+
+ expect(results.matchingRecipients).toEqual([
+ roleRecipient,
+ otherMemberRecipient,
+ ]);
+ });
+
+ it('matches general access by workspace name while searching', () => {
+ expect(getSearchResults({ search: ' APPLE ' })).toEqual({
+ matchingShares: [],
+ matchingRecipients: [],
+ matchesGeneralAccess: true,
+ isInviting: true,
+ hasSelection: false,
+ });
+ });
+
+ it('keeps the invitation state active after selecting a recipient and clearing search', () => {
+ const results = getSearchResults({
+ selectedRecipients: [SELECTED_RECIPIENT],
+ });
+
+ expect(results.hasSelection).toBe(true);
+ expect(results.isInviting).toBe(true);
+ expect(results.matchesGeneralAccess).toBe(true);
+ });
+
+ it('keeps an empty search without selection in the normal sharing view', () => {
+ const results = getSearchResults({ search: ' ' });
+
+ expect(results.hasSelection).toBe(false);
+ expect(results.isInviting).toBe(false);
+ expect(results.matchesGeneralAccess).toBe(false);
+ });
+});
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordSharingGeneralAccess.ts b/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordSharingGeneralAccess.ts
new file mode 100644
index 00000000000..30a4d69d426
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordSharingGeneralAccess.ts
@@ -0,0 +1,26 @@
+import { msg } from '@lingui/core/macro';
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ RecordShareAccessLevel,
+ type RecordSharingFieldsFragment,
+} from '~/generated-metadata/graphql';
+
+export const getRecordSharingGeneralAccess = ({
+ sharing,
+ objectLabelPlural,
+}: {
+ sharing:
+ | Pick<
+ RecordSharingFieldsFragment,
+ 'generalAccessLevel' | 'hasManagedGeneralAccess'
+ >
+ | undefined;
+ objectLabelPlural: string;
+}) => ({
+ hasGeneralAccess:
+ (sharing?.hasManagedGeneralAccess ?? false) ||
+ (isDefined(sharing?.generalAccessLevel) &&
+ sharing.generalAccessLevel !== RecordShareAccessLevel.NONE),
+ label: msg`Everyone with access to ${objectLabelPlural}`,
+});
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordSharingInvitationRecipients.ts b/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordSharingInvitationRecipients.ts
new file mode 100644
index 00000000000..07173b38fd5
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordSharingInvitationRecipients.ts
@@ -0,0 +1,68 @@
+import { type RecordSharingInvitationRecipient } from '@/object-record/record-sharing/types/RecordSharingInvitationRecipient';
+import { type PartialWorkspaceMember } from '@/settings/roles/types/RoleWithPartialMembers';
+import { getWorkspaceMemberNameOrEmail } from '@/workspace-member/utils/getWorkspaceMemberNameOrEmail';
+import {
+ RecordSharePrincipalType,
+ type RecordSharingFieldsFragment,
+} from '~/generated-metadata/graphql';
+import { getAbsoluteImageUrl } from '~/utils/image/getAbsoluteImageUrl';
+
+export const getRecordSharingInvitationRecipients = ({
+ workspaceMembers,
+ shares,
+ roles,
+ roleLabel,
+}: {
+ workspaceMembers: PartialWorkspaceMember[];
+ shares: RecordSharingFieldsFragment['shares'];
+ roles: RecordSharingFieldsFragment['roles'];
+ roleLabel: string;
+}): RecordSharingInvitationRecipient[] => {
+ const hasExistingShare = ({
+ principalId,
+ principalType,
+ }: {
+ principalId: string;
+ principalType: RecordSharePrincipalType;
+ }) =>
+ shares.some(
+ (share) =>
+ share.principalId === principalId &&
+ share.principalType === principalType,
+ );
+ const memberRecipients = workspaceMembers
+ .filter(
+ (member) =>
+ !hasExistingShare({
+ principalId: member.id,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ }),
+ )
+ .map((member): RecordSharingInvitationRecipient => {
+ const label = getWorkspaceMemberNameOrEmail(member);
+
+ return {
+ kind: 'workspaceMember',
+ id: member.id,
+ label,
+ description: label === member.userEmail ? undefined : member.userEmail,
+ avatarUrl: getAbsoluteImageUrl(member.avatarUrl),
+ };
+ });
+ const roleRecipients = roles
+ .filter(
+ (role) =>
+ !hasExistingShare({
+ principalId: role.id,
+ principalType: RecordSharePrincipalType.ROLE,
+ }),
+ )
+ .map((role): RecordSharingInvitationRecipient => ({
+ kind: 'role',
+ id: role.id,
+ label: role.label,
+ description: roleLabel,
+ }));
+
+ return [...memberRecipients, ...roleRecipients];
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordSharingRecipientGroups.ts b/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordSharingRecipientGroups.ts
new file mode 100644
index 00000000000..8f289c41c07
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordSharingRecipientGroups.ts
@@ -0,0 +1,38 @@
+import { msg } from '@lingui/core/macro';
+
+import {
+ RecordSharePrincipalType,
+ type RecordSharingFieldsFragment,
+} from '~/generated-metadata/graphql';
+
+export const getRecordSharingRecipientGroups = <
+ TMatchingShare extends {
+ share: Pick<RecordSharingFieldsFragment['shares'][number], 'principalType'>;
+ },
+>({
+ isInviting,
+ matchingShares,
+}: {
+ isInviting: boolean;
+ matchingShares: TMatchingShare[];
+}) => {
+ if (isInviting) {
+ return [{ heading: msg`Have access`, matchingShares }];
+ }
+
+ return [
+ {
+ heading: msg`Roles`,
+ matchingShares: matchingShares.filter(
+ ({ share }) => share.principalType === RecordSharePrincipalType.ROLE,
+ ),
+ },
+ {
+ heading: msg`Users`,
+ matchingShares: matchingShares.filter(
+ ({ share }) =>
+ share.principalType === RecordSharePrincipalType.WORKSPACE_MEMBER,
+ ),
+ },
+ ];
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordSharingSearchResults.ts b/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordSharingSearchResults.ts
new file mode 100644
index 00000000000..a0b7131097b
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordSharingSearchResults.ts
@@ -0,0 +1,141 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { type CurrentWorkspaceMember } from '@/auth/states/currentWorkspaceMemberState';
+import { type RecordSharingInvitationRecipient } from '@/object-record/record-sharing/types/RecordSharingInvitationRecipient';
+import { getRecordShareLabel } from '@/object-record/record-sharing/utils/getRecordShareLabel';
+import { isSameRecordSharingInvitationRecipient } from '@/object-record/record-sharing/utils/isSameRecordSharingInvitationRecipient';
+import { type PartialWorkspaceMember } from '@/settings/roles/types/RoleWithPartialMembers';
+import { getWorkspaceMemberNameOrEmail } from '@/workspace-member/utils/getWorkspaceMemberNameOrEmail';
+import {
+ RecordSharePrincipalType,
+ RecordShareRowCause,
+ type RecordSharingFieldsFragment,
+} from '~/generated-metadata/graphql';
+import { sortByAscString } from '~/utils/array/sortByAscString';
+
+const hasMatchingSearchValue = ({
+ values,
+ normalizedSearch,
+}: {
+ values: (string | null | undefined)[];
+ normalizedSearch: string;
+}) =>
+ values
+ .filter(isDefined)
+ .some((value) => value.toLowerCase().includes(normalizedSearch));
+
+export const getRecordSharingSearchResults = ({
+ search,
+ sharing,
+ workspaceMembers,
+ currentWorkspaceMember,
+ recipients,
+ selectedRecipients,
+ generalAccess,
+}: {
+ search: string;
+ sharing: Pick<RecordSharingFieldsFragment, 'shares' | 'roles'> | undefined;
+ workspaceMembers: PartialWorkspaceMember[];
+ currentWorkspaceMember: CurrentWorkspaceMember | null;
+ recipients: RecordSharingInvitationRecipient[];
+ selectedRecipients: RecordSharingInvitationRecipient[];
+ generalAccess: {
+ hasGeneralAccess: boolean;
+ label: string;
+ workspaceName: string;
+ };
+}) => {
+ const normalizedSearch = search.trim().toLowerCase();
+ const hasSelection = isNonEmptyArray(selectedRecipients);
+ const isInviting = isNonEmptyString(normalizedSearch) || hasSelection;
+ const matchingShares = (sharing?.shares ?? [])
+ .flatMap((share) => {
+ const member =
+ share.principalType === RecordSharePrincipalType.WORKSPACE_MEMBER
+ ? workspaceMembers.find(({ id }) => id === share.principalId)
+ : undefined;
+ const role =
+ share.principalType === RecordSharePrincipalType.ROLE
+ ? sharing?.roles.find(({ id }) => id === share.principalId)
+ : undefined;
+ const label = getRecordShareLabel({
+ share,
+ member,
+ role,
+ currentWorkspaceMember,
+ });
+ const matchesSearch = hasMatchingSearchValue({
+ values: [
+ label,
+ isDefined(member) ? getWorkspaceMemberNameOrEmail(member) : undefined,
+ member?.userEmail,
+ ],
+ normalizedSearch,
+ });
+
+ if (!matchesSearch) {
+ return [];
+ }
+
+ return [
+ {
+ share,
+ label,
+ member,
+ isOwner: share.rowCause === RecordShareRowCause.OWNER,
+ isCurrentWorkspaceMember:
+ share.principalType === RecordSharePrincipalType.WORKSPACE_MEMBER &&
+ share.principalId === currentWorkspaceMember?.id,
+ },
+ ];
+ })
+ .sort(
+ (firstRecipient, secondRecipient) =>
+ Number(secondRecipient.isOwner) - Number(firstRecipient.isOwner) ||
+ Number(secondRecipient.isCurrentWorkspaceMember) -
+ Number(firstRecipient.isCurrentWorkspaceMember) ||
+ sortByAscString(firstRecipient.label, secondRecipient.label) ||
+ sortByAscString(
+ firstRecipient.share.principalType,
+ secondRecipient.share.principalType,
+ ) ||
+ sortByAscString(
+ firstRecipient.share.principalId,
+ secondRecipient.share.principalId,
+ ) ||
+ sortByAscString(
+ firstRecipient.share.rowCause,
+ secondRecipient.share.rowCause,
+ ),
+ )
+ .map(({ share, label, member }) => ({ share, label, member }));
+ const matchingRecipients = recipients.filter(
+ (recipient) =>
+ !selectedRecipients.some((selectedRecipient) =>
+ isSameRecordSharingInvitationRecipient({
+ recipient,
+ otherRecipient: selectedRecipient,
+ }),
+ ) &&
+ hasMatchingSearchValue({
+ values: [recipient.label, recipient.description],
+ normalizedSearch,
+ }),
+ );
+ const matchesGeneralAccess =
+ isInviting &&
+ generalAccess.hasGeneralAccess &&
+ hasMatchingSearchValue({
+ values: [generalAccess.label, generalAccess.workspaceName],
+ normalizedSearch,
+ });
+
+ return {
+ matchingShares,
+ matchingRecipients,
+ matchesGeneralAccess,
+ isInviting,
+ hasSelection,
+ };
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/utils/isSameRecordSharingInvitationRecipient.ts b/packages/twenty-front/src/modules/object-record/record-sharing/utils/isSameRecordSharingInvitationRecipient.ts
new file mode 100644
index 00000000000..f824f5cba41
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/utils/isSameRecordSharingInvitationRecipient.ts
@@ -0,0 +1,10 @@
+import { type RecordSharingInvitationRecipient } from '@/object-record/record-sharing/types/RecordSharingInvitationRecipient';
+
+export const isSameRecordSharingInvitationRecipient = ({
+ recipient,
+ otherRecipient,
+}: {
+ recipient: Pick<RecordSharingInvitationRecipient, 'kind' | 'id'>;
+ otherRecipient: Pick<RecordSharingInvitationRecipient, 'kind' | 'id'>;
+}) =>
+ recipient.kind === otherRecipient.kind && recipient.id === otherRecipient.id;
diff --git a/packages/twenty-front/src/modules/side-panel/components/SidePanelPageInfo.tsx b/packages/twenty-front/src/modules/side-panel/components/SidePanelPageInfo.tsx
index 2b1ea52bcd5..ecc2ee0ab81 100644
--- a/packages/twenty-front/src/modules/side-panel/components/SidePanelPageInfo.tsx
+++ b/packages/twenty-front/src/modules/side-panel/components/SidePanelPageInfo.tsx
@@ -83,6 +83,7 @@ export const SidePanelPageInfo = ({ pageChip }: SidePanelPageInfoProps) => {
SidePanelPages.EmailPageStyle,
SidePanelPages.EmailBlockStyle,
SidePanelPages.AddToMessageList,
+ SidePanelPages.ShareRecord,
].includes(pageChip.page.page)
: false;
diff --git a/packages/twenty-front/src/modules/side-panel/hooks/useOpenShareRecordInSidePanel.ts b/packages/twenty-front/src/modules/side-panel/hooks/useOpenShareRecordInSidePanel.ts
index e6e5cb3ef4d..97f27365ac5 100644
--- a/packages/twenty-front/src/modules/side-panel/hooks/useOpenShareRecordInSidePanel.ts
+++ b/packages/twenty-front/src/modules/side-panel/hooks/useOpenShareRecordInSidePanel.ts
@@ -23,7 +23,6 @@ export const useOpenShareRecordInSidePanel = () => {
recordId: string;
}) => {
const pageId = v4();
- const objectLabel = objectMetadataItem.labelSingular;
store.set(
shareRecordTargetComponentState.atomFamily({ instanceId: pageId }),
@@ -35,7 +34,7 @@ export const useOpenShareRecordInSidePanel = () => {
navigateSidePanelMenu({
page: SidePanelPages.ShareRecord,
- pageTitle: t`Share ${objectLabel}`,
+ pageTitle: t`Share`,
pageIcon: IconShare,
pageId,
});
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordAddPeopleItem.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordAddPeopleItem.tsx
deleted file mode 100644
index 24bb37758ee..00000000000
--- a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordAddPeopleItem.tsx
+++ /dev/null
@@ -1,122 +0,0 @@
-import { styled } from '@linaria/react';
-import { useLingui } from '@lingui/react/macro';
-import { useState } from 'react';
-import { Dropdown } from 'twenty-ui/components/navigation';
-import { IconLock, IconPlus, IconUsers } from 'twenty-ui/icon';
-
-import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMembersState';
-import { RecordSharingAccessSelect } from '@/object-record/record-sharing/components/RecordSharingAccessSelect';
-import { type useRecordSharing } from '@/object-record/record-sharing/hooks/useRecordSharing';
-import { SidePanelShareRecordDropdownItem } from '@/side-panel/pages/share-record/components/SidePanelShareRecordDropdownItem';
-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-import { getWorkspaceMemberNameOrEmail } from '@/workspace-member/utils/getWorkspaceMemberNameOrEmail';
-import { RecordShareAccessLevel } from '~/generated-metadata/graphql';
-
-const StyledRecipients = styled.div`
- max-height: 240px;
- overflow-y: auto;
-`;
-
-type SidePanelShareRecordAddPeopleItemProps = {
- itemId: string;
- sharing: NonNullable<ReturnType<typeof useRecordSharing>['sharing']>;
- saving: boolean;
- setShare: ReturnType<typeof useRecordSharing>['setShare'];
-};
-
-export const SidePanelShareRecordAddPeopleItem = ({
- itemId,
- sharing,
- saving,
- setShare,
-}: SidePanelShareRecordAddPeopleItemProps) => {
- const { t } = useLingui();
- const currentWorkspaceMembers = useAtomStateValue(
- currentWorkspaceMembersState,
- );
- const [search, setSearch] = useState('');
- const [invitationAccessLevel, setInvitationAccessLevel] = useState(
- RecordShareAccessLevel.READ,
- );
- const matchesSearch = (text: string) =>
- text.toLowerCase().includes(search.trim().toLowerCase());
- const isAlreadyShared = (principalId: string) =>
- sharing.shares.some((share) => share.principalId === principalId);
- const availableMembers = currentWorkspaceMembers.filter(
- (member) =>
- !isAlreadyShared(member.id) &&
- matchesSearch(
- `${member.name.firstName} ${member.name.lastName} ${member.userEmail}`,
- ),
- );
- const availableRoles = sharing.roles.filter(
- (role) => !isAlreadyShared(role.id) && matchesSearch(role.label),
- );
-
- return (
- <SidePanelShareRecordDropdownItem
- itemId={itemId}
- label={t`Add people or roles`}
- Icon={IconPlus}
- disabled={saving}
- type="picker"
- width={320}
- >
- <Dropdown.Search
- value={search}
- onValueChange={setSearch}
- placeholder={t`Search people or roles`}
- />
- <Dropdown.Section>
- <RecordSharingAccessSelect
- label={t`Invitation access`}
- text={t`Invite as`}
- value={invitationAccessLevel}
- disabled={saving}
- onChange={setInvitationAccessLevel}
- closeOnSelect={false}
- />
- </Dropdown.Section>
- <Dropdown.Separator />
- <StyledRecipients>
- <Dropdown.Section>
- {availableMembers.length === 0 && availableRoles.length === 0 && (
- <Dropdown.Empty>{t`No matching people or roles`}</Dropdown.Empty>
- )}
- {availableMembers.map((member) => (
- <Dropdown.ActionItem
- key={member.id}
- startIcon={<IconUsers />}
- description={member.userEmail}
- disabled={saving}
- onClick={() => {
- void setShare({
- principal: { workspaceMemberId: member.id },
- accessLevel: invitationAccessLevel,
- });
- }}
- >
- {getWorkspaceMemberNameOrEmail(member)}
- </Dropdown.ActionItem>
- ))}
- {availableRoles.map((role) => (
- <Dropdown.ActionItem
- key={role.id}
- startIcon={<IconLock />}
- description={t`Role`}
- disabled={saving}
- onClick={() => {
- void setShare({
- principal: { roleId: role.id },
- accessLevel: invitationAccessLevel,
- });
- }}
- >
- {role.label}
- </Dropdown.ActionItem>
- ))}
- </Dropdown.Section>
- </StyledRecipients>
- </SidePanelShareRecordDropdownItem>
- );
-};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordContent.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordContent.tsx
index c2fc54734a0..71cf0a362a8 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordContent.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordContent.tsx
@@ -1,39 +1,33 @@
import { styled } from '@linaria/react';
-import { Fragment } from 'react';
import { useLingui } from '@lingui/react/macro';
-import { isDefined } from 'twenty-shared/utils';
-import { IconLink, IconLock, IconRefresh, IconUsers } from 'twenty-ui/icon';
+import { useRef } from 'react';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { IconLink } from 'twenty-ui/icon';
import { Button } from 'twenty-ui/primitives/input';
+import { Separator } from 'twenty-ui/primitives/layout';
import { themeCssVariables } from 'twenty-ui/theme';
-import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
-import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMembersState';
-import { CommandMenuItem } from '@/command-menu/components/CommandMenuItem';
-import { RecordSharingAccessLevelOptions } from '@/object-record/record-sharing/components/RecordSharingAccessLevelOptions';
+import { RecordSharingInvitation } from '@/object-record/record-sharing/components/RecordSharingInvitation';
+import { RecordSharingInvitationAccessPicker } from '@/object-record/record-sharing/components/RecordSharingInvitationAccessPicker';
+import { RecordSharingInvitationRecipientPicker } from '@/object-record/record-sharing/components/RecordSharingInvitationRecipientPicker';
import { type useRecordSharing } from '@/object-record/record-sharing/hooks/useRecordSharing';
-import { getRecordShareAccessLevelLabel } from '@/object-record/record-sharing/utils/getRecordShareAccessLevelLabel';
-import { getRecordShareLabel } from '@/object-record/record-sharing/utils/getRecordShareLabel';
-import { getRecordShareRoleAccessNote } from '@/object-record/record-sharing/utils/getRecordShareRoleAccessNote';
-import { SidePanelGroup } from '@/side-panel/components/SidePanelGroup';
-import { SidePanelList } from '@/side-panel/components/SidePanelList';
-import { SidePanelShareRecordAddPeopleItem } from '@/side-panel/pages/share-record/components/SidePanelShareRecordAddPeopleItem';
-import { SidePanelShareRecordDropdownItem } from '@/side-panel/pages/share-record/components/SidePanelShareRecordDropdownItem';
+import { type RecordSharingInvitationRecipient } from '@/object-record/record-sharing/types/RecordSharingInvitationRecipient';
+import { getRecordSharingRecipientGroups } from '@/object-record/record-sharing/utils/getRecordSharingRecipientGroups';
import { SidePanelShareRecordGeneralAccessItem } from '@/side-panel/pages/share-record/components/SidePanelShareRecordGeneralAccessItem';
+import { SidePanelShareRecordGroup } from '@/side-panel/pages/share-record/components/SidePanelShareRecordGroup';
+import { SidePanelShareRecordList } from '@/side-panel/pages/share-record/components/SidePanelShareRecordList';
+import { SidePanelShareRecordRecipient } from '@/side-panel/pages/share-record/components/SidePanelShareRecordRecipient';
+import { SidePanelShareRecordRetryItem } from '@/side-panel/pages/share-record/components/SidePanelShareRecordRetryItem';
+import { SidePanelShareRecordSkeleton } from '@/side-panel/pages/share-record/components/SidePanelShareRecordSkeleton';
+import { useSidePanelShareRecordInvitation } from '@/side-panel/pages/share-record/hooks/useSidePanelShareRecordInvitation';
+import { useSidePanelShareRecordSearch } from '@/side-panel/pages/share-record/hooks/useSidePanelShareRecordSearch';
import { SidePanelFooter } from '@/ui/layout/side-panel/components/SidePanelFooter';
-import { SelectableListItem } from '@/ui/layout/selectable-list/components/SelectableListItem';
-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import {
ObjectSharingReach,
- RecordSharePrincipalType,
- RecordShareRowCause,
RecordSharingMode,
} from '~/generated-metadata/graphql';
import { useCopyToClipboard } from '~/hooks/useCopyToClipboard';
-const ADD_PEOPLE_ITEM_ID = 'share-record-add-people';
-const GENERAL_ACCESS_ITEM_ID = 'share-record-general-access';
-const RETRY_ITEM_ID = 'share-record-retry';
-
const StyledContainer = styled.div`
display: flex;
flex-direction: column;
@@ -44,6 +38,7 @@ const StyledListContainer = styled.div`
display: flex;
flex: 1;
flex-direction: column;
+ min-height: 0;
overflow: hidden;
`;
@@ -55,11 +50,8 @@ const StyledDescription = styled.div`
white-space: normal;
`;
-const StyledRoleAccessNote = styled.div`
- color: ${themeCssVariables.font.color.tertiary};
- font-size: ${themeCssVariables.font.size.xs};
- padding: 0 ${themeCssVariables.spacing[2]} ${themeCssVariables.spacing[1]}
- ${themeCssVariables.spacing[8]};
+const StyledSeparator = styled.div`
+ padding: ${themeCssVariables.spacing[0.5]} 0;
`;
type SidePanelShareRecordContentProps = {
@@ -86,190 +78,200 @@ export const SidePanelShareRecordContent = ({
removeShare,
refetch,
} = sharingState;
- const currentWorkspaceMembers = useAtomStateValue(
- currentWorkspaceMembersState,
- );
- const currentWorkspaceMember = useAtomStateValue(currentWorkspaceMemberState);
+ const invitation = useSidePanelShareRecordInvitation({
+ sharing,
+ saving,
+ setShare,
+ setGeneralAccess,
+ objectLabelPlural,
+ });
+ const searchInputRef = useRef<HTMLInputElement>(null);
+ const {
+ search,
+ onSearchChange,
+ matchingShares,
+ matchingRecipients,
+ matchesGeneralAccess,
+ hasSelection,
+ isInviting,
+ } = useSidePanelShareRecordSearch({
+ sharing,
+ recipients: invitation.recipients,
+ selectedRecipients: invitation.selectedRecipients,
+ generalAccess: invitation.generalAccess,
+ });
const { copyToClipboard } = useCopyToClipboard();
const canManageSharing = sharing?.canManageSharing ?? false;
- const roles = sharing?.roles ?? [];
- const recipients = (sharing?.shares ?? []).map((share) => {
- const isRole = share.principalType === RecordSharePrincipalType.ROLE;
- const principalRoleId = isRole ? share.principalId : share.principalRoleId;
-
- return {
- share,
- label: getRecordShareLabel({
- share,
- member: currentWorkspaceMembers.find(
- (member) => member.id === share.principalId,
- ),
- role: roles.find((role) => role.id === share.principalId),
- currentWorkspaceMember,
- }),
- Icon: isRole ? IconLock : IconUsers,
- principal: isRole
- ? { roleId: share.principalId }
- : { workspaceMemberId: share.principalId },
- principalRole: roles.find((role) => role.id === principalRoleId),
- isEditable: share.rowCause === RecordShareRowCause.MANUAL,
- };
+ const isInitialLoading = loading && !isDefined(sharing) && !isDefined(error);
+ const recipientGroups = getRecordSharingRecipientGroups({
+ isInviting,
+ matchingShares,
});
+ const handleRecipientsChange = (
+ recipients: RecordSharingInvitationRecipient[],
+ ) => {
+ invitation.onRecipientsChange(recipients);
+ searchInputRef.current?.focus();
+ };
+ const handleInvite = async () => {
+ const hasInvitedAllRecipients = await invitation.onInvite();
- const selectableItemIds = isDefined(error)
- ? [RETRY_ITEM_ID]
- : canManageSharing
- ? [
- ADD_PEOPLE_ITEM_ID,
- GENERAL_ACCESS_ITEM_ID,
- ...recipients
- .filter((recipient) => recipient.isEditable)
- .map((recipient) => recipient.share.id),
- ]
- : [];
+ if (!hasInvitedAllRecipients) {
+ return;
+ }
+
+ onSearchChange('');
+ };
+ const accessPicker = (
+ <RecordSharingInvitationAccessPicker
+ value={invitation.accessLevel}
+ hasEveryoneRecipient={invitation.hasEveryoneRecipient}
+ disabled={invitation.isSubmitting}
+ onChange={invitation.onAccessLevelChange}
+ />
+ );
return (
<StyledContainer>
+ {canManageSharing && !isDefined(error) && (
+ <RecordSharingInvitation
+ searchInputRef={searchInputRef}
+ search={search}
+ onSearchChange={onSearchChange}
+ selectedRecipients={invitation.selectedRecipients}
+ hasInvalidAccessLevel={invitation.hasInvalidAccessLevel}
+ canInvite={invitation.canInvite}
+ isSubmitting={invitation.isSubmitting}
+ onInvite={() => void handleInvite()}
+ />
+ )}
<StyledListContainer>
- <SidePanelList selectableItemIds={selectableItemIds} loading={loading}>
- {isDefined(error) ? (
- <>
- <StyledDescription role="alert">{t`Sharing settings could not be loaded.`}</StyledDescription>
- <SelectableListItem
- itemId={RETRY_ITEM_ID}
- onEnter={() => {
- void refetch().catch(() => {});
- }}
- >
- <CommandMenuItem
- id={RETRY_ITEM_ID}
- label={t`Try again`}
- Icon={IconRefresh}
- onClick={() => {
- void refetch().catch(() => {});
- }}
- />
- </SelectableListItem>
- </>
- ) : (
- isDefined(sharing) &&
- (canManageSharing ? (
+ {isInitialLoading && <SidePanelShareRecordSkeleton />}
+ {!isInitialLoading && (
+ <SidePanelShareRecordList>
+ {isDefined(error) ? (
<>
- <SidePanelShareRecordAddPeopleItem
- itemId={ADD_PEOPLE_ITEM_ID}
- sharing={sharing}
- saving={saving}
- setShare={setShare}
- />
- <SidePanelGroup heading={t`General access`}>
- <SidePanelShareRecordGeneralAccessItem
- itemId={GENERAL_ACCESS_ITEM_ID}
- generalAccessLevel={sharing.generalAccessLevel}
- defaultGeneralAccessLevel={
- sharing.defaultGeneralAccessLevel
- }
- hasManagedGeneralAccess={sharing.hasManagedGeneralAccess}
- objectLabelPlural={objectLabelPlural}
- saving={saving}
- setGeneralAccess={setGeneralAccess}
- />
- </SidePanelGroup>
- <SidePanelGroup heading={t`People and roles with access`}>
- {recipients.map(
- ({
- share,
- label,
- Icon,
- principal,
- principalRole,
- isEditable,
- }) => {
- const roleAccessNote = getRecordShareRoleAccessNote({
- accessLevel: share.accessLevel,
- principalRole,
- sharingReach,
- objectLabelPlural,
- });
-
- return (
- <Fragment key={share.id}>
- {isEditable ? (
- <SidePanelShareRecordDropdownItem
- itemId={share.id}
- label={label}
- Icon={Icon}
- description={getRecordShareAccessLevelLabel(
- share.accessLevel,
- )}
- disabled={saving}
- >
- <RecordSharingAccessLevelOptions
- value={share.accessLevel}
- onChange={(accessLevel) => {
- void setShare({ principal, accessLevel });
- }}
- onRemove={() => {
- void removeShare({ principal });
- }}
- />
- </SidePanelShareRecordDropdownItem>
- ) : (
- <CommandMenuItem
- id={share.id}
- label={label}
- Icon={Icon}
- description={
- share.rowCause === RecordShareRowCause.OWNER
- ? t`Owner`
- : t`Managed access`
- }
- contextualTextPosition="right"
- disabled
- />
- )}
- {isDefined(roleAccessNote) && (
- <StyledRoleAccessNote>
- {roleAccessNote}
- </StyledRoleAccessNote>
- )}
- </Fragment>
- );
- },
+ <StyledDescription role="alert">{t`Sharing settings could not be loaded.`}</StyledDescription>
+ <SidePanelShareRecordRetryItem refetch={refetch} />
+ </>
+ ) : (
+ isDefined(sharing) &&
+ (canManageSharing ? (
+ <>
+ {hasSelection && (
+ <SidePanelShareRecordGroup heading={t`Selected`}>
+ {accessPicker}
+ <RecordSharingInvitationRecipientPicker
+ recipients={invitation.selectedRecipients}
+ selectedRecipients={invitation.selectedRecipients}
+ disabled={invitation.isSubmitting}
+ onRecipientsChange={handleRecipientsChange}
+ />
+ </SidePanelShareRecordGroup>
+ )}
+ {(!isInviting || matchesGeneralAccess) && (
+ <SidePanelShareRecordGroup
+ heading={isInviting ? t`Have access` : t`Everyone`}
+ >
+ <SidePanelShareRecordGeneralAccessItem
+ generalAccessLevel={sharing.generalAccessLevel}
+ defaultGeneralAccessLevel={
+ sharing.defaultGeneralAccessLevel
+ }
+ hasManagedGeneralAccess={
+ sharing.hasManagedGeneralAccess
+ }
+ objectLabelPlural={objectLabelPlural}
+ isSaving={invitation.isSubmitting}
+ setGeneralAccess={setGeneralAccess}
+ />
+ </SidePanelShareRecordGroup>
)}
- </SidePanelGroup>
+ {recipientGroups.map(({ heading, matchingShares }) =>
+ isNonEmptyArray(matchingShares) ? (
+ <SidePanelShareRecordGroup
+ key={heading.id}
+ heading={t(heading)}
+ shouldHideHeading={isInviting && matchesGeneralAccess}
+ >
+ {matchingShares.map(({ share, label, member }) => (
+ <SidePanelShareRecordRecipient
+ key={share.id}
+ share={share}
+ label={label}
+ member={member}
+ roles={sharing.roles}
+ objectLabelPlural={objectLabelPlural}
+ sharingReach={sharingReach}
+ isSaving={invitation.isSubmitting}
+ setShare={setShare}
+ removeShare={removeShare}
+ />
+ ))}
+ </SidePanelShareRecordGroup>
+ ) : null,
+ )}
+ {isInviting && (
+ <SidePanelShareRecordGroup heading={t`Not shared with`}>
+ {!hasSelection && (
+ <>
+ {accessPicker}
+ <StyledSeparator>
+ <Separator />
+ </StyledSeparator>
+ </>
+ )}
+ <RecordSharingInvitationRecipientPicker
+ recipients={matchingRecipients}
+ selectedRecipients={invitation.selectedRecipients}
+ disabled={invitation.isSubmitting}
+ onRecipientsChange={handleRecipientsChange}
+ />
+ {!isNonEmptyArray(matchingRecipients) && (
+ <StyledDescription>{t`No matching people or roles`}</StyledDescription>
+ )}
+ </SidePanelShareRecordGroup>
+ )}
+ {sharing.hasManagedGeneralAccess && (
+ <StyledDescription>{t`Workspace access is also managed by an application.`}</StyledDescription>
+ )}
+ {sharing.sharingMode === RecordSharingMode.INHERITED && (
+ <StyledDescription>{t`Access is also inherited from related records.`}</StyledDescription>
+ )}
+ {!sharing.hasManagedGeneralAccess &&
+ sharing.sharingMode !== RecordSharingMode.INHERITED && (
+ <StyledDescription>
+ {sharingReach === ObjectSharingReach.WORKSPACE
+ ? t`People you add get this record even if their role can't access ${objectLabelPlural}. Field permissions still apply.`
+ : t`Role and field permissions still apply.`}
+ </StyledDescription>
+ )}
+ </>
+ ) : (
<StyledDescription>
- {sharing.hasManagedGeneralAccess
- ? t`Workspace access is also managed by an application.`
- : sharing.sharingMode === RecordSharingMode.INHERITED
- ? t`Access is also inherited from related records.`
- : sharingReach === ObjectSharingReach.WORKSPACE
- ? t`People you add get this record even if their role can't access ${objectLabelPlural}. Field permissions still apply.`
- : t`Role and field permissions still apply.`}
+ {sharing.sharingMode === RecordSharingMode.ROLE_ONLY
+ ? t`Access to ${objectLabelPlural} is set by roles, not record by record.`
+ : sharing.sharingMode === RecordSharingMode.OPEN_BY_DEFAULT
+ ? t`Only the creator of this record, people with full access to it and admins can change who has access.`
+ : t`Only the creator of this record and people with full access to it can change who has access.`}
</StyledDescription>
- </>
- ) : (
- <StyledDescription>
- {sharing.sharingMode === RecordSharingMode.ROLE_ONLY
- ? t`Access to ${objectLabelPlural} is set by roles, not record by record.`
- : sharing.sharingMode === RecordSharingMode.OPEN_BY_DEFAULT
- ? t`Only the creator of this record, people with full access to it and admins can change who has access.`
- : t`Only the creator of this record and people with full access to it can change who has access.`}
- </StyledDescription>
- ))
- )}
- </SidePanelList>
+ ))
+ )}
+ </SidePanelShareRecordList>
+ )}
</StyledListContainer>
<SidePanelFooter
+ variant="compact"
actions={[
<Button
key="copy-link"
size="sm"
variant="outline"
startIcon={<IconLink />}
- onClick={() => {
- void copyToClipboard(recordUrl);
- }}
- >{t`Copy link`}</Button>,
+ onClick={() => void copyToClipboard(recordUrl)}
+ >
+ {t`Copy link`}
+ </Button>,
]}
/>
</StyledContainer>
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordDropdownItem.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordDropdownItem.tsx
index bebfcf760b1..46a437fc7f1 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordDropdownItem.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordDropdownItem.tsx
@@ -5,23 +5,19 @@ import {
type DropdownType,
ListItemButton,
} from 'twenty-ui/components/navigation';
-import { type IconComponent } from 'twenty-ui/icon';
+import { IconChevronRight, type IconComponent } from 'twenty-ui/icon';
import { useTheme } from 'twenty-ui/theme';
-import { useSidePanelListItemFocus } from '@/side-panel/hooks/useSidePanelListItemFocus';
+import { RECORD_SHARING_ACCESS_MENU_SIDE_OFFSET_IN_PX } from '@/object-record/record-sharing/constants/RecordSharingAccessMenuSideOffsetInPx';
import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
-import { useOpenDropdown } from '@/ui/layout/dropdown/hooks/useOpenDropdown';
-import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';
-import { SelectableListItem } from '@/ui/layout/selectable-list/components/SelectableListItem';
+import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';
import { ListItemIconContainer } from '@/ui/navigation/list-item/components/ListItemIconContainer';
-import { ListItemSubmenuIndicator } from '@/ui/navigation/list-item/components/ListItemSubmenuIndicator';
-import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';
type SidePanelShareRecordDropdownItemProps = {
- itemId: string;
label: string;
Icon: IconComponent;
+ LeftComponent?: ReactNode;
description?: string;
disabled?: boolean;
type?: DropdownType;
@@ -30,71 +26,52 @@ type SidePanelShareRecordDropdownItemProps = {
};
export const SidePanelShareRecordDropdownItem = ({
- itemId,
label,
Icon,
+ LeftComponent,
description,
disabled = false,
type = 'menu',
- width = 200,
+ width = GenericDropdownContentWidth.Narrow,
children,
}: SidePanelShareRecordDropdownItemProps) => {
const theme = useTheme();
const dropdownId = useId();
- const isDropdownOpen = useAtomComponentStateValue(
- isDropdownOpenComponentState,
- dropdownId,
- );
- const { openDropdown } = useOpenDropdown();
- const { nativeItemRef, isSelectedItemId, handleFocus } =
- useSidePanelListItemFocus(itemId);
return (
- <SelectableListItem
- itemId={itemId}
- onEnter={
- disabled
- ? undefined
- : () =>
- openDropdown({ dropdownComponentInstanceIdFromProps: dropdownId })
- }
- >
- <DropdownRoot dropdownId={dropdownId} type={type}>
- <Dropdown.Trigger
- ref={nativeItemRef}
- render={
- <ListItemButton
- startIcon={
+ <DropdownRoot dropdownId={dropdownId} type={type}>
+ <Dropdown.Trigger
+ render={
+ <ListItemButton
+ startIcon={
+ LeftComponent ?? (
<ListItemIconContainer>
<Icon
size={theme.icon.size.md}
stroke={theme.icon.stroke.sm}
/>
</ListItemIconContainer>
- }
- description={description}
- descriptionPlacement="end"
- endIcon={
- !disabled && (
- <ListItemSubmenuIndicator isOpen={isDropdownOpen} />
- )
- }
- focused={!disabled && isSelectedItemId}
- focusableWhenDisabled
- >
- {label}
- </ListItemButton>
- }
- disabled={disabled}
- onFocus={handleFocus}
- aria-label={
- isDefined(description) ? `${label} ${description}` : label
- }
- />
- <DropdownContent align="end" width={width} aria-label={label}>
- {children}
- </DropdownContent>
- </DropdownRoot>
- </SelectableListItem>
+ )
+ }
+ description={description}
+ descriptionPlacement="end"
+ endIcon={<IconChevronRight />}
+ focusableWhenDisabled
+ >
+ {label}
+ </ListItemButton>
+ }
+ disabled={disabled}
+ aria-label={isDefined(description) ? `${label} ${description}` : label}
+ />
+ <DropdownContent
+ align="end"
+ sideOffset={RECORD_SHARING_ACCESS_MENU_SIDE_OFFSET_IN_PX}
+ width={width}
+ aria-label={label}
+ >
+ {children}
+ </DropdownContent>
+ </DropdownRoot>
);
};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordGeneralAccessItem.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordGeneralAccessItem.tsx
index 56a6e487e0e..081f775a54c 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordGeneralAccessItem.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordGeneralAccessItem.tsx
@@ -1,87 +1,126 @@
import { useLingui } from '@lingui/react/macro';
import { isDefined } from 'twenty-shared/utils';
import { Dropdown } from 'twenty-ui/components/navigation';
-import { IconLock, IconUsers } from 'twenty-ui/icon';
+import { IconEye, IconLock, IconPencil } from 'twenty-ui/icon';
+import { Avatar } from 'twenty-ui/primitives/data-display';
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { RECORD_SHARE_ACCESS_LEVEL_OPTIONS } from '@/object-record/record-sharing/constants/RecordShareAccessLevelOptions';
import { type useRecordSharing } from '@/object-record/record-sharing/hooks/useRecordSharing';
import { getRecordShareAccessLevelLabel } from '@/object-record/record-sharing/utils/getRecordShareAccessLevelLabel';
+import { getRecordSharingGeneralAccess } from '@/object-record/record-sharing/utils/getRecordSharingGeneralAccess';
import { SidePanelShareRecordDropdownItem } from '@/side-panel/pages/share-record/components/SidePanelShareRecordDropdownItem';
+import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';
+import { ListItemIconContainer } from '@/ui/navigation/list-item/components/ListItemIconContainer';
+import { DEFAULT_WORKSPACE_LOGO } from '@/ui/navigation/navigation-drawer/constants/DefaultWorkspaceLogo';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { getWorkspaceAvatarColorSeed } from '@/workspace/utils/getWorkspaceAvatarColorSeed';
import { RecordShareAccessLevel } from '~/generated-metadata/graphql';
+import { getAbsoluteImageUrl } from '~/utils/image/getAbsoluteImageUrl';
type SidePanelShareRecordGeneralAccessItemProps = {
- itemId: string;
generalAccessLevel: RecordShareAccessLevel | null | undefined;
defaultGeneralAccessLevel: RecordShareAccessLevel | null | undefined;
hasManagedGeneralAccess: boolean;
objectLabelPlural: string;
- saving: boolean;
+ isSaving: boolean;
setGeneralAccess: ReturnType<typeof useRecordSharing>['setGeneralAccess'];
};
export const SidePanelShareRecordGeneralAccessItem = ({
- itemId,
generalAccessLevel,
defaultGeneralAccessLevel,
hasManagedGeneralAccess,
objectLabelPlural,
- saving,
+ isSaving,
setGeneralAccess,
}: SidePanelShareRecordGeneralAccessItemProps) => {
const { t } = useLingui();
+ const currentWorkspace = useAtomStateValue(currentWorkspaceState);
+ const workspaceName = currentWorkspace?.displayName ?? '';
const isRestricted =
!isDefined(generalAccessLevel) ||
generalAccessLevel === RecordShareAccessLevel.NONE;
- const hasWorkspaceAccess = !isRestricted || hasManagedGeneralAccess;
- const withDefaultMarker = (
- label: string,
- accessLevel: RecordShareAccessLevel,
- ) =>
+ const { hasGeneralAccess, label: generalAccessLabel } =
+ getRecordSharingGeneralAccess({
+ sharing: { generalAccessLevel, hasManagedGeneralAccess },
+ objectLabelPlural,
+ });
+ const withDefaultMarker = ({
+ label,
+ accessLevel,
+ }: {
+ label: string;
+ accessLevel: RecordShareAccessLevel;
+ }) =>
accessLevel === defaultGeneralAccessLevel ? t`${label} (default)` : label;
return (
<SidePanelShareRecordDropdownItem
- itemId={itemId}
- label={
- hasWorkspaceAccess
- ? t`Everyone with access to ${objectLabelPlural}`
- : t`Restricted`
+ label={hasGeneralAccess ? t(generalAccessLabel) : t`Restricted`}
+ Icon={IconLock}
+ LeftComponent={
+ hasGeneralAccess ? (
+ <ListItemIconContainer>
+ <Avatar
+ name={workspaceName}
+ colorSeed={getWorkspaceAvatarColorSeed(workspaceName)}
+ src={getAbsoluteImageUrl(
+ currentWorkspace?.logo ?? DEFAULT_WORKSPACE_LOGO,
+ )}
+ shape="square"
+ />
+ </ListItemIconContainer>
+ ) : undefined
}
- Icon={hasWorkspaceAccess ? IconUsers : IconLock}
description={
isRestricted
? undefined
: getRecordShareAccessLevelLabel(generalAccessLevel)
}
- disabled={saving}
- width={280}
+ disabled={isSaving}
+ width={GenericDropdownContentWidth.Medium}
>
<Dropdown.Section>
<Dropdown.OptionItem
- selected={!hasWorkspaceAccess}
- disabled={isRestricted || saving}
+ startIcon={<IconLock />}
+ selected={!hasGeneralAccess}
+ disabled={isRestricted || isSaving}
onSelect={() => {
void setGeneralAccess(RecordShareAccessLevel.NONE);
}}
>
- {withDefaultMarker(t`Restricted`, RecordShareAccessLevel.NONE)}
+ {withDefaultMarker({
+ label: t`Restricted`,
+ accessLevel: RecordShareAccessLevel.NONE,
+ })}
</Dropdown.OptionItem>
</Dropdown.Section>
<Dropdown.Separator />
- <Dropdown.Section label={t`Everyone with access to ${objectLabelPlural}`}>
+ <Dropdown.Section label={t(generalAccessLabel)}>
{RECORD_SHARE_ACCESS_LEVEL_OPTIONS.filter(
// Full access lets its holder manage sharing, so it is only granted by name
(option) => option.value !== RecordShareAccessLevel.FULL,
).map((option) => (
<Dropdown.OptionItem
key={option.value}
+ startIcon={
+ option.value === RecordShareAccessLevel.READ ? (
+ <IconEye />
+ ) : (
+ <IconPencil />
+ )
+ }
selected={generalAccessLevel === option.value}
- disabled={generalAccessLevel === option.value || saving}
+ disabled={generalAccessLevel === option.value || isSaving}
onSelect={() => {
void setGeneralAccess(option.value);
}}
>
- {withDefaultMarker(t(option.label), option.value)}
+ {withDefaultMarker({
+ label: t(option.label),
+ accessLevel: option.value,
+ })}
</Dropdown.OptionItem>
))}
</Dropdown.Section>
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordGroup.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordGroup.tsx
new file mode 100644
index 00000000000..21125d78c4c
--- /dev/null
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordGroup.tsx
@@ -0,0 +1,35 @@
+import { styled } from '@linaria/react';
+import { type ReactNode } from 'react';
+import { Text } from 'twenty-ui/primitives/typography';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+const StyledHeading = styled.div`
+ align-items: center;
+ display: flex;
+ height: ${themeCssVariables.spacing[5]};
+ padding: 0 ${themeCssVariables.spacing[1]};
+ user-select: none;
+`;
+
+type SidePanelShareRecordGroupProps = {
+ heading: ReactNode;
+ shouldHideHeading?: boolean;
+ children: ReactNode;
+};
+
+export const SidePanelShareRecordGroup = ({
+ heading,
+ shouldHideHeading = false,
+ children,
+}: SidePanelShareRecordGroupProps) => (
+ <>
+ {!shouldHideHeading && (
+ <StyledHeading>
+ <Text size="xs" weight="semibold" color="light">
+ {heading}
+ </Text>
+ </StyledHeading>
+ )}
+ {children}
+ </>
+);
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordList.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordList.tsx
new file mode 100644
index 00000000000..642cd371dbc
--- /dev/null
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordList.tsx
@@ -0,0 +1,24 @@
+import { styled } from '@linaria/react';
+import { type ReactNode } from 'react';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { ScrollWrapper } from '@/ui/utilities/scroll/components/ScrollWrapper';
+
+const StyledList = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[0.5]};
+ padding: ${themeCssVariables.spacing[1]} ${themeCssVariables.spacing[2]};
+`;
+
+type SidePanelShareRecordListProps = {
+ children: ReactNode;
+};
+
+export const SidePanelShareRecordList = ({
+ children,
+}: SidePanelShareRecordListProps) => (
+ <ScrollWrapper componentInstanceId="scroll-wrapper-side-panel">
+ <StyledList>{children}</StyledList>
+ </ScrollWrapper>
+);
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordRecipient.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordRecipient.tsx
new file mode 100644
index 00000000000..456f5b4b86e
--- /dev/null
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordRecipient.tsx
@@ -0,0 +1,133 @@
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { isDefined } from 'twenty-shared/utils';
+import { IconLock, IconUsers } from 'twenty-ui/icon';
+import { Avatar } from 'twenty-ui/primitives/data-display';
+import { ListItem } from 'twenty-ui/primitives/navigation';
+import { themeCssVariables, useTheme } from 'twenty-ui/theme';
+
+import { RecordSharingAccessLevelOptions } from '@/object-record/record-sharing/components/RecordSharingAccessLevelOptions';
+import { type useRecordSharing } from '@/object-record/record-sharing/hooks/useRecordSharing';
+import { getRecordShareAccessLevelLabel } from '@/object-record/record-sharing/utils/getRecordShareAccessLevelLabel';
+import { getRecordShareRoleAccessNote } from '@/object-record/record-sharing/utils/getRecordShareRoleAccessNote';
+import { type PartialWorkspaceMember } from '@/settings/roles/types/RoleWithPartialMembers';
+import { SidePanelShareRecordDropdownItem } from '@/side-panel/pages/share-record/components/SidePanelShareRecordDropdownItem';
+import { ListItemIconContainer } from '@/ui/navigation/list-item/components/ListItemIconContainer';
+import { getWorkspaceMemberNameOrEmail } from '@/workspace-member/utils/getWorkspaceMemberNameOrEmail';
+import {
+ type ObjectSharingReach,
+ RecordSharePrincipalType,
+ RecordShareRowCause,
+ type RecordSharingFieldsFragment,
+} from '~/generated-metadata/graphql';
+import { getAbsoluteImageUrl } from '~/utils/image/getAbsoluteImageUrl';
+
+const StyledRoleAccessNote = styled.div`
+ color: ${themeCssVariables.font.color.tertiary};
+ font-size: ${themeCssVariables.font.size.xs};
+ padding: 0 ${themeCssVariables.spacing[2]} ${themeCssVariables.spacing[1]}
+ ${themeCssVariables.spacing[8]};
+`;
+
+type SidePanelShareRecordRecipientProps = {
+ share: RecordSharingFieldsFragment['shares'][number];
+ label: string;
+ member: PartialWorkspaceMember | undefined;
+ roles: RecordSharingFieldsFragment['roles'];
+ objectLabelPlural: string;
+ sharingReach: ObjectSharingReach;
+ isSaving: boolean;
+ setShare: ReturnType<typeof useRecordSharing>['setShare'];
+ removeShare: ReturnType<typeof useRecordSharing>['removeShare'];
+};
+
+export const SidePanelShareRecordRecipient = ({
+ share,
+ label,
+ member,
+ roles,
+ objectLabelPlural,
+ sharingReach,
+ isSaving,
+ setShare,
+ removeShare,
+}: SidePanelShareRecordRecipientProps) => {
+ const { t } = useLingui();
+ const theme = useTheme();
+ const isRole = share.principalType === RecordSharePrincipalType.ROLE;
+ const principalRoleId = isRole ? share.principalId : share.principalRoleId;
+ const principal = isRole
+ ? { roleId: share.principalId }
+ : { workspaceMemberId: share.principalId };
+ const Icon = isRole ? IconLock : IconUsers;
+ const avatar = isDefined(member) ? (
+ <ListItemIconContainer>
+ <Avatar
+ src={getAbsoluteImageUrl(member.avatarUrl)}
+ name={getWorkspaceMemberNameOrEmail(member)}
+ colorSeed={member.id}
+ shape="circle"
+ />
+ </ListItemIconContainer>
+ ) : undefined;
+ const roleAccessNote = getRecordShareRoleAccessNote({
+ accessLevel: share.accessLevel,
+ principalRole: roles.find(({ id }) => id === principalRoleId),
+ sharingReach,
+ objectLabelPlural,
+ });
+ const isEditable = share.rowCause === RecordShareRowCause.MANUAL;
+ const getRecipientItem = () => {
+ if (!isEditable) {
+ return (
+ <ListItem
+ startIcon={
+ avatar ?? (
+ <ListItemIconContainer>
+ <Icon size={theme.icon.size.md} stroke={theme.icon.stroke.sm} />
+ </ListItemIconContainer>
+ )
+ }
+ description={
+ share.rowCause === RecordShareRowCause.OWNER
+ ? t`Owner`
+ : t`Managed access`
+ }
+ descriptionPlacement="end"
+ disabled
+ >
+ {label}
+ </ListItem>
+ );
+ }
+
+ return (
+ <SidePanelShareRecordDropdownItem
+ label={label}
+ Icon={Icon}
+ LeftComponent={avatar}
+ description={getRecordShareAccessLevelLabel(share.accessLevel)}
+ disabled={isSaving}
+ >
+ <RecordSharingAccessLevelOptions
+ value={share.accessLevel}
+ onChange={(accessLevel) => {
+ void setShare({ principal, accessLevel });
+ }}
+ onRemove={() => {
+ void removeShare({ principal });
+ }}
+ />
+ </SidePanelShareRecordDropdownItem>
+ );
+ };
+
+ return (
+ <>
+ {getRecipientItem()}
+ {isDefined(roleAccessNote) && (
+ <StyledRoleAccessNote>{roleAccessNote}</StyledRoleAccessNote>
+ )}
+ </>
+ );
+};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordRetryItem.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordRetryItem.tsx
new file mode 100644
index 00000000000..7df01371847
--- /dev/null
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordRetryItem.tsx
@@ -0,0 +1,37 @@
+import { useLingui } from '@lingui/react/macro';
+import { ListItemButton } from 'twenty-ui/components/navigation';
+import { IconRefresh } from 'twenty-ui/icon';
+import { useTheme } from 'twenty-ui/theme';
+
+import { type useRecordSharing } from '@/object-record/record-sharing/hooks/useRecordSharing';
+import { ListItemIconContainer } from '@/ui/navigation/list-item/components/ListItemIconContainer';
+
+type SidePanelShareRecordRetryItemProps = {
+ refetch: ReturnType<typeof useRecordSharing>['refetch'];
+};
+
+export const SidePanelShareRecordRetryItem = ({
+ refetch,
+}: SidePanelShareRecordRetryItemProps) => {
+ const { t } = useLingui();
+ const theme = useTheme();
+ const handleRetry = () => {
+ void refetch().catch(() => {});
+ };
+
+ return (
+ <ListItemButton
+ startIcon={
+ <ListItemIconContainer>
+ <IconRefresh
+ size={theme.icon.size.md}
+ stroke={theme.icon.stroke.sm}
+ />
+ </ListItemIconContainer>
+ }
+ onClick={handleRetry}
+ >
+ {t`Try again`}
+ </ListItemButton>
+ );
+};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordSkeleton.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordSkeleton.tsx
new file mode 100644
index 00000000000..4f04b49d5b2
--- /dev/null
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordSkeleton.tsx
@@ -0,0 +1,110 @@
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { Skeleton } from 'twenty-ui/primitives/feedback';
+import { ListItem } from 'twenty-ui/primitives/navigation';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { SidePanelShareRecordGroup } from '@/side-panel/pages/share-record/components/SidePanelShareRecordGroup';
+import { SidePanelShareRecordList } from '@/side-panel/pages/share-record/components/SidePanelShareRecordList';
+
+const SKELETON_GROUPS = [
+ {
+ id: 'everyone',
+ headingWidth: themeCssVariables.spacing[14],
+ rowWidths: [themeCssVariables.spacing[32]],
+ },
+ {
+ id: 'roles',
+ headingWidth: themeCssVariables.spacing[8],
+ rowWidths: [themeCssVariables.spacing[20]],
+ },
+ {
+ id: 'users',
+ headingWidth: themeCssVariables.spacing[8],
+ rowWidths: [themeCssVariables.spacing[24], themeCssVariables.spacing[28]],
+ },
+];
+
+const StyledContainer = styled.div`
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ min-height: 0;
+`;
+
+const StyledHeader = styled.div`
+ align-items: center;
+ border-bottom: 1px solid ${themeCssVariables.border.color.light};
+ box-sizing: border-box;
+ display: flex;
+ flex-shrink: 0;
+ height: ${themeCssVariables.spacing[10]};
+ justify-content: space-between;
+ padding: 0 ${themeCssVariables.spacing[3]};
+`;
+
+const StyledListContainer = styled.div`
+ flex: 1;
+ min-height: 0;
+ overflow: hidden;
+`;
+
+export const SidePanelShareRecordSkeleton = () => {
+ const { t } = useLingui();
+
+ return (
+ <StyledContainer
+ role="status"
+ aria-label={t`Loading sharing settings`}
+ aria-busy
+ >
+ <StyledHeader aria-hidden>
+ <Skeleton width="50%" height={themeCssVariables.spacing[3]} />
+ <Skeleton
+ width={themeCssVariables.spacing[13]}
+ height={themeCssVariables.spacing[6]}
+ />
+ </StyledHeader>
+ <StyledListContainer aria-hidden>
+ <SidePanelShareRecordList>
+ {SKELETON_GROUPS.map(({ id, headingWidth, rowWidths }) => (
+ <SidePanelShareRecordGroup
+ key={id}
+ heading={
+ <Skeleton
+ width={headingWidth}
+ height={themeCssVariables.spacing[2]}
+ />
+ }
+ >
+ {rowWidths.map((width) => (
+ <ListItem
+ key={width}
+ disabled
+ startIcon={
+ <Skeleton
+ width={themeCssVariables.spacing[6]}
+ height={themeCssVariables.spacing[6]}
+ />
+ }
+ description={
+ <Skeleton
+ width={themeCssVariables.spacing[10]}
+ height={themeCssVariables.spacing[3]}
+ />
+ }
+ descriptionPlacement="end"
+ >
+ <Skeleton
+ width={width}
+ height={themeCssVariables.spacing[3]}
+ />
+ </ListItem>
+ ))}
+ </SidePanelShareRecordGroup>
+ ))}
+ </SidePanelShareRecordList>
+ </StyledListContainer>
+ </StyledContainer>
+ );
+};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__stories__/SidePanelShareRecordContent.stories.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__stories__/SidePanelShareRecordContent.stories.tsx
index b12a10b4984..c9d61836cf6 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__stories__/SidePanelShareRecordContent.stories.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__stories__/SidePanelShareRecordContent.stories.tsx
@@ -2,11 +2,13 @@ import { styled } from '@linaria/react';
import { type Meta, type StoryObj } from '@storybook/react-vite';
import { createStore, Provider } from 'jotai';
import { type ReactNode, useState } from 'react';
-import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
-import { ComponentDecorator } from 'twenty-ui/testing';
+import { expect, fn, spyOn, userEvent, waitFor, within } from 'storybook/test';
+import { isDefined } from 'twenty-shared/utils';
+import { AVATAR_URL_MOCK, ComponentDecorator } from 'twenty-ui/testing';
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMembersState';
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { SidePanelShareRecordContent } from '@/side-panel/pages/share-record/components/SidePanelShareRecordContent';
import {
ObjectSharingReach,
@@ -17,6 +19,7 @@ import {
} from '~/generated-metadata/graphql';
import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';
import { ToastDecorator } from '~/testing/decorators/ToastDecorator';
+import { mockCurrentWorkspace } from '~/testing/mock-data/users';
const setGeneralAccess = fn();
const setShare = fn();
@@ -42,6 +45,13 @@ const MEMBERS = [
userEmail: '[email protected]',
userId: 'invite-user',
},
+ {
+ id: 'invite-with-avatar',
+ name: { firstName: 'Jony', lastName: 'Ive' },
+ userEmail: '[email protected]',
+ userId: 'invite-with-avatar-user',
+ avatarUrl: AVATAR_URL_MOCK,
+ },
];
const SHARING = {
@@ -94,6 +104,10 @@ const SidePanelStoryProviders = ({ children }: { children: ReactNode }) => {
const [store] = useState(() => {
const store = createStore();
store.set(currentWorkspaceMembersState.atom, MEMBERS);
+ store.set(currentWorkspaceState.atom, {
+ ...mockCurrentWorkspace,
+ displayName: 'Acme',
+ });
store.set(currentWorkspaceMemberState.atom, {
...MEMBERS[0],
colorScheme: 'Light',
@@ -137,6 +151,16 @@ const meta: Meta<typeof SidePanelShareRecordContent> = {
refetch,
},
},
+ beforeEach: () => {
+ setGeneralAccess.mockClear();
+ setGeneralAccess.mockResolvedValue(SHARING);
+ setShare.mockClear();
+ setShare.mockResolvedValue(SHARING);
+ removeShare.mockClear();
+ removeShare.mockResolvedValue(SHARING);
+ refetch.mockClear();
+ refetch.mockResolvedValue(undefined);
+ },
parameters: { container: { width: 600, height: 700 } },
};
@@ -144,26 +168,79 @@ export default meta;
type Story = StoryObj<typeof SidePanelShareRecordContent>;
export const Default: Story = {
- play: async ({ canvasElement }) => {
+ play: async ({ canvasElement, args }) => {
const page = within(canvasElement.ownerDocument.body);
const generalAccess = await page.findByRole('button', {
name: 'Restricted',
});
- const addPeople = page.getByRole('button', { name: 'Add people or roles' });
+ const footer = page
+ .getByRole('button', { name: 'Copy link' })
+ .closest('[data-variant="compact"]');
+ await expect(footer?.getBoundingClientRect().height).toBe(40);
+ const addPeople = page.getByPlaceholderText('Add people or everyone');
+ const role = page.getByRole('button', { name: 'Sales Viewer' });
const recipient = page.getByRole('button', { name: 'Phil Schiler Editor' });
await expect(generalAccess).toBeVisible();
+ await expect(page.getByText('Everyone')).toBeVisible();
+ await expect(page.getByText('Roles')).toBeVisible();
+ await expect(page.getByText('Users')).toBeVisible();
await expect(page.getByText('You')).toBeVisible();
await expect(page.getByText('Owner')).toBeVisible();
- await userEvent.tab();
+ await userEvent.click(addPeople);
await expect(addPeople).toHaveFocus();
await userEvent.tab();
await expect(generalAccess).toHaveFocus();
await userEvent.keyboard('{Enter}');
+ const restrictedOption = await page.findByRole('menuitemradio', {
+ name: 'Restricted (default)',
+ });
+ await expect(restrictedOption).toBeVisible();
+ const restrictedLabel = within(restrictedOption).getByText(
+ 'Restricted (default)',
+ );
+ await canvasElement.ownerDocument.fonts.ready;
+ await expect(restrictedLabel.scrollWidth).toBeLessThanOrEqual(
+ restrictedLabel.clientWidth,
+ );
+ const generalAccessHeading = page.getByText(
+ `Everyone with access to ${args.objectLabelPlural}`,
+ );
+ const headingRange = canvasElement.ownerDocument.createRange();
+ headingRange.selectNodeContents(generalAccessHeading);
+ await expect(headingRange.getClientRects()).toHaveLength(1);
await expect(
- await page.findByRole('menuitemradio', { name: 'Restricted (default)' }),
- ).toBeVisible();
- await userEvent.keyboard('{Escape}');
+ page.queryByRole('menuitemradio', { name: 'Full access' }),
+ ).not.toBeInTheDocument();
+ await userEvent.click(page.getByRole('menuitemradio', { name: 'Viewer' }));
+ await waitFor(() =>
+ expect(setGeneralAccess).toHaveBeenLastCalledWith(
+ RecordShareAccessLevel.READ,
+ ),
+ );
await expect(generalAccess).toHaveFocus();
+ await userEvent.keyboard('{Enter}');
+ await userEvent.click(
+ await page.findByRole('menuitemradio', { name: 'Editor' }),
+ );
+ await waitFor(() =>
+ expect(setGeneralAccess).toHaveBeenLastCalledWith(
+ RecordShareAccessLevel.READ_WRITE,
+ ),
+ );
+ await expect(generalAccess).toHaveFocus();
+ await userEvent.tab();
+ await expect(role).toHaveFocus();
+ await userEvent.keyboard('{Enter}');
+ await userEvent.click(
+ await page.findByRole('menuitemradio', { name: 'Editor' }),
+ );
+ await waitFor(() =>
+ expect(setShare).toHaveBeenCalledWith({
+ principal: { roleId: 'sales' },
+ accessLevel: RecordShareAccessLevel.READ_WRITE,
+ }),
+ );
+ await expect(role).toHaveFocus();
await userEvent.tab();
await expect(recipient).toHaveFocus();
await userEvent.keyboard('{Enter}');
@@ -182,23 +259,233 @@ export const Default: Story = {
export const AddPeople: Story = {
play: async ({ canvasElement }) => {
const page = within(canvasElement.ownerDocument.body);
+ const search = await page.findByPlaceholderText('Add people or everyone');
+ await userEvent.type(search, 'No matching recipient');
+ await expect(page.getByText('No matching people or roles')).toBeVisible();
+ await expect(page.queryByRole('checkbox')).not.toBeInTheDocument();
+ await expect(page.getByRole('button', { name: 'Invite' })).toBeDisabled();
+ await userEvent.clear(search);
+ await expect(
+ page.queryByText('No matching people or roles'),
+ ).not.toBeInTheDocument();
+ await userEvent.type(search, '[email protected]');
+ await expect(page.getByText('Have access')).toBeVisible();
+ await expect(
+ page.getByRole('button', { name: 'Phil Schiler Editor' }),
+ ).toBeVisible();
+ await expect(
+ page.queryByRole('checkbox', { name: /Jane Austen/ }),
+ ).not.toBeInTheDocument();
+ await userEvent.keyboard('{Enter}');
+ await expect(page.queryByRole('menu')).not.toBeInTheDocument();
+ await expect(search).toHaveFocus();
+ await userEvent.clear(search);
+ await userEvent.type(search, 'j');
+ await expect(page.getByText('Not shared with')).toBeVisible();
+ const recipientWithoutAvatar = page
+ .getByRole('checkbox', {
+ name: /Jane Austen/,
+ })
+ .closest('label');
+
+ if (!isDefined(recipientWithoutAvatar)) {
+ throw new Error('Jane Austen recipient row is missing');
+ }
+
+ await expect(
+ await within(recipientWithoutAvatar).findByText('J'),
+ ).toBeVisible();
+ const recipientWithAvatar = page
+ .getByRole('checkbox', { name: /Jony Ive/ })
+ .closest('label');
+
+ if (!isDefined(recipientWithAvatar)) {
+ throw new Error('Jony Ive recipient row is missing');
+ }
+
+ const avatar =
+ await within(recipientWithAvatar).findByRole<HTMLImageElement>(
+ 'presentation',
+ );
+ await expect(avatar).toBeVisible();
+ await waitFor(() => expect(avatar.naturalWidth).toBeGreaterThan(0));
+ },
+};
+
+export const ChangeAccessWithoutMovingRecipients: Story = {
+ args: {
+ sharingState: {
+ sharing: {
+ ...SHARING,
+ shares: [
+ SHARING.shares[0],
+ {
+ ...SHARING.shares[1],
+ id: 'jane-grant',
+ principalId: 'invite',
+ },
+ ...SHARING.shares.slice(1),
+ ],
+ },
+ loading: false,
+ error: undefined,
+ saving: false,
+ setGeneralAccess,
+ setShare,
+ removeShare,
+ refetch,
+ },
+ },
+ render: (args) => {
+ const [sharing, setSharing] = useState(args.sharingState.sharing);
+ const handleSetShare = async (
+ input: Parameters<typeof args.sharingState.setShare>[0],
+ ) => {
+ const result = await args.sharingState.setShare(input);
+
+ if (isDefined(result)) {
+ setSharing(result);
+ }
+
+ return result;
+ };
+
+ return (
+ <SidePanelShareRecordContent
+ recordUrl={args.recordUrl}
+ objectLabelPlural={args.objectLabelPlural}
+ sharingReach={args.sharingReach}
+ sharingState={{
+ ...args.sharingState,
+ sharing,
+ setShare: handleSetShare,
+ }}
+ />
+ );
+ },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ const jane = await page.findByRole('button', {
+ name: 'Jane Austen Editor',
+ });
+ const phil = page.getByRole('button', { name: 'Phil Schiler Editor' });
+ const janePosition = jane.getBoundingClientRect().top;
+ const philPosition = phil.getBoundingClientRect().top;
+ setShare.mockResolvedValueOnce({
+ ...SHARING,
+ shares: [
+ ...SHARING.shares,
+ {
+ ...SHARING.shares[1],
+ id: 'updated-jane-grant',
+ principalId: 'invite',
+ accessLevel: RecordShareAccessLevel.FULL,
+ },
+ ],
+ });
+
+ await userEvent.click(jane);
await userEvent.click(
- await page.findByRole('button', { name: 'Add people or roles' }),
+ await page.findByRole('menuitemradio', { name: 'Full access' }),
);
+ const updatedJane = await page.findByRole('button', {
+ name: 'Jane Austen Full access',
+ });
+
+ await expect(updatedJane.getBoundingClientRect().top).toBe(janePosition);
+ await expect(phil.getBoundingClientRect().top).toBe(philPosition);
+ await expect(setShare).toHaveBeenCalledWith({
+ principal: { workspaceMemberId: 'invite' },
+ accessLevel: RecordShareAccessLevel.FULL,
+ });
+ },
+};
+
+export const InvitePeople: Story = {
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ const search = await page.findByPlaceholderText('Add people or everyone');
+ await userEvent.type(search, 'j');
+ await userEvent.tab();
+ await expect(
+ page.getByRole('button', { name: 'Invite as Viewer' }),
+ ).toHaveFocus();
+ await userEvent.tab();
+ await expect(
+ page.getByRole('checkbox', { name: /Jane Austen/ }),
+ ).toHaveFocus();
+ await userEvent.keyboard(' ');
+ await expect(
+ page.getByRole('checkbox', { name: /Jane Austen/ }),
+ ).toBeChecked();
+ await expect(search).toHaveFocus();
+ await userEvent.click(page.getByRole('checkbox', { name: /Jony Ive/ }));
+ await expect(page.getByRole('button', { name: 'Invite 2' })).toBeEnabled();
+ await expect(setShare).not.toHaveBeenCalled();
+ await userEvent.click(page.getByRole('button', { name: 'Invite 2' }));
+ await waitFor(() => expect(setShare).toHaveBeenCalledTimes(2));
+ await expect(setShare).toHaveBeenNthCalledWith(1, {
+ principal: { workspaceMemberId: 'invite' },
+ accessLevel: RecordShareAccessLevel.READ,
+ });
+ await expect(setShare).toHaveBeenNthCalledWith(2, {
+ principal: { workspaceMemberId: 'invite-with-avatar' },
+ accessLevel: RecordShareAccessLevel.READ,
+ });
await waitFor(() =>
- expect(page.getByPlaceholderText('Search people or roles')).toBeVisible(),
+ expect(page.getByRole('button', { name: 'Invite' })).toBeDisabled(),
);
- await expect(page.getByText('Jane Austen')).toBeVisible();
+ await expect(search).toHaveValue('');
+ await expect(page.getByText('Everyone')).toBeVisible();
+ await expect(page.getByText('Roles')).toBeVisible();
+ await expect(page.getByText('Users')).toBeVisible();
+ await expect(page.queryByText('Selected')).not.toBeInTheDocument();
+ await expect(page.queryByText('Not shared with')).not.toBeInTheDocument();
+ await expect(page.queryByRole('checkbox')).not.toBeInTheDocument();
+ await expect(setGeneralAccess).not.toHaveBeenCalled();
},
};
-export const Saving: Story = {
+export const InviteEveryone: Story = {
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.type(
+ await page.findByPlaceholderText('Add people or everyone'),
+ 'Everyone',
+ );
+ await userEvent.click(
+ page.getByRole('checkbox', { name: /Everyone with access to Chats/ }),
+ );
+ await userEvent.click(
+ page.getByRole('button', { name: 'Invite as Viewer' }),
+ );
+ await expect(
+ page.queryByRole('menuitemradio', { name: 'Full access' }),
+ ).not.toBeInTheDocument();
+ await userEvent.click(page.getByRole('menuitemradio', { name: 'Editor' }));
+ await expect(setGeneralAccess).not.toHaveBeenCalled();
+ await userEvent.click(page.getByRole('button', { name: 'Invite 1' }));
+ await waitFor(() =>
+ expect(setGeneralAccess).toHaveBeenCalledWith(
+ RecordShareAccessLevel.READ_WRITE,
+ ),
+ );
+ await expect(setShare).not.toHaveBeenCalled();
+ },
+};
+
+export const InviteRole: Story = {
args: {
sharingState: {
- sharing: SHARING,
+ sharing: {
+ ...SHARING,
+ shares: SHARING.shares.filter(
+ (share) => share.principalType !== RecordSharePrincipalType.ROLE,
+ ),
+ },
loading: false,
error: undefined,
- saving: true,
+ saving: false,
setGeneralAccess,
setShare,
removeShare,
@@ -207,20 +494,186 @@ export const Saving: Story = {
},
play: async ({ canvasElement }) => {
const page = within(canvasElement.ownerDocument.body);
- const addPeople = await page.findByRole('button', {
- name: 'Add people or roles',
+ await userEvent.type(
+ await page.findByPlaceholderText('Add people or everyone'),
+ 'sales',
+ );
+ await userEvent.click(page.getByRole('checkbox', { name: 'Sales' }));
+ await expect(page.getByRole('checkbox', { name: 'Sales' })).toBeChecked();
+ await expect(setShare).not.toHaveBeenCalled();
+ await userEvent.click(
+ page.getByRole('button', { name: 'Invite as Viewer' }),
+ );
+ await userEvent.click(
+ await page.findByRole('menuitemradio', { name: 'Full access' }),
+ );
+ await userEvent.click(page.getByRole('button', { name: 'Invite 1' }));
+ await waitFor(() => expect(setShare).toHaveBeenCalledTimes(1));
+ await expect(setShare).toHaveBeenCalledWith({
+ principal: { roleId: 'sales' },
+ accessLevel: RecordShareAccessLevel.FULL,
});
- await expect(addPeople).toHaveAttribute('aria-disabled', 'true');
- await userEvent.click(addPeople);
+ await expect(setGeneralAccess).not.toHaveBeenCalled();
+ },
+};
+
+export const DefaultGeneralAccess: Story = {
+ args: {
+ sharingState: {
+ sharing: {
+ ...SHARING,
+ sharingMode: RecordSharingMode.OPEN_BY_DEFAULT,
+ generalAccessLevel: RecordShareAccessLevel.READ_WRITE,
+ defaultGeneralAccessLevel: RecordShareAccessLevel.READ_WRITE,
+ },
+ loading: false,
+ error: undefined,
+ saving: false,
+ setGeneralAccess,
+ setShare,
+ removeShare,
+ refetch,
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ const generalAccess = await page.findByRole('button', {
+ name: 'Everyone with access to Chats Editor',
+ });
+ await userEvent.click(generalAccess);
await expect(
- page.queryByPlaceholderText('Search people or roles'),
+ await page.findByRole('menuitemradio', { name: 'Editor (default)' }),
+ ).toBeVisible();
+ await expect(
+ page.queryByRole('menuitemradio', { name: 'Full access' }),
).not.toBeInTheDocument();
- await userEvent.tab();
- await expect(addPeople).toHaveFocus();
- await userEvent.keyboard('{Enter}');
+ await userEvent.click(
+ page.getByRole('menuitemradio', { name: 'Restricted' }),
+ );
+ await waitFor(() =>
+ expect(setGeneralAccess).toHaveBeenLastCalledWith(
+ RecordShareAccessLevel.NONE,
+ ),
+ );
+ await userEvent.click(generalAccess);
+ await userEvent.click(
+ await page.findByRole('menuitemradio', { name: 'Viewer' }),
+ );
+ await waitFor(() =>
+ expect(setGeneralAccess).toHaveBeenLastCalledWith(
+ RecordShareAccessLevel.READ,
+ ),
+ );
await expect(
- page.queryByPlaceholderText('Search people or roles'),
+ page.getByRole('button', { name: 'Phil Schiler Editor' }),
+ ).toBeVisible();
+ await expect(setShare).not.toHaveBeenCalled();
+ await expect(removeShare).not.toHaveBeenCalled();
+ },
+};
+
+export const RetainFailedInvitations: Story = {
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ setShare.mockResolvedValueOnce(undefined);
+ const search = await page.findByPlaceholderText('Add people or everyone');
+ await userEvent.type(search, 'j');
+ await userEvent.click(page.getByRole('checkbox', { name: /Jane Austen/ }));
+ await userEvent.click(page.getByRole('checkbox', { name: /Jony Ive/ }));
+ await userEvent.click(page.getByRole('button', { name: 'Invite 2' }));
+ await waitFor(() => expect(setShare).toHaveBeenCalledTimes(2));
+ await expect(
+ await page.findByRole('checkbox', { name: /Jane Austen/ }),
+ ).toBeChecked();
+ await expect(
+ page.queryByRole('checkbox', { name: /Jony Ive/, checked: true }),
).not.toBeInTheDocument();
+ await expect(page.getByRole('button', { name: 'Invite 1' })).toBeEnabled();
+ await expect(setShare).toHaveBeenCalledTimes(2);
+ await expect(search).toHaveValue('j');
+ await userEvent.click(page.getByRole('button', { name: 'Invite 1' }));
+ await waitFor(() => expect(search).toHaveValue(''));
+ await expect(setShare).toHaveBeenCalledTimes(3);
+ await expect(setShare).toHaveBeenLastCalledWith({
+ principal: { workspaceMemberId: 'invite' },
+ accessLevel: RecordShareAccessLevel.READ,
+ });
+ await expect(page.getByText('Everyone')).toBeVisible();
+ await expect(page.queryByText('Selected')).not.toBeInTheDocument();
+ await expect(page.getByRole('button', { name: 'Invite' })).toBeDisabled();
+ },
+};
+
+export const Loading: Story = {
+ args: {
+ sharingState: {
+ sharing: undefined,
+ loading: true,
+ error: undefined,
+ saving: false,
+ setGeneralAccess,
+ setShare,
+ removeShare,
+ refetch,
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ const loading = await page.findByRole('status', {
+ name: 'Loading sharing settings',
+ });
+
+ await expect(loading).toBeVisible();
+ await expect(loading).toHaveAttribute('aria-busy', 'true');
+ await expect(page.queryByRole('searchbox')).not.toBeInTheDocument();
+ await expect(
+ page.queryByRole('button', { name: /^Invite/ }),
+ ).not.toBeInTheDocument();
+ const copyLink = page.getByRole('button', { name: 'Copy link' });
+ await expect(copyLink).toBeVisible();
+ const footer = copyLink.closest('[data-variant="compact"]');
+ await expect(footer?.getBoundingClientRect().height).toBe(40);
+ await expect(setShare).not.toHaveBeenCalled();
+ await expect(setGeneralAccess).not.toHaveBeenCalled();
+ },
+};
+
+export const Saving: Story = {
+ args: {
+ sharingState: {
+ sharing: SHARING,
+ loading: false,
+ error: undefined,
+ saving: true,
+ setGeneralAccess,
+ setShare,
+ removeShare,
+ refetch,
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ const addPeople = await page.findByPlaceholderText(
+ 'Add people or everyone',
+ );
+ await expect(addPeople).toBeDisabled();
+ await expect(page.getByRole('button', { name: 'Invite' })).toBeDisabled();
+ await userEvent.type(addPeople, 'Jane');
+ await expect(addPeople).toHaveValue('');
+ for (const name of ['Restricted', 'Sales Viewer', 'Phil Schiler Editor']) {
+ const row = page.getByRole('button', { name });
+ await expect(row).toHaveAttribute('aria-disabled', 'true');
+ await expect(
+ row.querySelector('.tabler-icon-chevron-right'),
+ ).toBeVisible();
+ await userEvent.click(row);
+ row.focus();
+ await userEvent.keyboard('{Enter} {ArrowDown}');
+ await expect(page.queryByRole('menu')).not.toBeInTheDocument();
+ }
+ await expect(setShare).not.toHaveBeenCalled();
+ await expect(setGeneralAccess).not.toHaveBeenCalled();
+ await expect(removeShare).not.toHaveBeenCalled();
},
};
@@ -242,15 +695,30 @@ export const ReadOnly: Story = {
refetch,
},
},
- play: async ({ canvasElement }) => {
+ play: async ({ canvasElement, args }) => {
const page = within(canvasElement.ownerDocument.body);
await expect(
await page.findByText(
'Only the creator of this record and people with full access to it can change who has access.',
),
).toBeVisible();
- await expect(page.queryByText('General access')).not.toBeInTheDocument();
+ await expect(page.queryByText('Everyone')).not.toBeInTheDocument();
+ await expect(page.queryByText('Roles')).not.toBeInTheDocument();
+ await expect(page.queryByText('Users')).not.toBeInTheDocument();
await expect(page.getByRole('button', { name: 'Copy link' })).toBeVisible();
+ const writeText = spyOn(
+ navigator.clipboard,
+ 'writeText',
+ ).mockResolvedValue();
+
+ try {
+ await userEvent.click(page.getByRole('button', { name: 'Copy link' }));
+ await waitFor(() =>
+ expect(writeText).toHaveBeenCalledWith(args.recordUrl),
+ );
+ } finally {
+ writeText.mockRestore();
+ }
},
};
@@ -272,6 +740,61 @@ export const LoadError: Story = {
await expect(await page.findByRole('alert')).toHaveTextContent(
'Sharing settings could not be loaded.',
);
- await expect(page.getByText('Try again')).toBeVisible();
+ const retry = page.getByRole('button', { name: 'Try again' });
+ await userEvent.tab();
+ await expect(retry).toHaveFocus();
+ await userEvent.keyboard('{Enter}');
+ await expect(refetch).toHaveBeenCalledTimes(1);
+ await userEvent.click(retry);
+ await expect(refetch).toHaveBeenCalledTimes(2);
+ },
+};
+
+export const ManagedAccess: Story = {
+ args: {
+ sharingState: {
+ sharing: {
+ ...SHARING,
+ hasManagedGeneralAccess: true,
+ shares: SHARING.shares.map((share) =>
+ share.principalType === RecordSharePrincipalType.ROLE
+ ? { ...share, rowCause: RecordShareRowCause.APPLICATION }
+ : share,
+ ),
+ },
+ loading: false,
+ error: undefined,
+ saving: false,
+ setGeneralAccess,
+ setShare,
+ removeShare,
+ refetch,
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await expect(await page.findByText('Owner')).toBeVisible();
+ await expect(page.getByText('Managed access')).toBeVisible();
+ await expect(
+ page.getByText('Workspace access is also managed by an application.'),
+ ).toBeVisible();
+ await expect(
+ page.queryByRole('button', { name: /^Sales/ }),
+ ).not.toBeInTheDocument();
+ await expect(
+ page.queryByRole('button', { name: /^You/ }),
+ ).not.toBeInTheDocument();
+ await userEvent.click(
+ page.getByRole('button', { name: 'Phil Schiler Editor' }),
+ );
+ await userEvent.click(
+ await page.findByRole('menuitem', { name: 'Remove access' }),
+ );
+ await waitFor(() =>
+ expect(removeShare).toHaveBeenCalledWith({
+ principal: { workspaceMemberId: 'member' },
+ }),
+ );
+ await expect(setShare).not.toHaveBeenCalled();
},
};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__tests__/SidePanelShareRecordContent.test.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__tests__/SidePanelShareRecordContent.test.tsx
index 1e07f8defa1..54dda02d7a8 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__tests__/SidePanelShareRecordContent.test.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__tests__/SidePanelShareRecordContent.test.tsx
@@ -1,7 +1,6 @@
import { i18n } from '@lingui/core';
import { I18nProvider } from '@lingui/react';
import { render, screen, waitFor } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
import { Provider as JotaiProvider } from 'jotai';
import { type ReactNode } from 'react';
import { MemoryRouter } from 'react-router-dom';
@@ -15,6 +14,8 @@ import {
} from '~/generated-metadata/graphql';
import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMembersState';
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
+import { mockCurrentWorkspace } from '~/testing/mock-data/users';
import { SidePanelShareRecordContent } from '@/side-panel/pages/share-record/components/SidePanelShareRecordContent';
import {
jotaiStore,
@@ -70,10 +71,12 @@ const Wrapper = ({ children }: { children: ReactNode }) => (
const renderSharing = ({
sharingOverrides = {},
sharingReach = ObjectSharingReach.WORKSPACE,
+ isLoading = false,
error,
}: {
sharingOverrides?: Partial<RecordSharingFieldsFragment>;
sharingReach?: ObjectSharingReach;
+ isLoading?: boolean;
error?: Error;
} = {}) =>
render(
@@ -87,7 +90,7 @@ const renderSharing = ({
setShare,
removeShare,
refetch,
- loading: false,
+ loading: isLoading,
saving: false,
error,
}}
@@ -102,6 +105,10 @@ describe('Share record side panel', () => {
jest.clearAllMocks();
refetch.mockResolvedValue(undefined);
resetJotaiStore();
+ jotaiStore.set(currentWorkspaceState.atom, {
+ ...mockCurrentWorkspace,
+ displayName: 'Acme',
+ });
jotaiStore.set(currentWorkspaceMembersState.atom, [
{
id: 'alice-member',
@@ -111,71 +118,6 @@ describe('Share record side panel', () => {
]);
});
- it('finds a workspace member by email and grants viewing access', async () => {
- const user = userEvent.setup();
- renderSharing();
- await user.click(
- screen.getByRole('button', { name: 'Add people or roles' }),
- );
- await user.type(
- screen.getByPlaceholderText('Search people or roles'),
- 'alice@',
- );
- expect(screen.queryByText('Sales')).toBeNull();
- await user.click(screen.getByText('Alice Smith'));
- expect(setShare).toHaveBeenCalledWith({
- principal: { workspaceMemberId: 'alice-member' },
- accessLevel: RecordShareAccessLevel.READ,
- });
- });
-
- it('finds a role by name and grants viewing access', async () => {
- const user = userEvent.setup();
- renderSharing();
- await user.click(
- screen.getByRole('button', { name: 'Add people or roles' }),
- );
- await user.type(
- screen.getByPlaceholderText('Search people or roles'),
- 'sales',
- );
- expect(screen.queryByText('Alice Smith')).toBeNull();
- await user.click(screen.getByText('Sales'));
- expect(setShare).toHaveBeenCalledWith({
- principal: { roleId: 'sales-role' },
- accessLevel: RecordShareAccessLevel.READ,
- });
- });
-
- it('enables workspace-wide viewing through the general access', async () => {
- const user = userEvent.setup();
- renderSharing();
- await user.click(screen.getByRole('button', { name: 'Restricted' }));
- await user.click(screen.getByRole('menuitemradio', { name: 'Viewer' }));
- expect(setGeneralAccess).toHaveBeenCalledWith(RecordShareAccessLevel.READ);
- expect(setShare).not.toHaveBeenCalled();
- });
-
- it('returns to restricted access without removing named recipients', async () => {
- const user = userEvent.setup();
- renderSharing({
- sharingOverrides: {
- generalAccessLevel: RecordShareAccessLevel.READ,
- shares: [buildShare({})],
- },
- });
- await user.click(
- screen.getByRole('button', {
- name: /^Everyone with access to Companies/,
- }),
- );
- await user.click(
- screen.getByRole('menuitemradio', { name: 'Restricted (default)' }),
- );
- expect(setGeneralAccess).toHaveBeenCalledWith(RecordShareAccessLevel.NONE);
- expect(removeShare).not.toHaveBeenCalled();
- });
-
it('shows workspace access managed by an application', async () => {
renderSharing({ sharingOverrides: { hasManagedGeneralAccess: true } });
await waitFor(() =>
@@ -188,6 +130,20 @@ describe('Share record side panel', () => {
).toBeVisible();
});
+ it('keeps loaded sharing controls available during a refresh', async () => {
+ renderSharing({ isLoading: true });
+
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'Restricted' })).toBeVisible(),
+ );
+ expect(
+ screen.getByRole('searchbox', { name: 'Add people or everyone' }),
+ ).toBeVisible();
+ expect(
+ screen.queryByRole('status', { name: 'Loading sharing settings' }),
+ ).toBeNull();
+ });
+
it('hides management when the server says the viewer cannot manage sharing', async () => {
renderSharing({
sharingOverrides: { canManageSharing: false, roles: [] },
@@ -201,67 +157,11 @@ describe('Share record side panel', () => {
);
expect(screen.queryByText('General access')).toBeNull();
expect(
- screen.queryByRole('button', { name: 'Add people or roles' }),
+ screen.queryByRole('searchbox', { name: 'Add people or everyone' }),
).toBeNull();
expect(screen.getByText('Copy link')).toBeVisible();
});
- it('supports keyboard selection and reports empty searches', async () => {
- const user = userEvent.setup();
- renderSharing();
- await user.click(
- screen.getByRole('button', { name: 'Add people or roles' }),
- );
- const input = screen.getByPlaceholderText('Search people or roles');
- await user.type(input, 'no match');
- expect(screen.getByText('No matching people or roles')).toBeVisible();
- await user.clear(input);
- await user.type(input, 'sales');
- await user.keyboard('{ArrowDown}');
- await user.keyboard('{ArrowDown}');
- expect(screen.getByRole('button', { name: 'Sales Role' })).toHaveFocus();
- await user.keyboard('{Enter}');
- expect(setShare).toHaveBeenCalledWith({
- principal: { roleId: 'sales-role' },
- accessLevel: RecordShareAccessLevel.READ,
- });
- });
-
- it('keeps invitations out of the main menu and removes access through the recipient submenu', async () => {
- const user = userEvent.setup();
- renderSharing({ sharingOverrides: { shares: [buildShare({})] } });
- expect(screen.queryByPlaceholderText('Search people or roles')).toBeNull();
- expect(screen.queryByText('Remove access')).toBeNull();
- await user.click(
- screen.getByRole('button', { name: 'Alice Smith Viewer' }),
- );
- await user.click(screen.getByRole('menuitem', { name: 'Remove access' }));
- expect(removeShare).toHaveBeenCalledWith({
- principal: { workspaceMemberId: 'alice-member' },
- });
- expect(setShare).not.toHaveBeenCalled();
- });
-
- it('copies the supplied record link', async () => {
- const user = userEvent.setup();
- renderSharing();
- await user.click(screen.getByRole('button', { name: 'Copy link' }));
- expect(copyToClipboard).toHaveBeenCalledWith('https://example.com/record');
- });
-
- it('shows a retry action when settings cannot be loaded', async () => {
- const user = userEvent.setup();
- renderSharing({ error: new Error('offline') });
- expect(screen.getByRole('alert')).toHaveTextContent(
- 'Sharing settings could not be loaded.',
- );
- await user.click(screen.getByText('Try again'));
- expect(refetch).toHaveBeenCalledTimes(1);
- expect(
- screen.queryByRole('button', { name: 'Add people or roles' }),
- ).toBeNull();
- });
-
it('shows application and owner grants without offering to revoke them', async () => {
renderSharing({
sharingOverrides: {
@@ -298,128 +198,18 @@ describe('Share record side panel', () => {
it.each([
[
- 'Alice Smith',
- { workspaceMemberId: 'alice-member' },
- 'Editor',
- RecordShareAccessLevel.READ_WRITE,
- ],
- [
- 'Sales',
- { roleId: 'sales-role' },
- 'Editor',
- RecordShareAccessLevel.READ_WRITE,
- ],
- [
- 'Alice Smith',
- { workspaceMemberId: 'alice-member' },
- 'Full access',
- RecordShareAccessLevel.FULL,
- ],
- [
- 'Sales',
- { roleId: 'sales-role' },
- 'Full access',
- RecordShareAccessLevel.FULL,
- ],
- ])(
- 'can invite %s as %s',
- async (label, principal, accessLabel, accessLevel) => {
- const user = userEvent.setup();
- renderSharing();
- await user.click(
- screen.getByRole('button', { name: 'Add people or roles' }),
- );
- await user.click(
- screen.getByRole('button', { name: 'Invitation access' }),
- );
- await user.click(
- screen.getByRole('menuitemradio', { name: accessLabel }),
- );
- await user.keyboard('{Escape}');
- await user.click(screen.getByText(label));
- expect(setShare).toHaveBeenCalledWith({ principal, accessLevel });
- },
- );
-
- it.each([
- [
- 'Alice Smith',
- RecordSharePrincipalType.WORKSPACE_MEMBER,
- 'alice-member',
- { workspaceMemberId: 'alice-member' },
- ],
- [
- 'Sales',
- RecordSharePrincipalType.ROLE,
- 'sales-role',
- { roleId: 'sales-role' },
+ ObjectSharingReach.WORKSPACE,
+ "People you add get this record even if their role can't access Companies. Field permissions still apply.",
],
+ [ObjectSharingReach.ROLE_ACCESS, 'Role and field permissions still apply.'],
])(
- 'can upgrade and downgrade %s without removing their grant',
- async (label, principalType, principalId, principal) => {
- const user = userEvent.setup();
- const share = buildShare({ principalType, principalId });
- const view = renderSharing({ sharingOverrides: { shares: [share] } });
- await user.click(
- screen.getByRole('button', { name: new RegExp(`^${label}`) }),
- );
- await user.click(screen.getByText('Full access'));
- expect(setShare).toHaveBeenLastCalledWith({
- principal,
- accessLevel: RecordShareAccessLevel.FULL,
- });
- view.unmount();
- renderSharing({
- sharingOverrides: {
- shares: [{ ...share, accessLevel: RecordShareAccessLevel.FULL }],
- },
- });
- await user.click(
- screen.getByRole('button', { name: new RegExp(`^${label}`) }),
- );
- await user.click(screen.getAllByText('Viewer').at(-1)!);
- expect(setShare).toHaveBeenLastCalledWith({
- principal,
- accessLevel: RecordShareAccessLevel.READ,
- });
- expect(removeShare).not.toHaveBeenCalled();
+ 'tells managers what adding people grants when sharing reach is %s',
+ async (sharingReach, notice) => {
+ renderSharing({ sharingReach });
+ await waitFor(() => expect(screen.getByText(notice)).toBeVisible());
},
);
- it('can upgrade and downgrade the general access, but never to full access', async () => {
- const user = userEvent.setup();
- const view = renderSharing({
- sharingOverrides: { generalAccessLevel: RecordShareAccessLevel.READ },
- });
- await user.click(
- screen.getByRole('button', {
- name: /^Everyone with access to Companies/,
- }),
- );
- expect(
- screen.queryByRole('menuitemradio', { name: 'Full access' }),
- ).toBeNull();
- await user.click(screen.getByRole('menuitemradio', { name: 'Editor' }));
- expect(setGeneralAccess).toHaveBeenLastCalledWith(
- RecordShareAccessLevel.READ_WRITE,
- );
- view.unmount();
- renderSharing({
- sharingOverrides: {
- generalAccessLevel: RecordShareAccessLevel.READ_WRITE,
- },
- });
- await user.click(
- screen.getByRole('button', {
- name: /^Everyone with access to Companies/,
- }),
- );
- await user.click(screen.getByRole('menuitemradio', { name: 'Viewer' }));
- expect(setGeneralAccess).toHaveBeenLastCalledWith(
- RecordShareAccessLevel.READ,
- );
- });
-
it('tells viewers of a record open by default who can change its access', async () => {
renderSharing({
sharingOverrides: {
@@ -457,27 +247,6 @@ describe('Share record side panel', () => {
expect(screen.queryByText(/Only the creator of this record/)).toBeNull();
});
- it('marks the default access the server reports and lets owners restrict it', async () => {
- const user = userEvent.setup();
- renderSharing({
- sharingOverrides: {
- sharingMode: RecordSharingMode.OPEN_BY_DEFAULT,
- generalAccessLevel: RecordShareAccessLevel.READ_WRITE,
- defaultGeneralAccessLevel: RecordShareAccessLevel.READ_WRITE,
- },
- });
- await user.click(
- screen.getByRole('button', {
- name: 'Everyone with access to Companies Editor',
- }),
- );
- expect(
- screen.getByRole('menuitemradio', { name: 'Editor (default)' }),
- ).toBeVisible();
- await user.click(screen.getByRole('menuitemradio', { name: 'Restricted' }));
- expect(setGeneralAccess).toHaveBeenCalledWith(RecordShareAccessLevel.NONE);
- });
-
it.each([
[
ObjectSharingReach.WORKSPACE,
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/hooks/__tests__/useSidePanelShareRecordInvitation.test.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/hooks/__tests__/useSidePanelShareRecordInvitation.test.tsx
new file mode 100644
index 00000000000..65a1c2feaf2
--- /dev/null
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/hooks/__tests__/useSidePanelShareRecordInvitation.test.tsx
@@ -0,0 +1,92 @@
+import { i18n } from '@lingui/core';
+import { I18nProvider } from '@lingui/react';
+import { act, renderHook } from '@testing-library/react';
+import { createStore, Provider as JotaiProvider } from 'jotai';
+import { type ReactNode } from 'react';
+
+import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMembersState';
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
+import { useSidePanelShareRecordInvitation } from '@/side-panel/pages/share-record/hooks/useSidePanelShareRecordInvitation';
+import {
+ RecordShareAccessLevel,
+ RecordSharingMode,
+ type RecordSharingFieldsFragment,
+} from '~/generated-metadata/graphql';
+import { mockCurrentWorkspace } from '~/testing/mock-data/users';
+
+const RESTRICTED_SHARING: RecordSharingFieldsFragment = {
+ sharingMode: RecordSharingMode.PRIVATE,
+ canManageSharing: true,
+ permissions: {
+ canRead: true,
+ canUpdate: true,
+ canDelete: true,
+ canSoftDelete: true,
+ },
+ generalAccessLevel: RecordShareAccessLevel.NONE,
+ defaultGeneralAccessLevel: RecordShareAccessLevel.NONE,
+ hasManagedGeneralAccess: false,
+ roles: [],
+ shares: [],
+};
+
+const setShare = jest.fn();
+const setGeneralAccess = jest.fn();
+
+const renderInvitation = () => {
+ const store = createStore();
+ store.set(currentWorkspaceState.atom, {
+ ...mockCurrentWorkspace,
+ displayName: 'Acme',
+ });
+ store.set(currentWorkspaceMembersState.atom, []);
+
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <JotaiProvider store={store}>
+ <I18nProvider i18n={i18n}>{children}</I18nProvider>
+ </JotaiProvider>
+ );
+
+ return renderHook(
+ ({ sharing }: { sharing: RecordSharingFieldsFragment }) =>
+ useSidePanelShareRecordInvitation({
+ sharing,
+ saving: false,
+ setShare,
+ setGeneralAccess,
+ objectLabelPlural: 'Companies',
+ }),
+ { initialProps: { sharing: RESTRICTED_SHARING }, wrapper: Wrapper },
+ );
+};
+
+describe('useSidePanelShareRecordInvitation', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('drops a staged Everyone recipient once the record gains workspace access', async () => {
+ const { result, rerender } = renderInvitation();
+ const everyoneRecipients = result.current.recipients.filter(
+ (recipient) => recipient.kind === 'everyone',
+ );
+
+ act(() => {
+ result.current.onRecipientsChange(everyoneRecipients);
+ });
+
+ expect(result.current.hasEveryoneRecipient).toBe(true);
+
+ rerender({
+ sharing: {
+ ...RESTRICTED_SHARING,
+ generalAccessLevel: RecordShareAccessLevel.READ,
+ },
+ });
+
+ expect(result.current.selectedRecipients).toEqual([]);
+ expect(result.current.hasEveryoneRecipient).toBe(false);
+ await expect(result.current.onInvite()).resolves.toBe(false);
+ expect(setGeneralAccess).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/hooks/useSidePanelShareRecordInvitation.ts b/packages/twenty-front/src/modules/side-panel/pages/share-record/hooks/useSidePanelShareRecordInvitation.ts
new file mode 100644
index 00000000000..d50d4910f67
--- /dev/null
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/hooks/useSidePanelShareRecordInvitation.ts
@@ -0,0 +1,162 @@
+import { useLingui } from '@lingui/react/macro';
+import { useState } from 'react';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMembersState';
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
+import { type useRecordSharing } from '@/object-record/record-sharing/hooks/useRecordSharing';
+import { type RecordSharingInvitationRecipient } from '@/object-record/record-sharing/types/RecordSharingInvitationRecipient';
+import { getRecordSharingGeneralAccess } from '@/object-record/record-sharing/utils/getRecordSharingGeneralAccess';
+import { getRecordSharingInvitationRecipients } from '@/object-record/record-sharing/utils/getRecordSharingInvitationRecipients';
+import { isSameRecordSharingInvitationRecipient } from '@/object-record/record-sharing/utils/isSameRecordSharingInvitationRecipient';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { RecordShareAccessLevel } from '~/generated-metadata/graphql';
+
+const DEFAULT_INVITATION_ACCESS_LEVEL = RecordShareAccessLevel.READ;
+
+type UseSidePanelShareRecordInvitationProps = Pick<
+ ReturnType<typeof useRecordSharing>,
+ 'sharing' | 'saving' | 'setShare' | 'setGeneralAccess'
+> & {
+ objectLabelPlural: string;
+};
+
+export const useSidePanelShareRecordInvitation = ({
+ sharing,
+ saving,
+ setShare,
+ setGeneralAccess,
+ objectLabelPlural,
+}: UseSidePanelShareRecordInvitationProps) => {
+ const { t } = useLingui();
+ const currentWorkspace = useAtomStateValue(currentWorkspaceState);
+ const currentWorkspaceMembers = useAtomStateValue(
+ currentWorkspaceMembersState,
+ );
+ const [stagedRecipients, setStagedRecipients] = useState<
+ RecordSharingInvitationRecipient[]
+ >([]);
+ const [accessLevel, setAccessLevel] = useState(
+ DEFAULT_INVITATION_ACCESS_LEVEL,
+ );
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const canInvite = sharing?.canManageSharing ?? false;
+ const isBusy = isSubmitting || saving;
+ const workspaceName = currentWorkspace?.displayName ?? '';
+ const { hasGeneralAccess, label: generalAccessLabel } =
+ getRecordSharingGeneralAccess({ sharing, objectLabelPlural });
+ const generalAccess = {
+ hasGeneralAccess,
+ label: t(generalAccessLabel),
+ workspaceName,
+ };
+ const everyoneRecipients: RecordSharingInvitationRecipient[] =
+ isDefined(sharing) && isDefined(currentWorkspace) && !hasGeneralAccess
+ ? [
+ {
+ kind: 'everyone',
+ id: currentWorkspace.id,
+ label: generalAccess.label,
+ },
+ ]
+ : [];
+ const recipients = [
+ ...getRecordSharingInvitationRecipients({
+ workspaceMembers: currentWorkspaceMembers,
+ shares: sharing?.shares ?? [],
+ roles: sharing?.roles ?? [],
+ roleLabel: t`Role`,
+ }),
+ ...everyoneRecipients,
+ ];
+ const selectedRecipients = stagedRecipients.filter((stagedRecipient) =>
+ recipients.some((recipient) =>
+ isSameRecordSharingInvitationRecipient({
+ recipient,
+ otherRecipient: stagedRecipient,
+ }),
+ ),
+ );
+ const hasEveryoneRecipient = selectedRecipients.some(
+ (recipient) => recipient.kind === 'everyone',
+ );
+ const hasInvalidAccessLevel =
+ accessLevel === RecordShareAccessLevel.NONE ||
+ (hasEveryoneRecipient && accessLevel === RecordShareAccessLevel.FULL);
+
+ const onRecipientsChange = (
+ nextRecipients: RecordSharingInvitationRecipient[],
+ ) => {
+ if (isBusy || !canInvite) {
+ return;
+ }
+
+ setStagedRecipients(nextRecipients);
+ };
+
+ const onAccessLevelChange = (nextAccessLevel: RecordShareAccessLevel) => {
+ if (isBusy || !canInvite) {
+ return;
+ }
+
+ setAccessLevel(nextAccessLevel);
+ };
+
+ const inviteRecipient = (recipient: RecordSharingInvitationRecipient) => {
+ if (recipient.kind === 'everyone') {
+ return setGeneralAccess(accessLevel);
+ }
+
+ const principal =
+ recipient.kind === 'role'
+ ? { roleId: recipient.id }
+ : { workspaceMemberId: recipient.id };
+
+ return setShare({ principal, accessLevel });
+ };
+
+ const onInvite = async (): Promise<boolean> => {
+ if (
+ isBusy ||
+ !canInvite ||
+ !isNonEmptyArray(selectedRecipients) ||
+ hasInvalidAccessLevel
+ ) {
+ return false;
+ }
+
+ setIsSubmitting(true);
+
+ const failedRecipients: RecordSharingInvitationRecipient[] = [];
+
+ try {
+ for (const recipient of selectedRecipients) {
+ const updatedSharing = await inviteRecipient(recipient);
+
+ if (!isDefined(updatedSharing)) {
+ failedRecipients.push(recipient);
+ }
+ }
+
+ setStagedRecipients(failedRecipients);
+
+ return !isNonEmptyArray(failedRecipients);
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ return {
+ recipients,
+ selectedRecipients,
+ accessLevel,
+ generalAccess,
+ hasEveryoneRecipient,
+ hasInvalidAccessLevel,
+ canInvite,
+ isSubmitting: isBusy,
+ onRecipientsChange,
+ onAccessLevelChange,
+ onInvite,
+ };
+};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/hooks/useSidePanelShareRecordSearch.ts b/packages/twenty-front/src/modules/side-panel/pages/share-record/hooks/useSidePanelShareRecordSearch.ts
new file mode 100644
index 00000000000..eb2761e17e5
--- /dev/null
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/hooks/useSidePanelShareRecordSearch.ts
@@ -0,0 +1,45 @@
+import { useState } from 'react';
+
+import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
+import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMembersState';
+import { type useRecordSharing } from '@/object-record/record-sharing/hooks/useRecordSharing';
+import { type RecordSharingInvitationRecipient } from '@/object-record/record-sharing/types/RecordSharingInvitationRecipient';
+import { getRecordSharingSearchResults } from '@/object-record/record-sharing/utils/getRecordSharingSearchResults';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+
+type UseSidePanelShareRecordSearchProps = {
+ sharing: ReturnType<typeof useRecordSharing>['sharing'];
+ recipients: RecordSharingInvitationRecipient[];
+ selectedRecipients: RecordSharingInvitationRecipient[];
+ generalAccess: Parameters<
+ typeof getRecordSharingSearchResults
+ >[0]['generalAccess'];
+};
+
+export const useSidePanelShareRecordSearch = ({
+ sharing,
+ recipients,
+ selectedRecipients,
+ generalAccess,
+}: UseSidePanelShareRecordSearchProps) => {
+ const [search, setSearch] = useState('');
+ const currentWorkspaceMembers = useAtomStateValue(
+ currentWorkspaceMembersState,
+ );
+ const currentWorkspaceMember = useAtomStateValue(currentWorkspaceMemberState);
+ const searchResults = getRecordSharingSearchResults({
+ search,
+ sharing,
+ workspaceMembers: currentWorkspaceMembers,
+ currentWorkspaceMember,
+ recipients,
+ selectedRecipients,
+ generalAccess,
+ });
+
+ return {
+ search,
+ onSearchChange: setSearch,
+ ...searchResults,
+ };
+};
diff --git a/packages/twenty-front/src/modules/ui/layout/dropdown/constants/GenericDropdownContentWidth.ts b/packages/twenty-front/src/modules/ui/layout/dropdown/constants/GenericDropdownContentWidth.ts
index d03c61fa449..f3dcc44862a 100644
--- a/packages/twenty-front/src/modules/ui/layout/dropdown/constants/GenericDropdownContentWidth.ts
+++ b/packages/twenty-front/src/modules/ui/layout/dropdown/constants/GenericDropdownContentWidth.ts
@@ -3,4 +3,5 @@ export enum GenericDropdownContentWidth {
Medium = 200,
Large = 240,
ExtraLarge = 320,
+ ExtraExtraLarge = 400,
}
diff --git a/packages/twenty-front/src/modules/ui/layout/side-panel/components/SidePanelFooter.tsx b/packages/twenty-front/src/modules/ui/layout/side-panel/components/SidePanelFooter.tsx
index af2a21b1ac2..00148e825b2 100644
--- a/packages/twenty-front/src/modules/ui/layout/side-panel/components/SidePanelFooter.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/side-panel/components/SidePanelFooter.tsx
@@ -11,6 +11,17 @@ const StyledContainer = styled.div`
box-sizing: border-box;
padding: ${themeCssVariables.spacing[2]} ${themeCssVariables.spacing[3]};
width: 100%;
+
+ &[data-variant='compact'] {
+ align-items: center;
+ backdrop-filter: blur(${themeCssVariables.spacing[5]});
+ background: ${themeCssVariables.background.transparent.primary};
+ border-top-color: ${themeCssVariables.border.color.medium};
+ display: flex;
+ flex-shrink: 0;
+ height: ${themeCssVariables.spacing[10]};
+ padding: ${themeCssVariables.spacing[2]};
+ }
`;
const StyledActionsRow = styled(NodeDimension)`
@@ -23,9 +34,13 @@ const StyledActionsRow = styled(NodeDimension)`
type SidePanelFooterProps = {
actions: React.ReactNode[];
+ variant?: 'default' | 'compact';
};
-export const SidePanelFooter = ({ actions }: SidePanelFooterProps) => {
+export const SidePanelFooter = ({
+ actions,
+ variant = 'default',
+}: SidePanelFooterProps) => {
const [actionsRowWidth, setActionsRowWidth] = useState(0);
const handleActionsRowDimensionChange = useCallback(
@@ -36,7 +51,7 @@ export const SidePanelFooter = ({ actions }: SidePanelFooterProps) => {
);
return (
- <StyledContainer>
+ <StyledContainer data-variant={variant}>
<SidePanelFooterWidthContext.Provider value={actionsRowWidth}>
<StyledActionsRow onDimensionChange={handleActionsRowDimensionChange}>
{actions.map((action, index) => (