truncate.ts 681 B

123456789101112131415161718192021
  1. import { z } from "zod";
  2. import { defineDirective, resolvePropValue } from "@json-render/core";
  3. export const truncateDirective = defineDirective({
  4. name: "$truncate",
  5. description: "Truncate text to a max length with a suffix.",
  6. schema: z.object({
  7. $truncate: z.unknown(),
  8. length: z.number().optional(),
  9. suffix: z.string().optional(),
  10. }),
  11. resolve(raw, ctx) {
  12. const resolved = resolvePropValue(raw.$truncate, ctx);
  13. const text = resolved != null ? String(resolved) : "";
  14. const maxLength = raw.length ?? 100;
  15. const suffix = raw.suffix ?? "...";
  16. if (text.length <= maxLength) return text;
  17. return text.slice(0, maxLength) + suffix;
  18. },
  19. });