Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

4.2 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import type { TemplatePart, ValueOrRef } from "@carbon/ee/workflows";
import type { VariableTextPart } from "@carbon/react/VariableText";
import { decodeTokenId, encodeTokenId, namedPath, refLabel } from "./tokenId";

/** What the editor shows for a stored value. Labels are resolved here and nowhere else. */
export function toEditorParts(
  value: ValueOrRef | undefined,
  nodeName: (id: string) => string | undefined,
  /** Keyed by position in a template's parts; a bare reference is position 0. */
  partIssues?: Record<number, string>,
  /** Path segment -> what the customer calls it. A custom field's segment is an id. */
  segmentLabels?: Record<string, string>
): VariableTextPart[] {
  const token = (part: TemplatePart, index: number): VariableTextPart => {
    if (part.kind === "text") return { kind: "text", text: part.text };
    return {
      kind: "token",
      id: encodeTokenId(part),
      label: refLabel(
        part,
        part.kind === "ref" ? nodeName(part.nodeId) : undefined,
        namedPath(part.path, segmentLabels)
      ),
      invalid: partIssues?.[index] !== undefined
    };
  };

  if (!value) return [];
  if (value.kind === "template") return value.parts.map(token);
  if (value.kind === "ref" || value.kind === "item") return [token(value, 0)];
  // A set of rows is edited row by row, never as one stretch of text.
  if (value.kind === "pairs") return [];
  const text = value.value == null ? "" : String(value.value);
  return text ? [{ kind: "text", text }] : [];
}

export type SerializeOptions = {
  /**
   * True where the field type-checks a reference against its declared type.
   * A lone variable is then stored as a bare `ref`, which is what the rest of the
   * builder expects. False on template fields, whose variables may be of any type:
   * `checkInputs` accepts any template for a text input but type-checks a bare
   * ref, so collapsing there would reject values the template form allows.
   */
  collapseSingleRef: boolean;
};

/**
 * Drops the space the picker leaves after a token, and the one a removed token leaves
 * before the next — only meaningful on blur, since until then it is the gap before the
 * next word. While it survives, a lone variable stays a template and the clause loses
 * the variable's own type. Returns the same array when there is nothing to trim, so
 * callers can skip the write.
 */
export function withoutEdgeSpace(
  parts: VariableTextPart[]
): VariableTextPart[] {
  // Space at either end of a field with no variable in it may well be deliberate.
  if (!parts.some((part) => part.kind === "token")) return parts;
  let trimmed = parts;

  const last = trimmed[trimmed.length - 1];
  if (last?.kind === "text") {
    const text = last.text.replace(/\s+$/, "");
    if (text !== last.text) {
      trimmed = text
        ? [...trimmed.slice(0, -1), { ...last, text }]
        : trimmed.slice(0, -1);
    }
  }

  const first = trimmed[0];
  if (first?.kind === "text") {
    const text = first.text.replace(/^\s+/, "");
    if (text !== first.text) {
      trimmed = text
        ? [{ ...first, text }, ...trimmed.slice(1)]
        : trimmed.slice(1);
    }
  }

  return trimmed;
}

/** Plain text stays a literal; mixed content is a template. */
export function fromEditorParts(
  parts: VariableTextPart[],
  { collapseSingleRef }: SerializeOptions
): ValueOrRef | undefined {
  const result: TemplatePart[] = [];
  for (const part of parts) {
    if (part.kind === "text") {
      if (part.text) result.push({ kind: "text", text: part.text });
      continue;
    }
    const ref = decodeTokenId(part.id);
    if (ref) result.push(ref);
  }

  if (result.length === 0) return undefined;
  if (collapseSingleRef && result.length === 1 && result[0].kind !== "text") {
    return result[0];
  }
  if (result.every((p) => p.kind === "text")) {
    return {
      kind: "literal",
      type: { kind: "primitive", of: "string" },
      value: result.map((p) => (p.kind === "text" ? p.text : "")).join("")
    };
  }
  return { kind: "template", parts: result };
}