<commit_before>module.exports = [
  { link: "/README.md", text: "Introduction" },
  {
    text: "Aides mémoires",
    collapsible: true,
    children: [
      { link: "/cheatsheets/git/README.md", text: "Git" },
      { link: "/cheatsheets/html/README.md", text: "Html" },
      { link: "/cheatsheets/php/README.md", text: "PHP" },
      { link: "/cheatsheets/sql/README.md", text: "SQL" },
      { link: "/cheatsheets/javascript/README.md", text: "JavaScript" },
      { link: "/cheatsheets/cordova/README.md", text: "Cordova" },
      { link: "/cheatsheets/docker/README.md", text: "Docker" },
      { link: "/cheatsheets/vuejs/README.md", text: "VueJS" },
      { link: "/cheatsheets/owasp/README.md", text: "OWASP" },
      { link: "/cheatsheets/poo-uml/README.md", text: "Représentation UML" },
      { link: "/cheatsheets/poo/README.md", text: "Programation Orientée Objet" },
      { link: "/cheatsheets/laravel/README.md", text: "Laravel" },
      { link: "/cheatsheets/api/README.md", text: "Les API" }
    ]
  },

  {
    text: "Les cours",
    collapsible: true,
    children: [
      { text: "En + du cours", collapsible: true, children: ["/cheatsheets/html/README.md", "/tp/html_css/support.md", "/tp/php/support.md", "/tp/php/sql/support.md", "/tp/javascript/support.md"] },
      { text: "HTML + CSS", collapsible: true, children: ["/cours/introduction_html_css", "/tp/html_css/maquette.md"] },
      { text: "PHP", collapsible: true, children: ["/cours/introduction_php"] },
      { text: "PHP & SQL", collapsible: true, children: ["/cours/introduction_sql_php"] },
      { text: "Javascript", collapsible: true, children: ["/cours/introduction_javascript"] },
      { text: "Les API", collapsible: true, children: ["/cours/introduction_api"] },
      {
        text: "La POO",
        collapsible: true,
        children: [
          { text: "POO", collapsible: true, children: ["/cours/poo"] },
          { text: "MVC", collapsible: true, children: ["/cours/mvc"] },
          {
            text: "Interfaces & Abstractions", collapsible: true,
            children: [
              "/cours/exercices/poo/les-interfaces-1",
              "/cours/exercices/poo/les-interfaces-2",
              "/cours/exercices/poo/les-classes-abstraites.md"
            ]
          },
          {
            text: "Aide mémoire",
            collapsible: true,
            children: [
              { link: "/cheatsheets/poo-uml/README.md", text: "Représentation UML" },
              { link: "/cheatsheets/poo/README.md", text: "Programation Orientée Objet" }
            ]
          }
        ]
      },
    ]
  },

  {
    text: "Le HTML + CSS",
    collapsible: true,
    children: [
      { collapsible: true, text: "Les TP", children: ["/tp/html_css/tp1.md", "/tp/html_css/tp2.md", "/tp/html_css/tp3.md", "/tp/html_css/tp4.md", "/tp/html_css/tp5.md"] },
      { collapsible: true, text: "Librairies", children: ["/tp/html_css/bootstrap.md", "/tp/html_css/tailwind.md"] },
      { collapsible: true, text: "Ressources & Intégrations", children: ["/tp/html_css/integration.md"] }
    ]
  },

  {
    text: "Le PHP",
    collapsible: true,
    children: [
      { text: "Les bases", collapsible: true, children: ["/cours/introduction_php", "/cours/introduction_sql_php", "/tp/php/support.md", "/tp/php/sql/support.md"] },
      { text: "Les TP basiques", collapsible: true, children: ["/tp/php/tp1.md", "/tp/php/tp-param.md", "/tp/php/tp1.1.md", "/tp/php/tp1.2.md", "/tp/php/tp2.md", "/tp/php/tp3.md", "/tp/php/tp4.md"] },
      { text: "PHP & SQL", collapsible: true, children: ["/tp/php/sql/tp5.md", "/tp/php/sql/tp6.md"] },
      {
        text: "MVC",
        collapsible: true,
        children: [
          "/tp/php/mvc/tp1.md",
          "/tp/php/mvc/tp1.1.md",
          { text: "iOT Dashboard", children: ["/tp/php/mvc/dashboard/tp0.md", "/tp/php/mvc/dashboard/tp1.md"] }
        ]
      },
      { text: "Laravel", collapsible: true, children: ["/cours/laravel", "/tp/laravel/introduction", "/tp/laravel/authentification", "/tp/laravel/application_todo_list", "/tp/laravel/laravel_api", "/tp/laravel/creation_api"] }
    ]
  },

  {
    text: "Le JavaScript",
    collapsible: true,
    children: [
      { text: "Les bases", collapsible: true, children: ["/cours/introduction_javascript", "/tp/javascript/support.md"] },
      { text: "Les TP basiques", collapsible: true, children: ["/tp/javascript/tp1.md", "/tp/javascript/tp1.1.md", "/tp/javascript/tp1.2.md", "/tp/javascript/tp2.md", "/tp/javascript/tp3.md", "/tp/javascript/tp3.1.md", "/tp/javascript/tp5.md", "/tp/javascript/tp4.md", "/tp/javascript/tp4.1.md"] },
      { text: "Javascript avancé", collapsible: true, children: ["/cours/javascript_avances", "/tp/javascript_avances/introduction", "/tp/javascript_avances/revision"] },
      { text: "Les frameworks", collapsible: true, children: ["/cours/framework_javascript", "/tp/javascript_avances/introduction.md"] }
    ]
  },

  {
    text: "Les CMS",
    collapsible: true,
    children: ["/tp/cms/wordpress.md"]
  },

  {
    text: "Le versionning",
    collapsible: true,
    children: [
      { link: "/cheatsheets/git/README.md", text: "En + du cours" },
      { text: "Initiation à Git", collapsible: true, children: ["/cours/git", "/tp/git_initiation/"] },
      { text: "Git en groupe + GitLab", collapsible: true, children: ["/cours/gitlab", "/tp/gitlab/"] },
    ]
  },

  {
    text: "L'organisation",
    collapsible: true,
    children: ["/cours/organisations", "/tp/organisation/introduction"],
  },

  {
    text: "Sécurité du code",
    collapsible: true,
    children: [
      { text: "OWASP", children: ["/cours/securite_applications", { link: "/cheatsheets/owasp/README.md", text: "Synthèse du cours" }, "/tp/securite/"] }
    ]
  },

  {
    text: "VueJS",
    collapsible: true,
    children: [
      { text: "Cours Vue 2.0", collapsible: true, children: ["/cheatsheets/vuejs/README.md", "/cours/vuejs"] },
      { text: "Exemples", collapsible: true, children: ["/cours/demo/vuejs/demo1", "/cours/demo/vuejs/counter", "/cours/demo/vuejs/clock", "/cours/demo/vuejs/timestamp-color", "/cours/demo/vuejs/sound", "/cours/demo/vuejs/12vue", "/cours/demo/vuejs/chat"] },
      {
        text: "Version 2.0",
        collapsible: true,
        children: ["/tp/vuejs/tp0.md", "/tp/vuejs/tp1-vuejs-laravel-api", "/tp/vuejs/tp1", "/tp/vuejs/tp2", "/tp/vuejs/firebase-vuejs", "/tp/vuejs/vuetify-vuejs.md"]
      },
      {
        text: "Version 3.0",
        collapsible: true,
        children: ["/tp/vuejs3/vite.md", "/tp/vuejs3/petite-vue.md"]
      }
    ]
  },

  {
    text: "Le mobile",
    collapsible: true,
    children: [
      { text: "Cordova", collapsible: true, children: ["/cours/cordova", { link: "/cheatsheets/cordova/README.md", text: "En + du cours" }, "/tp/cordova/decouverte", "/tp/cordova/vuejs_cordova", "/tp/cordova/vuejs_api_led", "/tp/api/doc_api_led"] },
      {
        text: "Android",
        collapsible: true,
        children: [
          "/cours/android_base",
          "/cours/android_ble",
          { text: "Les bases", collapsible: true, children: ["/tp/android/android-base-tp", "/tp/android/android-base2-tp"] },
          { text: "Les appels d'API", collapsible: true, children: ["/cours/android_http", "/tp/android/network"] },
          { text: "L'organisation", collapsible: true, children: ["/tp/android/sample-explication"] },
          { text: "Les projets", collapsible: true, children: ["/tp/android/app-base-android.md", "/tp/android/app-ble-network.md", "/tp/android/app-avance-android.md"] }
        ]
      }
    ]
  },

  {
    text: "DevOps",
    collapsible: true,
    children: [
      { text: "Support de cours", collapsible: true, children: ["/tp/devops/support.md", { link: "/cours/docker", text: "Docker" }, "/cours/cicd", { link: "/cours/gitlabci", text: "Gitlab CI" }] },
      { text: "GitLab-CI", collapsible: true, children: ["/tp/ci/pages", "/tp/ci/ci-test/tests", "/tp/ci/packager-docker", "/tp/ci/ci-hybride", "/tp/ci/gitlab/runner.md", "/tp/devops/sonarqube/sonarqube.md"] },
      { text: "JamStack", collapsible: true, children: ["/tp/ci/jamstack/netlify.md"] },
      {
        text: "Docker",
        collapsible: true,
        children: [
          { link: "/cheatsheets/docker/README.md", text: "En + du cours" },
          "/tp/docker/introduction",
          "/tp/docker/creer_server_local.md", "/tp/docker/dockerfile", "/tp/docker/docker_compose"]
      },
      { text: "Kubernetes", collapsible: true, children: ["/tp/ci/kubernetes/deploy-container-in-kubernetes.md", "/tp/ci/kubernetes/cd-avec-kubernetes.md"] },
      { text: "OpenFaas", collapsible: true, children: ["/tp/openfaas/openfaas-quicky-installation", "/tp/openfaas/openfaas-quicky-installation-pi", "/tp/openfaas/openfaas-quicky-create-faas"] },
      { text: "Firebase", collapsible: true, children: ["/tp/ci/firebase/functions.md"] },
      "/tp/rpi/web-stack.md",
      "/tp/devops/alpine-vm.md"
    ]
  },

  {
    text: "Les API",
    collapsible: true,
    children: [
      { text: "Framework Flask (Python)", children: ["/cours/python", "/tp/python/flask", "/tp/python/flask_todolist_api"] },
      { text: "Typescript (prochainement)", children: ["/cours/typescript", "/tp/typescript/vuejs"] },
      { text: "NodeJS (prochainement)", children: ["/cours/nodejs"] },
    ]
  }

]<commit_msg>Ajout lien vers les interfaces dans le menu<commit_after>module.exports = [
  { link: "/README.md", text: "Introduction" },
  {
    text: "Aides mémoires",
    collapsible: true,
    children: [
      { link: "/cheatsheets/git/README.md", text: "Git" },
      { link: "/cheatsheets/html/README.md", text: "Html" },
      { link: "/cheatsheets/php/README.md", text: "PHP" },
      { link: "/cheatsheets/sql/README.md", text: "SQL" },
      { link: "/cheatsheets/javascript/README.md", text: "JavaScript" },
      { link: "/cheatsheets/cordova/README.md", text: "Cordova" },
      { link: "/cheatsheets/docker/README.md", text: "Docker" },
      { link: "/cheatsheets/vuejs/README.md", text: "VueJS" },
      { link: "/cheatsheets/owasp/README.md", text: "OWASP" },
      { link: "/cheatsheets/poo-uml/README.md", text: "Représentation UML" },
      { link: "/cheatsheets/poo/README.md", text: "Programation Orientée Objet" },
      { link: "/cheatsheets/laravel/README.md", text: "Laravel" },
      { link: "/cheatsheets/api/README.md", text: "Les API" }
    ]
  },

  {
    text: "Les cours",
    collapsible: true,
    children: [
      { text: "En + du cours", collapsible: true, children: ["/cheatsheets/html/README.md", "/tp/html_css/support.md", "/tp/php/support.md", "/tp/php/sql/support.md", "/tp/javascript/support.md"] },
      { text: "HTML + CSS", collapsible: true, children: ["/cours/introduction_html_css", "/tp/html_css/maquette.md"] },
      { text: "PHP", collapsible: true, children: ["/cours/introduction_php"] },
      { text: "PHP & SQL", collapsible: true, children: ["/cours/introduction_sql_php"] },
      { text: "Javascript", collapsible: true, children: ["/cours/introduction_javascript"] },
      { text: "Les API", collapsible: true, children: ["/cours/introduction_api"] },
      {
        text: "La POO",
        collapsible: true,
        children: [
          { text: "POO", collapsible: true, children: ["/cours/poo", "/cours/les_interfaces"] },
          { text: "MVC", collapsible: true, children: ["/cours/mvc"] },
          {
            text: "Interfaces & Abstractions", collapsible: true,
            children: [
              "/cours/exercices/poo/les-interfaces-1",
              "/cours/exercices/poo/les-interfaces-2",
              "/cours/exercices/poo/les-classes-abstraites.md"
            ]
          },
          {
            text: "Aide mémoire",
            collapsible: true,
            children: [
              { link: "/cheatsheets/poo-uml/README.md", text: "Représentation UML" },
              { link: "/cheatsheets/poo/README.md", text: "Programation Orientée Objet" }
            ]
          }
        ]
      },
    ]
  },

  {
    text: "Le HTML + CSS",
    collapsible: true,
    children: [
      { collapsible: true, text: "Les TP", children: ["/tp/html_css/tp1.md", "/tp/html_css/tp2.md", "/tp/html_css/tp3.md", "/tp/html_css/tp4.md", "/tp/html_css/tp5.md"] },
      { collapsible: true, text: "Librairies", children: ["/tp/html_css/bootstrap.md", "/tp/html_css/tailwind.md"] },
      { collapsible: true, text: "Ressources & Intégrations", children: ["/tp/html_css/integration.md"] }
    ]
  },

  {
    text: "Le PHP",
    collapsible: true,
    children: [
      { text: "Les bases", collapsible: true, children: ["/cours/introduction_php", "/cours/introduction_sql_php", "/tp/php/support.md", "/tp/php/sql/support.md"] },
      { text: "Les TP basiques", collapsible: true, children: ["/tp/php/tp1.md", "/tp/php/tp-param.md", "/tp/php/tp1.1.md", "/tp/php/tp1.2.md", "/tp/php/tp2.md", "/tp/php/tp3.md", "/tp/php/tp4.md"] },
      { text: "PHP & SQL", collapsible: true, children: ["/tp/php/sql/tp5.md", "/tp/php/sql/tp6.md"] },
      {
        text: "MVC",
        collapsible: true,
        children: [
          "/tp/php/mvc/tp1.md",
          "/tp/php/mvc/tp1.1.md",
          { text: "iOT Dashboard", children: ["/tp/php/mvc/dashboard/tp0.md", "/tp/php/mvc/dashboard/tp1.md"] }
        ]
      },
      { text: "Laravel", collapsible: true, children: ["/cours/laravel", "/tp/laravel/introduction", "/tp/laravel/authentification", "/tp/laravel/application_todo_list", "/tp/laravel/laravel_api", "/tp/laravel/creation_api"] }
    ]
  },

  {
    text: "Le JavaScript",
    collapsible: true,
    children: [
      { text: "Les bases", collapsible: true, children: ["/cours/introduction_javascript", "/tp/javascript/support.md"] },
      { text: "Les TP basiques", collapsible: true, children: ["/tp/javascript/tp1.md", "/tp/javascript/tp1.1.md", "/tp/javascript/tp1.2.md", "/tp/javascript/tp2.md", "/tp/javascript/tp3.md", "/tp/javascript/tp3.1.md", "/tp/javascript/tp5.md", "/tp/javascript/tp4.md", "/tp/javascript/tp4.1.md"] },
      { text: "Javascript avancé", collapsible: true, children: ["/cours/javascript_avances", "/tp/javascript_avances/introduction", "/tp/javascript_avances/revision"] },
      { text: "Les frameworks", collapsible: true, children: ["/cours/framework_javascript", "/tp/javascript_avances/introduction.md"] }
    ]
  },

  {
    text: "Les CMS",
    collapsible: true,
    children: ["/tp/cms/wordpress.md"]
  },

  {
    text: "Le versionning",
    collapsible: true,
    children: [
      { link: "/cheatsheets/git/README.md", text: "En + du cours" },
      { text: "Initiation à Git", collapsible: true, children: ["/cours/git", "/tp/git_initiation/"] },
      { text: "Git en groupe + GitLab", collapsible: true, children: ["/cours/gitlab", "/tp/gitlab/"] },
    ]
  },

  {
    text: "L'organisation",
    collapsible: true,
    children: ["/cours/organisations", "/tp/organisation/introduction"],
  },

  {
    text: "Sécurité du code",
    collapsible: true,
    children: [
      { text: "OWASP", children: ["/cours/securite_applications", { link: "/cheatsheets/owasp/README.md", text: "Synthèse du cours" }, "/tp/securite/"] }
    ]
  },

  {
    text: "VueJS",
    collapsible: true,
    children: [
      { text: "Cours Vue 2.0", collapsible: true, children: ["/cheatsheets/vuejs/README.md", "/cours/vuejs"] },
      { text: "Exemples", collapsible: true, children: ["/cours/demo/vuejs/demo1", "/cours/demo/vuejs/counter", "/cours/demo/vuejs/clock", "/cours/demo/vuejs/timestamp-color", "/cours/demo/vuejs/sound", "/cours/demo/vuejs/12vue", "/cours/demo/vuejs/chat"] },
      {
        text: "Version 2.0",
        collapsible: true,
        children: ["/tp/vuejs/tp0.md", "/tp/vuejs/tp1-vuejs-laravel-api", "/tp/vuejs/tp1", "/tp/vuejs/tp2", "/tp/vuejs/firebase-vuejs", "/tp/vuejs/vuetify-vuejs.md"]
      },
      {
        text: "Version 3.0",
        collapsible: true,
        children: ["/tp/vuejs3/vite.md", "/tp/vuejs3/petite-vue.md"]
      }
    ]
  },

  {
    text: "Le mobile",
    collapsible: true,
    children: [
      { text: "Cordova", collapsible: true, children: ["/cours/cordova", { link: "/cheatsheets/cordova/README.md", text: "En + du cours" }, "/tp/cordova/decouverte", "/tp/cordova/vuejs_cordova", "/tp/cordova/vuejs_api_led", "/tp/api/doc_api_led"] },
      {
        text: "Android",
        collapsible: true,
        children: [
          "/cours/android_base",
          "/cours/android_ble",
          { text: "Les bases", collapsible: true, children: ["/tp/android/android-base-tp", "/tp/android/android-base2-tp"] },
          { text: "Les appels d'API", collapsible: true, children: ["/cours/android_http", "/tp/android/network"] },
          { text: "L'organisation", collapsible: true, children: ["/tp/android/sample-explication"] },
          { text: "Les projets", collapsible: true, children: ["/tp/android/app-base-android.md", "/tp/android/app-ble-network.md", "/tp/android/app-avance-android.md"] }
        ]
      }
    ]
  },

  {
    text: "DevOps",
    collapsible: true,
    children: [
      { text: "Support de cours", collapsible: true, children: ["/tp/devops/support.md", { link: "/cours/docker", text: "Docker" }, "/cours/cicd", { link: "/cours/gitlabci", text: "Gitlab CI" }] },
      { text: "GitLab-CI", collapsible: true, children: ["/tp/ci/pages", "/tp/ci/ci-test/tests", "/tp/ci/packager-docker", "/tp/ci/ci-hybride", "/tp/ci/gitlab/runner.md", "/tp/devops/sonarqube/sonarqube.md"] },
      { text: "JamStack", collapsible: true, children: ["/tp/ci/jamstack/netlify.md"] },
      {
        text: "Docker",
        collapsible: true,
        children: [
          { link: "/cheatsheets/docker/README.md", text: "En + du cours" },
          "/tp/docker/introduction",
          "/tp/docker/creer_server_local.md", "/tp/docker/dockerfile", "/tp/docker/docker_compose"]
      },
      { text: "Kubernetes", collapsible: true, children: ["/tp/ci/kubernetes/deploy-container-in-kubernetes.md", "/tp/ci/kubernetes/cd-avec-kubernetes.md"] },
      { text: "OpenFaas", collapsible: true, children: ["/tp/openfaas/openfaas-quicky-installation", "/tp/openfaas/openfaas-quicky-installation-pi", "/tp/openfaas/openfaas-quicky-create-faas"] },
      { text: "Firebase", collapsible: true, children: ["/tp/ci/firebase/functions.md"] },
      "/tp/rpi/web-stack.md",
      "/tp/devops/alpine-vm.md"
    ]
  },

  {
    text: "Les API",
    collapsible: true,
    children: [
      { text: "Framework Flask (Python)", children: ["/cours/python", "/tp/python/flask", "/tp/python/flask_todolist_api"] },
      { text: "Typescript (prochainement)", children: ["/cours/typescript", "/tp/typescript/vuejs"] },
      { text: "NodeJS (prochainement)", children: ["/cours/nodejs"] },
    ]
  }

]<|endoftext|>


