@prismicio/types-internal
Version:
Prismic types for Custom Types and Prismic Data
77 lines (68 loc) • 1.63 kB
text/typescript
import * as t from "io-ts"
import type { LegacyContentCtx } from "../LegacyContentCtx"
import {
GroupContent,
GroupContentType,
GroupLegacy,
isGroupContent,
} from "./GroupContent"
import { isNestableContent, NestableContent, NestableLegacy } from "./nestable"
import {
isSlicesContent,
SlicesContent,
SlicesContentType,
SlicesLegacy,
} from "./slices"
import {
isUIDContent,
UIDContent,
UIDContentType,
UIDLegacy,
} from "./UIDContent"
export const WidgetContent = t.union([
GroupContent,
NestableContent,
UIDContent,
SlicesContent,
])
export const isWidgetContent = (u: unknown): u is WidgetContent =>
isGroupContent(u) ||
isNestableContent(u) ||
isUIDContent(u) ||
isSlicesContent(u)
export type WidgetContent = t.TypeOf<typeof WidgetContent>
export type ContentType = WidgetContent["__TYPE__"]
export const WidgetLegacy = (ctx: LegacyContentCtx) => {
return {
decode(value: unknown) {
if (!ctx.fieldType) return
const codec = (() => {
switch (ctx.fieldType) {
case "UID":
return UIDLegacy(ctx)
case "Group":
return GroupLegacy(ctx)
case "Choice":
case "Slices":
return SlicesLegacy(ctx)
default:
return NestableLegacy(ctx)
}
})()
if (!codec) return
return codec.decode(value)
},
encode(value: WidgetContent) {
switch (value.__TYPE__) {
case UIDContentType:
return UIDLegacy(ctx).encode(value)
case GroupContentType:
return GroupLegacy(ctx).encode(value)
case SlicesContentType:
return SlicesLegacy(ctx).encode(value)
default:
return NestableLegacy(ctx).encode(value)
}
},
}
}