<commit_before>define(function(require, exports, module) {
    "use strict";
    main.consumes = [
        "Plugin", "upload", "tree", "ui", "layout", "c9", "tabManager"
    ];

    main.provides = ["dragdrop"];
    return main;

    function main(options, imports, register) {
        var Plugin   = imports.Plugin;
        var upload   = imports.upload;
        var tree     = imports.tree;
        var ui       = imports.ui;
        var c9       = imports.c9;
        var tabs     = imports.tabManager;

        var css      = require("text!./dragdrop.css");
        var dirname  = require("path").dirname;

        var treeAsPane = true || options.treeAsPane;
        var dropbox, treeMouseHandler;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);

        var loaded = false;
        function load() {
            if (loaded) return false;
            loaded = true;

            ui.insertCss(css, plugin);

            document.addEventListener("dragenter", dragEnter, true);
            document.addEventListener("dragleave", dragLeave, true);
            document.addEventListener("dragover", dragOver, true);
            document.addEventListener("drop", dragDrop, true);

            tree.on("draw", function() {
                var acetree = tree.tree;
                treeMouseHandler = acetree.$mouseHandler;
                acetree.on("dragIn", updateDrag);
                acetree.on("dragMoveOutside", updateDrag);
                acetree.on("dropOutside", treeDrop, false);
                function updateDrag(ev) {
                    var selectedNodes = ev.dragInfo.selectedNodes;
                    var hasFile = selectedNodes && selectedNodes.some(function(node) {
                        return !node.isFolder;
                    });
                    var host = hasFile && findHost(ev.domEvent.target, ev);
                    updateTabDrag(!ev.dragInfo.isInTree && host);
                }
                function treeDrop(ev) {
                    var selectedNodes = ev.dragInfo.selectedNodes;
                    if (selectedNodes && dragContext.pane) {
                        selectedNodes.forEach(function(node, i) {
                            tabs.open({
                                path: node.path,
                                active: i === selectedNodes.length - 1,
                                pane: dragContext.pane
                            }, function(err, tab) {});
                        });
                    }
                    updateTabDrag();
                }
            });
        }

        function unload() {
            loaded = false;
            document.removeEventListener("dragenter", dragEnter, true);
            document.removeEventListener("dragleave", dragLeave, true);
            document.removeEventListener("dragover", dragOver, true);
            document.removeEventListener("drop", dragDrop, true);
        }

        /***** Methods *****/

        var dragContext = {};

        function dragEnter(e) {
            apf.preventDefault(e);
            if (this.disableDropbox || !isFile(e))
                return;
            e.dataTransfer.dropEffect = "copy";
            var host = findHost(e.target, e);
            if (!dragContext.mouseListener && (!treeAsPane || e.ctrlKey))
                window.addEventListener("mousemove", clearDrag, true);
            // TODO open tree panel when hoverng over the button
            updateUploadAreaDrag(e.target.host);
            updateTabDrag(host);
            updateTreeDrag(e, host);

            clearTimeout(dragContext.timer);
        }

        function dragLeave(e) {
            apf.preventDefault(e);
            if (this.disableDropbox)
                return;

            clearTimeout(dragContext.timer);
            dragContext.timer = setTimeout(clearDrag, 100);
        }

        function dragOver(e) {
            apf.preventDefault(e);
            if (this.disableDropbox || !isFile(e))
                return;
            if (treeMouseHandler && treeMouseHandler.$onCaptureMouseMove)
                treeMouseHandler.$onCaptureMouseMove(e);
            if (dragContext.timer)
                dragContext.timer = clearTimeout(dragContext.timer);
            e.dataTransfer.dropEffect = "copy";
        }

        function dragDrop(e) {
            apf.preventDefault(e);
            setTimeout(clearDrag);
            if (this.disableDropbox)
                return;

            var target = dragContext.path || dragContext.pane;
            if (target) {
                upload.uploadFromDrop(e, target,
                    dragContext.pane && !target.isTree ? "tab" : "tree");
                apf.stopEvent(e);
            }
        }

        function clearDrag(e) {
            dragContext.mouseListener = null;
            window.removeEventListener("mousemove", clearDrag, true);
            updateTreeDrag(e);
            updateTabDrag();
            updateUploadAreaDrag();
        }

        // helper
        function findHost(el, e) {
            var treeEl = tree.getElement("container");
            if (treeAsPane && !e.ctrlKey) {
                treeEl = treeEl.parentNode;
            }
            while (el) {
                var host = el.host;
                if (host && (host.cloud9pane))
                    return host;
                if (host && (host === treeEl))
                    return treeAsPane && !e.ctrlKey ? {
                        cloud9pane: {
                            isTree       : true,
                            container    : host.$ext,
                            dropboxTitle : "Drop a file or folder"
                        }
                    } : host;

                if (el === dropbox)
                    return {cloud9pane: dragContext.pane};
                el = el.parentNode;
            }
        }

        function isFile(e) {
            var types = e.dataTransfer.types;
            if (types && Array.prototype.indexOf.call(types, 'Files') !== -1)
                return true;
        }

        function getDropbox(title) {
            if (!dropbox) {
                dropbox = document.createElement("div");
                dropbox.className = "draganddrop";

                var label = document.createElement("span");
                dropbox.appendChild(label);
            }
            dropbox.firstChild.textContent = title || "Drop a file here to open";
            return dropbox;
        }

        function updateTabDrag(host) {
            var pane = host && (host.cloud9pane
                || host.parentNode && host.parentNode.cloud9pane);

            clearTimeout(dragContext.dropboxTimer);
            if (pane) {
                dragContext.path = null;
                if (dragContext.pane === pane)
                    return;

                var parent = pane.container;
                dropbox = getDropbox(pane.dropboxTitle);
                parent && parent.appendChild(dropbox);
                apf.setStyleClass(dropbox, "over");

                dragContext.pane = pane;
            } else if (dragContext.pane) {
                dragContext.pane = null;
                if (dropbox && dropbox.parentNode) {
                    dragContext.dropboxTimer = setTimeout(function(){
                        if (dropbox.parentNode)
                            dropbox.parentNode.removeChild(dropbox);
                    }, 100);
                    apf.setStyleClass(dropbox, null, ["over"]);
                }
            }
        }

        function updateUploadAreaDrag(host) {
            if (host && host.$ext && host.$ext.id === "uploadDropArea") {
                dragContext.uploadDropArea = host.$ext;
                dragContext.path = upload.getTargetFolder().path;
                apf.setStyleClass(dragContext.uploadDropArea, "over");
            } else if (dragContext.uploadDropArea) {
                apf.setStyleClass(dragContext.uploadDropArea, null, ["over"]);
                dragContext.uploadDropArea = null;
            }
        }

        // tree
        function updateTreeDrag(e, host) {
            var online = c9.status & c9.STORAGE;
            if (online && host === tree.getElement("container")) {
                if (!treeMouseHandler.releaseMouse) {
                    treeMouseHandler.captureMouse(e);
                    treeMouseHandler.setState("drag");
                    treeMouseHandler.dragStart();
                    tree.tree.on("folderDragEnter", folderDragEnter);
                    tree.tree.on("folderDragLeave", folderDragLeave);
                }
            } else if (treeMouseHandler && treeMouseHandler.releaseMouse) {
                var path = dragContext.path;
                treeMouseHandler.releaseMouse(e || {});
                tree.tree.off("folderDragEnter", folderDragEnter);
                tree.tree.off("folderDragLeave", folderDragLeave);
                // do not reset path if called from mouseup
                dragContext.path = path;
            }
        }

        function folderDragLeave(node){
            tree.tree.provider.setClass(node, "dragAppendUpload", false);
            dragContext.path = null;
        }

        function folderDragEnter(node){
            tree.tree.provider.setClass(node, "dragAppendUpload", true);
            dragContext.path = node.path;
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
            load();
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
            unload();
        });

        /***** Register and define API *****/

        plugin.freezePublicAPI({});

        register(null, {
            dragdrop: plugin
        });
    }
});<commit_msg>fix +1716 Upload to tree is broken in hosted (shows full pane)<commit_after>define(function(require, exports, module) {
    "use strict";
    main.consumes = [
        "Plugin", "upload", "tree", "ui", "layout", "c9", "tabManager"
    ];

    main.provides = ["dragdrop"];
    return main;

    function main(options, imports, register) {
        var Plugin   = imports.Plugin;
        var upload   = imports.upload;
        var tree     = imports.tree;
        var ui       = imports.ui;
        var c9       = imports.c9;
        var tabs     = imports.tabManager;

        var css      = require("text!./dragdrop.css");
        var dirname  = require("path").dirname;

        var treeAsPane = options.treeAsPane;
        var dropbox, treeMouseHandler;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);

        var loaded = false;
        function load() {
            if (loaded) return false;
            loaded = true;

            ui.insertCss(css, plugin);

            document.addEventListener("dragenter", dragEnter, true);
            document.addEventListener("dragleave", dragLeave, true);
            document.addEventListener("dragover", dragOver, true);
            document.addEventListener("drop", dragDrop, true);

            tree.on("draw", function() {
                var acetree = tree.tree;
                treeMouseHandler = acetree.$mouseHandler;
                acetree.on("dragIn", updateDrag);
                acetree.on("dragMoveOutside", updateDrag);
                acetree.on("dropOutside", treeDrop, false);
                function updateDrag(ev) {
                    var selectedNodes = ev.dragInfo.selectedNodes;
                    var hasFile = selectedNodes && selectedNodes.some(function(node) {
                        return !node.isFolder;
                    });
                    var host = hasFile && findHost(ev.domEvent.target, ev);
                    updateTabDrag(!ev.dragInfo.isInTree && host);
                }
                function treeDrop(ev) {
                    var selectedNodes = ev.dragInfo.selectedNodes;
                    if (selectedNodes && dragContext.pane) {
                        selectedNodes.forEach(function(node, i) {
                            tabs.open({
                                path: node.path,
                                active: i === selectedNodes.length - 1,
                                pane: dragContext.pane
                            }, function(err, tab) {});
                        });
                    }
                    updateTabDrag();
                }
            });
        }

        function unload() {
            loaded = false;
            document.removeEventListener("dragenter", dragEnter, true);
            document.removeEventListener("dragleave", dragLeave, true);
            document.removeEventListener("dragover", dragOver, true);
            document.removeEventListener("drop", dragDrop, true);
        }

        /***** Methods *****/

        var dragContext = {};

        function dragEnter(e) {
            apf.preventDefault(e);
            if (plugin.disableDropbox || !isFile(e))
                return;
            var host = findHost(e.target, e);
            if (!dragContext.mouseListener && (!treeAsPane || e.ctrlKey))
                window.addEventListener("mousemove", clearDrag, true);
            // TODO open tree panel when hoverng over the button
            updateUploadAreaDrag(e.target.host);
            updateTreeDrag(e, host);
            updateTabDrag(host);

            clearTimeout(dragContext.timer);

            dragContext.dropEffect = "copy";
            if (treeAsPane && dragContext.pane && dragContext.pane.isTree)
                dragContext.dropEffect = "link";
            e.dataTransfer.dropEffect = dragContext.dropEffect;
        }

        function dragLeave(e) {
            apf.preventDefault(e);
            if (plugin.disableDropbox)
                return;

            clearTimeout(dragContext.timer);
            dragContext.timer = setTimeout(clearDrag, 100);
        }

        function dragOver(e) {
            apf.preventDefault(e);
            if (plugin.disableDropbox || !isFile(e))
                return;

            if (treeAsPane && e.ctrlKey != dragContext.ctrlKey) {
                var pane = dragContext.pane;
                if (pane && pane.isTree || dragContext.path) {
                    dragEnter(e);
                }
            }

            if (treeMouseHandler && treeMouseHandler.$onCaptureMouseMove)
                treeMouseHandler.$onCaptureMouseMove(e);
            if (dragContext.timer)
                dragContext.timer = clearTimeout(dragContext.timer);
            e.dataTransfer.dropEffect = dragContext.dropEffect;
        }

        function dragDrop(e) {
            apf.preventDefault(e);
            setTimeout(clearDrag);
            if (plugin.disableDropbox)
                return;

            var target = dragContext.path || dragContext.pane;
            if (target) {
                upload.uploadFromDrop(e, target,
                    dragContext.pane && !target.isTree ? "tab" : "tree");
                apf.stopEvent(e);
            }
        }

        function clearDrag(e) {
            dragContext.mouseListener = null;
            window.removeEventListener("mousemove", clearDrag, true);
            updateTreeDrag(e);
            updateTabDrag();
            updateUploadAreaDrag();
        }

        // helper
        function findHost(el, e) {
            var ctrlKey = dragContext.ctrlKey = e.ctrlKey;
            var treeEl = tree.getElement("container");
            if (treeAsPane && !ctrlKey) {
                treeEl = treeEl.parentNode;
            }

            while (el) {
                var host = el.host;
                if (host && (host.cloud9pane))
                    return host;
                if (host && (host === treeEl))
                    return treeAsPane && !ctrlKey ? {
                        cloud9pane: {
                            isTree       : true,
                            container    : host.$ext,
                            dropboxTitle : "Drop a file or folder"
                        }
                    } : host;

                if (el === dropbox) {
                    if (treeAsPane && ctrlKey && dragContext.pane.isTree)
                        return treeEl;
                    return {cloud9pane: dragContext.pane};
                }

                el = el.parentNode;
            }
        }

        function isFile(e) {
            var types = e.dataTransfer.types;
            if (types && Array.prototype.indexOf.call(types, 'Files') !== -1)
                return true;
        }

        function getDropbox(title) {
            if (!dropbox) {
                dropbox = document.createElement("div");
                dropbox.className = "draganddrop";

                var label = document.createElement("span");
                dropbox.appendChild(label);
            }
            dropbox.firstChild.textContent = title || "Drop a file here to open";
            return dropbox;
        }

        function updateTabDrag(host) {
            var pane = host && (host.cloud9pane
                || host.parentNode && host.parentNode.cloud9pane);

            clearTimeout(dragContext.dropboxTimer);
            if (pane) {
                dragContext.path = null;
                if (dragContext.pane === pane)
                    return;

                var parent = pane.container;
                dropbox = getDropbox(pane.dropboxTitle);
                parent && parent.appendChild(dropbox);
                apf.setStyleClass(dropbox, "over");

                dragContext.pane = pane;
            } else if (dragContext.pane) {
                dragContext.pane = null;
                if (dropbox && dropbox.parentNode) {
                    dragContext.dropboxTimer = setTimeout(function(){
                        if (dropbox.parentNode)
                            dropbox.parentNode.removeChild(dropbox);
                    }, 100);
                    apf.setStyleClass(dropbox, null, ["over"]);
                }
            }
        }

        function updateUploadAreaDrag(host) {
            if (host && host.$ext && host.$ext.id === "uploadDropArea") {
                dragContext.uploadDropArea = host.$ext;
                dragContext.path = upload.getTargetFolder().path;
                apf.setStyleClass(dragContext.uploadDropArea, "over");
            } else if (dragContext.uploadDropArea) {
                apf.setStyleClass(dragContext.uploadDropArea, null, ["over"]);
                dragContext.uploadDropArea = null;
            }
        }

        // tree
        function updateTreeDrag(e, host) {
            var online = c9.status & c9.STORAGE;
            if (online && host === tree.getElement("container")) {
                if (!treeMouseHandler.releaseMouse) {
                    treeMouseHandler.captureMouse(e);
                    treeMouseHandler.setState("drag");
                    treeMouseHandler.dragStart();
                    tree.tree.on("folderDragEnter", folderDragEnter);
                    tree.tree.on("folderDragLeave", folderDragLeave);
                }
            } else if (treeMouseHandler && treeMouseHandler.releaseMouse) {
                var path = dragContext.path;
                treeMouseHandler.releaseMouse(e || {});
                tree.tree.off("folderDragEnter", folderDragEnter);
                tree.tree.off("folderDragLeave", folderDragLeave);
                // do not reset path if called from mouseup
                dragContext.path = path;
            }
        }

        function folderDragLeave(node){
            tree.tree.provider.setClass(node, "dragAppendUpload", false);
            dragContext.path = null;
        }

        function folderDragEnter(node){
            tree.tree.provider.setClass(node, "dragAppendUpload", true);
            dragContext.path = node.path;
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
            load();
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
            unload();
        });

        /***** Register and define API *****/

        plugin.freezePublicAPI({});

        register(null, {
            dragdrop: plugin
        });
    }
});<|endoftext|>