<commit_before>'use strict';

(function ($) {

    var MediaUploader = function ($element, attachment, data) {

        this.data = data;
        this.attachment = attachment;

        this.$element = $element;
        this.$reprElement = $('[data-field-id="' + $element.attr('id') + '"]');

        this.$thumbnail = this.$reprElement.find('.thumbnail');
        this.$filename = this.$reprElement.find('.filename');
        this.$remove = this.$reprElement.find('.remove');
        this.$reprElement.click(this.upload.bind(this));
        this.$remove.click(this.remove.bind(this));

        this.invalidate();
    };

    /**
     * Creates a wp media uploader
     * @returns {wp.media}
     */
    MediaUploader.prototype.createUploader = function () {

        var uploader = wp.media({
            title:    this.data.title,
            button:   {
                text: this.data.buttonText
            },
            library:  {
                type: this.data.libraryType
            },
            multiple: this.data.multiple
        });
        var state = uploader.state();
        return uploader;

    };

    MediaUploader.prototype.select = function () {

        this.attachment = this.custom_uploader.state().get('selection').first().toJSON();
        this.invalidate();

    };

    MediaUploader.prototype.escape = function () {
    };

    MediaUploader.prototype.reset = function () {
    };

    MediaUploader.prototype.remove = function (e) {
        this.attachment = null;
        this.invalidate();
        e.preventDefault();
        return false;
    };

    /**
     * Invoked when the upload button is pressed
     * @param e
     */
    MediaUploader.prototype.upload = function (e) {

        if ($(e.target).is('a.filename'))
            return;
        e.preventDefault();
        if (!this.attachment) {
            this.custom_uploader = this.createUploader();
            this.custom_uploader.once('select', this.select.bind(this));
            this.custom_uploader.once('escape', this.escape.bind(this));
            this.custom_uploader.once('reset', this.reset.bind(this));
            this.custom_uploader.open();
        }

    };

    MediaUploader.prototype.invalidate = function () {

        var attachmentUrl = this.attachment ? this.attachment.url : '';
        var attachmentId = this.attachment ? this.attachment.id : null;
        if (attachmentUrl) {
            this.$reprElement.addClass('set');
            this.$thumbnail.removeClass('not-set');
            this.$remove.show();
        } else {
            this.$reprElement.removeClass('set');
            this.$thumbnail.addClass('not-set');
            this.$remove.hide();
        }

        // Set background image (in case of image preview)
        if (this.$thumbnail.is('.image-thumbnail'))
            this.$thumbnail.css('background-image', 'url(\'' + attachmentUrl + '\')');

        // Set extension data attribute
        this.$thumbnail.attr('data-file-extension', attachmentUrl.split('.').pop());

        // Set filename label
        if (this.$filename)
            this.$filename.text(attachmentUrl.split(/[\\/]/).pop()).attr('href', attachmentUrl);

        this.$element.val(attachmentId);
    };

    if (Object.prototype.hasOwnProperty.call(window, 'Fieldwork')) {
        var Fieldwork = window.Fieldwork;
        Fieldwork.ee.on('fieldAdded', function (field) {
            var fieldData = field.getFieldData();
            var mediaUploaderProps = fieldData.mediaUploaderProps;
            if (mediaUploaderProps) {
                var attachment = fieldData.attachment;
                new MediaUploader(field.getElement(), attachment, mediaUploaderProps);
            }
        });
    } else if (console) {
        console.warn('global Fieldwork was not defined; could not link JVWP wp-media-uploader component');
    }

})(jQuery);<commit_msg>Fix some bug problem thing<commit_after>'use strict';

