import { FieldContent, FieldContentType, isRangeContent, } from "@prismicio/types-internal/lib/content" import type { Range } 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_MIN = 0 const DEFAULT_MAX = 100 const DEFAULT_STEP = 1 function random(min: number, max: number, step: number): number { const rand = Math.floor(Math.random() * (max - min)) + min if (rand % step === 0) return rand const withStep = rand + (step - (rand % step)) // we ensure that it respects the increment step return Math.min(withStep, max) // if exceed max, just return max } export interface RangeMockConfig extends MockConfig { min?: number max?: number step?: number } export const RangeMock: NestableMock = { generate(def: Range, config?: RangeMockConfig): FieldContent { const min = (() => { if (def.config?.min) { return config?.min && config.min > def.config.min ? config.min : def.config.min } return DEFAULT_MIN })() const max = (() => { if (def.config?.max) { return config?.max && config.max < def.config.max ? config.max : def.config.max } return DEFAULT_MAX })() const step = (() => { if (def.config?.step) { return config?.step && config.step > def.config.step ? config.step : def.config.step } return DEFAULT_STEP })() const value = (() => { if (config?.value) return config.value return random(min, max, step) })().toString() return { __TYPE__: FieldContentType, value, type: "Range", } }, applyPatch(data: Patch): | { result: FieldContent | undefined } | undefined { if (data.diff.op === DiffOperation.Removed) return { result: undefined } if (data.diff.value.type === "Range") { const patched = this.patch( data.diff, isRangeContent(data.content) ? data.content : undefined, data.config?.type === "Range" ? data.config : undefined, ) return { result: patched } } return }, patch( diff: DiffChange, _content: FieldContent, config?: RangeMockConfig, ): FieldContent | undefined { switch (diff.op) { case DiffOperation.Removed: return case DiffOperation.Updated: case DiffOperation.Added: return this.generate(diff.value, config) } }, }