<commit_before>/**
 * Product Template Script
 * ------------------------------------------------------------------------------
 * A file that contains scripts highly couple code to the Product template.
 *
 * @namespace product
 */

import $ from 'jquery';
import Variants from '../slate/variants';
import images from '../slate/images';
import currancy from '../slate/currency';

const selectors = {
  addToCart: '[data-add-to-cart]',
  addToCartText: '[data-add-to-cart-text]',
  comparePrice: '[data-compare-price]',
  comparePriceText: '[data-compare-text]',
  originalSelectorId: '[data-product-select]',
  priceWrapper: '[data-price-wrapper]',
  productFeaturedImage: '[data-product-featured-image]',
  productJson: '[data-product-json]',
  productPrice: '[data-product-price]',
  productThumbs: '[data-product-single-thumbnail]',
  singleOptionSelector: '[data-single-option-selector]',
};

/**
 * Product section constructor. Runs on page load as well as Theme Editor
 * `section:load` events.
 * @param {string} container - selector for the section container DOM element
 */
export default function Product(container) {
  this.$container = $(container);

  // Stop parsing if we don't have the product json script tag when loading
  // section in the Theme Editor
  if (!$(selectors.productJson, this.$container).html()) {
    return;
  }

  const sectionId = this.$container.attr('data-section-id');
  this.productSingleObject = JSON.parse(
    $(selectors.productJson, this.$container).html()
  );

  const options = {
    $container: this.$container,
    enableHistoryState: this.$container.data('enable-history-state') || false,
    singleOptionSelector: selectors.singleOptionSelector,
    originalSelectorId: selectors.originalSelectorId,
    product: this.productSingleObject,
  };

  this.settings = {};
  this.namespace = '.product';
  this.variants = new Variants(options);
  this.$featuredImage = $(selectors.productFeaturedImage, this.$container);

  this.$container.on(
    `variantChange${this.namespace}`,
    this.updateAddToCartState.bind(this)
  );
  this.$container.on(
    `variantPriceChange${this.namespace}`,
    this.updateProductPrices.bind(this)
  );

  if (this.$featuredImage.length > 0) {
    this.settings.imageSize = images.imageSize(this.$featuredImage.attr('src'));
    images.preload(this.productSingleObject.images, this.settings.imageSize);

    this.$container.on(
      `variantImageChange${this.namespace}`,
      this.updateProductImage.bind(this)
    );
  }
}

Product.prototype = $.extend({}, Product.prototype, {

  /**
   * Updates the DOM state of the add to cart button
   *
   * @param {boolean} enabled - Decides whether cart is enabled or disabled
   * @param {string} text - Updates the text notification content of the cart
   */
  updateAddToCartState(evt) {
    const variant = evt.variant;

    if (variant) {
      $(selectors.priceWrapper, this.$container).removeClass('hide');
    } else {
      $(selectors.addToCart, this.$container).prop('disabled', true);
      $(selectors.addToCartText, this.$container).html(
        theme.strings.unavailable
      );
      $(selectors.priceWrapper, this.$container).addClass('hide');
      return;
    }

    if (variant.available) {
      $(selectors.addToCart, this.$container).prop('disabled', false);
      $(selectors.addToCartText, this.$container).html(theme.strings.addToCart);
    } else {
      $(selectors.addToCart, this.$container).prop('disabled', true);
      $(selectors.addToCartText, this.$container).html(theme.strings.soldOut);
    }
  },

  /**
   * Updates the DOM with specified prices
   *
   * @param {string} productPrice - The current price of the product
   * @param {string} comparePrice - The original price of the product
   */
  updateProductPrices(evt) {
    const variant = evt.variant;
    const $comparePrice = $(selectors.comparePrice, this.$container);
    const $compareEls = $comparePrice.add(
      selectors.comparePriceText,
      this.$container
    );

    $(selectors.productPrice, this.$container).html(
      currency.formatMoney(variant.price, theme.moneyFormat)
    );

    if (variant.compare_at_price > variant.price) {
      $comparePrice.html(
        currency.formatMoney(variant.compare_at_price, theme.moneyFormat)
      );
      $compareEls.removeClass('hide');
    } else {
      $comparePrice.html('');
      $compareEls.addClass('hide');
    }
  },

  /**
   * Updates the DOM with the specified image URL
   *
   * @param {string} src - Image src URL
   */
  updateProductImage(evt) {
    const variant = evt.variant;
    const sizedImgUrl = images.getSizedImageUrl(
      variant.featured_image.src,
      this.settings.imageSize
    );

    this.$featuredImage.attr('src', sizedImgUrl);
  },

  /**
   * Event callback for Theme Editor `section:unload` event
   */
  onUnload() {
    this.$container.off(this.namespace);
  },
});
<commit_msg>Fix currency typo<commit_after>/**
 * Product Template Script
 * ------------------------------------------------------------------------------
 * A file that contains scripts highly couple code to the Product template.
 *
 * @namespace product
 */

import $ from 'jquery';
import Variants from '../slate/variants';
import images from '../slate/images';
import currency from '../slate/currency';

const selectors = {
  addToCart: '[data-add-to-cart]',
  addToCartText: '[data-add-to-cart-text]',
  comparePrice: '[data-compare-price]',
  comparePriceText: '[data-compare-text]',
  originalSelectorId: '[data-product-select]',
  priceWrapper: '[data-price-wrapper]',
  productFeaturedImage: '[data-product-featured-image]',
  productJson: '[data-product-json]',
  productPrice: '[data-product-price]',
  productThumbs: '[data-product-single-thumbnail]',
  singleOptionSelector: '[data-single-option-selector]',
};

/**
 * Product section constructor. Runs on page load as well as Theme Editor
 * `section:load` events.
 * @param {string} container - selector for the section container DOM element
 */
export default function Product(container) {
  this.$container = $(container);

  // Stop parsing if we don't have the product json script tag when loading
  // section in the Theme Editor
  if (!$(selectors.productJson, this.$container).html()) {
    return;
  }

  const sectionId = this.$container.attr('data-section-id');
  this.productSingleObject = JSON.parse(
    $(selectors.productJson, this.$container).html()
  );

  const options = {
    $container: this.$container,
    enableHistoryState: this.$container.data('enable-history-state') || false,
    singleOptionSelector: selectors.singleOptionSelector,
    originalSelectorId: selectors.originalSelectorId,
    product: this.productSingleObject,
  };

  this.settings = {};
  this.namespace = '.product';
  this.variants = new Variants(options);
  this.$featuredImage = $(selectors.productFeaturedImage, this.$container);

  this.$container.on(
    `variantChange${this.namespace}`,
    this.updateAddToCartState.bind(this)
  );
  this.$container.on(
    `variantPriceChange${this.namespace}`,
    this.updateProductPrices.bind(this)
  );

  if (this.$featuredImage.length > 0) {
    this.settings.imageSize = images.imageSize(this.$featuredImage.attr('src'));
    images.preload(this.productSingleObject.images, this.settings.imageSize);

    this.$container.on(
      `variantImageChange${this.namespace}`,
      this.updateProductImage.bind(this)
    );
  }
}

Product.prototype = $.extend({}, Product.prototype, {
  /**
   * Updates the DOM state of the add to cart button
   *
   * @param {boolean} enabled - Decides whether cart is enabled or disabled
   * @param {string} text - Updates the text notification content of the cart
   */
  updateAddToCartState(evt) {
    const variant = evt.variant;

    if (variant) {
      $(selectors.priceWrapper, this.$container).removeClass('hide');
    } else {
      $(selectors.addToCart, this.$container).prop('disabled', true);
      $(selectors.addToCartText, this.$container).html(
        theme.strings.unavailable
      );
      $(selectors.priceWrapper, this.$container).addClass('hide');
      return;
    }

    if (variant.available) {
      $(selectors.addToCart, this.$container).prop('disabled', false);
      $(selectors.addToCartText, this.$container).html(theme.strings.addToCart);
    } else {
      $(selectors.addToCart, this.$container).prop('disabled', true);
      $(selectors.addToCartText, this.$container).html(theme.strings.soldOut);
    }
  },

  /**
   * Updates the DOM with specified prices
   *
   * @param {string} productPrice - The current price of the product
   * @param {string} comparePrice - The original price of the product
   */
  updateProductPrices(evt) {
    const variant = evt.variant;
    const $comparePrice = $(selectors.comparePrice, this.$container);
    const $compareEls = $comparePrice.add(
      selectors.comparePriceText,
      this.$container
    );

    $(selectors.productPrice, this.$container).html(
      currency.formatMoney(variant.price, theme.moneyFormat)
    );

    if (variant.compare_at_price > variant.price) {
      $comparePrice.html(
        currency.formatMoney(variant.compare_at_price, theme.moneyFormat)
      );
      $compareEls.removeClass('hide');
    } else {
      $comparePrice.html('');
      $compareEls.addClass('hide');
    }
  },

  /**
   * Updates the DOM with the specified image URL
   *
   * @param {string} src - Image src URL
   */
  updateProductImage(evt) {
    const variant = evt.variant;
    const sizedImgUrl = images.getSizedImageUrl(
      variant.featured_image.src,
      this.settings.imageSize
    );

    this.$featuredImage.attr('src', sizedImgUrl);
  },

  /**
   * Event callback for Theme Editor `section:unload` event
   */
  onUnload() {
    this.$container.off(this.namespace);
  },
});
<|endoftext|>


<commit_before>/*
 * index.js: Database client for MongoHQ Cloud Databases
 *
 * (C) 2012 Nodejitsu Inc.
 *
 */

var utile     = require('utile'),
    base      = require('../../../core/base'),
    auth      = require('../../../common/auth'),
    url       = require('url'),
    request   = require('request'),
    errs      = require('errs');

var Client = exports.Client = function (options) {
  base.Client.call(this, options);

  if (!this.before) {
    this.before = [];
  }

  this.before.push(auth.basic);

  utile.mixin(this, require('./databases'));
};

utile.inherits(Client, base.Client);

Client.prototype.url = function () {
  var args = Array.prototype.slice.call(arguments);
  return [
    'https://www.mongohq.com','provider'
  ].concat(args).join('/');
};

Client.prototype.failCodes = {
  400: 'Bad Request',
  401: 'Unauthorized',
  403: 'Resize not allowed',
  404: 'Item or Account not found',
  409: 'Build in progress',
  413: 'Over Limit',
  415: 'Bad Media Type',
  500: 'Fault',
  503: 'Service Unavailable'
};

Client.prototype.successCodes = {
  200: 'OK',
  201: 'Created',
  202: 'Accepted',
  203: 'Non-authoritative information',
  204: 'No content'
};<commit_msg>[mongohq][fix] use the new endpoint for their API<commit_after>/*
 * index.js: Database client for MongoHQ Cloud Databases
 *
 * (C) 2012 Nodejitsu Inc.
 *
 */

var utile     = require('utile'),
    base      = require('../../../core/base'),
    auth      = require('../../../common/auth'),
    url       = require('url'),
    request   = require('request'),
    errs      = require('errs');

var Client = exports.Client = function (options) {
  base.Client.call(this, options);

  if (!this.before) {
    this.before = [];
  }

  this.before.push(auth.basic);

  utile.mixin(this, require('./databases'));
};

utile.inherits(Client, base.Client);

Client.prototype.url = function () {
  var args = Array.prototype.slice.call(arguments);
  return [
    'https://providers.mongohq.com', 'provider'
  ].concat(args).join('/');
};

Client.prototype.failCodes = {
  400: 'Bad Request',
  401: 'Unauthorized',
  403: 'Resize not allowed',
  404: 'Item or Account not found',
  409: 'Build in progress',
  413: 'Over Limit',
  415: 'Bad Media Type',
  500: 'Fault',
  503: 'Service Unavailable'
};

