Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

6.9 KB
Raw Blame
import { MenuProps, Dropdown, Button } from 'antd';
import classnames from 'classnames';

import { useAtom, useAtomValue } from 'jotai';
import { FC, useEffect, useState } from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
import dynamic from 'next/dynamic';
import { ErrorBoundary, getErrorMessage } from 'react-error-boundary';
import {
  ChatState,
  chatStateAtom,
  currentUserAtom,
  appStateAtom,
} from '../../stores/ClientConfigStore';
import styles from './UserDropdown.module.scss';
import { ComponentError } from '../../ui/ComponentError/ComponentError';
import { getPendingFediverseAuth } from '../../../utils/fediverseAuthSession';

// Lazy loaded components

const CaretDownOutlined = dynamic(() => import('@ant-design/icons/CaretDownOutlined'), {
  ssr: false,
});

const EditOutlined = dynamic(() => import('@ant-design/icons/EditOutlined'), {
  ssr: false,
});

const LockOutlined = dynamic(() => import('@ant-design/icons/LockOutlined'), {
  ssr: false,
});

const ShrinkOutlined = dynamic(() => import('@ant-design/icons/ShrinkOutlined'), {
  ssr: false,
});

const ExpandAltOutlined = dynamic(() => import('@ant-design/icons/ExpandAltOutlined'), {
  ssr: false,
});

const MessageOutlined = dynamic(() => import('@ant-design/icons/MessageOutlined'), {
  ssr: false,
});

const UserOutlined = dynamic(() => import('@ant-design/icons/UserOutlined'), {
  ssr: false,
});

const Modal = dynamic(() => import('../../ui/Modal/Modal').then(mod => mod.Modal), {
  ssr: false,
});

const NameChangeModal = dynamic(
  () => import('../../modals/NameChangeModal/NameChangeModal').then(mod => mod.NameChangeModal),
  {
    ssr: false,
  },
);

const AuthModal = dynamic(
  () => import('../../modals/AuthModal/AuthModal').then(mod => mod.AuthModal),
  {
    ssr: false,
  },
);

export type UserDropdownProps = {
  id: string;
  username?: string;
  hideTitleOnMobile?: boolean;
  showToggleChatOption?: boolean;
};

export const UserDropdown: FC<UserDropdownProps> = ({
  id,
  username: defaultUsername = undefined,
  hideTitleOnMobile = false,
  showToggleChatOption: showHideChatOption = true,
}) => {
  const [showNameChangeModal, setShowNameChangeModal] = useState<boolean>(false);
  const [showAuthModal, setShowAuthModal] = useState<boolean>(false);
  // Latch: once the auth modal has been opened, keep it mounted so in-flight
  // auth state survives close/reopen (the v4 shell used destroyOnClose=false;
  // the v6 AuthModal keeps children mounted after first open by default, but
  // must not be unmounted by conditional rendering).
  const [authModalMounted, setAuthModalMounted] = useState<boolean>(false);
  const [chatState, setChatState] = useAtom(chatStateAtom);
  const [popupWindow, setPopupWindow] = useState<Window>(null);
  const appState = useAtomValue(appStateAtom);

  // Reopen the auth modal on load if a fediverse verification was still in
  // progress, so a viewer who reloaded mid-flow (issue #4887) lands back on the
  // code-entry step instead of losing it.
  useEffect(() => {
    if (getPendingFediverseAuth()) {
      setShowAuthModal(true);
    }
  }, []);

  useEffect(() => {
    if (showAuthModal) {
      setAuthModalMounted(true);
    }
  }, [showAuthModal]);

  const toggleChatVisibility = () => {
    // If we don't support the hide chat option then don't do anything.
    if (!showHideChatOption) {
      return;
    }

    setChatState(chatState === ChatState.VISIBLE ? ChatState.HIDDEN : ChatState.VISIBLE);
  };

  const handleChangeName = () => {
    setShowNameChangeModal(true);
  };

  const closeChangeNameModal = () => {
    setShowNameChangeModal(false);
  };

  const closeChatPopup = () => {
    if (popupWindow) {
      popupWindow.close();
    }
    setPopupWindow(null);
    setChatState(ChatState.VISIBLE);
  };

  const openChatPopup = () => {
    // close popup (if any) to prevent multiple popup windows.
    closeChatPopup();
    const w = window.open('/embed/chat/readwrite', '_blank', 'popup');
    w.addEventListener('beforeunload', closeChatPopup);
    setPopupWindow(w);
    setChatState(ChatState.POPPED_OUT);
  };

  const canShowHideChat =
    showHideChatOption &&
    appState.chatAvailable &&
    (chatState === ChatState.HIDDEN || chatState === ChatState.VISIBLE);
  const canShowChatPopup =
    showHideChatOption &&
    appState.chatAvailable &&
    (chatState === ChatState.HIDDEN ||
      chatState === ChatState.VISIBLE ||
      chatState === ChatState.POPPED_OUT);

  // Register keyboard shortcut for the space bar to toggle playback
  useHotkeys(
    'c',
    toggleChatVisibility,
    {
      enableOnContentEditable: false,
    },
    [chatState === ChatState.VISIBLE],
  );

  const currentUser = useAtomValue(currentUserAtom);
  if (!currentUser) {
    return null;
  }

  const { displayName } = currentUser;
  const username = defaultUsername || displayName;

  const items: MenuProps['items'] = [
    {
      key: 0,
      icon: <EditOutlined />,
      label: 'Change name',
      onClick: handleChangeName,
    },
    {
      key: 1,
      icon: <LockOutlined />,
      label: 'Authenticate',
      onClick: () => setShowAuthModal(true),
    },
  ];
  if (canShowHideChat)
    items.push({
      key: 3,
      'aria-expanded': chatState === ChatState.VISIBLE,
      className: styles.chatToggle, // TODO why do we hide this button on tablets?
      icon: <MessageOutlined />,
      label: chatState === ChatState.VISIBLE ? 'Hide Chat (c)' : 'Show Chat (c)',
      onClick: toggleChatVisibility,
    } as MenuProps['items'][0]);
  if (canShowChatPopup)
    items.push({
      key: 4,
      icon: popupWindow ? <ShrinkOutlined /> : <ExpandAltOutlined />,
      label: popupWindow ? 'Put chat back' : 'Pop out chat',
      onClick: popupWindow ? closeChatPopup : openChatPopup,
    });

  return (
    <ErrorBoundary
      // eslint-disable-next-line react/no-unstable-nested-components
      fallbackRender={({ error, resetErrorBoundary }) => (
        <ComponentError
          componentName="UserDropdown"
          message={getErrorMessage(error)}
          retryFunction={resetErrorBoundary}
        />
      )}
    >
      <div className={styles.root}>
        <Dropdown menu={{ items }} trigger={['click']}>
          <Button id={id} type="primary" icon={<UserOutlined className={styles.userIcon} />}>
            <span
              className={classnames([
                styles.username,
                hideTitleOnMobile && styles.hideTitleOnMobile,
              ])}
            >
              {username}
            </span>
            <CaretDownOutlined />
          </Button>
        </Dropdown>
        <Modal
          title="Change Chat Display Name"
          open={showNameChangeModal}
          handleCancel={closeChangeNameModal}
        >
          <NameChangeModal closeModal={closeChangeNameModal} />
        </Modal>
        {(showAuthModal || authModalMounted) && (
          <AuthModal open={showAuthModal} handleClose={() => setShowAuthModal(false)} />
        )}
      </div>
    </ErrorBoundary>
  );
};