<commit_before>import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

import baseurl from 'baseurl.js';

axios.defaults.baseURL = baseurl;
axios.defaults.headers.common.Accept = 'application/json';
axios.defaults.timeout = 15000; // 15 seconds

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    drawer: null,
    currentUser: null,
    session_id: null,
    token: localStorage.getItem('token') || null,
    alerts: [
      // { type: 'info', message: 'Info' },
      // { type: 'success', message: 'Success' },
      // { type: 'warning', message: 'Warning' },
      // { type: 'error', message: 'Error' },
    ],
  },

  getters: {
    isAuthenticated(state) {
      return state.token;
    },

    getDrawer(state) {
      return state.drawer;
    },

    getAlerts(state) {
      return state.alerts;
    },
  },

  mutations: {
    SIGN_IN_USER(state, payload) {
      const token = payload.data.token;
      state.token = token;
      localStorage.setItem('token', token);
    },

    SIGN_IN_USER_WITH_TOKEN(state, token) {
      state.token = token;
      localStorage.setItem('token', token);
    },

    SIGN_OUT_USER(state) {
      state.token = null;
      localStorage.clear();
      state.alerts = [];
    },

    SET_ALERT(state, alert) {
      state.alerts.push(alert);
    },

    CLEAR_ALERTS(state) {
      state.alerts = [];
    },

    SET_DRAWER(state, option) {
      state.drawer = option;
    },
  },

  actions: {
    async signUp({ commit, state }, payload) {
      try {
        const response = await axios.post('/api/sign_up', payload);

        commit('SIGN_IN_USER', response);

        return response;
      } catch (error) {
        return error;
      }
    },

    async signIn({ commit, state }, payload) {
      try {
        const response = await axios.post('/api/sign_in', payload);

        commit('SIGN_IN_USER', response);

        return response;
      } catch (error) {
        return error;
      }
    },

    async signOut({ commit, state }) {
      try {
        await axios.delete('/api/sign_out');
      } finally {
        commit('SIGN_OUT_USER');
      }
    },

    async changePassword({ commit, state }, payload) {
      try {
        const response = await axios.post('/api/change_password', payload);

        commit('SIGN_IN_USER_WITH_TOKEN', response.data.token);

        return response;
      } catch (error) {
        return error;
      }
    },

    async requestPasswordReset({ commit, state }, payload) {
      try {
        return await axios.post('/api/request_password_reset', payload);
      } catch (error) {
        return error;
      }
    },

    async resetPassword({ commit, state }, payload) {
      try {
        const response = await axios.post('/api/reset_password', payload);

        commit('SIGN_IN_USER_WITH_TOKEN', response.data.token);

        return response;
      } catch (error) {
        return error;
      }
    },

    async fetchProfile({ commit, state }) {
      try {
        return await axios.get('/api/profile');
      } catch (error) {
        return error;
      }
    },

    async fetchCharacters({ commit, state }, page) {
      try {
        return await axios.get(`/api/characters?page=${page}`);
      } catch (error) {
        return error;
      }
    },

    async fetchCharacter({ commit, state }, id) {
      try {
        return await axios.get(`/api/characters/${id}`);
      } catch (error) {
        return error;
      }
    },

    async destroyCharacter({ commit, state }, id) {
      try {
        return await axios.delete(`/api/characters/${id}`);
      } catch (error) {
        return error;
      }
    },

    // async fetchCharacterLoyaltyPoint ({ commit, state }, id) {
    //     try {
    //         return await axios.get(`/api/characters/${id}/loyalty_points`);
    //     } catch (error) {
    //         return error;
    //     }
    // },

    async fetchUniverseAlliances({ commit, state }, page) {
      try {
        return await axios.get(`/api/eve/alliances?page=${page}`);
      } catch (error) {
        return error;
      }
    },

    async fetchUniverseAlliance({ commit, state }, id) {
      try {
        return await axios.get(`/api/eve/alliances/${id}`);
      } catch (error) {
        return error;
      }
    },

    async fetchUniverseAllianceCharacters({ commit, state }, { id, page }) {
      try {
        return await axios.get(`/api/eve/alliances/${id}/characters?page=${page}`);
      } catch (error) {
        return error;
      }
    },

    async fetchUniverseAllianceCorporations({ commit, state }, { id, page }) {
      try {
        return await axios.get(`/api/eve/alliances/${id}/corporations?page=${page}`);
      } catch (error) {
        return error;
      }
    },

    async fetchUniverseCorporations({ commit, state }, page) {
      try {
        return await axios.get(`/api/eve/corporations?page=${page}`);
      } catch (error) {
        return error;
      }
    },

    async fetchUniverseCorporation({ commit, state }, id) {
      try {
        return await axios.get(`/api/eve/corporations/${id}`);
      } catch (error) {
        return error;
      }
    },

    async fetchUniverseCorporationCharacters({ commit, state }, { id, page }) {
      try {
        return await axios.get(`/api/eve/corporations/${id}/characters?page=${page}`);
      } catch (error) {
        return error;
      }
    },

    async fetchUniverseCharacters({ commit, state }, { page, q }) {
      try {
        return await axios.get(`/api/eve/characters?page=${page}&q=${q}`);
      } catch (error) {
        return error;
      }
    },

    async fetchUniverseCharacter({ commit, state }, id) {
      try {
        return await axios.get(`/api/eve/characters/${id}`);
      } catch (error) {
        return error;
      }
    },

    async fetchUniverseCharacterCorporationsHistory({ commit, state }, { id, page }) {
      try {
        return await axios.get(`/api/eve/characters/${id}/corporations_history?page=${page}`);
      } catch (error) {
        return error;
      }
    },

    async fetchUniverseTypes({ commit, state }, { page, q }) {
      try {
        return await  axios.get(`/api/eve/types?page=${page}&q=${q}`);
      } catch (error) {
        return error;
      }
    },

    async fetchUniverseType({ commit, state }, id) {
      try {
        return await axios.get(`/api/eve/types/${id}`);
      } catch (error) {
        return error;
      }
    },
  },

  strict: process.env.NODE_ENV !== 'production',
});

export default store;

axios.interceptors.request.use((config) => {
  if (store.state.token) {
    config.headers.Authorization = `Bearer ${store.state.token}`;
  }

  return config;
});
<commit_msg>Cleanup<commit_after><|endoftext|>


<commit_before>/**
 * Copyright 2015 IBM Corp. 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.
 */

// security.js
const secure = require('express-secure-only');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');

module.exports = function (app) {
  // 1. redirects http to https
  app.use(secure());

  // 2. helmet with custom CSP header
  const cspReportUrl = '/report-csp-violation';
  app.use(helmet({
    contentSecurityPolicy: {
      // Specify directives as normal.
      directives: {
        defaultSrc: ["'self'"], // default value for unspecified directives that end in -src
        scriptSrc: ["'self'", 'www.google-analytics.com'], // jquery cdn, etc. try to avid "'unsafe-inline'"
        styleSrc: ["'self'", "'unsafe-inline'"], // no inline css
        imgSrc: ["'self'", 'www.google-analytics.com'], // should be "'self'" and possibly 'data:' for most apps
        frameAncestors: [], // parent iframes
        formAction: ["'self'"], // where can forms submit to
        reportUri: cspReportUrl,
      },

      // Set to true if you only want browsers to report errors, not block them.
      // You may also set this to a function(req, res) in order to decide dynamically
      // whether to use reportOnly mode, e.g., to allow for a dynamic kill switch.
      reportOnly: false,

      // Set to true if you want to blindly set all headers: Content-Security-Policy,
      // X-WebKit-CSP, and X-Content-Security-Policy.
      setAllHeaders: false,

      // Set to true if you want to disable CSP on Android where it can be buggy.
      disableAndroid: false,

      // Set to false if you want to completely disable any user-agent sniffing.
      // This may make the headers less compatible but it will be much faster.
      // This defaults to `true`.
      browserSniff: true,
    },
  }));
  // endpoint to report CSP violations
  app.post(cspReportUrl, (req, res) => {
    // eslint-disable-next-line no-console
    console.log('Content Security Policy Violation:\n', req.body);
    res.status(204).send(); // 204 = No Content
  });

  // 4. rate limiting
  const limiter = rateLimit({
    windowMs: 60 * 1000, // seconds
    delayMs: 0,
    max: 10,
    message: JSON.stringify({
      error: 'Too many requests, please try again in 30 seconds.',
      code: 429,
    }),
  });
  app.use('/api/', limiter);
};
<commit_msg>Remove CSP because it's causing problems<commit_after>/**
 * Copyright 2015 IBM Corp. 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.
 */

// security.js
const secure = require('express-secure-only');
const rateLimit = require('express-rate-limit');

module.exports = function (app) {
  // 1. redirects http to https
  app.use(secure());

  // 2. rate limiting
  const limiter = rateLimit({
    windowMs: 60 * 1000, // seconds
    delayMs: 0,
    max: 10,
    message: JSON.stringify({
      error: 'Too many requests, please try again in 30 seconds.',
      code: 429,
    }),
  });
  app.use('/api/', limiter);
};
<|endoftext|>


<commit_before>import { authenticated } from '../../mocks/accounts/graphql-api';
import AccountsServer from '../../mocks/accounts/server';
import { roomPublicFields } from './settings';

export const schema = `
	type Query {
		channels(filter: ChannelFilter = {
			privacy: ALL,
			joinedChannels: false,
			sortBy: NAME
		}): [Channel]
	}
`;

export const resolver = {
	Query: {
		channels: authenticated(AccountsServer, (root, args, { models }) => {
			const query = {};
			const options = {
				sort: {
					name: 1
				},
				fields: roomPublicFields
			};

			// Filter
			if (typeof args.filter !== 'undefined') {
				// sortBy
				if (args.filter.sortBy === 'NUMBER_OF_MESSAGES') {
					options.sort = {
						msgs: -1
					};
				}

				// privacy
				switch (args.filter.privacy) {
					case 'PRIVATE':
						query.t = 'p';
						break;
					case 'PUBLIC':
						query.t = {
							$ne: 'p'
						};
						break;
				}
			}

			return models.Rooms.find(query, options).fetch();
		})
	}
};
<commit_msg>Support nameFilter in channels query<commit_after>import { authenticated } from '../../mocks/accounts/graphql-api';
import AccountsServer from '../../mocks/accounts/server';
import { roomPublicFields } from './settings';

export const schema = `
	type Query {
		channels(filter: ChannelFilter = {
			privacy: ALL,
			joinedChannels: false,
			sortBy: NAME
		}): [Channel]
	}
`;

