<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  name: 'TwoPaneView',
  package: 'foam.ui.md',

  extendsModel: 'foam.ui.View',

  properties: [
    {
      model_: 'ArrayProperty',
      name: 'views',
      subType: 'foam.ui.ViewChoice',
      help: 'View choices.'
    },
    {
      name: 'choice',
      postSet: function(_, v) {
        this.view = v.view;
      },
      hidden: true
    },
    {
      model_: 'ViewFactoryProperty',
      name: 'view',
      defaultValue: 'foam.ui.View',
      postSet: function(old, v) {
        if ( ! this.$ ) return;
        this.removeAllChildren();
        var view = this.view();
        view.data = this.data;
        this.addChild(view);
        this.viewContainer.innerHTML = view.toHTML();
        view.initHTML();
      },
      hidden: true
    },
    {
      model_: 'foam.core.types.DOMElementProperty',
      name: 'viewContainer'
    },
    {
      name: 'className',
      defaultValue: 'twopane-container'
    },
  ],

  methods: {
    init: function() {
      this.SUPER();
    }
  },

  templates: [
    function CSS() {/*
      .twopane-container {
        display: flex;
        background-color: #EEEEEE;
      }
      .twopane-left {
        width: 200px;
      }
      .twopane-right {
        flex-grow: 1;
      }
      .twopane-left-item-selected {
        color: #00A7F2;
      }
      .twopane-left-item {
        padding: 20px;
        cursor: pointer;
        -webkit-user-select: none;
      }
      .twopane-left-item:hover {
        color: #00A7F2;
      }
    */},
    function choiceButton(_, i, length, choice) {/*
      <%
        var id = this.on('click', function() { self.choice = choice; });
        this.setClass('twopane-left-item-selected', function() { return self.choice === choice; }, id);
      %>
      <div id="<%= id %>" class="twopane-left-item"><%= choice.label %>

    */},
    function toHTML() {/*
      <div id="%%id" <%= this.cssClassAttr() %>>

          <% for ( var i = 0, choice; choice = this.views[i]; i++ ) {
               this.choiceButton(out, i, this.views.length, choice);
           } %>

        <div class="twopane-right" id="<%= this.viewContainer = this.nextID() %>"><%= this.view({ data$: this.data$ }) %>

    */}
  ]
});
<commit_msg>Make the choice property of the TwoPaneView an int so it's easier to make a memento from, default the choice to the first view in the list of views, and remove the viewContainer because it's not necessary.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  name: 'TwoPaneView',
  package: 'foam.ui.md',

  extendsModel: 'foam.ui.View',

  properties: [
    {
      model_: 'ArrayProperty',
      name: 'views',
      subType: 'foam.ui.ViewChoice',
      help: 'View choices.',
      postSet: function() { this.choice = this.choice; }
    },
    {
      model_: 'IntProperty',
      name: 'choice',
      memorable: true,
      preSet: function(_, c) {
        return Math.max(0, Math.min(c, this.views.length));
      },
      postSet: function(_, c) {
        if ( this.views.length ) {
          this.view = this.views[c].view();
          this.view.data = this.data;
        }
      }
    },
    {
      name: 'view',
      memorable: true,
      postSet: function(_, _) {
        if ( ! this.$ ) return;
        this.destroy();
        this.$.outerHTML = this.toHTML();
        this.initHTML();
      },
      hidden: true
    },
    {
      name: 'className',
      defaultValue: 'twopane-container'
    },
  ],

  templates: [
    function CSS() {/*
      .twopane-container {
        display: flex;
        background-color: #EEEEEE;
      }
      .twopane-left {
        width: 200px;
      }
      .twopane-right {
        flex-grow: 1;
      }
      .twopane-left-item-selected {
        color: #00A7F2;
      }
      .twopane-left-item {
        padding: 20px;
        cursor: pointer;
        -webkit-user-select: none;
      }
      .twopane-left-item:hover {
        color: #00A7F2;
      }
    */},
    function choiceButton(_, i, length, choice) {/*
      <%
        var id = this.on('click', function() { self.choice = i; });
        this.setClass('twopane-left-item-selected', function() { return self.choice == i; }, id);
      %>
      <div id="<%= id %>" class="twopane-left-item"><%= choice.label %>

    */},
    function toHTML() {/*
      <div id="%%id" <%= this.cssClassAttr() %>>

          <% for ( var i = 0, choice; choice = this.views[i]; i++ ) {
               this.choiceButton(out, i, this.views.length, choice);
           } %>

<%= this.view %>

    */}
  ]
});
<|endoftext|>


<commit_before>import React from 'react';
import { interpolate } from 'd3-interpolate';
import * as Easing from 'd3-ease';

class Motion extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.move = this.move.bind(this);
        this.state = {items: []};
    }
    componentWillReceiveProps() {
        if (!this.moveId)
            this.moveId = requestAnimationFrame(this.move);
    }
    componentDidMount() {
        this.moveId = requestAnimationFrame(this.move)
    }
    componentWillUnmount() {
        cancelAnimationFrame(this.moveId);
    }
    move() {
        this.setState(({items: prevItems}) => {
            var {data, enter, leave, update, getKey, onRest} = this.props;
            var tick = performance.now();
            var newItem = {progress: 0, tick, rest: false};
            var dataByKey = data.reduce((acc, item) => ({...acc, [getKey(item)]: item}), {});
            var itemsByKey = prevItems.reduce((acc, item) => ({...acc, [item.key]: item}), {});
            var items = prevItems
                .map(item => {
                    var end = !dataByKey[item.key] ? leave(item.data) : update(dataByKey[item.key]);
                    var equal = this.areEqual(item.end, end);
                    var rest = equal && item.progress === 1;
                    var progress = equal ? Math.min(item.progress + ((tick - item.tick) / 500), 1) : 0;
                    var interpolators = (equal && item.interpolators) || this.getInterpolators(item.style, end);
                    var style = this.interpolateStyle(interpolators, end, progress);
                    if (onRest && rest && !item.rest) {
                        onRest(item.data, item.key);
                    }
                    return {...item, style, end, interpolators, progress, tick, rest};
                })
                .filter(item => !item.rest || dataByKey[item.key])
                .concat(data
                    .filter(item => !itemsByKey[getKey(item)])
                    .map(item => ({...newItem, key: getKey(item), data: item, style: enter(item), end: update(item)}))
                );
            this.moveId = null;
            if (items.filter(({rest}) => !rest).length !== 0)
                this.moveId = requestAnimationFrame(this.move);
            return {items};
        })
    }
    areEqual(from, to) {
        if (Object.keys(from).length !== Object.keys(to).length)
            return false;
        for(var key in from) {
            if (from[key] !== to[key])
                return false;
        }
        return true;
    }
    getInterpolators(start, end) {
        var interpolators = {};
        for(var key in start)
            interpolators[key] = interpolate(start[key], end[key]);
        return interpolators;
    }
    interpolateStyle(interpolators, end, progress) {
        var style = {};
        for(var key in end)
            style[key] = interpolators[key](Easing.easeLinear(progress))
        return style;
    }
    render() {
        return this.props.children(this.state.items);
    }
}

export default Motion;
<commit_msg>Detected reverse and set move progress<commit_after>import React from 'react';
import { interpolate } from 'd3-interpolate';
import * as Easing from 'd3-ease';

class Motion extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.move = this.move.bind(this);
        this.state = {items: []};
    }
    componentWillReceiveProps() {
        if (!this.moveId)
            this.moveId = requestAnimationFrame(this.move);
    }
    componentDidMount() {
        this.moveId = requestAnimationFrame(this.move)
    }
    componentWillUnmount() {
        cancelAnimationFrame(this.moveId);
    }
    move() {
        this.setState(({items: prevItems}) => {
            var {data, enter, leave, update, getKey, onRest} = this.props;
            var tick = performance.now();
            var newItem = {progress: 0, tick, rest: false};
            var dataByKey = data.reduce((acc, item) => ({...acc, [getKey(item)]: item}), {});
            var itemsByKey = prevItems.reduce((acc, item) => ({...acc, [item.key]: item}), {});
            var items = prevItems
                .map(item => {
                    var end = !dataByKey[item.key] ? leave(item.data) : update(dataByKey[item.key]);
                    var equal = this.areEqual(item.end, end);
                    var reverse = this.areEqual(item.start, end);
                    var rest = equal && item.progress === 1;
                    var start = equal ? item.start : (reverse ? item.end : item.style);
                    var progress = equal ? Math.min(item.progress + ((tick - item.tick) / 5000), 1) : (reverse ? 1 - item.progress : 0);
                    var interpolators = (equal && item.interpolators) || this.getInterpolators(start, end);
                    var style = this.interpolateStyle(interpolators, end, progress);
                    if (onRest && rest && !item.rest) {
                        onRest(item);
                    }
                    return {...item, start, style, end, interpolators, progress, tick, rest};
                })
                .filter(item => !item.rest || dataByKey[item.key])
                .concat(data
                    .filter(item => !itemsByKey[getKey(item)])
                    .map(item => ({...newItem, key: getKey(item), data: item, start: enter(item), style: enter(item), end: update(item)}))
                );
            this.moveId = null;
            if (items.filter(({rest}) => !rest).length !== 0)
                this.moveId = requestAnimationFrame(this.move);
            return {items};
        })
    }
    areEqual(from, to) {
        if (Object.keys(from).length !== Object.keys(to).length)
            return false;
        for(var key in from) {
            if (from[key] !== to[key])
                return false;
        }
        return true;
    }
    getInterpolators(start, end) {
        var interpolators = {};
        for(var key in start)
            interpolators[key] = interpolate(start[key], end[key]);
        return interpolators;
    }
    interpolateStyle(interpolators, end, progress) {
        var style = {};
        for(var key in end)
            style[key] = interpolators[key](Easing.easeLinear(progress))
        return style;
    }
    render() {
        return this.props.children(this.state.items);
    }
}

