Skip to content

Commit

Permalink
[Sanity] Collapsed multiple Util-locations, updated API-version, adde…
Browse files Browse the repository at this point in the history
…d types (#3313)

* sanity config cleanup

* removed extra const for type

* re-organized admin tools and fixed types

* synced SEO-updates

* lock sync
  • Loading branch information
KenAJoh authored Nov 6, 2024
1 parent 2d669a7 commit 4118a27
Show file tree
Hide file tree
Showing 12 changed files with 108 additions and 169 deletions.
6 changes: 4 additions & 2 deletions aksel.nav.no/website/sanity/config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { ClientConfig } from "@sanity/client";

export const SANITY_PROJECT_ID = "hnbe3yhs";
export const SANITY_API_VERSION = "2021-10-21";
export const SANITY_API_VERSION = "2024-04-11";
export const SANITY_DATASET = "production";

export const clientConfig = {
export const clientConfig: ClientConfig = {
projectId: SANITY_PROJECT_ID,
dataset: SANITY_DATASET,
useCdn: false,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest";
import { sanitizeSlug } from "../util";
import { sanitizeSlug } from "../../util";

describe("Testing sanitizeSlug function", () => {
test("sanitizeSlug should return empty string if input is empty", () => {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Avatar from "boring-avatars";
import { defineField, defineType } from "sanity";
import { EditorPage } from "../custom-components/EditorPage";
import { showForDevsOnly } from "../../../util";

export const Editors = defineType({
title: "Forfattere",
Expand Down Expand Up @@ -40,39 +40,7 @@ export const Editors = defineType({
name: "alt_email",
type: "string",
validation: (Rule) => Rule.email(),
hidden: ({ currentUser }) => {
const user = currentUser;
return !user?.roles.find(({ name }) =>
["developer", "administrator"].includes(name),
);
},
}),
defineField({
name: "profilside",
type: "string",
title: "",
components: {
field: EditorPage,
},
readOnly: true,
hidden: ({ currentUser, parent }) => {
const user = currentUser;

if (!parent?.email || !parent?.title) {
return true;
}
if (
user?.roles.find(({ name }) =>
["developer", "administrator"].includes(name),
)
) {
return false;
}

return (
parent?.email === user?.email || parent?.alt_email === user?.email
);
},
hidden: showForDevsOnly(),
}),
],
preview: {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { defineField, defineType } from "sanity";
import SanityTabGroups from "../../../schema/documents/presets/groups";
import BaseSEOPreset from "../../../schema/documents/presets/seo";
import { sanitizeSlug } from "../../../schema/util";
import { sanitizeSlug } from "../../../util";

export const Tema = defineType({
name: "gp.tema",
Expand Down
8 changes: 5 additions & 3 deletions aksel.nav.no/website/sanity/schema/documents/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export * from "./blogg/artikkel";
export * from "./blogg/landingsside";
export * from "./editors";
export * from "./forside";
export * from "./god-praksis/artikkel";
export * from "./god-praksis/landingsside";
Expand All @@ -17,9 +16,12 @@ export * from "./komponenter/tokens";
export * from "./prinsipper/artikkel";
export * from "./prinsipper/landingsside";
export * from "./publiseringsflyt";
export * from "./redirects";
export * from "./skrivehjelp";
export * from "./standalone-artikkel";
export * from "./templates/artikkel";
export * from "./templates/landingsside";
export * from "./articleViews";

/* Admin tools */
export * from "./admin/editors";
export * from "./admin/redirects";
export * from "./admin/articleViews";
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { defineField, defineType } from "sanity";
import { komponentKategorier } from "../../../config";
import { devsOnly } from "../../../util";
import { showForDevsOnly } from "../../../util";
import { artikkelPreview } from "../presets/artikkel-preview";
import { editorField } from "../presets/editors";
import SanityTabGroups from "../presets/groups";
Expand Down Expand Up @@ -95,7 +95,7 @@ export const KomponentArtikkel = defineType({
type: "boolean",
initialValue: false,
group: "settings",
hidden: devsOnly,
hidden: showForDevsOnly(),
}),
defineField({
name: "intro",
Expand Down
88 changes: 46 additions & 42 deletions aksel.nav.no/website/sanity/schema/documents/presets/slug.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { SlugIsUniqueValidator, SlugRule, defineField } from "sanity";
import { SANITY_API_VERSION } from "@/sanity/config";
import { sanitizeSlug } from "../../util";
import { sanitizeSlug } from "../../../util";

export const validateSlug = (Rule, prefix, nesting) =>
export const validateSlug = (Rule: SlugRule, prefix: string, nesting: number) =>
Rule.required().custom((slug) => {
if (!slug.current.startsWith(prefix)) {
if (!slug?.current?.startsWith(prefix)) {
return `Slug må starte med prefiks: ${prefix}`;
}
if ((slug.current.match(/\//g) || []).length > nesting - 1) {
if ((slug?.current?.match(/\//g) || []).length > nesting - 1) {
return `Siden kan bare være på ${nesting} nivå`;
}
return true;
});

/* Checks every document for matching slug */
export const isSlugUnique = (slug, options) => {
export const isSlugUnique: SlugIsUniqueValidator = (slug, options) => {
const { document, getClient } = options;

const id = document._id.replace(/^drafts\./, "");
const id = document?._id.replace(/^drafts\./, "");
const params = {
draft: `drafts.${id}`,
published: id,
Expand All @@ -27,22 +28,23 @@ export const isSlugUnique = (slug, options) => {
return getClient({ apiVersion: SANITY_API_VERSION }).fetch(query, params);
};

export const sanitySlug = (prefix: string, depth: number, source?: string) => ({
title: "url",
name: "slug",
type: "slug",
validation: (Rule) => validateSlug(Rule, prefix, depth ?? 3),
group: "settings",
options: {
isUnique: isSlugUnique,
source: source ?? "heading",
slugify: (s) => prefix + sanitizeSlug(s),
},
});
export const sanitySlug = (prefix: string, depth: number, source?: string) =>
defineField({
title: "url",
name: "slug",
type: "slug",
validation: (Rule) => validateSlug(Rule, prefix, depth ?? 3),
group: "settings",
options: {
isUnique: isSlugUnique,
source: source ?? "heading",
slugify: (s) => prefix + sanitizeSlug(s),
},
});

export const validateKategoriSlug = (Rule, prefix) =>
export const validateKategoriSlug = (Rule: SlugRule, prefix: string) =>
Rule.required().custom((slug, { document }) => {
if (!slug.current.startsWith(`${prefix}${document?.kategori}/`)) {
if (!slug?.current?.startsWith(`${prefix}${document?.kategori}/`)) {
return `Slug må starte med prefiks: ${prefix}${document?.kategori}`;
}
if ((slug.current.match(/\//g) || []).length > 3 - 1) {
Expand All @@ -51,26 +53,28 @@ export const validateKategoriSlug = (Rule, prefix) =>
return true;
});

export const kategoriSlug = (prefix: string) => ({
title: "url",
name: "slug",
type: "slug",
validation: (Rule) => validateKategoriSlug(Rule, prefix),
group: "settings",
options: {
source: "heading",
slugify: (input, _, { parent }) => {
return `${prefix}${parent?.kategori}/${input}`
.toLowerCase()
.trim()
.slice(0, 200)
.trim()
.replace(/\s+/g, "-")
.replace(/-+/gm, "-")
.replace(/æ/g, "a")
.replace(/å/g, "a")
.replace(/ø/g, "o")
.replace(/[&\\#!,+()$~%.'"¨:*?<>{}]/g, "");
export const kategoriSlug = (prefix: string) =>
defineField({
title: "url",
name: "slug",
type: "slug",
validation: (Rule) => validateKategoriSlug(Rule, prefix),
group: "settings",
options: {
source: "heading",
slugify: (input, _, context) => {
const parent = context.parent as { kategori: string };
return `${prefix}${parent.kategori}/${input}`
.toLowerCase()
.trim()
.slice(0, 200)
.trim()
.replace(/\s+/g, "-")
.replace(/-+/gm, "-")
.replace(/æ/g, "a")
.replace(/å/g, "a")
.replace(/ø/g, "o")
.replace(/[&\\#!,+()$~%.'"¨:*?<>{}]/g, "");
},
},
},
});
});
39 changes: 0 additions & 39 deletions aksel.nav.no/website/sanity/schema/util.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import {
ConditionalPropertyCallbackContext,
NewDocumentOptionsResolver,
} from "sanity";
import { ConditionalProperty, NewDocumentOptionsResolver } from "sanity";

export const devsOnly = ({ currentUser }: ConditionalPropertyCallbackContext) =>
!currentUser?.roles.find(({ name }) =>
["developer", "administrator"].includes(name),
);
export function showForDevsOnly(): ConditionalProperty {
return ({ currentUser }) =>
!currentUser?.roles.find(({ name }) =>
["developer", "administrator"].includes(name),
);
}

export const newDocumentsCreator: NewDocumentOptionsResolver = (
prev,
Expand Down Expand Up @@ -65,3 +64,43 @@ export const newDocumentsCreator: NewDocumentOptionsResolver = (

return prev;
};

/**
* Cleans up strings to be used as URLs
* @param input
* @returns cleaned input
*/
export function sanitizeSlug(input: string) {
if (!input) {
return "";
}

return (
input
.toLowerCase()
.trim()
/* Space */
.replace(/\s+/g, "-")
/* multiple - converted to single - */
.replace(/-+/gm, "-")
/* Special-characters */
.replace(/[æåø]/g, (char) => {
switch (char) {
case "æ":
return "ae";
case "å":
return "a";
case "ø":
return "o";
default:
return "";
}
})
// Replace accented characters with non-accented equivalents
.normalize("NFD")
// biome-ignore lint/suspicious/noMisleadingCharacterClass: Nextjs-loader (webpack/loaders/next-swc-loader.js) does not support the `v` flag in regex expressions
.replace(/[\u0300-\u036f]/g, "")
// Replace any non [a-zA-Z0-9_]
.replace(/[^\w-]+/g, "")
);
}

0 comments on commit 4118a27

Please sign in to comment.