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.

11.1 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.

"use client";

/* Recursive, expandable JSON-Schema renderer for Carbon API operation parameters.
 *
 * The manifest's schemas are generated by converting the real zod validators
 * (`scripts/lib/validator-to-json-schema.ts`), so they carry enum values, nested
 * object shapes, array element shapes, and constraints. The previous flat renderer
 * collapsed all of that to a bare label — `enum` with the values hidden, `object`
 * with the fields dropped.
 *
 * Not Fumadocs' AutoTypeTable: that reflects TypeScript types out of `.ts` files, so
 * feeding it these 1,495 JSON Schemas would mean code-generating an interface per
 * operation, and it still renders flat with no drill-down. This mirrors the in-house
 * accordion (`editorial/field-table.tsx`) instead — same button + CSS-grid-rows
 * reveal, so nested rows stay in the DOM when collapsed and remain findable with
 * Cmd-F and by the search index.
 */

import { useId, useState } from "react";

export type JsonSchemaNode = {
  type?: string | string[];
  description?: string;
  enum?: unknown[];
  const?: unknown;
  format?: string;
  default?: unknown;
  properties?: Record<string, JsonSchemaNode>;
  required?: string[];
  items?: JsonSchemaNode;
  additionalProperties?: boolean | JsonSchemaNode;
  anyOf?: JsonSchemaNode[];
  minimum?: number;
  maximum?: number;
  exclusiveMinimum?: number;
  exclusiveMaximum?: number;
  minLength?: number;
  maxLength?: number;
  minItems?: number;
  pattern?: string;
};

/** A `type` that arrived as `["string","null"]` — zod's nullable representation. */
function typeNames(node: JsonSchemaNode): string[] {
  if (Array.isArray(node.type)) return node.type.map(String);
  return node.type ? [String(node.type)] : [];
}

function isPlainObjectSchema(node: JsonSchemaNode): boolean {
  return typeNames(node).includes("object") || node.properties != null;
}

/** The value schema of a `Record<string, T>` (zod emits `additionalProperties`). */
function recordValueSchema(node: JsonSchemaNode): JsonSchemaNode | null {
  const additional = node.additionalProperties;
  return additional && typeof additional === "object" ? additional : null;
}

/** The short label shown next to the field name. */
export function typeLabel(node: JsonSchemaNode): string {
  if (!node || Object.keys(node).length === 0) return "any";
  if (node.const !== undefined) return JSON.stringify(node.const);
  if (Array.isArray(node.enum) && node.enum.length > 0) return "enum";

  if (Array.isArray(node.anyOf) && node.anyOf.length > 0) {
    const labels = [...new Set(node.anyOf.map(typeLabel))];
    return labels.join(" | ");
  }

  const names = typeNames(node);

  if (names.includes("array")) {
    const item = node.items;
    const inner = item ? typeLabel(item) : "any";
    const arrayLabel = `${inner}[]`;
    return names.includes("null") ? `${arrayLabel} | null` : arrayLabel;
  }

  if (names.includes("object") || node.properties || recordValueSchema(node)) {
    const value = recordValueSchema(node);
    // A record has a value schema but no fixed properties.
    const base =
      value && !node.properties
        ? `Record<string, ${typeLabel(value)}>`
        : "object";
    return names.includes("null") ? `${base} | null` : base;
  }

  if (names.length > 0) return names.join(" | ");
  return node.format ?? "any";
}

/** Child rows to reveal when a row is expanded, or null when it is a leaf. */
function childrenOf(
  node: JsonSchemaNode
): { properties: Record<string, JsonSchemaNode>; required: Set<string> } | null {
  if (node.properties && Object.keys(node.properties).length > 0) {
    return {
      properties: node.properties,
      required: new Set(node.required ?? []),
    };
  }
  // Array of objects — drill into the element shape.
  const item = node.items;
  if (item?.properties && Object.keys(item.properties).length > 0) {
    return {
      properties: item.properties,
      required: new Set(item.required ?? []),
    };
  }
  // Record whose values are objects.
  const value = recordValueSchema(node);
  if (value?.properties && Object.keys(value.properties).length > 0) {
    return {
      properties: value.properties,
      required: new Set(value.required ?? []),
    };
  }
  return null;
}

/** Constraint chips (`min 0`, `max 1`, …) — the detail a bare type label loses. */
function constraints(node: JsonSchemaNode): string[] {
  const out: string[] = [];
  if (node.minimum !== undefined) out.push(`min ${node.minimum}`);
  if (node.exclusiveMinimum !== undefined) out.push(`> ${node.exclusiveMinimum}`);
  if (node.maximum !== undefined) out.push(`max ${node.maximum}`);
  if (node.exclusiveMaximum !== undefined) out.push(`< ${node.exclusiveMaximum}`);
  if (node.minLength !== undefined) out.push(`min length ${node.minLength}`);
  if (node.maxLength !== undefined) out.push(`max length ${node.maxLength}`);
  if (node.minItems !== undefined) out.push(`min items ${node.minItems}`);
  if (node.format) out.push(node.format);
  if (node.pattern) out.push(`pattern ${node.pattern}`);
  return out;
}

function enumValues(node: JsonSchemaNode): unknown[] | null {
  if (Array.isArray(node.enum) && node.enum.length > 0) return node.enum;
  // `string[]` whose element is an enum — the values belong to the element.
  if (Array.isArray(node.items?.enum) && node.items.enum.length > 0) {
    return node.items.enum;
  }
  return null;
}