Client.prototype.successCodes = {
  200: 'OK',
  201: 'Created',
  202: 'Accepted',
  203: 'Non-authoritative information',
  204: 'No content'
};<|endoftext|>


<commit_before>const ee = require('ee')
const {EMPTY, concat, of} = require('rx')
const {filter, map} = require('rx/operators')
const temporalSegmentation = require('./temporalSegmentation')
const {sequence} = require('sepal/utils/array')
const opticalVisParams = require('../optical/visParams')
const {getVisParams: getRadarVisParams} = require('../radar/visParams')

const ccdcSlice = (recipe, {selection: selectedBands} = {selection: []}) => {
    const model = recipe.model
    const segmentsImage = ee.Image(model.source.asset)
    const geometry = segmentsImage.geometry()
    return {
        getImage$() {
            const segments = temporalSegmentation.Segments(segmentsImage, model.source.dateFormat || 0)

            const interpolate = () => {
                const {date: {date}, options: {harmonics}} = model
                return segments.interpolate(date, harmonics)
            }

            const segmentSlice = () => {
                const {date: {date}, options: {harmonics, gapStrategy, extrapolateSegment, extrapolateMaxDays}} = model
                const strategy = gapStrategy === 'MASK' ? 'mask' : extrapolateSegment.toLowerCase()
                const segment = segments.findByDate(date, strategy)
                return segment.fit({date, harmonics, extrapolateMaxDays})
                    .addBands(segment.intercept())
                    .addBands(segment.slope())
                    .addBands(phaseAndAmplitude(segment, 3))
                    .addBands(segment.toImage('.*_rmse'))
            }

            const phaseAndAmplitude = segment => {
                return sequence(1, 3).map(harmonic =>
                    segment.phase(harmonic).addBands(segment.amplitude(harmonic))
                )
            }

            const {options: {gapStrategy}} = model
            const slice = gapStrategy === 'INTERPOLATE'
                ? interpolate()
                : segmentSlice()

            return of(ee.Image(
                slice
                    .select(selectedBands)
                    .copyProperties(segmentsImage, segmentsImage.propertyNames())
            ))
        },
        getVisParams$: function (image) {
            const opticalBandCombinations$ = ee.getInfo$(image.get('surfaceReflectance'), 'check if surfaceReflectance').pipe(
                map(surfaceReflectance => opticalVisParams[surfaceReflectance ? 'SR' : 'TOA'][selectedBands.join('|')]),
                filter(visParams => visParams)
            )

            const opticalIndex$ = selectedBands.length === 1
                ? of(opticalVisParams.indexes[selectedBands[0]]).pipe(
                    filter(visParams => visParams)
                )
                : EMPTY

            const radarBandCombinations$ = of(getRadarVisParams(selectedBands, [], 10000)).pipe(
                filter(visParams => visParams)
            )

            const bandDefs = {
                VV: {amplitude: [4000, 40000], rmse: [15000, 35000]},
                VH: {amplitude: [3000, 40000], rmse: [15000, 40000]},
                ratio_VV_VH: {amplitude: [0, 1200], rmse: [0, 3000]},

                blue: {amplitude: [0, 500], rmse: [0, 500]},
                green: {amplitude: [0, 500], rmse: [0, 500]},
                red: {amplitude: [0, 700], rmse: [0, 700]},
                nir: {amplitude: [0, 1000], rmse: [0, 1000]},
                swir1: {amplitude: [0, 1800], rmse: [0, 1800]},
                swir2: {amplitude: [0, 1800], rmse: [0, 1800]},

                ndvi: {amplitude: [0, 3000], rmse: [0, 2500]},
                ndmi: {amplitude: [0, 5000], rmse: [0, 2000]},
                ndwi: {amplitude: [0, 3000], rmse: [0, 3000]},
                // TODO: Tweak the index ranges
                mndwi: {amplitude: [0, 5000], rmse: [0, 2000]},
                ndfi: {amplitude: [0, 6500], rmse: [0, 6500]},
                evi: {amplitude: [0, 5000], rmse: [0, 2000]},
                evi2: {amplitude: [0, 5000], rmse: [0, 2000]},
                savi: {amplitude: [0, 5000], rmse: [0, 2000]},
                nbr: {amplitude: [0, 5000], rmse: [0, 2000]},
                ui: {amplitude: [0, 5000], rmse: [0, 2000]},
                ndbi: {amplitude: [0, 5000], rmse: [0, 2000]},
                ibi: {amplitude: [0, 5000], rmse: [0, 2000]},
                nbi: {amplitude: [0, 5000], rmse: [0, 2000]},
                ebbi: {amplitude: [0, 5000], rmse: [0, 2000]},
                bui: {amplitude: [0, 5000], rmse: [0, 2000]}

            }

            const bandsWithHarmonics = [...new Set(selectedBands
                .map(band => band.match('(.*)_amplitude_1'))
                .map(match => match && match[1])
                .filter(baseBand => baseBand)
            )]
            if (bandsWithHarmonics.length) {
                const selectedBandDefs = bandsWithHarmonics.map(band => bandDefs[band])
                const min = selectedBandDefs.map(bandDef => [-Math.PI, bandDef.amplitude[0], bandDef.rmse[0]]).flat()
                const max = selectedBandDefs.map(bandDef => [Math.PI, bandDef.amplitude[1], bandDef.rmse[1]]).flat()
                const stretch = [null, null, [1, 0]]
                const visParams = {bands: selectedBands, min, max, stretch, hsv: true}
                const harmonics$ = of(visParams)
                return harmonics$
            } else
                return concat(opticalBandCombinations$, opticalIndex$, radarBandCombinations$)
        },
        getGeometry$() {
            return of(geometry)
        }
    }
}

module.exports = ccdcSlice
<commit_msg>Updated visualization parameters for CCDC slice index preview.<commit_after>const ee = require('ee')
const {EMPTY, concat, of} = require('rx')
const {filter, map} = require('rx/operators')
const temporalSegmentation = require('./temporalSegmentation')
const {sequence} = require('sepal/utils/array')
const opticalVisParams = require('../optical/visParams')
const {getVisParams: getRadarVisParams} = require('../radar/visParams')

const ccdcSlice = (recipe, {selection: selectedBands} = {selection: []}) => {
    const model = recipe.model
    const segmentsImage = ee.Image(model.source.asset)
    const geometry = segmentsImage.geometry()
    return {
        getImage$() {
            const segments = temporalSegmentation.Segments(segmentsImage, model.source.dateFormat || 0)

            const interpolate = () => {
                const {date: {date}, options: {harmonics}} = model
                return segments.interpolate(date, harmonics)
            }

            const segmentSlice = () => {
                const {date: {date}, options: {harmonics, gapStrategy, extrapolateSegment, extrapolateMaxDays}} = model
                const strategy = gapStrategy === 'MASK' ? 'mask' : extrapolateSegment.toLowerCase()
                const segment = segments.findByDate(date, strategy)
                return segment.fit({date, harmonics, extrapolateMaxDays})
                    .addBands(segment.intercept())
                    .addBands(segment.slope())
                    .addBands(phaseAndAmplitude(segment, 3))
                    .addBands(segment.toImage('.*_rmse'))
            }

            const phaseAndAmplitude = segment => {
                return sequence(1, 3).map(harmonic =>
                    segment.phase(harmonic).addBands(segment.amplitude(harmonic))
                )
            }

            const {options: {gapStrategy}} = model
            const slice = gapStrategy === 'INTERPOLATE'
                ? interpolate()
                : segmentSlice()

            return of(ee.Image(
                slice
                    .select(selectedBands)
                    .copyProperties(segmentsImage, segmentsImage.propertyNames())
            ))
        },
        getVisParams$: function (image) {
            const opticalBandCombinations$ = ee.getInfo$(image.get('surfaceReflectance'), 'check if surfaceReflectance').pipe(
                map(surfaceReflectance => opticalVisParams[surfaceReflectance ? 'SR' : 'TOA'][selectedBands.join('|')]),
                filter(visParams => visParams)
            )

            const opticalIndex$ = selectedBands.length === 1
                ? of(opticalVisParams.indexes[selectedBands[0]]).pipe(
                    filter(visParams => visParams)
                )
                : EMPTY

            const radarBandCombinations$ = of(getRadarVisParams(selectedBands, [], 10000)).pipe(
                filter(visParams => visParams)
            )

            const bandDefs = {
                VV: {amplitude: [4000, 40000], rmse: [15000, 35000]},
                VH: {amplitude: [3000, 40000], rmse: [15000, 40000]},
                ratio_VV_VH: {amplitude: [0, 1200], rmse: [0, 3000]},

                blue: {amplitude: [0, 500], rmse: [0, 500]},
                green: {amplitude: [0, 500], rmse: [0, 500]},
                red: {amplitude: [0, 700], rmse: [0, 700]},
                nir: {amplitude: [0, 1000], rmse: [0, 1000]},
                swir1: {amplitude: [0, 1800], rmse: [0, 1800]},
                swir2: {amplitude: [0, 1800], rmse: [0, 1800]},

                ndvi: {amplitude: [0, 3000], rmse: [0, 2500]},
                ndmi: {amplitude: [0, 5000], rmse: [0, 2000]},
                ndwi: {amplitude: [0, 3000], rmse: [0, 3000]},
                mndwi: {amplitude: [0, 5000], rmse: [0, 2000]},
                ndfi: {amplitude: [0, 10000], rmse: [0, 8500]},
                evi: {amplitude: [0, 10000], rmse: [0, 10000]},
                evi2: {amplitude: [0, 10000], rmse: [0, 6500]},
                savi: {amplitude: [0, 10000], rmse: [0, 4000]},
                nbr: {amplitude: [0, 5000], rmse: [0, 2000]},
                ui: {amplitude: [0, 5000], rmse: [0, 2000]},
                ndbi: {amplitude: [0, 5000], rmse: [0, 2000]},
                ibi: {amplitude: [0, 5000], rmse: [0, 2000]},
                nbi: {amplitude: [0, 5000], rmse: [0, 2000]},
                ebbi: {amplitude: [0, 5000], rmse: [0, 2000]},
                bui: {amplitude: [0, 5000], rmse: [0, 2000]},

                wetness: {amplitude: [0, 1500], rmse: [0, 1500]},
                greenness: {amplitude: [0, 3000], rmse: [0, 1500]},
                brightness: {amplitude: [0, 3000], rmse: [0, 3000]},

            }

            const bandsWithHarmonics = [...new Set(selectedBands
                .map(band => band.match('(.*)_amplitude_1'))
                .map(match => match && match[1])
                .filter(baseBand => baseBand)
            )]
            if (bandsWithHarmonics.length) {
                const selectedBandDefs = bandsWithHarmonics.map(band => bandDefs[band])
                const min = selectedBandDefs.map(bandDef => [-Math.PI, bandDef.amplitude[0], bandDef.rmse[0]]).flat()
                const max = selectedBandDefs.map(bandDef => [Math.PI, bandDef.amplitude[1], bandDef.rmse[1]]).flat()
                const stretch = [null, null, [1, 0]]
                const visParams = {bands: selectedBands, min, max, stretch, hsv: true}
                const harmonics$ = of(visParams)
                return harmonics$
            } else
                return concat(opticalBandCombinations$, opticalIndex$, radarBandCombinations$)
        },
        getGeometry$() {
            return of(geometry)
        }
    }
}

module.exports = ccdcSlice
<|endoftext|>


<commit_before><commit_msg>[FIX] web: display selection label in graph<commit_after><|endoftext|>