(function ($) {

    var MediaUploader = function ($element, attachment, data) {

        this.data = data;
        this.attachment = attachment;

        this.$element = $element;
        this.$reprElement = $('[data-field-id="' + $element.attr('id') + '"]');

        this.$thumbnail = this.$reprElement.find('.thumbnail');
        this.$filename = this.$reprElement.find('.filename');
        this.$remove = this.$reprElement.find('.remove');
        this.$reprElement.click(this.upload.bind(this));
        this.$remove.click(this.remove.bind(this));

        this.invalidate();
    };

    /**
     * Creates a wp media uploader
     * @returns {wp.media}
     */
    MediaUploader.prototype.createUploader = function () {

        var uploader = wp.media({
            title:    this.data.title,
            button:   {
                text: this.data.buttonText
            },
            library:  {
                type: this.data.libraryType
            },
            multiple: this.data.multiple
        });
        var state = uploader.state();
        return uploader;

    };

    MediaUploader.prototype.select = function () {

        this.attachment = this.custom_uploader.state().get('selection').first().toJSON();
        this.invalidate();

    };

    MediaUploader.prototype.escape = function () {
    };

    MediaUploader.prototype.reset = function () {
    };

    MediaUploader.prototype.remove = function (e) {
        this.attachment = null;
        this.invalidate();
        e.preventDefault();
        return false;
    };

    /**
     * Invoked when the upload button is pressed
     * @param e
     */
    MediaUploader.prototype.upload = function (e) {

        if ($(e.target).is('a.filename'))
            return;
        e.preventDefault();
        if (!this.attachment || !this.attachment.url) {
            this.custom_uploader = this.createUploader();
            this.custom_uploader.once('select', this.select.bind(this));
            this.custom_uploader.once('escape', this.escape.bind(this));
            this.custom_uploader.once('reset', this.reset.bind(this));
            this.custom_uploader.open();
        }

    };

    MediaUploader.prototype.invalidate = function () {

        var attachmentUrl = this.attachment ? this.attachment.url : '';
        var attachmentId = this.attachment ? this.attachment.id : null;
        if (attachmentUrl) {
            this.$reprElement.addClass('set');
            this.$thumbnail.removeClass('not-set');
            this.$remove.show();

            // Set background image (in case of image preview)
            if (this.$thumbnail.is('.image-thumbnail'))
                this.$thumbnail.css('background-image', 'url(\'' + attachmentUrl + '\')');

            // Set extension data attribute
            this.$thumbnail.attr('data-file-extension', attachmentUrl.split('.').pop());

            // Set filename label
            if (this.$filename)
                this.$filename.text(attachmentUrl.split(/[\\/]/).pop()).attr('href', attachmentUrl);
        } else {
            this.$reprElement.removeClass('set');
            this.$thumbnail.addClass('not-set').css('background-image', 'none');
            this.$remove.hide();
            this.$filename.empty();
        }

        this.$element.val(attachmentId);
    };

    if (Object.prototype.hasOwnProperty.call(window, 'Fieldwork')) {
        var Fieldwork = window.Fieldwork;
        Fieldwork.ee.on('fieldAdded', function (field) {
            var fieldData = field.getFieldData();
            var mediaUploaderProps = fieldData.mediaUploaderProps;
            if (mediaUploaderProps) {
                var attachment = fieldData.attachment;
                new MediaUploader(field.getElement(), attachment, mediaUploaderProps);
            }
        });
    } else if (console) {
        console.warn('global Fieldwork was not defined; could not link JVWP wp-media-uploader component');
    }

})(jQuery);<|endoftext|>


<commit_before>/* ========================================================================
 * DOM-based Routing
 * Based on http://goo.gl/EUTi53 by Paul Irish
 *
 * Only fires on body classes that match. If a body class contains a dash,
 * replace the dash with an underscore when adding it to the object below.
 *
 * .noConflict()
 * The routing is enclosed within an anonymous function so that you can
 * always reference jQuery with $, even when in .noConflict() mode.
 * ======================================================================== */
 var app = angular.module('businesstarget', ['ngRoute', 'ngLodash', 'checklist-model', 'LocalStorageModule', 'ng.shims.placeholder'])
 .config(['$routeProvider',
   function($routeProvider) {
     $routeProvider.
       when('/step1', {
         templateUrl: 'step1.html',
         controller: 'SignupController'
       }).
       when('/step2', {
         templateUrl: 'step2.html',
         controller: 'SignupController'
       }).
       when('/step3', {
         templateUrl: 'step3.html',
         controller: 'SignupController'
       }).
       when('/thanks', {
         templateUrl: 'thanks.html',
       }).
       when('/edit/:id', {
         templateUrl: 'edit.html',
         controller: 'EditController'
       }).
       when('/login', {
         templateUrl: 'login.html',
         controller: 'LoginController'
       }).
       when('/unsubscribe/:id', {
         templateUrl: 'unsubscribe.html',
         controller: 'UnsubscribeController'
       }).
       otherwise({
         redirectTo: '/step1'
       });
 }])
 .config(function (localStorageServiceProvider) {
  localStorageServiceProvider
    .setPrefix('businesstarget');
  })
  .factory('apiService', ['$http', function($http) {
    var doRequest = function() {
      var interestUrl = "/wp-content/themes/businesstarget/api/interests.php";
      return $http({
        url: interestUrl
      });
    };
    return {
      interests: function() { return doRequest(); },
    };
  }])
  .controller('LoginController', ['$scope', '$location', '$http', function($scope, $location, $http) {

    var base_url = "/wp-content/themes/businesstarget/api/";
    var login_url = base_url + "send_login.php";
      $scope.submit_email = function(mail) {
          if (!$scope.loginform.$valid) {
            return;
           }
          $http.post(login_url, {mail:mail}).success(function(data, status, headers, config) {

          });
        $scope.displayThanks = true;
      };

   }])
   .controller('EditController', ['$scope', '$location', '$http', '$routeParams', '$q', 'lodash', function($scope, $location, $http, $routeParams, $q, lodash) {
     var _ = lodash;
     var base_url = "/wp-content/themes/businesstarget/api/";
     var me_url = base_url + "me.php";
     var interests_url = base_url + "interests.php";
     var edit_url = base_url + "edit.php";
     var my_id = $routeParams.id;
     var me_promise = $http.post(me_url, {id: my_id});
     var interests_promise = $http.get(interests_url);

     var sanify_interests = function(interests) {
       var i_arr = interests.split("|");
       return _.map(i_arr, function(elem){
        return elem.split(":")[0];
       });
     };
     var find_choice = function(my_choices, interests, parent_id) {
       var valid_choices_objects = _.filter(interests, _.matchesProperty('interesse_parent_id', parent_id));
       var valid_choices = _.map(valid_choices_objects, _.property('interesse_id'));
       return _.intersection(valid_choices, my_choices);
     };

     $q.all([me_promise, interests_promise]).then(function(result) {
       $scope.user = result[0].data;

       var data = result[1].data.root.data;
       interests = _.filter(data.rowset, function(elem) {
         return elem['@attributes'].id === 'interests';
       });
       $scope.interests = interests[0].row;

       $scope.my_interests = sanify_interests($scope.user.interests);

       $scope.user.occupation = _.first(find_choice($scope.my_interests, $scope.interests, "343"));
       $scope.user.industry = _.first(find_choice($scope.my_interests, $scope.interests, "310"));
       $scope.user.employees = _.first(find_choice($scope.my_interests, $scope.interests, "335"));
       $scope.user.managementlevel = _.first(find_choice($scope.my_interests, $scope.interests, "391"));
       $scope.user.buyer = _.first(find_choice($scope.my_interests, $scope.interests, "400"));
       $scope.user.traveller = _.first(find_choice($scope.my_interests, $scope.interests, "403"));
       $scope.user.car = _.first(find_choice($scope.my_interests, $scope.interests, "397"));

       $scope.user.businessinterests = find_choice($scope.my_interests, $scope.interests, "407");

     });

     $scope.submit_edit = function(user) {
       if (!$scope.edit.$valid) {
         return;
        }
        var ints = [];
        ints.push(user.occupation.toString());
        ints.push(user.industry.toString());

        ints.push(user.employees.toString());
        ints.push(user.managementlevel.toString());
        ints.push(user.buyer.toString());
        ints.push(user.traveller.toString());
        ints.push(user.car.toString());
        var new_interests = ints.concat(user.businessinterests);

        var turn_off = _.difference($scope.my_interests, new_interests);
        var turn_on = new_interests;

        var turn_off_string = _.map(turn_off, function(elem) {return elem+':0';}).join('|');
        var turn_on_string = _.map(turn_on, function(elem) {return elem+':1';}).join('|');
        var int_string = turn_off_string.length > 0 ? turn_off_string + '|' + turn_on_string : turn_on_string;

        $http.post(edit_url, {user_id: my_id, first_name: user.first_name, last_name: user.last_name, zip: user.zip, ints: int_string}).success(function(data, status, headers, config) {
          window.location = "/#thanks";
        });
     };
    }])

   .controller('UnsubscribeController', ['$scope', '$location', '$http', '$routeParams', function($scope, $location, $http, $routeParams) {
       var base_url = "/wp-content/themes/businesstarget/api/";
       var unsubscribe_url = base_url + "unsubscribe.php";
       var me_url = base_url + "me.php";
       $http.post(me_url, {id: $routeParams.id}).success(function(data, status, headers, config) {
         $scope.email = data.mail;
       });
       $scope.submit_unsubscribe = function(email) {
           var nlid = businesstarget_setup.nlid + ':0';
           $http.post(unsubscribe_url, {id: $routeParams.id, nlid: nlid, email: $scope.email}).success(function(data, status, headers, config) {
             $scope.displayThanks = true;
           });

       };
    }])
 .controller('SignupController', ['$scope', '$location', '$http', 'apiService', 'lodash', 'localStorageService', function($scope, $location, $http, apiService, lodash, localStorageService) {

    var interests;
    apiService.interests().success(function(response, status) {
      var _ = lodash;
      var data = response.root.data;
      interests = _.filter(data.rowset, function(elem) {
        return elem['@attributes'].id === 'interests';
      });
      interests = interests[0].row;
      localStorageService.set("interests", interests);
      $scope.interests = interests;
    });

    $scope.interests = interests;
    $scope.businessinterests = [];
    $scope.user = {};
    var base_url = "/wp-content/themes/businesstarget/api/";
    var signup_url = base_url + 'signup.php';
    var add_url = base_url + 'add.php';
     $scope.submit_step1 = function(user) {

       if (!$scope.formstep1.$valid) {
         return;
        }
       var nlid = businesstarget_setup.nlid;
       var lid = businesstarget_setup.lid;

       var ints = [];
       ints.push(user.industry.toString());
       ints.push(user.occupation.toString());
       $http.post(signup_url, {email:user.mail, lid: lid, nlids: nlid, intids:ints.join(","), zip: user.zip, first_name:user.first_name, last_name: user.last_name, bem_permission: user.bem_permission}).
        success(function(data, status, headers, config) {
          localStorageService.set("uid", data.uid);
          localStorageService.set("state", 2);
          localStorageService.set("user", user);
          localStorageService.set("mail", user.mail);
          $location.path("step2");
        });
     };
     $scope.submit_step2 = function(user) {
       if (!$scope.formstep2.$valid) {
         return;
        }
        var ints = [];
        var lid = businesstarget_setup.lid;
        ints.push(user.employees.toString());
        ints.push(user.managementlevel.toString());
        ints.push(user.buyer.toString());
        ints.push(user.traveller.toString());
        ints.push(user.car.toString());

        var mail = localStorageService.get("mail");
        $http.post(add_url, {email:mail, lid: lid, intids:ints.join(","),}).
         success(function(data, status, headers, config) {
           localStorageService.set("state", 3);
           $location.path("step3");
         });

     };
     $scope.submit_step3 = function(user) {
       if (!$scope.formstep3.$valid) {
         return;
        }
        var mail = localStorageService.get("mail");
        var intids = "";
        var lid = businesstarget_setup.lid;
        if (typeof user.businessinterests !== "undefined" && user.businessinterests.length > 0) {
          intids = user.businessinterests.join(",");
        }
        $http.post(add_url, {email:mail, lid: lid, intids:intids}).
         success(function(data, status, headers, config) {
           localStorageService.set("state", 1);
           $location.path("thanks");
         });

     };
  }]);

