/** @license * Copyright 2016 - present The Material Motion Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import { Constructor, MotionMappable, NextChannel, ObservableWithMotionOperators, } from '../types'; import { isDefined, } from '../typeGuards'; export type PluckPath = keyof T; export type PluckArgs = { path: PluckPath, }; export interface MotionPluckable { pluck(kwargs: PluckArgs): ObservableWithMotionOperators; pluck(path: PluckPath): ObservableWithMotionOperators; } export function withPluck>>(superclass: S): S & Constructor> { return class extends superclass implements MotionPluckable { /** * Extracts the value at a given path from every incoming object and passes * those values to the observer. * * For instance: * * - `transform$.pluck({ path: 'translate' })` is equivalent to * `transform$.map(transform => transform.translate)` * * - `transform$.pluck({ path: 'translate.x' })` is equivalent to * `transform$.map(transform => transform.translate.x)` */ pluck(kwargs: PluckArgs): ObservableWithMotionOperators; pluck(path: PluckPath): ObservableWithMotionOperators; pluck({ path }: PluckArgs & K): ObservableWithMotionOperators { if (!isDefined(path)) { path = arguments[0]; } return (this as any as ObservableWithMotionOperators>)._map({ transform: createPlucker(path as K) }); } }; } export function createPlucker(path: K) { const pathSegments = path.split('.'); return function plucker>(value: T): T[K] { let result: T[K] = value; for (const pathSegment of pathSegments) { result = result[pathSegment]; } return result; }; }