export default Motion;
<|endoftext|>


<commit_before>odoo.define('pos_adyen.payment', function (require) {
"use strict";

var core = require('web.core');
var rpc = require('web.rpc');
var PaymentInterface = require('point_of_sale.PaymentInterface');

var _t = core._t;

var PaymentAdyen = PaymentInterface.extend({
    send_payment_request: function (cid) {
        this._super.apply(this, arguments);
        this._reset_state();
        return this._adyen_pay();
    },
    send_payment_cancel: function (order, cid) {
        this._super.apply(this, arguments);
        // set only if we are polling
        this.was_cancelled = !!this.polling;
        return this._adyen_cancel();
    },
    close: function () {
        this._super.apply(this, arguments);
    },

    // private methods
    _reset_state: function () {
        this.was_cancelled = false;
        this.last_diagnosis_service_id = false;
        this.remaining_polls = 2;
        clearTimeout(this.polling);
    },

    _handle_odoo_connection_failure: function (data) {
        // handle timeout
        var line = this.pos.get_order().selected_paymentline;
        if (line) {
            line.set_payment_status('retry');
        }
        this._show_error(_('Could not connect to the Odoo server, please check your internet connection and try again.'));

        return Promise.reject(data); // prevent subsequent onFullFilled's from being called
    },

    _call_adyen: function (data) {
        var self = this;
        return rpc.query({
            model: 'pos.payment.method',
            method: 'proxy_adyen_request',
            args: [data, this.payment_method.adyen_test_mode, this.payment_method.adyen_api_key],
        }, {
            // When a payment terminal is disconnected it takes Adyen
            // a while to return an error (~6s). So wait 10 seconds
            // before concluding Odoo is unreachable.
            timeout: 10000,
            shadow: true,
        }).catch(this._handle_odoo_connection_failure.bind(this));
    },

    _adyen_get_sale_id: function () {
        var config = this.pos.config;
        return _.str.sprintf('%s (ID: %s)', config.display_name, config.id);
    },

    _adyen_common_message_header: function () {
        var config = this.pos.config;
        this.most_recent_service_id = Math.floor(Math.random() * Math.pow(2, 64)).toString(); // random ID to identify request/response pairs
        this.most_recent_service_id = this.most_recent_service_id.substring(0, 10); // max length is 10

        return {
            'ProtocolVersion': '3.0',
            'MessageClass': 'Service',
            'MessageType': 'Request',
            'SaleID': this._adyen_get_sale_id(config),
            'ServiceID': this.most_recent_service_id,
            'POIID': this.payment_method.adyen_terminal_identifier
        };
    },

    _adyen_pay_data: function () {
        var order = this.pos.get_order();
        var config = this.pos.config;
        var line = order.selected_paymentline;
        var data = {
            'SaleToPOIRequest': {
                'MessageHeader': _.extend(this._adyen_common_message_header(), {
                    'MessageCategory': 'Payment',
                }),
                'PaymentRequest': {
                    'SaleData': {
                        'SaleTransactionID': {
                            'TransactionID': order.uid,
                            'TimeStamp': moment().format(), // iso format: '2018-01-10T11:30:15+00:00'
                        }
                    },
                    'PaymentTransaction': {
                        'AmountsReq': {
                            'Currency': this.pos.currency.name,
                            'RequestedAmount': line.amount,
                        }
                    }
                }
            }
        };

        if (config.adyen_ask_customer_for_tip) {
            data.SaleToPOIRequest.PaymentRequest.SaleData.SaleToAcquirerData = "tenderOption=AskGratuity";
        }

        return data;
    },

    _adyen_pay: function () {
        var self = this;
        var data = this._adyen_pay_data();

        return this._call_adyen(data).then(function (data) {
            return self._adyen_handle_response(data);
        });
    },

    _adyen_cancel: function (ignore_error) {
        var previous_service_id = this.most_recent_service_id;
        var header = _.extend(this._adyen_common_message_header(), {
            'MessageCategory': 'Abort',
        });

        var data = {
            'SaleToPOIRequest': {
                'MessageHeader': header,
                'AbortRequest': {
                    'AbortReason': 'MerchantAbort',
                    'MessageReference': {
                        'MessageCategory': 'Payment',
                        'SaleID': header.SaleID,
                        'ServiceID': previous_service_id,
                    }
                },
            }
        };

        return this._call_adyen(data).then(function (data) {

            // Only valid response is a 200 OK HTTP response which is
            // represented by true.
            if (! ignore_error && data !== true) {
                self._show_error(_('Cancelling the payment failed. Please cancel it manually on the payment terminal.'));
            }
        });
    },

    _convert_receipt_info: function (output_text) {
        return output_text.reduce(function (acc, entry) {
            var params = new URLSearchParams(entry.Text);

            if (params.get('name') && !params.get('value')) {
                return acc + _.str.sprintf('
%s', params.get('name'));
            } else if (params.get('name') && params.get('value')) {
                return acc + _.str.sprintf('
%s: %s', params.get('name'), params.get('value'));
            }

            return acc;
        }, '');
    },

    _poll_for_response: function (resolve, reject) {
        var self = this;
        if (this.was_cancelled) {
            resolve(false);
            return Promise.resolve();
        }

        return rpc.query({
            model: 'pos.payment.method',
            method: 'get_latest_adyen_status',
            args: [this.payment_method.id,
                   this._adyen_get_sale_id(),
                   this.payment_method.adyen_terminal_identifier,
                   this.payment_method.adyen_test_mode,
                   this.payment_method.adyen_api_key],
        }, {
            timeout: 5000,
            shadow: true,
        }).catch(function (data) {
            reject();
            return self._handle_odoo_connection_failure(data);
        }).then(function (status) {
            var notification = status.latest_response;
            var last_diagnosis_service_id = status.last_received_diagnosis_id;
            var order = self.pos.get_order();
            var line = order.selected_paymentline;

            if (self.last_diagnosis_service_id != last_diagnosis_service_id) {
                self.last_diagnosis_service_id = last_diagnosis_service_id;
                self.remaining_polls = 2;
            } else {
                self.remaining_polls--;
            }

            if (notification && notification.SaleToPOIResponse.MessageHeader.ServiceID == self.most_recent_service_id) {
                var response = notification.SaleToPOIResponse.PaymentResponse.Response;
                var additional_response = new URLSearchParams(response.AdditionalResponse);

                if (response.Result == 'Success') {
                    var config = self.pos.config;
                    var payment_response = notification.SaleToPOIResponse.PaymentResponse;
                    var payment_result = payment_response.PaymentResult;
                    var customer_receipt = payment_response.PaymentReceipt.find(function (receipt) {
                        return receipt.DocumentQualifier == 'CustomerReceipt';
                    });

                    if (customer_receipt) {
                        line.set_receipt_info(self._convert_receipt_info(customer_receipt.OutputContent.OutputText));
                    }

                    var tip_amount = payment_result.AmountsResp.TipAmount;
                    if (config.adyen_ask_customer_for_tip && tip_amount > 0) {
                        order.set_tip(tip_amount);
                        line.set_amount(payment_result.AmountsResp.AuthorizedAmount);
                    }

                    line.transaction_id = additional_response.get('pspReference');
                    line.card_type = additional_response.get('cardType');
                    resolve(true);
                } else {
                    var message = additional_response.get('message');
                    self._show_error(_.str.sprintf(_t('Message from Adyen: %s'), message));

                    // this means the transaction was cancelled by pressing the cancel button on the device
                    if (message.startsWith('108 ')) {
                        resolve(false);
                    } else {
                        line.set_payment_status('force_done');
                        reject();
                    }
                }
            } else if (self.remaining_polls <= 0) {
                self._show_error(_t('The connection to your payment terminal failed. Please check if it is still connected to the internet.'));
                self._adyen_cancel();
                resolve(false);
            }
        });
    },

    _adyen_handle_response: function (response) {
        var line = this.pos.get_order().selected_paymentline;

        if (response.error && response.error.status_code == 401) {
            this._show_error(_t('Authentication failed. Please check your Adyen credentials.'));
            line.set_payment_status('force_done');
            return Promise.resolve();
        }

        response = response.SaleToPOIRequest;
        if (response && response.EventNotification && response.EventNotification.EventToNotify == 'Reject') {
            console.error('error from Adyen', response);

            var msg = '';
            if (response.EventNotification) {
                var params = new URLSearchParams(response.EventNotification.EventDetails);
                msg = params.get('message');
            }

            this._show_error(_.str.sprintf(_t('An unexpected error occured. Message from Adyen: %s'), msg));
            if (line) {
                line.set_payment_status('force_done');
            }

            return Promise.resolve();
        } else {
            line.set_payment_status('waitingCard');

            // This is not great, the payment screen should be
            // refactored so it calls render_paymentlines whenever a
            // paymentline changes. This way the call to
            // set_payment_status would re-render it automatically.
            this.pos.chrome.gui.current_screen.render_paymentlines();

            var self = this;
            var res = new Promise(function (resolve, reject) {
                // clear previous intervals just in case, otherwise
                // it'll run forever
                clearTimeout(self.polling);

                self.polling = setInterval(function () {
                    self._poll_for_response(resolve, reject);
                }, 3000);
            });

            // make sure to stop polling when we're done
            res.finally(function () {
                self._reset_state();
            });

            return res;
        }
    },

    _show_error: function (msg, title) {
        if (!title) {
            title =  _t('Adyen Error');
        }
        this.pos.gui.show_popup('error',{
            'title': title,
            'body': msg,
        });
    },
});

return PaymentAdyen;
});
<commit_msg>[REF] pos_adyen: migration to OWL framework<commit_after>odoo.define('pos_adyen.payment', function (require) {
"use strict";

var core = require('web.core');
var rpc = require('web.rpc');
var PaymentInterface = require('point_of_sale.PaymentInterface');
const { Gui } = require('point_of_sale.Gui');

var _t = core._t;

var PaymentAdyen = PaymentInterface.extend({
    send_payment_request: function (cid) {
        this._super.apply(this, arguments);
        this._reset_state();
        return this._adyen_pay();
    },
    send_payment_cancel: function (order, cid) {
        this._super.apply(this, arguments);
        // set only if we are polling
        this.was_cancelled = !!this.polling;
        return this._adyen_cancel();
    },
    close: function () {
        this._super.apply(this, arguments);
    },

    // private methods
    _reset_state: function () {
        this.was_cancelled = false;
        this.last_diagnosis_service_id = false;
        this.remaining_polls = 2;
        clearTimeout(this.polling);
    },

    _handle_odoo_connection_failure: function (data) {
        // handle timeout
        var line = this.pos.get_order().selected_paymentline;
        if (line) {
            line.set_payment_status('retry');
        }
        this._show_error(_('Could not connect to the Odoo server, please check your internet connection and try again.'));

        return Promise.reject(data); // prevent subsequent onFullFilled's from being called
    },

    _call_adyen: function (data) {
        var self = this;
        return rpc.query({
            model: 'pos.payment.method',
            method: 'proxy_adyen_request',
            args: [data, this.payment_method.adyen_test_mode, this.payment_method.adyen_api_key],
        }, {
            // When a payment terminal is disconnected it takes Adyen
            // a while to return an error (~6s). So wait 10 seconds
            // before concluding Odoo is unreachable.
            timeout: 10000,
            shadow: true,
        }).catch(this._handle_odoo_connection_failure.bind(this));
    },

    _adyen_get_sale_id: function () {
        var config = this.pos.config;
        return _.str.sprintf('%s (ID: %s)', config.display_name, config.id);
    },

    _adyen_common_message_header: function () {
        var config = this.pos.config;
        this.most_recent_service_id = Math.floor(Math.random() * Math.pow(2, 64)).toString(); // random ID to identify request/response pairs
        this.most_recent_service_id = this.most_recent_service_id.substring(0, 10); // max length is 10

        return {
            'ProtocolVersion': '3.0',
            'MessageClass': 'Service',
            'MessageType': 'Request',
            'SaleID': this._adyen_get_sale_id(config),
            'ServiceID': this.most_recent_service_id,
            'POIID': this.payment_method.adyen_terminal_identifier
        };
    },

    _adyen_pay_data: function () {
        var order = this.pos.get_order();
        var config = this.pos.config;
        var line = order.selected_paymentline;
        var data = {
            'SaleToPOIRequest': {
                'MessageHeader': _.extend(this._adyen_common_message_header(), {
                    'MessageCategory': 'Payment',
                }),
                'PaymentRequest': {
                    'SaleData': {
                        'SaleTransactionID': {
                            'TransactionID': order.uid,
                            'TimeStamp': moment().format(), // iso format: '2018-01-10T11:30:15+00:00'
                        }
                    },
                    'PaymentTransaction': {
                        'AmountsReq': {
                            'Currency': this.pos.currency.name,
                            'RequestedAmount': line.amount,
                        }
                    }
                }
            }
        };

        if (config.adyen_ask_customer_for_tip) {
            data.SaleToPOIRequest.PaymentRequest.SaleData.SaleToAcquirerData = "tenderOption=AskGratuity";
        }

        return data;
    },

    _adyen_pay: function () {
        var self = this;
        var data = this._adyen_pay_data();

        return this._call_adyen(data).then(function (data) {
            return self._adyen_handle_response(data);
        });
    },

    _adyen_cancel: function (ignore_error) {
        var previous_service_id = this.most_recent_service_id;
        var header = _.extend(this._adyen_common_message_header(), {
            'MessageCategory': 'Abort',
        });

        var data = {
            'SaleToPOIRequest': {
                'MessageHeader': header,
                'AbortRequest': {
                    'AbortReason': 'MerchantAbort',
                    'MessageReference': {
                        'MessageCategory': 'Payment',
                        'SaleID': header.SaleID,
                        'ServiceID': previous_service_id,
                    }
                },
            }
        };

        return this._call_adyen(data).then(function (data) {

            // Only valid response is a 200 OK HTTP response which is
            // represented by true.
            if (! ignore_error && data !== true) {
                self._show_error(_('Cancelling the payment failed. Please cancel it manually on the payment terminal.'));
            }
        });
    },

    _convert_receipt_info: function (output_text) {
        return output_text.reduce(function (acc, entry) {
            var params = new URLSearchParams(entry.Text);

            if (params.get('name') && !params.get('value')) {
                return acc + _.str.sprintf('
%s', params.get('name'));
            } else if (params.get('name') && params.get('value')) {
                return acc + _.str.sprintf('
%s: %s', params.get('name'), params.get('value'));
            }

            return acc;
        }, '');
    },

    _poll_for_response: function (resolve, reject) {
        var self = this;
        if (this.was_cancelled) {
            resolve(false);
            return Promise.resolve();
        }

        return rpc.query({
            model: 'pos.payment.method',
            method: 'get_latest_adyen_status',
            args: [this.payment_method.id,
                   this._adyen_get_sale_id(),
                   this.payment_method.adyen_terminal_identifier,
                   this.payment_method.adyen_test_mode,
                   this.payment_method.adyen_api_key],
        }, {
            timeout: 5000,
            shadow: true,
        }).catch(function (data) {
            reject();
            return self._handle_odoo_connection_failure(data);
        }).then(function (status) {
            var notification = status.latest_response;
            var last_diagnosis_service_id = status.last_received_diagnosis_id;
            var order = self.pos.get_order();
            var line = order.selected_paymentline;

            if (self.last_diagnosis_service_id != last_diagnosis_service_id) {
                self.last_diagnosis_service_id = last_diagnosis_service_id;
                self.remaining_polls = 2;
            } else {
                self.remaining_polls--;
            }

            if (notification && notification.SaleToPOIResponse.MessageHeader.ServiceID == self.most_recent_service_id) {
                var response = notification.SaleToPOIResponse.PaymentResponse.Response;
                var additional_response = new URLSearchParams(response.AdditionalResponse);

                if (response.Result == 'Success') {
                    var config = self.pos.config;
                    var payment_response = notification.SaleToPOIResponse.PaymentResponse;
                    var payment_result = payment_response.PaymentResult;
                    var customer_receipt = payment_response.PaymentReceipt.find(function (receipt) {
                        return receipt.DocumentQualifier == 'CustomerReceipt';
                    });

                    if (customer_receipt) {
                        line.set_receipt_info(self._convert_receipt_info(customer_receipt.OutputContent.OutputText));
                    }

                    var tip_amount = payment_result.AmountsResp.TipAmount;
                    if (config.adyen_ask_customer_for_tip && tip_amount > 0) {
                        order.set_tip(tip_amount);
                        line.set_amount(payment_result.AmountsResp.AuthorizedAmount);
                    }

                    line.transaction_id = additional_response.get('pspReference');
                    line.card_type = additional_response.get('cardType');
                    resolve(true);
                } else {
                    var message = additional_response.get('message');
                    self._show_error(_.str.sprintf(_t('Message from Adyen: %s'), message));

                    // this means the transaction was cancelled by pressing the cancel button on the device
                    if (message.startsWith('108 ')) {
                        resolve(false);
                    } else {
                        line.set_payment_status('force_done');
                        reject();
                    }
                }
            } else if (self.remaining_polls <= 0) {
                self._show_error(_t('The connection to your payment terminal failed. Please check if it is still connected to the internet.'));
                self._adyen_cancel();
                resolve(false);
            }
        });
    },

    _adyen_handle_response: function (response) {
        var line = this.pos.get_order().selected_paymentline;

        if (response.error && response.error.status_code == 401) {
            this._show_error(_t('Authentication failed. Please check your Adyen credentials.'));
            line.set_payment_status('force_done');
            return Promise.resolve();
        }

        response = response.SaleToPOIRequest;
        if (response && response.EventNotification && response.EventNotification.EventToNotify == 'Reject') {
            console.error('error from Adyen', response);

            var msg = '';
            if (response.EventNotification) {
                var params = new URLSearchParams(response.EventNotification.EventDetails);
                msg = params.get('message');
            }

            this._show_error(_.str.sprintf(_t('An unexpected error occured. Message from Adyen: %s'), msg));
            if (line) {
                line.set_payment_status('force_done');
            }

            return Promise.resolve();
        } else {
            line.set_payment_status('waitingCard');

            var self = this;
            var res = new Promise(function (resolve, reject) {
                // clear previous intervals just in case, otherwise
                // it'll run forever
                clearTimeout(self.polling);

                self.polling = setInterval(function () {
                    self._poll_for_response(resolve, reject);
                }, 3000);
            });

            // make sure to stop polling when we're done
            res.finally(function () {
                self._reset_state();
            });

            return res;
        }
    },

    _show_error: function (msg, title) {
        if (!title) {
            title =  _t('Adyen Error');
        }
        Gui.showPopup('ErrorPopup',{
            'title': title,
            'body': msg,
        });
    },
});

return PaymentAdyen;
});
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const webpack = require('webpack');

const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const SpritesmithPlugin = require('webpack-spritesmith');
const GenerateJsonPlugin = require('generate-json-webpack-plugin');

// List available locales, to fetch only the required locales from Moment.JS:
// Build a regexp that selects the locale's name without the JS extension (due
// to the way moment includes those) and ensure that's the last character to
// not include locale variants. See discussion in
// https://framagit.org/kresusapp/kresus/merge_requests/448#note_130514
const locales = fs.readdirSync('shared/locales').map(
    x => x.replace('.json', '')
);
const localesRegex = new RegExp(
    '(' + locales.join('|') + ')$'
);

let entry = {
    main: [
        'babel-polyfill',
        './node_modules/normalize.css/normalize.css',
        './node_modules/font-awesome/css/font-awesome.css',
        './node_modules/dygraphs/dist/dygraph.css',
        './node_modules/c3/c3.css',
        './node_modules/flatpickr/dist/themes/light.css',
        './client/css/base.css',
        './client/init.js'
    ]
};

const themes = fs.readdirSync('client/themes').filter(
    f => fs.statSync(`client/themes/${f}`).isDirectory()
);

themes.forEach(theme => {
    entry[`themes/${theme}`] = `./client/themes/${theme}/style.css`;
});

// These extra locales should be put after the main client entrypoint to ensure
// that all the scripts are loaded and `window` is populated before trying to
// append locales to these objects.
locales.forEach(locale => {
    if (locale !== 'en') {
        // Flatpickr locales entries
        entry.main.push(`flatpickr/dist/l10n/${locale}.js`);
    }
});

// Webpack config
const config = {
    entry: entry,

    output: {
        path: path.resolve(__dirname, '..', '..', 'build', 'client'),
        filename: '[name].js',
    },

    module: {
        loaders: [
            {
                test: /\.js$/,
                // Exclude all but dygraphs
                // Dygraphs ships ES5 files with arrow functions by default, so
                // we need to pass Babel on them
                exclude: /node_modules(?!\/dygraphs)/,
                use: {
                    loader: 'babel-loader'
                }
            },

            {
                test: /dependenciesLicenses\.json$/,
                use: {
                    loader: 'dependencies-licenses-loader'
                }
            },

            {
                test: /\.json$/,
                include: /shared\/locales/,
                use: [
                    {
                        loader: 'json-strip-loader',
                        query: {
                            key: 'server',
                            deep: false
                        }
                    }
                ]
            },

            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ['css-loader']
                })
            },

            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                use: [
                    {
                        loader: 'file-loader',
                        query: {
                            name: 'assets/images/[sha512:hash:hex].[ext]'
                        }
                    },
                    {
                        loader: 'image-webpack-loader',
                        query: {
                            bypassOnDebug: true,
                            'optipng': {
                                optimizationLevel: 7
                            },
                            'gifsicle': {
                                interlaced: false
                            }
                        }
                    }
                ]
            },

            {
                test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                use: [
                    {
                        loader: 'url-loader',
                        query: {
                            limit: 10000,
                            mimetype: 'application/font-woff',
                            name: 'assets/fonts/[name]-[hash].[ext]'
                        }
                    }
                ]
            },

            {
                test: /\.(ttf|otf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                use: [
                    {
                        loader: 'file-loader',
                        query: {
                            name: 'assets/fonts/[name]-[sha512:hash:hex].[ext]'
                        }
                    }
                ]
            }
        ]
    },

    devServer: {
        disableHostCheck: true,
        host: "0.0.0.0",
        proxy: {
            "/api": "http://localhost:9876/",
            "/manifest": "http://localhost:9876/"
        }
    },

    resolve: {
        modules: ['node_modules', 'build/spritesmith-generated']
    },

    resolveLoader: {
        modules: ['node_modules', path.resolve(__dirname, 'loaders')]
    },

    plugins: [
        // Directly copy the static index and robots files.
        new CopyWebpackPlugin([
            { from: './static/index.html' },
            { from: './static/robots.txt' },
            { from: './static/images/favicon', to: 'favicon' }
        ]),

        // Extract CSS in a dedicated file.
        new ExtractTextPlugin({
            filename: getPath => {
                let pathname = getPath('[name]');
                // Entries names with '/' refer to themes paths.
                if (pathname.indexOf('/') !== -1) {
                    return `${pathname.replace('/', '-')}-bundle.css`;
                }
                return `${pathname}.css`;
            },
            disable: false,
            allChunks: true
        }),

        // Build bank icons sprite.
        new SpritesmithPlugin({
            src: {
                cwd: path.resolve(__dirname, '..', '..', 'static', 'images', 'banks'),
                glob: '*.png'
            },
            target: {
                image: path.resolve(__dirname, '..', '..', 'build', 'spritesmith-generated', 'sprite.png'),
                css: path.resolve(__dirname, '..', '..', 'build', 'spritesmith-generated', 'sprite.css')
            },
            apiOptions: {
                cssImageRef: '~sprite.png'
            }
        }),

        // Only keep the useful locales from Moment.
        new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, localesRegex),

        // Generate a themes.json file with the list of themes.
        new GenerateJsonPlugin('themes.json', {themes: themes})
    ]
}