(function($) {

  // Use this variable to set up the common and page specific functions. If you
  // rename this variable, you will also need to rename the namespace below.
  var Sage = {
    // All pages
    'common': {
      init: function() {
        new WOW().init();
      },
      finalize: function() {
        // JavaScript to be fired on all pages, after page specific JS is fired
      }
    },
    // Home page
    'home': {
      init: function() {
        // JavaScript to be fired on the home page
      },
      finalize: function() {
        // JavaScript to be fired on the home page, after the init JS
      }
    },
    // About us page, note the change from about-us to about_us.
    'about_us': {
      init: function() {
        // JavaScript to be fired on the about us page
      }
    }
  };

  // The routing fires all common scripts, followed by the page specific scripts.
  // Add additional events for more control over timing e.g. a finalize event
  var UTIL = {
    fire: function(func, funcname, args) {
      var fire;
      var namespace = Sage;
      funcname = (funcname === undefined) ? 'init' : funcname;
      fire = func !== '';
      fire = fire && namespace[func];
      fire = fire && typeof namespace[func][funcname] === 'function';

      if (fire) {
        namespace[func][funcname](args);
      }
    },
    loadEvents: function() {
      // Fire common init JS
      UTIL.fire('common');

      // Fire page-specific init JS, and then finalize JS
      $.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
        UTIL.fire(classnm);
        UTIL.fire(classnm, 'finalize');
      });

      // Fire common finalize JS
      UTIL.fire('common', 'finalize');
    }
  };

  // Load Events
  $(document).ready(UTIL.loadEvents);

})(jQuery); // Fully reference jQuery after this point.
<commit_msg>Building<commit_after>/* ========================================================================
 * DOM-based Routing
 * Based on http://goo.gl/EUTi53 by Paul Irish
 *
 * Only fires on body classes that match. If a body class contains a dash,
 * replace the dash with an underscore when adding it to the object below.
 *
 * .noConflict()
 * The routing is enclosed within an anonymous function so that you can
 * always reference jQuery with $, even when in .noConflict() mode.
 * ======================================================================== */
 var app = angular.module('businesstarget', ['ngRoute', 'ngLodash', 'checklist-model', 'LocalStorageModule', 'ng.shims.placeholder'])
 .config(['$routeProvider',
   function($routeProvider) {
     $routeProvider.
       when('/step1', {
         templateUrl: 'step1.html',
         controller: 'SignupController'
       }).
       when('/step2', {
         templateUrl: 'step2.html',
         controller: 'SignupController'
       }).
       when('/step3', {
         templateUrl: 'step3.html',
         controller: 'SignupController'
       }).
       when('/thanks', {
         templateUrl: 'thanks.html',
       }).
       when('/edit/:id', {
         templateUrl: 'edit.html',
         controller: 'EditController'
       }).
       when('/login', {
         templateUrl: 'login.html',
         controller: 'LoginController'
       }).
       when('/unsubscribe/:id', {
         templateUrl: 'unsubscribe.html',
         controller: 'UnsubscribeController'
       }).
       otherwise({
         redirectTo: '/step1'
       });
 }])
 .config(function (localStorageServiceProvider) {
  localStorageServiceProvider
    .setPrefix('businesstarget');
  })
  .factory('apiService', ['$http', function($http) {
    var doRequest = function() {
      var interestUrl = "/wp-content/themes/businesstarget/api/interests.php";
      return $http({
        url: interestUrl
      });
    };
    return {
      interests: function() { return doRequest(); },
    };
  }])
  .controller('LoginController', ['$scope', '$location', '$http', function($scope, $location, $http) {

    var base_url = "/wp-content/themes/businesstarget/api/";
    var login_url = base_url + "send_login.php";
      $scope.submit_email = function(mail) {
          if (!$scope.loginform.$valid) {
            return;
           }
          $http.post(login_url, {mail:mail}).success(function(data, status, headers, config) {

          });
        $scope.displayThanks = true;
      };

   }])
   .controller('EditController', ['$scope', '$location', '$http', '$routeParams', '$q', 'lodash', function($scope, $location, $http, $routeParams, $q, lodash) {
     var _ = lodash;
     var base_url = "/wp-content/themes/businesstarget/api/";
     var me_url = base_url + "me.php";
     var interests_url = base_url + "interests.php";
     var edit_url = base_url + "edit.php";
     var my_id = $routeParams.id;
     var me_promise = $http.post(me_url, {id: my_id});
     var interests_promise = $http.get(interests_url);

     var sanify_interests = function(interests) {
       var i_arr = interests.split("|");
       return _.map(i_arr, function(elem){
        return elem.split(":")[0];
       });
     };
     var find_choice = function(my_choices, interests, parent_id) {
       var valid_choices_objects = _.filter(interests, _.matchesProperty('interesse_parent_id', parent_id));
       var valid_choices = _.map(valid_choices_objects, _.property('interesse_id'));
       return _.intersection(valid_choices, my_choices);
     };

     $q.all([me_promise, interests_promise]).then(function(result) {
       $scope.user = result[0].data;

       var data = result[1].data.root.data;
       interests = _.filter(data.rowset, function(elem) {
         return elem['@attributes'].id === 'interests';
       });
       $scope.interests = interests[0].row;

       $scope.my_interests = sanify_interests($scope.user.interests);

       $scope.user.occupation = _.first(find_choice($scope.my_interests, $scope.interests, "343"));
       $scope.user.industry = _.first(find_choice($scope.my_interests, $scope.interests, "310"));
       $scope.user.employees = _.first(find_choice($scope.my_interests, $scope.interests, "335"));
       $scope.user.managementlevel = _.first(find_choice($scope.my_interests, $scope.interests, "391"));
       $scope.user.buyer = _.first(find_choice($scope.my_interests, $scope.interests, "400"));
       $scope.user.traveller = _.first(find_choice($scope.my_interests, $scope.interests, "403"));
       $scope.user.car = _.first(find_choice($scope.my_interests, $scope.interests, "397"));

       $scope.user.businessinterests = find_choice($scope.my_interests, $scope.interests, "407");

     });

     $scope.submit_edit = function(user) {
       if (!$scope.edit.$valid) {
         return;
        }
        var ints = [];
        ints.push(user.occupation.toString());
        ints.push(user.industry.toString());

        ints.push(user.employees.toString());
        ints.push(user.managementlevel.toString());
        ints.push(user.buyer.toString());
        ints.push(user.traveller.toString());
        ints.push(user.car.toString());
        var new_interests = ints.concat(user.businessinterests);

        var turn_off = _.difference($scope.my_interests, new_interests);
        var turn_on = new_interests;

        var turn_off_string = _.map(turn_off, function(elem) {return elem+':0';}).join('|');
        var turn_on_string = _.map(turn_on, function(elem) {return elem+':1';}).join('|');
        var int_string = turn_off_string.length > 0 ? turn_off_string + '|' + turn_on_string : turn_on_string;

        $http.post(edit_url, {user_id: my_id, first_name: user.first_name, last_name: user.last_name, zip: user.zip, ints: int_string}).success(function(data, status, headers, config) {
          window.location = "/#thanks";
        });
     };
    }])

   .controller('UnsubscribeController', ['$scope', '$location', '$http', '$routeParams', function($scope, $location, $http, $routeParams) {
       var base_url = "/wp-content/themes/businesstarget/api/";
       var unsubscribe_url = base_url + "unsubscribe.php";
       var me_url = base_url + "me.php";
       $http.post(me_url, {id: $routeParams.id}).success(function(data, status, headers, config) {
         $scope.email = data.mail;
       });
       $scope.submit_unsubscribe = function(email) {
           var nlid = businesstarget_setup.nlid + ':0';
           $http.post(unsubscribe_url, {id: $routeParams.id, nlid: nlid, email: $scope.email}).success(function(data, status, headers, config) {
             $scope.displayThanks = true;
           });

       };
    }])
 .controller('SignupController', ['$scope', '$location', '$http', 'apiService', 'lodash', 'localStorageService', function($scope, $location, $http, apiService, lodash, localStorageService) {
    var interests;
    apiService.interests().success(function(response, status) {
      var _ = lodash;
      var data = response.root.data;
      interests = _.filter(data.rowset, function(elem) {
        return elem['@attributes'].id === 'interests';
      });
      interests = interests[0].row;
      localStorageService.set("interests", interests);
      $scope.interests = interests;
    });

    $scope.interests = interests;
    $scope.businessinterests = [];
    $scope.user = {};
    var base_url = "/wp-content/themes/businesstarget/api/";
    var signup_url = base_url + 'signup.php';
    var add_url = base_url + 'add.php';
     $scope.submit_step1 = function(user) {

       if (!$scope.formstep1.$valid) {
         return;
        }
       var nlid = businesstarget_setup.nlid;
       var lid = businesstarget_setup.lid;

       var ints = [];
       ints.push(user.industry.toString());
       ints.push(user.occupation.toString());
       $http.post(signup_url, {email:user.mail, lid: lid, nlids: nlid, intids:ints.join(","), zip: user.zip, first_name:user.first_name, last_name: user.last_name, bem_permission: user.bem_permission}).
        success(function(data, status, headers, config) {
          localStorageService.set("uid", data.uid);
          localStorageService.set("state", 2);
          localStorageService.set("user", user);
          localStorageService.set("mail", user.mail);
          $location.path("step2");
        });
     };
     $scope.submit_step2 = function(user) {
       if (!$scope.formstep2.$valid) {
         return;
        }
        var ints = [];
        var lid = businesstarget_setup.lid;
        ints.push(user.employees.toString());
        ints.push(user.managementlevel.toString());
        ints.push(user.buyer.toString());
        ints.push(user.traveller.toString());
        ints.push(user.car.toString());

        var mail = localStorageService.get("mail");
        $http.post(add_url, {email:mail, lid: lid, intids:ints.join(","),}).
         success(function(data, status, headers, config) {
           localStorageService.set("state", 3);
           $location.path("step3");
         });

     };
     $scope.submit_step3 = function(user) {
       if (!$scope.formstep3.$valid) {
         return;
        }
        var mail = localStorageService.get("mail");
        var intids = "";
        var lid = businesstarget_setup.lid;
        if (typeof user.businessinterests !== "undefined" && user.businessinterests.length > 0) {
          intids = user.businessinterests.join(",");
        }
        $http.post(add_url, {email:mail, lid: lid, intids:intids}).
         success(function(data, status, headers, config) {
           localStorageService.set("state", 1);
           $location.path("thanks");
         });

     };
  }]);

