Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/screens/chat/ChatChannelCreatePage.tsx
T

418 lines
18 KiB
TypeScript

import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherArrowLeft, FeatherHash, FeatherMessageCircle, FeatherPlus, FeatherUsers } from "@subframe/core";
import type { ChatChannelCreateMode, ChatChannelCreateSubmission, ChatChannelCreateVM, ChatGroupPrivacy } from "@hivegrid/view-models";
import { Alert } from "~/ui/components/Alert";
import { Avatar } from "~/ui/components/Avatar";
import { Button } from "~/ui/components/Button";
import { ButtonGroup } from "~/ui/components/ButtonGroup";
import { Card } from "~/ui/components/Card";
import { Checkbox } from "~/ui/components/Checkbox";
import { EmptyState } from "~/ui/components/EmptyState";
import { LoadingIndicatorSkeleton } from "~/ui/components/LoadingIndicatorSkeleton";
import { Select } from "~/ui/components/Select";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { ChatSwitch } from "./ChatSwitch";
export type ChatChannelCreateActions = {
readonly onCancel: () => void;
readonly onCreate: (submission: ChatChannelCreateSubmission) => void | Promise<void>;
readonly onRetry: () => void | Promise<void>;
};
export type ChatChannelCreatePageProps = {
readonly vm: ChatChannelCreateVM;
readonly actions: ChatChannelCreateActions;
readonly busy?: boolean;
readonly actionErrorKey?: string | null;
};
function CreateShell({ children, actions }: { readonly children: React.ReactNode; readonly actions?: React.ReactNode }): React.JSX.Element {
const { t } = useTranslation();
return (
<PageShell uiId="ui.chat.channelCreate" className="mobile:[&_button]:min-h-11 mobile:[&_button]:min-w-11">
<PageHeader
icon={<FeatherMessageCircle className={PAGE_HEADER_ICON_CLASS} />}
title={t("chat.channelCreate.title")}
subtitle={t("chat.channelCreate.subtitle")}
actions={actions}
uiId="ui.chat.channelCreate.header"
/>
<PageBody>{children}</PageBody>
</PageShell>
);
}
export function ChatChannelCreatePage({ vm, actions, busy = false, actionErrorKey = null }: ChatChannelCreatePageProps): React.JSX.Element {
const { t } = useTranslation();
const readyData = vm.status === "ready" ? vm.data : null;
const initialMode = readyData?.selectedMode ?? null;
const initialGroupForm = readyData?.form?.mode === "group" ? readyData.form : null;
const initialDmForm = readyData?.form?.mode === "dm" ? readyData.form : null;
const [mode, setMode] = useState<ChatChannelCreateMode | null>(initialMode);
const [name, setName] = useState(initialGroupForm?.name ?? "");
const [description, setDescription] = useState(initialGroupForm?.description ?? "");
const [privacy, setPrivacy] = useState<ChatGroupPrivacy>(initialGroupForm?.privacy ?? "public");
const [initialUserIds, setInitialUserIds] = useState<readonly string[]>(initialGroupForm?.initialUserIds ?? []);
const [initialGroupIds, setInitialGroupIds] = useState<readonly string[]>(initialGroupForm?.initialGroupIds ?? []);
const [syncGroupMembership, setSyncGroupMembership] = useState(initialGroupForm?.syncGroupMembership ?? false);
const [peerUserId, setPeerUserId] = useState(initialDmForm?.peerUserId ?? "");
const [localErrorKey, setLocalErrorKey] = useState<string | null>(null);
const groupTabRef = useRef<HTMLButtonElement | null>(null);
const dmTabRef = useRef<HTMLButtonElement | null>(null);
useEffect(() => {
if (!readyData) return;
setMode(readyData.selectedMode);
if (readyData.form?.mode === "group") {
setName(readyData.form.name);
setDescription(readyData.form.description);
setPrivacy(readyData.form.privacy);
setInitialUserIds(readyData.form.initialUserIds);
setInitialGroupIds(readyData.form.initialGroupIds);
setSyncGroupMembership(readyData.form.syncGroupMembership);
} else if (readyData.form?.mode === "dm") {
setPeerUserId(readyData.form.peerUserId ?? "");
}
setLocalErrorKey(null);
}, [readyData]);
const selectedUserIds = useMemo(() => new Set(initialUserIds), [initialUserIds]);
const selectedGroupIds = useMemo(() => new Set(initialGroupIds), [initialGroupIds]);
const canSubmit = mode === "group" ? name.trim().length > 0 : mode === "dm" ? peerUserId.length > 0 : false;
function selectMode(nextMode: ChatChannelCreateMode, focus = false): void {
setMode(nextMode);
setLocalErrorKey(null);
if (focus) requestAnimationFrame(() => (nextMode === "group" ? groupTabRef.current : dmTabRef.current)?.focus());
}
function handleModeKeyDown(event: React.KeyboardEvent<HTMLButtonElement>, currentMode: ChatChannelCreateMode): void {
if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
event.preventDefault();
const allowed = readyData?.allowedModes ?? [];
if (allowed.length < 2) return;
const currentIndex = allowed.indexOf(currentMode);
const nextIndex =
event.key === "Home"
? 0
: event.key === "End"
? allowed.length - 1
: event.key === "ArrowRight"
? (currentIndex + 1) % allowed.length
: (currentIndex - 1 + allowed.length) % allowed.length;
const nextMode = allowed[nextIndex];
if (nextMode) selectMode(nextMode, true);
}
const submit = () => {
if (mode === "group") {
if (!name.trim()) {
setLocalErrorKey("chat.channelCreate.validation.groupNameRequired");
return;
}
setLocalErrorKey(null);
void actions.onCreate({
mode: "group",
name: name.trim(),
description: description.trim() || null,
privacy,
initialUserIds: [...new Set(initialUserIds)],
initialGroupIds: [...new Set(initialGroupIds)],
syncGroupMembership: syncGroupMembership && initialGroupIds.length > 0,
});
return;
}
if (mode === "dm") {
if (!peerUserId) {
setLocalErrorKey("chat.channelCreate.validation.dmPeerRequired");
return;
}
setLocalErrorKey(null);
void actions.onCreate({ mode: "dm", peerUserId });
}
};
const headerActions = (
<ButtonGroup align="end">
<Button variant="tertiary" icon={<FeatherArrowLeft />} onClick={actions.onCancel} disabled={busy}>
{t("chat.channelCreate.actions.cancel")}
</Button>
{readyData?.allowedModes.length ? (
<Button icon={<FeatherPlus />} onClick={submit} disabled={!canSubmit || busy} loading={busy} data-ui-id="ui.chat.channelCreate.submit">
{t(mode === "dm" ? "chat.channelCreate.actions.startDm" : "chat.channelCreate.actions.createGroup")}
</Button>
) : null}
</ButtonGroup>
);
if (vm.status === "idle" || vm.status === "loading") {
return (
<CreateShell actions={headerActions}>
<LoadingIndicatorSkeleton variant="card" role="status" aria-label={t("chat.channelCreate.users.loading")} data-ui-id="ui.chat.channelCreate.loading" />
</CreateShell>
);
}
if (vm.status === "error") {
return (
<CreateShell actions={headerActions}>
<EmptyState
outlined
variant="error"
title={t("shared.error")}
body={t(vm.error.messageKey)}
action={
<Button variant="tertiary" onClick={() => void actions.onRetry()}>
{t("shared.retry")}
</Button>
}
data-ui-id="ui.chat.channelCreate.error"
/>
</CreateShell>
);
}
if (vm.status === "empty" || !readyData || readyData.allowedModes.length === 0 || !mode) {
return (
<CreateShell actions={headerActions}>
<EmptyState
outlined
title={t(readyData?.keys.noAllowedModesKey ?? "chat.channelCreate.permissions.none")}
body={t("chat.channelCreate.permissions.noneBody")}
action={
<Button variant="tertiary" onClick={actions.onCancel}>
{t("chat.channelCreate.actions.backToChat")}
</Button>
}
data-ui-id="ui.chat.channelCreate.permissionDenied"
/>
</CreateShell>
);
}
return (
<CreateShell actions={headerActions}>
{actionErrorKey || localErrorKey ? (
<Alert
variant="error"
notDismissible
title={t("chat.channelCreate.errors.title")}
description={t(actionErrorKey ?? localErrorKey ?? "chat.errors.invalidInput")}
data-ui-id="ui.chat.channelCreate.actionError"
/>
) : null}
{readyData.allowedModes.length > 1 ? (
<ButtonGroup role="tablist" aria-label={t("chat.channelCreate.mode.label")} data-ui-id="ui.chat.channelCreate.modeTabs">
{readyData.allowedModes.includes("group") ? (
<Button
ref={groupTabRef}
role="tab"
id="chat-channel-create-tab-group"
aria-controls="chat-channel-create-panel-group"
aria-selected={mode === "group"}
tabIndex={mode === "group" ? 0 : -1}
variant={mode === "group" ? "secondary" : "tertiary"}
icon={<FeatherUsers />}
onClick={() => selectMode("group")}
onKeyDown={(event) => handleModeKeyDown(event, "group")}
>
{t(readyData.keys.groupModeKey)}
</Button>
) : null}
{readyData.allowedModes.includes("dm") ? (
<Button
ref={dmTabRef}
role="tab"
id="chat-channel-create-tab-dm"
aria-controls="chat-channel-create-panel-dm"
aria-selected={mode === "dm"}
tabIndex={mode === "dm" ? 0 : -1}
variant={mode === "dm" ? "secondary" : "tertiary"}
icon={<FeatherMessageCircle />}
onClick={() => selectMode("dm")}
onKeyDown={(event) => handleModeKeyDown(event, "dm")}
>
{t(readyData.keys.dmModeKey)}
</Button>
) : null}
</ButtonGroup>
) : null}
{mode === "group" ? (
<Card
id="chat-channel-create-panel-group"
role="tabpanel"
aria-labelledby="chat-channel-create-tab-group"
size="large"
data-ui-id="ui.chat.channelCreate.groupForm"
>
<TextInput
fillContainer
showLabel
label={t("chat.channelCreate.fields.name")}
helpText={t("chat.channelCreate.fields.nameHelp")}
error={localErrorKey === "chat.channelCreate.validation.groupNameRequired"}
message={localErrorKey ? t(localErrorKey) : undefined}
>
<TextInput.Input
value={name}
onChange={(event) => {
setName(event.target.value);
if (event.target.value.trim()) setLocalErrorKey(null);
}}
placeholder={t("chat.channelCreate.placeholders.name")}
maxLength={120}
autoFocus
data-ui-id="ui.chat.channelCreate.name"
/>
</TextInput>
<TextArea showLabel label={t("chat.channelCreate.fields.description")} helpText={t("chat.channelCreate.fields.descriptionHelp")}>
<TextArea.Input
value={description}
onChange={(event) => setDescription(event.target.value)}
placeholder={t("chat.channelCreate.placeholders.description")}
maxLength={4000}
data-ui-id="ui.chat.channelCreate.description"
/>
</TextArea>
<Card variant="neutral" data-ui-id="ui.chat.channelCreate.privacy">
<ButtonGroup align="space-between">
<ButtonGroup>
<FeatherHash aria-hidden="true" />
<span>{t(privacy === "private" ? "chat.channelCreate.privacy.private" : "chat.channelCreate.privacy.public")}</span>
</ButtonGroup>
<ChatSwitch
checked={privacy === "private"}
onCheckedChange={(checked) => setPrivacy(checked ? "private" : "public")}
aria-label={t("chat.channelCreate.fields.private")}
/>
</ButtonGroup>
<span>{t(privacy === "private" ? "chat.channelCreate.privacy.privateHelp" : "chat.channelCreate.privacy.publicHelp")}</span>
</Card>
<ButtonGroup align="stack" data-ui-id="ui.chat.channelCreate.members">
<strong>{t("chat.channelCreate.fields.members")}</strong>
<span>{t("chat.channelCreate.fields.membersHelp")}</span>
{readyData.userOptions.length === 0 ? (
<EmptyState outlined title={t(readyData.keys.usersEmptyKey)} body={t("chat.channelCreate.users.groupEmptyBody")} />
) : (
readyData.userOptions.map((user) => (
<Card key={user.userId} size="small" variant={selectedUserIds.has(user.userId) ? "information" : "default"}>
<ButtonGroup align="space-between">
<ButtonGroup>
<Avatar image={user.avatar.imageUrl ?? undefined} size="small">
{user.avatar.fallbackLabel}
</Avatar>
<span>{user.displayName}</span>
</ButtonGroup>
<Checkbox
checked={selectedUserIds.has(user.userId)}
label={user.email}
onCheckedChange={(checked) =>
setInitialUserIds((current) => (checked ? [...new Set([...current, user.userId])] : current.filter((id) => id !== user.userId)))
}
data-user-id={user.userId}
/>
</ButtonGroup>
</Card>
))
)}
</ButtonGroup>
<ButtonGroup align="stack" data-ui-id="ui.chat.channelCreate.groups">
<strong>{t("chat.channelCreate.fields.groups")}</strong>
<span>{t("chat.channelCreate.fields.groupsHelp")}</span>
{readyData.groupOptions.length === 0 ? (
<EmptyState outlined title={t(readyData.keys.groupsEmptyKey)} body={t("chat.channelCreate.groups.emptyBody")} />
) : (
readyData.groupOptions.map((group) => (
<Card key={group.groupId} size="small" variant={selectedGroupIds.has(group.groupId) ? "information" : "default"}>
<ButtonGroup align="space-between">
<ButtonGroup align="stack">
<strong>{group.name}</strong>
<span>
{group.description || t("chat.channelCreate.groups.noDescription")} ·{" "}
{t("chat.channelCreate.groups.memberCount", { count: group.memberCount })}
</span>
</ButtonGroup>
<Checkbox
checked={selectedGroupIds.has(group.groupId)}
label={group.name}
onCheckedChange={(checked) => {
setInitialGroupIds((current) => {
const next = checked ? [...new Set([...current, group.groupId])] : current.filter((id) => id !== group.groupId);
if (next.length === 0) setSyncGroupMembership(false);
return next;
});
}}
data-group-id={group.groupId}
/>
</ButtonGroup>
</Card>
))
)}
</ButtonGroup>
<Card variant="neutral" data-ui-id="ui.chat.channelCreate.groupSync">
<ButtonGroup align="space-between">
<ButtonGroup align="stack">
<strong>{t("chat.channelCreate.fields.groupSync")}</strong>
<span>{t("chat.channelCreate.fields.groupSyncHelp")}</span>
</ButtonGroup>
<ChatSwitch
checked={syncGroupMembership}
disabled={initialGroupIds.length === 0}
onCheckedChange={setSyncGroupMembership}
aria-label={t("chat.channelCreate.fields.groupSync")}
/>
</ButtonGroup>
</Card>
</Card>
) : (
<Card
id="chat-channel-create-panel-dm"
role="tabpanel"
aria-labelledby="chat-channel-create-tab-dm"
size="large"
data-ui-id="ui.chat.channelCreate.dmForm"
>
{readyData.userOptions.length === 0 ? (
<EmptyState outlined title={t(readyData.keys.usersEmptyKey)} body={t("chat.channelCreate.users.dmEmptyBody")} />
) : (
<Select
value={peerUserId}
onValueChange={(value) => {
setPeerUserId(value);
setLocalErrorKey(null);
}}
showLabel
label={t("chat.channelCreate.fields.peer")}
helpText={t("chat.channelCreate.fields.peerHelp")}
placeholder={t("chat.channelCreate.placeholders.peer")}
triggerAriaLabel={t("chat.channelCreate.fields.peer")}
error={localErrorKey === "chat.channelCreate.validation.dmPeerRequired"}
errorText={localErrorKey ? t(localErrorKey) : undefined}
data-ui-id="ui.chat.channelCreate.peer"
>
{readyData.userOptions.map((user) => (
<Select.Item key={user.userId} value={user.userId}>
{user.displayName} · {user.email}
</Select.Item>
))}
</Select>
)}
</Card>
)}
</CreateShell>
);
}