Skip to content

armgit / umami

Public Imported from GitHub
0

Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.

3.7 KB
Raw Blame
import {
  Button,
  Column,
  Form,
  FormField,
  FormSubmitButton,
  Label,
  Loading,
  Row,
  Switch,
  TextField,
} from '@umami/react-zen';
import { useEffect, useState } from 'react';
import { useApi, useConfig, useMessages, useModified } from '@/components/hooks';
import { ThemeModeSelector } from '@/components/input/ThemeModeSelector';

export function SimpleShareEditForm({
  shareId,
  onSave,
  onClose,
}: {
  shareId: string;
  onSave?: () => void;
  onClose?: () => void;
}) {
  const { t, labels, getErrorMessage } = useMessages();
  const config = useConfig();
  const { get, post } = useApi();
  const { touch } = useModified();
  const { modified } = useModified('shares');
  const [share, setShare] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState<any>(null);

  const getUrl = (slug: string) => {
    return `${config?.cloudMode ? process.env.cloudUrl : window?.location.origin}${process.env.basePath || ''}/share/${slug}`;
  };

  useEffect(() => {
    const loadShare = async () => {
      setIsLoading(true);
      try {
        const data = await get(`/share/id/${shareId}`);
        setShare(data);
      } finally {
        setIsLoading(false);
      }
    };

    loadShare();
  }, [get, modified, shareId]);

  const handleSubmit = async (data: { name: string; allowFilter?: boolean; theme?: string }) => {
    setIsPending(true);
    setError(null);

    try {
      await post(`/share/id/${shareId}`, {
        name: data.name,
        slug: share.slug,
        parameters: {
          ...(share.parameters || {}),
          allowFilter: data.allowFilter ?? true,
          theme: data.theme === 'system' ? undefined : data.theme,
        },
      });

      touch('shares');
      onSave?.();
      onClose?.();
    } catch (e) {
      setError(e);
    } finally {
      setIsPending(false);
    }
  };

  if (isLoading) {
    return <Loading placement="absolute" />;
  }

  return (
    <Form
      onSubmit={handleSubmit}
      error={getErrorMessage(error)}
      defaultValues={{
        name: share?.name || '',
        allowFilter: share?.parameters?.allowFilter ?? true,
        theme: share?.parameters?.theme || 'system',
      }}
    >
      {({ watch, setValue }) => (
        <Column gap="6">
          <Column gap="1">
            <Label>{t(labels.shareUrl)}</Label>
            <TextField value={getUrl(share?.slug || '')} isReadOnly allowCopy />
          </Column>
          <FormField label={t(labels.name)} name="name" rules={{ required: t(labels.required) }}>
            <TextField autoComplete="off" autoFocus />
          </FormField>
          <Row gap="6">
            <FormField label={t(labels.filters)} name="allowFilter">
              <Switch
                isSelected={watch('allowFilter')}
                onChange={value => setValue('allowFilter', value, { shouldDirty: true })}
              >
                {t(labels.filtersEnabled)}
              </Switch>
            </FormField>
            <FormField label={t(labels.theme)} name="theme">
              <ThemeModeSelector
                value={watch('theme')}
                includeSystem
                onChange={value => setValue('theme', value, { shouldDirty: true })}
              />
            </FormField>
          </Row>
          <Row justifyContent="flex-end" paddingTop="3" gap="3">
            {onClose && (
              <Button isDisabled={isPending} onPress={onClose}>
                {t(labels.cancel)}
              </Button>
            )}
            <FormSubmitButton variant="primary" isDisabled={isPending}>
              {t(labels.save)}
            </FormSubmitButton>
          </Row>
        </Column>
      )}
    </Form>
  );
}