if (process.env.ANALYZE) {
    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
    config.plugins.push(
        // Generate analyzer reports if needed
        new BundleAnalyzerPlugin({
            // Can be `server`, `static` or `disabled`.
            // In `server` mode analyzer will start HTTP server to show bundle report.
            // In `static` mode single HTML file with bundle report will be generated.
            // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`.
            analyzerMode: 'static',

            // Path to bundle report file that will be generated in `static` mode.
            // Relative to bundles output directory.
            reportFilename: '../reports/client.html',

            // Module sizes to show in report by default.
            // Should be one of `stat`, `parsed` or `gzip`.
            // See "Definitions" section for more information.
            defaultSizes: 'parsed',

            // Automatically open report in default browser
            openAnalyzer: true,

            // If `true`, Webpack Stats JSON file will be generated in bundles output directory
            generateStatsFile: true,

            // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
            // Relative to bundles output directory.
            statsFilename: '../reports/client.json'
        })
    );
}

module.exports = config;
<commit_msg>Fix #792: Sync webpack-dev-server proxy timeout with the one used in Kresus;<commit_after>const fs = require('fs');
const path = require('path');
const webpack = require('webpack');

const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const SpritesmithPlugin = require('webpack-spritesmith');
const GenerateJsonPlugin = require('generate-json-webpack-plugin');

