> For AI agents: the complete documentation index is available at https://wallarm.github.io/design-system/llms.txt, the full documentation bundle is available at https://wallarm.github.io/design-system/llms-full.txt.

# Rule editor

**Components:** [`Page`](https://wallarm.github.io/design-system/components/page.md), [`PageHeader`](https://wallarm.github.io/design-system/components/page.md), [`PageToolbar`](https://wallarm.github.io/design-system/components/page.md), [`PageContent`](https://wallarm.github.io/design-system/components/page.md), [`Table`](https://wallarm.github.io/design-system/components/table.md), [`SearchInput`](https://wallarm.github.io/design-system/components/search-input.md), [`Drawer`](https://wallarm.github.io/design-system/components/drawer.md), [`Stepper`](https://wallarm.github.io/design-system/components/stepper.md)


+17 more

[`Field`](https://wallarm.github.io/design-system/components/field.md), [`Input`](https://wallarm.github.io/design-system/components/input.md), [`Select`](https://wallarm.github.io/design-system/components/select.md), [`Checkbox`](https://wallarm.github.io/design-system/components/checkbox.md), [`CheckboxGroup`](https://wallarm.github.io/design-system/components/checkbox.md), [`HttpMethod`](https://wallarm.github.io/design-system/components/http-method.md), [`CodeEditorRoot`](https://wallarm.github.io/design-system/components/code-editor.md), [`CodeEditorContent`](https://wallarm.github.io/design-system/components/code-editor.md), [`CodeSnippetRoot`](https://wallarm.github.io/design-system/components/code-snippet.md), [`InlineCodeSnippet`](https://wallarm.github.io/design-system/components/code-snippet.md), [`RadioGroup`](https://wallarm.github.io/design-system/components/radio.md), [`Radio`](https://wallarm.github.io/design-system/components/radio.md), [`Attribute`](https://wallarm.github.io/design-system/components/attribute.md), [`Badge`](https://wallarm.github.io/design-system/components/badge.md), [`Alert`](https://wallarm.github.io/design-system/components/alert.md), [`Button`](https://wallarm.github.io/design-system/components/button.md), [`Toaster`](https://wallarm.github.io/design-system/components/toast.md)

A custom rules page whose "Create rule" button opens a create drawer: four steps take the user from where the rule applies to what it does, with a review before anything is saved.

## What it shows

- A [Resource list page](https://wallarm.github.io/design-system/patterns/resource-list-page.md) behind the drawer, with `HttpMethod`, `InlineCodeSnippet` and `Badge` cells.
- A four-step `Stepper` drawer from [Create and edit forms](https://wallarm.github.io/design-system/patterns/create-edit-forms.md).
- Scope: `Input`, a `Select` for the host and a `CheckboxGroup` of methods.
- Condition: a `CodeEditor` with YAML highlighting, shown again as a read-only `CodeSnippet` on review.
- Action: `RadioGroup variant='card'` for block or monitor.
- Review: `Attribute` rows and a section as in the [Detail drawer](https://wallarm.github.io/design-system/patterns/detail-drawer.md).
- Errors after a submit attempt and a toast after create, from [Feedback toasts](https://wallarm.github.io/design-system/patterns/feedback-toasts.md).

## Examples

The rules list. Press "Create rule" to open the drawer and walk Scope, Condition, Action and Review; press "Create rule" on Review with gaps to see the drawer jump back to the first invalid step.

The custom rules list. "Create rule" opens a four-step `Stepper` drawer: Scope (a host
`Select`, a path and a `CheckboxGroup` of methods), Condition (a YAML `CodeEditor`), Action
(`RadioGroup variant='card'`) and Review (`Attribute` rows and a read-only `CodeSnippet`).
Steps never block; "Create rule" on Review jumps back to the first invalid step, or closes the
drawer, adds the row and shows a toast.

```tsx
import { type ChangeEvent, type FormEvent, useState } from 'react';
import { Alert, AlertContent, AlertDescription, AlertIcon, AlertTitle } from '@wallarm-org/design-system/Alert';
import { Attribute, AttributeLabel, AttributeValue } from '@wallarm-org/design-system/Attribute';
import { Badge } from '@wallarm-org/design-system/Badge';
import { Button } from '@wallarm-org/design-system/Button';
import { Checkbox, CheckboxGroup, CheckboxIndicator, CheckboxLabel } from '@wallarm-org/design-system/Checkbox';
import { CodeEditorContent, CodeEditorRoot } from '@wallarm-org/design-system/CodeEditor';
import { CodeSnippetActions, CodeSnippetAdapterProvider, CodeSnippetCode, CodeSnippetContent, CodeSnippetCopyButton, CodeSnippetHeader, CodeSnippetLineNumbers, CodeSnippetRoot, CodeSnippetTitle, CodeSnippetWrapButton, InlineCodeSnippet, loadPrismAdapter } from '@wallarm-org/design-system/CodeSnippet';
import { Drawer, DrawerBody, DrawerClose, DrawerContent, DrawerFooter, DrawerFooterControls, DrawerHeader, DrawerTitle } from '@wallarm-org/design-system/Drawer';
import { Field, FieldDescription, FieldError, FieldIndicator, FieldLabel, FieldLegend } from '@wallarm-org/design-system/Field';
import { Heading } from '@wallarm-org/design-system/Heading';
import { HttpMethod } from '@wallarm-org/design-system/HttpMethod';
import { Plus } from '@wallarm-org/design-system/icons';
import { Input } from '@wallarm-org/design-system/Input';
import { Page, PageActions, PageContent, PageDescription, PageHeader, PageHeaderGroup, PageTitle, PageToolbar } from '@wallarm-org/design-system/Page';
import { Radio, RadioDescription, RadioGroup, RadioIndicator, RadioLabel } from '@wallarm-org/design-system/Radio';
import { SearchInput } from '@wallarm-org/design-system/SearchInput';
import { Select, SelectContent, SelectInput, SelectOption, SelectOptionIndicator, SelectOptionText, SelectPositioner } from '@wallarm-org/design-system/Select';
import { Separator } from '@wallarm-org/design-system/Separator';
import { HStack, VStack } from '@wallarm-org/design-system/Stack';
import { Stepper, StepperContent, StepperIndicator, StepperItem, type StepperItemStatus, StepperList, StepperNextTrigger, StepperPrevTrigger, StepperSeparator, StepperTitle, StepperTrigger } from '@wallarm-org/design-system/Stepper';
import { Table } from '@wallarm-org/design-system/Table';
import { useToast } from '@wallarm-org/design-system/Toast';

export const Default = ({ isLoading }) => {
  const toast = useToast();
  const [rules, setRules] = useState(RULES);
  const [query, setQuery] = useState('');
  const [open, setOpen] = useState(false);
  const [step, setStep] = useState(0);
  const [visited, setVisited] = useState<number[]>([]);
  const [name, setName] = useState(EMPTY_DRAFT.name);
  const [host, setHost] = useState(EMPTY_DRAFT.host);
  const [path, setPath] = useState(EMPTY_DRAFT.path);
  const [methods, setMethods] = useState(EMPTY_DRAFT.methods);
  const [condition, setCondition] = useState(EMPTY_DRAFT.condition);
  const [action, setAction] = useState<RuleAction>(EMPTY_DRAFT.action);
  const [pending, setPending] = useState(false);

  const errors = {
    name: name.trim() === '' ? 'Enter a rule name.' : null,
    host: host.length === 0 ? 'Select a host.' : null,
    path: path.startsWith('/') ? null : 'Start the path with /.',
    methods: methods.length === 0 ? 'Select at least one method.' : null,
    condition: condition.trim() === '' ? 'Write a condition.' : null,
  };
  const valid = [
    !errors.name && !errors.host && !errors.path && !errors.methods,
    !errors.condition,
    true,
    true,
  ];
  const statuses = valid.map<StepperItemStatus>((ok, i) =>
    !visited.includes(i) ? 'upcoming' : ok ? 'completed' : 'danger',
  );
  const showScopeErrors = visited.includes(0);
  const showConditionErrors = visited.includes(1);
  const last = step === RULE_STEPS.length - 1;

  const search = query.trim().toLowerCase();
  const rows = rules.filter(
    rule => rule.name.toLowerCase().includes(search) || rule.path.includes(search),
  );

  const handleCreate = () => {
    setName(EMPTY_DRAFT.name);
    setHost(EMPTY_DRAFT.host);
    setPath(EMPTY_DRAFT.path);
    setMethods(EMPTY_DRAFT.methods);
    setCondition(EMPTY_DRAFT.condition);
    setAction(EMPTY_DRAFT.action);
    setVisited([]);
    setStep(0);
    setOpen(true);
  };
  const handleStepChange = ({ step: next }: { step: number }) => {
    setVisited(prev => (prev.includes(step) ? prev : [...prev, step]));
    setStep(next);
  };
  const handleNameChange = (event: ChangeEvent<HTMLInputElement>) => setName(event.target.value);
  const handleHostChange = ({ value }: { value: string[] }) => setHost(value);
  const handlePathChange = (event: ChangeEvent<HTMLInputElement>) => setPath(event.target.value);
  const handleActionChange = ({ value }: { value: string | null }) =>
    setAction(value === 'monitor' ? 'monitor' : 'block');

  const handleSubmit = async (event: FormEvent) => {
    event.preventDefault();
    if (!valid.every(Boolean)) {
      setVisited([0, 1, 2]);
      setStep(valid.indexOf(false));
      return;
    }
    setPending(true);
    await saveRequest();
    setPending(false);
    setRules(prev => [
      {
        id: `r-${2042 + prev.length}`,
        name,
        host: host[0] ?? '',
        path,
        methods,
        action,
        updatedAt: new Date().toISOString(),
      },
      ...prev,
    ]);
    setOpen(false);
    toast.create({ id: 'rule-created', title: 'Rule created', type: 'default' });
  };

  return (
    <Page name='custom-rules' fullSize fixedHeight data-testid='rules-page'>
      <PageHeader>
        <PageHeaderGroup className='flex-1'>
          <PageTitle>Custom rules</PageTitle>
          <PageDescription>
            Rules that block or monitor requests matching your own conditions, on top of the
            built-in attack detection.
          </PageDescription>
        </PageHeaderGroup>
        <PageActions>
          <Button size='medium' onClick={handleCreate} data-testid='rules-create'>
            <Plus />
            Create rule
          </Button>
        </PageActions>
      </PageHeader>

      <PageToolbar>
        <SearchInput
          value={query}
          onChange={setQuery}
          placeholder='Search name or path'
          className='w-[320px]'
          data-testid='rules-search'
        />
      </PageToolbar>

      <PageContent>
        <Table
          aria-label='Custom rules'
          data={isLoading ? [] : rows}
          columns={RULE_COLUMNS}
          isLoading={isLoading}
          getRowId={getRuleId}
          data-testid='rules-table'
        />
      </PageContent>

      <Drawer open={open} onOpenChange={setOpen} data-testid='rule-drawer'>
        <DrawerContent>
          <DrawerHeader>
            <DrawerTitle>Create rule</DrawerTitle>
          </DrawerHeader>
          {/* noValidate: the page validates itself and shows its own errors. */}
          <form noValidate onSubmit={handleSubmit} className='flex min-h-0 flex-1 flex-col'>
            <Stepper
              count={RULE_STEPS.length}
              step={step}
              onStepChange={handleStepChange}
              className='flex min-h-0 flex-1 flex-col'
              data-testid='rule-stepper'
            >
              <StepperList aria-label='Create rule steps'>
                {RULE_STEPS.map((title, i) => (
                  <StepperItem key={title} index={i} status={statuses[i]}>
                    <StepperTrigger>
                      <StepperIndicator />
                      <StepperTitle>{title}</StepperTitle>
                    </StepperTrigger>
                    <StepperSeparator />
                  </StepperItem>
                ))}
              </StepperList>
              <CodeSnippetAdapterProvider adapter={loadPrismAdapter}>
                <DrawerBody>
                  <StepperContent index={0} className='py-16'>
                    <VStack gap={12}>
                      <Field required>
                        <FieldLabel>
                          Name
                          <FieldIndicator />
                        </FieldLabel>
                        <Input
                          value={name}
                          error={showScopeErrors && Boolean(errors.name)}
                          onChange={handleNameChange}
                          placeholder='Login credential stuffing'
                          data-testid='rule-name'
                        />
                        {showScopeErrors && errors.name && <FieldError>{errors.name}</FieldError>}
                      </Field>
                      <div className='grid grid-cols-2 gap-12'>
                        <Field required>
                          <FieldLabel>
                            Host
                            <FieldIndicator />
                          </FieldLabel>
                          <Select
                            collection={hostCollection}
                            value={host}
                            onValueChange={handleHostChange}
                            invalid={showScopeErrors && Boolean(errors.host)}
                            data-testid='rule-host'
                          >
                            <SelectInput placeholder='Select a host' />
                            <SelectPositioner>
                              <SelectContent>
                                {hostCollection.items.map(item => (
                                  <SelectOption key={item.value} item={item}>
                                    <SelectOptionText>{item.label}</SelectOptionText>
                                    <SelectOptionIndicator />
                                  </SelectOption>
                                ))}
                              </SelectContent>
                            </SelectPositioner>
                          </Select>
                          {showScopeErrors && errors.host && <FieldError>{errors.host}</FieldError>}
                        </Field>
                        <Field required>
                          <FieldLabel>
                            Path
                            <FieldIndicator />
                          </FieldLabel>
                          <Input
                            value={path}
                            error={showScopeErrors && Boolean(errors.path)}
                            onChange={handlePathChange}
                            placeholder='/v2/login'
                            data-testid='rule-path'
                          />
                          {showScopeErrors && errors.path && <FieldError>{errors.path}</FieldError>}
                        </Field>
                      </div>
                      {/* A direct CheckboxGroup child makes Field a fieldset, so each checkbox keeps its
                          own id. Inside a plain field every checkbox label points at the field id,
                          and clicking any method toggles the first. */}
                      <Field data-testid='rule-methods'>
                        <FieldLegend variant='label'>Methods</FieldLegend>
                        <FieldDescription>
                          Requests with other methods skip this rule.
                        </FieldDescription>
                        <CheckboxGroup name='methods' value={methods} onValueChange={setMethods}>
                          {HTTP_METHODS.map(method => (
                            <Checkbox key={method} value={method}>
                              <CheckboxIndicator />
                              <CheckboxLabel>
                                <HttpMethod method={method} />
                              </CheckboxLabel>
                            </Checkbox>
                          ))}
                        </CheckboxGroup>
                        {showScopeErrors && errors.methods && (
                          <FieldError>{errors.methods}</FieldError>
                        )}
                      </Field>
                    </VStack>
                  </StepperContent>

                  <StepperContent index={1} className='py-16'>
                    <Field required>
                      <FieldLabel>
                        Condition
                        <FieldIndicator />
                      </FieldLabel>
                      <FieldDescription>
                        YAML. A request matches when every item under all is true.
                      </FieldDescription>
                      <CodeEditorRoot
                        value={condition}
                        onChange={setCondition}
                        language='yaml'
                        data-testid='rule-condition'
                      >
                        <CodeSnippetHeader>
                          <CodeSnippetTitle>condition.yaml</CodeSnippetTitle>
                          <CodeSnippetActions>
                            <CodeSnippetCopyButton />
                            <CodeSnippetWrapButton />
                          </CodeSnippetActions>
                        </CodeSnippetHeader>
                        <CodeEditorContent lineNumbers aria-label='Rule condition' />
                      </CodeEditorRoot>
                      {showConditionErrors && errors.condition && (
                        <FieldError>{errors.condition}</FieldError>
                      )}
                    </Field>
                  </StepperContent>

                  <StepperContent index={2} className='py-16'>
                    <Field required>
                      <FieldLabel>
                        Action
                        <FieldIndicator />
                      </FieldLabel>
                      <FieldDescription>What happens to a request that matches.</FieldDescription>
                      <RadioGroup
                        variant='card'
                        name='action'
                        value={action}
                        onValueChange={handleActionChange}
                      >
                        <Radio value='block'>
                          <RadioIndicator />
                          <RadioLabel>Block</RadioLabel>
                          <RadioDescription>
                            Return 403 and record the request as an attack.
                          </RadioDescription>
                        </Radio>
                        <Radio value='monitor'>
                          <RadioIndicator />
                          <RadioLabel>Monitor</RadioLabel>
                          <RadioDescription>
                            Let the request through and record it as an attack. Use it to tune a new
                            rule first.
                          </RadioDescription>
                        </Radio>
                      </RadioGroup>
                    </Field>
                  </StepperContent>

                  <StepperContent index={3} className='py-16'>
                    <VStack gap={16}>
                      <Alert color='info'>
                        <AlertIcon />
                        <AlertContent>
                          <AlertTitle>Applies within a minute</AlertTitle>
                          <AlertDescription>
                            Every node picks up the rule on its next sync. Requests already in
                            flight are not rechecked.
                          </AlertDescription>
                        </AlertContent>
                      </Alert>
                      <div>
                        <VStack gap={6} className='pb-8' data-testid='rule-review'>
                          <Attribute orientation='horizontal'>
                            <AttributeLabel width={140}>Name</AttributeLabel>
                            <AttributeValue>{name}</AttributeValue>
                          </Attribute>
                          <Attribute orientation='horizontal'>
                            <AttributeLabel width={140}>Host</AttributeLabel>
                            <AttributeValue>{host[0]}</AttributeValue>
                          </Attribute>
                          <Attribute orientation='horizontal'>
                            <AttributeLabel width={140}>Path</AttributeLabel>
                            <AttributeValue>
                              <InlineCodeSnippet code={path} size='md' />
                            </AttributeValue>
                          </Attribute>
                          <Attribute orientation='horizontal'>
                            <AttributeLabel width={140}>Methods</AttributeLabel>
                            <AttributeValue>
                              <HStack gap={4}>
                                {methods.map(method => (
                                  <HttpMethod key={method} method={method} />
                                ))}
                              </HStack>
                            </AttributeValue>
                          </Attribute>
                          <Attribute orientation='horizontal'>
                            <AttributeLabel width={140}>Action</AttributeLabel>
                            <AttributeValue>
                              <Badge variant='dotted' type='secondary' color={ACTION[action].color}>
                                {ACTION[action].label}
                              </Badge>
                            </AttributeValue>
                          </Attribute>
                        </VStack>
                        <Separator spacing={4} />
                        <HStack justify='between' align='center' className='py-8'>
                          <Heading as='h3' size='md' weight='medium'>
                            Condition
                          </Heading>
                        </HStack>
                        <CodeSnippetRoot code={condition} language='yaml'>
                          <CodeSnippetContent>
                            <CodeSnippetLineNumbers />
                            <CodeSnippetCode />
                          </CodeSnippetContent>
                        </CodeSnippetRoot>
                      </div>
                    </VStack>
                  </StepperContent>
                </DrawerBody>
              </CodeSnippetAdapterProvider>
              <DrawerFooter>
                <DrawerFooterControls placement='left'>
                  <DrawerClose asChild>
                    <Button variant='ghost' color='neutral'>
                      Cancel
                    </Button>
                  </DrawerClose>
                </DrawerFooterControls>
                <DrawerFooterControls placement='right'>
                  <StepperPrevTrigger asChild>
                    <Button variant='outline' color='neutral' data-testid='rule-back'>
                      Back
                    </Button>
                  </StepperPrevTrigger>
                  {last ? (
                    <Button type='submit' loading={pending} data-testid='rule-submit'>
                      Create rule
                    </Button>
                  ) : (
                    <StepperNextTrigger asChild>
                      <Button data-testid='rule-next'>Next</Button>
                    </StepperNextTrigger>
                  )}
                </DrawerFooterControls>
              </DrawerFooter>
            </Stepper>
          </form>
        </DrawerContent>
      </Drawer>
    </Page>
  );
};
```

The rules request still in flight: skeleton rows, with "Create rule" still available.

The rules request is still in flight: the table shows skeleton rows while "Create rule" stays
available.

```tsx
import { type ChangeEvent, type FormEvent, useState } from 'react';
import { Alert, AlertContent, AlertDescription, AlertIcon, AlertTitle } from '@wallarm-org/design-system/Alert';
import { Attribute, AttributeLabel, AttributeValue } from '@wallarm-org/design-system/Attribute';
import { Badge } from '@wallarm-org/design-system/Badge';
import { Button } from '@wallarm-org/design-system/Button';
import { Checkbox, CheckboxGroup, CheckboxIndicator, CheckboxLabel } from '@wallarm-org/design-system/Checkbox';
import { CodeEditorContent, CodeEditorRoot } from '@wallarm-org/design-system/CodeEditor';
import { CodeSnippetActions, CodeSnippetAdapterProvider, CodeSnippetCode, CodeSnippetContent, CodeSnippetCopyButton, CodeSnippetHeader, CodeSnippetLineNumbers, CodeSnippetRoot, CodeSnippetTitle, CodeSnippetWrapButton, InlineCodeSnippet, loadPrismAdapter } from '@wallarm-org/design-system/CodeSnippet';
import { Drawer, DrawerBody, DrawerClose, DrawerContent, DrawerFooter, DrawerFooterControls, DrawerHeader, DrawerTitle } from '@wallarm-org/design-system/Drawer';
import { Field, FieldDescription, FieldError, FieldIndicator, FieldLabel, FieldLegend } from '@wallarm-org/design-system/Field';
import { Heading } from '@wallarm-org/design-system/Heading';
import { HttpMethod } from '@wallarm-org/design-system/HttpMethod';
import { Plus } from '@wallarm-org/design-system/icons';
import { Input } from '@wallarm-org/design-system/Input';
import { Page, PageActions, PageContent, PageDescription, PageHeader, PageHeaderGroup, PageTitle, PageToolbar } from '@wallarm-org/design-system/Page';
import { Radio, RadioDescription, RadioGroup, RadioIndicator, RadioLabel } from '@wallarm-org/design-system/Radio';
import { SearchInput } from '@wallarm-org/design-system/SearchInput';
import { Select, SelectContent, SelectInput, SelectOption, SelectOptionIndicator, SelectOptionText, SelectPositioner } from '@wallarm-org/design-system/Select';
import { Separator } from '@wallarm-org/design-system/Separator';
import { HStack, VStack } from '@wallarm-org/design-system/Stack';
import { Stepper, StepperContent, StepperIndicator, StepperItem, type StepperItemStatus, StepperList, StepperNextTrigger, StepperPrevTrigger, StepperSeparator, StepperTitle, StepperTrigger } from '@wallarm-org/design-system/Stepper';
import { Table } from '@wallarm-org/design-system/Table';
import { useToast } from '@wallarm-org/design-system/Toast';

export const Loading = ({ isLoading }) => {
  const toast = useToast();
  const [rules, setRules] = useState(RULES);
  const [query, setQuery] = useState('');
  const [open, setOpen] = useState(false);
  const [step, setStep] = useState(0);
  const [visited, setVisited] = useState<number[]>([]);
  const [name, setName] = useState(EMPTY_DRAFT.name);
  const [host, setHost] = useState(EMPTY_DRAFT.host);
  const [path, setPath] = useState(EMPTY_DRAFT.path);
  const [methods, setMethods] = useState(EMPTY_DRAFT.methods);
  const [condition, setCondition] = useState(EMPTY_DRAFT.condition);
  const [action, setAction] = useState<RuleAction>(EMPTY_DRAFT.action);
  const [pending, setPending] = useState(false);

  const errors = {
    name: name.trim() === '' ? 'Enter a rule name.' : null,
    host: host.length === 0 ? 'Select a host.' : null,
    path: path.startsWith('/') ? null : 'Start the path with /.',
    methods: methods.length === 0 ? 'Select at least one method.' : null,
    condition: condition.trim() === '' ? 'Write a condition.' : null,
  };
  const valid = [
    !errors.name && !errors.host && !errors.path && !errors.methods,
    !errors.condition,
    true,
    true,
  ];
  const statuses = valid.map<StepperItemStatus>((ok, i) =>
    !visited.includes(i) ? 'upcoming' : ok ? 'completed' : 'danger',
  );
  const showScopeErrors = visited.includes(0);
  const showConditionErrors = visited.includes(1);
  const last = step === RULE_STEPS.length - 1;

  const search = query.trim().toLowerCase();
  const rows = rules.filter(
    rule => rule.name.toLowerCase().includes(search) || rule.path.includes(search),
  );

  const handleCreate = () => {
    setName(EMPTY_DRAFT.name);
    setHost(EMPTY_DRAFT.host);
    setPath(EMPTY_DRAFT.path);
    setMethods(EMPTY_DRAFT.methods);
    setCondition(EMPTY_DRAFT.condition);
    setAction(EMPTY_DRAFT.action);
    setVisited([]);
    setStep(0);
    setOpen(true);
  };
  const handleStepChange = ({ step: next }: { step: number }) => {
    setVisited(prev => (prev.includes(step) ? prev : [...prev, step]));
    setStep(next);
  };
  const handleNameChange = (event: ChangeEvent<HTMLInputElement>) => setName(event.target.value);
  const handleHostChange = ({ value }: { value: string[] }) => setHost(value);
  const handlePathChange = (event: ChangeEvent<HTMLInputElement>) => setPath(event.target.value);
  const handleActionChange = ({ value }: { value: string | null }) =>
    setAction(value === 'monitor' ? 'monitor' : 'block');

  const handleSubmit = async (event: FormEvent) => {
    event.preventDefault();
    if (!valid.every(Boolean)) {
      setVisited([0, 1, 2]);
      setStep(valid.indexOf(false));
      return;
    }
    setPending(true);
    await saveRequest();
    setPending(false);
    setRules(prev => [
      {
        id: `r-${2042 + prev.length}`,
        name,
        host: host[0] ?? '',
        path,
        methods,
        action,
        updatedAt: new Date().toISOString(),
      },
      ...prev,
    ]);
    setOpen(false);
    toast.create({ id: 'rule-created', title: 'Rule created', type: 'default' });
  };

  return (
    <Page name='custom-rules' fullSize fixedHeight data-testid='rules-page'>
      <PageHeader>
        <PageHeaderGroup className='flex-1'>
          <PageTitle>Custom rules</PageTitle>
          <PageDescription>
            Rules that block or monitor requests matching your own conditions, on top of the
            built-in attack detection.
          </PageDescription>
        </PageHeaderGroup>
        <PageActions>
          <Button size='medium' onClick={handleCreate} data-testid='rules-create'>
            <Plus />
            Create rule
          </Button>
        </PageActions>
      </PageHeader>

      <PageToolbar>
        <SearchInput
          value={query}
          onChange={setQuery}
          placeholder='Search name or path'
          className='w-[320px]'
          data-testid='rules-search'
        />
      </PageToolbar>

      <PageContent>
        <Table
          aria-label='Custom rules'
          data={isLoading ? [] : rows}
          columns={RULE_COLUMNS}
          isLoading={isLoading}
          getRowId={getRuleId}
          data-testid='rules-table'
        />
      </PageContent>

      <Drawer open={open} onOpenChange={setOpen} data-testid='rule-drawer'>
        <DrawerContent>
          <DrawerHeader>
            <DrawerTitle>Create rule</DrawerTitle>
          </DrawerHeader>
          {/* noValidate: the page validates itself and shows its own errors. */}
          <form noValidate onSubmit={handleSubmit} className='flex min-h-0 flex-1 flex-col'>
            <Stepper
              count={RULE_STEPS.length}
              step={step}
              onStepChange={handleStepChange}
              className='flex min-h-0 flex-1 flex-col'
              data-testid='rule-stepper'
            >
              <StepperList aria-label='Create rule steps'>
                {RULE_STEPS.map((title, i) => (
                  <StepperItem key={title} index={i} status={statuses[i]}>
                    <StepperTrigger>
                      <StepperIndicator />
                      <StepperTitle>{title}</StepperTitle>
                    </StepperTrigger>
                    <StepperSeparator />
                  </StepperItem>
                ))}
              </StepperList>
              <CodeSnippetAdapterProvider adapter={loadPrismAdapter}>
                <DrawerBody>
                  <StepperContent index={0} className='py-16'>
                    <VStack gap={12}>
                      <Field required>
                        <FieldLabel>
                          Name
                          <FieldIndicator />
                        </FieldLabel>
                        <Input
                          value={name}
                          error={showScopeErrors && Boolean(errors.name)}
                          onChange={handleNameChange}
                          placeholder='Login credential stuffing'
                          data-testid='rule-name'
                        />
                        {showScopeErrors && errors.name && <FieldError>{errors.name}</FieldError>}
                      </Field>
                      <div className='grid grid-cols-2 gap-12'>
                        <Field required>
                          <FieldLabel>
                            Host
                            <FieldIndicator />
                          </FieldLabel>
                          <Select
                            collection={hostCollection}
                            value={host}
                            onValueChange={handleHostChange}
                            invalid={showScopeErrors && Boolean(errors.host)}
                            data-testid='rule-host'
                          >
                            <SelectInput placeholder='Select a host' />
                            <SelectPositioner>
                              <SelectContent>
                                {hostCollection.items.map(item => (
                                  <SelectOption key={item.value} item={item}>
                                    <SelectOptionText>{item.label}</SelectOptionText>
                                    <SelectOptionIndicator />
                                  </SelectOption>
                                ))}
                              </SelectContent>
                            </SelectPositioner>
                          </Select>
                          {showScopeErrors && errors.host && <FieldError>{errors.host}</FieldError>}
                        </Field>
                        <Field required>
                          <FieldLabel>
                            Path
                            <FieldIndicator />
                          </FieldLabel>
                          <Input
                            value={path}
                            error={showScopeErrors && Boolean(errors.path)}
                            onChange={handlePathChange}
                            placeholder='/v2/login'
                            data-testid='rule-path'
                          />
                          {showScopeErrors && errors.path && <FieldError>{errors.path}</FieldError>}
                        </Field>
                      </div>
                      {/* A direct CheckboxGroup child makes Field a fieldset, so each checkbox keeps its
                          own id. Inside a plain field every checkbox label points at the field id,
                          and clicking any method toggles the first. */}
                      <Field data-testid='rule-methods'>
                        <FieldLegend variant='label'>Methods</FieldLegend>
                        <FieldDescription>
                          Requests with other methods skip this rule.
                        </FieldDescription>
                        <CheckboxGroup name='methods' value={methods} onValueChange={setMethods}>
                          {HTTP_METHODS.map(method => (
                            <Checkbox key={method} value={method}>
                              <CheckboxIndicator />
                              <CheckboxLabel>
                                <HttpMethod method={method} />
                              </CheckboxLabel>
                            </Checkbox>
                          ))}
                        </CheckboxGroup>
                        {showScopeErrors && errors.methods && (
                          <FieldError>{errors.methods}</FieldError>
                        )}
                      </Field>
                    </VStack>
                  </StepperContent>

                  <StepperContent index={1} className='py-16'>
                    <Field required>
                      <FieldLabel>
                        Condition
                        <FieldIndicator />
                      </FieldLabel>
                      <FieldDescription>
                        YAML. A request matches when every item under all is true.
                      </FieldDescription>
                      <CodeEditorRoot
                        value={condition}
                        onChange={setCondition}
                        language='yaml'
                        data-testid='rule-condition'
                      >
                        <CodeSnippetHeader>
                          <CodeSnippetTitle>condition.yaml</CodeSnippetTitle>
                          <CodeSnippetActions>
                            <CodeSnippetCopyButton />
                            <CodeSnippetWrapButton />
                          </CodeSnippetActions>
                        </CodeSnippetHeader>
                        <CodeEditorContent lineNumbers aria-label='Rule condition' />
                      </CodeEditorRoot>
                      {showConditionErrors && errors.condition && (
                        <FieldError>{errors.condition}</FieldError>
                      )}
                    </Field>
                  </StepperContent>

                  <StepperContent index={2} className='py-16'>
                    <Field required>
                      <FieldLabel>
                        Action
                        <FieldIndicator />
                      </FieldLabel>
                      <FieldDescription>What happens to a request that matches.</FieldDescription>
                      <RadioGroup
                        variant='card'
                        name='action'
                        value={action}
                        onValueChange={handleActionChange}
                      >
                        <Radio value='block'>
                          <RadioIndicator />
                          <RadioLabel>Block</RadioLabel>
                          <RadioDescription>
                            Return 403 and record the request as an attack.
                          </RadioDescription>
                        </Radio>
                        <Radio value='monitor'>
                          <RadioIndicator />
                          <RadioLabel>Monitor</RadioLabel>
                          <RadioDescription>
                            Let the request through and record it as an attack. Use it to tune a new
                            rule first.
                          </RadioDescription>
                        </Radio>
                      </RadioGroup>
                    </Field>
                  </StepperContent>

                  <StepperContent index={3} className='py-16'>
                    <VStack gap={16}>
                      <Alert color='info'>
                        <AlertIcon />
                        <AlertContent>
                          <AlertTitle>Applies within a minute</AlertTitle>
                          <AlertDescription>
                            Every node picks up the rule on its next sync. Requests already in
                            flight are not rechecked.
                          </AlertDescription>
                        </AlertContent>
                      </Alert>
                      <div>
                        <VStack gap={6} className='pb-8' data-testid='rule-review'>
                          <Attribute orientation='horizontal'>
                            <AttributeLabel width={140}>Name</AttributeLabel>
                            <AttributeValue>{name}</AttributeValue>
                          </Attribute>
                          <Attribute orientation='horizontal'>
                            <AttributeLabel width={140}>Host</AttributeLabel>
                            <AttributeValue>{host[0]}</AttributeValue>
                          </Attribute>
                          <Attribute orientation='horizontal'>
                            <AttributeLabel width={140}>Path</AttributeLabel>
                            <AttributeValue>
                              <InlineCodeSnippet code={path} size='md' />
                            </AttributeValue>
                          </Attribute>
                          <Attribute orientation='horizontal'>
                            <AttributeLabel width={140}>Methods</AttributeLabel>
                            <AttributeValue>
                              <HStack gap={4}>
                                {methods.map(method => (
                                  <HttpMethod key={method} method={method} />
                                ))}
                              </HStack>
                            </AttributeValue>
                          </Attribute>
                          <Attribute orientation='horizontal'>
                            <AttributeLabel width={140}>Action</AttributeLabel>
                            <AttributeValue>
                              <Badge variant='dotted' type='secondary' color={ACTION[action].color}>
                                {ACTION[action].label}
                              </Badge>
                            </AttributeValue>
                          </Attribute>
                        </VStack>
                        <Separator spacing={4} />
                        <HStack justify='between' align='center' className='py-8'>
                          <Heading as='h3' size='md' weight='medium'>
                            Condition
                          </Heading>
                        </HStack>
                        <CodeSnippetRoot code={condition} language='yaml'>
                          <CodeSnippetContent>
                            <CodeSnippetLineNumbers />
                            <CodeSnippetCode />
                          </CodeSnippetContent>
                        </CodeSnippetRoot>
                      </div>
                    </VStack>
                  </StepperContent>
                </DrawerBody>
              </CodeSnippetAdapterProvider>
              <DrawerFooter>
                <DrawerFooterControls placement='left'>
                  <DrawerClose asChild>
                    <Button variant='ghost' color='neutral'>
                      Cancel
                    </Button>
                  </DrawerClose>
                </DrawerFooterControls>
                <DrawerFooterControls placement='right'>
                  <StepperPrevTrigger asChild>
                    <Button variant='outline' color='neutral' data-testid='rule-back'>
                      Back
                    </Button>
                  </StepperPrevTrigger>
                  {last ? (
                    <Button type='submit' loading={pending} data-testid='rule-submit'>
                      Create rule
                    </Button>
                  ) : (
                    <StepperNextTrigger asChild>
                      <Button data-testid='rule-next'>Next</Button>
                    </StepperNextTrigger>
                  )}
                </DrawerFooterControls>
              </DrawerFooter>
            </Stepper>
          </form>
        </DrawerContent>
      </Drawer>
    </Page>
  );
};
```

## Related

- [Create and edit forms](https://wallarm.github.io/design-system/patterns/create-edit-forms.md)
- [Resource list page](https://wallarm.github.io/design-system/patterns/resource-list-page.md)
- [Detail drawer](https://wallarm.github.io/design-system/patterns/detail-drawer.md)
- [Confirmation dialogs](https://wallarm.github.io/design-system/patterns/confirmation-dialogs.md): guard a dirty drawer on close.
- [Feedback toasts](https://wallarm.github.io/design-system/patterns/feedback-toasts.md)