(function($) {

  // Use this variable to set up the common and page specific functions. If you
  // rename this variable, you will also need to rename the namespace below.
  var Sage = {
    // All pages
    'common': {
      init: function() {
        new WOW().init();
      },
      finalize: function() {
        // JavaScript to be fired on all pages, after page specific JS is fired
      }
    },
    // Home page
    'home': {
      init: function() {
        // JavaScript to be fired on the home page
      },
      finalize: function() {
        // JavaScript to be fired on the home page, after the init JS
      }
    },
    // About us page, note the change from about-us to about_us.
    'about_us': {
      init: function() {
        // JavaScript to be fired on the about us page
      }
    }
  };

  // The routing fires all common scripts, followed by the page specific scripts.
  // Add additional events for more control over timing e.g. a finalize event
  var UTIL = {
    fire: function(func, funcname, args) {
      var fire;
      var namespace = Sage;
      funcname = (funcname === undefined) ? 'init' : funcname;
      fire = func !== '';
      fire = fire && namespace[func];
      fire = fire && typeof namespace[func][funcname] === 'function';

      if (fire) {
        namespace[func][funcname](args);
      }
    },
    loadEvents: function() {
      // Fire common init JS
      UTIL.fire('common');

      // Fire page-specific init JS, and then finalize JS
      $.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
        UTIL.fire(classnm);
        UTIL.fire(classnm, 'finalize');
      });

      // Fire common finalize JS
      UTIL.fire('common', 'finalize');
    }
  };

  // Load Events
  $(document).ready(UTIL.loadEvents);
})(jQuery);
<|endoftext|>


<commit_before>import { connect } from 'react-redux';
import Authentications from '../../components/Authentications';

export const load = ({dispatch}) => {
	// myaws.Auth.signOut();
	return dispatch((dispatch, getState) => {
		return myaws.Auth.setCredentials().then(myaws.Auth.getCurrentUserInfo).then(data => {
			// break the promise chain when there is no user signed in
			if (data === null) {
				throw new errors.NoCurrentUserException();
			}

			let { userId } = data;

			return Promise.all([
				myaws.DynamoDB.getLastModifiedExperimentOf(userId),
				myaws.DynamoDB.getUserDate(userId)
			]).then(results => {
				let [ experimentState, userDataResponse ] = results;

				// load states
				if (experimentState) {
					dispatch(actions.actionCreator({
						type: actions.ActionTypes.LOAD_EXPERIMENT,
						experimentState
					}));
				}
				let userState = userDataResponse.Item.fetch;

				dispatch(actions.actionCreator({
					type: actions.ActionTypes.LOAD_USER,
					userState
				}));

				return Promise.resolve();
			});
		}).catch(err => {
			// keep the chaining by throwing all other error except
			// NoCurrentUserException
			if (err.code === 'NoCurrentUserException') {
				console.log(err.message);
			} else {
				console.log(err)
				throw err;
			}
		})
	})
}

export const saveExperiment = ({dispatch}) => {
	return dispatch((dispatch, getState) => {
		return myaws.Auth.getCurrentUserInfo().then((userInfo) => {
			dispatch(actions.actionCreator({
				type: actions.ActionTypes.PREPARE_SAVE_EXPERIMENT,
				userId: userInfo.userId
			}));

			return myaws.DynamoDB.saveExperiment(getState().experimentState);
		}).then(() => {
			utils.notifications.notifySuccessBySnackbar({
				dispatch,
				message: "Saved !"
			});
		});
	})
}

const signIn = ({dispatch, username, password, firstSignIn=false}) => {
	return dispatch((dispatch, getState) => {
		return myaws.Auth.signIn({
			username,
			password
		}).then((userInfo) => {
			// if it is first time signing in
			// register user in DynamoDB
			if (firstSignIn) {
				let { userId, username, email } = userInfo;

				return myaws.DynamoDB.saveUserData(core.createUser({
					userId,
					username,
					email
				}));
			}

			return Promise.resolve();
		}).then(() => {
			// if user has changed anything
			// save the change

			let anyChange = !utils.deepEqual(core.getInitExperimentState(), getState().experimentState);
			if (anyChange || true) {
				return saveExperiment({dispatch});
			}

			return Promise.resolve();
		}).then(() => {
			return load({dispatch});
		}).catch((err) => {
			if (err.code === "UserNotConfirmedException") {
				popVerification({
					dispatch,
					signInCallback: () => {
						return signIn({
							dispatch,
							username,
							password,
							firstSignIn
						});
					}
				});
			} else {
				throw err;
			}
		});
	});
}

const signUp = ({dispatch, username, password, attributes, ...options}) => {
	return myaws.Auth.signUp({username, password, attributes, ...options}).then(() => {
		popVerification({
			dispatch,
			signInCallback: () => {
				return signIn({
					dispatch,
					username,
					password,
					firstSignIn: true,
				})
			}
		});
	});
}

const handleWindowClose = ({dispatch}) => {
	dispatch(actions.actionCreator({
		type: actions.ActionTypes.SET_AUTH_WINDOW,
		open: false
	}));
}

export const popSignIn = ({dispatch}) => {
	dispatch(actions.actionCreator({
		type: actions.ActionTypes.SET_AUTH_WINDOW,
		open: true,
		loginMode: enums.AUTH_MODES.signIn
	}));
}

export const popRegister = ({dispatch}) => {
	dispatch(actions.actionCreator({
		type: actions.ActionTypes.SET_AUTH_WINDOW,
		open: true,
		loginMode: enums.AUTH_MODES.register
	}));
}

export const popForgetPassword = ({dispatch}) => {
	dispatch(actions.actionCreator({
		type: actions.ActionTypes.SET_AUTH_WINDOW,
		open: true,
		loginMode: enums.AUTH_MODES.forgotPassword
	}));
}

export const popVerification = ({dispatch, ...args}) => {
	dispatch(actions.actionCreator({
		type: actions.ActionTypes.SET_AUTH_WINDOW,
		open: true,
		loginMode: enums.AUTH_MODES.verification,
		...args
	}));
}

const setLoginMode = ({dispatch, mode}) => {
	dispatch(actions.actionCreator({
		type: actions.ActionTypes.SET_AUTH_WINDOW,
		loginMode: mode
	}));
}

const mapStateToProps = (state, ownProps) => {
  return {
  	...state.authentications
  }
}

const mapDispatchToProps = (dispatch, ownProps) => ({
	signIn: ({...args}) => signIn({dispatch, ...args}),
	signUp: ({...args}) => signUp({dispatch, ...args}),
	load: () => load({dispatch}),
	handleWindowClose: () => handleWindowClose({dispatch}),
	popSignIn: () => popSignIn({dispatch}),
	popRegister: () => popRegister({dispatch}),
	popForgetPassword: () => popForgetPassword({dispatch}),
	popVerification: () => popVerification({dispatch}),
	setLoginMode: (mode) => setLoginMode({dispatch, mode}),
})

export default connect(mapStateToProps, mapDispatchToProps)(Authentications);
<commit_msg>Get rid of test lines<commit_after>import { connect } from 'react-redux';
import Authentications from '../../components/Authentications';

export const load = ({dispatch}) => {
	// myaws.Auth.signOut();
	return dispatch((dispatch, getState) => {
		return myaws.Auth.setCredentials().then(myaws.Auth.getCurrentUserInfo).then(data => {
			// break the promise chain when there is no user signed in
			if (data === null) {
				throw new errors.NoCurrentUserException();
			}

			let { userId } = data;

			return Promise.all([
				myaws.DynamoDB.getLastModifiedExperimentOf(userId),
				myaws.DynamoDB.getUserDate(userId)
			]).then(results => {
				let [ experimentState, userDataResponse ] = results;

				// load states
				if (experimentState) {
					dispatch(actions.actionCreator({
						type: actions.ActionTypes.LOAD_EXPERIMENT,
						experimentState
					}));
				}
				let userState = userDataResponse.Item.fetch;

				dispatch(actions.actionCreator({
					type: actions.ActionTypes.LOAD_USER,
					userState
				}));

				return Promise.resolve();
			});
		}).catch(err => {
			// keep the chaining by throwing all other error except
			// NoCurrentUserException
			if (err.code === 'NoCurrentUserException') {
				console.log(err.message);
			} else {
				console.log(err)
				throw err;
			}
		})
	})
}

export const saveExperiment = ({dispatch}) => {
	return dispatch((dispatch, getState) => {
		return myaws.Auth.getCurrentUserInfo().then((userInfo) => {
			dispatch(actions.actionCreator({
				type: actions.ActionTypes.PREPARE_SAVE_EXPERIMENT,
				userId: userInfo.userId
			}));

			return myaws.DynamoDB.saveExperiment(getState().experimentState);
		}).then(() => {
			utils.notifications.notifySuccessBySnackbar({
				dispatch,
				message: "Saved !"
			});
		});
	})
}

const signIn = ({dispatch, username, password, firstSignIn=false}) => {
	return dispatch((dispatch, getState) => {
		return myaws.Auth.signIn({
			username,
			password
		}).then((userInfo) => {
			// if it is first time signing in
			// register user in DynamoDB
			if (firstSignIn) {
				let { userId, username, email } = userInfo;

				return myaws.DynamoDB.saveUserData(core.createUser({
					userId,
					username,
					email
				}));
			}

			return Promise.resolve();
		}).then(() => {
			// if user has changed anything
			// save the change

			let anyChange = !utils.deepEqual(core.getInitExperimentState(), getState().experimentState);
			if (anyChange) {
				return saveExperiment({dispatch});
			}

			return Promise.resolve();
		}).then(() => {
			return load({dispatch});
		}).catch((err) => {
			if (err.code === "UserNotConfirmedException") {
				popVerification({
					dispatch,
					signInCallback: () => {
						return signIn({
							dispatch,
							username,
							password,
							firstSignIn
						});
					}
				});
			} else {
				throw err;
			}
		});
	});
}

const signUp = ({dispatch, username, password, attributes, ...options}) => {
	return myaws.Auth.signUp({username, password, attributes, ...options}).then(() => {
		popVerification({
			dispatch,
			signInCallback: () => {
				return signIn({
					dispatch,
					username,
					password,
					firstSignIn: true,
				})
			}
		});
	});
}

const handleWindowClose = ({dispatch}) => {
	dispatch(actions.actionCreator({
		type: actions.ActionTypes.SET_AUTH_WINDOW,
		open: false
	}));
}

export const popSignIn = ({dispatch}) => {
	dispatch(actions.actionCreator({
		type: actions.ActionTypes.SET_AUTH_WINDOW,
		open: true,
		loginMode: enums.AUTH_MODES.signIn
	}));
}