// List available locales, to fetch only the required locales from Moment.JS:
// Build a regexp that selects the locale's name without the JS extension (due
// to the way moment includes those) and ensure that's the last character to
// not include locale variants. See discussion in
// https://framagit.org/kresusapp/kresus/merge_requests/448#note_130514
const locales = fs.readdirSync('shared/locales').map(
    x => x.replace('.json', '')
);
const localesRegex = new RegExp(
    '(' + locales.join('|') + ')$'
);

let entry = {
    main: [
        'babel-polyfill',
        './node_modules/normalize.css/normalize.css',
        './node_modules/font-awesome/css/font-awesome.css',
        './node_modules/dygraphs/dist/dygraph.css',
        './node_modules/c3/c3.css',
        './node_modules/flatpickr/dist/themes/light.css',
        './client/css/base.css',
        './client/init.js'
    ]
};

const themes = fs.readdirSync('client/themes').filter(
    f => fs.statSync(`client/themes/${f}`).isDirectory()
);

themes.forEach(theme => {
    entry[`themes/${theme}`] = `./client/themes/${theme}/style.css`;
});

// These extra locales should be put after the main client entrypoint to ensure
// that all the scripts are loaded and `window` is populated before trying to
// append locales to these objects.
locales.forEach(locale => {
    if (locale !== 'en') {
        // Flatpickr locales entries
        entry.main.push(`flatpickr/dist/l10n/${locale}.js`);
    }
});

// Webpack config
const config = {
    entry: entry,

    output: {
        path: path.resolve(__dirname, '..', '..', 'build', 'client'),
        filename: '[name].js',
    },

    module: {
        loaders: [
            {
                test: /\.js$/,
                // Exclude all but dygraphs
                // Dygraphs ships ES5 files with arrow functions by default, so
                // we need to pass Babel on them
                exclude: /node_modules(?!\/dygraphs)/,
                use: {
                    loader: 'babel-loader'
                }
            },

            {
                test: /dependenciesLicenses\.json$/,
                use: {
                    loader: 'dependencies-licenses-loader'
                }
            },

            {
                test: /\.json$/,
                include: /shared\/locales/,
                use: [
                    {
                        loader: 'json-strip-loader',
                        query: {
                            key: 'server',
                            deep: false
                        }
                    }
                ]
            },

            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ['css-loader']
                })
            },

            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                use: [
                    {
                        loader: 'file-loader',
                        query: {
                            name: 'assets/images/[sha512:hash:hex].[ext]'
                        }
                    },
                    {
                        loader: 'image-webpack-loader',
                        query: {
                            bypassOnDebug: true,
                            'optipng': {
                                optimizationLevel: 7
                            },
                            'gifsicle': {
                                interlaced: false
                            }
                        }
                    }
                ]
            },

            {
                test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                use: [
                    {
                        loader: 'url-loader',
                        query: {
                            limit: 10000,
                            mimetype: 'application/font-woff',
                            name: 'assets/fonts/[name]-[hash].[ext]'
                        }
                    }
                ]
            },

            {
                test: /\.(ttf|otf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                use: [
                    {
                        loader: 'file-loader',
                        query: {
                            name: 'assets/fonts/[name]-[sha512:hash:hex].[ext]'
                        }
                    }
                ]
            }
        ]
    },

    devServer: {
        disableHostCheck: true,
        host: "0.0.0.0",
        proxy: {
            "/api": {
                target: "http://localhost:9876/",
                proxyTimeout: 5 * 60 * 1000,
                onProxyReq: (proxyReq, req, res) => req.setTimeout(5 * 60 * 1000)
            },
            "/manifest": "http://localhost:9876/"
        }
    },

    resolve: {
        modules: ['node_modules', 'build/spritesmith-generated']
    },

    resolveLoader: {
        modules: ['node_modules', path.resolve(__dirname, 'loaders')]
    },

    plugins: [
        // Directly copy the static index and robots files.
        new CopyWebpackPlugin([
            { from: './static/index.html' },
            { from: './static/robots.txt' },
            { from: './static/images/favicon', to: 'favicon' }
        ]),

        // Extract CSS in a dedicated file.
        new ExtractTextPlugin({
            filename: getPath => {
                let pathname = getPath('[name]');
                // Entries names with '/' refer to themes paths.
                if (pathname.indexOf('/') !== -1) {
                    return `${pathname.replace('/', '-')}-bundle.css`;
                }
                return `${pathname}.css`;
            },
            disable: false,
            allChunks: true
        }),

        // Build bank icons sprite.
        new SpritesmithPlugin({
            src: {
                cwd: path.resolve(__dirname, '..', '..', 'static', 'images', 'banks'),
                glob: '*.png'
            },
            target: {
                image: path.resolve(__dirname, '..', '..', 'build', 'spritesmith-generated', 'sprite.png'),
                css: path.resolve(__dirname, '..', '..', 'build', 'spritesmith-generated', 'sprite.css')
            },
            apiOptions: {
                cssImageRef: '~sprite.png'
            }
        }),

        // Only keep the useful locales from Moment.
        new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, localesRegex),

        // Generate a themes.json file with the list of themes.
        new GenerateJsonPlugin('themes.json', {themes: themes})
    ]
}

