Source: viewmodel.js

/*! meta-client/modules/viewmodel */
/*jslint
    browser, long, bitwise
*/
/*global
*/
/**
 * viewmodel module.
 *
 * @module meta-client/modules/viewmodel
 */
import _ from "underscore";
import {} from "knockout-mapping";
import ko from "knockout";
import model from "meta-core/modules/model";

const vm = {};

vm.newObjectMapping = function (property) {
    return {
        update: function (options) {
            if (options.data && ko.isObservable(options.data) === false) {
                options.parent[property](options.data);
            }
            return ko.unwrap(options.data);
        }
    };
};

vm.newPasswordValidator = function ({
    passwordConfirm,
    passwordNew,
    regexString = null,
    unmask
}) {
    const hasRegex = _.isEmpty(regexString) === false;
    const passwordRegex = (
        hasRegex
        ? new RegExp(regexString)
        : undefined
    );
    return ko.pureComputed(function () {
        const password = passwordNew();
        const isValid = hasRegex === false || _.isEmpty(password) || password.match(passwordRegex);
        return isValid && (unmask() || password === passwordConfirm());
    });
};

vm.updateProperty = function (object, property, value) {
    if (_.has(object, property)) {
        const propertyValue = object[property];
        if (ko.isObservable(propertyValue)) {
            propertyValue(value);
        } else {
            object[property] = value;
        }
    }
};

vm.updateObject = function (object, name, update) {
    if (name) {
        vm.updateProperty(object, model.META_NAME, name);
    }
    const value = _.get(update, model.OBJECT_VALUE);
    if (_.isObject(value)) {
        if (ko.mapping.isMapped(object)) {
            if (_.has(object, model.OBJECT_VALUE)) {
                ko.mapping.fromJS({value}, object);
            } else {
                ko.mapping.fromJS(value, object);
            }
        } else {
            vm.updateProperty(object, model.OBJECT_VALUE, Object.assign(ko.unwrap(object.value), value));
        }
    }
    const position = _.get(update, model.OBJECT_POSITION);
    if (_.isObject(position)) {
        vm.updateProperty(
            object,
            model.OBJECT_POSITION,
            (
                model.isValidPosition(position)
                ? position
                : undefined
            )
        );
    }
    return object;
};

export default Object.freeze(vm);