Skip to content

Commit

Permalink
feat(compensations): move offices string to preview subtitle and refo…
Browse files Browse the repository at this point in the history
…rmat
  • Loading branch information
mathiazom committed Aug 30, 2024
1 parent 156d6d1 commit 0dec9af
Showing 1 changed file with 35 additions and 17 deletions.
52 changes: 35 additions & 17 deletions studio/schemas/documents/compensations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,15 @@ 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;
/*
maximum number of offices without preview string shortening
(should be at least 2)
given array: ["Trondheim", "Oslo", "Bergen", "Molde"]
2 => Trondheim, and more
3 => Trondheim, Oslo, and more
4 => Trondheim, Oslo, Bergen, and Molde
*/
const OFFICES_PREVIEW_CUTOFF = 3;

export const compensationsId = "compensations";

Expand Down Expand Up @@ -36,35 +43,46 @@ 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 + 1).keys()].reduce(
(o, i) => ({ ...o, [`office${i}`]: `offices.${i}.basicTitle` }),
{},
),
},
prepare({ subtitle, ...officesMap }) {
const offices = Object.values<string>(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(", ");
}
prepare({ title, ...officesMap }) {
return {
title,
subtitle,
subtitle: previewStringFromOfficesMap(
officesMap,
OFFICES_PREVIEW_CUTOFF,
),
};
},
},
});

function previewStringFromOfficesMap(
officesMap: {
[key: string]: string;
},
cutoff: number,
): string | undefined {
const offices = Object.values<string>(officesMap).filter(
(o) => o !== undefined,
);
if (offices.length === 0) {
return undefined;
} else if (offices.length === 1) {
return `Office: ${offices[0]}`;
} else if (offices.length > cutoff) {
return `Offices: ${offices.toSpliced(cutoff - 1).join(", ")}, and more`;
}
return `Offices: ${offices.toSpliced(-1).join(", ")} and ${offices.at(-1)}`;
}

export default compensations;

0 comments on commit 0dec9af

Please sign in to comment.