export const resolver = {
	Query: {
		channels: authenticated(AccountsServer, (root, args, { models }) => {
			const query = {};
			const options = {
				sort: {
					name: 1
				},
				fields: roomPublicFields
			};

			// Filter
			if (typeof args.filter !== 'undefined') {
				// nameFilter
				if (typeof args.filter.nameFilter !== undefined) {
					query.name = {
						$regex: new RegExp(args.filter.nameFilter, 'i')
					};
				}

				// sortBy
				if (args.filter.sortBy === 'NUMBER_OF_MESSAGES') {
					options.sort = {
						msgs: -1
					};
				}

				// privacy
				switch (args.filter.privacy) {
					case 'PRIVATE':
						query.t = 'p';
						break;
					case 'PUBLIC':
						query.t = {
							$ne: 'p'
						};
						break;
				}
			}

			return models.Rooms.find(query, options).fetch();
		})
	}
};
<|endoftext|>


<commit_before>
// polyfills, ...

Function.prototype.bind = function (context) {
    var update = function (array, args) {
        var arrayLength = array.length, length = args.length;
        while (length--)
            array[arrayLength + length] = args[length];
        return array;
    }

    var merge = function (array, args) {
        array = slice.call(array, 0);
        return update(array, args);
    }

    var slice = Array.prototype.slice;

    if (arguments.length < 2 && typeof arguments[0] == "undefined")
        return this;
    var __method = this, args = slice.call(arguments, 1);
    return function() {
        var a = merge(args, arguments);
        return __method.apply(context, a);
    }
};

(function(win, doc){
	if(win.addEventListener)return;		//No need to polyfill

	function docHijack(p){var old = doc[p];doc[p] = function(v){return addListen(old(v))}}
	function addEvent(on, fn, self){
		return (self = this).attachEvent('on' + on, function(e){
			var e = e || win.event;
			e.preventDefault  = e.preventDefault  || function(){e.returnValue = false}
			e.stopPropagation = e.stopPropagation || function(){e.cancelBubble = true}
			fn.call(self, e);
		});
	}
	function addListen(obj, i){
		if(i = obj.length)while(i--)obj[i].addEventListener = addEvent;
		else obj.addEventListener = addEvent;
		return obj;
	}

	addListen([doc, win]);
	if('Element' in win)win.Element.prototype.addEventListener = addEvent;			//IE8
	else{		//IE < 8
		doc.attachEvent('onreadystatechange', function(){addListen(doc.all)});		//Make sure we also init at domReady
		docHijack('getElementsByTagName');
		docHijack('getElementById');
		docHijack('createElement');
		addListen(doc.all);
	}
})(window, document);

/**
 * PIMCORE PDF VIEWER
 */

if (typeof pimcore == "undefined") {
    pimcore = {};
}

pimcore.pdf = function (config) {
    this.id = config["id"];
    this.data = config["data"];

    this.init();
};

pimcore.pdf.prototype.init = function () {

    this.containerEl = document.getElementById(this.id);

    var elements = this.containerEl.getElementsByTagName("div");
    for(var i=0; i<elements.length; i++) {
        this[elements[i].className.replace(/pimcore-/,"").split(" ")[0]] = elements[i];
    }

    // add empty first-page
    this.data.pages.splice(0,0,{
        placeholder: true
    });

    // add pages
    var page, position;
    for(i=0; i<this.data.pages.length; i++) {

        position = "right";
        if(i % 2 == 0) {
            position = "left";
        }

        page = document.createElement("div");
        page.className = "pimcore-pdfPage pimcore-pdfPage-" + position;
        //page.setAttribute("data-page", i);

        this.data.pages[i]["node"] = page;
        this.pdfPages.appendChild(page);
    }

    this.pdfButtonLeft.addEventListener("click", this.prevPage.bind(this), true);
    this.pdfButtonRight.addEventListener("click", this.nextPage.bind(this), true);
    this.pdfFullscreenClose.addEventListener("click", this.closeFullScreen.bind(this), true);
    this.pdfDownload.addEventListener("click", this.download.bind(this), true);

    this.pdfButtonRight.addEventListener("mouseover", this.buttonHover, true);
    this.pdfButtonLeft.addEventListener("mouseover", this.buttonHover, true);
    this.pdfButtonRight.addEventListener("mouseout", this.buttonHoverOut, true);
    this.pdfButtonLeft.addEventListener("mouseout", this.buttonHoverOut, true);

    if(this.data["fullscreen"]) {
        this.pdfZoom.addEventListener("mouseover", this.buttonHover, true);
        this.pdfZoom.addEventListener("mouseout", this.buttonHoverOut, true);
        this.pdfZoom.addEventListener("click", this.zoom.bind(this), true);
    } else {
        this.pdfZoom.style.display = "none";
    }

    this.toPage(1);
    this.calculateDimensions();

    window.setInterval(this.calculateDimensions.bind(this), 1000);

    window.addEventListener("resize", this.calculateDimensions.bind(this), true);
};

pimcore.pdf.prototype.calculateDimensions = function () {

    // zoom button
    this.pdfZoom.style.fontSize = (this.pdfZoom.offsetHeight/1.5) + "px";
    this.pdfZoom.style.lineHeight = (this.pdfZoom.offsetHeight) + "px";

    // arrows
    var buttonWidth = this.pdfButtonRight.offsetWidth;
    if(!buttonWidth) {
        buttonWidth = this.pdfButtonLeft.offsetWidth;
    }

    this.pdfArrowRight.style.borderWidth = Math.round(buttonWidth/3) + "px";
    this.pdfArrowRight.style.marginRight = Math.round(buttonWidth/3) + "px";
    this.pdfArrowLeft.style.borderWidth = Math.round(buttonWidth/3) + "px";
    this.pdfArrowLeft.style.marginLeft = Math.round(buttonWidth/3) + "px";

    // check fullscreen
    if(document.mozFullScreenElement || document.webkitFullScreenElement || document.msFullScreenElement
        || document.fullScreenElement || document.webkitCurrentFullScreenElement || document.currentFullScreenElement
        || document.mozCurrentFullScreenElement || document.msCurrentFullScreenElement) {
        this.containerEl.classList.add("pimcore-pdfFullscreen");
    } else if(this.containerEl.classList && (this.containerEl.requestFullscreen
        || this.containerEl.mozRequestFullScreen || this.containerEl.webkitRequestFullscreen
        || this.containerEl.msRequestFullscreen)) {
        this.containerEl.classList.remove("pimcore-pdfFullscreen");
    }

    var im;
    var maxHeight = window.innerHeight;
    for(var i=0; i<this.data.pages.length; i++) {
        im = this.data.pages[i]["node"].getElementsByTagName("img")[0];
        if(im) {
            im.style.maxHeight = maxHeight + "px";
        }
    }

    // this is because of firefox, maybe there's a better solution for that
    // the problem is that the pdfPageContainer DIV is always 100% wide, although he is floating, ... Chrome & IE works
    /*if(navigator.userAgent.match(/(Firefox)/)) {
        var imgEl;
        for(var i=0; i<this.data.pages.length; i++) {
            if(!this.data.pages[i]["node"].classList.contains("hidden")) {
                imgEl = this.data.pages[i]["node"].getElementsByTagName("img")[0];
                if(imgEl && imgEl.offsetWidth > 50) {
                    imgEl.parentNode.style.width = imgEl.offsetWidth + "px";
                }
            }
        }
    }*/
};

pimcore.pdf.prototype.buttonHover = function () {
    this.style.opacity = "0.8";
};

pimcore.pdf.prototype.buttonHoverOut = function () {
    this.style.opacity = "0.6";
};

pimcore.pdf.prototype.addImageToPage = function (page) {
    var imgContainer, img, hotspot, hd, o, l;

    if(this.data.pages[page] && !this.data.pages[page]["detailLoaded"]) {
        if(this.data.pages[page]["detail"]) {
            imgContainer = document.createElement("div");
            imgContainer.className = "pimcore-pdfPageContainer";
            this.data.pages[page]["node"].appendChild(imgContainer);

            img = document.createElement("img");
            img.setAttribute("src", this.data.pages[page]["detail"]);
            imgContainer.appendChild(img);

            if(this.data.pages[page]["hotspots"] && this.data.pages[page]["hotspots"].length > 0) {
                for(o=0; o<this.data.pages[page]["hotspots"].length; o++) {
                    hd = this.data.pages[page]["hotspots"][o];
                    hotspot = document.createElement("div");
                    hotspot.className = "pimcore-pdfHotspot";
                    hotspot.style.width = hd["width"] + "%";
                    hotspot.style.height = hd["height"] + "%";
                    hotspot.style.top = hd["top"] + "%";
                    hotspot.style.left = hd["left"] + "%";

                    hotspot.addEventListener("mouseover", function () {
                        this.style.opacity = "0.5";
                    }, true);
                    hotspot.addEventListener("mouseout", function () {
                        this.style.opacity = "0.2";
                    }, true);

                    if(hd["data"] && hd["data"].length > 0) {
                        for(l=0; l<hd["data"].length; l++) {
                            if(hd["data"][l]["type"] == "link" && hd["data"][l]["value"]) {
                                hotspot.addEventListener("click", function (data) {
                                    window.open(data["value"]);
                                }.bind(hotspot, hd["data"][l]), true);
                                break;
                            }
                        }
                    }

                    imgContainer.appendChild(hotspot);
                }
            }
        } else {
            this.data.pages[page]["node"].innerHTML = " ";
        }
        this.data.pages[page]["detailLoaded"] = true;
    }
};

pimcore.pdf.prototype.zoom = function () {

    // provide original pdf for mobile users
    if(navigator.userAgent.match(/(iPad|iPhone|Android)/)) {
        this.download();
    } else {
        var elem = this.containerEl;
        if (elem.requestFullscreen) {
          elem.requestFullscreen();
        } else if (elem.mozRequestFullScreen) {
          elem.mozRequestFullScreen();
        } else if (elem.webkitRequestFullscreen) {
          elem.webkitRequestFullscreen();
        }  else if (elem.msRequestFullscreen) {
          elem.msRequestFullscreen();
        } else {
            // fallback
            this.containerEl.originalParent = this.containerEl.parentNode;
            this.containerEl.className = this.containerEl.className + " pimcore-pdfFullscreen";
            document.body.appendChild(this.containerEl);
        }
    }
};

pimcore.pdf.prototype.closeFullScreen = function (page) {
    if(this.containerEl.originalParent) {
        this.containerEl.originalParent.appendChild(this.containerEl);
        this.containerEl.className = this.containerEl.className.replace(/pimcore-pdfFullscreen/,"")
    }

    if (document.cancelFullScreen) {
        document.cancelFullScreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
    }  else if (document.msCancelFullScreen) {
        document.msCancelFullScreen();
    }
};