<commit_before>/**
 * Created by Julian/Wolke on 15.11.2016.
 */

let RRACommand = require('../../structures/rraCommand');
class LewdImage extends RRACommand {
    constructor({t}) {
        super();
        this.cmd = 'lewd';
        this.cat = 'image';
        this.needGuild = false;
        this.t = t;
        this.accessLevel = 0;
    }
}
module.exports = LewdImage;
<commit_msg>Add youtube video to !w.lewd<commit_after>/**
 * Created by Julian/Wolke on 15.11.2016.
 */

let axios = require('axios');
let Command = require('../../structures/command');
class LewdImage extends Command {
    constructor({t}) {
        super();
        this.cmd = 'lewd';
        this.cat = 'image';
        this.needGuild = false;
        this.t = t;
        this.accessLevel = 0;
    }

    async run(msg) {
        if (Math.random() > 0.7)
            return await msg.channel.createMessage('https://www.youtube.com/watch?v=qr89xoZyE1g');
        try {
            let res = await axios.get('https://rra.ram.moe/i/r', { params: { "type": this.cmd } });
            let path = res.data.path.replace('/i/', '');
            await msg.channel.createMessage(`https://cdn.ram.moe/${path}`);
        } catch (e) {
            return winston.error(e);
        }
    }
}
module.exports = LewdImage;
<|endoftext|>


<commit_before>/**
 * Copyright 2018-present Facebook.
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 * @format
 */

import type {Element} from './ElementsInspector.js';
import type {PluginClient} from '../../../plugin';
import type Client from '../../../Client.js';
import type Logger from '../../../fb-stubs/Logger.js';
import Panel from '../Panel.js';
import ManagedDataInspector from '../data-inspector/ManagedDataInspector.js';
import {Component} from 'react';
import {Console} from '../console';
import {GK} from 'flipper';

const deepEqual = require('deep-equal');

type OnValueChanged = (path: Array<string>, val: any) => void;

type InspectorSidebarSectionProps = {
  data: any,
  id: string,
  onValueChanged: ?OnValueChanged,
  tooltips?: Object,
};

class InspectorSidebarSection extends Component<InspectorSidebarSectionProps> {
  setValue = (path: Array<string>, value: any) => {
    if (this.props.onValueChanged) {
      this.props.onValueChanged([this.props.id, ...path], value);
    }
  };

  shouldComponentUpdate(nextProps: InspectorSidebarSectionProps) {
    return (
      !deepEqual(nextProps, this.props) ||
      this.props.id !== nextProps.id ||
      this.props.onValueChanged !== nextProps.onValueChanged
    );
  }

  extractValue = (val: any, depth: number) => {
    if (val && val.__type__) {
      return {
        mutable: Boolean(val.__mutable__),
        type: val.__type__ === 'auto' ? typeof val.value : val.__type__,
        value: val.value,
      };
    } else {
      return {
        mutable: typeof val === 'object',
        type: typeof val,
        value: val,
      };
    }
  };

  render() {
    const {id} = this.props;
    return (
      <Panel heading={id} floating={false} grow={false}>
        <ManagedDataInspector
          data={this.props.data}
          setValue={this.props.onValueChanged ? this.setValue : undefined}
          extractValue={this.extractValue}
          expandRoot={true}
          collapsed={true}
          tooltips={this.props.tooltips}
        />
      </Panel>
    );
  }
}

type Props = {|
  element: ?Element,
  tooltips?: Object,
  onValueChanged: ?OnValueChanged,
  client: PluginClient,
  realClient: Client,
  logger: Logger,
  extensions?: Array<any>,
|};

type State = {|
  isConsoleEnabled: boolean,
|};

export class InspectorSidebar extends Component<Props, State> {
  state = {
    isConsoleEnabled: false,
  };

  constructor(props: Props) {
    super(props);
    this.checkIfConsoleIsEnabled();
  }

  componentDidUpdate(prevProps: Props, prevState: State) {
    if (prevProps.client !== this.props.client) {
      this.checkIfConsoleIsEnabled();
    }
  }

  checkIfConsoleIsEnabled() {
    this.props.client
      .call('isConsoleEnabled')
      .then((result: {isEnabled: boolean}) => {
        this.setState({isConsoleEnabled: result.isEnabled});
      });
  }

  render() {
    const {element, extensions} = this.props;
    if (!element || !element.data) {
      return null;
    }

    const sections =
      (extensions &&
        /* $FlowFixMe(>=0.86.0) This
         * comment suppresses an error found when Flow v0.86 was
         * deployed. To see the error, delete this comment and
         * run Flow. */
        extensions.map(ext =>
          ext(
            this.props.client,
            this.props.realClient,
            element.id,
            this.props.logger,
          ),
        )) ||
      [];

    for (const key in element.data) {
      if (key === 'Extra Sections') {
        for (const extraSection in element.data[key]) {
          let data = element.data[key][extraSection];

          // data might be sent as stringified JSON, we want to parse it for a nicer persentation.
          if (typeof data === 'string') {
            try {
              data = JSON.parse(data);
            } catch (e) {
              // data was not a valid JSON, using string instead
            }
          }
          sections.push(
            <InspectorSidebarSection
              tooltips={this.props.tooltips}
              key={extraSection}
              id={extraSection}
              data={data}
              onValueChanged={this.props.onValueChanged}
            />,
          );
        }
      } else {
        sections.push(
          <InspectorSidebarSection
            tooltips={this.props.tooltips}
            key={key}
            id={key}
            data={element.data[key]}
            onValueChanged={this.props.onValueChanged}
          />,
        );
      }
    }

    if (GK.get('sonar_show_console_plugin') && this.state.isConsoleEnabled) {
      sections.push(
        <Panel heading="JS Console" floating={false} grow={false}>
          <Console client={this.props.client} getContext={() => element.id} />
        </Panel>,
      );
    }

    return sections;
  }
}
<commit_msg>Fix "invalid weak map key" error when nodes in the layout inspector are empty strings<commit_after>/**
 * Copyright 2018-present Facebook.
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 * @format
 */

