SPB Git

Repository Public

extras.tsx 9.5 KB 177 lines tsx

1"use client";2import { useMemo, useState, type ReactNode } from "react";3import { useI18n } from "@/i18n";4import { fromLocalInput, localTimeZone, toLocalInput } from "@/lib/format";5import { linkify } from "@/lib/linkify";6import { encodeQr, qrPath, QrTooLongError } from "@/lib/qr";7import { schemaToFields, type FieldError, type FormField, type FormValues } from "@/lib/schemaForm";8import { Button, CopyButton } from "./core";9import { Checkbox, Segmented, SelectField, Switch, TextAreaField, TextField } from "./form";1011/** Plain text with preserved line breaks and auto-linked http(s) URLs. Rendered as text nodes and <a>: no HTML. */12export function Linkified({ text }: { text: string }) {13  const segments = useMemo(() => linkify(text), [text]);14  return (15    <span className="pre">16      {segments.map((s, i) => (s.kind === "link" ? <a key={i} href={s.href} target="_blank" rel="noopener noreferrer nofollow">{s.value}</a> : <span key={i}>{s.value}</span>))}17    </span>18  );19}2021/** QR code drawn locally as SVG (always dark on light so scanners read it in both themes). */22export function QrCode({ value, label }: { value: string; label: string }) {23  const { t } = useI18n();24  const drawn = useMemo(() => {25    try {26      return qrPath(encodeQr(value));27    } catch (e) {28      if (e instanceof QrTooLongError) return null;29      throw e;30    }31  }, [value]);32  if (!drawn) return <p className="muted">{t("ui.qr.tooLong")}</p>;33  return (34    <svg className="mcc-qr" viewBox={drawn.viewBox} role="img" aria-label={label} shapeRendering="crispEdges">35      <rect className="bg" width="100%" height="100%" />36      <path className="fg" d={drawn.d} />37    </svg>38  );39}4041export type RangePreset = "1h" | "24h" | "7d" | "30d";42export type RangeValue = { kind: "preset"; preset: RangePreset } | { kind: "custom"; from: string; to: string };43export const PRESET_MS: Record<RangePreset, number> = { "1h": 3600_000, "24h": 86400_000, "7d": 7 * 86400_000, "30d": 30 * 86400_000 };44export function resolveRange(v: RangeValue, now: number = Date.now()): { from: string; to: string; fromMs: number; toMs: number } {45  if (v.kind === "custom") return { from: v.from, to: v.to, fromMs: Date.parse(v.from), toMs: Date.parse(v.to) };46  const fromMs = now - PRESET_MS[v.preset];47  return { from: new Date(fromMs).toISOString(), to: new Date(now).toISOString(), fromMs, toMs: now };48}4950/** Period selector: 1 h / 24 h / 7 d / 30 d presets, or a custom range entered in the browser time zone (shown). */51export function DateTimeRangePicker({ value, onChange, presets = ["1h", "24h", "7d", "30d"] }: { value: RangeValue; onChange: (v: RangeValue) => void; presets?: readonly RangePreset[] }) {52  const { t } = useI18n();53  const [draft, setDraft] = useState<{ from: string; to: string } | null>(null);54  const custom = value.kind === "custom" || draft !== null;55  const d = draft ?? (value.kind === "custom" ? { from: toLocalInput(value.from), to: toLocalInput(value.to) } : null);56  const fromIso = d ? fromLocalInput(d.from) : null;57  const toIso = d ? fromLocalInput(d.to) : null;58  const invalid = !!d && (!fromIso || !toIso || Date.parse(fromIso) >= Date.parse(toIso));59  return (60    <div className="row-wrap" role="group" aria-label={t("ui.range.label")}>61      <Segmented62        label={t("ui.range.label")}63        value={custom ? "custom" : value.kind === "preset" ? value.preset : "custom"}64        onChange={(v) => {65          if (v === "custom") {66            const r = resolveRange(value);67            setDraft({ from: toLocalInput(r.fromMs), to: toLocalInput(r.toMs) });68          } else {69            setDraft(null);70            onChange({ kind: "preset", preset: v });71          }72        }}73        options={[...presets.map((p) => ({ value: p, label: t(`ui.range.${p}`), title: t(`ui.range.long.${p}`) })), { value: "custom" as const, label: t("ui.range.custom") }]}74      />75      {custom && d ? (76        <form className="row-wrap" onSubmit={(e) => { e.preventDefault(); if (!invalid && fromIso && toIso) { onChange({ kind: "custom", from: fromIso, to: toIso }); setDraft(null); } }}>77          <TextField label={t("ui.range.from")} hideLabel type="datetime-local" value={d.from} onChange={(from) => setDraft({ ...d, from })} />78          <TextField label={t("ui.range.to")} hideLabel type="datetime-local" value={d.to} onChange={(to) => setDraft({ ...d, to })} error={invalid ? t("ui.range.invalid") : undefined} />79          <Button size="sm" type="submit" disabled={invalid || draft === null}>{t("common.apply")}</Button>80          <span className="mcc-hint">{t("ui.range.zone", { zone: localTimeZone() })}</span>81        </form>82      ) : null}83    </div>84  );85}8687/** Form generated from a JSON Schema (`params_schema`). Validation messages come from `validateForm`. */88export function SchemaForm({ schema, values, onChange, errors, disabled, emptyText }: { schema: unknown; values: FormValues; onChange: (v: FormValues) => void; errors: readonly FieldError[]; disabled?: boolean; emptyText?: string }) {89  const { t } = useI18n();90  const fields = useMemo(() => schemaToFields(schema), [schema]);91  if (fields.length === 0) return emptyText ? <p className="muted">{emptyText}</p> : null;92  const set = (name: string, v: unknown) => onChange({ ...values, [name]: v });93  const msg = (f: FormField): string | undefined => {94    const e = errors.find((x) => x.field === f.name);95    return e ? t(`ui.schema.${e.code}`, { limit: e.limit ?? "" }) : undefined;96  };97  return (98    <div className="mcc-form">99      {fields.map((f) => {100        const common = { label: f.label, hint: f.description, error: msg(f), required: f.required, disabled };101        const v = values[f.name];102        switch (f.kind) {103          case "boolean":104            return <Switch key={f.name} label={f.label} checked={v === true} onChange={(x) => set(f.name, x)} {...(f.description ? { hint: f.description } : {})} {...(disabled ? { disabled } : {})} />;105          case "enum":106            return <SelectField key={f.name} {...common} value={String(v ?? "")} onChange={(x) => set(f.name, x)} options={[...(f.required && v ? [] : [{ value: "", label: t("ui.schema.choose") }]), ...(f.options ?? []).map((o) => ({ value: o, label: o }))]} />;107          case "enum-list":108            return (109              <fieldset key={f.name} className="mcc-fieldset" disabled={disabled}>110                <legend>{f.label}</legend>111                {(f.options ?? []).map((o) => {112                  const list = Array.isArray(v) ? (v as string[]) : [];113                  return <Checkbox key={o} label={o} checked={list.includes(o)} onChange={(c) => set(f.name, c ? [...list, o] : list.filter((x) => x !== o))} />;114                })}115                {msg(f) ? <span className="mcc-error-text" role="alert">{msg(f)}</span> : null}116              </fieldset>117            );118          case "text":119          case "json":120          case "string-list":121            return <TextAreaField key={f.name} {...common} hint={f.kind === "string-list" ? `${f.description ? f.description + " " : ""}${t("ui.schema.listHint")}` : f.kind === "json" ? `${f.description ? f.description + " " : ""}${t("ui.schema.jsonHint")}` : f.description} value={Array.isArray(v) ? v.join("\n") : String(v ?? "")} onChange={(x) => set(f.name, x)} spellCheck={false} />;122          case "integer":123          case "number":124            return <TextField key={f.name} {...common} inputMode={f.kind === "integer" ? "numeric" : "decimal"} mono value={String(v ?? "")} onChange={(x) => set(f.name, x)} />;125          default:126            return <TextField key={f.name} {...common} value={String(v ?? "")} onChange={(x) => set(f.name, x)} {...(f.maxLength !== undefined ? { maxLength: f.maxLength } : {})} />;127        }128      })}129    </div>130  );131}132133export interface LogLine {134  id: number | string;135  text: string;136  stream?: "stdout" | "stderr" | "system" | undefined;137}138/** Bounded output viewer: text nodes only, optional search with highlighted matches, copy. */139export function LogView({ lines, label, empty, truncated }: { lines: readonly LogLine[]; label: string; empty: ReactNode; truncated?: boolean }) {140  const { t, tn } = useI18n();141  const [q, setQ] = useState("");142  const needle = q.trim().toLowerCase();143  const shown = needle ? lines.filter((l) => l.text.toLowerCase().includes(needle)) : lines;144  const mark = (text: string): ReactNode => {145    if (!needle) return text;146    const out: ReactNode[] = [];147    let i = 0;148    const lower = text.toLowerCase();149    for (;;) {150      const j = lower.indexOf(needle, i);151      if (j === -1) break;152      if (j > i) out.push(text.slice(i, j));153      out.push(<mark key={j}>{text.slice(j, j + needle.length)}</mark>);154      i = j + needle.length;155    }156    out.push(text.slice(i));157    return out;158  };159  return (160    <div className="stack-sm">161      <div className="row-between">162        <div className="row">163          <TextField label={t("ui.log.search")} hideLabel placeholder={t("ui.log.search")} icon="search" value={q} onChange={setQ} type="search" />164          {needle ? <span className="mcc-hint nowrap" role="status">{tn("ui.log.matches", shown.length)}</span> : null}165        </div>166        <CopyButton text={lines.map((l) => l.text).join("\n")}>{t("ui.log.copy")}</CopyButton>167      </div>168      {truncated ? <p className="mcc-hint">{t("ui.log.truncated")}</p> : null}169      {lines.length === 0 ? empty : (170        <pre className="mcc-log" tabIndex={0} aria-label={label} data-testid="log-output">171          {shown.map((l) => <span key={l.id} className={l.stream === "stderr" ? "err" : l.stream === "system" ? "sys" : undefined}>{mark(l.text)}{l.text.endsWith("\n") ? "" : "\n"}</span>)}172        </pre>173      )}174    </div>175  );176}177
Files main
Menu

Theme