<commit_before>import convertSourceMap from "convert-source-map";
import * as optionParsers from "./option-parsers";
import shebangRegex from "shebang-regex";
import TraversalPath from "../../traversal/path";
import isFunction from "lodash/lang/isFunction";
import isAbsolute from "path-is-absolute";
import resolveRc from "../../tools/resolve-rc";
import sourceMap from "source-map";
import transform from "./../index";
import generate from "../../generation";
import defaults from "lodash/object/defaults";
import includes from "lodash/collection/includes";
import traverse from "../../traversal";
import assign from "lodash/object/assign";
import Logger from "./logger";
import parse from "../../helpers/parse";
import Scope from "../../traversal/scope";
import slash from "slash";
import * as util from  "../../util";
import path from "path";
import each from "lodash/collection/each";
import * as t from "../../types";

var checkTransformerVisitor = {
  enter(node, parent, scope, state) {
    checkNode(state.stack, node, scope);
  }
};

function checkNode(stack, node, scope) {
  each(stack, function (pass) {
    if (pass.shouldRun || pass.ran) return;
    pass.checkNode(node, scope);
  });
}

export default class File {
  constructor(opts = {}) {
    this.dynamicImportedNoDefault = [];
    this.dynamicImportIds         = {};
    this.dynamicImported          = [];
    this.dynamicImports           = [];

    this.usedHelpers = {};
    this.dynamicData = {};
    this.data        = {};

    this.lastStatements = [];
    this.log            = new Logger(this, opts.filename || "unknown");
    this.opts           = this.normalizeOptions(opts);
    this.ast            = {};

    this.buildTransformers();
  }

  static helpers = [
    "inherits",
    "defaults",
    "create-class",
    "create-decorated-class",
    "tagged-template-literal",
    "tagged-template-literal-loose",
    "interop-require",
    "to-array",
    "to-consumable-array",
    "sliced-to-array",
    "sliced-to-array-loose",
    "object-without-properties",
    "has-own",
    "slice",
    "bind",
    "define-property",
    "async-to-generator",
    "interop-require-wildcard",
    "typeof",
    "extends",
    "get",
    "set",
    "class-call-check",
    "object-destructuring-empty",
    "temporal-undefined",
    "temporal-assert-defined",
    "self-global",
    "default-props"
  ];

  static options = require("./options");

  normalizeOptions(opts: Object) {
    opts = assign({}, opts);

    if (opts.filename && isAbsolute(opts.filename)) {
      opts = resolveRc(opts.filename, opts);
    }

    //

    for (let key in opts) {
      if (key[0] === "_") continue;

      let option = File.options[key];
      if (!option) this.log.error(`Unknown option: ${key}`, ReferenceError);
    }

    for (let key in File.options) {
      let option = File.options[key];

      var val = opts[key];
      if (!val && option.optional) continue;

      if (val && option.deprecated) {
        throw new Error("Deprecated option " + key + ": " + option.deprecated);
      }

      if (val == null) val = option.default || val;

      var optionParser = optionParsers[option.type];
      if (optionParser) val = optionParser(key, val);

      if (option.alias) {
        opts[option.alias] ||= val;
      } else {
        opts[key] = val;
      }
    }

    if (opts.inputSourceMap) {
      opts.sourceMaps = true;
    }

    // normalize windows path separators to unix
    opts.filename = slash(opts.filename);
    if (opts.sourceRoot) {
      opts.sourceRoot = slash(opts.sourceRoot);
    }

    if (opts.moduleId) {
      opts.moduleIds = true;
    }

    opts.basename = path.basename(opts.filename, path.extname(opts.filename));

    opts.ignore = util.arrayify(opts.ignore, util.regexify);
    opts.only   = util.arrayify(opts.only, util.regexify);

    defaults(opts, {
      moduleRoot: opts.sourceRoot
    });

    defaults(opts, {
      sourceRoot: opts.moduleRoot
    });

    defaults(opts, {
      filenameRelative: opts.filename
    });

    defaults(opts, {
      sourceFileName: opts.filenameRelative,
      sourceMapName:  opts.filenameRelative
    });

    //

    if (opts.externalHelpers) {
      this.set("helpersNamespace", t.identifier("babelHelpers"));
    }

    return opts;
  };

  isLoose(key: string) {
    return includes(this.opts.loose, key);
  }

  buildPlugins(stack) {

  }

  buildTransformers() {
    var file = this;

    var transformers = {};

    var secondaryStack = [];
    var stack = [];

    this.buildPlugins(stack);

    each(transform.transformers, function (transformer, key) {
      var pass = transformers[key] = transformer.buildPass(file);

      if (pass.canTransform()) {
        stack.push(pass);

        if (transformer.metadata.secondPass) {
          secondaryStack.push(pass);
        }

        if (transformer.manipulateOptions) {
          transformer.manipulateOptions(file.opts, file);
        }
      }
    });

    this.transformerStack = stack.concat(secondaryStack);
    this.transformers = transformers;
  }

  getModuleFormatter(type: string) {
    var ModuleFormatter = isFunction(type) ? type : transform.moduleFormatters[type];

    if (!ModuleFormatter) {
      var loc = util.resolve(type);
      if (loc) ModuleFormatter = require(loc);
    }

    if (!ModuleFormatter) {
      throw new ReferenceError(`Unknown module formatter type ${JSON.stringify(type)}`);
    }

    return new ModuleFormatter(this);
  }

  parseInputSourceMap(code: string) {
    var opts = this.opts;

    if (opts.inputSourceMap !== false) {
      var inputMap = convertSourceMap.fromSource(code);
      if (inputMap) {
        opts.inputSourceMap = inputMap.toObject();
        code = convertSourceMap.removeComments(code);
      }
    }

    return code;
  }

  parseShebang(code: string) {
    var shebangMatch = shebangRegex.exec(code);

    if (shebangMatch) {
      this.shebang = shebangMatch[0];

      // remove shebang
      code = code.replace(shebangRegex, "");
    }

    return code;
  }

  set(key: string, val): any {
    return this.data[key] = val;
  };

  setDynamic(key: string, fn: Function) {
    this.dynamicData[key] = fn;
  }

  get(key: string): any {
    var data = this.data[key];
    if (data) {
      return data;
    } else {
      var dynamic = this.dynamicData[key];
      if (dynamic) {
        return this.set(key, dynamic());
      }
    }
  }

  resolveModuleSource(source: string): string {
    var resolveModuleSource = this.opts.resolveModuleSource;
    if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
    return source;
  }

  addImport(source: string, name?: string, noDefault?: boolean): Object {
    name ||= source;
    var id = this.dynamicImportIds[name];

    if (!id) {
      source = this.resolveModuleSource(source);
      id = this.dynamicImportIds[name] = this.scope.generateUidIdentifier(name);

      var specifiers = [t.importDefaultSpecifier(id)];
      var declar = t.importDeclaration(specifiers, t.literal(source));
      declar._blockHoist = 3;

      this.dynamicImported.push(declar);
      if (noDefault) this.dynamicImportedNoDefault.push(declar);

      if (this.transformers["es6.modules"].canTransform()) {
        this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports);
      } else {
        this.dynamicImports.push(declar);
      }
    }

    return id;
  }

  isConsequenceExpressionStatement(node: Object): boolean {
    return t.isExpressionStatement(node) && this.lastStatements.indexOf(node) >= 0;
  }

  attachAuxiliaryComment(node: Object): Object {
    var comment = this.opts.auxiliaryComment;
    if (comment) {
      node.leadingComments ||= [];
      node.leadingComments.push({
        type: "Line",
        value: " " + comment
      });
    }
    return node;
  }

  addHelper(name: string): Object {
    if (!includes(File.helpers, name)) {
      throw new ReferenceError(`Unknown helper ${name}`);
    }

    var program = this.ast.program;

    var declar = program._declarations && program._declarations[name];
    if (declar) return declar.id;

    this.usedHelpers[name] = true;

    var generator = this.get("helperGenerator");
    var runtime   = this.get("helpersNamespace");
    if (generator) {
      return generator(name);
    } else if (runtime) {
      var id = t.identifier(t.toIdentifier(name));
      return t.memberExpression(runtime, id);
    } else {
      var ref = util.template("helper-" + name);
      ref._compact = true;
      var uid = this.scope.generateUidIdentifier(name);
      this.scope.push({
        key: name,
        id: uid,
        init: ref
      });
      return uid;
    }
  }

  errorWithNode(node, msg, Error = SyntaxError) {
    var loc = node.loc.start;
    var err = new Error(`Line ${loc.line}: ${msg}`);
    err.loc = loc;
    return err;
  }

  addCode(code: string) {
    code = (code || "") + "";
    code = this.parseInputSourceMap(code);
    this.code = code;
    return this.parseShebang(code);
  }

  shouldIgnore() {
    var opts = this.opts;

    var filename = opts.filename;
    var ignore   = opts.ignore;
    var only     = opts.only;

    if (only.length) {
      for (var i = 0; i < only.length; i++) {
        if (only[i].test(filename)) return false;
      }
      return true;
    } else if (ignore.length) {
      for (var i = 0; i < ignore.length; i++) {
        if (ignore[i].test(filename)) return true;
      }
    }

    return false;
  }

  parse(code: string) {
    if (this.shouldIgnore()) {
      return {
        code: code,
        map:  null,
        ast:  null
      };
    }

    code = this.addCode(code);

    var opts = this.opts;

    //

    var parseOpts = {
      highlightCode: opts.highlightCode,
      nonStandard:   opts.nonStandard,
      filename:      opts.filename,
      plugins:       {}
    };

    var features = parseOpts.features = {};
    for (var key in this.transformers) {
      var transformer = this.transformers[key];
      features[key] = transformer.canTransform();
    }

    parseOpts.looseModules = this.isLoose("es6.modules");
    parseOpts.strictMode = features.strict;
    parseOpts.sourceType = "module";

    //

    return parse(parseOpts, code, (tree) => {
      this.transform(tree);
      return this.generate();
    });
  }

  setAst(ast) {
    this.path  = TraversalPath.get(null, null, ast, ast, "program", this);
    this.scope = this.path.scope;
    this.ast   = ast;

    /*this.path.traverse({
      enter(node, parent, scope) {
        if (this.isScope()) {
          for (var key in scope.bindings) {
            scope.bindings[key].setTypeAnnotation();
          }
        }
      }
    });*/
  }

  transform(ast) {
    this.log.debug();

    this.setAst(ast);

    this.lastStatements = t.getLastStatements(ast.program);

    var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
    if (modFormatter.init && this.transformers["es6.modules"].canTransform()) {
      modFormatter.init();
    }

    this.checkNode(ast);

    this.call("pre");

    each(this.transformerStack, function (pass) {
      pass.transform();
    });

    this.call("post");
  }

  call(key: string) {
    var stack = this.transformerStack;
    for (var i = 0; i < stack.length; i++) {
      var transformer = stack[i].transformer;
      var fn = transformer[key];
      if (fn) fn(this);
    }
  }

  checkNode(node, scope) {
    if (Array.isArray(node)) {
      for (var i = 0; i < node.length; i++) {
        this.checkNode(node[i], scope);
      }
      return;
    }

    var stack = this.transformerStack;
    scope ||= this.scope;

    checkNode(stack, node, scope);

    scope.traverse(node, checkTransformerVisitor, {
      stack: stack
    });
  }

  mergeSourceMap(map: Object) {
    var opts = this.opts;

    var inputMap = opts.inputSourceMap;

    if (inputMap) {
      map.sources[0] = inputMap.file;

      var inputMapConsumer   = new sourceMap.SourceMapConsumer(inputMap);
      var outputMapConsumer  = new sourceMap.SourceMapConsumer(map);
      var outputMapGenerator = sourceMap.SourceMapGenerator.fromSourceMap(outputMapConsumer);
      outputMapGenerator.applySourceMap(inputMapConsumer);

      var mergedMap = outputMapGenerator.toJSON();
      mergedMap.sources = inputMap.sources
      mergedMap.file    = inputMap.file;
      return mergedMap;
    }

    return map;
  }

  generate(): {
    usedHelpers?: Array<string>;
    code: string;
    map?: Object;
    ast?: Object;
  } {
    var opts = this.opts;
    var ast  = this.ast;

    var result = {
      code: "",
      map:  null,
      ast:  null
    };

    if (this.opts.returnUsedHelpers) {
      result.usedHelpers = Object.keys(this.usedHelpers);
    }

    if (opts.ast) result.ast = ast;
    if (!opts.code) return result;

    var _result = generate(ast, opts, this.code);
    result.code = _result.code;
    result.map  = _result.map;

    if (this.shebang) {
      // add back shebang
      result.code = `${this.shebang}\n${result.code}`;
    }

    if (result.map) {
      result.map = this.mergeSourceMap(result.map);
    }

    if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
      result.code += "\n" + convertSourceMap.fromObject(result.map).toComment();
    }

    if (opts.sourceMaps === "inline") {
      result.map = null;
    }

    return result;
  }
}
<commit_msg>reneable seting of type annotations<commit_after>import convertSourceMap from "convert-source-map";
import * as optionParsers from "./option-parsers";
import shebangRegex from "shebang-regex";
import TraversalPath from "../../traversal/path";
import isFunction from "lodash/lang/isFunction";
import isAbsolute from "path-is-absolute";
import resolveRc from "../../tools/resolve-rc";
import sourceMap from "source-map";
import transform from "./../index";
import generate from "../../generation";
import defaults from "lodash/object/defaults";
import includes from "lodash/collection/includes";
import traverse from "../../traversal";
import assign from "lodash/object/assign";
import Logger from "./logger";
import parse from "../../helpers/parse";
import Scope from "../../traversal/scope";
import slash from "slash";
import * as util from  "../../util";
import path from "path";
import each from "lodash/collection/each";
import * as t from "../../types";