export const popRegister = ({dispatch}) => {
	dispatch(actions.actionCreator({
		type: actions.ActionTypes.SET_AUTH_WINDOW,
		open: true,
		loginMode: enums.AUTH_MODES.register
	}));
}

export const popForgetPassword = ({dispatch}) => {
	dispatch(actions.actionCreator({
		type: actions.ActionTypes.SET_AUTH_WINDOW,
		open: true,
		loginMode: enums.AUTH_MODES.forgotPassword
	}));
}

export const popVerification = ({dispatch, ...args}) => {
	dispatch(actions.actionCreator({
		type: actions.ActionTypes.SET_AUTH_WINDOW,
		open: true,
		loginMode: enums.AUTH_MODES.verification,
		...args
	}));
}

const setLoginMode = ({dispatch, mode}) => {
	dispatch(actions.actionCreator({
		type: actions.ActionTypes.SET_AUTH_WINDOW,
		loginMode: mode
	}));
}

const mapStateToProps = (state, ownProps) => {
  return {
  	...state.authentications
  }
}

const mapDispatchToProps = (dispatch, ownProps) => ({
	signIn: ({...args}) => signIn({dispatch, ...args}),
	signUp: ({...args}) => signUp({dispatch, ...args}),
	load: () => load({dispatch}),
	handleWindowClose: () => handleWindowClose({dispatch}),
	popSignIn: () => popSignIn({dispatch}),
	popRegister: () => popRegister({dispatch}),
	popForgetPassword: () => popForgetPassword({dispatch}),
	popVerification: () => popVerification({dispatch}),
	setLoginMode: (mode) => setLoginMode({dispatch, mode}),
})

export default connect(mapStateToProps, mapDispatchToProps)(Authentications);
<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@storybook/react';
import {
  text, array
} from '@storybook/addon-knobs';
import { action } from '@storybook/addon-actions';
import { State, Store } from '@sambego/storybook-state';
import SimpleColorPicker from './simple-color-picker';
import { notes, info } from './documentation';

const store = new Store({
  selectedColor: '#00DC00'
});

const onChange = (e) => {
  store.set({
    selectedColor: e.target.value
  });
  action('select')();
};

storiesOf('SimpleColorPicker', module)
  .addParameters({
    info: {
      propTablesExclude: [State]
    }
  })

  .add('default', () => {
    const name = text('name', 'basicPicker');
    const availableColors = array('availableColors', ['#00DC00', '#255BC7', '#ED1C5F']);

    return (
      <State store={ store }>
        <SimpleColorPicker
          availableColors={ availableColors }
          name={ name }
          onChange={ onChange }

        />
      </State>
    );
  }, {
    notes: { markdown: notes },
    info: { text: info }
  });
<commit_msg>update simple color picker<commit_after>import React from 'react';
import { storiesOf } from '@storybook/react';
import { text, array } from '@storybook/addon-knobs';
import { action } from '@storybook/addon-actions';
import { State, Store } from '@sambego/storybook-state';
import SimpleColorPicker from './simple-color-picker';
import { notes, info } from './documentation';

const store = new Store({
  selectedColor: '#00DC00'
});

const onChange = (e) => {
  store.set({
    selectedColor: e.target.value
  });
  action('select')();
};

storiesOf('SimpleColorPicker', module)
  .addParameters({
    info: {
      propTablesExclude: [State]
    }
  })

  .add(
    'default',
    () => {
      const name = text('name', 'basicPicker');
      const availableColors = array('availableColors', ['#00DC00', '#255BC7', '#ED1C5F']);

      return (
        <State store={ store }>
          <SimpleColorPicker
            availableColors={ availableColors } name={ name }
            onChange={ onChange }
          />
        </State>
      );
    },
    {
      notes: { markdown: notes },
      info: { text: info }
    }
  );
<|endoftext|>


<commit_before>var async = require('async'),
    EventEmitter2 = require('eventemitter2').EventEmitter2;

/**
 * Manages the state and loading of multiple resources to load.
 *
 * @class
 * @param baseUrl {string} The base url for all resources loaded by this loader.
 */
function Loader(baseUrl) {
    EventEmitter2.call(this);

    /**
     * The base url for all resources loaded by this loader.
     *
     * @member {string}
     */
    this.baseUrl = baseUrl || '';

    /**
     * The resources waiting to be loaded.
     *
     * @member {Resource[]}
     */
    this.queue = [];

    /**
     * The progress percent of the loader going through the queue.
     *
     * @member {number}
     */
    this.progress = 0;

    /**
     * The percentage of total progress that a single resource represents.
     *
     * @member {number}
     */
    this._progressChunk = 0;

    /**
     * The middleware to run before loading each resource.
     *
     * @member {function[]}
     */
    this._beforeMiddleware = [];

    /**
     * The middleware to run after loading each resource.
     *
     * @member {function[]}
     */
    this._afterMiddleware = [];

    /**
     * The `_loadResource` function bound with this object context.
     *
     * @private
     * @member {function}
     */
    this._boundLoadResource = this._loadResource.bind(this);

    /**
     * The `_onComplete` function bound with this object context.
     *
     * @private
     * @member {function}
     */
    this._boundOnComplete = this._onComplete.bind(this);

    /**
     * Emitted once per loaded or errored resource.
     *
     * @event progress
     */

    /**
     * Emitted once per errored resource.
     *
     * @event error
     */

    /**
     * Emitted once per loaded resource.
     *
     * @event load
     */

    /**
     * Emitted when the loader begins to process the queue.
     *
     * @event start
     */

    /**
     * Emitted when the queued resources all load.
     *
     * @event complete
     */
}

Loader.prototype = Object.create(EventEmitter2.prototype);
Loader.prototype.constructor = Loader;
module.exports = Loader;

/**
 * Adds a resource (or multiple resources) to the loader queue.
 *
 * @alias enqueue
 * @param url {string} The url for this resource, relative to the baseUrl of this loader.
 * @param [crossOrigin] {boolean} Is this request cross-origin? Default is to determine automatically.
 * @param [loadType=Resource.LOAD_TYPE.XHR] {Resource.LOAD_TYPE} How should this resource be loaded?
 * @return {Loader}
 */
Loader.prototype.add = Loader.prototype.enqueue = function (url, crossOrigin, loadType) {
    this.queue.push(new Resource(this.baseUrl + url, crossOrigin, loadType));

    return this;
};

/**
 * Sets up a middleware function that will run *before* the
 * resource is loaded.
 *
 * @alias before
 * @param middleware {function} The middleware function to register.
 * @return {Loader}
 */
Loader.prototype.pre = Loader.prototype.before = function (fn) {
    this._beforeMiddleware.push(fn);

    return this;
};

/**
 * Sets up a middleware function that will run *after* the
 * resource is loaded.
 *
 * @alias after
 * @param middleware {function} The middleware function to register.
 * @return {Loader}
 */
Loader.prototype.use = Loader.prototype.after = function (fn) {
    this._afterMiddleware.push(fn);

    return this;
};

/**
 * Resets the queue of the loader to prepare for a new load.
 *
 * @return {Loader}
 */
Loader.prototype.reset = function () {
    this.queue.length = 0;
    this.progress = 0;
};

/**
 * Starts loading the queued resources.
 *
 * @fires start
 * @param [parallel=true] {boolean} Should the queue be downloaded in parallel?
 * @param [callback] {function} Optional callback that will be bound to the `complete` event.
 * @return {Loader}
 */
Loader.prototype.load = function (parallel, cb) {
    if (typeof parallel === 'function') {
        cb = parallel;
    }

    this._progressChunk = 100 / this.queue.length;

    this.emit('start');

    // only disable parallel if they explicitly pass `false`
    if (parallel === false) {
        async.each(this.queue, this._boundLoadResource, this._onComplete);
    }
    else {
        async.eachSeries(this.queue, this._boundLoadResource, this._onComplete);
    }

    return this;
};

/**
 * Loads a single resource.
 *
 * @fires progress
 * @private
 */
Loader.prototype._loadResource = function (resource, next) {
    var self = this;

    this._runMiddleware(resource, this._beforeMiddleware, function () {
        resource.on('progress', self.emit.bind(self, 'progress'));
        resource.on('load', self._onLoad.bind(self, resource, next));

        resource.load();
    });
};

/**
 * Called once each resource has loaded.
 *
 * @fires complete
 * @private
 */
Loader.prototype._onComplete = function () {
    this.emit('complete');
};

/**
 * Called each time a resources is loaded.
 *
 * @fires progress
 * @fires error
 * @fires load
 * @private
 */
Loader.prototype._onLoad = function (resource, next) {
    this.progress += this._progressChunk;

    this.emit('progress', resource);

    if (resource.error) {
        this.emit('error', resource);
    }
    else {
        this.emit('load', resource)
    }

    this._runMiddleware(resource, this._afterMiddleware, next);
};

/**
 * Run middleware functions on a resource.
 *
 * @private
 */
Loader.prototype._runMiddleware = function (resource, fns, cb) {
    var self = this;

    async.eachSeries(fns, function (fn, next) {
        fn.call(self, resource, next);
    }, cb);
};

Loader.LOAD_TYPE = Resource.LOAD_TYPE;
Loader.XHR_READY_STATE = Resource.XHR_READY_STATE;
Loader.XHR_RESPONSE_TYPE = Resource.XHR_RESPONSE_TYPE;
<commit_msg>add callback of load to complete event<commit_after>var async = require('async'),
    EventEmitter2 = require('eventemitter2').EventEmitter2;

/**
 * Manages the state and loading of multiple resources to load.
 *
 * @class
 * @param baseUrl {string} The base url for all resources loaded by this loader.
 */
function Loader(baseUrl) {
    EventEmitter2.call(this);

    /**
     * The base url for all resources loaded by this loader.
     *
     * @member {string}
     */
    this.baseUrl = baseUrl || '';

    /**
     * The resources waiting to be loaded.
     *
     * @member {Resource[]}
     */
    this.queue = [];

    /**
     * The progress percent of the loader going through the queue.
     *
     * @member {number}
     */
    this.progress = 0;

    /**
     * The percentage of total progress that a single resource represents.
     *
     * @member {number}
     */
    this._progressChunk = 0;

    /**
     * The middleware to run before loading each resource.
     *
     * @member {function[]}
     */
    this._beforeMiddleware = [];

    /**
     * The middleware to run after loading each resource.
     *
     * @member {function[]}
     */
    this._afterMiddleware = [];

    /**
     * The `_loadResource` function bound with this object context.
     *
     * @private
     * @member {function}
     */
    this._boundLoadResource = this._loadResource.bind(this);

    /**
     * The `_onComplete` function bound with this object context.
     *
     * @private
     * @member {function}
     */
    this._boundOnComplete = this._onComplete.bind(this);

    /**
     * Emitted once per loaded or errored resource.
     *
     * @event progress
     */

    /**
     * Emitted once per errored resource.
     *
     * @event error
     */

    /**
     * Emitted once per loaded resource.
     *
     * @event load
     */

    /**
     * Emitted when the loader begins to process the queue.
     *
     * @event start
     */

    /**
     * Emitted when the queued resources all load.
     *
     * @event complete
     */
}

Loader.prototype = Object.create(EventEmitter2.prototype);
Loader.prototype.constructor = Loader;
module.exports = Loader;

/**
 * Adds a resource (or multiple resources) to the loader queue.
 *
 * @alias enqueue
 * @param url {string} The url for this resource, relative to the baseUrl of this loader.
 * @param [crossOrigin] {boolean} Is this request cross-origin? Default is to determine automatically.
 * @param [loadType=Resource.LOAD_TYPE.XHR] {Resource.LOAD_TYPE} How should this resource be loaded?
 * @return {Loader}
 */
