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 490e285
Showing 1 changed file with 26 additions and 14 deletions.
40 changes: 26 additions & 14 deletions studio/schemas/documents/compensations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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<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(", ");
}
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;

0 comments on commit 490e285

Please sign in to comment.