All files / src/apps/user/pages/rules DomainListInput.tsx

98.41% Statements 62/63
90.47% Branches 38/42
100% Functions 15/15
98.03% Lines 50/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140                              6x   6x       185x 185x 185x 185x 185x 184x 184x 184x 184x 184x 366x 172x 170x       6x 85x   91x       6x 83x 83x 83x 37x 37x 37x 37x     83x     6x         78x 78x 78x   78x 7x 7x 5x 5x     78x 1x   78x           30x 30x                           1x                         63x   63x 61x     66x 3x 3x 63x       2x                                
import { X } from "lucide-react";
import React, { useState } from "react";
 
/**
 * A Tools rule's sources: web domains, one chip each.
 *
 * Takes what a person pastes as well as what they type — a link, a wildcard,
 * several at once separated by commas or spaces — and shows each as the
 * domain svc-core will store (`app/util/web_domains.py`): lowercase, without
 * a scheme, a path or `www.`. An entry that names no domain stays visible,
 * marked, so the person can fix it; saving refuses it either way. The value
 * travels as the builder's comma-separated text, like every list parameter.
 */
 
/** The most domains one rule's action may name — svc-core's `MAX_DOMAINS`. */
export const MAX_DOMAINS = 50;
 
const LABEL = /^(?!-)[\p{L}\p{N}-]{1,63}(?<!-)$/u;
 
/** The domain `raw` names, as svc-core stores it — `""` when it names none. */
export function normaliseDomain(raw: string): string {
  let text = raw.trim().toLowerCase();
  if (text.includes("://")) text = text.split("://", 2)[1];
  text = text.split(/[/?#]/, 1)[0];
  text = text.slice(text.lastIndexOf("@") + 1);
  if (text.startsWith("[")) return "";
  text = text.split(":", 1)[0].replace(/^\.+|\.+$/g, "");
  if (text.startsWith("*.")) text = text.slice(2);
  if (text.startsWith("www.")) text = text.slice(4);
  const labels = text.split(".");
  if (labels.length < 2 || text.length > 253) return "";
  if (!labels.every((label) => LABEL.test(label))) return "";
  if (/^\d+$/.test(labels[labels.length - 1])) return "";
  return text;
}
 
/** The entries a value holds, as written. */
const entriesOf = (value: string): string[] =>
  value
    .split(/[\s,;]+/)
    .map((part) => part.trim())
    .filter(Boolean);
 
/** Each entry once, as stored where it names a domain, as written where not. */
const tidy = (entries: string[]): string[] => {
  const seen = new Set<string>();
  const kept: string[] = [];
  for (const entry of entries) {
    const shown = normaliseDomain(entry) || entry;
    Eif (!seen.has(shown)) {
      seen.add(shown);
      kept.push(shown);
    }
  }
  return kept;
};
 
const DomainListInput: React.FC<{
  value: string;
  onChange: (value: string) => void;
  label: string;
}> = ({ value, onChange, label }) => {
  const [draft, setDraft] = useState("");
  const domains = tidy(entriesOf(value));
  const invalid = domains.filter((entry) => !normaliseDomain(entry));
 
  const commit = (text: string) => {
    const added = entriesOf(text);
    if (added.length === 0) return;
    onChange(tidy([...domains, ...added]).join(", "));
    setDraft("");
  };
 
  const remove = (entry: string) =>
    onChange(domains.filter((d) => d !== entry).join(", "));
 
  return (
    <div className="space-y-1.5">
      <div
        className="flex flex-wrap items-center gap-1.5 rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700 px-2 py-1.5 focus-within:ring-2 focus-within:ring-gray-300 dark:focus-within:ring-gray-500"
      >
        {domains.map((entry) => {
          const ok = !!normaliseDomain(entry);
          return (
            <span
              key={entry}
              title={ok ? undefined : "Not a web domain — write it as example.com"}
              className={`inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 font-mono text-xs ${
                ok
                  ? "border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-800 text-gray-700 dark:text-gray-200"
                  : "border-dashed border-gray-400 dark:border-gray-500 text-gray-500 dark:text-gray-400 line-through"
              }`}
            >
              {entry}
              <button
                type="button"
                aria-label={`Remove ${entry}`}
                onClick={() => remove(entry)}
                className="rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-200"
              >
                <X className="size-3" />
              </button>
            </span>
          );
        })}
        <input
          aria-label={label}
          value={draft}
          placeholder={domains.length === 0 ? "gov.uk, ico.org.uk" : "Add a source"}
          onChange={(e) => {
            const text = e.target.value;
            // A separator typed or pasted ends an entry.
            if (/[\s,;]/.test(text)) commit(text);
            else setDraft(text);
          }}
          onKeyDown={(e) => {
            if (e.key === "Enter") {
              e.preventDefault();
              commit(draft);
            } else Iif (e.key === "Backspace" && !draft && domains.length > 0) {
              remove(domains[domains.length - 1]);
            }
          }}
          onBlur={() => commit(draft)}
          className="min-w-[8rem] flex-1 bg-transparent px-1 py-0.5 font-mono text-sm text-gray-800 dark:text-gray-200 placeholder-gray-400 focus:outline-none"
        />
      </div>
      {(invalid.length > 0 || domains.length > 0) && (
        <p className="text-[11px] leading-snug text-gray-500 dark:text-gray-400">
          {invalid.length > 0
            ? `Not a web domain: ${invalid.join(", ")} — write each as example.com.`
            : `${domains.length} of ${MAX_DOMAINS} sources.`}
        </p>
      )}
    </div>
  );
};
 
export default DomainListInput;