Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adds check for language #38

Merged
merged 2 commits into from
Jul 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/studio-i18n/page-tree-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ export const pageTreeConfig: PageTreeConfig = {
titleFieldName: 'title',
documentInternationalization: {
supportedLanguages: ['nl', 'en', 'fr'],
documentLanguageShouldMatchParent: true,
}
};
4 changes: 2 additions & 2 deletions src/client.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SanityClient } from 'sanity';

import { getAllPageMetadata } from './helpers/page-tree';
import { getRawPageMetadataQuery } from './queries';
import { getAllRawPageMetadataQuery } from './queries';
import { PageMetadata, PageTreeConfig } from './types';

export type { PageMetadata } from './types';
Expand All @@ -25,7 +25,7 @@ class PageTreeClient {
}

public async getAllPageMetadata(): Promise<PageMetadata[]> {
const rawPageMetadata = await this.client.fetch(getRawPageMetadataQuery(this.config));
const rawPageMetadata = await this.client.fetch(getAllRawPageMetadataQuery(this.config));
return getAllPageMetadata(this.config, rawPageMetadata);
}
}
4 changes: 2 additions & 2 deletions src/hooks/usePageTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { useMemo } from 'react';
import { useListeningQuery } from 'sanity-plugin-utils';

import { mapRawPageMetadatasToPageTree } from '../helpers/page-tree';
import { getRawPageMetadataQuery } from '../queries';
import { getAllRawPageMetadataQuery } from '../queries';
import { PageTreeConfig, RawPageMetadata } from '../types';

