From 490e2858a11ed5821343d8808a5eece8cead64ad Mon Sep 17 00:00:00 2001 From: Mathias Oterhals Myklebust Date: Fri, 30 Aug 2024 12:52:00 +0200 Subject: [PATCH] feat(compensations): move offices string to preview subtitle and reformat --- studio/schemas/documents/compensations.ts | 40 +++++++++++++++-------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/studio/schemas/documents/compensations.ts b/studio/schemas/documents/compensations.ts index 25e045ef8..060defc7d 100644 --- a/studio/schemas/documents/compensations.ts +++ b/studio/schemas/documents/compensations.ts @@ -5,8 +5,14 @@ import offices from "../objects/offices"; import { title } from "../fields/text"; import { benefitId } from "./benefit"; -// smallest number of offices where ellipsis (...) will be used in preview -const OFFICES_PREVIEW_ELLIPSIS_LIMIT = 5; +/* + smallest number of offices where the preview string is shortened + (should be at least 2) + 2 => Trondheim, and more + 3 => Trondheim, Oslo, and more + 4 => Trondheim, Oslo, Bergen, and more +*/ +const OFFICES_PREVIEW_CUTOFF = 2; export const compensationsId = "compensations"; @@ -36,35 +42,41 @@ const compensations = defineType({ ], preview: { select: { - subtitle: "basicTitle", + title: "basicTitle", /* Array object values are accessed with dot notation and array index: "offices.0.basicTitle" This limits the preview to only select a subset of the array https://www.sanity.io/docs/previews-list-views#62febb15a63a */ - ...[...Array(OFFICES_PREVIEW_ELLIPSIS_LIMIT).keys()].reduce( + ...[...Array(OFFICES_PREVIEW_CUTOFF).keys()].reduce( (o, i) => ({ ...o, [`office${i}`]: `offices.${i}.basicTitle` }), {}, ), }, - prepare({ subtitle, ...officesMap }) { + prepare({ title, ...officesMap }) { const offices = Object.values(officesMap).filter( (o) => o !== undefined, ); - let title; - if (offices.length >= OFFICES_PREVIEW_ELLIPSIS_LIMIT) { - title = - offices.slice(0, OFFICES_PREVIEW_ELLIPSIS_LIMIT - 1).join(", ") + - ", ..."; - } else { - title = offices.join(", "); - } return { title, - subtitle, + subtitle: previewStringFromArray(offices, OFFICES_PREVIEW_CUTOFF), }; }, }, }); +function previewStringFromArray( + array: string[], + cutoff: number, +): string | undefined { + if (array.length === 0) { + return undefined; + } else if (array.length === 1) { + return array[0]; + } else if (array.length >= cutoff) { + return array.toSpliced(cutoff - 1).join(", ") + ", and more"; + } + return array.toSpliced(-1).join(", ") + " and " + array.at(-1); +} + export default compensations;