Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

6.9 KB
Raw Blame
import { type AgentLabelListItem } from '@lobechat/types';
import { Button, createModal, Flexbox, Input, ModalFooter, useModalContext } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import { t as translate } from 'i18next';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';

import InlineErrorText from '@/components/InlineErrorText';
import { type InlineErrorState, toInlineError } from '@/components/InlineErrorText/errorDetail';
import { useHomeStore } from '@/store/home';

import { DEFAULT_LABEL_COLOR, isValidLabelColor, LABEL_COLOR_PRESETS } from './constants';
import { isDuplicateLabelNameError } from './errors';

const styles = stylex.create({
  swatch: {
    cursor: 'pointer',
    width: '20px',
    height: '20px',
    borderWidth: '2px',
    borderStyle: 'solid',
    borderColor: 'transparent',
    borderRadius: '50%',
    transition: 'transform 0.1s',
    transform: { 'default': null, ':hover': 'scale(1.15)' },
  },
  swatchActive: { borderColor: cssVar.colorText },
});

export interface LabelFormModalOptions {
  /**
   * When creating from an agent's Labels submenu, apply the new label to that
   * agent right away β€” creating "for" an agent and then having to reopen the
   * picker would be surprising.
   */
  assignTo?: { agentId: string; currentLabelIds: string[] };
  /** Present when editing; absent when creating. */
  label?: AgentLabelListItem;
  /**
   * Opened from a failed restore: the label is archived and its old name is
   * taken, so saving must also flip `archived` back off β€” otherwise the user
   * renames it and still has to find the restore action again.
   */
  restoreOnSave?: boolean;
}

const LabelFormContent = memo<LabelFormModalOptions>(({ assignTo, label, restoreOnSave }) => {
  const { t } = useTranslation(['setting', 'common']);
  const { close } = useModalContext();
  const [createAgentLabel, toggleAgentLabel, updateAgentLabel] = useHomeStore((s) => [
    s.createAgentLabel,
    s.toggleAgentLabel,
    s.updateAgentLabel,
  ]);

  const [name, setName] = useState(label?.name ?? '');
  const [description, setDescription] = useState(label?.description ?? '');
  const [color, setColor] = useState<string>(label?.color ?? DEFAULT_LABEL_COLOR);
  const [loading, setLoading] = useState(false);
  /**
   * Save failures stay in the modal: a name clash shows under the name input (the field the
   * user must change), any other failure shows above the footer buttons.
   */
  const [nameError, setNameError] = useState('');
  const [saveError, setSaveError] = useState<InlineErrorState | null>(null);

  const handleSave = async () => {
    const trimmed = name.trim();
    if (!trimmed || loading) return;

    setNameError('');
    setSaveError(null);
    setLoading(true);
    try {
      if (label) {
        await updateAgentLabel(label.id, {
          ...(restoreOnSave ? { archived: false } : {}),
          color,
          description: description.trim() || null,
          name: trimmed,
        });
      } else {
        const id = await createAgentLabel({
          color,
          description: description.trim() || undefined,
          name: trimmed,
        });
        if (assignTo && id) {
          // Delta, not `[...currentLabelIds, id]`: those ids were captured when
          // the modal opened, so replaying them as a full set would delete
          // anything another editor applied while the user was typing.
          await toggleAgentLabel(assignTo.agentId, id, true);
        }
      }
      close();
    } catch (error) {
      // Keep the modal open on a name clash β€” the user's next move is to edit
      // the name they already typed, not to start over.
      if (isDuplicateLabelNameError(error)) {
        setNameError(t('workspaceSetting.labels.form.duplicateName'));
        return;
      }
      console.error('Failed to save label:', error);
      setSaveError(toInlineError(t('workspaceSetting.labels.form.saveFailedRetry'), error));
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <Flexbox gap={16} paddingBlock={8} paddingInline={16}>
        <Flexbox gap={8}>
          <span>{t('workspaceSetting.labels.form.name')}</span>
          <Input
            autoFocus
            aria-invalid={!!nameError}
            data-invalid={nameError ? '' : undefined}
            maxLength={40}
            placeholder={t('workspaceSetting.labels.form.namePlaceholder')}
            value={name}
            onChange={(e) => {
              setName(e.target.value);
              setNameError('');
            }}
          />
          {nameError && (
            <span role={'alert'} style={{ color: cssVar.colorError, fontSize: 12 }}>
              {nameError}
            </span>
          )}
        </Flexbox>
        <Flexbox gap={8}>
          <span>{t('workspaceSetting.labels.form.description')}</span>
          <Input
            maxLength={200}
            placeholder={t('workspaceSetting.labels.form.descriptionPlaceholder')}
            value={description}
            onChange={(e) => setDescription(e.target.value)}
          />
        </Flexbox>
        <Flexbox gap={8}>
          <span>{t('workspaceSetting.labels.form.color')}</span>
          <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
            {LABEL_COLOR_PRESETS.map((preset) => (
              <span
                aria-label={preset}
                key={preset}
                role={'button'}
                style={{ background: preset }}
                className={
                  stylex.props(styles.swatch, color === preset && styles.swatchActive).className
                }
                onClick={() => setColor(preset)}
              />
            ))}
            <Input
              placeholder={'#RRGGBB'}
              style={{ width: 100 }}
              value={color}
              onChange={(e) => setColor(e.target.value)}
            />
          </Flexbox>
        </Flexbox>
        {saveError && (
          <InlineErrorText detail={saveError.detail}>{saveError.summary}</InlineErrorText>
        )}
      </Flexbox>
      <ModalFooter>
        <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>
        <Button
          disabled={!name.trim() || !isValidLabelColor(color)}
          loading={loading}
          type={'primary'}
          onClick={handleSave}
        >
          {t('ok', { defaultValue: 'OK', ns: 'common' })}
        </Button>
      </ModalFooter>
    </>
  );
});

LabelFormContent.displayName = 'LabelFormContent';

export const openLabelFormModal = (options: LabelFormModalOptions = {}) =>
  createModal({
    content: <LabelFormContent {...options} />,
    footer: null,
    styles: { content: { padding: 0 } },
    title: translate(
      options.restoreOnSave
        ? 'workspaceSetting.labels.form.restoreTitle'
        : options.label
          ? 'workspaceSetting.labels.form.editTitle'
          : 'workspaceSetting.labels.form.createTitle',
      { ns: 'setting' },
    ),
    width: 420,
  });