pimcore.pdf.prototype.download = function () {
    window.open(this.data.pdf);
}

pimcore.pdf.prototype.toPage = function (page) {

    // hide all pages
    for(var i=0; i<this.data.pages.length; i++) {
        if(this.data.pages[i]["node"].className.indexOf("hidden") < 0) {
            this.data.pages[i]["node"].className += " hidden";
        }
    }

    // get first page to show
    while(page % 2 !== 0) {
        page--;
    }

    for(i=page; i<=(page+1); i++) {
        if(this.data.pages[i]) {
            this.data.pages[i]["node"].className  = this.data.pages[i]["node"].className.replace("hidden", "");
        }
    }

    this.currentPage = page;

    if(page < 1) {
        this.pdfButtonLeft.style.display = "none";
    } else {
        this.pdfButtonLeft.style.display = "block";
    }

    if(page >= (this.data.pages.length-2)) {
        this.pdfButtonRight.style.display = "none";
    } else {
        this.pdfButtonRight.style.display = "block";
    }

    // pre-load next x pages
    for(i=page; i<=(page+4); i++) {
        this.addImageToPage(i);
    }

    this.calculateDimensions();
};

pimcore.pdf.prototype.nextPage = function () {
    this.toPage(this.currentPage+3);
};

pimcore.pdf.prototype.prevPage = function () {
    this.toPage(this.currentPage-2);
};

<commit_msg>bugfix if more than one pdf viewer included in a page, the fullscreen mode shows always the last pdf<commit_after>
// polyfills, ...

Function.prototype.bind = function (context) {
    var update = function (array, args) {
        var arrayLength = array.length, length = args.length;
        while (length--)
            array[arrayLength + length] = args[length];
        return array;
    }

    var merge = function (array, args) {
        array = slice.call(array, 0);
        return update(array, args);
    }

    var slice = Array.prototype.slice;

    if (arguments.length < 2 && typeof arguments[0] == "undefined")
        return this;
    var __method = this, args = slice.call(arguments, 1);
    return function() {
        var a = merge(args, arguments);
        return __method.apply(context, a);
    }
};

(function(win, doc){
	if(win.addEventListener)return;		//No need to polyfill

	function docHijack(p){var old = doc[p];doc[p] = function(v){return addListen(old(v))}}
	function addEvent(on, fn, self){
		return (self = this).attachEvent('on' + on, function(e){
			var e = e || win.event;
			e.preventDefault  = e.preventDefault  || function(){e.returnValue = false}
			e.stopPropagation = e.stopPropagation || function(){e.cancelBubble = true}
			fn.call(self, e);
		});
	}
	function addListen(obj, i){
		if(i = obj.length)while(i--)obj[i].addEventListener = addEvent;
		else obj.addEventListener = addEvent;
		return obj;
	}

	addListen([doc, win]);
	if('Element' in win)win.Element.prototype.addEventListener = addEvent;			//IE8
	else{		//IE < 8
		doc.attachEvent('onreadystatechange', function(){addListen(doc.all)});		//Make sure we also init at domReady
		docHijack('getElementsByTagName');
		docHijack('getElementById');
		docHijack('createElement');
		addListen(doc.all);
	}
})(window, document);

/**
 * PIMCORE PDF VIEWER
 */

if (typeof pimcore == "undefined") {
    pimcore = {};
}

pimcore.pdf = function (config) {
    this.id = config["id"];
    this.data = config["data"];

    this.init();
};

pimcore.pdf.prototype.init = function () {

    this.containerEl = document.getElementById(this.id);

    var elements = this.containerEl.getElementsByTagName("div");
    for(var i=0; i<elements.length; i++) {
        this[elements[i].className.replace(/pimcore-/,"").split(" ")[0]] = elements[i];
    }

    // add empty first-page
    this.data.pages.splice(0,0,{
        placeholder: true
    });

    // add pages
    var page, position;
    for(i=0; i<this.data.pages.length; i++) {

        position = "right";
        if(i % 2 == 0) {
            position = "left";
        }

        page = document.createElement("div");
        page.className = "pimcore-pdfPage pimcore-pdfPage-" + position;
        //page.setAttribute("data-page", i);

        this.data.pages[i]["node"] = page;
        this.pdfPages.appendChild(page);
    }

    this.pdfButtonLeft.addEventListener("click", this.prevPage.bind(this), true);
    this.pdfButtonRight.addEventListener("click", this.nextPage.bind(this), true);
    this.pdfFullscreenClose.addEventListener("click", this.closeFullScreen.bind(this), true);
    this.pdfDownload.addEventListener("click", this.download.bind(this), true);

    this.pdfButtonRight.addEventListener("mouseover", this.buttonHover, true);
    this.pdfButtonLeft.addEventListener("mouseover", this.buttonHover, true);
    this.pdfButtonRight.addEventListener("mouseout", this.buttonHoverOut, true);
    this.pdfButtonLeft.addEventListener("mouseout", this.buttonHoverOut, true);

    if(this.data["fullscreen"]) {
        this.pdfZoom.addEventListener("mouseover", this.buttonHover, true);
        this.pdfZoom.addEventListener("mouseout", this.buttonHoverOut, true);
        this.pdfZoom.addEventListener("click", this.zoom.bind(this), true);
    } else {
        this.pdfZoom.style.display = "none";
    }

    this.toPage(1);
    this.calculateDimensions();

    window.setInterval(this.calculateDimensions.bind(this), 1000);

    window.addEventListener("resize", this.calculateDimensions.bind(this), true);
};

pimcore.pdf.prototype.calculateDimensions = function () {

    // zoom button
    this.pdfZoom.style.fontSize = (this.pdfZoom.offsetHeight/1.5) + "px";
    this.pdfZoom.style.lineHeight = (this.pdfZoom.offsetHeight) + "px";

    // arrows
    var buttonWidth = this.pdfButtonRight.offsetWidth;
    if(!buttonWidth) {
        buttonWidth = this.pdfButtonLeft.offsetWidth;
    }

    this.pdfArrowRight.style.borderWidth = Math.round(buttonWidth/3) + "px";
    this.pdfArrowRight.style.marginRight = Math.round(buttonWidth/3) + "px";
    this.pdfArrowLeft.style.borderWidth = Math.round(buttonWidth/3) + "px";
    this.pdfArrowLeft.style.marginLeft = Math.round(buttonWidth/3) + "px";

    // check fullscreen
    if(document.mozFullScreenElement || document.webkitFullScreenElement || document.msFullScreenElement
        || document.fullScreenElement || document.webkitCurrentFullScreenElement || document.currentFullScreenElement
        || document.mozCurrentFullScreenElement || document.msCurrentFullScreenElement) {

    } else if(this.containerEl.classList && (this.containerEl.requestFullscreen
        || this.containerEl.mozRequestFullScreen || this.containerEl.webkitRequestFullscreen
        || this.containerEl.msRequestFullscreen)) {
        this.containerEl.classList.remove("pimcore-pdfFullscreen");
    }

    var im;
    var maxHeight = window.innerHeight;
    for(var i=0; i<this.data.pages.length; i++) {
        im = this.data.pages[i]["node"].getElementsByTagName("img")[0];
        if(im) {
            im.style.maxHeight = maxHeight + "px";
        }
    }

    // this is because of firefox, maybe there's a better solution for that
    // the problem is that the pdfPageContainer DIV is always 100% wide, although he is floating, ... Chrome & IE works
    /*if(navigator.userAgent.match(/(Firefox)/)) {
        var imgEl;
        for(var i=0; i<this.data.pages.length; i++) {
            if(!this.data.pages[i]["node"].classList.contains("hidden")) {
                imgEl = this.data.pages[i]["node"].getElementsByTagName("img")[0];
                if(imgEl && imgEl.offsetWidth > 50) {
                    imgEl.parentNode.style.width = imgEl.offsetWidth + "px";
                }
            }
        }
    }*/
};

pimcore.pdf.prototype.buttonHover = function () {
    this.style.opacity = "0.8";
};

pimcore.pdf.prototype.buttonHoverOut = function () {
    this.style.opacity = "0.6";
};

pimcore.pdf.prototype.addImageToPage = function (page) {
    var imgContainer, img, hotspot, hd, o, l;

    if(this.data.pages[page] && !this.data.pages[page]["detailLoaded"]) {
        if(this.data.pages[page]["detail"]) {
            imgContainer = document.createElement("div");
            imgContainer.className = "pimcore-pdfPageContainer";
            this.data.pages[page]["node"].appendChild(imgContainer);

            img = document.createElement("img");
            img.setAttribute("src", this.data.pages[page]["detail"]);
            imgContainer.appendChild(img);

            if(this.data.pages[page]["hotspots"] && this.data.pages[page]["hotspots"].length > 0) {
                for(o=0; o<this.data.pages[page]["hotspots"].length; o++) {
                    hd = this.data.pages[page]["hotspots"][o];
                    hotspot = document.createElement("div");
                    hotspot.className = "pimcore-pdfHotspot";
                    hotspot.style.width = hd["width"] + "%";
                    hotspot.style.height = hd["height"] + "%";
                    hotspot.style.top = hd["top"] + "%";
                    hotspot.style.left = hd["left"] + "%";

                    hotspot.addEventListener("mouseover", function () {
                        this.style.opacity = "0.5";
                    }, true);
                    hotspot.addEventListener("mouseout", function () {
                        this.style.opacity = "0.2";
                    }, true);

                    if(hd["data"] && hd["data"].length > 0) {
                        for(l=0; l<hd["data"].length; l++) {
                            if(hd["data"][l]["type"] == "link" && hd["data"][l]["value"]) {
                                hotspot.addEventListener("click", function (data) {
                                    window.open(data["value"]);
                                }.bind(hotspot, hd["data"][l]), true);
                                break;
                            }
                        }
                    }

                    imgContainer.appendChild(hotspot);
                }
            }
        } else {
            this.data.pages[page]["node"].innerHTML = " ";
        }
        this.data.pages[page]["detailLoaded"] = true;
    }
};

pimcore.pdf.prototype.zoom = function () {

    // provide original pdf for mobile users
    if(navigator.userAgent.match(/(iPad|iPhone|Android)/)) {
        this.download();
    } else {
        var elem = this.containerEl;
        elem.classList.add("pimcore-pdfFullscreen");
        if (elem.requestFullscreen) {
          elem.requestFullscreen();
        } else if (elem.mozRequestFullScreen) {
          elem.mozRequestFullScreen();
        } else if (elem.webkitRequestFullscreen) {
          elem.webkitRequestFullscreen();
        }  else if (elem.msRequestFullscreen) {
          elem.msRequestFullscreen();
        } else {
            // fallback
            this.containerEl.originalParent = this.containerEl.parentNode;
            document.body.appendChild(this.containerEl);
        }
    }
};

