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

feat: add unstable_mapSliceZone() #302

Merged
merged 4 commits into from
Jun 7, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
266 changes: 266 additions & 0 deletions src/helpers/unstable_mapSliceZone.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
import { Slice } from "../types/value/slice";

/**
* Convert a value to a lazyily loaded module. This is useful when using
* functions like `() => import("...")`.
*/
type LazyModule<T> = () => Promise<T | { default: T }>;

/**
* Returns the type of a `SliceLike` type.
*
* @typeParam Slice - The Slice from which the type will be extracted.
*/
type ExtractSliceType<Slice extends SliceLike> = Slice extends SliceLikeRestV2
? Slice["slice_type"]
: Slice extends SliceLikeGraphQL
? Slice["type"]
: never;

/**
* The minimum required properties to represent a Prismic Slice from the Prismic
* Rest API V2 for the `<SliceZone>` component.
*
* If using Prismic's Rest API V2, use the `Slice` export from
* `@prismicio/types` for a full interface.
angeloashmore marked this conversation as resolved.
Show resolved Hide resolved
*
* @typeParam SliceType - Type name of the Slice.
*/
export type SliceLikeRestV2<SliceType extends string = string> = {
slice_type: Slice<SliceType>["slice_type"];
id?: string;
};

/**
* The minimum required properties to represent a Prismic Slice from the Prismic
* GraphQL API for the `<SliceZone>` component.
angeloashmore marked this conversation as resolved.
Show resolved Hide resolved
*
* @typeParam SliceType - Type name of the Slice.
*/
export type SliceLikeGraphQL<SliceType extends string = string> = {
type: Slice<SliceType>["slice_type"];
};

/**
* The minimum required properties to represent a Prismic Slice for the
* `<SliceZone>` component.
*
* If using Prismic's Rest API V2, use the `Slice` export from
* `@prismicio/types` for a full interface.
angeloashmore marked this conversation as resolved.
Show resolved Hide resolved
*
* @typeParam SliceType - Type name of the Slice.
*/
export type SliceLike<SliceType extends string = string> =
| SliceLikeRestV2<SliceType>
| SliceLikeGraphQL<SliceType>;

/**
* A looser version of the `SliceZone` type from `@prismicio/types` using
* `SliceLike`.
*
* If using Prismic's Rest API V2, use the `SliceZone` export from
* `@prismicio/types` for the full type.
angeloashmore marked this conversation as resolved.
Show resolved Hide resolved
*
* @typeParam TSlice - The type(s) of a Slice in the Slice Zone.
*/
export type SliceZoneLike<TSlice extends SliceLike = SliceLike> =
readonly TSlice[];

/**
* A set of properties that identify a Slice as having been mapped.
* `<SliceZone>` uses these properties internally to determine how props are
* provided to a Slice's component.
*/
type MappedSliceLike = {
/**
* If `true`, this Slice has been modified from its original value using a
* mapper.
*/
__mapped: true;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we @internal it so it's more likely to be hidden from intellisense?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if we should mark it as @internal. We need to expose it so consumers of the Slice Zone can use it. It is a public way to identify if a Slice has been mapped.

We initially only plan to use it within <SliceZone> so we can determine how to pass a component its props, but there may be other use cases for mapping a Slice Zone.

};

/**
* React props for a component rendering content from a Prismic Slice using the
* `<SliceZone>` component.
*
* @typeParam TSlice - The Slice passed as a prop.
* @typeParam TContext - Arbitrary data passed to `<SliceZone>` and made
* available to all Slice components.
angeloashmore marked this conversation as resolved.
Show resolved Hide resolved
*/
export type SliceComponentProps<
angeloashmore marked this conversation as resolved.
Show resolved Hide resolved
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TSlice extends SliceLike = any,
TContext = unknown,
> = {
/**
* Slice data for this component.
angeloashmore marked this conversation as resolved.
Show resolved Hide resolved
*/
slice: TSlice;

/**
* The index of the Slice in the Slice Zone.
*/
index: number;

/**
* All Slices from the Slice Zone to which the Slice belongs.
*/
// TODO: We have to keep this list of Slices general due to circular
// reference limtiations. If we had another generic to determine the full
// union of Slice types, it would include TSlice. This causes TypeScript to
// throw a compilation error.
slices: SliceZoneLike<SliceLike>;

/**
* Arbitrary data passed to `<SliceZone>` and made available to all Slice
* components.
angeloashmore marked this conversation as resolved.
Show resolved Hide resolved
*/
context: TContext;
};