if (process.env.ANALYZE) {
    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
    config.plugins.push(
        // Generate analyzer reports if needed
        new BundleAnalyzerPlugin({
            // Can be `server`, `static` or `disabled`.
            // In `server` mode analyzer will start HTTP server to show bundle report.
            // In `static` mode single HTML file with bundle report will be generated.
            // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`.
            analyzerMode: 'static',

            // Path to bundle report file that will be generated in `static` mode.
            // Relative to bundles output directory.
            reportFilename: '../reports/client.html',

            // Module sizes to show in report by default.
            // Should be one of `stat`, `parsed` or `gzip`.
            // See "Definitions" section for more information.
            defaultSizes: 'parsed',

            // Automatically open report in default browser
            openAnalyzer: true,

            // If `true`, Webpack Stats JSON file will be generated in bundles output directory
            generateStatsFile: true,

            // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
            // Relative to bundles output directory.
            statsFilename: '../reports/client.json'
        })
    );
}

module.exports = config;
<|endoftext|>


<commit_before>/*globals svgEditor, svgCanvas, $, widget*/
/*jslint vars: true, eqeq: true, regexp: true, continue: true*/
/*
 * ext-storage.js
 *
 * Licensed under the MIT License
 *
 * Copyright(c) 2010 Brett Zamir
 *
 */
/**
* This extension allows automatic saving of the SVG canvas contents upon
*  page unload (which can later be automatically retrieved upon future
*  editor loads).
*
*  The functionality was originally part of the SVG Editor, but moved to a
*  separate extension to make the setting behavior optional, and adapted
*  to inform the user of its setting of local data.
*/

/*
TODOS
1. Revisit on whether to use $.pref over directly setting curConfig in all
	extensions for a more public API (not only for extPath and imagePath,
	but other currently used config in the extensions)
2. We might provide control of storage settings through the UI besides the
    initial (or URL-forced) dialog.
*/
svgEditor.addExtension('storage', function() {
	// We could empty any already-set data for users when they decline storage,
	//  but it would be a risk for users who wanted to store but accidentally
	// said "no"; instead, we'll let those who already set it, delete it themselves;
	// to change, set the "emptyStorageOnDecline" config setting to true
	// in config.js.
	var emptyStorageOnDecline = svgEditor.curConfig.emptyStorageOnDecline,
		// When the code in svg-editor.js prevents local storage on load per
		//  user request, we also prevent storing on unload here so as to
		//  avoid third-party sites making XSRF requests or providing links
		// which would cause the user's local storage not to load and then
		// upon page unload (such as the user closing the window), the storage
		//  would thereby be set with an empty value, erasing any of the
		// user's prior work. To change this behavior so that no use of storage
		// or adding of new storage takes place regardless of settings, set
		// the "noStorageOnLoad" config setting to true in config.js.
		noStorageOnLoad = svgEditor.curConfig.noStorageOnLoad,
		forceStorage = svgEditor.curConfig.forceStorage,
		storage = svgEditor.storage;

	function replaceStoragePrompt (val) {
		val = val ? 'storagePrompt=' + val : '';
		if (window.location.href.indexOf('storagePrompt=') > -1) {
			window.location.href = window.location.href.replace(/([&?])storagePrompt=[^&]*(&?)/, function (n0, n1, amp) {
				return (val ? n1 : '') + val + (!val && amp ? n1 : (amp || ''));
			});
		}
		else {
			window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + val;
		}
	}
	function setSVGContentStorage (val) {
		if (storage) {
			var name = 'svgedit-' + svgEditor.curConfig.canvasName;
			if (!val) {
				storage.removeItem(name);
			}
			else {
				storage.setItem(name, val);
			}
		}
	}

	function expireCookie (cookie) {
		document.cookie = encodeURIComponent(cookie) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
	}

	function removeStoragePrefCookie () {
		expireCookie('store');
	}

	function emptyStorage() {
		setSVGContentStorage('');
		var name;
		for (name in svgEditor.curPrefs) {
			if (svgEditor.curPrefs.hasOwnProperty(name)) {
				name = 'svg-edit-' + name;
				if (storage) {
					storage.removeItem(name);
				}
				expireCookie(name);
			}
		}
	}

//	emptyStorage();

	/**
	* Listen for unloading: If and only if opted in by the user, set the content
	*   document and preferences into storage:
	* 1. Prevent save warnings (since we're automatically saving unsaved
	*       content into storage)
	* 2. Use localStorage to set SVG contents (potentially too large to allow in cookies)
	* 3. Use localStorage (where available) or cookies to set preferences.
	*/
	function setupBeforeUnloadListener () {
		window.addEventListener('beforeunload', function(e) {
			// Don't save anything unless the user opted in to storage
			if (!document.cookie.match(/(?:^|;\s*)store=(?:prefsAndContent|prefsOnly)/)) {
				return;
			}
			var key;
			if (document.cookie.match(/(?:^|;\s*)store=prefsAndContent/)) {
				setSVGContentStorage(svgCanvas.getSvgString());
			}

			svgEditor.setConfig({no_save_warning: true}); // No need for explicit saving at all once storage is on
			// svgEditor.showSaveWarning = false;

			var curPrefs = svgEditor.curPrefs;

			for (key in curPrefs) {
				if (curPrefs.hasOwnProperty(key)) { // It's our own config, so we don't need to iterate up the prototype chain
					var val = curPrefs[key],
						store = (val != undefined);
					key = 'svg-edit-' + key;
					if (!store) {
						continue;
					}
					if (storage) {
						storage.setItem(key, val);
					}
					else if (window.widget) {
						widget.setPreferenceForKey(val, key);
					}
					else {
						val = encodeURIComponent(val);
						document.cookie = encodeURIComponent(key) + '=' + val + '; expires=Fri, 31 Dec 9999 23:59:59 GMT';
					}
				}
			}
		}, false);
	}

	/*
	// We could add locales here instead (and also thereby avoid the need
	// to keep our content within "langReady"), but this would be less
	// convenient for translators.
	$.extend(uiStrings, {confirmSetStorage: {
		message: "By default and where supported, SVG-Edit can store your editor "+
		"preferences and SVG content locally on your machine so you do not "+
		"need to add these back each time you load SVG-Edit. If, for privacy "+
		"reasons, you do not wish to store this information on your machine, "+
		"you can change away from the default option below.",
		storagePrefsAndContent: "Store preferences and SVG content locally",
		storagePrefsOnly: "Only store preferences locally",
		storagePrefs: "Store preferences locally",
		storageNoPrefsOrContent: "Do not store my preferences or SVG content locally",
		storageNoPrefs: "Do not store my preferences locally",
		rememberLabel: "Remember this choice?",
		rememberTooltip: "If you choose to opt out of storage while remembering this choice, the URL will change so as to avoid asking again."
	}});
	*/
	var loaded = false;
	return {
		name: 'storage',
		langReady: function (data) {
			var // lang = data.lang,
				uiStrings = data.uiStrings, // No need to store as dialog should only run once
				storagePrompt = $.deparam.querystring(true).storagePrompt;

			// No need to run this one-time dialog again just because the user
			//   changes the language
			if (loaded) {
				return;
			}
			loaded = true;

			// Note that the following can load even if "noStorageOnLoad" is
			//   set to false; to avoid any chance of storage, avoid this
			//   extension! (and to avoid using any prior storage, set the
			//   config option "noStorageOnLoad" to true).
			if (!forceStorage && (
				// If the URL has been explicitly set to always prompt the
				//  user (e.g., so one can be pointed to a URL where one
				// can alter one's settings, say to prevent future storage)...
				storagePrompt === true ||
				(
					// ...or...if the URL at least doesn't explicitly prevent a
					//  storage prompt (as we use for users who
					// don't want to set cookies at all but who don't want
					// continual prompts about it)...
					storagePrompt !== false &&
					// ...and this user hasn't previously indicated a desire for storage
					!document.cookie.match(/(?:^|;\s*)store=(?:prefsAndContent|prefsOnly)/)
				)
				// ...then show the storage prompt.
			)) {

				var options = [];
				if (storage) {
					options.unshift(
						{value: 'prefsAndContent', text: uiStrings.confirmSetStorage.storagePrefsAndContent},
						{value: 'prefsOnly', text: uiStrings.confirmSetStorage.storagePrefsOnly},
						{value: 'noPrefsOrContent', text: uiStrings.confirmSetStorage.storageNoPrefsOrContent}
					);
				}
				else {
					options.unshift(
						{value: 'prefsOnly', text: uiStrings.confirmSetStorage.storagePrefs},
						{value: 'noPrefsOrContent', text: uiStrings.confirmSetStorage.storageNoPrefs}
					);
				}

				// Hack to temporarily provide a wide and high enough dialog
				var oldContainerWidth = $('#dialog_container')[0].style.width,
					oldContainerMarginLeft = $('#dialog_container')[0].style.marginLeft,
					oldContentHeight = $('#dialog_content')[0].style.height,
					oldContainerHeight = $('#dialog_container')[0].style.height;
				$('#dialog_content')[0].style.height = '120px';
				$('#dialog_container')[0].style.height = '170px';
				$('#dialog_container')[0].style.width = '800px';
				$('#dialog_container')[0].style.marginLeft = '-400px';

				// Open select-with-checkbox dialog
				$.select(
					uiStrings.confirmSetStorage.message,
					options,
					function (pref, checked) {
						if (pref && pref !== 'noPrefsOrContent') {
							// Regardless of whether the user opted
							// to remember the choice (and move to a URL which won't
							// ask them again), we have to assume the user
							// doesn't even want to remember their not wanting
							// storage, so we don't set the cookie or continue on with
							//  setting storage on beforeunload
							document.cookie = 'store=' + encodeURIComponent(pref) + '; expires=Fri, 31 Dec 9999 23:59:59 GMT'; // 'prefsAndContent' | 'prefsOnly'
							// If the URL was configured to always insist on a prompt, if
							//    the user does indicate a wish to store their info, we
							//    don't want ask them again upon page refresh so move
							//    them instead to a URL which does not always prompt
							if (storagePrompt === true && checked) {
								replaceStoragePrompt();
								return;
							}
						}
						else { // The user does not wish storage (or cancelled, which we treat equivalently)
							removeStoragePrefCookie();
							if (pref && // If the user explicitly expresses wish for no storage
								emptyStorageOnDecline
							) {
								emptyStorage();
							}
							if (pref && checked) {
								// Open a URL which won't set storage and won't prompt user about storage
								replaceStoragePrompt('false');
								return;
							}
						}

						// Reset width/height of dialog (e.g., for use by Export)
						$('#dialog_container')[0].style.width = oldContainerWidth;
						$('#dialog_container')[0].style.marginLeft = oldContainerMarginLeft;
						$('#dialog_content')[0].style.height = oldContentHeight;
						$('#dialog_container')[0].style.height = oldContainerHeight;

						// It should be enough to (conditionally) add to storage on
						//   beforeunload, but if we wished to update immediately,
						//   we might wish to try setting:
						//       svgEditor.setConfig({noStorageOnLoad: true});
						//   and then call:
						//       svgEditor.loadContentAndPrefs();

						// We don't check for noStorageOnLoad here because
						//   the prompt gives the user the option to store data
						setupBeforeUnloadListener();

						svgEditor.storagePromptClosed = true;
					},
					null,
					null,
					{
						label: uiStrings.confirmSetStorage.rememberLabel,
						checked: false,
						tooltip: uiStrings.confirmSetStorage.rememberTooltip
					}
				);
			}
			else if (!noStorageOnLoad || forceStorage) {
				setupBeforeUnloadListener();
			}
		}
	};
});
<commit_msg>Ensure top URL will change in case it wishes to react according to storagePrompt param (such as in the embedded editor).<commit_after>/*globals svgEditor, svgCanvas, $, widget*/
/*jslint vars: true, eqeq: true, regexp: true, continue: true*/
/*
 * ext-storage.js
 *
 * Licensed under the MIT License
 *
 * Copyright(c) 2010 Brett Zamir
 *
 */