pimcore.pdf.prototype.closeFullScreen = function (page) {
    if(this.containerEl.originalParent) {
        this.containerEl.originalParent.appendChild(this.containerEl);
        this.containerEl.className = this.containerEl.className.replace(/pimcore-pdfFullscreen/,"")
    }

    if (document.cancelFullScreen) {
        document.cancelFullScreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
    }  else if (document.msCancelFullScreen) {
        document.msCancelFullScreen();
    }
};

pimcore.pdf.prototype.download = function () {
    window.open(this.data.pdf);
}

pimcore.pdf.prototype.toPage = function (page) {

    // hide all pages
    for(var i=0; i<this.data.pages.length; i++) {
        if(this.data.pages[i]["node"].className.indexOf("hidden") < 0) {
            this.data.pages[i]["node"].className += " hidden";
        }
    }

    // get first page to show
    while(page % 2 !== 0) {
        page--;
    }

    for(i=page; i<=(page+1); i++) {
        if(this.data.pages[i]) {
            this.data.pages[i]["node"].className  = this.data.pages[i]["node"].className.replace("hidden", "");
        }
    }

    this.currentPage = page;

    if(page < 1) {
        this.pdfButtonLeft.style.display = "none";
    } else {
        this.pdfButtonLeft.style.display = "block";
    }

    if(page >= (this.data.pages.length-2)) {
        this.pdfButtonRight.style.display = "none";
    } else {
        this.pdfButtonRight.style.display = "block";
    }

    // pre-load next x pages
    for(i=page; i<=(page+4); i++) {
        this.addImageToPage(i);
    }

    this.calculateDimensions();
};

pimcore.pdf.prototype.nextPage = function () {
    this.toPage(this.currentPage+3);
};

pimcore.pdf.prototype.prevPage = function () {
    this.toPage(this.currentPage-2);
};

<|endoftext|>


<commit_before>(function($) {
  'use strict';

  $(document).ready(function() {

    var last = 0;
    $(this).on("mousemove", function(e) {
      if (e.timeStamp > last + 500) {
        console.log(e)
        var w = window.innerWidth;
        var h = window.innerHeight;
        var wP = 40 * (e.clientX / w * 0.15 + 0.75);
        var hP = 40 * (e.clientY / h * 0.15 + 0.75);
        last = e.timeStamp;
        //$(".background").css("background-position", wP + "% " + hP + "%");
      }
    });
  });
})($);<commit_msg>organize js handler<commit_after>(function($) {
  'use strict';

  function EventHandler() {
    var navbarOpen = false;

    $(".nav-toggle").click(function() {
      if (navbarOpen) {
        navbarOpen = false;

      } else {
        navbarOpen = true;
      }
    });
  }

  $(document).ready(function() {
    var handler = new EventHandler();

  });
})($);<|endoftext|>


<commit_before>// Eudeba epub uploader
$(function() {

    uploadForm = $("form[name=csv-file-upload]");

    // From http://stackoverflow.com/a/16086380
    //    uploadForm.submit( function() {
    uploadForm.bind("submit", function (event) {

alert('submitting...');
        var formData = new FormData($(this)[0]);

        $.ajax({

            url:         $(this).attr("action"),
            type:        'POST',
            data:        formData,
            async:       false,
            success:     function (data) {
alert('done! result:\r\n\r\n' + data);
                        // location.reload();
            },
            cache:       false,
            contentType: false,
            processData: false
        });

        return false;
    });

});
<commit_msg>Clean up code a bit, join to rename file<commit_after>// Benford's Law analyzer
$(function() {
    uploader();
});

// Bind to an upload form,
function uploader() {
    uploadForm = $("form[name=csv-file-upload]");

    // From http://stackoverflow.com/a/16086380
    //    uploadForm.submit( function() {
    uploadForm.bind("submit", function (event) {

        var formData = new FormData($(this)[0]);

        $.ajax({

            url:         $(this).attr("action"),
            type:        'POST',
            data:        formData,
            async:       false,
            success:     function (data) {
                        // location.reload();
                        fillColumns();
            },
            cache:       false,
            contentType: false,
            processData: false
        });

        return false;
    });

}

function fillColumns(){
    // Find classes not belonging to tinyMCE
    // Split the classes from original stylesheets and from eudeba.css

    var cssFrom = $('#css-from');
    for(var i in sheets) {
        var option = '<option value="' + selector + '">'
                + sheetName + ': ' + selector + '</option>\r\n'
        cssFrom.append($(option));
    }
}
<|endoftext|>


<commit_before>document.addEventListener('deviceready',function(){
    /* USEFUL STUFF:
     * https://developer.mozilla.org/en-US/docs/Web/API/FileError#Error_codes
     */
    var fail = function(e){
        navigator.notification.alert("oh dear, something went wrong :(",function(){},"File Persistance","OK");
        console.log("oh dear, something went wrong :(");
    };
    var filePersist = new FilePersist();
    var myExampleDirName = "exampleDir";
    var myExampleFileName = "exampleFile";

//    filePersist.getDir(cordova.file.dataDirectory,function(dataDir){
//        filePersist.getDir(dataDir,function(myExampleDir){
//            var objToSave = {
//                "string": "hello",
//                "boolean": true,
//                "int": 1,
//                "array": ["test","test2"]
//            };
//            var success = function(){
//                navigator.notification.alert("Object successfully saved to fileSystem",function(){},"File Persistance","OK");
//                console.log("Object successfully saved to fileSystem");
//                filePersist.getFileContents(myExampleDir,myExampleFileName,function(obj){
//                    navigator.notification.alert("The console log is now displaying what we just saved...",function(){},"File Persistance","OK");
//                    console.log("What is in "+myExampleDir.nativeURL+myExampleFileName);
//                    console.log(obj);
//                },fail,filePersist.options.createIfDoesNotExist);
//            };
//            filePersist.setFileContents(myExampleDir,myExampleFileName,objToSave,fail,success,filePersist.options.createIfDoesNotExist);
//        },fail,myExampleDirName,filePersist.options.createIfDoesNotExist);
//    },fail);

},false);
<commit_msg>* wp8 again<commit_after>document.addEventListener('deviceready',function(){
    /* USEFUL STUFF:
     * https://developer.mozilla.org/en-US/docs/Web/API/FileError#Error_codes
     */
    var fail = function(e){
        navigator.notification.alert("oh dear, something went wrong :(",function(){},"File Persistance","OK");
        console.log("oh dear, something went wrong :(");
    };
    var filePersist = new FilePersist();
    var myExampleDirName = "exampleDir";
    var myExampleFileName = "exampleFile";
    filePersist.getDir(cordova.file.dataDirectory,function(dataDir){
        filePersist.getDir(dataDir,function(myExampleDir){
            var objToSave = {
                "string": "hello",
                "boolean": true,
                "int": 1,
                "array": ["test","test2"]
            };
            var success = function(){
                navigator.notification.alert("Object successfully saved to fileSystem",function(){},"File Persistance","OK");
                console.log("Object successfully saved to fileSystem");
                filePersist.getFileContents(myExampleDir,myExampleFileName,function(obj){
                    navigator.notification.alert("The console log is now displaying what we just saved...",function(){},"File Persistance","OK");
                    console.log("What is in "+myExampleDir.nativeURL+myExampleFileName);
                    console.log(obj);
                },fail,filePersist.options.createIfDoesNotExist);
            };
            filePersist.setFileContents(myExampleDir,myExampleFileName,objToSave,fail,success,filePersist.options.createIfDoesNotExist);
        },fail,myExampleDirName,filePersist.options.createIfDoesNotExist);
    },fail);

},false);
<|endoftext|>


<commit_before>'use strict';
module.exports =
class IPInfo {
    constructor() {
        this.ipinfo = require('ipinfo');
    }

    sendPlainTextResponse(res, payload) {
        this.ipinfo(payload.text, function (err, info) {
            if (err) {
                res.status(500).send(err);
            } else {
                res.send(info);
            }
        });
    }

    sendPrettyResponse(res, payload) {
        let superagent = require('superagent'),
            querystring = require('querystring'),
            self = this;
        const WEBHOOK = process.env.WEBHOOK;
        const MAPS_KEY = process.env.MAPS_KEY;

        this.ipinfo(payload.text, function (err, info) {
            if (err) {
                res.status(500).send(err);
            } else {
                let fields = [],
                    message = {
                        username: 'IPInfo',
                        icon_url: 'http://vignette1.wikia.nocookie.net/cowboybebop/images/c/cd/6_Ein1.png/revision/latest?cb=20091209161501',
                        channel: payload.channel_id || '@slackbot',
                        attachments: [{
                            title: "IP Info for " + info.ip,
                            title_link: "http://ipinfo.io/" + info.ip,
                            fields: fields
                        }]
                    },
                    addField = function addField(title, value) {
                        if (value) {
                            fields.push({
                                title: title,
                                value: value,
                                short: true
                            });
                        }
                    };

                addField('City', info.city);
                addField('Region', info.region);
                addField('Postal', info.postal);
                addField('Country', info.country);
                addField('Hostname', info.hostname);
                addField('Organiziation', info.org);

                if (info.loc) {
                    message.attachments[0].image_url = "https://maps.googleapis.com/maps/api/staticmap?" + querystring.stringify({
                            center: info.loc,
                            size: '400x125',
                            zoom: '9',
                            key: MAPS_KEY
                        });
                }

                console.log('posting message', message);

                superagent.post(WEBHOOK, message, function (err) {
                    if (err) {
                        console.log('Error posting to slack!', err.toString());
                        self.sendPlainTextResponse(res, payload);
                    } else {
                        res.status(200).end();
                    }
                });
            }
        });
    }
}
<commit_msg>some tweaks<commit_after>'use strict';
module.exports =
class IPInfo {
    constructor() {
        this.ipinfo = require('ipinfo');
    }

    sendPlainTextResponse(res, payload) {
        this.ipinfo(payload.text, function (err, info) {
            if (err) {
                res.status(500).send(err);
            } else {
                res.send(info);
            }
        });
    }