var checkTransformerVisitor = {
  enter(node, parent, scope, state) {
    checkNode(state.stack, node, scope);
  }
};

function checkNode(stack, node, scope) {
  each(stack, function (pass) {
    if (pass.shouldRun || pass.ran) return;
    pass.checkNode(node, scope);
  });
}

export default class File {
  constructor(opts = {}) {
    this.dynamicImportedNoDefault = [];
    this.dynamicImportIds         = {};
    this.dynamicImported          = [];
    this.dynamicImports           = [];

    this.usedHelpers = {};
    this.dynamicData = {};
    this.data        = {};

    this.lastStatements = [];
    this.log            = new Logger(this, opts.filename || "unknown");
    this.opts           = this.normalizeOptions(opts);
    this.ast            = {};

    this.buildTransformers();
  }

  static helpers = [
    "inherits",
    "defaults",
    "create-class",
    "create-decorated-class",
    "tagged-template-literal",
    "tagged-template-literal-loose",
    "interop-require",
    "to-array",
    "to-consumable-array",
    "sliced-to-array",
    "sliced-to-array-loose",
    "object-without-properties",
    "has-own",
    "slice",
    "bind",
    "define-property",
    "async-to-generator",
    "interop-require-wildcard",
    "typeof",
    "extends",
    "get",
    "set",
    "class-call-check",
    "object-destructuring-empty",
    "temporal-undefined",
    "temporal-assert-defined",
    "self-global",
    "default-props"
  ];

  static options = require("./options");

  normalizeOptions(opts: Object) {
    opts = assign({}, opts);

    if (opts.filename && isAbsolute(opts.filename)) {
      opts = resolveRc(opts.filename, opts);
    }

    //

    for (let key in opts) {
      if (key[0] === "_") continue;

      let option = File.options[key];
      if (!option) this.log.error(`Unknown option: ${key}`, ReferenceError);
    }

    for (let key in File.options) {
      let option = File.options[key];

      var val = opts[key];
      if (!val && option.optional) continue;

      if (val && option.deprecated) {
        throw new Error("Deprecated option " + key + ": " + option.deprecated);
      }

      if (val == null) val = option.default || val;

      var optionParser = optionParsers[option.type];
      if (optionParser) val = optionParser(key, val);

      if (option.alias) {
        opts[option.alias] ||= val;
      } else {
        opts[key] = val;
      }
    }

    if (opts.inputSourceMap) {
      opts.sourceMaps = true;
    }

    // normalize windows path separators to unix
    opts.filename = slash(opts.filename);
    if (opts.sourceRoot) {
      opts.sourceRoot = slash(opts.sourceRoot);
    }

    if (opts.moduleId) {
      opts.moduleIds = true;
    }

    opts.basename = path.basename(opts.filename, path.extname(opts.filename));

    opts.ignore = util.arrayify(opts.ignore, util.regexify);
    opts.only   = util.arrayify(opts.only, util.regexify);

    defaults(opts, {
      moduleRoot: opts.sourceRoot
    });

    defaults(opts, {
      sourceRoot: opts.moduleRoot
    });

    defaults(opts, {
      filenameRelative: opts.filename
    });

    defaults(opts, {
      sourceFileName: opts.filenameRelative,
      sourceMapName:  opts.filenameRelative
    });

    //

    if (opts.externalHelpers) {
      this.set("helpersNamespace", t.identifier("babelHelpers"));
    }

    return opts;
  };

  isLoose(key: string) {
    return includes(this.opts.loose, key);
  }

  buildPlugins(stack) {

  }

  buildTransformers() {
    var file = this;

    var transformers = {};

    var secondaryStack = [];
    var stack = [];

    this.buildPlugins(stack);

    each(transform.transformers, function (transformer, key) {
      var pass = transformers[key] = transformer.buildPass(file);

      if (pass.canTransform()) {
        stack.push(pass);

        if (transformer.metadata.secondPass) {
          secondaryStack.push(pass);
        }

        if (transformer.manipulateOptions) {
          transformer.manipulateOptions(file.opts, file);
        }
      }
    });

    this.transformerStack = stack.concat(secondaryStack);
    this.transformers = transformers;
  }

  getModuleFormatter(type: string) {
    var ModuleFormatter = isFunction(type) ? type : transform.moduleFormatters[type];

    if (!ModuleFormatter) {
      var loc = util.resolve(type);
      if (loc) ModuleFormatter = require(loc);
    }

    if (!ModuleFormatter) {
      throw new ReferenceError(`Unknown module formatter type ${JSON.stringify(type)}`);
    }

    return new ModuleFormatter(this);
  }

  parseInputSourceMap(code: string) {
    var opts = this.opts;

    if (opts.inputSourceMap !== false) {
      var inputMap = convertSourceMap.fromSource(code);
      if (inputMap) {
        opts.inputSourceMap = inputMap.toObject();
        code = convertSourceMap.removeComments(code);
      }
    }

    return code;
  }

  parseShebang(code: string) {
    var shebangMatch = shebangRegex.exec(code);

    if (shebangMatch) {
      this.shebang = shebangMatch[0];

      // remove shebang
      code = code.replace(shebangRegex, "");
    }

    return code;
  }

  set(key: string, val): any {
    return this.data[key] = val;
  };

  setDynamic(key: string, fn: Function) {
    this.dynamicData[key] = fn;
  }

  get(key: string): any {
    var data = this.data[key];
    if (data) {
      return data;
    } else {
      var dynamic = this.dynamicData[key];
      if (dynamic) {
        return this.set(key, dynamic());
      }
    }
  }

  resolveModuleSource(source: string): string {
    var resolveModuleSource = this.opts.resolveModuleSource;
    if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
    return source;
  }

  addImport(source: string, name?: string, noDefault?: boolean): Object {
    name ||= source;
    var id = this.dynamicImportIds[name];

    if (!id) {
      source = this.resolveModuleSource(source);
      id = this.dynamicImportIds[name] = this.scope.generateUidIdentifier(name);

      var specifiers = [t.importDefaultSpecifier(id)];
      var declar = t.importDeclaration(specifiers, t.literal(source));
      declar._blockHoist = 3;

      this.dynamicImported.push(declar);
      if (noDefault) this.dynamicImportedNoDefault.push(declar);

      if (this.transformers["es6.modules"].canTransform()) {
        this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports);
      } else {
        this.dynamicImports.push(declar);
      }
    }

    return id;
  }

  isConsequenceExpressionStatement(node: Object): boolean {
    return t.isExpressionStatement(node) && this.lastStatements.indexOf(node) >= 0;
  }

  attachAuxiliaryComment(node: Object): Object {
    var comment = this.opts.auxiliaryComment;
    if (comment) {
      node.leadingComments ||= [];
      node.leadingComments.push({
        type: "Line",
        value: " " + comment
      });
    }
    return node;
  }

  addHelper(name: string): Object {
    if (!includes(File.helpers, name)) {
      throw new ReferenceError(`Unknown helper ${name}`);
    }

    var program = this.ast.program;

    var declar = program._declarations && program._declarations[name];
    if (declar) return declar.id;

    this.usedHelpers[name] = true;

    var generator = this.get("helperGenerator");
    var runtime   = this.get("helpersNamespace");
    if (generator) {
      return generator(name);
    } else if (runtime) {
      var id = t.identifier(t.toIdentifier(name));
      return t.memberExpression(runtime, id);
    } else {
      var ref = util.template("helper-" + name);
      ref._compact = true;
      var uid = this.scope.generateUidIdentifier(name);
      this.scope.push({
        key: name,
        id: uid,
        init: ref
      });
      return uid;
    }
  }

  errorWithNode(node, msg, Error = SyntaxError) {
    var loc = node.loc.start;
    var err = new Error(`Line ${loc.line}: ${msg}`);
    err.loc = loc;
    return err;
  }

  addCode(code: string) {
    code = (code || "") + "";
    code = this.parseInputSourceMap(code);
    this.code = code;
    return this.parseShebang(code);
  }

  shouldIgnore() {
    var opts = this.opts;

    var filename = opts.filename;
    var ignore   = opts.ignore;
    var only     = opts.only;

    if (only.length) {
      for (var i = 0; i < only.length; i++) {
        if (only[i].test(filename)) return false;
      }
      return true;
    } else if (ignore.length) {
      for (var i = 0; i < ignore.length; i++) {
        if (ignore[i].test(filename)) return true;
      }
    }

    return false;
  }

  parse(code: string) {
    if (this.shouldIgnore()) {
      return {
        code: code,
        map:  null,
        ast:  null
      };
    }

    code = this.addCode(code);

    var opts = this.opts;

    //

    var parseOpts = {
      highlightCode: opts.highlightCode,
      nonStandard:   opts.nonStandard,
      filename:      opts.filename,
      plugins:       {}
    };

    var features = parseOpts.features = {};
    for (var key in this.transformers) {
      var transformer = this.transformers[key];
      features[key] = transformer.canTransform();
    }

    parseOpts.looseModules = this.isLoose("es6.modules");
    parseOpts.strictMode = features.strict;
    parseOpts.sourceType = "module";

    //

    return parse(parseOpts, code, (tree) => {
      this.transform(tree);
      return this.generate();
    });
  }

  setAst(ast) {
    this.path  = TraversalPath.get(null, null, ast, ast, "program", this);
    this.scope = this.path.scope;
    this.ast   = ast;

    this.path.traverse({
      enter(node, parent, scope) {
        if (this.isScope()) {
          for (var key in scope.bindings) {
            scope.bindings[key].setTypeAnnotation();
          }
        }
      }
    });
  }

  transform(ast) {
    this.log.debug();

    this.setAst(ast);

    this.lastStatements = t.getLastStatements(ast.program);

    var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
    if (modFormatter.init && this.transformers["es6.modules"].canTransform()) {
      modFormatter.init();
    }

    this.checkNode(ast);

    this.call("pre");

    each(this.transformerStack, function (pass) {
      pass.transform();
    });

    this.call("post");
  }

  call(key: string) {
    var stack = this.transformerStack;
    for (var i = 0; i < stack.length; i++) {
      var transformer = stack[i].transformer;
      var fn = transformer[key];
      if (fn) fn(this);
    }
  }

  checkNode(node, scope) {
    if (Array.isArray(node)) {
      for (var i = 0; i < node.length; i++) {
        this.checkNode(node[i], scope);
      }
      return;
    }

    var stack = this.transformerStack;
    scope ||= this.scope;

    checkNode(stack, node, scope);

    scope.traverse(node, checkTransformerVisitor, {
      stack: stack
    });
  }

  mergeSourceMap(map: Object) {
    var opts = this.opts;

    var inputMap = opts.inputSourceMap;

    if (inputMap) {
      map.sources[0] = inputMap.file;

      var inputMapConsumer   = new sourceMap.SourceMapConsumer(inputMap);
      var outputMapConsumer  = new sourceMap.SourceMapConsumer(map);
      var outputMapGenerator = sourceMap.SourceMapGenerator.fromSourceMap(outputMapConsumer);
      outputMapGenerator.applySourceMap(inputMapConsumer);

      var mergedMap = outputMapGenerator.toJSON();
      mergedMap.sources = inputMap.sources
      mergedMap.file    = inputMap.file;
      return mergedMap;
    }

    return map;
  }

  generate(): {
    usedHelpers?: Array<string>;
    code: string;
    map?: Object;
    ast?: Object;
  } {
    var opts = this.opts;
    var ast  = this.ast;

    var result = {
      code: "",
      map:  null,
      ast:  null
    };

    if (this.opts.returnUsedHelpers) {
      result.usedHelpers = Object.keys(this.usedHelpers);
    }

    if (opts.ast) result.ast = ast;
    if (!opts.code) return result;

    var _result = generate(ast, opts, this.code);
    result.code = _result.code;
    result.map  = _result.map;

    if (this.shebang) {
      // add back shebang
      result.code = `${this.shebang}\n${result.code}`;
    }

    if (result.map) {
      result.map = this.mergeSourceMap(result.map);
    }

    if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
      result.code += "\n" + convertSourceMap.fromObject(result.map).toComment();
    }

    if (opts.sourceMaps === "inline") {
      result.map = null;
    }

    return result;
  }
}
<|endoftext|>


