UNPKG

@prismicio/types-internal

Version:
117 lines (103 loc) 2.81 kB
import * as t from "io-ts" import { v4 as uuid } from "uuid" import { FieldType, SlicesTypes } from "../customtypes/widgets" export const FieldOrSliceType = t.union([ t.union([FieldType, SlicesTypes]), t.literal("Repeatable.Link"), ]) export type FieldOrSliceType = t.TypeOf<typeof FieldOrSliceType> interface LegacyContentCtxParams { fieldKey: string contentKey?: string fieldPath?: Array<string> contentPath?: Array<string> allTypes?: Map<string, FieldOrSliceType> allKeys?: Map<string, string> } export class LegacyContentCtx { fieldKey: string prefixedKey: string keyOfType: string keyOfKey: string fieldPath: Array<string> fieldType?: FieldOrSliceType | undefined allTypes: Map<string, FieldOrSliceType> allKeys: Map<string, string> contentKey: string contentPath: Array<string> fieldContentKey: string constructor({ fieldKey, contentKey, contentPath, fieldPath, allTypes, allKeys, }: LegacyContentCtxParams) { this.fieldKey = fieldKey this.contentKey = contentKey || fieldKey this.fieldPath = fieldPath || [] this.contentPath = contentPath || [] this.allTypes = allTypes || new Map<string, FieldOrSliceType>() this.allKeys = allKeys || new Map<string, string>() const prefixedKey = Array.of(this.fieldPath, [this.fieldKey]) .flat() .join(".") const prefixedContentKey = Array.of(this.contentPath, [this.contentKey]) .flat() .join(".") this.prefixedKey = prefixedKey this.keyOfType = `${prefixedKey}_TYPE` this.keyOfKey = `${prefixedContentKey}_KEY` this.fieldType = this.allTypes.get(this.prefixedKey) this.fieldContentKey = this.allKeys.get(prefixedContentKey) ?? uuid() } withContentKey(contentKey: string): LegacyContentCtx { return new LegacyContentCtx({ ...this, contentPath: [...this.contentPath, this.contentKey], contentKey, }) } } interface GetFieldCtxParams { fieldKey: string contentKey?: string ctx: LegacyContentCtx prefixes?: Array<string> } export function getFieldCtx({ fieldKey, contentKey: contentKeyParam, ctx, prefixes, }: GetFieldCtxParams): LegacyContentCtx { const contentKey = contentKeyParam || fieldKey return new LegacyContentCtx({ fieldKey, contentKey, contentPath: [...ctx.contentPath, ctx.contentKey, ...(prefixes || [])], fieldPath: [...ctx.fieldPath, ctx.fieldKey, ...(prefixes || [])], allTypes: ctx.allTypes, allKeys: ctx.allKeys, }) } export function defaultCtx( key: string, allTypes: Map<string, FieldOrSliceType> = new Map(), allKeys: Map<string, string> = new Map(), ): LegacyContentCtx { return new LegacyContentCtx({ fieldKey: key, contentKey: key, contentPath: [], fieldPath: [], allTypes, allKeys, }) } export type WithTypes<T> = { keys: Record<string, string> types: Record<string, FieldOrSliceType> content: T }