    sendPrettyResponse(res, payload) {
        let superagent = require('superagent'),
            querystring = require('querystring'),
            self = this;
        const WEBHOOK = process.env.WEBHOOK;
        const MAPS_KEY = process.env.MAPS_KEY;

        this.ipinfo(payload.text, function (err, info) {
            if (err) {
                res.status(500).send(err);
            } else {
                let fields = [],
                    message = {
                        username: 'IPInfo',
                        icon_url: 'http://vignette1.wikia.nocookie.net/cowboybebop/images/c/cd/6_Ein1.png/revision/latest?cb=20091209161501',
                        channel: payload.channel_id || '@slackbot',
                        attachments: [{
                            title: "IP Info for " + info.ip,
                            title_link: "http://ipinfo.io/" + info.ip,
                            fields: fields
                        }]
                    },
                    addField = function addField(title, value) {
                        if (value) {
                            fields.push({
                                title: title,
                                value: value,
                                short: true
                            });
                        }
                    };

                addField('City', info.city);
                addField('Region', info.region);
                addField('Postal', info.postal);
                addField('Country', info.country);
                addField('Hostname', info.hostname);
                addField('Organiziation', info.org);

                if (info.loc) {
                    message.attachments.push({
                        image_url: "https://maps.googleapis.com/maps/api/staticmap?" + querystring.stringify({
                            center: info.loc,
                            //size: '400x125',
                            size: '640x200',
                            zoom: '9',
                            key: MAPS_KEY
                        })
                    });
                }

                console.log('posting message', message);

                superagent.post(WEBHOOK, message, function (err) {
                    if (err) {
                        console.log('Error posting to slack!', err.toString());
                        self.sendPlainTextResponse(res, payload);
                    } else {
                        res.status(200).end();
                    }
                });
            }
        });
    }
}
<|endoftext|>


<commit_before><commit_msg>removed export for now, as it's not compiling properly<commit_after><|endoftext|>


<commit_before>import React, { useMemo } from 'react';
import { BackHeader, BaselineAlignment, auth, Select, Option, Row } from 'strapi-helper-plugin';
import { Padded, Text } from '@buffetjs/core';
import { Col } from 'reactstrap';
import { useHistory } from 'react-router-dom';
import { get } from 'lodash';
import { useIntl } from 'react-intl';
import ContainerFluid from '../../components/ContainerFluid';
import PageTitle from '../../components/PageTitle';
import SizedInput from '../../components/SizedInput';
import { Header } from '../../components/Settings';
import { useSettingsForm } from '../../hooks';
import { form, schema } from './utils';
import useChangeLanguage from '../LanguageProvider/hooks/useChangeLanguage';
import { languages, languageNativeNames } from '../../i18n';
import { Title, ProfilePageLabel } from './components';
import Bloc from '../../components/Bloc';

const ProfilePage = () => {
  const { goBack } = useHistory();
  const changeLanguage = useChangeLanguage();
  const { formatMessage } = useIntl();

  const onSubmitSuccessCb = data => {
    changeLanguage(data.preferedLanguage);
    auth.setUserInfo(data);
  };

  const [
    { formErrors, initialData, isLoading, modifiedData, showHeaderLoader, showHeaderButtonLoader },
    // eslint-disable-next-line no-unused-vars
    _,
    { handleCancel, handleChange, handleSubmit, setField },
  ] = useSettingsForm('/admin/users/me', schema, onSubmitSuccessCb, [
    'email',
    'firstname',
    'lastname',
    'username',
    'preferedLanguage',
  ]);

  const headerLabel = useMemo(() => {
    const userInfos = auth.getUserInfo();

    if (modifiedData) {
      return modifiedData.username || `${modifiedData.firstname} ${modifiedData.lastname}`;
    }

    return userInfos.username || `${userInfos.firstname} ${userInfos.lastname}`;
  }, [modifiedData]);

  return (
    <form onSubmit={handleSubmit}>
      <PageTitle title="User profile" />
      <BackHeader onClick={goBack} />

      <BaselineAlignment top size="2px" />

      <ContainerFluid padding="18px 30px 0 30px">

      </ContainerFluid>

      <BaselineAlignment top size="5px" />

      {/* Experience block */}
      <Padded size="md" left right bottom>
        <Bloc isLoading={isLoading}>
          <Padded size="sm" top left right bottom>
            <Col>
              <Padded size="sm" top bottom>
                <Title>
                  {formatMessage({ id: 'Settings.profile.form.section.profile.title' })}
                </Title>
              </Padded>
            </Col>

            <BaselineAlignment top size="9px" />

            <Row>
              {Object.keys(form).map(key => (
                <SizedInput
                  {...form[key]}
                  key={key}
                  error={formErrors[key]}
                  name={key}
                  onChange={handleChange}
                  value={get(modifiedData, key, '')}
                />
              ))}
            </Row>
          </Padded>
        </Bloc>
      </Padded>

      <BaselineAlignment top size="13px" />

      {/* Password block */}
      <Padded size="md" left right bottom>
        <Bloc>
          <Padded size="sm" top left right bottom>
            <Col>
              <Padded size="sm" top bottom>
                <Title>
                  {formatMessage({ id: 'Settings.profile.form.section.password.title' })}
                </Title>
              </Padded>
            </Col>

            <BaselineAlignment top size="9px" />

            <Row>
              <SizedInput
                label="Auth.form.password.label"
                type="password"
                autoComplete="new-password"
                validations={{}}
                error={formErrors.password}
                name="password"
                onChange={handleChange}
                value={get(modifiedData, 'password', '')}
              />

              <SizedInput
                label="Auth.form.confirmPassword.label"
                type="password"
                validations={{}}
                error={formErrors.confirmPassword}
                name="confirmPassword"
                onChange={handleChange}
                value={get(modifiedData, 'confirmPassword', '')}
              />
            </Row>
          </Padded>
        </Bloc>
      </Padded>

      <BaselineAlignment top size="13px" />

      {/* Interface block */}
      <Padded size="md" left right bottom>
        <Bloc>
          <Padded size="sm" top left right bottom>
            <Col>
              <Padded size="sm" top bottom>
                <Title>
                  {formatMessage({ id: 'Settings.profile.form.section.experience.title' })}
                </Title>
              </Padded>
            </Col>

            <BaselineAlignment top size="7px" />

              <ProfilePageLabel htmlFor="">
                {formatMessage({
                  id: 'Settings.profile.form.section.experience.interfaceLanguage',
                })}
              </ProfilePageLabel>

              <Select
                aria-labelledby="interface-language"
                selectedValue={get(modifiedData, 'preferedLanguage')}
                onChange={nextLocaleCode => setField('preferedLanguage', nextLocaleCode)}
              >
                {languages.map(language => {
                  const langName = languageNativeNames[language];

                  return (
                    <Option value={language} key={language}>
                      {langName}
                    </Option>
                  );
                })}
              </Select>

              <Padded size="sm" top bottom>
                <Text color="grey">
                  {formatMessage({
                    id: 'Settings.profile.form.section.experience.interfaceLanguage.hint',
                  })}
                </Text>
              </Padded>

          </Padded>
        </Bloc>
      </Padded>
    </form>
  );
};