import type {Element} from './ElementsInspector.js';
import type {PluginClient} from '../../../plugin';
import type Client from '../../../Client.js';
import type Logger from '../../../fb-stubs/Logger.js';
import Panel from '../Panel.js';
import ManagedDataInspector from '../data-inspector/ManagedDataInspector.js';
import {Component} from 'react';
import {Console} from '../console';
import {GK} from 'flipper';

const deepEqual = require('deep-equal');

type OnValueChanged = (path: Array<string>, val: any) => void;

type InspectorSidebarSectionProps = {
  data: any,
  id: string,
  onValueChanged: ?OnValueChanged,
  tooltips?: Object,
};

class InspectorSidebarSection extends Component<InspectorSidebarSectionProps> {
  setValue = (path: Array<string>, value: any) => {
    if (this.props.onValueChanged) {
      this.props.onValueChanged([this.props.id, ...path], value);
    }
  };

  shouldComponentUpdate(nextProps: InspectorSidebarSectionProps) {
    return (
      !deepEqual(nextProps, this.props) ||
      this.props.id !== nextProps.id ||
      this.props.onValueChanged !== nextProps.onValueChanged
    );
  }

  extractValue = (val: any, depth: number) => {
    if (val && val.__type__) {
      return {
        mutable: Boolean(val.__mutable__),
        type: val.__type__ === 'auto' ? typeof val.value : val.__type__,
        value: val.value,
      };
    } else {
      return {
        mutable: typeof val === 'object',
        type: typeof val,
        value: val,
      };
    }
  };

  render() {
    const {id} = this.props;
    return (
      <Panel heading={id} floating={false} grow={false}>
        <ManagedDataInspector
          data={this.props.data}
          setValue={this.props.onValueChanged ? this.setValue : undefined}
          extractValue={this.extractValue}
          expandRoot={true}
          collapsed={true}
          tooltips={this.props.tooltips}
        />
      </Panel>
    );
  }
}

type Props = {|
  element: ?Element,
  tooltips?: Object,
  onValueChanged: ?OnValueChanged,
  client: PluginClient,
  realClient: Client,
  logger: Logger,
  extensions?: Array<any>,
|};

type State = {|
  isConsoleEnabled: boolean,
|};

export class InspectorSidebar extends Component<Props, State> {
  state = {
    isConsoleEnabled: false,
  };

  constructor(props: Props) {
    super(props);
    this.checkIfConsoleIsEnabled();
  }

  componentDidUpdate(prevProps: Props, prevState: State) {
    if (prevProps.client !== this.props.client) {
      this.checkIfConsoleIsEnabled();
    }
  }

  checkIfConsoleIsEnabled() {
    this.props.client
      .call('isConsoleEnabled')
      .then((result: {isEnabled: boolean}) => {
        this.setState({isConsoleEnabled: result.isEnabled});
      });
  }

  render() {
    const {element, extensions} = this.props;
    if (!element || !element.data) {
      return null;
    }

    const sections =
      (extensions &&
        /* $FlowFixMe(>=0.86.0) This
         * comment suppresses an error found when Flow v0.86 was
         * deployed. To see the error, delete this comment and
         * run Flow. */
        extensions.map(ext =>
          ext(
            this.props.client,
            this.props.realClient,
            element.id,
            this.props.logger,
          ),
        )) ||
      [];

    for (const key in element.data) {
      if (key === 'Extra Sections') {
        for (const extraSection in element.data[key]) {
          let data = element.data[key][extraSection];

          // data might be sent as stringified JSON, we want to parse it for a nicer persentation.
          if (typeof data === 'string') {
            try {
              data = JSON.parse(data);
            } catch (e) {
              // data was not a valid JSON, type is required to be an object
              console.error(
                `ElementsInspector unable to parse extra section: ${extraSection}`,
              );
              data = {};
            }
          }
          sections.push(
            <InspectorSidebarSection
              tooltips={this.props.tooltips}
              key={extraSection}
              id={extraSection}
              data={data}
              onValueChanged={this.props.onValueChanged}
            />,
          );
        }
      } else {
        sections.push(
          <InspectorSidebarSection
            tooltips={this.props.tooltips}
            key={key}
            id={key}
            data={element.data[key]}
            onValueChanged={this.props.onValueChanged}
          />,
        );
      }
    }

    if (GK.get('sonar_show_console_plugin') && this.state.isConsoleEnabled) {
      sections.push(
        <Panel heading="JS Console" floating={false} grow={false}>
          <Console client={this.props.client} getContext={() => element.id} />
        </Panel>,
      );
    }

    return sections;
  }
}
<|endoftext|>


<commit_before>import { Curve } from '../../../math/curve.js';
import { CurveSet } from '../../../math/curve-set.js';
import { Vec3 } from '../../../math/vec3.js';

import { LIGHTTYPE_DIRECTIONAL } from '../../../scene/constants.js';

import { Asset } from '../../../asset/asset.js';

import { Component } from '../component.js';
import { ComponentSystem } from '../system.js';

import { ParticleSystemComponent } from './component.js';
import { ParticleSystemComponentData } from './data.js';

const _schema = [
    'enabled',
    'autoPlay',
    'numParticles',
    'lifetime',
    'rate',
    'rate2',
    'startAngle',
    'startAngle2',
    'loop',
    'preWarm',
    'lighting',
    'halfLambert',
    'intensity',
    'depthWrite',
    'noFog',
    'depthSoftening',
    'sort',
    'blendType',
    'stretch',
    'alignToMotion',
    'emitterShape',
    'emitterExtents',
    'emitterExtentsInner',
    'emitterRadius',
    'emitterRadiusInner',
    'initialVelocity',
    'wrap',
    'wrapBounds',
    'localSpace',
    'screenSpace',
    'colorMapAsset',
    'normalMapAsset',
    'mesh',
    'meshAsset',
    'renderAsset',
    'orientation',
    'particleNormal',
    'localVelocityGraph',
    'localVelocityGraph2',
    'velocityGraph',
    'velocityGraph2',
    'rotationSpeedGraph',
    'rotationSpeedGraph2',
    'radialSpeedGraph',
    'radialSpeedGraph2',
    'scaleGraph',
    'scaleGraph2',
    'colorGraph',
    'colorGraph2',
    'alphaGraph',
    'alphaGraph2',
    'colorMap',
    'normalMap',
    'animTilesX',
    'animTilesY',
    'animStartFrame',
    'animNumFrames',
    'animNumAnimations',
    'animIndex',
    'randomizeAnimIndex',
    'animSpeed',
    'animLoop',
    'layers'
];

/**
 * @class
 * @name ParticleSystemComponentSystem
 * @augments ComponentSystem
 * @classdesc Allows an Entity to render a particle system.
 * @description Create a new ParticleSystemComponentSystem.
 * @param {Application} app - The Application.
 */
class ParticleSystemComponentSystem extends ComponentSystem {
    constructor(app) {
        super(app);

        this.id = 'particlesystem';

        this.ComponentType = ParticleSystemComponent;
        this.DataType = ParticleSystemComponentData;

        this.schema = _schema;

        this.propertyTypes = {
            emitterExtents: 'vec3',
            emitterExtentsInner: 'vec3',
            particleNormal: 'vec3',
            wrapBounds: 'vec3',
            localVelocityGraph: 'curveset',
            localVelocityGraph2: 'curveset',
            velocityGraph: 'curveset',
            velocityGraph2: 'curveset',
            colorGraph: 'curveset',
            colorGraph2: 'curveset',
            alphaGraph: 'curve',
            alphaGraph2: 'curve',
            rotationSpeedGraph: 'curve',
            rotationSpeedGraph2: 'curve',
            radialSpeedGraph: 'curve',
            radialSpeedGraph2: 'curve',
            scaleGraph: 'curve',
            scaleGraph2: 'curve'
        };

        this.on('beforeremove', this.onBeforeRemove, this);
        this.app.systems.on('update', this.onUpdate, this);
    }

    initializeComponentData(component, _data, properties) {
        const data = {};

        properties = [];
        const types = this.propertyTypes;

        // we store the mesh asset id as "mesh" (it should be "meshAsset")
        // this re-maps "mesh" into "meshAsset" if it is an asset or an asset id
        if (_data.mesh instanceof Asset || typeof _data.mesh === 'number') {
            // migrate into meshAsset property
            _data.meshAsset = _data.mesh;
            delete _data.mesh;
        }

        for (const prop in _data) {
            if (_data.hasOwnProperty(prop)) {
                properties.push(prop);
                // duplicate input data as we are modifying it
                data[prop] = _data[prop];
            }

            if (types[prop] === 'vec3') {
                if (Array.isArray(data[prop])) {
                    data[prop] = new Vec3(data[prop][0], data[prop][1], data[prop][2]);
                }
            } else if (types[prop] === 'curve') {
                if (!(data[prop] instanceof Curve)) {
                    const t = data[prop].type;
                    data[prop] = new Curve(data[prop].keys);
                    data[prop].type = t;
                }
            } else if (types[prop] === 'curveset') {
                if (!(data[prop] instanceof CurveSet)) {
                    const t = data[prop].type;
                    data[prop] = new CurveSet(data[prop].keys);
                    data[prop].type = t;
                }
            }

            // duplicate layer list
            if (data.layers && Array.isArray(data.layers)) {
                data.layers = data.layers.slice(0);
            }
        }

        super.initializeComponentData(component, data, properties);
    }

    cloneComponent(entity, clone) {
        const source = entity.particlesystem.data;
        const schema = this.schema;

        const data = {};

        for (let i = 0, len = schema.length; i < len; i++) {
            const prop = schema[i];
            let sourceProp = source[prop];
            if (sourceProp instanceof Vec3 ||
                sourceProp instanceof Curve ||
                sourceProp instanceof CurveSet) {

                sourceProp = sourceProp.clone();
                data[prop] = sourceProp;
            } else if (prop === "layers") {
                data.layers = source.layers.slice(0);
            } else {
                if (sourceProp !== null && sourceProp !== undefined) {
                    data[prop] = sourceProp;
                }
            }
        }

        return this.addComponent(clone, data);
    }