/**
* This extension allows automatic saving of the SVG canvas contents upon
*  page unload (which can later be automatically retrieved upon future
*  editor loads).
*
*  The functionality was originally part of the SVG Editor, but moved to a
*  separate extension to make the setting behavior optional, and adapted
*  to inform the user of its setting of local data.
*/

/*
TODOS
1. Revisit on whether to use $.pref over directly setting curConfig in all
	extensions for a more public API (not only for extPath and imagePath,
	but other currently used config in the extensions)
2. We might provide control of storage settings through the UI besides the
    initial (or URL-forced) dialog.
*/
svgEditor.addExtension('storage', function() {
	// We could empty any already-set data for users when they decline storage,
	//  but it would be a risk for users who wanted to store but accidentally
	// said "no"; instead, we'll let those who already set it, delete it themselves;
	// to change, set the "emptyStorageOnDecline" config setting to true
	// in config.js.
	var emptyStorageOnDecline = svgEditor.curConfig.emptyStorageOnDecline,
		// When the code in svg-editor.js prevents local storage on load per
		//  user request, we also prevent storing on unload here so as to
		//  avoid third-party sites making XSRF requests or providing links
		// which would cause the user's local storage not to load and then
		// upon page unload (such as the user closing the window), the storage
		//  would thereby be set with an empty value, erasing any of the
		// user's prior work. To change this behavior so that no use of storage
		// or adding of new storage takes place regardless of settings, set
		// the "noStorageOnLoad" config setting to true in config.js.
		noStorageOnLoad = svgEditor.curConfig.noStorageOnLoad,
		forceStorage = svgEditor.curConfig.forceStorage,
		storage = svgEditor.storage;

	function replaceStoragePrompt (val) {
		val = val ? 'storagePrompt=' + val : '';
		var loc = top.location; // Allow this to work with the embedded editor as well
		if (loc.href.indexOf('storagePrompt=') > -1) {
			loc.href = loc.href.replace(/([&?])storagePrompt=[^&]*(&?)/, function (n0, n1, amp) {
				return (val ? n1 : '') + val + (!val && amp ? n1 : (amp || ''));
			});
		}
		else {
			loc.href += (loc.href.indexOf('?') > -1 ? '&' : '?') + val;
		}
	}
	function setSVGContentStorage (val) {
		if (storage) {
			var name = 'svgedit-' + svgEditor.curConfig.canvasName;
			if (!val) {
				storage.removeItem(name);
			}
			else {
				storage.setItem(name, val);
			}
		}
	}

	function expireCookie (cookie) {
		document.cookie = encodeURIComponent(cookie) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
	}

	function removeStoragePrefCookie () {
		expireCookie('store');
	}

	function emptyStorage() {
		setSVGContentStorage('');
		var name;
		for (name in svgEditor.curPrefs) {
			if (svgEditor.curPrefs.hasOwnProperty(name)) {
				name = 'svg-edit-' + name;
				if (storage) {
					storage.removeItem(name);
				}
				expireCookie(name);
			}
		}
	}

//	emptyStorage();

	/**
	* Listen for unloading: If and only if opted in by the user, set the content
	*   document and preferences into storage:
	* 1. Prevent save warnings (since we're automatically saving unsaved
	*       content into storage)
	* 2. Use localStorage to set SVG contents (potentially too large to allow in cookies)
	* 3. Use localStorage (where available) or cookies to set preferences.
	*/
	function setupBeforeUnloadListener () {
		window.addEventListener('beforeunload', function(e) {
			// Don't save anything unless the user opted in to storage
			if (!document.cookie.match(/(?:^|;\s*)store=(?:prefsAndContent|prefsOnly)/)) {
				return;
			}
			var key;
			if (document.cookie.match(/(?:^|;\s*)store=prefsAndContent/)) {
				setSVGContentStorage(svgCanvas.getSvgString());
			}

			svgEditor.setConfig({no_save_warning: true}); // No need for explicit saving at all once storage is on
			// svgEditor.showSaveWarning = false;

			var curPrefs = svgEditor.curPrefs;

			for (key in curPrefs) {
				if (curPrefs.hasOwnProperty(key)) { // It's our own config, so we don't need to iterate up the prototype chain
					var val = curPrefs[key],
						store = (val != undefined);
					key = 'svg-edit-' + key;
					if (!store) {
						continue;
					}
					if (storage) {
						storage.setItem(key, val);
					}
					else if (window.widget) {
						widget.setPreferenceForKey(val, key);
					}
					else {
						val = encodeURIComponent(val);
						document.cookie = encodeURIComponent(key) + '=' + val + '; expires=Fri, 31 Dec 9999 23:59:59 GMT';
					}
				}
			}
		}, false);
	}

	/*
	// We could add locales here instead (and also thereby avoid the need
	// to keep our content within "langReady"), but this would be less
	// convenient for translators.
	$.extend(uiStrings, {confirmSetStorage: {
		message: "By default and where supported, SVG-Edit can store your editor "+
		"preferences and SVG content locally on your machine so you do not "+
		"need to add these back each time you load SVG-Edit. If, for privacy "+
		"reasons, you do not wish to store this information on your machine, "+
		"you can change away from the default option below.",
		storagePrefsAndContent: "Store preferences and SVG content locally",
		storagePrefsOnly: "Only store preferences locally",
		storagePrefs: "Store preferences locally",
		storageNoPrefsOrContent: "Do not store my preferences or SVG content locally",
		storageNoPrefs: "Do not store my preferences locally",
		rememberLabel: "Remember this choice?",
		rememberTooltip: "If you choose to opt out of storage while remembering this choice, the URL will change so as to avoid asking again."
	}});
	*/
	var loaded = false;
	return {
		name: 'storage',
		langReady: function (data) {
			var // lang = data.lang,
				uiStrings = data.uiStrings, // No need to store as dialog should only run once
				storagePrompt = $.deparam.querystring(true).storagePrompt;

			// No need to run this one-time dialog again just because the user
			//   changes the language
			if (loaded) {
				return;
			}
			loaded = true;

			// Note that the following can load even if "noStorageOnLoad" is
			//   set to false; to avoid any chance of storage, avoid this
			//   extension! (and to avoid using any prior storage, set the
			//   config option "noStorageOnLoad" to true).
			if (!forceStorage && (
				// If the URL has been explicitly set to always prompt the
				//  user (e.g., so one can be pointed to a URL where one
				// can alter one's settings, say to prevent future storage)...
				storagePrompt === true ||
				(
					// ...or...if the URL at least doesn't explicitly prevent a
					//  storage prompt (as we use for users who
					// don't want to set cookies at all but who don't want
					// continual prompts about it)...
					storagePrompt !== false &&
					// ...and this user hasn't previously indicated a desire for storage
					!document.cookie.match(/(?:^|;\s*)store=(?:prefsAndContent|prefsOnly)/)
				)
				// ...then show the storage prompt.
			)) {

				var options = [];
				if (storage) {
					options.unshift(
						{value: 'prefsAndContent', text: uiStrings.confirmSetStorage.storagePrefsAndContent},
						{value: 'prefsOnly', text: uiStrings.confirmSetStorage.storagePrefsOnly},
						{value: 'noPrefsOrContent', text: uiStrings.confirmSetStorage.storageNoPrefsOrContent}
					);
				}
				else {
					options.unshift(
						{value: 'prefsOnly', text: uiStrings.confirmSetStorage.storagePrefs},
						{value: 'noPrefsOrContent', text: uiStrings.confirmSetStorage.storageNoPrefs}
					);
				}

				// Hack to temporarily provide a wide and high enough dialog
				var oldContainerWidth = $('#dialog_container')[0].style.width,
					oldContainerMarginLeft = $('#dialog_container')[0].style.marginLeft,
					oldContentHeight = $('#dialog_content')[0].style.height,
					oldContainerHeight = $('#dialog_container')[0].style.height;
				$('#dialog_content')[0].style.height = '120px';
				$('#dialog_container')[0].style.height = '170px';
				$('#dialog_container')[0].style.width = '800px';
				$('#dialog_container')[0].style.marginLeft = '-400px';

				// Open select-with-checkbox dialog
				$.select(
					uiStrings.confirmSetStorage.message,
					options,
					function (pref, checked) {
						if (pref && pref !== 'noPrefsOrContent') {
							// Regardless of whether the user opted
							// to remember the choice (and move to a URL which won't
							// ask them again), we have to assume the user
							// doesn't even want to remember their not wanting
							// storage, so we don't set the cookie or continue on with
							//  setting storage on beforeunload
							document.cookie = 'store=' + encodeURIComponent(pref) + '; expires=Fri, 31 Dec 9999 23:59:59 GMT'; // 'prefsAndContent' | 'prefsOnly'
							// If the URL was configured to always insist on a prompt, if
							//    the user does indicate a wish to store their info, we
							//    don't want ask them again upon page refresh so move
							//    them instead to a URL which does not always prompt
							if (storagePrompt === true && checked) {
								replaceStoragePrompt();
								return;
							}
						}
						else { // The user does not wish storage (or cancelled, which we treat equivalently)
							removeStoragePrefCookie();
							if (pref && // If the user explicitly expresses wish for no storage
								emptyStorageOnDecline
							) {
								emptyStorage();
							}
							if (pref && checked) {
								// Open a URL which won't set storage and won't prompt user about storage
								replaceStoragePrompt('false');
								return;
							}
						}

						// Reset width/height of dialog (e.g., for use by Export)
						$('#dialog_container')[0].style.width = oldContainerWidth;
						$('#dialog_container')[0].style.marginLeft = oldContainerMarginLeft;
						$('#dialog_content')[0].style.height = oldContentHeight;
						$('#dialog_container')[0].style.height = oldContainerHeight;

						// It should be enough to (conditionally) add to storage on
						//   beforeunload, but if we wished to update immediately,
						//   we might wish to try setting:
						//       svgEditor.setConfig({noStorageOnLoad: true});
						//   and then call:
						//       svgEditor.loadContentAndPrefs();

						// We don't check for noStorageOnLoad here because
						//   the prompt gives the user the option to store data
						setupBeforeUnloadListener();

						svgEditor.storagePromptClosed = true;
					},
					null,
					null,
					{
						label: uiStrings.confirmSetStorage.rememberLabel,
						checked: false,
						tooltip: uiStrings.confirmSetStorage.rememberTooltip
					}
				);
			}
			else if (!noStorageOnLoad || forceStorage) {
				setupBeforeUnloadListener();
			}
		}
	};
});
<|endoftext|>