<commit_before>/*---------------------------------------------------------
 * OpenERP Web Mobile List View
 *---------------------------------------------------------*/

openerp.web_mobile.list_mobile = function (openerp) {

openerp.web_mobile.ListView = openerp.base.Widget.extend({
    init: function(session, element_id, list_id) {
        this._super(session, element_id);
        this.list_id = list_id;
    },
    start: function() {
        this.rpc('/base/menu/action', {'menu_id': this.list_id},
                    this.on_menu_action_loaded);
    },
    on_menu_action_loaded: function(data) {
        var self = this;
        if (data.action.length) {
            this.action = data.action[0][2];
            this.on_search_data();
        }
    },
    on_search_data: function(ev){
        var self = this;
        var dataset = new openerp.base.DataSetStatic(this, this.action.res_model, this.action.context);
        dataset.name_search('', [], 'ilike',false ,function(result){
            self.$element.html(QWeb.render("ListView", {'records' : result}));
            self.$element.find("a#list-id").click(self.on_list_click);
            $.mobile.changePage($("#oe_list"), "slide", true, true);
        });
    },
    on_list_click: function(ev) {
        $record = $(ev.currentTarget);
        var self = this;
        id = $record.data('id');
        this.header = new openerp.web_mobile.Header(this, "oe_header");
        this.formview = new openerp.web_mobile.FormView(this, "oe_form", id, this.action);
        this.header.start();
        this.formview.start();
    }
 });
}<commit_msg>[FIX] Minor change to close header on formview<commit_after>/*---------------------------------------------------------
 * OpenERP Web Mobile List View
 *---------------------------------------------------------*/

openerp.web_mobile.list_mobile = function (openerp) {

openerp.web_mobile.ListView = openerp.base.Widget.extend({
    init: function(session, element_id, list_id) {
        this._super(session, element_id);
        this.list_id = list_id;
    },
    start: function() {
        this.rpc('/base/menu/action', {'menu_id': this.list_id},
                    this.on_menu_action_loaded);
    },
    on_menu_action_loaded: function(data) {
        var self = this;
        if (data.action.length) {
            this.action = data.action[0][2];
            this.on_search_data();
        }
    },
    on_search_data: function(ev){
        var self = this;
        var dataset = new openerp.base.DataSetStatic(this, this.action.res_model, this.action.context);
        dataset.name_search('', [], 'ilike',false ,function(result){
            self.$element.html(QWeb.render("ListView", {'records' : result}));
            self.$element.find("a#list-id").click(self.on_list_click);
            $.mobile.changePage($("#oe_list"), "slide", true, true);
        });
    },
    on_list_click: function(ev) {
        $record = $(ev.currentTarget);
        var self = this;
        id = $record.data('id');
//        this.header = new openerp.web_mobile.Header(this, "oe_header");
        this.formview = new openerp.web_mobile.FormView(this, "oe_form", id, this.action);
//        this.header.start();
        this.formview.start();
    }
 });
}<|endoftext|>