function Chip({ children }: { children: React.ReactNode }) {
  return (
    <span className="inline-flex items-center rounded-[5px] border border-ed-hairline bg-ed-inset px-1.5 py-px font-mono text-ed-11 text-ed-ink-66">
      {children}
    </span>
  );
}

function SchemaRow({
  name,
  node,
  required,
  depth,
}: {
  name: string;
  node: JsonSchemaNode;
  required: boolean;
  depth: number;
}) {
  const [open, setOpen] = useState(false);
  const panelId = `schema-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;

  const values = enumValues(node);
  const kids = childrenOf(node);
  const limits = constraints(node);
  // Only offer a chevron when there is genuinely something to reveal — no dead
  // affordances on plain scalar rows.
  const expandable = Boolean(values || kids || limits.length > 0);

  return (
    <div>
      <button
        type="button"
        aria-expanded={expandable ? open : undefined}
        aria-controls={expandable ? panelId : undefined}
        onClick={() => expandable && setOpen((o) => !o)}
        style={{ paddingLeft: `${16 + depth * 18}px` }}
        className={`flex w-full items-center gap-2 py-[11px] pr-4 text-left hover:bg-ed-row-hover ${
          expandable ? "cursor-pointer" : "cursor-default"
        }`}
      >
        <code className="font-mono text-ed-13 text-ed-ink">{name}</code>
        {required ? (
          <span className="text-ed-11 font-medium text-ed-amber-text">
            required
          </span>
        ) : (
          <span className="text-ed-11 font-medium text-ed-ink/48">optional</span>
        )}
        {node.default !== undefined && (
          <span className="font-mono text-ed-11 text-ed-ink/48">
            default {JSON.stringify(node.default)}
          </span>
        )}
        <span className="ml-auto whitespace-nowrap font-mono text-ed-12 text-ed-ink-45">
          {typeLabel(node)}
        </span>
        <span
          aria-hidden="true"
          className={`w-3.5 shrink-0 text-center text-ed-18 leading-none text-ed-brand-ink transition-transform duration-200 motion-reduce:transition-none ${
            expandable ? "" : "opacity-0"
          } ${open ? "rotate-45" : ""}`}
        >
          +
        </span>
      </button>

      {node.description && (
        <p
          style={{ paddingLeft: `${16 + depth * 18}px` }}
          className="m-0 -mt-1 pb-2.5 pr-4 text-ed-14 leading-normal text-ed-ink/74"
        >
          {node.description}
        </p>
      )}

      {expandable && (
        <div
          className={`grid overflow-hidden transition-[grid-template-rows] duration-200 ease-out motion-reduce:transition-none ${
            open ? "grid-rows-[1fr]" : "grid-rows-[0fr]"
          }`}
        >
          <div className="min-h-0 overflow-hidden">
            {/* A `0fr` row still renders its content, so nested rows stay tabbable
                while collapsed unless they are inert. */}
            <div
              id={panelId}
              role="region"
              inert={!open}
              className="border-t border-ed-hairline bg-ed-inset"
            >
              {(values || limits.length > 0) && (
                <div
                  style={{ paddingLeft: `${16 + (depth + 1) * 18}px` }}
                  className="flex flex-wrap items-center gap-1.5 py-2.5 pr-4"
                >
                  {limits.map((c) => (
                    <Chip key={c}>{c}</Chip>
                  ))}
                  {values?.map((v) => (
                    <Chip key={String(v)}>{JSON.stringify(v)}</Chip>
                  ))}
                </div>
              )}
              {kids && (
                <div className="divide-y divide-ed-hairline border-t border-ed-hairline first:border-t-0">
                  {sortByRequired(kids.properties, kids.required).map((key) => (
                    <SchemaRow
                      key={key}
                      name={key}
                      node={kids.properties[key]}
                      required={kids.required.has(key)}
                      depth={depth + 1}
                    />
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/** Required fields first, then alphabetical — the order a caller fills them in. */
function sortByRequired(
  properties: Record<string, JsonSchemaNode>,
  required: Set<string>
): string[] {
  return Object.keys(properties).sort((a, b) => {
    const diff = Number(required.has(b)) - Number(required.has(a));
    return diff !== 0 ? diff : a.localeCompare(b);
  });
}

export function SchemaTable({ schema }: { schema: unknown }) {
  const root = (schema ?? {}) as JsonSchemaNode;
  const properties = root.properties ?? {};
  const required = new Set(root.required ?? []);
  const names = sortByRequired(properties, required);

  if (names.length === 0) {
    return (
      <p className="mt-2.5 text-ed-15 leading-normal text-ed-ink/74">
        This operation takes no arguments.
      </p>
    );
  }

  return (
    <div className="my-5 overflow-hidden rounded-xl border border-ed-hairline bg-ed-paper">
      <div className="flex items-center gap-3 border-b border-ed-hairline bg-ed-header px-4 py-[9px] font-mono text-ed-10 font-semibold uppercase tracking-[0.07em] text-ed-ink-45">
        <span>Parameter</span>
        <span className="ml-auto">Type</span>
        <span className="w-3.5" />
      </div>
      <div className="divide-y divide-ed-hairline">
        {names.map((name) => (
          <SchemaRow
            key={name}
            name={name}
            node={properties[name]}
            required={required.has(name)}
            depth={0}
          />
        ))}
      </div>
    </div>
  );
}