    onUpdate(dt) {
        const components = this.store;
        let numSteps;
        const stats = this.app.stats.particles;

        for (const id in components) {
            if (components.hasOwnProperty(id)) {
                const component = components[id];
                const entity = component.entity;
                const data = component.data;

                if (data.enabled && entity.enabled) {
                    const emitter = data.model.emitter;
                    if (!emitter.meshInstance.visible) continue;

                    // Bake ambient and directional lighting into one ambient cube
                    // TODO: only do if lighting changed
                    // TODO: don't do for every emitter
                    if (emitter.lighting) {
                        const layers = data.layers;
                        for (let i = 0; i < layers.length; i++) {
                            const layer = this.app.scene.layers.getLayerById(layers[i]);
                            if (!layer) continue;

                            if (!layer._lightCube) {
                                layer._lightCube = new Float32Array(6 * 3);
                            }
                            const lightCube = layer._lightCube;
                            for (let j = 0; j < 6; j++) {
                                lightCube[j * 3] = this.app.scene.ambientLight.r;
                                lightCube[j * 3 + 1] = this.app.scene.ambientLight.g;
                                lightCube[j * 3 + 2] = this.app.scene.ambientLight.b;
                            }
                            const dirs = layer._splitLights[LIGHTTYPE_DIRECTIONAL];
                            for (let j = 0; j < dirs.length; j++) {
                                for (let c = 0; c < 6; c++) {
                                    const weight = Math.max(emitter.lightCubeDir[c].dot(dirs[j]._direction), 0) * dirs[j]._intensity;
                                    lightCube[c * 3] += dirs[j]._color.r * weight;
                                    lightCube[c * 3 + 1] += dirs[j]._color.g * weight;
                                    lightCube[c * 3 + 2] += dirs[j]._color.b * weight;
                                }
                            }
                        }
                        emitter.constantLightCube.setValue(lightCube); // ?
                    }

                    if (!data.paused) {
                        emitter.simTime += dt;
                        if (emitter.simTime > emitter.fixedTimeStep) {
                            numSteps = Math.floor(emitter.simTime / emitter.fixedTimeStep);
                            emitter.simTime -= numSteps * emitter.fixedTimeStep;
                        }
                        if (numSteps) {
                            numSteps = Math.min(numSteps, emitter.maxSubSteps);
                            for (let i = 0; i < numSteps; i++) {
                                emitter.addTime(emitter.fixedTimeStep, false);
                            }
                            stats._updatesPerFrame += numSteps;
                            stats._frameTime += emitter._addTimeTime;
                            emitter._addTimeTime = 0;
                        }
                        emitter.finishFrame();
                    }
                }
            }
        }
    }

    onBeforeRemove(entity, component) {
        component.onBeforeRemove();
    }

    destroy() {
        super.destroy();

        this.app.systems.off('update', this.onUpdate, this);
    }
}

Component._buildAccessors(ParticleSystemComponent.prototype, _schema);

