Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

9.4 KB
Raw Blame
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Icon } from "@editor/ui/Icon";
import { ActionIcon, Button, Dropdown, IconPicker, Input } from "@editor/ui";
import { PipelineBlockerTooltip } from "@processor/components/pipelines/PipelineBlockerTooltip";
import { PIPELINE_ICON_OPTIONS } from "@processor/components/pipelines/pipelineIcon";
import { EnforceAsPolicyControl } from "@processor/components/pipelines/EnforceAsPolicyControl";
import "@processor/components/pipelines/PipelineEditHeader.css";

export interface PipelineEditHeaderProps {
  name: string;
  onNameChange: (name: string) => void;
  /** Row icon key (see pipelineIcon); chosen from the picker beside the name. */
  icon: string;
  onIconChange: (key: string) => void;
  /** "Enforce as policy" toggle, shown in the actions row. */
  required: boolean;
  onRequiredChange: (required: boolean) => void;
  /** Whether this pipeline's source is the editor. */
  runsOnEditor?: boolean;
  /**
   * Whether the user may edit pipelines and policies (a manager). When false everything here is
   * read-only - save, pause, delete, reprocess, rename and the enforce toggle.
   */
  canManagePolicies?: boolean;
  /**
   * The permission check has not resolved yet. Config actions stay locked (fail-closed), but the
   * manager-only reason is withheld so a still-loading manager isn't told they lack permission.
   */
  permissionsLoading?: boolean;

  /** The pipeline's live state. Toggling it takes effect immediately, not on save. */
  enabled: boolean;
  onTogglePause: () => void;
  togglingEnabled: boolean;

  onBack: () => void;

  canSave: boolean;
  /** Everything still owed before the edits can be saved, shown on the disabled Save button. */
  blockers: string[];
  saving: boolean;
  onSave: () => void;

  /** Run the saved pipeline against its real input, delivering to its real destination. */
  onRun: () => void;
  running: boolean;
  /** Reprocess everything in the sources: clears the processed record, then runs at once. */
  onReprocess: () => void;
  reprocessing: boolean;
  onDelete: () => void;
}

/**
 * Edit mode's toolbar over an existing, live pipeline. The left is what it *is* - a back arrow, its
 * name as the page title, a pencil to rename in place. The right is what you can *do to it*: pause
 * or activate it (an operational toggle that acts at once, matching the Policies vocabulary), run it
 * now, and - behind an overflow, since they are rare or destructive - reprocess its sources or delete
 * it. Saving the chain edits is the primary action, on the far right. (Reading the definition is an
 * inspect action, so it lives in the graph toolbar beside Test, not here.)
 */