export const usePageTree = (config: PageTreeConfig) => {
const { data, loading } = useListeningQuery<RawPageMetadata[]>(getRawPageMetadataQuery(config), {
const { data, loading } = useListeningQuery<RawPageMetadata[]>(getAllRawPageMetadataQuery(config), {
options: { apiVersion: config.apiVersion },
});

Expand Down
4 changes: 2 additions & 2 deletions src/hooks/usePageTreeItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { useMemo } from 'react';
import { useListeningQuery } from 'sanity-plugin-utils';

import { getAllPageMetadata } from '../helpers/page-tree';
import { getRawPageMetadataQuery } from '../queries';
import { getAllRawPageMetadataQuery } from '../queries';
import { PageTreeConfig, RawPageMetadata } from '../types';

export const usePageTreeItem = (documentId: string, config: PageTreeConfig, perspective?: ClientPerspective) => {
const { data, loading } = useListeningQuery<RawPageMetadata[]>(getRawPageMetadataQuery(config), {
const { data, loading } = useListeningQuery<RawPageMetadata[]>(getAllRawPageMetadataQuery(config), {
options: { apiVersion: config.apiVersion, perspective },
});

Expand Down
4 changes: 2 additions & 2 deletions src/next.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { FilteredResponseQueryOptions, SanityClient } from 'next-sanity';

import { getAllPageMetadata } from './helpers/page-tree';
import { getRawPageMetadataQuery } from './queries';
import { getAllRawPageMetadataQuery } from './queries';
import { PageMetadata, PageTreeConfig } from './types';

export type { PageMetadata } from './types';
Expand Down Expand Up @@ -29,7 +29,7 @@ class NextPageTreeClient {

public async getAllPageMetadata(): Promise<PageMetadata[]> {
const rawPageMetadata = await this.client.fetch(
getRawPageMetadataQuery(this.config),
getAllRawPageMetadataQuery(this.config),
undefined,
this.defaultSanityFetchOptions ?? {},
);
Expand Down
19 changes: 12 additions & 7 deletions src/queries/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
import { getLanguageFieldName } from '../helpers/config';
import { PageTreeConfig } from '../types';

export const getRawPageMetadataQuery = (config: PageTreeConfig) => `*[_type in [${Object.values(config.pageSchemaTypes)
export const getAllRawPageMetadataQuery = (config: PageTreeConfig) => `*[_type in [${Object.values(
config.pageSchemaTypes,
)
.map(key => `"${key}"`)
.join(', ')}]]{
${rawPageMetadataFragment(config)}
}`;

export const getRawPageMetadataQuery = (documentId: string, config: PageTreeConfig) => `*[_id == "${documentId}"]{
${rawPageMetadataFragment(config)}
}`;

export const rawPageMetadataFragment = (config: PageTreeConfig) => `
_id,
_type,
_updatedAt,
parent,
slug,
title,
${getLanguageFieldName(config) ?? ''}
}`;

export const getDocumentTypeQuery = (documentId: string) => `*[_id == "${documentId}"]{
_type
}`;
${getLanguageFieldName(config) ?? ''}`;
4 changes: 2 additions & 2 deletions src/schema/definePageType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { defineField, defineType, DocumentDefinition, SlugOptions } from 'sanity
import { PageTreeField } from '../components/PageTreeField';
import { SlugField } from '../components/SlugField';
import { PageTreeConfig } from '../types';
import { allowedParentValidator } from '../validators/parent-validator';
import { parentValidator } from '../validators/parent-validator';
import { slugValidator } from '../validators/slug-validator';

type Options = {
Expand Down Expand Up @@ -67,7 +67,7 @@ const basePageFields = (config: PageTreeConfig, options: Options, ownType: Docum
title: 'Parent page',
type: 'reference',
to: getPossibleParentsFromConfig(config, ownType).map(type => ({ type })),
validation: Rule => Rule.required().custom(allowedParentValidator(config, ownType.name)),
validation: Rule => Rule.required().custom(parentValidator(config, ownType.name)),
group: options.fieldsGroupName,
components: {
field: props => PageTreeField({ ...props, config, mode: 'select-parent' }),
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ export type PageTreeConfig = {
supportedLanguages: string[];
/* Optional field name of the language field, defaults to "language" */
languageFieldName?: string;
/* Adds validation check to ensure that the language of the document matches the language of the parent document. Default: false */
documentLanguageShouldMatchParent?: boolean;
};
};

Expand Down
66 changes: 42 additions & 24 deletions src/validators/parent-validator.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,60 @@
import { Reference, ValidationContext } from 'sanity';

import { getDocumentTypeQuery } from '../queries';
import { PageTreeConfig, RawPageMetadata, SanityRef } from '../types';
import { getLanguageFieldName } from '../helpers/config';
import { getRawPageMetadataQuery } from '../queries';
import { PageTreeConfig, RawPageMetadata } from '../types';

/**
* Validates that the slug is unique within the parent page and therefore that entire the path is unique.
*/
export const allowedParentValidator =
export const parentValidator =
(config: PageTreeConfig, ownType: string) =>
async (selectedParent: Reference | undefined, context: ValidationContext) => {
const allowedParents = config.allowedParents?.[ownType];

if (allowedParents === undefined) {
return true;
}
async (selectedParentRef: Reference | undefined, context: ValidationContext) => {
const client = context.getClient({ apiVersion: config.apiVersion });

const parentRef = context.document?.parent as SanityRef | undefined;
if (!parentRef) {
if (!selectedParentRef) {
return true;
}

const parentId = parentRef._ref;
const parentId = selectedParentRef._ref;
const selectedParent = (await client.fetch<RawPageMetadata[]>(getRawPageMetadataQuery(parentId, config)))[0];

if (parentId === undefined) {
return true;
const allowedParentValidation = allowedParentValidator(selectedParent, config, ownType);
if (allowedParentValidation !== true) {
return allowedParentValidation;
}

const client = context.getClient({ apiVersion: config.apiVersion });
const selectedParentType = (await client.fetch<Pick<RawPageMetadata, '_type'>[]>(getDocumentTypeQuery(parentId)))[0]
?._type;
return parentLanguageValidator(selectedParent, config, context);
};

if (!selectedParentType) {
return 'Unable to check the type of the selected parent.';
}
const allowedParentValidator = (selectedParent: RawPageMetadata, config: PageTreeConfig, ownType: string) => {
const allowedParents = config.allowedParents?.[ownType];

if (!allowedParents.includes(selectedParentType)) {
return `The parent of type "${selectedParentType}" is not allowed for this type of document.`;
if (allowedParents === undefined) {
return true;
}

if (!allowedParents.includes(selectedParent._type)) {
return `The parent of type "${selectedParent._type}" is not allowed for this type of document.`;
}

return true;
};

const parentLanguageValidator = (
selectedParent: RawPageMetadata,
config: PageTreeConfig,
context: ValidationContext,
) => {
if (config.documentInternationalization?.documentLanguageShouldMatchParent) {
const languageFieldName = getLanguageFieldName(config);
const language = context.document?.[languageFieldName];
const parentLanguage = selectedParent?.[languageFieldName];

if (language !== parentLanguage) {
return 'The language of the parent must match the language of the document.';
}
}

return true;
};
return true;
};
4 changes: 2 additions & 2 deletions src/validators/slug-validator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SlugValue, ValidationContext } from 'sanity';

import { DRAFTS_PREFIX } from '../helpers/page-tree';
import { getRawPageMetadataQuery } from '../queries';
import { getAllRawPageMetadataQuery } from '../queries';
import { PageTreeConfig, RawPageMetadata, SanityRef } from '../types';
import { getSanityDocumentId } from '../utils/sanity';

Expand All @@ -17,7 +17,7 @@ export const slugValidator =
return true;
}

const allPages = await client.fetch<RawPageMetadata[]>(getRawPageMetadataQuery(config));
const allPages = await client.fetch<RawPageMetadata[]>(getAllRawPageMetadataQuery(config));
const siblingPages = allPages.filter(page => page.parent?._ref === parentRef._ref);

const siblingPagesWithSameSlug = siblingPages
Expand Down