<commit_before>(function (win) {

    if (!(win.history && win.history.pushState))
        return;

    var submitData = {};
    win.document.addEventListener('click', function (e) {
        var element = e.target;
        var anchor = getAjaxTarget(element, 'A');
        if (!e.ctrlKey && !e.shiftKey && anchor) {
            e.preventDefault();
            refreshAjax(anchor.getAttribute('href'), null, true, anchor);
        }
        if (element.tagName === 'INPUT' && element.name) {
            if (element.type === 'submit')
                submitData[element.name] = element.value;
            if (element.type === 'image') {
                submitData[element.name + '.x'] = win.Math.max(0, e.offsetX);
                submitData[element.name + '.y'] = win.Math.max(0, e.offsetY);
            }
        }
    });

    win.document.addEventListener('submit', function (e) {
        var form = getAjaxTarget(e.target, 'FORM');
        if (form) {
            e.preventDefault();
            refreshAjax(form.getAttribute('action'), getFormData(form), true, form);
        }
    });

    var tagNames = /^INPUT|TEXTAREA|SELECT$/;
    var ignoreTypes = /^button|image|submit|reset|file$/;
    var checkTypes = /^checkbox|radio$/;
    function getFormData(form) {
        var elements = form.elements;
        var data = {};
        for (var i = 0; i < elements.length; i++) {
            var element = elements[i];
            if (tagNames.test(element.tagName) && element.name
                && !ignoreTypes.test(element.type) && !element.disabled
                && (!checkTypes.test(element.type) || element.checked))
                data[element.name] = element.value;
        }
        for (var key in submitData)
            data[key] = submitData[key];
        submitData = {};
        return data;
    }

    function getAjaxTarget(element, tagName) {
        var target = null;
        while (element) {
            if (element.getAttribute) {
                var navigation = element.getAttribute('data-navigation');
                if (!target && element.tagName === tagName && navigation === 'refresh')
                    target = element;
                if (navigation === 'noajax')
                    return null;
            }
            element = element.parentNode;
        }
        return target;
    }

    var link = win.location.pathname + win.location.search;
    function navigate(data, target) {
        refreshAjax(link, data, true, target);
    }

    function refreshAjax(newLink, data, addHistory, target, title) {
        var req = {
            link: newLink,
            data: data,
            target: target,
            cancel: false
        };
        raiseEvent('prenavigate', req, null);
        if (!req.cancel) {
            var resp = {
                history: addHistory ? 'add' : null,
                title: title ? title : win.document.title
            };
            var ajaxReq = new win.XMLHttpRequest();
            ajaxReq.onreadystatechange = onReady(ajaxReq, req, resp);
            ajaxReq.open(data ? 'post' : 'get', getAjaxLink(newLink, target));
            if (data)
                ajaxReq.setRequestHeader("Content-Type", "application/json");
            ajaxReq.send(win.JSON.stringify(data));
        }
    }

    function getAjaxLink(baseLink, target) {
        baseLink += baseLink.indexOf('?') > 0 ? '&' : '?';
        baseLink += 'refreshajax=' + win.encodeURIComponent(link);
        baseLink += '&navigation=' + (target ? 'refresh' : 'history');
        if (target) {
            baseLink = setLinkData(target, baseLink, 'include-current');
            baseLink = setLinkData(target, baseLink, 'current-keys');
            baseLink = setLinkData(target, baseLink, 'to-keys');
        }
        return baseLink;
    }

    function setLinkData(target, link, name) {
        var value = target.getAttribute('data-' + name);
        if (value)
            link += '&' + name.replace('-', '') + '=' + win.encodeURIComponent(value);
        return link;
    }

    var cache = {};
    function onReady(ajaxReq, req, resp) {
        var oldLink = link;
        return function () {
            if (ajaxReq.readyState === 4 && ajaxReq.status === 200) {
                var ajaxResp = win.JSON.parse(ajaxReq.responseText);
                if (ajaxResp.RedirectLink) {
                    win.location.href = ajaxResp.RedirectLink;
                    return;
                }
                if (link !== oldLink)
                    return;
                if (ajaxResp.Title)
                    resp.title = ajaxResp.Title;
                resp.panels = ajaxResp.Panels;
                resp.link = ajaxResp.Link;
                handleRespone(req, resp);
            }
        };
    }

    var neighbourhood = {};
    neighbourhood[link] = [];
    var links = [link];
    function handleRespone(req, resp) {
        var backResp = {};
        backResp.link = link;
        backResp.title = win.document.title;
        backResp.panels = {};
        raiseEvent('postnavigate', req, resp);
        for (var id in resp.panels) {
            var panel = win.document.getElementById(id);
            backResp.panels[id] = panel.innerHTML;
            panel.innerHTML = resp.panels[id];
        }
        raiseEvent('postupdate', req, resp);
        var newLink = resp.link;
        if (link !== newLink) {
            cacheResponse(resp, backResp);
            if (resp.history === 'add')
                win.history.pushState(resp.title, resp.title, newLink);
            if (resp.history === 'replace')
                win.history.replaceState(resp.title, resp.title, newLink);
        }
        win.document.title = resp.title;
        link = newLink;
    }

    function cacheResponse(resp, backResp) {
        var newLink = resp.link;
        cache[link + '&' + newLink] = resp;
        cache[newLink + '&' + link] = backResp;
        if (links.indexOf(newLink) === -1) {
            neighbourhood[newLink] = [];
            links.push(newLink);
        }
        if (neighbourhood[link].indexOf(newLink) === -1) {
            neighbourhood[link].push(newLink);
            neighbourhood[newLink].push(link);
        }
    }

    win.addEventListener('popstate', function (e) {
        var newLink = win.location.pathname + win.location.search;
        if (link !== newLink) {
            var path = getShortestPath(link, newLink);
            if (path) {
                for (var i = 0; i < path.length - 1; i++) {
                    var resp = cache[path[i] + '&' + path[i + 1]];
                    handleRespone(null, resp);
                }
            } else
                refreshAjax(newLink, null, false, null, e.state);
        }
    });

    function getShortestPath(fromLink, toLink) {
        var previous = {};
        var distances = {};
        var unlinks = [];
        var max = links.length;
        for (var i = 0; i < links.length; i++) {
            unlinks.push(links[i]);
            distances[links[i]] = max;
        }
        var distance = distances[fromLink] = 0;
        while (unlinks.length !== 0) {
            distance++;
            var link = unlinks.sort(function (x, y) {
                return distances[x] - distances[y]
            })[0];
            if (link === toLink) {
                var path = [];
                while (toLink) {
                    path.push(toLink);
                    toLink = previous[toLink];
                }
                return path.reverse();
            }
            var neighbours = neighbourhood[link];
            for (var i = 0; i < neighbours.length; i++) {
                var neighbour = neighbours[i];
                if (distances[neighbour] === max) {
                    distances[neighbour] = distance;
                    previous[neighbour] = link;
                }
            }
            unlinks.shift();
        }
        return null;
    }

    var handlers = {};
    function getAddHandler(eventName) {
        return function (handler) {
            if (!handlers[eventName])
                handlers[eventName] = [];
            handlers[eventName].push(handler);
        };
    }

    function raiseEvent(eventName, req, resp) {
        if (!handlers[eventName])
            return;
        for (var i = 0; i < handlers[eventName].length; i++)
            handlers[eventName][i](req, resp);
    }

    win.refreshAjax = {
        navigate: navigate,
        prenavigate: getAddHandler('prenavigate'),
        postnavigate: getAddHandler('postnavigate'),
        postupdate: getAddHandler('postupdate')
};
})(window);<commit_msg>Don't allow request to be cancelled. The ajax can be turned off using data-navigation attribute<commit_after>(function (win) {

    if (!(win.history && win.history.pushState))
        return;

    var submitData = {};
    win.document.addEventListener('click', function (e) {
        var element = e.target;
        var anchor = getAjaxTarget(element, 'A');
        if (!e.ctrlKey && !e.shiftKey && anchor) {
            e.preventDefault();
            refreshAjax(anchor.getAttribute('href'), null, true, anchor);
        }
        if (element.tagName === 'INPUT' && element.name) {
            if (element.type === 'submit')
                submitData[element.name] = element.value;
            if (element.type === 'image') {
                submitData[element.name + '.x'] = win.Math.max(0, e.offsetX);
                submitData[element.name + '.y'] = win.Math.max(0, e.offsetY);
            }
        }
    });

    win.document.addEventListener('submit', function (e) {
        var form = getAjaxTarget(e.target, 'FORM');
        if (form) {
            e.preventDefault();
            refreshAjax(form.getAttribute('action'), getFormData(form), true, form);
        }
    });

    var tagNames = /^INPUT|TEXTAREA|SELECT$/;
    var ignoreTypes = /^button|image|submit|reset|file$/;
    var checkTypes = /^checkbox|radio$/;
    function getFormData(form) {
        var elements = form.elements;
        var data = {};
        for (var i = 0; i < elements.length; i++) {
            var element = elements[i];
            if (tagNames.test(element.tagName) && element.name
                && !ignoreTypes.test(element.type) && !element.disabled
                && (!checkTypes.test(element.type) || element.checked))
                data[element.name] = element.value;
        }
        for (var key in submitData)
            data[key] = submitData[key];
        submitData = {};
        return data;
    }

    function getAjaxTarget(element, tagName) {
        var target = null;
        while (element) {
            if (element.getAttribute) {
                var navigation = element.getAttribute('data-navigation');
                if (!target && element.tagName === tagName && navigation === 'refresh')
                    target = element;
                if (navigation === 'noajax')
                    return null;
            }
            element = element.parentNode;
        }
        return target;
    }

    var link = win.location.pathname + win.location.search;
    function navigate(data, target) {
        refreshAjax(link, data, true, target);
    }

    function refreshAjax(newLink, data, addHistory, target, title) {
        var req = {
            link: newLink,
            data: data,
            target: target,
        };
        raiseEvent('prenavigate', req, null);
        var resp = {
            history: addHistory ? 'add' : null,
            title: title ? title : win.document.title
        };
        var ajaxReq = new win.XMLHttpRequest();
        ajaxReq.onreadystatechange = onReady(ajaxReq, req, resp);
        ajaxReq.open(data ? 'post' : 'get', getAjaxLink(newLink, target));
        if (data)
            ajaxReq.setRequestHeader("Content-Type", "application/json");
        ajaxReq.send(win.JSON.stringify(data));
    }

    function getAjaxLink(baseLink, target) {
        baseLink += baseLink.indexOf('?') > 0 ? '&' : '?';
        baseLink += 'refreshajax=' + win.encodeURIComponent(link);
        baseLink += '&navigation=' + (target ? 'refresh' : 'history');
        if (target) {
            baseLink = setLinkData(target, baseLink, 'include-current');
            baseLink = setLinkData(target, baseLink, 'current-keys');
            baseLink = setLinkData(target, baseLink, 'to-keys');
        }
        return baseLink;
    }

    function setLinkData(target, link, name) {
        var value = target.getAttribute('data-' + name);
        if (value)
            link += '&' + name.replace('-', '') + '=' + win.encodeURIComponent(value);
        return link;
    }

    var cache = {};
    function onReady(ajaxReq, req, resp) {
        var oldLink = link;
        return function () {
            if (ajaxReq.readyState === 4 && ajaxReq.status === 200) {
                var ajaxResp = win.JSON.parse(ajaxReq.responseText);
                if (ajaxResp.RedirectLink) {
                    win.location.href = ajaxResp.RedirectLink;
                    return;
                }
                if (link !== oldLink)
                    return;
                if (ajaxResp.Title)
                    resp.title = ajaxResp.Title;
                resp.panels = ajaxResp.Panels;
                resp.link = ajaxResp.Link;
                handleRespone(req, resp);
            }
        };
    }

    var neighbourhood = {};
    neighbourhood[link] = [];
    var links = [link];
    function handleRespone(req, resp) {
        var backResp = {};
        backResp.link = link;
        backResp.title = win.document.title;
        backResp.panels = {};
        raiseEvent('postnavigate', req, resp);
        for (var id in resp.panels) {
            var panel = win.document.getElementById(id);
            backResp.panels[id] = panel.innerHTML;
            panel.innerHTML = resp.panels[id];
        }
        raiseEvent('postupdate', req, resp);
        var newLink = resp.link;
        if (link !== newLink) {
            cacheResponse(resp, backResp);
            if (resp.history === 'add')
                win.history.pushState(resp.title, resp.title, newLink);
            if (resp.history === 'replace')
                win.history.replaceState(resp.title, resp.title, newLink);
        }
        win.document.title = resp.title;
        link = newLink;
    }

    function cacheResponse(resp, backResp) {
        var newLink = resp.link;
        cache[link + '&' + newLink] = resp;
        cache[newLink + '&' + link] = backResp;
        if (links.indexOf(newLink) === -1) {
            neighbourhood[newLink] = [];
            links.push(newLink);
        }
        if (neighbourhood[link].indexOf(newLink) === -1) {
            neighbourhood[link].push(newLink);
            neighbourhood[newLink].push(link);
        }
    }

    win.addEventListener('popstate', function (e) {
        var newLink = win.location.pathname + win.location.search;
        if (link !== newLink) {
            var path = getShortestPath(link, newLink);
            if (path) {
                for (var i = 0; i < path.length - 1; i++) {
                    var resp = cache[path[i] + '&' + path[i + 1]];
                    handleRespone(null, resp);
                }
            } else
                refreshAjax(newLink, null, false, null, e.state);
        }
    });

    function getShortestPath(fromLink, toLink) {
        var previous = {};
        var distances = {};
        var unlinks = [];
        var max = links.length;
        for (var i = 0; i < links.length; i++) {
            unlinks.push(links[i]);
            distances[links[i]] = max;
        }
        var distance = distances[fromLink] = 0;
        while (unlinks.length !== 0) {
            distance++;
            var link = unlinks.sort(function (x, y) {
                return distances[x] - distances[y]
            })[0];
            if (link === toLink) {
                var path = [];
                while (toLink) {
                    path.push(toLink);
                    toLink = previous[toLink];
                }
                return path.reverse();
            }
            var neighbours = neighbourhood[link];
            for (var i = 0; i < neighbours.length; i++) {
                var neighbour = neighbours[i];
                if (distances[neighbour] === max) {
                    distances[neighbour] = distance;
                    previous[neighbour] = link;
                }
            }
            unlinks.shift();
        }
        return null;
    }

    var handlers = {};
    function getAddHandler(eventName) {
        return function (handler) {
            if (!handlers[eventName])
                handlers[eventName] = [];
            handlers[eventName].push(handler);
        };
    }

    function raiseEvent(eventName, req, resp) {
        if (!handlers[eventName])
            return;
        for (var i = 0; i < handlers[eventName].length; i++)
            handlers[eventName][i](req, resp);
    }

    win.refreshAjax = {
        navigate: navigate,
        prenavigate: getAddHandler('prenavigate'),
        postnavigate: getAddHandler('postnavigate'),
        postupdate: getAddHandler('postupdate')
};
})(window);<|endoftext|>