export default ProfilePage;
<commit_msg>Add spacing at the bottom of the user profile page (#9886)<commit_after>import React, { useMemo } from 'react';
import { BackHeader, BaselineAlignment, auth, Select, Option, Row } from 'strapi-helper-plugin';
import { Padded, Text } from '@buffetjs/core';
import { Col } from 'reactstrap';
import { useHistory } from 'react-router-dom';
import { get } from 'lodash';
import { useIntl } from 'react-intl';
import ContainerFluid from '../../components/ContainerFluid';
import PageTitle from '../../components/PageTitle';
import SizedInput from '../../components/SizedInput';
import { Header } from '../../components/Settings';
import { useSettingsForm } from '../../hooks';
import { form, schema } from './utils';
import useChangeLanguage from '../LanguageProvider/hooks/useChangeLanguage';
import { languages, languageNativeNames } from '../../i18n';
import { Title, ProfilePageLabel } from './components';
import Bloc from '../../components/Bloc';

const ProfilePage = () => {
  const { goBack } = useHistory();
  const changeLanguage = useChangeLanguage();
  const { formatMessage } = useIntl();

  const onSubmitSuccessCb = data => {
    changeLanguage(data.preferedLanguage);
    auth.setUserInfo(data);
  };

  const [
    { formErrors, initialData, isLoading, modifiedData, showHeaderLoader, showHeaderButtonLoader },
    // eslint-disable-next-line no-unused-vars
    _,
    { handleCancel, handleChange, handleSubmit, setField },
  ] = useSettingsForm('/admin/users/me', schema, onSubmitSuccessCb, [
    'email',
    'firstname',
    'lastname',
    'username',
    'preferedLanguage',
  ]);

  const headerLabel = useMemo(() => {
    const userInfos = auth.getUserInfo();

    if (modifiedData) {
      return modifiedData.username || `${modifiedData.firstname} ${modifiedData.lastname}`;
    }

    return userInfos.username || `${userInfos.firstname} ${userInfos.lastname}`;
  }, [modifiedData]);

  return (
    <form onSubmit={handleSubmit}>
      <PageTitle title="User profile" />
      <BackHeader onClick={goBack} />

      <BaselineAlignment top size="2px" />

      <ContainerFluid padding="18px 30px 0 30px">

      </ContainerFluid>

      <BaselineAlignment top size="5px" />

      {/* Experience block */}
      <Padded size="md" left right bottom>
        <Bloc isLoading={isLoading}>
          <Padded size="sm" top left right bottom>
            <Col>
              <Padded size="sm" top bottom>
                <Title>
                  {formatMessage({ id: 'Settings.profile.form.section.profile.title' })}
                </Title>
              </Padded>
            </Col>

            <BaselineAlignment top size="9px" />

            <Row>
              {Object.keys(form).map(key => (
                <SizedInput
                  {...form[key]}
                  key={key}
                  error={formErrors[key]}
                  name={key}
                  onChange={handleChange}
                  value={get(modifiedData, key, '')}
                />
              ))}
            </Row>
          </Padded>
        </Bloc>
      </Padded>

      <BaselineAlignment top size="13px" />

      {/* Password block */}
      <Padded size="md" left right bottom>
        <Bloc>
          <Padded size="sm" top left right bottom>
            <Col>
              <Padded size="sm" top bottom>
                <Title>
                  {formatMessage({ id: 'Settings.profile.form.section.password.title' })}
                </Title>
              </Padded>
            </Col>

            <BaselineAlignment top size="9px" />

            <Row>
              <SizedInput
                label="Auth.form.password.label"
                type="password"
                autoComplete="new-password"
                validations={{}}
                error={formErrors.password}
                name="password"
                onChange={handleChange}
                value={get(modifiedData, 'password', '')}
              />

              <SizedInput
                label="Auth.form.confirmPassword.label"
                type="password"
                validations={{}}
                error={formErrors.confirmPassword}
                name="confirmPassword"
                onChange={handleChange}
                value={get(modifiedData, 'confirmPassword', '')}
              />
            </Row>
          </Padded>
        </Bloc>
      </Padded>

      <BaselineAlignment top size="13px" />

      {/* Interface block */}
      <Padded size="md" left right bottom>
        <Bloc>
          <Padded size="sm" top left right bottom>
            <Col>
              <Padded size="sm" top bottom>
                <Title>
                  {formatMessage({ id: 'Settings.profile.form.section.experience.title' })}
                </Title>
              </Padded>
            </Col>

            <BaselineAlignment top size="7px" />

              <ProfilePageLabel htmlFor="">
                {formatMessage({
                  id: 'Settings.profile.form.section.experience.interfaceLanguage',
                })}
              </ProfilePageLabel>

              <Select
                aria-labelledby="interface-language"
                selectedValue={get(modifiedData, 'preferedLanguage')}
                onChange={nextLocaleCode => setField('preferedLanguage', nextLocaleCode)}
              >
                {languages.map(language => {
                  const langName = languageNativeNames[language];

                  return (
                    <Option value={language} key={language}>
                      {langName}
                    </Option>
                  );
                })}
              </Select>

              <Padded size="sm" top bottom>
                <Text color="grey">
                  {formatMessage({
                    id: 'Settings.profile.form.section.experience.interfaceLanguage.hint',
                  })}
                </Text>
              </Padded>

          </Padded>
        </Bloc>
      </Padded>

      <BaselineAlignment top size="80px" />
    </form>
  );
};

export default ProfilePage;
<|endoftext|>


<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.settings.website");
pimcore.settings.website = Class.create({

    initialize:function () {

        this.getTabPanel();
    },

    activate:function () {
        var tabPanel = Ext.getCmp("pimcore_panel_tabs");
        tabPanel.setActiveItem("pimcore_website_settings");
    },

    getTabPanel:function () {

        if (!this.panel) {
            this.panel = new Ext.Panel({
                id:"pimcore_website_settings",
                title: t('website_settings'),
                iconCls: "pimcore_icon_website",
                border:false,
                layout:"fit",
                closable:true,
                items:[this.getRowEditor()]
            });

            var tabPanel = Ext.getCmp("pimcore_panel_tabs");
            tabPanel.add(this.panel);
            tabPanel.setActiveItem("pimcore_website_settings");

            this.panel.on("destroy", function () {
                pimcore.globalmanager.remove("settings_website");
            }.bind(this));

            pimcore.layout.refresh();
        }

        return this.panel;
    },

    getRowEditor:function () {

        var itemsPerPage = 20;
        var url = '/admin/settings/website-settings?';

        this.store = pimcore.helpers.grid.buildDefaultStore(
            url,
            [
                "id", 'name','type',
                {name: "data"},
                {name: 'siteId', allowBlank: true},
                {name: 'creationDate', allowBlank: true},
                {name: 'modificationDate', allowBlank: true}

            ],
            itemsPerPage
        );

        this.store.addListener('exception', function (proxy, response, operation) {
                Ext.MessageBox.show({
                    title: 'REMOTE EXCEPTION',
                    msg: operation.getError(),
                    icon: Ext.MessageBox.ERROR,
                    buttons: Ext.Msg.OK
                });
            }
        );
        this.store.setAutoSync(true);

        this.filterField = new Ext.form.TextField({
            width: 200,
            style: "margin: 0 10px 0 0;",
            enableKeyEvents:true,
            listeners:{
                "keydown":function (field, key) {
                    if (key.getKey() == key.ENTER) {
                        var input = field;
                        var proxy = this.store.getProxy();
                        proxy.extraParams.filter = input.getValue();
                        this.store.load();
                    }
                }.bind(this)
            }
        });

        this.pagingtoolbar = pimcore.helpers.grid.buildDefaultPagingToolbar(this.store, itemsPerPage);

        var typesColumns = [
            {
                header: t("type"),
                dataIndex: 'type',
                editable: false,
                width: 40,
                renderer: this.getTypeRenderer.bind(this),
                sortable: true
            },
            {
                header: t("name"),
                dataIndex: 'name',
                width: 200,
                editor: new Ext.form.TextField({
                    allowBlank: false
                }),
                sortable: true
            },
            {
                header: t("value"),
                dataIndex: 'data',
                flex: 10,
                getEditor: this.getCellEditor.bind(this),
                editable: true,
                renderer: this.getCellRenderer.bind(this),
                listeners: {
                    "mousedown": this.cellMousedown.bind(this)
                }
            },
            {header: t("site"), width: 250, sortable:true, dataIndex: "siteId",
                editor: new Ext.form.ComboBox({
                        store: pimcore.globalmanager.get("sites"),
                        valueField: "id",
                        displayField: "domain",
                        triggerAction: "all"
                }),
                renderer: function (siteId) {
                    var store = pimcore.globalmanager.get("sites");
                    var pos = store.findExact("id", siteId);
                    if(pos >= 0) {
                        var val = store.getAt(pos).get("domain");
                        return val;
                    }
                    return null;
                }
            }
            ,
            {header: t("creationDate"), sortable: true, dataIndex: 'creationDate', editable: false,
                hidden: true,
                renderer: function(d) {
                    if (d !== undefined) {
                        var date = new Date(d * 1000);
                        return Ext.Date.format(date, "Y-m-d H:i:s");
                    } else {
                        return "";
                    }
                }
            }
            ,
            {header: t("modificationDate"), sortable: true, dataIndex: 'modificationDate', editable: false,
                hidden: true,
                renderer: function(d) {
                    if (d !== undefined) {
                        var date = new Date(d * 1000);
                        return Ext.Date.format(date, "Y-m-d H:i:s");
                    } else {
                        return "";
                    }
                }
            }
            ,
            {
                xtype:'actioncolumn',
                width:40,
                tooltip:t('empty'),
                icon: "/pimcore/static/img/icon/bin_empty.png",
                handler:function (grid, rowIndex) {
                    grid.getStore().getAt(rowIndex).set("data","");
                }.bind(this)

            }
            ,
            {
                xtype:'actioncolumn',
                width:40,
                tooltip:t('delete'),
                icon:"/pimcore/static/img/icon/cross.png",
                handler:function (grid, rowIndex) {
                    grid.getStore().removeAt(rowIndex);
                }.bind(this)
            }
        ];

        var propertyTypes = new Ext.data.SimpleStore({
            fields: ['id', 'name'],
            data: [
                ["text", "Text"],
                ["document", "Document"],
                ["asset", "Asset"],
                ["object", "Object"],
                ["bool", "Checkbox"]
            ]
        });

        this.customKeyField = new Ext.form.TextField({
            name: 'key',
            emptyText: t('key')
        });

        var customType = new Ext.form.ComboBox({
            fieldLabel: t('type'),
            name: "type",
            valueField: "id",
            displayField:'name',
            store: propertyTypes,
            editable: false,
            triggerAction: 'all',
            mode: "local",
            listWidth: 200,
            hideLabel: true,
            emptyText: t('type')
        });

        this.cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1,
            listeners: {
                beforeedit: function(editor, context, eOpts) {
                    console.log("before edit");
                    //need to clear cached editors of cell-editing editor in order to
                    //enable different editors per row
                    editor.editors.each(Ext.destroy, Ext);
                    editor.editors.clear();
                }
            }
        });

        this.grid = Ext.create('Ext.grid.Panel', {
            frame:false,
            autoScroll:true,
            store:this.store,
            columnLines:true,
            trackMouseOver:true,
            stripeRows:true,
            columns : {
                items: typesColumns
            },
            sm:  Ext.create('Ext.selection.RowModel', {}),
            bbar:this.pagingtoolbar,
            plugins: [
                this.cellEditing
            ],
            tbar:[
                {
                    xtype: "tbtext",
                    text: t('add_setting') + " "
                },
                this.customKeyField, customType,
                {
                    xtype: "button",
                    handler: this.addSetFromUserDefined.bind(this, this.customKeyField, customType),
                    iconCls: "pimcore_icon_add"
                },
                '->',
                {
                    text:t("filter") + "/" + t("search"),
                    xtype:"tbtext",
                    style:"margin: 0 10px 0 0;"
                },
                this.filterField
            ]
            ,
            viewConfig: {
                listeners: {
                    rowupdated: this.updateRows.bind(this, "rowupdated"),
                    refresh: this.updateRows.bind(this, "refresh")
                },
                forceFit:true,
                xtype: 'patchedgridview'
            }
        });

        this.store.on("update", this.updateRows.bind(this));
        this.grid.on("viewready", this.updateRows.bind(this));
        this.grid.on("afterrender", function() {
            this.setAutoScroll(true);
        });

        this.store.load();

        return this.grid;
    },

    getTypeRenderer: function (value, metaData, record, rowIndex, colIndex, store) {

        return '

';
    },

    getCellEditor: function (record) {
        var data = record.data;

        var type = data.type;
        var property;
        console.log("get editor");
        console.log(data);
        console.log(type);

        if (type == "text") {
            property = Ext.create('Ext.form.TextField');
        } else if (type == "textarea") {
            property = Ext.create('Ext.form.TextArea');
        } else if (type == "document" || type == "asset" || type == "object") {
            //no editor needed here
        } else if (type == "date") {
            property = Ext.create('Ext.form.field.Date', {
                format: "Y-m-d"
            });
        } else if (type == "checkbox") {
            //no editor needed here
        } else if (type == "select") {
            var config = data.config;
            property =  Ext.create('Ext.form.ComboBox', {
                triggerAction: 'all',
                editable: false,
                store: config.split(",")
            });
        }

        return property;
    },

    updateRows: function (event) {
        var rows = Ext.get(this.grid.getEl().dom).query(".x-grid-row");

        for (var i = 0; i < rows.length; i++) {
            try {
                var propertyName = Ext.get(rows[i]).query(".x-grid-cell-first div div")[0].getAttribute("data-id");
                var storeIndex = this.grid.getStore().find("id", propertyName);

                var record = this.grid.getStore().getAt(storeIndex);
                var data = record.data;

                if (data.type == "document" || data.type == "asset" || data.type == "object") {

                    // add dnd support
                    var dd = new Ext.dd.DropZone(rows[i], {
                        ddGroup: "element",

                        getTargetFromEvent: function(e) {
                            return this.getEl();
                        },

                        onNodeOver : function(elementType, node, dragZone, e, data ) {

                            var record = data.records[0];
                            var data = record.data;

                            if (data.elementType == elementType) {
                                return Ext.dd.DropZone.prototype.dropAllowed;
                            }

                            return Ext.dd.DropZone.prototype.dropNotAllowed;
                        }.bind(this, data.type),

                        onNodeDrop : function(storeIndex, targetNode, dragZone, e, data) {
                            try {
                                var record = data.records[0];
                                var data = record.data;
                                var rec = this.grid.getStore().getAt(storeIndex);
                                rec.set("data", data.path);

                                this.updateRows();

                                return true;
                            } catch (e) {
                                console.log(e);
                            }
                            return false;
                        }.bind(this, storeIndex)
                    });
                }
            }
            catch (e) {
                console.log(e);
            }
        }
    },

    getCellRenderer: function (value, metaData, record, rowIndex, colIndex, store) {

        var data = record.data;
        var type = data.type;

        console.log("get renderer");
        console.log(type);

        if (!value) {
            value = "";
        }

        if (type == "document" || type == "asset" || type == "object") {
            return '
' + value + '
';
        } else if (type == "bool") {
            console.log(value);
            if (value) {
                return '

';
            } else {
                return '

';
            }
        }

        return value;
    },

    cellMousedown: function (grid, cell, rowIndex, cellIndex, e) {

        // this is used for the boolean field type

        var store = this.store;
        var record = store.getAt(rowIndex);
        var data = record.data;
        var type = data.type;

        if (type == "bool") {

            this.cellEditing.editors.each(Ext.destroy, Ext);
            this.cellEditing.editors.clear();

            record.set("data", !data.data);
        }
    },

    addSetFromUserDefined: function (customKey, customType) {
        if(in_array(customKey.getValue(), this.disallowedKeys)) {
            Ext.MessageBox.alert(t("error"), t("name_is_not_allowed"));
        }
        this.add(customKey.getValue(), customType.getValue(), false, false, false, true);
        this.customKeyField.setValue(null);
    },

    add: function (key, type, value, config, inherited, inheritable) {

        var store = this.grid.getStore();

        this.cellEditing.editors.each(Ext.destroy, Ext);
        this.cellEditing.editors.clear();

        // check for duplicate name
        var dublicateIndex = store.findBy(function (key, record, id) {
            if (record.get("name").toLowerCase() == key.toLowerCase()) {
                return true;
            }
            return false;
        }.bind(this, key));

        if (dublicateIndex >= 0) {
            if (store.getAt(dublicateIndex).data.inherited == false) {
                Ext.MessageBox.alert(t("error"), t("name_already_in_use"));
                return;
            }
        }

        // check for empty key & type
        if (key.length < 2 || !type || type.length < 1) {
            Ext.MessageBox.alert(t("error"), t("name_and_key_must_be_defined"));
            return;
        }

        if (!value) {
            if (type == "bool") {
                value = true;
            }
            if (type == "document" || type == "asset" || type == "object") {
                value = "";
            }
            if (type == "text") {
                value = "";
            }
            value = "";
        }

        store.add({
            name: key,
            data: value,
            type: type
        });
    }

});<commit_msg>extjs6 - website-settings<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.settings.website");
pimcore.settings.website = Class.create({

    initialize:function () {

        this.getTabPanel();
    },

    activate:function () {
        var tabPanel = Ext.getCmp("pimcore_panel_tabs");
        tabPanel.setActiveItem("pimcore_website_settings");
    },

    getTabPanel:function () {

        if (!this.panel) {
            this.panel = new Ext.Panel({
                id:"pimcore_website_settings",
                title: t('website_settings'),
                iconCls: "pimcore_icon_website",
                border:false,
                layout:"fit",
                closable:true,
                items:[this.getRowEditor()]
            });

            var tabPanel = Ext.getCmp("pimcore_panel_tabs");
            tabPanel.add(this.panel);
            tabPanel.setActiveItem("pimcore_website_settings");

            this.panel.on("destroy", function () {
                pimcore.globalmanager.remove("settings_website");
            }.bind(this));

            pimcore.layout.refresh();
        }

        return this.panel;
    },

    getRowEditor:function () {

        var itemsPerPage = 20;
        var url = '/admin/settings/website-settings?';

        this.store = pimcore.helpers.grid.buildDefaultStore(
            url,
            [
                "id", 'name','type',
                {name: "data"},
                {name: 'siteId', allowBlank: true},
                {name: 'creationDate', allowBlank: true},
                {name: 'modificationDate', allowBlank: true}

            ],
            itemsPerPage
        );

        this.store.addListener('exception', function (proxy, response, operation) {
                Ext.MessageBox.show({
                    title: 'REMOTE EXCEPTION',
                    msg: operation.getError(),
                    icon: Ext.MessageBox.ERROR,
                    buttons: Ext.Msg.OK
                });
            }
        );
        this.store.setAutoSync(true);

        this.filterField = new Ext.form.TextField({
            width: 200,
            style: "margin: 0 10px 0 0;",
            enableKeyEvents:true,
            listeners:{
                "keydown":function (field, key) {
                    if (key.getKey() == key.ENTER) {
                        var input = field;
                        var proxy = this.store.getProxy();
                        proxy.extraParams.filter = input.getValue();
                        this.store.load();
                    }
                }.bind(this)
            }
        });

        this.pagingtoolbar = pimcore.helpers.grid.buildDefaultPagingToolbar(this.store, itemsPerPage);

        var typesColumns = [
            {
                header: t("type"),
                dataIndex: 'type',
                editable: false,
                width: 40,
                renderer: this.getTypeRenderer.bind(this),
                sortable: true
            },
            {
                header: t("name"),
                dataIndex: 'name',
                width: 200,
                editor: new Ext.form.TextField({
                    allowBlank: false
                }),
                sortable: true
            },
            {
                header: t("value"),
                dataIndex: 'data',
                flex: 10,
                getEditor: this.getCellEditor.bind(this),
                editable: true,
                renderer: this.getCellRenderer.bind(this),
                listeners: {
                    "mousedown": this.cellMousedown.bind(this)
                }
            },
            {header: t("site"), width: 250, sortable:true, dataIndex: "siteId",
                editor: new Ext.form.ComboBox({
                        store: pimcore.globalmanager.get("sites"),
                        valueField: "id",
                        displayField: "domain",
                        triggerAction: "all"
                }),
                renderer: function (siteId) {
                    var store = pimcore.globalmanager.get("sites");
                    var pos = store.findExact("id", siteId);
                    if(pos >= 0) {
                        var val = store.getAt(pos).get("domain");
                        return val;
                    }
                    return null;
                }
            }
            ,
            {header: t("creationDate"), sortable: true, dataIndex: 'creationDate', editable: false,
                hidden: true,
                renderer: function(d) {
                    if (d !== undefined) {
                        var date = new Date(d * 1000);
                        return Ext.Date.format(date, "Y-m-d H:i:s");
                    } else {
                        return "";
                    }
                }
            }
            ,
            {header: t("modificationDate"), sortable: true, dataIndex: 'modificationDate', editable: false,
                hidden: true,
                renderer: function(d) {
                    if (d !== undefined) {
                        var date = new Date(d * 1000);
                        return Ext.Date.format(date, "Y-m-d H:i:s");
                    } else {
                        return "";
                    }
                }
            }
            ,
            {
                xtype:'actioncolumn',
                width:40,
                tooltip:t('empty'),
                icon: "/pimcore/static/img/icon/bin_empty.png",
                handler:function (grid, rowIndex) {
                    grid.getStore().getAt(rowIndex).set("data","");
                }.bind(this)

            }
            ,
            {
                xtype:'actioncolumn',
                width:40,
                tooltip:t('delete'),
                icon:"/pimcore/static/img/icon/cross.png",
                handler:function (grid, rowIndex) {
                    grid.getStore().removeAt(rowIndex);
                }.bind(this)
            }
        ];

        var propertyTypes = new Ext.data.SimpleStore({
            fields: ['id', 'name'],
            data: [
                ["text", "Text"],
                ["document", "Document"],
                ["asset", "Asset"],
                ["object", "Object"],
                ["bool", "Checkbox"]
            ]
        });

        this.customKeyField = new Ext.form.TextField({
            name: 'key',
            emptyText: t('key')
        });

        var customType = new Ext.form.ComboBox({
            fieldLabel: t('type'),
            name: "type",
            valueField: "id",
            displayField:'name',
            store: propertyTypes,
            editable: false,
            triggerAction: 'all',
            mode: "local",
            listWidth: 200,
            hideLabel: true,
            emptyText: t('type')
        });

        this.cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1,
            listeners: {
                beforeedit: function(editor, context, eOpts) {
                    //need to clear cached editors of cell-editing editor in order to
                    //enable different editors per row
                    editor.editors.each(Ext.destroy, Ext);
                    editor.editors.clear();
                }
            }
        });

        this.grid = Ext.create('Ext.grid.Panel', {
            frame:false,
            autoScroll:true,
            store:this.store,
            columnLines:true,
            trackMouseOver:true,
            stripeRows:true,
            columns : {
                items: typesColumns
            },
            sm:  Ext.create('Ext.selection.RowModel', {}),
            bbar:this.pagingtoolbar,
            plugins: [
                this.cellEditing
            ],
            tbar:[
                {
                    xtype: "tbtext",
                    text: t('add_setting') + " "
                },
                this.customKeyField, customType,
                {
                    xtype: "button",
                    handler: this.addSetFromUserDefined.bind(this, this.customKeyField, customType),
                    iconCls: "pimcore_icon_add"
                },
                '->',
                {
                    text:t("filter") + "/" + t("search"),
                    xtype:"tbtext",
                    style:"margin: 0 10px 0 0;"
                },
                this.filterField
            ]
            ,
            viewConfig: {
                listeners: {
                    rowupdated: this.updateRows.bind(this, "rowupdated"),
                    refresh: this.updateRows.bind(this, "refresh")
                },
                forceFit:true,
                xtype: 'patchedgridview'
            }
        });

        this.store.on("update", this.updateRows.bind(this));
        this.grid.on("viewready", this.updateRows.bind(this));
        this.grid.on("afterrender", function() {
            this.setAutoScroll(true);
        });

        this.store.load();

        return this.grid;
    },

    getTypeRenderer: function (value, metaData, record, rowIndex, colIndex, store) {

        return '

';
    },

    getCellEditor: function (record) {
        var data = record.data;

        var type = data.type;
        var property;

        if (type == "text") {
            property = Ext.create('Ext.form.TextField');
        } else if (type == "textarea") {
            property = Ext.create('Ext.form.TextArea');
        } else if (type == "document" || type == "asset" || type == "object") {
            //no editor needed here
        } else if (type == "date") {
            property = Ext.create('Ext.form.field.Date', {
                format: "Y-m-d"
            });
        } else if (type == "checkbox") {
            //no editor needed here
        } else if (type == "select") {
            var config = data.config;
            property =  Ext.create('Ext.form.ComboBox', {
                triggerAction: 'all',
                editable: false,
                store: config.split(",")
            });
        }

        return property;
    },

    updateRows: function (event) {
        var rows = Ext.get(this.grid.getEl().dom).query(".x-grid-row");

        for (var i = 0; i < rows.length; i++) {
            try {
                var propertyName = Ext.get(rows[i]).query(".x-grid-cell-first div div")[0].getAttribute("data-id");
                var storeIndex = this.grid.getStore().find("id", propertyName);

                var record = this.grid.getStore().getAt(storeIndex);
                var data = record.data;

                if (data.type == "document" || data.type == "asset" || data.type == "object") {

                    // add dnd support
                    var dd = new Ext.dd.DropZone(rows[i], {
                        ddGroup: "element",

                        getTargetFromEvent: function(e) {
                            return this.getEl();
                        },

                        onNodeOver : function(elementType, node, dragZone, e, data ) {

                            var record = data.records[0];
                            var data = record.data;

                            if (data.elementType == elementType) {
                                return Ext.dd.DropZone.prototype.dropAllowed;
                            }

                            return Ext.dd.DropZone.prototype.dropNotAllowed;
                        }.bind(this, data.type),

                        onNodeDrop : function(storeIndex, targetNode, dragZone, e, data) {
                            try {
                                var record = data.records[0];
                                var data = record.data;
                                var rec = this.grid.getStore().getAt(storeIndex);
                                rec.set("data", data.path);

                                this.updateRows();

                                return true;
                            } catch (e) {
                                console.log(e);
                            }
                            return false;
                        }.bind(this, storeIndex)
                    });
                }
            }
            catch (e) {
                console.log(e);
            }
        }
    },

    getCellRenderer: function (value, metaData, record, rowIndex, colIndex, store) {

        var data = record.data;
        var type = data.type;

        if (!value) {
            value = "";
        }

        if (type == "document" || type == "asset" || type == "object") {
            return '
' + value + '
';
        } else if (type == "bool") {
            if (value) {
                return '

';
            } else {
                return '

';
            }
        }

        return value;
    },

    cellMousedown: function (grid, cell, rowIndex, cellIndex, e) {

        // this is used for the boolean field type

        var store = this.store;
        var record = store.getAt(rowIndex);
        var data = record.data;
        var type = data.type;

        if (type == "bool") {

            this.cellEditing.editors.each(Ext.destroy, Ext);
            this.cellEditing.editors.clear();

            record.set("data", !data.data);
        }
    },

    addSetFromUserDefined: function (customKey, customType) {
        if(in_array(customKey.getValue(), this.disallowedKeys)) {
            Ext.MessageBox.alert(t("error"), t("name_is_not_allowed"));
        }
        this.add(customKey.getValue(), customType.getValue(), false, false, false, true);
        this.customKeyField.setValue(null);
    },

    add: function (key, type, value, config, inherited, inheritable) {

        var store = this.grid.getStore();

        this.cellEditing.editors.each(Ext.destroy, Ext);
        this.cellEditing.editors.clear();

        // check for duplicate name
        var dublicateIndex = store.findBy(function (key, record, id) {
            if (record.get("name").toLowerCase() == key.toLowerCase()) {
                return true;
            }
            return false;
        }.bind(this, key));

        if (dublicateIndex >= 0) {
            if (store.getAt(dublicateIndex).data.inherited == false) {
                Ext.MessageBox.alert(t("error"), t("name_already_in_use"));
                return;
            }
        }

        // check for empty key & type
        if (key.length < 2 || !type || type.length < 1) {
            Ext.MessageBox.alert(t("error"), t("name_and_key_must_be_defined"));
            return;
        }

        if (!value) {
            if (type == "bool") {
                value = true;
            }
            if (type == "document" || type == "asset" || type == "object") {
                value = "";
            }
            if (type == "text") {
                value = "";
            }
            value = "";
        }

        store.add({
            name: key,
            data: value,
            type: type
        });
    }

});<|endoftext|>