/**
* A record of mappers.
*/
export type Mappers<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TSlice extends SliceLike = any,
TContext = unknown,
> = Partial<{
[P in ExtractSliceType<TSlice>]: Mapper<
Extract<TSlice, SliceLike<P>>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
any,
TContext
>;
}>;

/**
* A function that maps a Slice and its metadata to a modified version. The
* return value will be passed to the Slice's component as props.
*/
export type Mapper<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TSlice extends SliceLike = any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TProps extends Record<string, any> | undefined | void = any,
TContext = unknown,
> = (args: MapperArgs<TSlice, TContext>) => TProps | Promise<TProps>;

/**
* Arguments provided to a mapper function.
*/
export type MapperArgs<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TSlice extends SliceLike = any,
TContext = unknown,
> = SliceComponentProps<TSlice, TContext>;

/**
* Unwraps a lazily loaded mapper module.
*/
type ResolveLazyMapperModule<TMapper extends Mapper | LazyModule<Mapper>> =
TMapper extends LazyModule<Mapper>
? Awaited<ReturnType<TMapper>> extends {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
default: any;
}
? Awaited<ReturnType<TMapper>>["default"]
: Awaited<ReturnType<TMapper>>
: TMapper;

/**
* Transforms a Slice into its mapped version.
*/
type MapSliceLike<
TSliceLike extends SliceLike,
TMappers extends Record<string, Mapper>,
> = TSliceLike extends SliceLikeRestV2
? TSliceLike["slice_type"] extends keyof TMappers
? SliceLikeRestV2<TSliceLike["slice_type"]> &
MappedSliceLike &
Awaited<
ReturnType<
ResolveLazyMapperModule<TMappers[TSliceLike["slice_type"]]>
>
>
: TSliceLike
: TSliceLike extends SliceLikeGraphQL
? TSliceLike["type"] extends keyof TMappers
? SliceLikeGraphQL<TSliceLike["type"]> &
MappedSliceLike &
Awaited<
ReturnType<ResolveLazyMapperModule<TMappers[TSliceLike["type"]]>>
>
: TSliceLike
: never;

/**
* Transforms a Slice Zone using a set of mapping functions, one for each type
* of Slice. Mapping functions can be async.
*
* Whenever possible, use this function on the server to minimize client-side
* processing.
*
* @example
*
* ```typescript
* const mappedSliceZone = await unstable_mapSliceZone(page.data.slices, {
* code_block: ({ slice }) => ({
* codeHTML: await highlight(slice.primary.code),
* }),
* });
* ```
*
* @experimental Names and implementations may change in the future.
* `unstable_mapSliceZone()` does not follow SemVer.
*/
export function unstable_mapSliceZone<
TSliceLike extends SliceLike,
TMappers extends Record<string, Mapper>,
TContext = unknown,
>(
sliceZone: SliceZoneLike<TSliceLike>,
mappers: TMappers,
context?: TContext,
): Promise<MapSliceLike<TSliceLike, TMappers>[]> {
return Promise.all(
sliceZone.map(async (slice, index, slices) => {
const isRestSliceType = "slice_type" in slice;
const sliceType = isRestSliceType ? slice.slice_type : slice.type;

const mapper = mappers[sliceType];

if (!mapper) {
return slice;
}

const mapperArgs = { slice, slices, index, context };

let result = await mapper(mapperArgs);

if (
mapper.length < 1 &&
(typeof result === "function" ||
(typeof result === "object" && "default" in result))
) {
result = "default" in result ? result.default : result;
result = await result(mapperArgs);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd maybe rename the first result to something like resultOrMapperModule so that the following line can read better.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer result here since we ultimately will be using result as the final mapper function return value. result is used later in the function to spread into an object, which should never be a module.

However, I added comments around const result to explain exactly what is happening at that stage. I think that should accomplish what your rename suggestion is doing.

What do you think?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Works for me!

}

if (isRestSliceType) {
return {
__mapped: true,
id: slice.id,
slice_type: sliceType,
...result,
};
} else {
return {
__mapped: true,
type: sliceType,
...result,
};
}
}),
);
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export { asHTML } from "./helpers/asHTML";
export { asImageSrc } from "./helpers/asImageSrc";
export { asImageWidthSrcSet } from "./helpers/asImageWidthSrcSet";
export { asImagePixelDensitySrcSet } from "./helpers/asImagePixelDensitySrcSet";
export { unstable_mapSliceZone } from "./helpers/unstable_mapSliceZone";
export * as isFilled from "./helpers/isFilled";

// Conversion helper.
Expand Down
Loading