<commit_before>{
  bodyStyle     : 'padding:5px 5px 0',
  autoScroll    : true,
  fieldDefaults : { labelWidth : 150 },

  defaults       : {
    anchor       : '-20', // to leave some space for the scrollbar
  },

  initComponent: function(){
    // passing config options to BasicForm is possible via initialConfig only
    // see Ext.form.Panel documentation
    this.initialConfig = {
      // form tracks it's default field values so they can be reset()
      trackResetOnLoad: true,
    }

    if (!this.bbar && !this.readOnly) this.bbar = {xtype: 'toolbar'}; // an empty bbar by default, so that we can dynamically add buttons

    // Custom error reader. We don't use it to process form values, but rather to normalize the response from the server in case of "real" (iframe) form submit.
    ErrorReader = function(){};

    ErrorReader.prototype.read = function(xhr) {
      var unescapeHTML = function(str) {
        return str.replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');
      }
      xhr.responseText = unescapeHTML(xhr.responseText.replace(/
/, "").replace("
", ""));
      return {records: [], success: true};
    };

    this.initialConfig.errorReader = new ErrorReader();

    // Now let Ext.form.Form do the rest
    this.callParent(arguments);

    // To inform the parent about the apply event
    this.addEvents('apply', 'cancel');

    if (this.applyOnReturn) {
      Ext.each(this.query('field'), function(field) {
        field.on('specialkey', function(field, event) {
          if (event.getKey() == 13) this.up('form').onApply();
        });
      });
    }
  },

  afterRender: function(){
    this.callParent();

    // have a record to be displayed?
    if (this.record) { this.setFormValues(this.record); }

    // render in display mode?
    if (this.locked || this.readOnly) this.setReadonlyMode(true);
  },

  onEdit: function(){
    this.setReadonlyMode(false);
  },

  onCancel: function(){
    this.getForm().reset();
    this.setReadonlyMode(true, true);
  },

  updateToolbar: function(){
    var tbar = this.child('toolbar');

    if ( this.inReadonlyMode ) {
      //   if the form in readonly mode, remove "Apply" and "Cancel"
      //   buttons from toolbar and add "Edit" button
      var buttonToRemove = tbar.child("button[name='apply']");
      if ( buttonToRemove ) {
        tbar.remove( buttonToRemove );
      }

      var buttonToRemove = tbar.child("button[name='cancel']");
      if ( buttonToRemove ) {
        tbar.remove( buttonToRemove );
      }

      tbar.add( this.actions.edit );

    } else {
      // if the form editable, remove "edit" button and
      // insert "apply" and "cancel" instead

      var buttonIndex = tbar.items.findIndex("name", "edit");
      var buttonToRemove = tbar.items.getAt(buttonIndex);
      if (buttonToRemove) {
        tbar.remove(buttonToRemove);
      }
      tbar.insert( buttonIndex, this.actions.cancel );
      tbar.insert( buttonIndex, this.actions.apply );
    }

    tbar.doLayout();
  },

  onApply: function() {
    if (this.fireEvent('apply', this)) {
      var values = this.getForm().getValues();
      for (var fieldName in values) {
        var field = this.getForm().findField(fieldName);

        // TODO: move the following checks to the server side (through the :display_only option)

        // do not submit values from disabled fields
        if (!field || field.disabled) {
          delete values[fieldName];
        }

        // do not submit values from read-only association fields
        if (field
          && field.name.indexOf("__") !== -1
          && (field.readOnly || !field.isXType('combobox'))
          && (!field.nestedAttribute) // except for "nested attributes"
        ) {
          delete values[fieldName];
        }

        // do not submit values from displayfields
        if (field.isXType('displayfield')) {
          delete values[fieldName];
        }

        // do not submit displayOnly fields
        if (field.displayOnly) {
          delete values[fieldName];
        }
      }

      // loading mask
      this.setLoading(true);

      // We must use a different approach when the form is multipart, as we can't use the endpoint
      if (this.getForm().hasUpload()) {
        this.getForm().submit({ // normal submit
          url: this.netzkeEndpointUrl("netzke_submit"),
          params: {
            data: Ext.encode(values) // here are the correct values that may be different from display values
          },
          failure: function(form, action){
            var respObj = Ext.decode(action.response.responseText);
            delete respObj.success;
            this.netzkeBulkExecute(respObj);
            this.setLoading(false);
          },
          success: function(form, action) {
            var respObj = Ext.decode(action.response.responseText);
            delete respObj.success;
            this.netzkeBulkExecute(respObj);
          },
          scope: this
        });
      } else {
        this.netzkeSubmit(Ext.apply((this.baseParams || {}), { data:Ext.encode(values) }), function(){ this.setLoading(false); }, this);
      }
    }
    this.fireEvent('afterApply', this);
  },

  // called from the server
  onSubmitSuccess: function() {
    this.fireEvent("submitsuccess");
    if (this.mode == "lockable") this.setReadonlyMode(true);
    this.setLoading(false);
  },

  setFormValues: function(values){
    var assocValues = values.meta.associationValues || {};
    for (var assocFieldName in assocValues) {

      var assocField = this.getForm().getFields().filter('name', assocFieldName).first();
      if (assocField.isXType('combobox')) {
        // HACK: using private property 'store' here!
        assocField.store.loadData([[values[assocFieldName], assocValues[assocFieldName]]]);
        delete assocField.lastQuery; // force loading the store next time user clicks the trigger
      } else {
        assocField.setValue(assocValues[assocFieldName]);
        delete values[assocFieldName]; // we don't want this to be set once more below with setValues()
      }
    }

    this.getForm().setValues(values);
  },

  setReadonlyMode: function(onOff, cancel){
    if (this.inReadonlyMode == onOff) return;
    this.getForm().getFields().each(function(i){
      if (i.setReadonlyMode) i.setReadonlyMode(onOff);
    });

    // this.getForm().cleanDestroyed(); // because fields inside of composite fields are not auto-cleaned!
    this.doLayout();
    this.inReadonlyMode = onOff;
    if (this.mode == "lockable") this.updateToolbar();
  },

  // recursively extract field names
  extractFields: function(items){
    Ext.each(items, function(i){
      if (i.items) {this.extractFields(i.items);}
      else if (i.name) {this.fieldNames.push(i.name);}
    }, this);
  },

  applyFormErrors: function(errors) {
    var field;
    Ext.iterate(errors, function(fieldName, message){
      fieldName = fieldName.underscore();
      if ( field = this.getForm().findField(fieldName) || this.getForm().findField(fieldName.replace(/([a-z]+)([0-9])/g, '$1_$2'))) {
        field.markInvalid(message.join('
'));
      }
    }, this);
  }
}
<commit_msg>More cleanup<commit_after>{
  bodyStyle     : 'padding:5px 5px 0',
  autoScroll    : true,
  fieldDefaults : { labelWidth : 150 },

  defaults       : {
    anchor       : '-20' // to leave some space for the scrollbar
  },

  initComponent: function(){
    // passing config options to BasicForm is possible via initialConfig only
    // see Ext.form.Panel documentation
    this.initialConfig = {
      // form tracks it's default field values so they can be reset()
      trackResetOnLoad: true,
    }

    if (!this.bbar && !this.readOnly) this.bbar = {xtype: 'toolbar'}; // an empty bbar by default, so that we can dynamically add buttons

    // Custom error reader. We don't use it to process form values, but rather to normalize the response from the server in case of "real" (iframe) form submit.
    ErrorReader = function(){};

    ErrorReader.prototype.read = function(xhr) {
      var unescapeHTML = function(str) {
        return str.replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');
      }
      xhr.responseText = unescapeHTML(xhr.responseText.replace(/
/, "").replace("
", ""));
      return {records: [], success: true};
    };

    this.initialConfig.errorReader = new ErrorReader();

    // Now let Ext.form.Form do the rest
    this.callParent(arguments);

    // To inform the parent about the apply event
    this.addEvents('apply', 'cancel');

    if (this.applyOnReturn) {
      Ext.each(this.query('field'), function(field) {
        field.on('specialkey', function(field, event) {
          if (event.getKey() == 13) this.up('form').onApply();
        });
      });
    }
  },

  afterRender: function(){
    this.callParent();

    // have a record to be displayed?
    if (this.record) { this.setFormValues(this.record); }

    // render in display mode?
    if (this.locked || this.readOnly) this.setReadonlyMode(true);
  },

  onEdit: function(){
    this.setReadonlyMode(false);
  },

  onCancel: function(){
    this.getForm().reset();
    this.setReadonlyMode(true, true);
  },

  updateToolbar: function(){
    var tbar = this.child('toolbar');

    if ( this.inReadonlyMode ) {
      //   if the form in readonly mode, remove "Apply" and "Cancel"
      //   buttons from toolbar and add "Edit" button
      var buttonToRemove = tbar.child("button[name='apply']");
      if ( buttonToRemove ) {
        tbar.remove( buttonToRemove );
      }

      var buttonToRemove = tbar.child("button[name='cancel']");
      if ( buttonToRemove ) {
        tbar.remove( buttonToRemove );
      }

      tbar.add( this.actions.edit );

    } else {
      // if the form editable, remove "edit" button and
      // insert "apply" and "cancel" instead

      var buttonIndex = tbar.items.findIndex("name", "edit");
      var buttonToRemove = tbar.items.getAt(buttonIndex);
      if (buttonToRemove) {
        tbar.remove(buttonToRemove);
      }
      tbar.insert( buttonIndex, this.actions.cancel );
      tbar.insert( buttonIndex, this.actions.apply );
    }

    tbar.doLayout();
  },

  onApply: function() {
    if (this.fireEvent('apply', this)) {
      var values = this.getForm().getValues();
      for (var fieldName in values) {
        var field = this.getForm().findField(fieldName);

        // TODO: move the following checks to the server side (through the :display_only option)

        // do not submit values from disabled fields
        if (!field || field.disabled) {
          delete values[fieldName];
        }

        // do not submit values from read-only association fields
        if (field
          && field.name.indexOf("__") !== -1
          && (field.readOnly || !field.isXType('combobox'))
          && (!field.nestedAttribute) // except for "nested attributes"
        ) {
          delete values[fieldName];
        }

        // do not submit values from displayfields
        if (field.isXType('displayfield')) {
          delete values[fieldName];
        }

        // do not submit displayOnly fields
        if (field.displayOnly) {
          delete values[fieldName];
        }
      }

      // loading mask
      this.setLoading(true);

      // We must use a different approach when the form is multipart, as we can't use the endpoint
      if (this.getForm().hasUpload()) {
        this.getForm().submit({ // normal submit
          url: this.netzkeEndpointUrl("netzke_submit"),
          params: {
            data: Ext.encode(values) // here are the correct values that may be different from display values
          },
          failure: function(form, action){
            var respObj = Ext.decode(action.response.responseText);
            delete respObj.success;
            this.netzkeBulkExecute(respObj);
            this.setLoading(false);
          },
          success: function(form, action) {
            var respObj = Ext.decode(action.response.responseText);
            delete respObj.success;
            this.netzkeBulkExecute(respObj);
          },
          scope: this
        });
      } else {
        this.netzkeSubmit(Ext.apply((this.baseParams || {}), { data:Ext.encode(values) }), function(){ this.setLoading(false); }, this);
      }
    }
    this.fireEvent('afterApply', this);
  },

  // called from the server
  onSubmitSuccess: function() {
    this.fireEvent("submitsuccess");
    if (this.mode == "lockable") this.setReadonlyMode(true);
    this.setLoading(false);
  },

  setFormValues: function(values){
    var assocValues = values.meta.associationValues || {};
    for (var assocFieldName in assocValues) {

      var assocField = this.getForm().getFields().filter('name', assocFieldName).first();
      if (assocField.isXType('combobox')) {
        // HACK: using private property 'store' here!
        assocField.store.loadData([[values[assocFieldName], assocValues[assocFieldName]]]);
        delete assocField.lastQuery; // force loading the store next time user clicks the trigger
      } else {
        assocField.setValue(assocValues[assocFieldName]);
        delete values[assocFieldName]; // we don't want this to be set once more below with setValues()
      }
    }

    this.getForm().setValues(values);
  },

  setReadonlyMode: function(onOff, cancel){
    if (this.inReadonlyMode == onOff) return;
    this.getForm().getFields().each(function(i){
      if (i.setReadonlyMode) i.setReadonlyMode(onOff);
    });

    // this.getForm().cleanDestroyed(); // because fields inside of composite fields are not auto-cleaned!
    this.doLayout();
    this.inReadonlyMode = onOff;
    if (this.mode == "lockable") this.updateToolbar();
  },

  // recursively extract field names
  extractFields: function(items){
    Ext.each(items, function(i){
      if (i.items) {this.extractFields(i.items);}
      else if (i.name) {this.fieldNames.push(i.name);}
    }, this);
  },

  applyFormErrors: function(errors) {
    var field;
    Ext.iterate(errors, function(fieldName, message){
      fieldName = fieldName.underscore();
      if ( field = this.getForm().findField(fieldName) || this.getForm().findField(fieldName.replace(/([a-z]+)([0-9])/g, '$1_$2'))) {
        field.markInvalid(message.join('
'));
      }
    }, this);
  }
}
<|endoftext|>


<commit_before>$(function() {

	$(".app-menu").menu();
	$(".app-button").button();
	$(".app-buttonset").buttonset();

	$("table.app-stripe>tbody>tr:even").addClass("app-even");
	$("table.app-stripe>tbody>tr:odd").addClass("app-odd");

	$("table.app-multihead").each(function(index) {
		var $head = $("thead", this);
		var step = $(this).attr("data-multihead");
		step = (step ? step : 10);
		$("tbody tr", this).each(function(index) {
			if (index != 0 && index % step == 0) {
				var $row = $(this);
				$("tr", $head).each(function(index) {
					var $tr = $(this).clone().insertBefore($row);
					$(":checkbox.app-checkall", $tr).each(function(index) {
						if ($(this).hasClass("app-checkall-headonly")) {
							$(this).addClass("app-displaynone");
						}
					});
				});
			}
		});
	});

	$(":checkbox.app-checkall").each(function(index) {
		var selector = $(this).attr("data-selector");
		$(selector).prop("checked", $(this).prop("checked"));
		$(this).change(function(event) {
			$(selector).prop("checked", $(this).prop("checked"));
		});
	});

	$(".pager-link").each(function(index) {
		var form = $(this).attr("data-form");
		var pno = $(this).attr("data-pno");
		var current = $(this).attr("data-current");
		$("li", this).each(function(index) {
			var pageNo = $("a", this).attr("title");
			if (pageNo == current) {
				$("a", this).removeAttr("href");
			} else {
				$("a", this).click(function(event) {
					event.preventDefault();
					$("input[name='" + pno + "']", $(form)).val(pageNo - 1);
					$(form).submit();
				});
			}
		});
	});

	$(".page-size").each(function(index) {
		var form = $("select", this).attr("data-form");
		var psz = $("select", this).attr("data-psz");
		var current = $("input[name='" + psz + "']", $(form)).val();
		$("select", this).val(current);
		$("select", this).selectmenu({
			change : function(event) {
				event.preventDefault();
				$("input[name='" + psz + "']", $(form)).val($(this).val());
				$(form).submit();
			}
		});
	});

	$(".download-button").each(function(index) {
		var form = $("button", this).attr("data-form");
		$("button", this).button().click(function(event) {
			event.preventDefault();
			$(form).append("<input type='hidden' name='download' />");
			$(form).submit();
			$("input[name='download']", $(form)).remove();
		});
	});

	$(".refresh-button").each(function(index) {
		var form = $("button", this).attr("data-form");
		var selector = $("button", this).attr("data-selector");
		$(selector).each(function(index) {
			var name = $(this).attr("name");
			var val = $("input[name='" + name + "']", $(form)).val();
			if ($(this).attr("type") == "radio") {
				$(this).attr("checked", $(this).val() == val);
			} else {
				$(this).val(val);
			}
		});
		$("button", this).button().click(function(event) {
			event.preventDefault();
			$(selector).each(function(index) {
				var name = $(this).attr("name");
				$("input[name='" + name + "']", $(form)).val($(this).val());
			});
			$(form).submit();
		});
	});

	$(".page-sorter").each(function(index) {
		$("select", this).selectmenu();
	});

	var token = $("meta[name='_csrf']").attr("content");
	var header = $("meta[name='_csrf_header']").attr("content");
	$(document).ajaxSend(function(event, jqxhr, settings) {
		jqxhr.setRequestHeader(header, token);
	});

});
<commit_msg>SpringApp * ブロック開閉機能。<commit_after>$(function() {

	$(".app-menu").menu();
	$(".app-button").button();
	$(".app-buttonset").buttonset();

	$(".app-collapsible").each(function(index) {

		$(">.app-block-header", this).addClass("ui-helper-clearfix");
		$(">.app-block-header", this).wrapInner("

");
		$(">.app-block-header", this).append("

");

		var toggleOpenClose = (function($block) {
			var iconO = $block.attr("data-icon-open");
			iconO = (iconO == undefined ? "ui-icon-plus" : iconO);
			var iconC = $block.attr("data-icon-close");
			iconC = (iconC == undefined ? "ui-icon-minus" : iconC);
			return function() {
				if ($block.prop("opened")) {
					$(">.app-block-header>div:last>span", $block).removeClass(iconC).addClass(iconO);
					$(">.app-block-contents", $block).hide();
					$block.prop("opened", false);
				} else {
					$(">.app-block-header>div:last>span", $block).removeClass(iconO).addClass(iconC);
					$(">.app-block-contents", $block).show();
					$block.prop("opened", true);
				}
			};
		})($(this));

		$(this).prop("opened", $(this).attr("data-collapsed") == "true");
		toggleOpenClose();

		$(">.app-block-header>div:last>span", this).click(function(event) {
			toggleOpenClose();
		});
	});

	$("table.app-stripe>tbody>tr:even").addClass("app-even");
	$("table.app-stripe>tbody>tr:odd").addClass("app-odd");

	$("table.app-multihead").each(function(index) {
		var $head = $("thead", this);
		var step = $(this).attr("data-multihead");
		step = (step ? step : 10);
		$("tbody tr", this).each(function(index) {
			if (index != 0 && index % step == 0) {
				var $row = $(this);
				$("tr", $head).each(function(index) {
					var $tr = $(this).clone().insertBefore($row);
					$(":checkbox.app-checkall", $tr).each(function(index) {
						if ($(this).hasClass("app-checkall-headonly")) {
							$(this).addClass("app-displaynone");
						}
					});
				});
			}
		});
	});

	$(":checkbox.app-checkall").each(function(index) {
		var selector = $(this).attr("data-selector");
		$(selector).prop("checked", $(this).prop("checked"));
		$(this).change(function(event) {
			$(selector).prop("checked", $(this).prop("checked"));
		});
	});

	$(".pager-link").each(function(index) {
		var form = $(this).attr("data-form");
		var pno = $(this).attr("data-pno");
		var current = $(this).attr("data-current");
		$("li", this).each(function(index) {
			var pageNo = $("a", this).attr("title");
			if (pageNo == current) {
				$("a", this).removeAttr("href");
			} else {
				$("a", this).click(function(event) {
					event.preventDefault();
					$("input[name='" + pno + "']", $(form)).val(pageNo - 1);
					$(form).submit();
				});
			}
		});
	});

	$(".page-size").each(function(index) {
		var form = $("select", this).attr("data-form");
		var psz = $("select", this).attr("data-psz");
		var current = $("input[name='" + psz + "']", $(form)).val();
		$("select", this).val(current);
		$("select", this).selectmenu({
			change : function(event) {
				event.preventDefault();
				$("input[name='" + psz + "']", $(form)).val($(this).val());
				$(form).submit();
			}
		});
	});

	$(".download-button").each(function(index) {
		var form = $("button", this).attr("data-form");
		$("button", this).button().click(function(event) {
			event.preventDefault();
			$(form).append("<input type='hidden' name='download' />");
			$(form).submit();
			$("input[name='download']", $(form)).remove();
		});
	});

	$(".refresh-button").each(function(index) {
		var form = $("button", this).attr("data-form");
		var selector = $("button", this).attr("data-selector");
		$(selector).each(function(index) {
			var name = $(this).attr("name");
			var val = $("input[name='" + name + "']", $(form)).val();
			if ($(this).attr("type") == "radio") {
				$(this).attr("checked", $(this).val() == val);
			} else {
				$(this).val(val);
			}
		});
		$("button", this).button().click(function(event) {
			event.preventDefault();
			$(selector).each(function(index) {
				var name = $(this).attr("name");
				$("input[name='" + name + "']", $(form)).val($(this).val());
			});
			$(form).submit();
		});
	});

	$(".page-sorter").each(function(index) {
		$("select", this).selectmenu();
	});

	var token = $("meta[name='_csrf']").attr("content");
	var header = $("meta[name='_csrf_header']").attr("content");
	$(document).ajaxSend(function(event, jqxhr, settings) {
		jqxhr.setRequestHeader(header, token);
	});

});
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var assert = require('assert');
var util = require('util');
var _ = require('@sailshq/lodash');
var InMemoryJoin = require('./in-memory-join');
var Joins = require('./joins');

/**
 * runOperations()
 *
 * (aka "operation runner")
 *
 * Run a set of generated operations and then perform an in-memory join if
 * needed. Afterwards, the normalized result set is turned into records.
 *
 * > Used in both `.find()` and `.findOne()` queries.
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 *
 * @param  {Ref}   operations
 *         A special "Operations" instance.
 *
 * @param  {Dictionary}   stageThreeQuery
 *
 * @param  {Ref}   WLModel
 *
 * @param  {Function} cb
 *         @param {Error?} err   [if an error occured]
 *         @param {Array} records
 *
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 */

module.exports = function runOperations(operations, stageThreeQuery, WLModel, cb) {

  assert(operations, 'An "Operations" instance should be provided as the first argument.');
  assert(stageThreeQuery, 'Stage three query (S3Q) should be provided as the 2nd argument');
  assert(WLModel, 'Live Waterline model should be provided as the 3rd argument');
  assert(_.isFunction(cb), '`cb` (4th argument) should be a function');

  //  ╦═╗╦ ╦╔╗╔  ┌─┐┌─┐┌─┐┬─┐┌─┐┌┬┐┬┌─┐┌┐┌┌─┐
  //  ╠╦╝║ ║║║║  │ │├─┘├┤ ├┬┘├─┤ │ ││ ││││└─┐
  //  ╩╚═╚═╝╝╚╝  └─┘┴  └─┘┴└─┴ ┴ ┴ ┴└─┘┘└┘└─┘
  operations.run(function _afterRunningOperations(err, values) {
    if (err) {
      return cb(err);
    }

    // If the values don't have a cache there is nothing to return
    if (!values.cache) {
      return cb();
    }

    (function (proceed){
      try {

        // If no joins are used, grab the only item from the cache and pass that on.
        if (!stageThreeQuery.joins || !stageThreeQuery.joins.length) {
          values = values.cache[WLModel.identity];
          return proceed(undefined, values);
        }//-•

        // Otherwise, if the values are already combined, return the results.
        if (values.combined) {
          return proceed(undefined, values.cache[WLModel.identity]);
        }//-•

        // Otherwise, perform an in-memory join (run the integrator) on the values
        // returned from the operations, and then use that as our joined results.
        var joinedResults;
        try {
          joinedResults = InMemoryJoin(stageThreeQuery, values.cache, WLModel.primaryKey);
        } catch (e) { return proceed(e); }

        return proceed(undefined, joinedResults);

      } catch (e) { return proceed(e); }
    })(function _returnResults(err, results){
      if (err) { return cb(err); }

      //  ╔═╗╦═╗╔═╗╔═╗╔═╗╔═╗╔═╗  ┌─┐┌─┐┌┬┐┌┐ ┬┌┐┌┌─┐┌┬┐  ┬─┐┌─┐┌─┐┬ ┬┬ ┌┬┐┌─┐
      //  ╠═╝╠╦╝║ ║║  ║╣ ╚═╗╚═╗  │  │ ││││├┴┐││││├┤  ││  ├┬┘├┤ └─┐│ ││  │ └─┐
      //  ╩  ╩╚═╚═╝╚═╝╚═╝╚═╝╚═╝  └─┘└─┘┴ ┴└─┘┴┘└┘└─┘─┴┘  ┴└─└─┘└─┘└─┘┴─┘┴ └─┘
      if (!results) {
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // TODO: figure out what's up here.  Is this ever the expected behavior?
        // If not, we should send back an error instead.
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        return cb();
      }

      // Normalize results to an array
      if (!_.isArray(results) && results) {
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // TODO: why is this necessary?  Move check below up to here if possible.
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        results = [results];
      }

      // Transform column names into attribute names for each of the result records
      // before attempting any in-memory join logic on them.
      var transformedRecords = _.map(results, function(result) {
        return WLModel._transformer.unserialize(result);
      });

      // Build `joins` for each of the specified populate instructions.
      // (Turn them into proper records.)
      var joins = stageThreeQuery.joins ? stageThreeQuery.joins : [];
      var data;
      try {
        data = Joins(joins, transformedRecords, WLModel.identity, WLModel.schema, WLModel.waterline.collections);
      } catch (e) {
        return cb(e);
      }

      // If `data` is invalid (not an array) return early to avoid getting into trouble.
      if (!data || !_.isArray(data)) {
        return cb(new Error('Consistency violation: Result from operations runner should be an array, but instead got: '+util.inspect(data, {depth: 5})+''));
      }//-•

      return cb(undefined, data);

    });//</ get results from appropriate source >

  });//</ .run() >
};
<commit_msg>Tweaks to fireworks in operation-runner.<commit_after>/**
 * Module dependencies
 */

var assert = require('assert');
var util = require('util');
var _ = require('@sailshq/lodash');
var InMemoryJoin = require('./in-memory-join');
var Joins = require('./joins');

/**
 * runFindOperations()
 *
 * (ska "operation runner")
 *
 * Run a set of generated "find" operations, and then perform an in-memory
 * join if needed.  Afterwards, the normalized result set is turned into
 * (potentially-populated) records.
 *
 * > Used for `.find()` and `.findOne()` queries.
 *
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 *
 * @param  {Ref}   operations
 *         A special "Operations" instance.
 *
 * @param  {Dictionary}   stageThreeQuery
 *
 * @param  {Ref}   WLModel
 *
 * @param  {Function} cb
 *         @param {Error?} err   [if an error occured]
 *         @param {Array} records
 *
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 */

module.exports = function runFindOperations(operations, stageThreeQuery, WLModel, cb) {

  assert(operations, 'An "Operations" instance should be provided as the first argument.');
  assert(stageThreeQuery, 'Stage three query (S3Q) should be provided as the 2nd argument');
  assert(WLModel, 'Live Waterline model should be provided as the 3rd argument');
  assert(_.isFunction(cb), '`cb` (4th argument) should be a function');

  //  ╦═╗╦ ╦╔╗╔  ┌─┐┌─┐┌─┐┬─┐┌─┐┌┬┐┬┌─┐┌┐┌┌─┐
  //  ╠╦╝║ ║║║║  │ │├─┘├┤ ├┬┘├─┤ │ ││ ││││└─┐
  //  ╩╚═╚═╝╝╚╝  └─┘┴  └─┘┴└─┴ ┴ ┴ ┴└─┘┘└┘└─┘
  operations.run(function _afterRunningOperations(err, values) {
    if (err) {
      return cb(err);
    }

    // If the values don't have a cache there is nothing to return
    if (!values.cache) {
      return cb();
    }

    (function (proceed){
      try {

        // If no joins are used, grab the only item from the cache and pass that on.
        if (!stageThreeQuery.joins || !stageThreeQuery.joins.length) {
          values = values.cache[WLModel.identity];
          return proceed(undefined, values);
        }//-•

        // Otherwise, if the values are already combined, return the results.
        if (values.combined) {
          return proceed(undefined, values.cache[WLModel.identity]);
        }//-•

        // Otherwise, perform an in-memory join (run the integrator) on the values
        // returned from the operations, and then use that as our joined results.
        var joinedResults;
        try {
          joinedResults = InMemoryJoin(stageThreeQuery, values.cache, WLModel.primaryKey);
        } catch (e) { return proceed(e); }

        return proceed(undefined, joinedResults);

      } catch (e) { return proceed(e); }
    })(function _returnResults(err, results){
      if (err) { return cb(err); }

      //  ╔═╗╦═╗╔═╗╔═╗╔═╗╔═╗╔═╗  ┌─┐┌─┐┌┬┐┌┐ ┬┌┐┌┌─┐┌┬┐  ┬─┐┌─┐┌─┐┬ ┬┬ ┌┬┐┌─┐
      //  ╠═╝╠╦╝║ ║║  ║╣ ╚═╗╚═╗  │  │ ││││├┴┐││││├┤  ││  ├┬┘├┤ └─┐│ ││  │ └─┐
      //  ╩  ╩╚═╚═╝╚═╝╚═╝╚═╝╚═╝  └─┘└─┘┴ ┴└─┘┴┘└┘└─┘─┴┘  ┴└─└─┘└─┘└─┘┴─┘┴ └─┘
      if (!results) {
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // TODO: figure out what's up here.  Is this ever the expected behavior?
        // If not, we should send back an error instead.
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        return cb();
      }

      // Normalize results to an array
      if (!_.isArray(results) && results) {
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // TODO: why is this necessary?  Move check below up to here if possible.
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        results = [results];
      }

      // Transform column names into attribute names for each of the result records
      // before attempting any in-memory join logic on them.
      var transformedRecords = _.map(results, function(result) {
        return WLModel._transformer.unserialize(result);
      });

      // Build `joins` for each of the specified populate instructions.
      // (Turn them into proper records.)
      var joins = stageThreeQuery.joins ? stageThreeQuery.joins : [];
      var data;
      try {
        data = Joins(joins, transformedRecords, WLModel.identity, WLModel.schema, WLModel.waterline.collections);
      } catch (e) {
        return cb(e);
      }

      // If `data` is invalid (not an array) return early to avoid getting into trouble.
      if (!data || !_.isArray(data)) {
        return cb(new Error('Consistency violation: Result from operations runner should be an array, but instead got: '+util.inspect(data, {depth: 5})+''));
      }//-•

      return cb(undefined, data);

    });//</ get results from appropriate source >

  });//</ .run() >
};
<|endoftext|>


<commit_before>'use strict';

var Actions = require('../constants/Actions');
var Promise = require('q');
var NotificationActions = require('./NotificationActions');
var NavigationActions = require('./NavigationActions');
var authStorage = require('../services/auth-storage');
var HairfieActions = require('./HairfieActions');
var _ = require('lodash');

var _mustBeConnected = function(context) {
    return Promise.all([
        context.executeAction(
            NotificationActions.notifyFailure,
            "Vous devez vous connecter pour exécuter cette action"
        ),
        context.executeAction(
            NavigationActions.navigate,
            { route: 'connect_page' }
        )
    ]);
};

module.exports = {
    userConnect: function(context, token) {
        return context.hairfieApi
            .get('/users/' + token.userId, { query: { access_token: token.id }})
            .then(function (userInfo) {
                return Promise.all ([
                    authStorage.setToken(context, token),
                    context.dispatch(Actions.RECEIVE_TOKEN, token),
                    context.dispatch(Actions.RECEIVE_USER_INFO, userInfo)
                ]);
            }, function () {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu, veuillez vous reconnecter"
                );
            })
    },
    editUser: function(context, payload) {
        var token = payload.token;
        delete payload.token;
        return context.hairfieApi
            .put('/users/' + token.userId, payload, { query: { access_token: token.id }})
            .then(function (data) {
                console.log(data);
            })
    },
    getUserById: function(context, id) {
        return context.hairfieApi
            .get('/users/' + id)
            .then(function (userInfo) {
                return Promise.all ([
                    context.dispatch(Actions.RECEIVE_USER_INFO, userInfo)
                ]);
            }, function () {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu, veuillez vous reconnecter"
                );
            })
    },
    getUserHairfies: function (context, id) {
        var query = {
        'filter[where][authorId]': id,
        'filter[order]': 'createdAt DESC',
        'filter[limit]': 12
        };
        return context.hairfieApi
            .get('/hairfies', { query: query })
            .then(function (hairfies) {
                Promise.all([
                    context.dispatch(Actions.RECEIVE_USER_HAIRFIES, {userId: id, hairfies: hairfies})
                ]);
            }, function () {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu"
                );
            });
    },
    getUserLikes: function (context, id) {
        var query = {
        'limit': 12,
        'userId': id
        };
        return context.hairfieApi
            .get('/users/' + id + '/liked-hairfies', { query: query })
            .then(function (hairfies) {
                Promise.all([
                    context.dispatch(Actions.RECEIVE_USER_LIKES, {userId: id, hairfies: hairfies})
                ]);
            }, function () {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu"
                );
            });
    },
    getUserReviews: function (context, id) {
        var query = {
        'filter[where][authorId]': id,
        'filter[order]': 'createdAt DESC'
        };
        return context.hairfieApi
            .get('/businessReviews', { query: query })
            .then(function (reviews) {
                Promise.all([
                    context.dispatch(Actions.RECEIVE_USER_REVIEWS, {userId: id, reviews: reviews})
                ]);
            }, function () {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu"
                );
            });
    },
    hairfieLike: function(context, payload) {
        var token = context.getStore('AuthStore').getToken();
        if (!token || !token.userId) {
            _mustBeConnected(context);
            return;
        }
        return context.hairfieApi
            .put('/users/' + token.userId + '/liked-hairfies/' + payload.id, {hairfieId: payload.id})
            .then (function () {
                return Promise.all([
                        context.executeAction(HairfieActions.loadHairfie, payload.id),
                        context.dispatch('RECEIVE_USER_LIKE_HAIRFIE', {userId:token.userId, hairfie: payload, isLiked: true})
                        ]);
            }, function() {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu"
                );
            })
    },
    hairfieUnlike: function(context, payload) {
        var token = context.getStore('AuthStore').getToken();
        if (!token || !token.userId) {
            _mustBeConnected(context);
            return;
        }
        return context.hairfieApi
            .delete('/users/' + token.userId + '/liked-hairfies/' + payload.id, {hairfieId: payload.id})
            .then (function () {
                return Promise.all([
                        context.executeAction(HairfieActions.loadHairfie, payload.id),
                        context.dispatch('RECEIVE_USER_LIKE_HAIRFIE', {userId:token.userId, hairfie: payload, isLiked: false})
                        ]);
            }, function() {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu"
                );
            })
    },
    isLikedHairfie: function(context, payload) {
        var token = context.getStore('AuthStore').getToken();
        if (!token || !token.userId)
            return;
        return context.hairfieApi
            .head('/users/' + token.userId + '/liked-hairfies/' + payload.id, {haifieId: payload.id })
            .then(function () {
                return true;
            })
            .catch(function (e) {
                if (e.status == 404) {
                    return false;
                }
            })
            .then(function(isLiked) {
                return context.dispatch('RECEIVE_USER_LIKE_HAIRFIE', {userId:token.userId, hairfie: payload, isLiked: isLiked});
            })
    }
};<commit_msg>Fix EditUser<commit_after>'use strict';

var Actions = require('../constants/Actions');
var Promise = require('q');
var NotificationActions = require('./NotificationActions');
var NavigationActions = require('./NavigationActions');
var authStorage = require('../services/auth-storage');
var HairfieActions = require('./HairfieActions');
var _ = require('lodash');

var _mustBeConnected = function(context) {
    return Promise.all([
        context.executeAction(
            NotificationActions.notifyFailure,
            "Vous devez vous connecter pour exécuter cette action"
        ),
        context.executeAction(
            NavigationActions.navigate,
            { route: 'connect_page' }
        )
    ]);
};

module.exports = {
    userConnect: function(context, token) {
        return context.hairfieApi
            .get('/users/' + token.userId, { query: { access_token: token.id }})
            .then(function (userInfo) {
                return Promise.all ([
                    authStorage.setToken(context, token),
                    context.dispatch(Actions.RECEIVE_TOKEN, token),
                    context.dispatch(Actions.RECEIVE_USER_INFO, userInfo)
                ]);
            }, function () {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu, veuillez vous reconnecter"
                );
            })
    },
    editUser: function(context, payload) {
        var token = payload.token;
        delete payload.token;
        return context.hairfieApi
            .put('/users/' + token.userId, payload, { query: { access_token: token.id }})
            .then(function (data) {
                context.executeAction(NotificationActions.notifySuccess, "Vos informations ont bien été éditée");
            }, function() {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu, veuillez vous reconnecter"
                );
            })
    },
    getUserById: function(context, id) {
        return context.hairfieApi
            .get('/users/' + id)
            .then(function (userInfo) {
                return Promise.all ([
                    context.dispatch(Actions.RECEIVE_USER_INFO, userInfo)
                ]);
            }, function () {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu, veuillez vous reconnecter"
                );
            })
    },
    getUserHairfies: function (context, id) {
        var query = {
        'filter[where][authorId]': id,
        'filter[order]': 'createdAt DESC',
        'filter[limit]': 12
        };
        return context.hairfieApi
            .get('/hairfies', { query: query })
            .then(function (hairfies) {
                Promise.all([
                    context.dispatch(Actions.RECEIVE_USER_HAIRFIES, {userId: id, hairfies: hairfies})
                ]);
            }, function () {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu"
                );
            });
    },
    getUserLikes: function (context, id) {
        var query = {
        'limit': 12,
        'userId': id
        };
        return context.hairfieApi
            .get('/users/' + id + '/liked-hairfies', { query: query })
            .then(function (hairfies) {
                Promise.all([
                    context.dispatch(Actions.RECEIVE_USER_LIKES, {userId: id, hairfies: hairfies})
                ]);
            }, function () {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu"
                );
            });
    },
    getUserReviews: function (context, id) {
        var query = {
        'filter[where][authorId]': id,
        'filter[order]': 'createdAt DESC'
        };
        return context.hairfieApi
            .get('/businessReviews', { query: query })
            .then(function (reviews) {
                Promise.all([
                    context.dispatch(Actions.RECEIVE_USER_REVIEWS, {userId: id, reviews: reviews})
                ]);
            }, function () {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu"
                );
            });
    },
    hairfieLike: function(context, payload) {
        var token = context.getStore('AuthStore').getToken();
        if (!token || !token.userId) {
            _mustBeConnected(context);
            return;
        }
        return context.hairfieApi
            .put('/users/' + token.userId + '/liked-hairfies/' + payload.id, {hairfieId: payload.id})
            .then (function () {
                return Promise.all([
                        context.executeAction(HairfieActions.loadHairfie, payload.id),
                        context.dispatch('RECEIVE_USER_LIKE_HAIRFIE', {userId:token.userId, hairfie: payload, isLiked: true})
                        ]);
            }, function() {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu"
                );
            })
    },
    hairfieUnlike: function(context, payload) {
        var token = context.getStore('AuthStore').getToken();
        if (!token || !token.userId) {
            _mustBeConnected(context);
            return;
        }
        return context.hairfieApi
            .delete('/users/' + token.userId + '/liked-hairfies/' + payload.id, {hairfieId: payload.id})
            .then (function () {
                return Promise.all([
                        context.executeAction(HairfieActions.loadHairfie, payload.id),
                        context.dispatch('RECEIVE_USER_LIKE_HAIRFIE', {userId:token.userId, hairfie: payload, isLiked: false})
                        ]);
            }, function() {
                return context.executeAction(
                    NotificationActions.notifyFailure,
                    "Un problème est survenu"
                );
            })
    },
    isLikedHairfie: function(context, payload) {
        var token = context.getStore('AuthStore').getToken();
        if (!token || !token.userId)
            return;
        return context.hairfieApi
            .head('/users/' + token.userId + '/liked-hairfies/' + payload.id, {haifieId: payload.id })
            .then(function () {
                return true;
            })
            .catch(function (e) {
                if (e.status == 404) {
                    return false;
                }
            })
            .then(function(isLiked) {
                return context.dispatch('RECEIVE_USER_LIKE_HAIRFIE', {userId:token.userId, hairfie: payload, isLiked: isLiked});
            })
    }
};<|endoftext|>