<commit_before>$(function(){
    var $slider_wrap = $('#sliderWrap'),
        $slider = $('#sliderList'),
        $slider_list = $('#sliderList'),
        $slider_items = $('.sliderItem'),
        slider_len = $slider_items.length,
        cur_index = 0,
        next_index = 1;

    // $slider_wrap.css({'position': 'relative'});
    //
    // $slider_items.each(function(index){
    //
    //     if(index != cur_index){
    //         $(this).hide();
    //
    //         return this;
    //     }
    //
    // });

    // $('#btn').on('click', function(){
    //     $slider_items.eq(0).fadeOut();
    // });

    var slider = new $.slider({
        slider_wrap_id: 'sliderWrap',
        slider_items_class: 'sliderItem',
    });

    slider.init().autoSlide();
    // slider.init();

    // var index = 0;
    //
    // $('#btn').on('click', function(){
    //     slider.slideTo(++index);
    // });
    //
    // $('#btn_2').on('click', function(){
    //     slider.slideTo(1);
    // });
});
<commit_msg>remove unused code<commit_after>$(function() {
    var $slider_wrap = $('#sliderWrap'),
        $slider = $('#sliderList'),
        $slider_list = $('#sliderList'),
        $slider_items = $('.sliderItem'),
        slider_len = $slider_items.length,
        cur_index = 0,
        next_index = 1;

    var slider = new $.slider({
        slider_wrap_id: 'sliderWrap',
        slider_items_class: 'sliderItem',
    });

    slider.init().autoSlide();
});
<|endoftext|>