export function PipelineEditHeader({
  name,
  onNameChange,
  icon,
  onIconChange,
  required,
  onRequiredChange,
  runsOnEditor = false,
  canManagePolicies = true,
  permissionsLoading = false,
  enabled,
  onTogglePause,
  togglingEnabled,
  onBack,
  canSave,
  blockers,
  saving,
  onSave,
  onRun,
  running,
  onReprocess,
  reprocessing,
  onDelete,
}: PipelineEditHeaderProps) {
  const { t } = useTranslation();
  const readOnly = !canManagePolicies;
  const [renaming, setRenaming] = useState(false);
  const [draft, setDraft] = useState(name);
  const inputRef = useRef<HTMLInputElement>(null);
  // Enter and Escape both end the rename, which unmounts the input - and unmounting a focused input
  // fires blur in a real browser (jsdom does not). Without this guard that blur would re-run the
  // commit, so Escape would save the very draft it was meant to discard. The key handler sets this so
  // the trailing blur is ignored; a plain click-away leaves it false and blur commits as normal.
  const keyHandledRef = useRef(false);

  useEffect(() => {
    if (renaming) inputRef.current?.select();
  }, [renaming]);

  function startRename() {
    keyHandledRef.current = false;
    setDraft(name);
    setRenaming(true);
  }

  // End the rename, committing the draft only when asked and only if non-empty (an all-whitespace
  // rename would leave the pipeline titleless).
  function finishRename(commit: boolean) {
    keyHandledRef.current = true;
    if (commit) {
      const next = draft.trim();
      if (next) onNameChange(next);
    }
    setRenaming(false);
  }

  // Clicking away commits; the unmount-triggered blur that follows a key press does not (the key
  // already decided the outcome).
  function handleBlur() {
    if (keyHandledRef.current) {
      keyHandledRef.current = false;
      return;
    }
    finishRename(true);
  }

  return (
    <section className="portal-pipeline-edit-header">
      <div className="portal-pipeline-edit-header__identity">
        <ActionIcon
          variant="quiet"
          size="sm"
          onClick={onBack}
          aria-label={t("portal.pipelines.builder.back")}
        >
          <Icon name="arrow-left" size={"1.25rem"} />
        </ActionIcon>

        <IconPicker
          value={icon}
          onChange={onIconChange}
          options={PIPELINE_ICON_OPTIONS}
          ariaLabel={t("portal.pipelines.builder.icon.label")}
          disabled={readOnly}
        />

        {renaming ? (
          <Input
            ref={inputRef}
            className="portal-pipeline-edit-header__name-input"
            value={draft}
            aria-label={t("portal.pipelines.composer.name")}
            onChange={(e) => setDraft(e.target.value)}
            onBlur={handleBlur}
            onKeyDown={(e) => {
              if (e.key === "Enter") finishRename(true);
              if (e.key === "Escape") finishRename(false);
            }}
          />
        ) : (
          <>
            <h1 className="portal-pipeline-edit-header__title">{name}</h1>
            {!readOnly && (
              <ActionIcon
                variant="quiet"
                size="sm"
                onClick={startRename}
                aria-label={t("portal.pipelines.builder.rename")}
              >
                <Icon name="pencil" size={"1rem"} />
              </ActionIcon>
            )}
          </>
        )}
      </div>

      <div className="portal-pipeline-edit-header__actions">
        {runsOnEditor && (
          <EnforceAsPolicyControl
            required={required}
            onRequiredChange={onRequiredChange}
            disabled={!canManagePolicies}
            permissionsLoading={permissionsLoading}
          />
        )}

        {/* Pause and Save both write the whole policy, so they are mutually exclusive: neither can
            start while the other is committing, or the two writes race and the loser's version wins. */}
        <Button
          variant="secondary"
          size="sm"
          loading={togglingEnabled}
          disabled={saving || readOnly}
          onClick={onTogglePause}
          leftSection={
            enabled ? (
              <Icon name="pause" size={"1.125rem"} />
            ) : (
              <Icon name="power" size={"1.125rem"} />
            )
          }
        >
          {enabled
            ? t("portal.pipelines.builder.pause")
            : t("portal.pipelines.builder.activate")}
        </Button>

        {/* Run and Reprocess both start a run, so only one at a time: each is disabled while the
            other is in flight, matching the handler guards (a click otherwise silently no-ops). */}
        <Button
          variant="secondary"
          size="sm"
          loading={running}
          disabled={reprocessing}
          onClick={onRun}
          leftSection={<Icon name="play" size={"1.125rem"} />}
        >
          {t("portal.pipelines.detail.run")}
        </Button>

        {/* Rare and destructive actions kept off the row so they do not compete with running. */}
        <Dropdown.Root align="end">
          <Dropdown.Trigger>
            <ActionIcon
              variant="tertiary"
              size="sm"
              aria-label={t("portal.pipelines.builder.moreActions")}
            >
              <Icon name="ellipsis" size={"1.125rem"} />
            </ActionIcon>
          </Dropdown.Trigger>
          <Dropdown.Menu>
            <Dropdown.Item
              onSelect={onReprocess}
              disabled={reprocessing || running || readOnly}
              leading={<Icon name="rotate-ccw" size={"1.125rem"} />}
            >
              {t("portal.pipelines.detail.clearHistory")}
            </Dropdown.Item>
            <Dropdown.Divider />
            <Dropdown.Item
              onSelect={onDelete}
              disabled={readOnly}
              className="portal-pipeline-edit-header__delete-item"
              leading={<Icon name="trash" size={"1.125rem"} />}
            >
              {t("portal.pipelines.detail.delete")}
            </Dropdown.Item>
          </Dropdown.Menu>
        </Dropdown.Root>

        {/* Wrapped in a span so the disabled button's hover still reaches the tooltip. */}
        <PipelineBlockerTooltip
          heading={t("portal.pipelines.builder.blocker.saveHeading")}
          blockers={
            readOnly && !permissionsLoading
              ? [t("portal.pipelines.builder.blocker.managerOnly")]
              : blockers
          }
        >
          <span className="portal-pipeline-edit-header__save">
            <Button
              size="sm"
              onClick={onSave}
              loading={saving}
              disabled={!canSave || togglingEnabled || readOnly}
            >
              {t("portal.pipelines.composer.save")}
            </Button>
          </span>
        </PipelineBlockerTooltip>
      </div>
    </section>
  );
}