Loader.prototype.add = Loader.prototype.enqueue = function (url, crossOrigin, loadType) {
    this.queue.push(new Resource(this.baseUrl + url, crossOrigin, loadType));

    return this;
};

/**
 * Sets up a middleware function that will run *before* the
 * resource is loaded.
 *
 * @alias before
 * @param middleware {function} The middleware function to register.
 * @return {Loader}
 */
Loader.prototype.pre = Loader.prototype.before = function (fn) {
    this._beforeMiddleware.push(fn);

    return this;
};

/**
 * Sets up a middleware function that will run *after* the
 * resource is loaded.
 *
 * @alias after
 * @param middleware {function} The middleware function to register.
 * @return {Loader}
 */
Loader.prototype.use = Loader.prototype.after = function (fn) {
    this._afterMiddleware.push(fn);

    return this;
};

/**
 * Resets the queue of the loader to prepare for a new load.
 *
 * @return {Loader}
 */
Loader.prototype.reset = function () {
    this.queue.length = 0;
    this.progress = 0;
};

/**
 * Starts loading the queued resources.
 *
 * @fires start
 * @param [parallel=true] {boolean} Should the queue be downloaded in parallel?
 * @param [callback] {function} Optional callback that will be bound to the `complete` event.
 * @return {Loader}
 */
Loader.prototype.load = function (parallel, cb) {
    if (typeof parallel === 'function') {
        cb = parallel;
    }

    if (typeof cb === 'function') {
        this.once('complete', cb);
    }

    this._progressChunk = 100 / this.queue.length;

    this.emit('start');

    // only disable parallel if they explicitly pass `false`
    if (parallel === false) {
        async.each(this.queue, this._boundLoadResource, this._onComplete);
    }
    else {
        async.eachSeries(this.queue, this._boundLoadResource, this._onComplete);
    }

    return this;
};

/**
 * Loads a single resource.
 *
 * @fires progress
 * @private
 */
Loader.prototype._loadResource = function (resource, next) {
    var self = this;

    this._runMiddleware(resource, this._beforeMiddleware, function () {
        resource.on('progress', self.emit.bind(self, 'progress'));
        resource.on('load', self._onLoad.bind(self, resource, next));

        resource.load();
    });
};

/**
 * Called once each resource has loaded.
 *
 * @fires complete
 * @private
 */
Loader.prototype._onComplete = function () {
    this.emit('complete');
};

/**
 * Called each time a resources is loaded.
 *
 * @fires progress
 * @fires error
 * @fires load
 * @private
 */
Loader.prototype._onLoad = function (resource, next) {
    this.progress += this._progressChunk;

    this.emit('progress', resource);

    if (resource.error) {
        this.emit('error', resource);
    }
    else {
        this.emit('load', resource)
    }

    this._runMiddleware(resource, this._afterMiddleware, next);
};

/**
 * Run middleware functions on a resource.
 *
 * @private
 */
Loader.prototype._runMiddleware = function (resource, fns, cb) {
    var self = this;

    async.eachSeries(fns, function (fn, next) {
        fn.call(self, resource, next);
    }, cb);
};

Loader.LOAD_TYPE = Resource.LOAD_TYPE;
Loader.XHR_READY_STATE = Resource.XHR_READY_STATE;
Loader.XHR_RESPONSE_TYPE = Resource.XHR_RESPONSE_TYPE;
<|endoftext|>


<commit_before>// ==UserScript==
// @name         byr-signature
// @namespace    https://github.com/flowmemo/byr-signature
// @version      0.1.5
// @description  为北邮人论坛发帖添加个性签名
// @author       flowmemo
// @match        https://bbs.byr.cn/*
// @grant        GM_getValue
// @grant        GM_setValue
// @license      MIT
// ==/UserScript==

// JavaScript Standard Style: https://github.com/feross/standard

;(function () {
  'use strict'

  log('hello')

  var _DEBUG = 0
  function log () {
    if (_DEBUG === 1) console.log.apply(console, arguments)
  }

  var defaultSig = '————\n' +
        '示例签名:\n' +
        '微博 [url=http://weibo.com/flowmemo][color=#0000FF]@flowmemo[/color][/url] , 现在主要写JavaScript. 关注广泛, 欢迎交流.\n' +
        '\n' +
        '[url=https://github.com/flowmemo/byr-signature][color=#0000FF]此签名通过「北邮人签名档」脚本发送[/color][/url]'
  var id // timeout id

  function addPostSig () {
    log('addPostSig')
    var signature = GM_getValue('sig', defaultSig)
    var div = document.getElementById('post_content')
    if (!div) return
    div.value += '\n' + signature
    return true
  }

  function addQuickSig () {
    log('addQuickSig')

    var signature = GM_getValue('sig', defaultSig)
    var page = document.querySelector('.page-select a')
    if (!page) return
    var curPage = page.text
    if (!window.location.href.match(/\?p=(\d+)/)) {
      if (curPage !== '1') return
    } else {
      var hrefPage = window.location.href.match(/\?p=(\d+)/)[1]
      if (hrefPage !== curPage) return
    }

    var div = document.getElementsByName('content')[0]
    if (!div) return
    div.value += '\n' + signature
    log('add value')
    return true
  }

  function addSigPanel () {
    log('sigPanel')

    var div = document.createElement('div')
    var postItems = document.getElementsByClassName('post-list-item')
    var referNode = postItems[postItems.length - 2]
    referNode.appendChild(div)

    div.outerHTML = '

' +
            '
byr-signature自定义签名
' +
            '
' +
            '<textarea class="post-textarea" name="sig-content" placeholder="在此输入你的签名"></textarea>
' +
            '

<input name="saveSig" type="button" value="保存"> 保存后刷新页面生效（注意保存你的发帖内容）

'

    var userSig = document.getElementsByName('sig-content')[0]
    userSig.value = GM_getValue('sig', defaultSig)
    var saveButton = document.getElementsByName('saveSig')[0]
    saveButton.addEventListener('click', function () {
      GM_setValue('sig', (userSig.value))
    })
  }

  function polling () {
    log('polling')

    if (window.location.href.indexOf('#!article') === -1) return
    window.clearTimeout(id) // clear timeout if it already exists

    ;(function cb () {
      if (window.location.href.indexOf('/post') > -1) {
        if (addPostSig()) {
          addSigPanel()
          return
        }
      } else if (addQuickSig()) return
      id = setTimeout(cb, 300)
    })()
  }

  if (window.location.href.indexOf('#!article') > -1) polling()
  window.addEventListener('hashchange', polling)
})()
<commit_msg>update default sig<commit_after>// ==UserScript==
// @name         byr-signature
// @namespace    weibo.com/flowmemo
// @version      0.1.6
// @description  为北邮人论坛发帖添加个性签名
// @author       flowmemo
// @match        https://bbs.byr.cn/*
// @grant        GM_getValue
// @grant        GM_setValue
// @license      MIT
// ==/UserScript==

// JavaScript Standard Style: https://github.com/feross/standard

;(function () {
  'use strict'
  var _DEBUG = 0
  function log () {
    if (_DEBUG === 1) console.log.apply(console, arguments)
  }

  log('hello')

  var defaultSig = '————\n' +
        '示例签名: 微博 [url=http://weibo.com/flowmemo][color=#0000FF]@flowmemo[/color][/url] , 现在主要写JavaScript. 关注广泛, 欢迎交流.\n' +
        '修改签名请到[url=https://bbs.byr.cn/#!article/WWWTechnology/post][color=#0000FF]这里[/color][/url]\n' +
        '[url=https://github.com/flowmemo/byr-signature][color=#0000FF]此签名通过「北邮人签名档」脚本发送[/color][/url]'
  var id // timeout id

  function addPostSig () {
    log('addPostSig')
    var signature = GM_getValue('sig', defaultSig)
    var div = document.getElementById('post_content')
    if (!div) return
    div.value += '\n' + signature
    return true
  }

  function addQuickSig () {
    log('addQuickSig')

    var signature = GM_getValue('sig', defaultSig)
    var page = document.querySelector('.page-select a')
    if (!page) return
    var curPage = page.text
    if (!window.location.href.match(/\?p=(\d+)/)) {
      if (curPage !== '1') return
    } else {
      var hrefPage = window.location.href.match(/\?p=(\d+)/)[1]
      if (hrefPage !== curPage) return
    }

    var div = document.getElementsByName('content')[0]
    if (!div) return
    div.value += '\n' + signature
    log('add value')
    return true
  }

  function addSigPanel () {
    log('sigPanel')

    var div = document.createElement('div')
    var postItems = document.getElementsByClassName('post-list-item')
    var referNode = postItems[postItems.length - 2]
    referNode.appendChild(div)

    div.outerHTML = '

' +
            '
byr-signature自定义签名
' +
            '
' +
            '<textarea class="post-textarea" name="sig-content" placeholder="在此输入你的签名"></textarea>
' +
            '

<input name="saveSig" type="button" value="保存"> 保存后刷新页面生效（注意保存你的发帖内容）

'

    var userSig = document.getElementsByName('sig-content')[0]
    userSig.value = GM_getValue('sig', defaultSig)
    var saveButton = document.getElementsByName('saveSig')[0]
    saveButton.addEventListener('click', function () {
      GM_setValue('sig', (userSig.value))
    })
  }

  function polling () {
    log('polling')

    if (window.location.href.indexOf('#!article') === -1) return
    window.clearTimeout(id) // clear timeout if it already exists

    ;(function cb () {
      if (window.location.href.indexOf('/post') > -1) {
        if (addPostSig()) {
          addSigPanel()
          return
        }
      } else if (addQuickSig()) return
      id = setTimeout(cb, 300)
    })()
  }

  if (window.location.href.indexOf('#!article') > -1) polling()
  window.addEventListener('hashchange', polling)
})()
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        //app.receivedEvent('deviceready');
        document.addEventListener("menubutton", menuKeyDown, false);
        document.addEventListener("backbutton", backKeyDown, false);
    }

    /* // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
        //alert('Received Event: ' + id);
    }*/
};

function menuKeyDown() {
	$('#menu').slideDown('fast');
	return false;
}

function backKeyDown() {
	var exit = true;
	if ($('#menu').is(':visible')) {
		$('#menu').hide();
		exit = false;
	}
	if ($('#aboutDialog').is(':visible')) {
		window.history.back();
		exit = false;
	}
	if (!exit) {
		return false; // back button was used to exit a menu, don't exit app
	}

	return exitApp();
}

function exitApp() {
	navigator.app.exitApp();
	return true;
}

var MILLISECONDS_WAIT = 5000;
var NUM_ENTRIES_PER_COLUMN = 4;
var feedList = [{name: 'Dear Prudence', url: 'http://www.slate.com/articles/life/dear_prudence.fulltext.all.10.rss', image: 'prudie.jpg'},
	            {name: 'Carolyn Hax', url: 'http://feeds.washingtonpost.com/rss/linksets/lifestyle/carolyn-hax', image: 'hax.jpg'},
	            {name: 'Savage Love', url: 'http://www.thestranger.com/gyrobase/Rss.xml?category=258', image: 'savage.jpg'},
	            {name: "Annie's Mailbox", url: 'http://www.creators.com/advice/annies-mailbox.rss', image: 'annies.jpg'},
	            {name: 'Dear Margo', url: 'http://www.creators.com/advice/dear-margo.rss', image: 'margo.jpg'},
	            {name: 'Miss Information', url: 'http://www.nerve.com/taxonomy/term/95215/all/feed', image: 'miss_information.jpg'},
	            {name: 'Questionable Advice', url: 'http://www.creators.com/advice/questionable-advice.rss', image: 'jessica_leigh.jpg'},
	            {name: 'The Advice Goddess', url: 'http://www.creators.com/advice/advice-goddess-amy-alkon.rss', image: 'amy_alkon.jpg'},
	            {name: 'Tales From The Front', url: 'http://www.creators.com/advice/tales-from-the-front.rss', image: 'cheryl_lavin.jpg'},
	            {name: 'At Work', url: 'http://www.creators.com/advice/at-work-lindsey-novak.rss', image: 'lindsey_novak.jpg'}];