export { ParticleSystemComponentSystem };
<commit_msg>[Fix] Fix to ParticleSystem crash caused by recent refactor (#3598)<commit_after>import { Curve } from '../../../math/curve.js';
import { CurveSet } from '../../../math/curve-set.js';
import { Vec3 } from '../../../math/vec3.js';

import { LIGHTTYPE_DIRECTIONAL } from '../../../scene/constants.js';

import { Asset } from '../../../asset/asset.js';

import { Component } from '../component.js';
import { ComponentSystem } from '../system.js';

import { ParticleSystemComponent } from './component.js';
import { ParticleSystemComponentData } from './data.js';

const _schema = [
    'enabled',
    'autoPlay',
    'numParticles',
    'lifetime',
    'rate',
    'rate2',
    'startAngle',
    'startAngle2',
    'loop',
    'preWarm',
    'lighting',
    'halfLambert',
    'intensity',
    'depthWrite',
    'noFog',
    'depthSoftening',
    'sort',
    'blendType',
    'stretch',
    'alignToMotion',
    'emitterShape',
    'emitterExtents',
    'emitterExtentsInner',
    'emitterRadius',
    'emitterRadiusInner',
    'initialVelocity',
    'wrap',
    'wrapBounds',
    'localSpace',
    'screenSpace',
    'colorMapAsset',
    'normalMapAsset',
    'mesh',
    'meshAsset',
    'renderAsset',
    'orientation',
    'particleNormal',
    'localVelocityGraph',
    'localVelocityGraph2',
    'velocityGraph',
    'velocityGraph2',
    'rotationSpeedGraph',
    'rotationSpeedGraph2',
    'radialSpeedGraph',
    'radialSpeedGraph2',
    'scaleGraph',
    'scaleGraph2',
    'colorGraph',
    'colorGraph2',
    'alphaGraph',
    'alphaGraph2',
    'colorMap',
    'normalMap',
    'animTilesX',
    'animTilesY',
    'animStartFrame',
    'animNumFrames',
    'animNumAnimations',
    'animIndex',
    'randomizeAnimIndex',
    'animSpeed',
    'animLoop',
    'layers'
];

/**
 * @class
 * @name ParticleSystemComponentSystem
 * @augments ComponentSystem
 * @classdesc Allows an Entity to render a particle system.
 * @description Create a new ParticleSystemComponentSystem.
 * @param {Application} app - The Application.
 */
class ParticleSystemComponentSystem extends ComponentSystem {
    constructor(app) {
        super(app);

        this.id = 'particlesystem';

        this.ComponentType = ParticleSystemComponent;
        this.DataType = ParticleSystemComponentData;

        this.schema = _schema;

        this.propertyTypes = {
            emitterExtents: 'vec3',
            emitterExtentsInner: 'vec3',
            particleNormal: 'vec3',
            wrapBounds: 'vec3',
            localVelocityGraph: 'curveset',
            localVelocityGraph2: 'curveset',
            velocityGraph: 'curveset',
            velocityGraph2: 'curveset',
            colorGraph: 'curveset',
            colorGraph2: 'curveset',
            alphaGraph: 'curve',
            alphaGraph2: 'curve',
            rotationSpeedGraph: 'curve',
            rotationSpeedGraph2: 'curve',
            radialSpeedGraph: 'curve',
            radialSpeedGraph2: 'curve',
            scaleGraph: 'curve',
            scaleGraph2: 'curve'
        };

        this.on('beforeremove', this.onBeforeRemove, this);
        this.app.systems.on('update', this.onUpdate, this);
    }

    initializeComponentData(component, _data, properties) {
        const data = {};

        properties = [];
        const types = this.propertyTypes;

        // we store the mesh asset id as "mesh" (it should be "meshAsset")
        // this re-maps "mesh" into "meshAsset" if it is an asset or an asset id
        if (_data.mesh instanceof Asset || typeof _data.mesh === 'number') {
            // migrate into meshAsset property
            _data.meshAsset = _data.mesh;
            delete _data.mesh;
        }

        for (const prop in _data) {
            if (_data.hasOwnProperty(prop)) {
                properties.push(prop);
                // duplicate input data as we are modifying it
                data[prop] = _data[prop];
            }

            if (types[prop] === 'vec3') {
                if (Array.isArray(data[prop])) {
                    data[prop] = new Vec3(data[prop][0], data[prop][1], data[prop][2]);
                }
            } else if (types[prop] === 'curve') {
                if (!(data[prop] instanceof Curve)) {
                    const t = data[prop].type;
                    data[prop] = new Curve(data[prop].keys);
                    data[prop].type = t;
                }
            } else if (types[prop] === 'curveset') {
                if (!(data[prop] instanceof CurveSet)) {
                    const t = data[prop].type;
                    data[prop] = new CurveSet(data[prop].keys);
                    data[prop].type = t;
                }
            }

            // duplicate layer list
            if (data.layers && Array.isArray(data.layers)) {
                data.layers = data.layers.slice(0);
            }
        }

        super.initializeComponentData(component, data, properties);
    }

    cloneComponent(entity, clone) {
        const source = entity.particlesystem.data;
        const schema = this.schema;

        const data = {};

        for (let i = 0, len = schema.length; i < len; i++) {
            const prop = schema[i];
            let sourceProp = source[prop];
            if (sourceProp instanceof Vec3 ||
                sourceProp instanceof Curve ||
                sourceProp instanceof CurveSet) {

                sourceProp = sourceProp.clone();
                data[prop] = sourceProp;
            } else if (prop === "layers") {
                data.layers = source.layers.slice(0);
            } else {
                if (sourceProp !== null && sourceProp !== undefined) {
                    data[prop] = sourceProp;
                }
            }
        }

        return this.addComponent(clone, data);
    }

    onUpdate(dt) {
        const components = this.store;
        let numSteps;
        const stats = this.app.stats.particles;

        for (const id in components) {
            if (components.hasOwnProperty(id)) {
                const component = components[id];
                const entity = component.entity;
                const data = component.data;

                if (data.enabled && entity.enabled) {
                    const emitter = data.model.emitter;
                    if (!emitter.meshInstance.visible) continue;

                    // Bake ambient and directional lighting into one ambient cube
                    // TODO: only do if lighting changed
                    // TODO: don't do for every emitter
                    if (emitter.lighting) {
                        const layers = data.layers;
                        let lightCube;
                        for (let i = 0; i < layers.length; i++) {
                            const layer = this.app.scene.layers.getLayerById(layers[i]);
                            if (!layer) continue;

                            if (!layer._lightCube) {
                                layer._lightCube = new Float32Array(6 * 3);
                            }
                            lightCube = layer._lightCube;
                            for (let j = 0; j < 6; j++) {
                                lightCube[j * 3] = this.app.scene.ambientLight.r;
                                lightCube[j * 3 + 1] = this.app.scene.ambientLight.g;
                                lightCube[j * 3 + 2] = this.app.scene.ambientLight.b;
                            }
                            const dirs = layer._splitLights[LIGHTTYPE_DIRECTIONAL];
                            for (let j = 0; j < dirs.length; j++) {
                                for (let c = 0; c < 6; c++) {
                                    const weight = Math.max(emitter.lightCubeDir[c].dot(dirs[j]._direction), 0) * dirs[j]._intensity;
                                    lightCube[c * 3] += dirs[j]._color.r * weight;
                                    lightCube[c * 3 + 1] += dirs[j]._color.g * weight;
                                    lightCube[c * 3 + 2] += dirs[j]._color.b * weight;
                                }
                            }
                        }
                        emitter.constantLightCube.setValue(lightCube); // ?
                    }

                    if (!data.paused) {
                        emitter.simTime += dt;
                        if (emitter.simTime > emitter.fixedTimeStep) {
                            numSteps = Math.floor(emitter.simTime / emitter.fixedTimeStep);
                            emitter.simTime -= numSteps * emitter.fixedTimeStep;
                        }
                        if (numSteps) {
                            numSteps = Math.min(numSteps, emitter.maxSubSteps);
                            for (let i = 0; i < numSteps; i++) {
                                emitter.addTime(emitter.fixedTimeStep, false);
                            }
                            stats._updatesPerFrame += numSteps;
                            stats._frameTime += emitter._addTimeTime;
                            emitter._addTimeTime = 0;
                        }
                        emitter.finishFrame();
                    }
                }
            }
        }
    }

    onBeforeRemove(entity, component) {
        component.onBeforeRemove();
    }

    destroy() {
        super.destroy();

        this.app.systems.off('update', this.onUpdate, this);
    }
}

Component._buildAccessors(ParticleSystemComponent.prototype, _schema);

export { ParticleSystemComponentSystem };
<|endoftext|>


<commit_before>$(document).ready(function() {
  $("#texty").addClass("scrolling");

  var topBtn = false;
  $("body").scroll(function() {
    if ($("#cor").isInViewport()) {
      $("#cor").addClass("slideLeft");
    } else if ($("#tow").isInViewport()) {
      $("#tow").addClass("slideRight");
    } else if ($("#sky").isInViewport()) {
      $("#sky").addClass("slideLeft");
    } else if ($("#bud").isInViewport()) {
      $("#bud").addClass("slideRight");
    } else if ($("#hay").isInViewport()) {
      $("#hay").addClass("slideLeft");
    } else if ($("#hill").isInViewport()) {
      $("#hill").addClass("slideRight");
    } else if ($("#cen").isInViewport()) {
      $("#cen").addClass("slideLeft");
    } else if ($("#chq").isInViewport()) {
      $("#chq").addClass("slideLeft");
    } else if ($("#portfolio").isInViewport()) {
      $("#portfolio").addClass("fade");
    }
    if (document.body.scrollTop < 250) {
      if (document.getElementById("top-btn").classList.contains("in")) {
        document.getElementById("top-btn").classList.remove("in");
      }
    }
    if (document.body.scrollTop >= 250) {
      if (!document.getElementById("top-btn").classList.contains("in")) {
        document.getElementById("top-btn").classList.add("in");
      }
    }
  });

  //   window.addEventListener('resize', function(){
  //     if(window.innerWidth > 568){

  //     }
  // });

  // Smooth scrolling using jQuery easing
  // $('a[href*="#"]:not([href="#"]:not([href*="#portfolioModal"]))').click(
  //   function() {
  //     if (
  //       location.pathname.replace(/^\//, "") ==
  //         this.pathname.replace(/^\//, "") &&
  //       location.hostname == this.hostname
  //     ) {
  //       var target = $(this.hash);
  //       target = target.length ? target : $("[name=" + this.hash.slice(1) + "]");
  //       if (target.length) {
  //         $("html, body").animate(
  //           {
  //             scrollTop: target.offset().top
  //           },
  //           800,
  //           "easeInOutExpo"
  //         );
  //         return false;
  //       }
  //     }
  //   }
  // );

  // function scrollFunction() {
  //   document.body.scrollTop > 250 ? document.getElementById("top-btn").style.display = "flex" : document.getElementById("top-btn").style.display = "none";
  //   console.log('scrollFunction')
  // }
  // function topFunction() {
  //   (document.body.scrollTop = 0), (document.documentElement.scrollTop = 0);
  //   console.log('topFunction')
  // }
  // (window.onscroll = function() {
  //   scrollFunction();
  // })

  $(document).scrollTop() > 250 &&
    (document.getElementById("top-btn").style.display = "flex"),
    $("#top-btn").on("click", function() {
      $(".top-link").trigger("click");
    }),
    $('a[href*="#"]')
      .not('[href="#"]')
      .not('[href="#0"]')
      .click(function(e) {
        if (
          location.pathname.replace(/^\//, "") ==
            this.pathname.replace(/^\//, "") &&
          location.hostname == this.hostname
        ) {
          var t = $(this.hash);
          (t = t.length ? t : $("[name=" + this.hash.slice(1) + "]")),
            t.length &&
              (e.preventDefault(),
              $("html, body").animate(
                {
                  scrollTop: t.offset().top
                },
                1e3,
                function() {
                  var e = $(t);
                  return (
                    e.focus(),
                    !e.is(":focus") &&
                      (e.attr("tabindex", "-1"), void e.focus())
                  );
                }
              ));
        }
      });

  $.fn.isInViewport = function() {
    var tony = $(this);
    if (tony.offset() !== undefined) {
      var elementTop = $(this).offset().top;
      var elementBottom = elementTop + $(this).outerHeight();
      var viewportTop = $(window).scrollTop();
      var viewportBottom = viewportTop + $(window).height();
      return elementBottom > viewportTop && elementTop < viewportBottom;
    }
  };
}); // End of use strict

function BackgroundNode(_ref) {
  var node = _ref.node,
    loadedClassName = _ref.loadedClassName;

  var src = node.getAttribute("data-background-image-url");
  var show = function show(onComplete) {
    requestAnimationFrame(function() {
      node.style.backgroundImage = "url(" + src + ")";
      node.classList.add(loadedClassName);
      onComplete();
    });
  };

  return {
    node: node,

    // onComplete is called after the image is done loading.
    load: function load(onComplete) {
      var img = new Image();
      img.onload = show(onComplete);
      img.src = src;
    }
  };
}

var defaultOptions = {
  selector: "[data-background-image-url]",
  loadedClassName: "loaded"
};

function BackgroundLazyLoader() {
  var _ref2 =
      arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultOptions,
    selector = _ref2.selector,
    loadedClassName = _ref2.loadedClassName;

  var nodes = [].slice
    .apply(document.querySelectorAll(selector))
    .map(function(node) {
      return new BackgroundNode({
        node: node,
        loadedClassName: loadedClassName
      });
    });

  var callback = function callback(entries, observer) {
    entries.forEach(function(_ref3) {
      var target = _ref3.target,
        isIntersecting = _ref3.isIntersecting;

      if (!isIntersecting) {
        return;
      }

      var obj = nodes.find(function(it) {
        return it.node.isSameNode(target);
      });

      if (obj) {
        obj.load(function() {
          // Unobserve the node:
          observer.unobserve(target);
          // Remove this node from our list:
          nodes = nodes.filter(function(n) {
            return !n.node.isSameNode(target);
          });

          // If there are no remaining unloaded nodes,
          // disconnect the observer since we don't need it anymore.
          if (!nodes.length) {
            observer.disconnect();
          }
        });
      }
    });
  };

  var observer = new IntersectionObserver(callback);
  nodes.forEach(function(node) {
    return observer.observe(node.node);
  });
}

BackgroundLazyLoader();

var fontsUsed = [
  "Questrial",
  "Fjalla One",
  "Roboto Slab",
  "Helvetica Neue",
  "Helvetica",
  "Arial",
  "sans-serif",
  "Montserrat",
  ]<commit_msg>add lazy-load margin so images load 100px below fold<commit_after>$(document).ready(function() {
  $("#texty").addClass("scrolling");

  var topBtn = false;
  $("body").scroll(function() {
    if ($("#cor").isInViewport()) {
      $("#cor").addClass("slideLeft");
    } else if ($("#tow").isInViewport()) {
      $("#tow").addClass("slideRight");
    } else if ($("#sky").isInViewport()) {
      $("#sky").addClass("slideLeft");
    } else if ($("#bud").isInViewport()) {
      $("#bud").addClass("slideRight");
    } else if ($("#hay").isInViewport()) {
      $("#hay").addClass("slideLeft");
    } else if ($("#hill").isInViewport()) {
      $("#hill").addClass("slideRight");
    } else if ($("#cen").isInViewport()) {
      $("#cen").addClass("slideLeft");
    } else if ($("#chq").isInViewport()) {
      $("#chq").addClass("slideLeft");
    } else if ($("#portfolio").isInViewport()) {
      $("#portfolio").addClass("fade");
    }
    if (document.body.scrollTop < 250) {
      if (document.getElementById("top-btn").classList.contains("in")) {
        document.getElementById("top-btn").classList.remove("in");
      }
    }
    if (document.body.scrollTop >= 250) {
      if (!document.getElementById("top-btn").classList.contains("in")) {
        document.getElementById("top-btn").classList.add("in");
      }
    }
  });

  //   window.addEventListener('resize', function(){
  //     if(window.innerWidth > 568){

  //     }
  // });

  // Smooth scrolling using jQuery easing
  // $('a[href*="#"]:not([href="#"]:not([href*="#portfolioModal"]))').click(
  //   function() {
  //     if (
  //       location.pathname.replace(/^\//, "") ==
  //         this.pathname.replace(/^\//, "") &&
  //       location.hostname == this.hostname
  //     ) {
  //       var target = $(this.hash);
  //       target = target.length ? target : $("[name=" + this.hash.slice(1) + "]");
  //       if (target.length) {
  //         $("html, body").animate(
  //           {
  //             scrollTop: target.offset().top
  //           },
  //           800,
  //           "easeInOutExpo"
  //         );
  //         return false;
  //       }
  //     }
  //   }
  // );

  // function scrollFunction() {
  //   document.body.scrollTop > 250 ? document.getElementById("top-btn").style.display = "flex" : document.getElementById("top-btn").style.display = "none";
  //   console.log('scrollFunction')
  // }
  // function topFunction() {
  //   (document.body.scrollTop = 0), (document.documentElement.scrollTop = 0);
  //   console.log('topFunction')
  // }
  // (window.onscroll = function() {
  //   scrollFunction();
  // })

  $(document).scrollTop() > 250 &&
    (document.getElementById("top-btn").style.display = "flex"),
    $("#top-btn").on("click", function() {
      $(".top-link").trigger("click");
    }),
    $('a[href*="#"]')
      .not('[href="#"]')
      .not('[href="#0"]')
      .click(function(e) {
        if (
          location.pathname.replace(/^\//, "") ==
            this.pathname.replace(/^\//, "") &&
          location.hostname == this.hostname
        ) {
          var t = $(this.hash);
          (t = t.length ? t : $("[name=" + this.hash.slice(1) + "]")),
            t.length &&
              (e.preventDefault(),
              $("html, body").animate(
                {
                  scrollTop: t.offset().top
                },
                1e3,
                function() {
                  var e = $(t);
                  return (
                    e.focus(),
                    !e.is(":focus") &&
                      (e.attr("tabindex", "-1"), void e.focus())
                  );
                }
              ));
        }
      });

  $.fn.isInViewport = function() {
    var tony = $(this);
    if (tony.offset() !== undefined) {
      var elementTop = $(this).offset().top;
      var elementBottom = elementTop + $(this).outerHeight();
      var viewportTop = $(window).scrollTop();
      var viewportBottom = viewportTop + $(window).height();
      return elementBottom > viewportTop && elementTop < viewportBottom;
    }
  };
}); // End of use strict

function BackgroundNode(_ref) {
  var node = _ref.node,
    loadedClassName = _ref.loadedClassName;

  var src = node.getAttribute("data-background-image-url");
  var show = function show(onComplete) {
    requestAnimationFrame(function() {
      node.style.backgroundImage = "url(" + src + ")";
      node.classList.add(loadedClassName);
      onComplete();
    });
  };

  return {
    node: node,

    // onComplete is called after the image is done loading.
    load: function load(onComplete) {
      var img = new Image();
      img.onload = show(onComplete);
      img.src = src;
    }
  };
}

var defaultOptions = {
  selector: "[data-background-image-url]",
  loadedClassName: "loaded"
};

function BackgroundLazyLoader() {
  var _ref2 =
      arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultOptions,
    selector = _ref2.selector,
    loadedClassName = _ref2.loadedClassName;

  var nodes = [].slice
    .apply(document.querySelectorAll(selector))
    .map(function(node) {
      return new BackgroundNode({
        node: node,
        loadedClassName: loadedClassName
      });
    });

  var callback = function callback(entries, observer) {
    entries.forEach(function(_ref3) {
      var target = _ref3.target,
        isIntersecting = _ref3.isIntersecting;

      if (!isIntersecting) {
        return;
      }

      var obj = nodes.find(function(it) {
        return it.node.isSameNode(target);
      });

      if (obj) {
        obj.load(function() {
          // Unobserve the node:
          observer.unobserve(target);
          // Remove this node from our list:
          nodes = nodes.filter(function(n) {
            return !n.node.isSameNode(target);
          });

          // If there are no remaining unloaded nodes,
          // disconnect the observer since we don't need it anymore.
          if (!nodes.length) {
            observer.disconnect();
          }
        });
      }
    });
  };

  var observer = new IntersectionObserver(callback, {
    rootMargin: "200px",
    threshold: 0
  });
  nodes.forEach(function(node) {
    return observer.observe(node.node);
  });
}

BackgroundLazyLoader();
<|endoftext|>


<commit_before>$(document).ready(function(){

	Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");

	window.onLoad = function(){
		//query
		//list
		//destroyAll
	}

	$('#classroom-enter').click(function(){
		event.preventDefault();
		var request = $('#classroom-enter-form').val();
		console.log(request);
		var Classroom = Parse.Object.extend("Classroom");
		var search = new Parse.Query(Classroom);
		search.equalTo("code",request);
		search.find({
			success: function(results){
				if(results.length != 1) {
					console.log(results.length);
					console.log("YUFAILSOHARD!?");
				} else {
					console.log(results.length);
					console.log("YAAASSS!!!!\n");
				}
			},
			error: function(error){
				console.log("YUFAILSOHARD!?");
			}
		});
	});

	$('#post').click(function(){
		//Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");
		event.preventDefault();
		var Post = Parse.Object.extend("Post");
		var post = new Post();
		post.set("question","");
		post.set("upvotes", 0);
		post.set("downvotes", 0);
		post.set("answered", false);

		post.save(null, {
	  		success: function(Post) {
	    		// Execute any logic that should take place after the object is saved.
	    		//alert('New object created with objectId: ' + post.id);

	    		/*************************
				Rosemond's Code Goes Here!
	  			**************************/

	  		},
	  		error: function(Post, error) {
	    		// Execute any logic that should take place if the save fails.
	    		// error is a Parse.Error with an error code and message.
	    		alert('Failed to create new object, with error code: ' + error.message);
	  		}

		});

		var TestObject = Parse.Object.extend("TestObject");
		var testObject = new TestObject();
		testObject.save({foo: "bar"}).then(function(object) {
	  		//alert("yay! it worked");
		});
	});
});

<commit_msg>An experiment to extract the ID from a found classroom<commit_after>$(document).ready(function(){

	Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");

	window.onLoad = function(){
		//query
		//list
		//destroyAll
	}

	$('#classroom-enter').click(function(){
		event.preventDefault();
		var request = $('#classroom-enter-form').val();
		console.log(request);
		var Classroom = Parse.Object.extend("Classroom");
		var search = new Parse.Query(Classroom);
		search.equalTo("code",request);
		search.find({
			success: function(results){
				if(results.length != 1) {
					console.log(results.length);
					console.log("YUFAILSOHARD!?");
				} else {
					console.log(results.length);
					console.log(results);
					console.log("YAAASSS!!!!\n");

				}
			},
			error: function(error){
				console.log("YUFAILSOHARD!?");
			}
		});
	});

	$('#post').click(function(){
		//Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");
		event.preventDefault();
		var Post = Parse.Object.extend("Post");
		var post = new Post();
		post.set("question","");
		post.set("upvotes", 0);
		post.set("downvotes", 0);
		post.set("answered", false);

		post.save(null, {
	  		success: function(Post) {
	    		// Execute any logic that should take place after the object is saved.
	    		//alert('New object created with objectId: ' + post.id);

	    		/*************************
				Rosemond's Code Goes Here!
	  			**************************/

	  		},
	  		error: function(Post, error) {
	    		// Execute any logic that should take place if the save fails.
	    		// error is a Parse.Error with an error code and message.
	    		alert('Failed to create new object, with error code: ' + error.message);
	  		}

		});

		var TestObject = Parse.Object.extend("TestObject");
		var testObject = new TestObject();
		testObject.save({foo: "bar"}).then(function(object) {
	  		//alert("yay! it worked");
		});
	});
});

<|endoftext|>


<commit_before>// ==UserScript==
// @id             max-links@boombuler
// @name           iitc: Max-Links-Plugin
// @version        0.1
// @updateURL      https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/plugins/max-links.user.js
// @downloadURL    https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/plugins/max-links.user.js
// @description    Calculates how to link the portals to create the maximum number of fields.
// @include        http://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// ==/UserScript==

function wrapper() {
  // ensure plugin framework is there, even if iitc is not yet loaded
  if(typeof window.plugin !== 'function')
    window.plugin = function() {};

  // PLUGIN START ////////////////////////////////////////////////////////

  // use own namespace for plugin
  window.plugin.maxLinks = function() {};

  // const values
  window.plugin.maxLinks.MAX_DRAWN_LINKS = 400;
  window.plugin.maxLinks.MAX_DRAWN_LINKS_INCREASED_LIMIT = 1000;
  window.plugin.maxLinks.STROKE_STYLE = {
    color: '#FF0000',
    opacity: 1,
    weight:2,
    clickable: false,
    smoothFactor: 10
  };
  var delaunayScriptLocation = 'https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/dist/delaunay.js';

  window.plugin.maxLinks.layer = null;

  var updating = false;
  var renderLimitReached = false;

  window.plugin.maxLinks.updateLayer = function() {
    if (updating || window.plugin.maxLinks.layer === null || !window.map.hasLayer(window.plugin.maxLinks.layer))
      return;
    updating = true;
    window.plugin.maxLinks.layer.clearLayers();

    var locations = [];
    var minX = 0;
    var minY = 0;

    $.each(window.portals, function(guid, portal) {
      var loc = portal.options.details.locationE6;
      var nloc = { x: loc.lngE6, y: loc.latE6 };
      if (nloc.x < minX)
        minX = nloc.x;
      if (nloc.y < minX)
        minX = nloc.y;
      locations.push(nloc);
    });

    $.each(locations, function(idx, nloc) {
      nloc.x += Math.abs(minX);
      nloc.y += Math.abs(minY);
    });

    var triangles = window.delaunay.triangulate(locations);
    var drawnLinks = 0;
    renderLimitReached = false;
    var renderlimit = window.USE_INCREASED_RENDER_LIMIT ? window.plugin.maxLinks.MAX_DRAWN_LINKS_INCREASED_LIMIT : window.plugin.maxLinks.MAX_DRAWN_LINKS;
    $.each(triangles, function(idx, triangle) {
      if (drawnLinks <= renderlimit) {
        triangle.draw(window.plugin.maxLinks.layer, minX, minY)
        drawnLinks += 3;
      } else {
        renderLimitReached = true;
      }
    });
    updating = false;
    window.renderUpdateStatus();
  }

  var setup =  function() {
    load(delaunayScriptLocation).thenRun(function() {

      window.delaunay.Triangle.prototype.draw = function(layer, divX, divY) {
        var drawLine = function(src, dest) {
          var poly = L.polyline([[(src.y + divY)/1E6, (src.x + divX)/1E6], [(dest.y + divY)/1E6, (dest.x + divX)/1E6]], window.plugin.maxLinks.STROKE_STYLE);
          poly.addTo(layer);
        };

        drawLine(this.a, this.b);
        drawLine(this.b, this.c);
        drawLine(this.c, this.a);
      }

      window.plugin.maxLinks.layer = L.layerGroup([]);

      window.addHook('checkRenderLimit', function(e) {
         if (window.map.hasLayer(window.plugin.maxLinks.layer) && renderLimitReached)
           e.reached = true;
      });

      window.map.on('layeradd', function(e) {
        if (e.layer === window.plugin.maxLinks.layer)
          window.plugin.maxLinks.updateLayer();
      });
      window.map.on('zoomend moveend', window.plugin.maxLinks.updateLayer);
      window.layerChooser.addOverlay(window.plugin.maxLinks.layer, 'Maximum Links');
    });
  }

  // PLUGIN END //////////////////////////////////////////////////////////
  if(window.iitcLoaded && typeof setup === 'function') {
    setup();
  } else {
    if(window.bootPlugins)
      window.bootPlugins.push(setup);
    else
      window.bootPlugins = [setup];
  }
} // wrapper end

// inject code into site context
var script = document.createElement('script');
script.appendChild(document.createTextNode('('+ wrapper +')();'));
(document.body || document.head || document.documentElement).appendChild(script);<commit_msg>added some linebreaks<commit_after>// ==UserScript==
// @id             max-links@boombuler
// @name           iitc: Max-Links-Plugin
// @version        0.1
// @updateURL      https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/plugins/max-links.user.js
// @downloadURL    https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/plugins/max-links.user.js
// @description    Calculates how to link the portals to create the maximum number of fields.
// @include        http://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// ==/UserScript==

function wrapper() {
  // ensure plugin framework is there, even if iitc is not yet loaded
  if(typeof window.plugin !== 'function')
    window.plugin = function() {};

  // PLUGIN START ////////////////////////////////////////////////////////

  // use own namespace for plugin
  window.plugin.maxLinks = function() {};

  // const values
  window.plugin.maxLinks.MAX_DRAWN_LINKS = 400;
  window.plugin.maxLinks.MAX_DRAWN_LINKS_INCREASED_LIMIT = 1000;
  window.plugin.maxLinks.STROKE_STYLE = {
    color: '#FF0000',
    opacity: 1,
    weight:2,
    clickable: false,
    smoothFactor: 10
  };
  var delaunayScriptLocation = 'https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/dist/delaunay.js';

  window.plugin.maxLinks.layer = null;

  var updating = false;
  var renderLimitReached = false;

  window.plugin.maxLinks.updateLayer = function() {
    if (updating || window.plugin.maxLinks.layer === null ||
        !window.map.hasLayer(window.plugin.maxLinks.layer))
      return;
    updating = true;
    window.plugin.maxLinks.layer.clearLayers();

    var locations = [];
    var minX = 0;
    var minY = 0;

    $.each(window.portals, function(guid, portal) {
      var loc = portal.options.details.locationE6;
      var nloc = { x: loc.lngE6, y: loc.latE6 };
      if (nloc.x < minX)
        minX = nloc.x;
      if (nloc.y < minX)
        minX = nloc.y;
      locations.push(nloc);
    });

    $.each(locations, function(idx, nloc) {
      nloc.x += Math.abs(minX);
      nloc.y += Math.abs(minY);
    });

    var triangles = window.delaunay.triangulate(locations);
    var drawnLinks = 0;
    renderLimitReached = false;
    var renderlimit = window.USE_INCREASED_RENDER_LIMIT ?
      window.plugin.maxLinks.MAX_DRAWN_LINKS_INCREASED_LIMIT :
      window.plugin.maxLinks.MAX_DRAWN_LINKS;
    $.each(triangles, function(idx, triangle) {
      if (drawnLinks <= renderlimit) {
        triangle.draw(window.plugin.maxLinks.layer, minX, minY)
        drawnLinks += 3;
      } else {
        renderLimitReached = true;
      }
    });
    updating = false;
    window.renderUpdateStatus();
  }

  var setup =  function() {
    load(delaunayScriptLocation).thenRun(function() {

      window.delaunay.Triangle.prototype.draw = function(layer, divX, divY) {
        var drawLine = function(src, dest) {
          var poly = L.polyline([[(src.y + divY)/1E6, (src.x + divX)/1E6], [(dest.y + divY)/1E6, (dest.x + divX)/1E6]], window.plugin.maxLinks.STROKE_STYLE);
          poly.addTo(layer);
        };

        drawLine(this.a, this.b);
        drawLine(this.b, this.c);
        drawLine(this.c, this.a);
      }

      window.plugin.maxLinks.layer = L.layerGroup([]);

      window.addHook('checkRenderLimit', function(e) {
         if (window.map.hasLayer(window.plugin.maxLinks.layer) && renderLimitReached)
           e.reached = true;
      });

      window.map.on('layeradd', function(e) {
        if (e.layer === window.plugin.maxLinks.layer)
          window.plugin.maxLinks.updateLayer();
      });
      window.map.on('zoomend moveend', window.plugin.maxLinks.updateLayer);
      window.layerChooser.addOverlay(window.plugin.maxLinks.layer, 'Maximum Links');
    });
  }

  // PLUGIN END //////////////////////////////////////////////////////////
  if(window.iitcLoaded && typeof setup === 'function') {
    setup();
  } else {
    if(window.bootPlugins)
      window.bootPlugins.push(setup);
    else
      window.bootPlugins = [setup];
  }
} // wrapper end

// inject code into site context
var script = document.createElement('script');
script.appendChild(document.createTextNode('('+ wrapper +')();'));
(document.body || document.head || document.documentElement).appendChild(script);<|endoftext|>


<commit_before>import assignSafe from '../util/assign-safe';
import dashCase from '../util/dash-case';
import data from '../util/data';
import maybeThis from '../util/maybe-this';
import notify from './notify';

// TODO: Lean out option normalisation.
function property (name, prop) {
  var internalGetter, internalSetter, internalValue, isBoolean;

  if (typeof prop === 'object') {
    prop = assignSafe({}, prop);
  } else {
    prop = { type: prop };
  }

  if (prop.attr === true) {
    prop.attr = dashCase(name);
  }

  if (prop.notify === undefined) {
    prop.notify = true;
  }

  if (typeof prop.type !== 'function') {
    prop.type = val => val;
  }

  if (prop.init !== undefined && typeof prop.init !== 'function') {
    let value = prop.init;
    prop.init = () => value;
  }

  internalGetter = prop.get;
  internalSetter = prop.set;
  isBoolean = prop.type && prop.type === Boolean;

  prop.get = function () {
    return internalGetter ? internalGetter.apply(this) : internalValue;
  };

  prop.set = function (value) {
    var info = data(this);

    // If the property is being updated and it is a boolean we must just check
    // if the attribute exists because "" is true for a boolean attribute.
    if (info.updatingProperty && isBoolean) {
      value = this.hasAttribute(prop.attr);
    }

    // We report both new and old values;
    var newValue = prop.type(value);
    var oldValue = this[name];

    // TODO: Should we check at this point to see if it has changed and do
    // nothing if it hasn't? How can we then force-update if we need to?

    // Regardless of any options, we store the value internally.
    internalValue = newValue;

    // We check first to see if we're already updating the property from
    // the attribute. If we are, then there's no need to update the attribute
    // especially because it would invoke an infinite loop.
    if (prop.attr && !info.updatingProperty) {
      info.updatingAttribute = true;

      if (isBoolean && internalValue) {
        this.setAttribute(prop.attr, '');
      } else if (internalValue == null || isBoolean && !internalValue) {
        this.removeAttribute(prop.attr, '');
      } else {
        this.setAttribute(prop.attr, internalValue);
      }

      info.updatingAttribute = false;
    }

    // A setter is responsible for setting its own value. We still store the
    // value internally because the default getter may still be used to return
    // that value. Even if it's not, we use it to reference the old value which
    // is useful information for the setter.
    if (internalSetter) {
      internalSetter.call(this, newValue, oldValue);
    }

    if (prop.notify) {
      notify(this, name, {
        newValue: newValue,
        oldValue: oldValue
      });
    }
  };

  return prop;
}

function defineProperty (elem, name, prop) {
  // We don't need to scope the data to the component ID be cause if multiple
  // bindings on the same component define the same attribute, then they'd
  // conflict anyways.
  var info = data(elem);

  if (!info.attributeToPropertyMap) {
    info.attributeToPropertyMap = {};
  }

  prop = property(name, prop);
  Object.defineProperty(elem, name, prop);

  // TODO: What happens if the setter does something with a descendant that
  // may not exist yet?
  //
  // Initialise the value if a initial value was provided. Attributes that exist
  // on the element should trump any default values that are provided.
  if (prop.init !== undefined && !prop.attr || !elem.hasAttribute(prop.attr)) {
    elem[name] = prop.init.call(elem);
  }

  // This ensures that the corresponding attribute will know to update this
  // property when it is set.
  if (prop.attr) {
    info.attributeToPropertyMap[prop.attr] = name;
  }
}

function defineProperties (elem, props) {
  Object.keys(props).forEach(function (name) {
    defineProperty(elem, name, props[name]);
  });
}

export default maybeThis(function (elem, props = {}, prop = {}) {
  if (typeof props === 'string') {
    defineProperty(elem, props, prop);
  } else {
    defineProperties(elem, props);
  }
});
<commit_msg>Put brackets around a statement to ensure proper order and combinations.<commit_after>import assignSafe from '../util/assign-safe';
import dashCase from '../util/dash-case';
import data from '../util/data';
import maybeThis from '../util/maybe-this';
import notify from './notify';

// TODO: Lean out option normalisation.
function property (name, prop) {
  var internalGetter, internalSetter, internalValue, isBoolean;

  if (typeof prop === 'object') {
    prop = assignSafe({}, prop);
  } else {
    prop = { type: prop };
  }

  if (prop.attr === true) {
    prop.attr = dashCase(name);
  }

  if (prop.notify === undefined) {
    prop.notify = true;
  }

  if (typeof prop.type !== 'function') {
    prop.type = val => val;
  }

  if (prop.init !== undefined && typeof prop.init !== 'function') {
    let value = prop.init;
    prop.init = () => value;
  }

  internalGetter = prop.get;
  internalSetter = prop.set;
  isBoolean = prop.type && prop.type === Boolean;

  prop.get = function () {
    return internalGetter ? internalGetter.apply(this) : internalValue;
  };

  prop.set = function (value) {
    var info = data(this);

    // If the property is being updated and it is a boolean we must just check
    // if the attribute exists because "" is true for a boolean attribute.
    if (info.updatingProperty && isBoolean) {
      value = this.hasAttribute(prop.attr);
    }

    // We report both new and old values;
    var newValue = prop.type(value);
    var oldValue = this[name];

    // TODO: Should we check at this point to see if it has changed and do
    // nothing if it hasn't? How can we then force-update if we need to?

    // Regardless of any options, we store the value internally.
    internalValue = newValue;

    // We check first to see if we're already updating the property from
    // the attribute. If we are, then there's no need to update the attribute
    // especially because it would invoke an infinite loop.
    if (prop.attr && !info.updatingProperty) {
      info.updatingAttribute = true;

      if (isBoolean && internalValue) {
        this.setAttribute(prop.attr, '');
      } else if (internalValue == null || isBoolean && !internalValue) {
        this.removeAttribute(prop.attr, '');
      } else {
        this.setAttribute(prop.attr, internalValue);
      }

      info.updatingAttribute = false;
    }

    // A setter is responsible for setting its own value. We still store the
    // value internally because the default getter may still be used to return
    // that value. Even if it's not, we use it to reference the old value which
    // is useful information for the setter.
    if (internalSetter) {
      internalSetter.call(this, newValue, oldValue);
    }

    if (prop.notify) {
      notify(this, name, {
        newValue: newValue,
        oldValue: oldValue
      });
    }
  };

  return prop;
}

function defineProperty (elem, name, prop) {
  // We don't need to scope the data to the component ID be cause if multiple
  // bindings on the same component define the same attribute, then they'd
  // conflict anyways.
  var info = data(elem);

  if (!info.attributeToPropertyMap) {
    info.attributeToPropertyMap = {};
  }

  prop = property(name, prop);
  Object.defineProperty(elem, name, prop);

  // TODO: What happens if the setter does something with a descendant that
  // may not exist yet?
  //
  // Initialise the value if a initial value was provided. Attributes that exist
  // on the element should trump any default values that are provided.
  if (prop.init && (!prop.attr || !elem.hasAttribute(prop.attr))) {
    elem[name] = prop.init.call(elem);
  }

  // This ensures that the corresponding attribute will know to update this
  // property when it is set.
  if (prop.attr) {
    info.attributeToPropertyMap[prop.attr] = name;
  }
}

function defineProperties (elem, props) {
  Object.keys(props).forEach(function (name) {
    defineProperty(elem, name, props[name]);
  });
}

export default maybeThis(function (elem, props = {}, prop = {}) {
  if (typeof props === 'string') {
    defineProperty(elem, props, prop);
  } else {
    defineProperties(elem, props);
  }
});
<|endoftext|>


<commit_before>/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for
 * full list of contributors). Published under the 2-clause BSD license.
 * See license.txt in the OpenLayers distribution or repository for the
 * full text of the license. */

/**
 * @requires OpenLayers/Format/XML.js
 * @requires OpenLayers/Format/OGCExceptionReport.js
 */

/**
 * Class: OpenLayers.Format.XML.VersionedOGC
 * Base class for versioned formats, i.e. a format which supports multiple
 * versions.
 *
 * Inherits from:
 *  - <OpenLayers.Format.XML>
 */
OpenLayers.Format.XML.VersionedOGC = OpenLayers.Class(OpenLayers.Format.XML, {

    /**
     * APIProperty: defaultVersion
     * {String} Version number to assume if none found.
     */
    defaultVersion: null,

    /**
     * APIProperty: version
     * {String} Specify a version string if one is known.
     */
    version: null,

    /**
     * APIProperty: profile
     * {String} If provided, use a custom profile.
     */
    profile: null,

    /**
     * APIProperty: allowFallback
     * {Boolean} If a profiled parser cannot be found for the returned version,
     * use a non-profiled parser as the fallback. Application code using this
     * should take into account that the return object structure might be
     * missing the specifics of the profile. Defaults to false.
     */
    allowFallback: false,

    /**
     * APIProperty: errorProperty
     * {String} Which property of the returned object to check for in order to
     * determine whether or not parsing has failed. In the case that the
     * errorProperty is undefined on the returned object, the document will be
     * run through an OGCExceptionReport parser.
     */
    errorProperty: null,

    /**
     * Property: name
     * {String} The name of this parser, this is the part of the CLASS_NAME
     * except for "OpenLayers.Format."
     */
    name: null,

    /**
     * APIProperty: stringifyOutput
     * {Boolean} If true, write will return a string otherwise a DOMElement.
     * Default is false.
     */
    stringifyOutput: false,

    /**
     * Property: parser
     * {Object} Instance of the versioned parser.  Cached for multiple read and
     *     write calls of the same version.
     */
    parser: null,

    /**
     * Constructor: OpenLayers.Format.XML.VersionedOGC.
     * Constructor.
     *
     * Parameters:
     * options - {Object} Optional object whose properties will be set on
     *     the object.
     */
    initialize: function(options) {
        OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
        var className = this.CLASS_NAME;
        this.name = className.substring(className.lastIndexOf(".")+1);
    },

    /**
     * Method: getVersion
     * Returns the version to use. Subclasses can override this function
     * if a different version detection is needed.
     *
     * Parameters:
     * root - {DOMElement}
     * options - {Object} Optional configuration object.
     *
     * Returns:
     * {String} The version to use.
     */
    getVersion: function(root, options) {
        var version;
        // read
        if (root) {
            version = this.version;
            if(!version) {
                version = root.getAttribute("version");
                if(!version) {
                    version = this.defaultVersion;
                }
            }
        } else { // write
            version = (options && options.version) ||
                this.version || this.defaultVersion;
        }
        return version;
    },

    /**
     * Method: getParser
     * Get an instance of the cached parser if available, otherwise create one.
     *
     * Parameters:
     * version - {String}
     *
     * Returns:
     * {<OpenLayers.Format>}
     */
    getParser: function(version) {
        version = version || this.defaultVersion;
        var profile = this.profile ? "_" + this.profile : "";
        if(!this.parser || this.parser.VERSION != version) {
            var format = OpenLayers.Format[this.name][
                "v" + version.replace(/\./g, "_") + profile
            ];
            if(!format) {
                if (profile !== "" && this.allowFallback) {
                    // fallback to the non-profiled version of the parser
                    profile = "";
                    format = OpenLayers.Format[this.name][
                        "v" + version.replace(/\./g, "_")
                    ];
                }
                if (!format) {
                    throw "Can't find a " + this.name + " parser for version " +
                          version + profile;
                }
            }
            this.parser = new format(this.options);
        }
        return this.parser;
    },

    /**
     * APIMethod: write
     * Write a document.
     *
     * Parameters:
     * obj - {Object} An object representing the document.
     * options - {Object} Optional configuration object.
     *
     * Returns:
     * {String} The document as a string
     */
    write: function(obj, options) {
        var version = this.getVersion(null, options);
        this.parser = this.getParser(version);
        var root = this.parser.write(obj, options);
        if (this.stringifyOutput === false) {
            return root;
        } else {
            return OpenLayers.Format.XML.prototype.write.apply(this, [root]);
        }
    },

    /**
     * APIMethod: read
     * Read a doc and return an object representing the document.
     *
     * Parameters:
     * data - {String | DOMElement} Data to read.
     * options - {Object} Options for the reader.
     *
     * Returns:
     * {Object} An object representing the document.
     */
    read: function(data, options) {
        if(typeof data == "string") {
            data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
        }
        var root = data.documentElement;
        var version = this.getVersion(root);
        this.parser = this.getParser(version);          // Select the parser
        var obj = this.parser.read(data, options);      // Parse the data

        var errorProperty = this.parser.errorProperty || null;
        if (errorProperty !== null && obj[errorProperty] === undefined) {
            // an error must have happened, so parse it and report back
            var format = new OpenLayers.Format.OGCExceptionReport();
            obj.error = format.read(data);
        }
        obj.version = version;
        return obj;
    },

    CLASS_NAME: "OpenLayers.Format.XML.VersionedOGC"
});
<commit_msg>Update comment/documentation<commit_after>/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for
 * full list of contributors). Published under the 2-clause BSD license.
 * See license.txt in the OpenLayers distribution or repository for the
 * full text of the license. */

/**
 * @requires OpenLayers/Format/XML.js
 * @requires OpenLayers/Format/OGCExceptionReport.js
 */

/**
 * Class: OpenLayers.Format.XML.VersionedOGC
 * Base class for versioned formats, i.e. a format which supports multiple
 * versions.
 *
 * To enable checking if parsing succeeded, you will need to define a property
 * called errorProperty on the parser you want to check. The parser will then
 * check the returned object to see if that property is present. If it is, it
 * assumes the parsing was successful. If it is not present (or is null), it will
 * pass the document through an OGCExceptionReport parser.
 *
 * If errorProperty is undefined for the parser, this error checking mechanism
 * will be disabled.
 *
 *
 *
 * Inherits from:
 *  - <OpenLayers.Format.XML>
 */
OpenLayers.Format.XML.VersionedOGC = OpenLayers.Class(OpenLayers.Format.XML, {

    /**
     * APIProperty: defaultVersion
     * {String} Version number to assume if none found.
     */
    defaultVersion: null,

    /**
     * APIProperty: version
     * {String} Specify a version string if one is known.
     */
    version: null,

    /**
     * APIProperty: profile
     * {String} If provided, use a custom profile.
     */
    profile: null,

    /**
     * APIProperty: allowFallback
     * {Boolean} If a profiled parser cannot be found for the returned version,
     * use a non-profiled parser as the fallback. Application code using this
     * should take into account that the return object structure might be
     * missing the specifics of the profile. Defaults to false.
     */
    allowFallback: false,

    /**
     * Property: name
     * {String} The name of this parser, this is the part of the CLASS_NAME
     * except for "OpenLayers.Format."
     */
    name: null,

    /**
     * APIProperty: stringifyOutput
     * {Boolean} If true, write will return a string otherwise a DOMElement.
     * Default is false.
     */
    stringifyOutput: false,

    /**
     * Property: parser
     * {Object} Instance of the versioned parser.  Cached for multiple read and
     *     write calls of the same version.
     */
    parser: null,

    /**
     * Constructor: OpenLayers.Format.XML.VersionedOGC.
     * Constructor.
     *
     * Parameters:
     * options - {Object} Optional object whose properties will be set on
     *     the object.
     */
    initialize: function(options) {
        OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
        var className = this.CLASS_NAME;
        this.name = className.substring(className.lastIndexOf(".")+1);
    },

    /**
     * Method: getVersion
     * Returns the version to use. Subclasses can override this function
     * if a different version detection is needed.
     *
     * Parameters:
     * root - {DOMElement}
     * options - {Object} Optional configuration object.
     *
     * Returns:
     * {String} The version to use.
     */
    getVersion: function(root, options) {
        var version;
        // read
        if (root) {
            version = this.version;
            if(!version) {
                version = root.getAttribute("version");
                if(!version) {
                    version = this.defaultVersion;
                }
            }
        } else { // write
            version = (options && options.version) ||
                this.version || this.defaultVersion;
        }
        return version;
    },

    /**
     * Method: getParser
     * Get an instance of the cached parser if available, otherwise create one.
     *
     * Parameters:
     * version - {String}
     *
     * Returns:
     * {<OpenLayers.Format>}
     */
    getParser: function(version) {
        version = version || this.defaultVersion;
        var profile = this.profile ? "_" + this.profile : "";
        if(!this.parser || this.parser.VERSION != version) {
            var format = OpenLayers.Format[this.name][
                "v" + version.replace(/\./g, "_") + profile
            ];
            if(!format) {
                if (profile !== "" && this.allowFallback) {
                    // fallback to the non-profiled version of the parser
                    profile = "";
                    format = OpenLayers.Format[this.name][
                        "v" + version.replace(/\./g, "_")
                    ];
                }
                if (!format) {
                    throw "Can't find a " + this.name + " parser for version " +
                          version + profile;
                }
            }
            this.parser = new format(this.options);
        }
        return this.parser;
    },

    /**
     * APIMethod: write
     * Write a document.
     *
     * Parameters:
     * obj - {Object} An object representing the document.
     * options - {Object} Optional configuration object.
     *
     * Returns:
     * {String} The document as a string
     */
    write: function(obj, options) {
        var version = this.getVersion(null, options);
        this.parser = this.getParser(version);
        var root = this.parser.write(obj, options);
        if (this.stringifyOutput === false) {
            return root;
        } else {
            return OpenLayers.Format.XML.prototype.write.apply(this, [root]);
        }
    },

    /**
     * APIMethod: read
     * Read a doc and return an object representing the document.
     *
     * Parameters:
     * data - {String | DOMElement} Data to read.
     * options - {Object} Options for the reader.
     *
     * Returns:
     * {Object} An object representing the document.
     */
    read: function(data, options) {
        if(typeof data == "string") {
            data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
        }
        var root = data.documentElement;
        var version = this.getVersion(root);
        this.parser = this.getParser(version);          // Select the parser
        var obj = this.parser.read(data, options);      // Parse the data

        var errorProperty = this.parser.errorProperty || null;
        if (errorProperty !== null && obj[errorProperty] === undefined) {
            // an error must have happened, so parse it and report back
            var format = new OpenLayers.Format.OGCExceptionReport();
            obj.error = format.read(data);
        }
        obj.version = version;
        return obj;
    },

    CLASS_NAME: "OpenLayers.Format.XML.VersionedOGC"
});
<|endoftext|>