{"version":3,"file":"interpolate.mjs","names":[],"sources":["../../../src/expression/definitions/interpolate.ts"],"sourcesContent":["import unitBezier from '@mapbox/unitbezier';\n\nimport {\n    array,\n    ArrayType,\n    ColorType,\n    ColorTypeT,\n    NumberType,\n    NumberTypeT,\n    PaddingType,\n    PaddingTypeT,\n    NumberArrayTypeT,\n    ColorArrayTypeT,\n    VariableAnchorOffsetCollectionType,\n    VariableAnchorOffsetCollectionTypeT,\n    typeToString,\n    verifyType,\n    ProjectionDefinitionType,\n    ColorArrayType,\n    NumberArrayType\n} from '../types';\nimport {findStopLessThanOrEqualTo} from '../stops';\nimport {Color} from '../types/color';\nimport {interpolateArray, interpolateNumber} from '../../util/interpolate-primitives';\nimport {Padding} from '../types/padding';\nimport {ColorArray} from '../types/color_array';\nimport {NumberArray} from '../types/number_array';\nimport {VariableAnchorOffsetCollection} from '../types/variable_anchor_offset_collection';\nimport {ProjectionDefinition} from '../types/projection_definition';\n\nimport type {Stops} from '../stops';\nimport type {Expression} from '../expression';\nimport type {ParsingContext} from '../parsing_context';\nimport type {EvaluationContext} from '../evaluation_context';\nimport type {ProjectionDefinitionTypeT, Type} from '../types';\n\nexport type InterpolationType =\n    | {\n          name: 'linear';\n      }\n    | {\n          name: 'exponential';\n          base: number;\n      }\n    | {\n          name: 'cubic-bezier';\n          controlPoints: [number, number, number, number];\n      };\ntype InterpolatedValueType =\n    | NumberTypeT\n    | ColorTypeT\n    | ProjectionDefinitionTypeT\n    | PaddingTypeT\n    | NumberArrayTypeT\n    | ColorArrayTypeT\n    | VariableAnchorOffsetCollectionTypeT\n    | ArrayType<NumberTypeT>;\nexport class Interpolate implements Expression {\n    labels: Array<number> = [];\n    outputs: Array<Expression> = [];\n\n    constructor(\n        public type: InterpolatedValueType,\n        public operator:\n            | 'interpolate'\n            | 'interpolate-hcl'\n            | 'interpolate-lab'\n            | 'interpolate-oklch'\n            | 'interpolate-oklab',\n        public interpolation: InterpolationType,\n        public input: Expression,\n        stops: Stops,\n        public readonly key: string\n    ) {\n        for (const [label, expression] of stops) {\n            this.labels.push(label);\n            this.outputs.push(expression);\n        }\n    }\n\n    static interpolationFactor(\n        interpolation: InterpolationType,\n        input: number,\n        lower: number,\n        upper: number\n    ) {\n        let t = 0;\n        if (interpolation.name === 'exponential') {\n            t = exponentialInterpolation(input, interpolation.base, lower, upper);\n        } else if (interpolation.name === 'linear') {\n            t = exponentialInterpolation(input, 1, lower, upper);\n        } else if (interpolation.name === 'cubic-bezier') {\n            const c = interpolation.controlPoints;\n            const ub = unitBezier(c[0], c[1], c[2], c[3]);\n            t = ub(exponentialInterpolation(input, 1, lower, upper));\n        }\n        return t;\n    }\n\n    static parse(args: ReadonlyArray<unknown>, context: ParsingContext): Expression {\n        let [operator, interpolation, input, ...rest] = args;\n\n        if (!Array.isArray(interpolation) || interpolation.length === 0) {\n            return context.error('Expected an interpolation type expression.', 1) as null;\n        }\n\n        if (interpolation[0] === 'linear') {\n            interpolation = {name: 'linear'};\n        } else if (interpolation[0] === 'exponential') {\n            const base = interpolation[1];\n            if (typeof base !== 'number')\n                return context.error(\n                    'Exponential interpolation requires a numeric base.',\n                    1,\n                    1\n                ) as null;\n            interpolation = {\n                name: 'exponential',\n                base\n            };\n        } else if (interpolation[0] === 'cubic-bezier') {\n            const controlPoints = interpolation.slice(1);\n            if (\n                controlPoints.length !== 4 ||\n                controlPoints.some((t) => typeof t !== 'number' || t < 0 || t > 1)\n            ) {\n                return context.error(\n                    'Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.',\n                    1\n                ) as null;\n            }\n\n            interpolation = {\n                name: 'cubic-bezier',\n                controlPoints: controlPoints as any\n            };\n        } else {\n            return context.error(\n                `Unknown interpolation type ${String(interpolation[0])}`,\n                1,\n                0\n            ) as null;\n        }\n\n        if (args.length - 1 < 4) {\n            return context.error(\n                `Expected at least 4 arguments, but found only ${args.length - 1}.`\n            ) as null;\n        }\n\n        if ((args.length - 1) % 2 !== 0) {\n            return context.error('Expected an even number of arguments.') as null;\n        }\n\n        input = context.parse(input, 2, NumberType);\n        if (!input) return null;\n\n        const stops: Stops = [];\n\n        let outputType: Type = null;\n        if (\n            (operator === 'interpolate-hcl' ||\n                operator === 'interpolate-lab' ||\n                operator === 'interpolate-oklch' ||\n                operator === 'interpolate-oklab') &&\n            context.expectedType != ColorArrayType\n        ) {\n            outputType = ColorType;\n        } else if (context.expectedType && context.expectedType.kind !== 'value') {\n            outputType = context.expectedType;\n        }\n\n        for (let i = 0; i < rest.length; i += 2) {\n            const label = rest[i];\n            const value = rest[i + 1];\n\n            const labelKey = i + 3;\n            const valueKey = i + 4;\n\n            if (typeof label !== 'number') {\n                return context.error(\n                    'Input/output pairs for \"interpolate\" expressions must be defined using literal numeric values (not computed expressions) for the input values.',\n                    labelKey\n                ) as null;\n            }\n\n            if (stops.length && stops[stops.length - 1][0] >= label) {\n                return context.error(\n                    'Input/output pairs for \"interpolate\" expressions must be arranged with input values in strictly ascending order.',\n                    labelKey\n                ) as null;\n            }\n            const parsed = context.parse(value, valueKey, outputType);\n            if (!parsed) return null;\n            outputType = outputType || parsed.type;\n            stops.push([label, parsed]);\n        }\n\n        if (\n            !verifyType(outputType, NumberType) &&\n            !verifyType(outputType, ProjectionDefinitionType) &&\n            !verifyType(outputType, ColorType) &&\n            !verifyType(outputType, PaddingType) &&\n            !verifyType(outputType, NumberArrayType) &&\n            !verifyType(outputType, ColorArrayType) &&\n            !verifyType(outputType, VariableAnchorOffsetCollectionType) &&\n            !verifyType(outputType, array(NumberType))\n        ) {\n            return context.error(`Type ${typeToString(outputType)} is not interpolatable.`) as null;\n        }\n\n        return new Interpolate(\n            outputType,\n            operator as any,\n            interpolation as InterpolationType,\n            input as Expression,\n            stops,\n            context.key\n        );\n    }\n\n    evaluate(ctx: EvaluationContext) {\n        const labels = this.labels;\n        const outputs = this.outputs;\n\n        if (labels.length === 1) {\n            return outputs[0].evaluate(ctx);\n        }\n\n        const value: number = this.input.evaluate(ctx);\n        if (value <= labels[0]) {\n            return outputs[0].evaluate(ctx);\n        }\n\n        const stopCount = labels.length;\n        if (value >= labels[stopCount - 1]) {\n            return outputs[stopCount - 1].evaluate(ctx);\n        }\n\n        const index = findStopLessThanOrEqualTo(labels, value, this.key);\n        const lower = labels[index];\n        const upper = labels[index + 1];\n        const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper);\n\n        const outputLower = outputs[index].evaluate(ctx);\n        const outputUpper = outputs[index + 1].evaluate(ctx);\n\n        switch (this.operator) {\n            case 'interpolate':\n                switch (this.type.kind) {\n                    case 'number':\n                        return interpolateNumber(outputLower, outputUpper, t);\n                    case 'color':\n                        return Color.interpolate(outputLower, outputUpper, t);\n                    case 'padding':\n                        return Padding.interpolate(outputLower, outputUpper, t);\n                    case 'colorArray':\n                        return ColorArray.interpolate(outputLower, outputUpper, t);\n                    case 'numberArray':\n                        return NumberArray.interpolate(outputLower, outputUpper, t);\n                    case 'variableAnchorOffsetCollection':\n                        return VariableAnchorOffsetCollection.interpolate(\n                            outputLower,\n                            outputUpper,\n                            t,\n                            this.key\n                        );\n                    case 'array':\n                        return interpolateArray(outputLower, outputUpper, t);\n                    case 'projectionDefinition':\n                        return ProjectionDefinition.interpolate(outputLower, outputUpper, t);\n                }\n            case 'interpolate-hcl':\n                switch (this.type.kind) {\n                    case 'color':\n                        return Color.interpolate(outputLower, outputUpper, t, 'hcl');\n                    case 'colorArray':\n                        return ColorArray.interpolate(outputLower, outputUpper, t, 'hcl');\n                }\n            case 'interpolate-lab':\n                switch (this.type.kind) {\n                    case 'color':\n                        return Color.interpolate(outputLower, outputUpper, t, 'lab');\n                    case 'colorArray':\n                        return ColorArray.interpolate(outputLower, outputUpper, t, 'lab');\n                }\n            case 'interpolate-oklch':\n                switch (this.type.kind) {\n                    case 'color':\n                        return Color.interpolate(outputLower, outputUpper, t, 'oklch');\n                    case 'colorArray':\n                        return ColorArray.interpolate(outputLower, outputUpper, t, 'oklch');\n                }\n            case 'interpolate-oklab':\n                switch (this.type.kind) {\n                    case 'color':\n                        return Color.interpolate(outputLower, outputUpper, t, 'oklab');\n                    case 'colorArray':\n                        return ColorArray.interpolate(outputLower, outputUpper, t, 'oklab');\n                }\n        }\n    }\n\n    eachChild(fn: (_: Expression) => void) {\n        fn(this.input);\n        for (const expression of this.outputs) {\n            fn(expression);\n        }\n    }\n\n    outputDefined(): boolean {\n        return this.outputs.every((out) => out.outputDefined());\n    }\n}\n\n/**\n * Returns a ratio that can be used to interpolate between exponential function\n * stops.\n * How it works: Two consecutive stop values define a (scaled and shifted) exponential function `f(x) = a * base^x + b`, where `base` is the user-specified base,\n * and `a` and `b` are constants affording sufficient degrees of freedom to fit\n * the function to the given stops.\n *\n * Here's a bit of algebra that lets us compute `f(x)` directly from the stop\n * values without explicitly solving for `a` and `b`:\n *\n * First stop value: `f(x0) = y0 = a * base^x0 + b`\n * Second stop value: `f(x1) = y1 = a * base^x1 + b`\n * => `y1 - y0 = a(base^x1 - base^x0)`\n * => `a = (y1 - y0)/(base^x1 - base^x0)`\n *\n * Desired value: `f(x) = y = a * base^x + b`\n * => `f(x) = y0 + a * (base^x - base^x0)`\n *\n * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a\n * little algebra:\n * ```\n * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0)\n *                     = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0)\n * ```\n *\n * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have\n * `f(x) = y0 + (y1 - y0) * ratio`.  In other words, `ratio` may be treated as\n * an interpolation factor between the two stops' output values.\n *\n * (Note: a slightly different form for `ratio`,\n * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer\n * expensive `Math.pow()` operations.)\n *\n * @private\n */\nfunction exponentialInterpolation(input, base, lowerValue, upperValue) {\n    const difference = upperValue - lowerValue;\n    const progress = input - lowerValue;\n\n    if (difference === 0) {\n        return 0;\n    } else if (base === 1) {\n        return progress / difference;\n    } else {\n        return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);\n    }\n}\n\nexport const interpolateFactory = {\n    color: Color.interpolate,\n    number: interpolateNumber,\n    padding: Padding.interpolate,\n    numberArray: NumberArray.interpolate,\n    colorArray: ColorArray.interpolate,\n    variableAnchorOffsetCollection: VariableAnchorOffsetCollection.interpolate,\n    array: interpolateArray\n};\n"],"mappings":";;;;;;;;;;;AAyDA,IAAa,cAAb,MAAa,YAAkC;CAI3C,YACI,MACA,UAMA,eACA,OACA,OACA,KACF;EAXS,KAAA,OAAA;EACA,KAAA,WAAA;EAMA,KAAA,gBAAA;EACA,KAAA,QAAA;EAES,KAAA,MAAA;EAdI,KAAA,SAAA,CAAC;EACI,KAAA,UAAA,CAAC;EAe1B,KAAK,MAAM,CAAC,OAAO,eAAe,OAAO;GACrC,KAAK,OAAO,KAAK,KAAK;GACtB,KAAK,QAAQ,KAAK,UAAU;EAChC;CACJ;CAEA,OAAO,oBACH,eACA,OACA,OACA,OACF;EACE,IAAI,IAAI;EACR,IAAI,cAAc,SAAS,eACvB,IAAI,yBAAyB,OAAO,cAAc,MAAM,OAAO,KAAK;OACjE,IAAI,cAAc,SAAS,UAC9B,IAAI,yBAAyB,OAAO,GAAG,OAAO,KAAK;OAChD,IAAI,cAAc,SAAS,gBAAgB;GAC9C,MAAM,IAAI,cAAc;GAExB,IADW,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,EACrC,CAAC,CAAC,yBAAyB,OAAO,GAAG,OAAO,KAAK,CAAC;EAC3D;EACA,OAAO;CACX;CAEA,OAAO,MAAM,MAA8B,SAAqC;EAC5E,IAAI,CAAC,UAAU,eAAe,OAAO,GAAG,QAAQ;EAEhD,IAAI,CAAC,MAAM,QAAQ,aAAa,KAAK,cAAc,WAAW,GAC1D,OAAO,QAAQ,MAAM,8CAA8C,CAAC;EAGxE,IAAI,cAAc,OAAO,UACrB,gBAAgB,EAAC,MAAM,SAAQ;OAC5B,IAAI,cAAc,OAAO,eAAe;G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