function displayAbout() {
	$('#menu').hide();
	$.mobile.changePage("#aboutDialog");
	return false;
}

function refreshColumns() {
	$('#menu').hide();
	loadColumns();
	$('html, body').animate({ scrollTop: 0 }, 'fast');
	return false;
}

function loadColumns() {
	$('#loadingImage').show('slow');
	for (i = 0; i < feedList.length; i++) {
		displayColumnEntries(feedList[i]['name'], feedList[i]['url'], feedList[i]['image']);
	}
	window.setTimeout('cleanupOldColumnEntries()', MILLISECONDS_WAIT + 1500);
}

function loadAboutColumnNames() {
	$('#aboutList').append('
Columns: ' + buildColumnNames() + '
');
}

function cleanupOldColumnEntries() {
	var maxEntries = feedList.length * NUM_ENTRIES_PER_COLUMN;
	//console.log('maxEntries: ', maxEntries);
	$("#adviceList li").each(function( index ) {
		  //console.log(index, ": ", $(this).text());
		  if (index > maxEntries) {
			  //console.log('removing ', index);
			  $(this).remove();
		  }
	});
}

function displayColumnEntries(name, url, image) {
	$.jGFeed(url, function(feeds) {
	    // Check for errors
	    if(!feeds || typeof feeds === 'undefined') {
	    	alert('Sorry - there has been an error receiving the advice column feeds.');
	    	return false;
	    }

		for (var j=0; j<feeds.entries.length; j++) {
	        var entry = feeds.entries[j];
	        if ($('#adviceList li[data-entry-id="' + entry.link + '"]').length === 0) {
	        	$('#adviceList').append(buildEntryString(name, entry, image));
	        }
		}

		// sort 1 time(s), 5 seconds total wait
		window.setTimeout('sortElements(' + 1 + ')', MILLISECONDS_WAIT);
	}, NUM_ENTRIES_PER_COLUMN);
}

function sortElements(marker) {
	$('#adviceList li').sort(function(a, b) {
	    return a.dataset.timestamp > b.dataset.timestamp ? -1 : 1;
	}).appendTo('#adviceList');

	if (--marker < 1) {
		$('#loadingImage').fadeOut('slow');
		return;
	}
	window.setTimeout('sortElements(' + marker + ')', MILLISECONDS_WAIT);
}

function buildEntryString(name, entry, image) {
	var dateArr = entry.publishedDate.split(' ');
	var title = fixTitle(entry.title);

	return '
'
	  + '
' + dateArr[0] + ' ' + dateArr[2] + ' ' + dateArr[1] + ', ' + dateArr[3] + '
'
	  + '
' + (entry.title.search(name) >= 0 ? '' : name + ': ') + title + '
'
	  + '
' + (typeof image !== 'undefined' ? '' : '')
	  + fixContent(entry.content) + '
'
	  + '
Read
'
	  + '
';
}

function buildColumnNames() {
	var html = '';
	for (i = 0; i < feedList.length; i++) {
		html += feedList[i].name;
		if (i < feedList.length - 1) {
			html += ', ';
		}
	}
	return html;
}

function fixTitle(entryTitle) {
	// remove the "for MM/DD/YYY" from the end of creator.com titles
	var titleMatch = entryTitle.match(/.*(\sfor\s\d\d\/\d\d\/\d\d\d\d)$/);
	if (titleMatch) { // check if the input string matched the pattern
	     entryTitle = entryTitle.substring(0, entryTitle.search(titleMatch[1])); // get the capturing group
	}
	return entryTitle;
}

function fixContent(content) {
	// replace "a href" links with in app browser links
	var regex = new RegExp("()", 'g');
	if (content.match(regex)) {
	    content = content.replace(regex, "$1" + '"javascript:void(0);" onclick="openLink(\'' + "$2" + '\');"' + "$3");
	}
	return content;
}

function openLink(link) {
	navigator.app.loadUrl(link, { openExternal: true });
	//window.plugins.childBrowser.showWebPage(link, { showLocationBar: true });
}<commit_msg>added filter for feeds that include non-advice column entries<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        //app.receivedEvent('deviceready');
        document.addEventListener("menubutton", menuKeyDown, false);
        document.addEventListener("backbutton", backKeyDown, false);
    }

    /* // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
        //alert('Received Event: ' + id);
    }*/
};

function menuKeyDown() {
	$('#menu').slideDown('fast');
	return false;
}

function backKeyDown() {
	var exit = true;
	if ($('#menu').is(':visible')) {
		$('#menu').hide();
		exit = false;
	}
	if ($('#aboutDialog').is(':visible')) {
		window.history.back();
		exit = false;
	}
	if (!exit) {
		return false; // back button was used to exit a menu, don't exit app
	}

	return exitApp();
}

function exitApp() {
	navigator.app.exitApp();
	return true;
}

var MILLISECONDS_WAIT = 5000;
var NUM_ENTRIES_PER_COLUMN = 4;
var feedList = [{name: 'Dear Prudence', url: 'http://www.slate.com/articles/life/dear_prudence.fulltext.all.10.rss', image: 'prudie.jpg'},
	            {name: 'Carolyn Hax', url: 'http://feeds.washingtonpost.com/rss/linksets/lifestyle/carolyn-hax', image: 'hax.jpg'},
	            {name: 'Savage Love', url: 'http://www.thestranger.com/gyrobase/Rss.xml?category=258', image: 'savage.jpg'},
	            {name: "Annie's Mailbox", url: 'http://www.creators.com/advice/annies-mailbox.rss', image: 'annies.jpg'},
	            {name: 'Dear Margo', url: 'http://www.creators.com/advice/dear-margo.rss', image: 'margo.jpg'},
	            {name: 'Miss Information', url: 'http://www.nerve.com/taxonomy/term/95215/all/feed', image: 'miss_information.jpg'},
	            {name: 'Questionable Advice', url: 'http://www.creators.com/advice/questionable-advice.rss', image: 'jessica_leigh.jpg'},
	            {name: 'The Advice Goddess', url: 'http://www.creators.com/advice/advice-goddess-amy-alkon.rss', image: 'amy_alkon.jpg'},
	            {name: 'Tales From The Front', url: 'http://www.creators.com/advice/tales-from-the-front.rss', image: 'cheryl_lavin.jpg'},
	            {name: 'At Work', url: 'http://www.creators.com/advice/at-work-lindsey-novak.rss', image: 'lindsey_novak.jpg'},
	            {name: 'The Awl', url: 'http://feeds.feedburner.com/TheAwl?format=xml', image: 'the_awl.png', filter: {category: 'Advice'}}];

function displayAbout() {
	$('#menu').hide();
	$.mobile.changePage("#aboutDialog");
	return false;
}

function refreshColumns() {
	$('#menu').hide();
	loadColumns();
	$('html, body').animate({ scrollTop: 0 }, 'fast');
	return false;
}

function loadColumns() {
	$('#loadingImage').show('slow');
	for (i = 0; i < feedList.length; i++) {
		displayColumnEntries(feedList[i]['name'], feedList[i]['url'], feedList[i]['image'], feedList[i]['filter']);
	}
	window.setTimeout('cleanupOldColumnEntries()', MILLISECONDS_WAIT + 1500);
}

function loadAboutColumnNames() {
	$('#aboutList').append('
Columns: ' + buildColumnNames() + '
');
}

function cleanupOldColumnEntries() {
	var maxEntries = feedList.length * NUM_ENTRIES_PER_COLUMN;
	//console.log('maxEntries: ', maxEntries);
	$("#adviceList li").each(function( index ) {
		  //console.log(index, ": ", $(this).text());
		  if (index > maxEntries) {
			  //console.log('removing ', index);
			  $(this).remove();
		  }
	});
}

function displayColumnEntries(name, url, image, filter) {
	$.jGFeed(url, function(feeds) {
	    // Check for errors
	    if(!feeds || typeof feeds === 'undefined') {
	    	alert('Sorry - there has been an error receiving the advice column feeds.');
	    	return false;
	    }

		for (var j=0; j<feeds.entries.length; j++) {
	        var entry = feeds.entries[j];
	        if (shouldIncludeEntry(entry, filter)) {
		        if ($('#adviceList li[data-entry-id="' + entry.link + '"]').length === 0) {
		        	$('#adviceList').append(buildEntryString(name, entry, image));
		        }
	        }
		}

		// sort 1 time(s), 5 seconds total wait
		window.setTimeout('sortElements(' + 1 + ')', MILLISECONDS_WAIT);
	}, NUM_ENTRIES_PER_COLUMN);
}

function shouldIncludeEntry(entry, filter) {
	if (filter === undefined) {
		return true; // no filter - include entry by default
	}

	if (filter['category'] !== undefined) { // filtering is by category
		if (entry.categories && entry.categories.length > 0) {
			for (i = 0; i < entry.categories.length; i++) {
				//console.log('checking filter', filter.category, 'vs:', entry.categories[i]);
				if (filter.category === entry.categories[i]) {
					//console.log('Found it - returning true');
					return true;
				}
			}
		}
	}

	// there was a filter, but we couldn't match it
	//console.log('Did not find a category match - returning false');
	return false;
}

function sortElements(marker) {
	$('#adviceList li').sort(function(a, b) {
	    return a.dataset.timestamp > b.dataset.timestamp ? -1 : 1;
	}).appendTo('#adviceList');

	if (--marker < 1) {
		$('#loadingImage').fadeOut('slow');
		return;
	}
	window.setTimeout('sortElements(' + marker + ')', MILLISECONDS_WAIT);
}

function buildEntryString(name, entry, image) {
	var dateArr = entry.publishedDate.split(' ');
	var title = fixTitle(name, entry.title);

	return '
'
	  + '
' + dateArr[0] + ' ' + dateArr[2] + ' ' + dateArr[1] + ', ' + dateArr[3] + '
'
	  + '
' + title + '
'
	  + '
' + (typeof image !== 'undefined' ? '' : '')
	  + fixContent(entry.content) + '
'
	  + '
Read
'
	  + '
';
}

function buildColumnNames() {
	var html = '';
	for (i = 0; i < feedList.length; i++) {
		html += feedList[i].name;
		if (i < feedList.length - 1) {
			html += ', ';
		}
	}
	return html;
}

function fixTitle(name, title) {
	// remove the "for MM/DD/YYY" from the end of creator.com titles
	var titleMatch = title.match(/.*(\sfor\s\d\d\/\d\d\/\d\d\d\d)$/);
	if (titleMatch) { // check if the input string matched the pattern
	     title = title.substring(0, title.search(titleMatch[1])); // get the capturing group
	}

	if (name !== 'The Awl' && title.search(name) < 0) {
		title = name + ': ' + title;
	}

	return title;
}

function fixContent(content) {
	// replace "a href" links with in app browser links
	var regex = new RegExp("()", 'g');
	if (content.match(regex)) {
	    content = content.replace(regex, "$1" + '"javascript:void(0);" onclick="openLink(\'' + "$2" + '\');"' + "$3");
	}
	return content;
}

function openLink(link) {
	navigator.app.loadUrl(link, { openExternal: true });
	//window.plugins.childBrowser.showWebPage(link, { showLocationBar: true });
}<|endoftext|>