<commit_before>var P = (function(prototype, ownProperty, undefined) {
  // helper functions that also help minification
  function isObject(o) { return typeof o === 'object'; }
  function isFunction(f) { return typeof f === 'function'; }

  // used to extend the prototypes of superclasses (which might not
  // have `.Bare`s)
  function SuperclassBare() {}

  return function P(_superclass /* = Object */, definition) {
    // handle the case where no superclass is given
    if (definition === undefined) {
      definition = _superclass;
      _superclass = Object;
    }

    // C is the class to be returned.
    //
    // It delegates to instantiating an instance of `Bare`, so that it
    // will always return a new instance regardless of the calling
    // context.
    //
    //  TODO: the Chrome inspector shows all created objects as `C`
    //        rather than `Object`.  Setting the .name property seems to
    //        have no effect.  Is there a way to override this behavior?
    function C() {
      var self = new Bare;
      if (isFunction(self.init)) self.init.apply(self, arguments);
      return self;
    }

    // C.Bare is a class with a noop constructor.  Its prototype is the
    // same as C, so that instances of C.Bare are also instances of C.
    // New objects can be allocated without initialization by calling
    // `new MyClass.Bare`.
    function Bare() {}
    C.Bare = Bare;

    // Set up the prototype of the new class.
    var _super = SuperclassBare[prototype] = _superclass[prototype];
    var proto = Bare[prototype] = C[prototype] = new SuperclassBare;

    // other variables, as a minifier optimization
    var extensions;

    // set the constructor property on the prototype, for convenience
    proto.constructor = C;

    C.mixin = function(def) {
      Bare[prototype] = C[prototype] = P(C, def)[prototype];
      return C;
    }

    return (C.open = function(def) {
      extensions = {};

      if (isFunction(def)) {
        // call the defining function with all the arguments you need
        // extensions captures the return value.
        extensions = def.call(C, proto, _super, C, _superclass);
      }
      else if (isObject(def)) {
        // if you passed an object instead, we'll take it
        extensions = def;
      }

      // ...and extend it
      if (isObject(extensions)) {
        for (var ext in extensions) {
          if (ownProperty.call(extensions, ext)) {
            proto[ext] = extensions[ext];
          }
        }
      }

      // if there's no init, we assume we're inheriting a non-pjs class, so
      // we default to applying the superclass's constructor.
      if (!isFunction(proto.init)) {
        proto.init = _superclass;
      }

      return C;
    })(definition);
  }

  // as a minifier optimization, we've closured in a few helper functions
  // and the string 'prototype' (C[p] is much shorter than C.prototype)
})('prototype', ({}).hasOwnProperty);
<commit_msg>Add C.p as an alias for C.prototype<commit_after>var P = (function(prototype, ownProperty, undefined) {
  // helper functions that also help minification
  function isObject(o) { return typeof o === 'object'; }
  function isFunction(f) { return typeof f === 'function'; }

  // used to extend the prototypes of superclasses (which might not
  // have `.Bare`s)
  function SuperclassBare() {}

  return function P(_superclass /* = Object */, definition) {
    // handle the case where no superclass is given
    if (definition === undefined) {
      definition = _superclass;
      _superclass = Object;
    }

    // C is the class to be returned.
    //
    // It delegates to instantiating an instance of `Bare`, so that it
    // will always return a new instance regardless of the calling
    // context.
    //
    //  TODO: the Chrome inspector shows all created objects as `C`
    //        rather than `Object`.  Setting the .name property seems to
    //        have no effect.  Is there a way to override this behavior?
    function C() {
      var self = new Bare;
      if (isFunction(self.init)) self.init.apply(self, arguments);
      return self;
    }

    // C.Bare is a class with a noop constructor.  Its prototype is the
    // same as C, so that instances of C.Bare are also instances of C.
    // New objects can be allocated without initialization by calling
    // `new MyClass.Bare`.
    function Bare() {}
    C.Bare = Bare;

    // Set up the prototype of the new class.
    var _super = SuperclassBare[prototype] = _superclass[prototype];
    var proto = Bare[prototype] = C[prototype] = C.p = new SuperclassBare;

    // other variables, as a minifier optimization
    var extensions;

    // set the constructor property on the prototype, for convenience
    proto.constructor = C;

    C.mixin = function(def) {
      Bare[prototype] = C[prototype] = P(C, def)[prototype];
      return C;
    }

    return (C.open = function(def) {
      extensions = {};

      if (isFunction(def)) {
        // call the defining function with all the arguments you need
        // extensions captures the return value.
        extensions = def.call(C, proto, _super, C, _superclass);
      }
      else if (isObject(def)) {
        // if you passed an object instead, we'll take it
        extensions = def;
      }

      // ...and extend it
      if (isObject(extensions)) {
        for (var ext in extensions) {
          if (ownProperty.call(extensions, ext)) {
            proto[ext] = extensions[ext];
          }
        }
      }

      // if there's no init, we assume we're inheriting a non-pjs class, so
      // we default to applying the superclass's constructor.
      if (!isFunction(proto.init)) {
        proto.init = _superclass;
      }

      return C;
    })(definition);
  }

  // as a minifier optimization, we've closured in a few helper functions
  // and the string 'prototype' (C[p] is much shorter than C.prototype)
})('prototype', ({}).hasOwnProperty);
<|endoftext|>