import { FieldContent, FieldContentType, isSelectContent, } from "@prismicio/types-internal/lib/content" import type { Select } from "@prismicio/types-internal/lib/customtypes" import { DiffChange, DiffOperation, } from "@prismicio/types-internal/lib/customtypes/diff" import type { NestableMock, Patch } from "../../Mock" import type { MockConfig } from "../../MockConfig" const DEFAULT_VALUE = "mock_option" function random(def: Select): string { if (!def.config) return DEFAULT_VALUE if (def.config.default_value && Math.random() < 0.5) { return def.config.default_value } if (!def.config.options) return DEFAULT_VALUE const index = Math.floor(Math.random() * def.config.options.length) return def.config.options[index] || DEFAULT_VALUE } export type SelectMockConfig = MockConfig export const SelectMock: NestableMock = { generate(def: Select, config?: SelectMockConfig): FieldContent { const value = config?.value || random(def) return { __TYPE__: FieldContentType, value, type: "Select", } }, applyPatch(data: Patch): | { result: FieldContent | undefined } | undefined { if (data.diff.op === DiffOperation.Removed) return { result: undefined } if (data.diff.value.type === "Select") { const patched = this.patch( data.diff, isSelectContent(data.content) ? data.content : undefined, data.config?.type === "Select" ? data.config : undefined, ) return { result: patched } } return }, patch( diff: DiffChange, _content: FieldContent, config?: SelectMockConfig, ): FieldContent | undefined { switch (diff.op) { case DiffOperation.Removed: return case DiffOperation.Updated: case DiffOperation.Added: return this.generate(diff.value, config) } }, }