<commit_before>Openure = {
    allViews: [],
    currentView: "",
    listener: "",
    trackedViewsIDs: [],
    previousView: null,
    stackSize: 0,
    maxStackSize: 30,

    findViewsInArray: function(array) {
    //for x in array.len....
        //this.findViewsInView(region.currentView);
    },

    registerView: function(view) {
        if (view.cid && _.lastIndexOf(this.trackedViewsIDs, view.cid) == -1) {
            this.trackedViewsIDs.push(view.cid);

            this.allViews.push(view);
        }
    },

    findViewsInObject: function(obj) {
    this.stackSize++;
    if (this.stackSize < this.maxStackSize){
          for(var prop in obj) {
                if(obj.nodeName) {
                    //this is an html element, and continuing will blow up
                    return;
                }
              if (obj[prop] instanceof Backbone.View) {
                    this.registerView(obj[prop])
                  this.findViewsInObject(obj[prop]);
              }
        else if (obj[prop] instanceof Array) {
          this.findViewsInArray(obj[prop]);
        }
        else if (obj[prop] instanceof Function) {
          //skip
        }
              else if (obj[prop] instanceof Object) {
                  this.findViewsInObject(obj[prop]);
              }
          }
    }
    this.stackSize--;
    },

    applySelectedView: function() {
        clearInterval(this.listener);
        console.log("rock the view - " + this.currentView.cid);

        //Remove the current console when clicking a new one.
        if($('#console').length) {
            this.previousView.el.removeChild($('#console')[0]);
        }

        //For now, close it by clicking the same view again.
        if(this.previousView && this.previousView.cid === this.currentView.cid){
            this.previousView = null;
            return;
        }

        var jqconsole = document.createElement('div');

        var width = this.currentView.$el.css('width');
        width = width.substr(0, width.indexOf('px')); //pull off the px
        var consoleWidth = parseInt(width) - 5;
        jqconsole.style.cssText = 'width:' + consoleWidth + 'px;z-index:99';
        jqconsole.id = "console";

        this.currentView.el.appendChild(jqconsole);

// Creating the console.
        var header = 'Welcome to Openure in JQConsole!\n' +
            'The variable "view" is now in context\n' +
            'here and in the chrome console.\n' +
            'As is model, collection, and options.\n';
        this.jqconsole = $('#console').jqconsole(header, 'JS> ');

// Abort prompt on Ctrl+Z.
        this.jqconsole.RegisterShortcut('Z', function() {
            this.jqconsole.AbortPrompt();
            handler();
        });

// Move to line start Ctrl+A.
        this.jqconsole.RegisterShortcut('A', function() {
            this.jqconsole.MoveToStart();
            handler();
        });

// Move to line end Ctrl+E.
        this.jqconsole.RegisterShortcut('E', function() {
            this.jqconsole.MoveToEnd();
            handler();
        });

        this.jqconsole.RegisterMatching('{', '}', 'brace');
        this.jqconsole.RegisterMatching('(', ')', 'paran');
        this.jqconsole.RegisterMatching('[', ']', 'bracket');

        isObject = function(obj) {
            return obj === Object(obj);
        };

// Handle a command.
        var handler = _.bind(function(command) {
            if (command) {
                try {
                    var result = window.eval(command);
                } catch (e) {
                    this.jqconsole.Write('ERROR: ' + e.message + '\n');
                }
                try {
                    if(isObject(result)) {
                        result = JSON.stringify(result, function(k, v) {
                            return (k === '$el' || k === 'el' || k === '_events' || k === '_listeners') ? undefined : v;
                        }, 2);
                    }
                } catch (e) {
                    if (e.message === 'Converting circular structure to JSON') {
                        this.jqconsole.Write('ERROR: ' + e.message + '\n');
                        this.jqconsole.Write('Please try the same command in the chrome console.\n');
                    }
                    else {
                        this.jqconsole.Write('ERROR: ' + e.message + '\n');
                    }
                }

                this.jqconsole.Write(result);
                this.jqconsole.Write('\n');
            }
            this.jqconsole.Prompt(true, handler, function(command) {
                // Continue line if can't compile the command.
                try {
                    Function(command);
                } catch (e) {
                    if (/[\[\{\(]$/.test(command)) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
                return false;
            });
        }, this);

// Initiate the first prompt.
        handler();

        model = this.currentView.model;
        view = this.currentView;
        collection = this.currentView.collection;
        options = this.currentView.options;
        this.previousView = view;
    },

    go: function() {
        var openureKey = $('openure_keys');
        if(openureKey.length < 1 || openureKey.text() === ""){
            console.log('No Openure keys are configured.  Go to the Chrome extensions page and add the key to the Openure options page.')
            return;
        }
        console.log('Running Openure against global variable: ' + openureKey.text());
        this.findViewsInObject(eval(openureKey.text()));

        _.each(this.allViews, function(view) {
            view.$el[0].addEventListener('click', _.bind(function(e) {
                if(e.metaKey && e.shiftKey) {
                    var ownIt = _.bind(this.applySelectedView, this);

                    clearInterval(this.listener);
                    this.listener = setInterval(ownIt, 100);

                    e.preventDefault();
                    this.currentView = view;
                }
            }, this), true);
        }, this);
    }
};

$(function () {
    Openure.go();
});
<commit_msg>Fixed spacing issues and cleaned up missing semi-colons<commit_after>Openure = {
  allViews: [],
  currentView: "",
  listener: "",
  trackedViewsIDs: [],
  previousView: null,
  stackSize: 0,
  maxStackSize: 30,

  findViewsInArray: function(array) {
  //for x in array.len....
    //this.findViewsInView(region.currentView);
  },

  registerView: function(view) {
    if (view.cid && _.lastIndexOf(this.trackedViewsIDs, view.cid) == -1) {
      this.trackedViewsIDs.push(view.cid);
      this.allViews.push(view);
    }
  },

  findViewsInObject: function(obj) {
    this.stackSize++;
    if (this.stackSize < this.maxStackSize) {
      for(var prop in obj) {
        if(obj.nodeName) {
          //this is an html element, and continuing will blow up
          return;
        }

        if (obj[prop] instanceof Backbone.View) {
          this.registerView(obj[prop]);
          this.findViewsInObject(obj[prop]);
        } else if (obj[prop] instanceof Array) {
          this.findViewsInArray(obj[prop]);
        } else if (obj[prop] instanceof Function) {
          //skip
        } else if (obj[prop] instanceof Object) {
          this.findViewsInObject(obj[prop]);
        }
      }
    }
    this.stackSize--;
  },

  applySelectedView: function() {
    clearInterval(this.listener);
    console.log("rock the view - " + this.currentView.cid);

    //Remove the current console when clicking a new one.
    if($('#console').length) {
      this.previousView.el.removeChild($('#console')[0]);
    }

    //For now, close it by clicking the same view again.
    if(this.previousView && this.previousView.cid === this.currentView.cid){
      this.previousView = null;
      return;
    }

    var jqconsole = document.createElement('div');

    var width = this.currentView.$el.css('width');
    width = width.substr(0, width.indexOf('px')); //pull off the px
    var consoleWidth = parseInt(width, 10) - 5;
    jqconsole.style.cssText = 'width:' + consoleWidth + 'px;z-index:99';
    jqconsole.id = "console";

    this.currentView.el.appendChild(jqconsole);

    // Creating the console.
    var header = 'Welcome to Openure in JQConsole!\n' +
      'The variable "view" is now in context\n' +
      'here and in the chrome console.\n' +
      'As is model, collection, and options.\n';
    this.jqconsole = $('#console').jqconsole(header, 'JS> ');

    // Abort prompt on Ctrl+Z.
    this.jqconsole.RegisterShortcut('Z', function() {
      this.jqconsole.AbortPrompt();
      handler();
    });

    // Move to line start Ctrl+A.
    this.jqconsole.RegisterShortcut('A', function() {
      this.jqconsole.MoveToStart();
      handler();
    });

    // Move to line end Ctrl+E.
    this.jqconsole.RegisterShortcut('E', function() {
      this.jqconsole.MoveToEnd();
      handler();
    });

    this.jqconsole.RegisterMatching('{', '}', 'brace');
    this.jqconsole.RegisterMatching('(', ')', 'paran');
    this.jqconsole.RegisterMatching('[', ']', 'bracket');

    isObject = function(obj) {
      return obj === Object(obj);
    };

    // Handle a command.
    var handler = _.bind(function(command) {
      var result;
      if (command) {
        try {
          result = window.eval(command);
        } catch (e) {
          this.jqconsole.Write('ERROR: ' + e.message + '\n');
        }
        try {
          if(isObject(result)) {
            result = JSON.stringify(result, function(k, v) {
              return (k === '$el' || k === 'el' || k === '_events' || k === '_listeners') ? undefined : v;
            }, 2);
          }
        } catch (e) {
          if (e.message === 'Converting circular structure to JSON') {
            this.jqconsole.Write('ERROR: ' + e.message + '\n');
            this.jqconsole.Write('Please try the same command in the chrome console.\n');
          }
          else {
            this.jqconsole.Write('ERROR: ' + e.message + '\n');
          }
        }

        this.jqconsole.Write(result);
        this.jqconsole.Write('\n');
      }
      this.jqconsole.Prompt(true, handler, function(command) {
        // Continue line if can't compile the command.
        try {
          Function(command);
        } catch (e) {
          if (/[\[\{\(]$/.test(command)) {
            return 1;
          } else {
            return 0;
          }
        }
        return false;
      });
    }, this);

    // Initiate the first prompt.
    handler();

    model = this.currentView.model;
    view = this.currentView;
    collection = this.currentView.collection;
    options = this.currentView.options;
    this.previousView = view;
  },

  go: function() {
    var openureKey = $('openure_keys');
    if(openureKey.length < 1 || openureKey.text() === ""){
      console.log('No Openure keys are configured.  Go to the Chrome extensions page and add the key to the Openure options page.');
      return;
    }
    console.log('Running Openure against global variable: ' + openureKey.text());
    this.findViewsInObject(eval(openureKey.text()));

    _.each(this.allViews, function(view) {
      view.$el[0].addEventListener('click', _.bind(function(e) {
        if(e.metaKey && e.shiftKey) {
          var ownIt = _.bind(this.applySelectedView, this);

          clearInterval(this.listener);
          this.listener = setInterval(ownIt, 100);

          e.preventDefault();
          this.currentView = view;
        }
      }, this), true);
    }, this);
  }
};

$(function () {
  Openure.go();
});
<|endoftext|>


<commit_before>var path = require('path')
var eslint = require('eslint')
var pkg = require('./package.json')

module.exports = {
  version: pkg.version,
  homepage: pkg.homepage,
  bugs: pkg.bugs.url,
  eslint: eslint,
  cmd: 'superlint',
  tagline: 'Supermind linting standards',
  eslintConfig: {
    configFile: path.join(__dirname, 'eslintrc.js')
  },
  parseOpts(options, settings) {
    if (settings.use) {
      var eslintrc = require('./eslintrc')
      eslintrc.extends.concat(settings.use)
      console.log(eslintrc)
    }
    return options
  }
}
<commit_msg>updated parseOpts<commit_after>var path = require('path')
var eslint = require('eslint')
var pkg = require('./package.json')

module.exports = {
  version: pkg.version,
  homepage: pkg.homepage,
  bugs: pkg.bugs.url,
  eslint: eslint,
  cmd: 'superlint',
  tagline: 'Supermind linting standards',
  eslintConfig: {
    configFile: path.join(__dirname, 'eslintrc.js')
  },
  parseOpts(options, config) {
    console.log(options)
    console.log('----------')
    console.log(config)
    console.log('----------')
    if (config.use) {
      var eslintrc = require('./eslintrc')
      eslintrc.extends.concat(config.use)
      console.log(eslintrc)
    }
    return options
  }
}
<|endoftext|>


<commit_before>"use strict";

const babelPresetMeteor = require("babel-preset-meteor");
const reifyPlugin = require("babel-plugin-transform-es2015-modules-reify");
const strictModulesPluginFactory =
  require("@babel/plugin-transform-modules-commonjs").default;

const babelModulesPlugin = [function () {
  const plugin = strictModulesPluginFactory.apply(this, arguments);
  // Since babel-preset-meteor uses an exact version of the
  // @babel/plugin-transform-modules-commonjs transform (6.8.0), we can be
  // sure this plugin.inherits property is indeed the
  // @babel/plugin-transform-strict-mode transform that we wish to
  // disable. Otherwise it would be difficult to know exactly what we're
  // deleting here, since plugins don't provide much identifying
  // information.
  delete plugin.inherits;
  return plugin;
}, {
  allowTopLevelThis: true,
  strictMode: false,
  loose: true
}];

exports.getDefaults = function getDefaults(features) {
  if (features &&
      features.nodeMajorVersion >= 8) {
    return getDefaultsForNode8(features);
  }

  const combined = {
    presets: [babelPresetMeteor],
    plugins: [
      [reifyPlugin, {
        generateLetDeclarations: true,
        enforceStrictMode: false
      }]
    ]
  };

  combined.plugins.push(
    require("./plugins/dynamic-import.js")
  );

  if (! (features &&
         features.runtime === false)) {
    combined.plugins.push(getRuntimeTransform());
  }

  if (features) {
    if (features.react) {
      combined.presets.push(require("@babel/preset-react"));
      combined.plugins.push(
        require("@babel/plugin-proposal-class-properties")
      );
    }

    if (features.jscript) {
      combined.plugins.push(
        require("./plugins/named-function-expressions.js"),
        require("./plugins/sanitize-for-in-objects.js")
      );
    }
  }

  // Even though we use Reify to transpile `import` and `export`
  // declarations in the original source, Babel sometimes inserts its own
  // `import` declarations later on, and of course Babel knows best how to
  // compile those declarations.
  combined.plugins.push(babelModulesPlugin);

  return {
    compact: false,
    sourceMap: false,
    ast: false,
    babelrc: false,
    presets: [combined]
  };
};

function getRuntimeTransform() {
  return [require("@babel/plugin-transform-runtime"), {
    // Avoid importing polyfills for things like Object.keys, which
    // Meteor already shims in other ways.
    polyfill: false,

    // Use runtime helpers that do not import any core-js polyfills,
    // since Meteor provides those polyfills in other ways.
    useBuiltIns: true
  }];
}

function getDefaultsForNode8(features) {
  const plugins = [];

  // Support Flow type syntax by simply stripping it out.
  plugins.push(
    require("@babel/plugin-syntax-flow"),
    require("@babel/plugin-transform-flow-strip-types")
  );

  // Compile import/export syntax with Reify.
  plugins.push([reifyPlugin, {
    generateLetDeclarations: true,
    enforceStrictMode: false
  }]);

  if (! (features &&
         features.runtime === false)) {
    // Import helpers from the babel-runtime package rather than
    // redefining them at the top of each module.
    plugins.push(getRuntimeTransform());
  }

  // Make assigning to imported symbols a syntax error.
  plugins.push(require("@babel/plugin-check-constants"));

  // Not fully supported in Node 8 without the --harmony flag.
  plugins.push(
    require("@babel/plugin-syntax-object-rest-spread"),
    require("@babel/plugin-proposal-object-rest-spread")
  );

  // Ensure that async functions run in a Fiber, while also taking
  // full advantage of native async/await support in Node 8.
  plugins.push([require("./plugins/async-await.js"), {
    // Do not transform `await x` to `Promise.await(x)`, since Node
    // 8 has native support for await expressions.
    useNativeAsyncAwait: false
  }]);

  // Transform `import(id)` to `module.dynamicImport(id)`.
  plugins.push(require("./plugins/dynamic-import.js"));

  // Enable class property syntax for server-side React code.
  plugins.push(require("@babel/plugin-proposal-class-properties"));

  // In case babel-plugin-transform-runtime generated any import
  // declarations after reifyPlugin ran, make sure to compile them.
  plugins.push(babelModulesPlugin);

  const presets = [{
    plugins
  }];

  if (features) {
    if (features.react) {
      // Enable JSX syntax for server-side React code.
      presets.push(require("@babel/preset-react"));
    }
  }

  return {
    compact: false,
    sourceMap: false,
    ast: false,
    babelrc: false,
    presets
  };
}

exports.getMinifierDefaults = function getMinifierDefaults(features) {
  const options = {
    // Generate code in loose mode
    compact: false,
    // Don't generate a source map, we do that during compilation
    sourceMap: false,
    // We don't need to generate AST code
    ast: false,
    // Do not honor babelrc settings, would conflict with compilation
    babelrc: false,
    // May be modified according to provided features below.
    plugins: [],
    // Only include the minifier plugins, since we've already compiled all
    // the ECMAScript syntax we want.
    presets: [require("babel-preset-minify")]
  };

  if (features) {
    if (features.inlineNodeEnv) {
      options.plugins.push([
        require("./plugins/inline-node-env.js"),
        { nodeEnv: features.inlineNodeEnv }
      ]);
    }
  }

  return options;
};
<commit_msg>Make transform-runtime useBuiltIns option configurable.<commit_after>"use strict";

const babelPresetMeteor = require("babel-preset-meteor");
const reifyPlugin = require("babel-plugin-transform-es2015-modules-reify");
const strictModulesPluginFactory =
  require("@babel/plugin-transform-modules-commonjs").default;

const babelModulesPlugin = [function () {
  const plugin = strictModulesPluginFactory.apply(this, arguments);
  // Since babel-preset-meteor uses an exact version of the
  // @babel/plugin-transform-modules-commonjs transform (6.8.0), we can be
  // sure this plugin.inherits property is indeed the
  // @babel/plugin-transform-strict-mode transform that we wish to
  // disable. Otherwise it would be difficult to know exactly what we're
  // deleting here, since plugins don't provide much identifying
  // information.
  delete plugin.inherits;
  return plugin;
}, {
  allowTopLevelThis: true,
  strictMode: false,
  loose: true
}];

exports.getDefaults = function getDefaults(features) {
  if (features &&
      features.nodeMajorVersion >= 8) {
    return getDefaultsForNode8(features);
  }

  const combined = {
    presets: [babelPresetMeteor],
    plugins: [
      [reifyPlugin, {
        generateLetDeclarations: true,
        enforceStrictMode: false
      }]
    ]
  };

  combined.plugins.push(
    require("./plugins/dynamic-import.js")
  );

  const rt = getRuntimeTransform(features);
  if (rt) {
    combined.plugins.push(rt);
  }

  if (features) {
    if (features.react) {
      combined.presets.push(require("@babel/preset-react"));
      combined.plugins.push(
        require("@babel/plugin-proposal-class-properties")
      );
    }

    if (features.jscript) {
      combined.plugins.push(
        require("./plugins/named-function-expressions.js"),
        require("./plugins/sanitize-for-in-objects.js")
      );
    }
  }

  // Even though we use Reify to transpile `import` and `export`
  // declarations in the original source, Babel sometimes inserts its own
  // `import` declarations later on, and of course Babel knows best how to
  // compile those declarations.
  combined.plugins.push(babelModulesPlugin);

  return {
    compact: false,
    sourceMap: false,
    ast: false,
    babelrc: false,
    presets: [combined]
  };
};

function isObject(value) {
  return value !== null && typeof value === "object";
}

function getRuntimeTransform(features) {
  let useBuiltIns = false;

  if (isObject(features)) {
    if (features.runtime === false) {
      return null;
    }

    if (isObject(features.runtime)) {
      useBuiltIns = !! features.runtime.useBuiltIns;
    }
  }

  // Import helpers from the babel-runtime package rather than redefining
  // them at the top of each module.
  return [require("@babel/plugin-transform-runtime"), {
    // Avoid importing polyfills for things like Object.keys, which
    // Meteor already shims in other ways.
    polyfill: false,

    // Use runtime helpers that do not import any core-js polyfills,
    // since Meteor provides those polyfills in other ways.
    useBuiltIns: useBuiltIns
  }];
}

function getDefaultsForNode8(features) {
  const plugins = [];

  // Support Flow type syntax by simply stripping it out.
  plugins.push(
    require("@babel/plugin-syntax-flow"),
    require("@babel/plugin-transform-flow-strip-types")
  );

  // Compile import/export syntax with Reify.
  plugins.push([reifyPlugin, {
    generateLetDeclarations: true,
    enforceStrictMode: false
  }]);

  const rt = getRuntimeTransform(features);
  if (rt) {
    plugins.push(rt);
  }

  // Make assigning to imported symbols a syntax error.
  plugins.push(require("@babel/plugin-check-constants"));

  // Not fully supported in Node 8 without the --harmony flag.
  plugins.push(
    require("@babel/plugin-syntax-object-rest-spread"),
    require("@babel/plugin-proposal-object-rest-spread")
  );

  // Ensure that async functions run in a Fiber, while also taking
  // full advantage of native async/await support in Node 8.
  plugins.push([require("./plugins/async-await.js"), {
    // Do not transform `await x` to `Promise.await(x)`, since Node
    // 8 has native support for await expressions.
    useNativeAsyncAwait: false
  }]);

  // Transform `import(id)` to `module.dynamicImport(id)`.
  plugins.push(require("./plugins/dynamic-import.js"));

  // Enable class property syntax for server-side React code.
  plugins.push(require("@babel/plugin-proposal-class-properties"));

  // In case babel-plugin-transform-runtime generated any import
  // declarations after reifyPlugin ran, make sure to compile them.
  plugins.push(babelModulesPlugin);

  const presets = [{
    plugins
  }];

  if (features) {
    if (features.react) {
      // Enable JSX syntax for server-side React code.
      presets.push(require("@babel/preset-react"));
    }
  }

  return {
    compact: false,
    sourceMap: false,
    ast: false,
    babelrc: false,
    presets
  };
}

exports.getMinifierDefaults = function getMinifierDefaults(features) {
  const options = {
    // Generate code in loose mode
    compact: false,
    // Don't generate a source map, we do that during compilation
    sourceMap: false,
    // We don't need to generate AST code
    ast: false,
    // Do not honor babelrc settings, would conflict with compilation
    babelrc: false,
    // May be modified according to provided features below.
    plugins: [],
    // Only include the minifier plugins, since we've already compiled all
    // the ECMAScript syntax we want.
    presets: [require("babel-preset-minify")]
  };

  if (features) {
    if (features.inlineNodeEnv) {
      options.plugins.push([
        require("./plugins/inline-node-env.js"),
        { nodeEnv: features.inlineNodeEnv }
      ]);
    }
  }

  return options;
};
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react'

import Translate from '../Translate'

export default class DefaultDetails extends Component {
  render() {
    const {
      deleteElement,
      id
    } = this.props

    return (
      <Translate
        childProps={ { onClick: () => deleteElement(id) } }
        HtmlElement="button"
        message="delete"
      />
    )
  }
}

DefaultDetails.propTypes = {
  deleteElement: PropTypes.func.isRequired,
  id: PropTypes.number.isRequired,
}
<commit_msg>Remove extra trailing comma<commit_after>import React, { PropTypes, Component } from 'react'

import Translate from '../Translate'

export default class DefaultDetails extends Component {
  render() {
    const {
      deleteElement,
      id
    } = this.props

    return (
      <Translate
        childProps={ { onClick: () => deleteElement(id) } }
        HtmlElement="button"
        message="delete"
      />
    )
  }
}

DefaultDetails.propTypes = {
  deleteElement: PropTypes.func.isRequired,
  id: PropTypes.number.isRequired
}
<|endoftext|>


<commit_before>"use strict";

const getESModule = require("reify/lib/runtime/utils.js").getESModule;
const nodeRequire = require;
require = function require(id) {
  const exports = nodeRequire(id);
  return getESModule(exports) && exports.default || exports;
};

const babelPresetMeteor = require("babel-preset-meteor");
const babelPresetMeteorModern = require("babel-preset-meteor/modern");
const reifyPlugin = require("reify/plugins/babel");

function getReifyPlugin(features) {
  return [reifyPlugin, getReifyOptions(features)];
}

function getReifyOptions(features) {
  const reifyOptions = {
    avoidModernSyntax: true,
    enforceStrictMode: false,
    dynamicImport: true
  };

  if (features) {
    if (features.modernBrowsers ||
        features.nodeMajorVersion >= 8) {
      reifyOptions.avoidModernSyntax = false;
      reifyOptions.generateLetDeclarations = true;
    }

    if (features.compileForShell) {
      // If we're compiling code to run in the Node REPL; we never want to
      // wrap it with a function to rename the `module` identifier.
      reifyOptions.moduleAlias = "module";
    }
  }

  return reifyOptions;
}

exports.getDefaults = function getDefaults(features) {
  if (features) {
    if (features.nodeMajorVersion >= 8) {
      return getDefaultsForNode8(features);
    }

    if (features.modernBrowsers) {
      return getDefaultsForModernBrowsers(features);
    }
  }

  const combined = {
    presets: [],
    plugins: [getReifyPlugin(features)]
  };

  const compileModulesOnly = features && features.compileModulesOnly;
  if (! compileModulesOnly) {
    combined.presets.push(babelPresetMeteor);

    const rt = getRuntimeTransform(features);
    if (rt) {
      combined.plugins.push(rt);
    }

    maybeAddReactPlugins(features, combined);
    maybeAddTypeScriptPreset(features, combined.presets);

    if (features && features.jscript) {
      combined.plugins.push(
        require("./plugins/named-function-expressions.js"),
        require("./plugins/sanitize-for-in-objects.js")
      );
    }
  }

  return finish([combined]);
};

function maybeAddReactPlugins(features, options) {
  if (features && features.react) {
    options.presets.push(require("@babel/preset-react"));
    options.plugins.push(
      [require("@babel/plugin-proposal-class-properties"), {
        loose: true
      }]
    );
  }
}

function maybeAddTypeScriptPreset(features, presets) {
  if (features && features.typescript) {
    presets.push(require("@babel/preset-typescript"));
  }
}

function getDefaultsForModernBrowsers(features) {
  const combined = {
    presets: [],
    plugins: [getReifyPlugin(features)]
  };

  const compileModulesOnly = features && features.compileModulesOnly;
  if (! compileModulesOnly) {
    combined.presets.push(babelPresetMeteorModern.getPreset);

    const rt = getRuntimeTransform(features);
    if (rt) {
      combined.plugins.push(rt);
    }

    maybeAddReactPlugins(features, combined);
    maybeAddTypeScriptPreset(features, combined.presets);
  }

  return finish([combined]);
}

const parserOpts = require("reify/lib/parsers/babel.js").options;
const util = require("./util.js");

function finish(presets) {
  return {
    compact: false,
    sourceMaps: false,
    ast: false,
    // Disable .babelrc lookup and processing.
    babelrc: false,
    // Disable babel.config.js lookup and processing.
    configFile: false,
    parserOpts: util.deepClone(parserOpts),
    presets: presets
  };
}

function isObject(value) {
  return value !== null && typeof value === "object";
}

function getRuntimeTransform(features) {
  if (isObject(features)) {
    if (features.runtime === false) {
      return null;
    }
  }

  // Import helpers from the babel-runtime package rather than redefining
  // them at the top of each module.
  return require("@babel/plugin-transform-runtime");
}

function getDefaultsForNode8(features) {
  // Compile import/export syntax with Reify.
  const plugins = [getReifyPlugin(features)];

  const compileModulesOnly = features.compileModulesOnly;
  if (! compileModulesOnly) {
    // Support Flow type syntax by simply stripping it out.
    plugins.push(
      require("@babel/plugin-syntax-flow"),
      require("@babel/plugin-transform-flow-strip-types")
    );

    const rt = getRuntimeTransform(features);
    if (rt) {
      plugins.push(rt);
    }

    // Not fully supported in Node 8 without the --harmony flag.
    plugins.push(
      require("@babel/plugin-syntax-object-rest-spread"),
      require("@babel/plugin-proposal-object-rest-spread")
    );

    // Ensure that async functions run in a Fiber, while also taking
    // full advantage of native async/await support in Node 8.
    plugins.push([require("./plugins/async-await.js"), {
      // Do not transform `await x` to `Promise.await(x)`, since Node
      // 8 has native support for await expressions.
      useNativeAsyncAwait: false
    }]);

    // Enable async generator functions proposal.
    plugins.push(require("@babel/plugin-proposal-async-generator-functions"));
  }

  const presets = [{
    plugins
  }];

  if (! compileModulesOnly) {
    maybeAddReactPlugins(features, { plugins, presets });
    maybeAddTypeScriptPreset(features, presets);
  }

  return finish(presets);
}

exports.getMinifierDefaults = function getMinifierDefaults(features) {
  const inlineNodeEnv = features && features.inlineNodeEnv;
  const keepFnName = !! (features && features.keepFnName);
  const options = {
    // Generate code in loose mode
    compact: false,
    // Don't generate a source map, we do that during compilation
    sourceMaps: false,
    // Necessary after https://github.com/babel/minify/pull/855
    comments: false,
    // We don't need to generate AST code
    ast: false,
    // Do not honor babelrc settings, would conflict with compilation
    babelrc: false,
    // May be modified according to provided features below.
    plugins: [],
    // Only include the minifier plugins, since we've already compiled all
    // the ECMAScript syntax we want.
    presets: [
      [require("babel-preset-minify"), {
        keepClassName: keepFnName,
        keepFnName
      }]
    ]
  };

  if (inlineNodeEnv) {
    options.plugins.push([
      require("./plugins/inline-node-env.js"),
      { nodeEnv: inlineNodeEnv }
    ]);
  }

  return options;
};
<commit_msg>Don't forget to include babel-preset-meteor/modern for Node 8.<commit_after>"use strict";

const getESModule = require("reify/lib/runtime/utils.js").getESModule;
const nodeRequire = require;
require = function require(id) {
  const exports = nodeRequire(id);
  return getESModule(exports) && exports.default || exports;
};

const babelPresetMeteor = require("babel-preset-meteor");
const babelPresetMeteorModern = require("babel-preset-meteor/modern");
const reifyPlugin = require("reify/plugins/babel");

function getReifyPlugin(features) {
  return [reifyPlugin, getReifyOptions(features)];
}

function getReifyOptions(features) {
  const reifyOptions = {
    avoidModernSyntax: true,
    enforceStrictMode: false,
    dynamicImport: true
  };

  if (features) {
    if (features.modernBrowsers ||
        features.nodeMajorVersion >= 8) {
      reifyOptions.avoidModernSyntax = false;
      reifyOptions.generateLetDeclarations = true;
    }

    if (features.compileForShell) {
      // If we're compiling code to run in the Node REPL; we never want to
      // wrap it with a function to rename the `module` identifier.
      reifyOptions.moduleAlias = "module";
    }
  }

  return reifyOptions;
}

exports.getDefaults = function getDefaults(features) {
  if (features) {
    if (features.nodeMajorVersion >= 8) {
      return getDefaultsForNode8(features);
    }

    if (features.modernBrowsers) {
      return getDefaultsForModernBrowsers(features);
    }
  }

  const combined = {
    presets: [],
    plugins: [getReifyPlugin(features)]
  };

  const compileModulesOnly = features && features.compileModulesOnly;
  if (! compileModulesOnly) {
    combined.presets.push(babelPresetMeteor);

    const rt = getRuntimeTransform(features);
    if (rt) {
      combined.plugins.push(rt);
    }

    maybeAddReactPlugins(features, combined);
    maybeAddTypeScriptPreset(features, combined.presets);

    if (features && features.jscript) {
      combined.plugins.push(
        require("./plugins/named-function-expressions.js"),
        require("./plugins/sanitize-for-in-objects.js")
      );
    }
  }

  return finish([combined]);
};

function maybeAddReactPlugins(features, options) {
  if (features && features.react) {
    options.presets.push(require("@babel/preset-react"));
    options.plugins.push(
      [require("@babel/plugin-proposal-class-properties"), {
        loose: true
      }]
    );
  }
}

function maybeAddTypeScriptPreset(features, presets) {
  if (features && features.typescript) {
    presets.push(require("@babel/preset-typescript"));
  }
}

function getDefaultsForModernBrowsers(features) {
  const combined = {
    presets: [],
    plugins: [getReifyPlugin(features)]
  };

  const compileModulesOnly = features && features.compileModulesOnly;
  if (! compileModulesOnly) {
    combined.presets.push(babelPresetMeteorModern.getPreset);

    const rt = getRuntimeTransform(features);
    if (rt) {
      combined.plugins.push(rt);
    }

    maybeAddReactPlugins(features, combined);
    maybeAddTypeScriptPreset(features, combined.presets);
  }

  return finish([combined]);
}

const parserOpts = require("reify/lib/parsers/babel.js").options;
const util = require("./util.js");

function finish(presets) {
  return {
    compact: false,
    sourceMaps: false,
    ast: false,
    // Disable .babelrc lookup and processing.
    babelrc: false,
    // Disable babel.config.js lookup and processing.
    configFile: false,
    parserOpts: util.deepClone(parserOpts),
    presets: presets
  };
}

function isObject(value) {
  return value !== null && typeof value === "object";
}

function getRuntimeTransform(features) {
  if (isObject(features)) {
    if (features.runtime === false) {
      return null;
    }
  }

  // Import helpers from the babel-runtime package rather than redefining
  // them at the top of each module.
  return require("@babel/plugin-transform-runtime");
}

function getDefaultsForNode8(features) {
  const combined = {
    presets: [],
    plugins: [getReifyPlugin(features)]
  };

  const compileModulesOnly = features.compileModulesOnly;
  if (! compileModulesOnly) {
    combined.presets.push(babelPresetMeteorModern.getPreset);

    // Support Flow type syntax by simply stripping it out.
    combined.plugins.push(
      require("@babel/plugin-syntax-flow"),
      require("@babel/plugin-transform-flow-strip-types")
    );

    const rt = getRuntimeTransform(features);
    if (rt) {
      combined.plugins.push(rt);
    }

    // Not fully supported in Node 8 without the --harmony flag.
    combined.plugins.push(
      require("@babel/plugin-syntax-object-rest-spread"),
      require("@babel/plugin-proposal-object-rest-spread")
    );

    // Ensure that async functions run in a Fiber, while also taking
    // full advantage of native async/await support in Node 8.
    combined.plugins.push([require("./plugins/async-await.js"), {
      // Do not transform `await x` to `Promise.await(x)`, since Node
      // 8 has native support for await expressions.
      useNativeAsyncAwait: false
    }]);

    // Enable async generator functions proposal.
    combined.plugins.push(require("@babel/plugin-proposal-async-generator-functions"));
  }

  if (! compileModulesOnly) {
    maybeAddReactPlugins(features, combined);
    maybeAddTypeScriptPreset(features, combined.presets);
  }

  return finish([combined]);
}

exports.getMinifierDefaults = function getMinifierDefaults(features) {
  const inlineNodeEnv = features && features.inlineNodeEnv;
  const keepFnName = !! (features && features.keepFnName);
  const options = {
    // Generate code in loose mode
    compact: false,
    // Don't generate a source map, we do that during compilation
    sourceMaps: false,
    // Necessary after https://github.com/babel/minify/pull/855
    comments: false,
    // We don't need to generate AST code
    ast: false,
    // Do not honor babelrc settings, would conflict with compilation
    babelrc: false,
    // May be modified according to provided features below.
    plugins: [],
    // Only include the minifier plugins, since we've already compiled all
    // the ECMAScript syntax we want.
    presets: [
      [require("babel-preset-minify"), {
        keepClassName: keepFnName,
        keepFnName
      }]
    ]
  };

  if (inlineNodeEnv) {
    options.plugins.push([
      require("./plugins/inline-node-env.js"),
      { nodeEnv: inlineNodeEnv }
    ]);
  }

  return options;
};
<|endoftext|>


<commit_before>import React from 'react';
import { select, text } from '@storybook/addon-knobs/react';
import { addStoryInGroup, COMPOSITIONS } from '../../../.storybook/utils';
import Button, { ButtonGroup } from '../button';
import DetailPage from './DetailPage';
import Icon from '../icon';
import IconButton from '../button/IconButton';
import { IconTrashMediumOutline, IconWarningBadgedMediumFilled } from '@teamleader/ui-icons';
import StatusLabel from '../statusLabel';
import { Box } from '../box';
import { Heading1, Monospaced, TextBody } from '../typography';
import { COLOR } from '../../constants';

const actionButtons = () => (
  <ButtonGroup marginLeft={7}>
    <ButtonGroup segmented>
      <Button>Open</Button>
      <Button active>Won</Button>
      <Button>Lost</Button>
    </ButtonGroup>
    <IconButton icon={<IconTrashMediumOutline />} />
  </ButtonGroup>
);

const totals = () => (
  <Box display="flex" alignSelf="flex-end">
    <Box textAlign="right">
      <TextBody color="neutral">
        Total
      </TextBody>
      <Box alignItems="center" display="flex">
        <Heading1>
          <Monospaced>999h99</Monospaced>
        </Heading1>
        <Icon color="gold" tint="dark" marginLeft={2}>
          <IconWarningBadgedMediumFilled />
        </Icon>
      </Box>
    </Box>
    <Box textAlign="right" marginLeft={7}>
      <TextBody color="neutral">
        Total
      </TextBody>
      <Box alignItems="center" display="flex">
        <Heading1>
          <Monospaced>999h99</Monospaced>
        </Heading1>
        <Icon color="gold" tint="dark" marginLeft={2}>
          <IconWarningBadgedMediumFilled />
        </Icon>
      </Box>
    </Box>
    <Box textAlign="right" marginLeft={7}>
      <TextBody color="neutral">
        Total
      </TextBody>
      <Box alignItems="center" display="flex">
        <Heading1>
          <Monospaced>999h99</Monospaced>
        </Heading1>
        <Icon color="gold" tint="dark" marginLeft={2}>
          <IconWarningBadgedMediumFilled />
        </Icon>
      </Box>
    </Box>
  </Box>
);

export default {
  title: addStoryInGroup(COMPOSITIONS, 'DetailPage'),

  parameters: {
    backgrounds: [
      { name: 'Neutral lightest', value: COLOR.NEUTRAL.LIGHTEST },
      { name: 'Neutral light', value: COLOR.NEUTRAL.LIGHT, default: true },
    ],
    info: {
      propTables: false,
    },
  },
};

export const composition = () => (
  <DetailPage>
    {header()}
    {body()}
  </DetailPage>
);

composition.story = {
  name: 'Composition',
  parameters: {
    info: {
      propTables: [DetailPage],
    },
  },
};

export const body = () => (
  <DetailPage.Body>
    <TextBody>Here you can add arbitrary content.</TextBody>
  </DetailPage.Body>
);

body.story = {
  name: 'Body',
  parameters: {
    info: {
      propTables: [DetailPage.Body],
    },
  },
};

export const header = () => (
  <DetailPage.Header
    backLinkProps={{
      element: select('Back link element', ['a', 'button'], 'button'),
      children: text('Back link label', 'Back to overview'),
    }}
    title={text('title', 'I am the detail page title')}
  />
);

header.story = {
  name: 'Header',
  parameters: {
    info: {
      propTables: [DetailPage.Header],
    },
  },
};

export const headerWithTitleSuffix = () => (
  <DetailPage.Header
    backLinkProps={{
      element: select('Back link element', ['a', 'button'], 'button'),
      children: text('Back link label', 'Back to overview'),
    }}
    title={text('title', 'I am the detail page title')}
    titleSuffix={<StatusLabel color="violet">Draft</StatusLabel>}
  />
);

headerWithTitleSuffix.story = {
  name: 'Header with title suffix',
  parameters: {
    info: {
      propTables: [DetailPage.Header],
    },
  },
};

export const headerWithActions = () => (
  <DetailPage.Header
    backLinkProps={{
      element: select('Back link element', ['a', 'button'], 'button'),
      children: text('Back link label', 'Back to overview'),
    }}
    title={text('title', 'I am the detail page title')}
  >
    {actionButtons()}
  </DetailPage.Header>
);

headerWithActions.story = {
  name: 'Header with actions',
  parameters: {
    info: {
      propTables: [DetailPage.Header],
    },
  },
};

export const headerWithTotals = () => (
  <DetailPage.Header
    backLinkProps={{
      element: select('Back link element', ['a', 'button'], 'button'),
      children: text('Back link label', 'Back to overview'),
    }}
    title={text('title', 'I am the detail page title')}
  >
    {totals()}
  </DetailPage.Header>
);

headerWithTotals.story = {
  name: 'Header with totals',
  parameters: {
    info: {
      propTables: [DetailPage.Header],
    },
  },
};

export const headerWithTotalsAndActions = () => (
  <DetailPage.Header
    backLinkProps={{
      element: select('Back link element', ['a', 'button'], 'button'),
      children: text('Back link label', 'Back to overview'),
    }}
    title={text('title', 'I am a way too long detail page title which will overflow with an ellipsis')}
  >
    {totals()}
    {actionButtons()}
  </DetailPage.Header>
);

headerWithTotalsAndActions.story = {
  name: 'Header with totals and actions',
  parameters: {
    info: {
      propTables: [DetailPage.Header],
    },
  },
};

export const headerWithEverthingTogether = () => (
  <DetailPage.Header
    backLinkProps={{
      element: select('Back link element', ['a', 'button'], 'button'),
      children: text('Back link label', 'Back to overview'),
    }}
    title={text('title', 'I am a way too long detail page title which will overflow with an ellipsis')}
    titleSuffix={<StatusLabel color="violet">Draft</StatusLabel>}
  >
    {totals()}
    {actionButtons()}
  </DetailPage.Header>
);

headerWithEverthingTogether.story = {
  name: 'Header with everything together',
  parameters: {
    info: {
      propTables: [DetailPage.Header],
    },
  },
};
<commit_msg>DetailPage: update story - move IconButton in front of segmented buttons<commit_after>import React from 'react';
import { select, text } from '@storybook/addon-knobs/react';
import { addStoryInGroup, COMPOSITIONS } from '../../../.storybook/utils';
import Button, { ButtonGroup } from '../button';
import DetailPage from './DetailPage';
import Icon from '../icon';
import IconButton from '../button/IconButton';
import { IconTrashMediumOutline, IconWarningBadgedMediumFilled } from '@teamleader/ui-icons';
import StatusLabel from '../statusLabel';
import { Box } from '../box';
import { Heading1, Monospaced, TextBody } from '../typography';
import { COLOR } from '../../constants';

const actionButtons = () => (
  <ButtonGroup marginLeft={7}>
    <IconButton icon={<IconTrashMediumOutline />} />
    <ButtonGroup segmented>
      <Button>Open</Button>
      <Button active>Won</Button>
      <Button>Lost</Button>
    </ButtonGroup>
  </ButtonGroup>
);

const totals = () => (
  <Box display="flex" alignSelf="flex-end">
    <Box textAlign="right">
      <TextBody color="neutral">
        Total
      </TextBody>
      <Box alignItems="center" display="flex">
        <Heading1>
          <Monospaced>999h99</Monospaced>
        </Heading1>
        <Icon color="gold" tint="dark" marginLeft={2}>
          <IconWarningBadgedMediumFilled />
        </Icon>
      </Box>
    </Box>
    <Box textAlign="right" marginLeft={7}>
      <TextBody color="neutral">
        Total
      </TextBody>
      <Box alignItems="center" display="flex">
        <Heading1>
          <Monospaced>999h99</Monospaced>
        </Heading1>
        <Icon color="gold" tint="dark" marginLeft={2}>
          <IconWarningBadgedMediumFilled />
        </Icon>
      </Box>
    </Box>
    <Box textAlign="right" marginLeft={7}>
      <TextBody color="neutral">
        Total
      </TextBody>
      <Box alignItems="center" display="flex">
        <Heading1>
          <Monospaced>999h99</Monospaced>
        </Heading1>
        <Icon color="gold" tint="dark" marginLeft={2}>
          <IconWarningBadgedMediumFilled />
        </Icon>
      </Box>
    </Box>
  </Box>
);

export default {
  title: addStoryInGroup(COMPOSITIONS, 'DetailPage'),

  parameters: {
    backgrounds: [
      { name: 'Neutral lightest', value: COLOR.NEUTRAL.LIGHTEST },
      { name: 'Neutral light', value: COLOR.NEUTRAL.LIGHT, default: true },
    ],
    info: {
      propTables: false,
    },
  },
};

export const composition = () => (
  <DetailPage>
    {header()}
    {body()}
  </DetailPage>
);

composition.story = {
  name: 'Composition',
  parameters: {
    info: {
      propTables: [DetailPage],
    },
  },
};

export const body = () => (
  <DetailPage.Body>
    <TextBody>Here you can add arbitrary content.</TextBody>
  </DetailPage.Body>
);

body.story = {
  name: 'Body',
  parameters: {
    info: {
      propTables: [DetailPage.Body],
    },
  },
};

export const header = () => (
  <DetailPage.Header
    backLinkProps={{
      element: select('Back link element', ['a', 'button'], 'button'),
      children: text('Back link label', 'Back to overview'),
    }}
    title={text('title', 'I am the detail page title')}
  />
);

header.story = {
  name: 'Header',
  parameters: {
    info: {
      propTables: [DetailPage.Header],
    },
  },
};

export const headerWithTitleSuffix = () => (
  <DetailPage.Header
    backLinkProps={{
      element: select('Back link element', ['a', 'button'], 'button'),
      children: text('Back link label', 'Back to overview'),
    }}
    title={text('title', 'I am the detail page title')}
    titleSuffix={<StatusLabel color="violet">Draft</StatusLabel>}
  />
);

headerWithTitleSuffix.story = {
  name: 'Header with title suffix',
  parameters: {
    info: {
      propTables: [DetailPage.Header],
    },
  },
};

export const headerWithActions = () => (
  <DetailPage.Header
    backLinkProps={{
      element: select('Back link element', ['a', 'button'], 'button'),
      children: text('Back link label', 'Back to overview'),
    }}
    title={text('title', 'I am the detail page title')}
  >
    {actionButtons()}
  </DetailPage.Header>
);

headerWithActions.story = {
  name: 'Header with actions',
  parameters: {
    info: {
      propTables: [DetailPage.Header],
    },
  },
};

export const headerWithTotals = () => (
  <DetailPage.Header
    backLinkProps={{
      element: select('Back link element', ['a', 'button'], 'button'),
      children: text('Back link label', 'Back to overview'),
    }}
    title={text('title', 'I am the detail page title')}
  >
    {totals()}
  </DetailPage.Header>
);

headerWithTotals.story = {
  name: 'Header with totals',
  parameters: {
    info: {
      propTables: [DetailPage.Header],
    },
  },
};

export const headerWithTotalsAndActions = () => (
  <DetailPage.Header
    backLinkProps={{
      element: select('Back link element', ['a', 'button'], 'button'),
      children: text('Back link label', 'Back to overview'),
    }}
    title={text('title', 'I am a way too long detail page title which will overflow with an ellipsis')}
  >
    {totals()}
    {actionButtons()}
  </DetailPage.Header>
);

headerWithTotalsAndActions.story = {
  name: 'Header with totals and actions',
  parameters: {
    info: {
      propTables: [DetailPage.Header],
    },
  },
};

export const headerWithEverthingTogether = () => (
  <DetailPage.Header
    backLinkProps={{
      element: select('Back link element', ['a', 'button'], 'button'),
      children: text('Back link label', 'Back to overview'),
    }}
    title={text('title', 'I am a way too long detail page title which will overflow with an ellipsis')}
    titleSuffix={<StatusLabel color="violet">Draft</StatusLabel>}
  >
    {totals()}
    {actionButtons()}
  </DetailPage.Header>
);

headerWithEverthingTogether.story = {
  name: 'Header with everything together',
  parameters: {
    info: {
      propTables: [DetailPage.Header],
    },
  },
};
<|endoftext|>


<commit_before>var googBookmarks = [
    new node('Calendar', 'http://calendar.google.com'),
    new node('Email', 'https://www.gmail.com'),
    new node('Search', 'http://www.google.com')
];
var techBookmarks = [
    new node('Microsoft', 'http://www.microsoft.com'),
    new node('Google', null, googBookmarks),
    new node('Mozilla', 'http://developer.mozilla.org')
];
var topLevel = [
    new node('Tech', null, techBookmarks),
    new node('Trello', 'https://www.trello.com'),
    new node('Hmm', 'http://www.grantwinney.com')
];

var addAllToSubFolder = true;

// makeCorsRequest();
  makePinboardApiRequest();
// populateBookmarks(new node('Ignore', null, topLevel));

function populateBookmarks(node) {
    chrome.bookmarks.getChildren("0", function(children) {
        for (var i = 0; i < children.length; i++) {
            if (children[i].title == 'Bookmarks Bar') {
                if (addAllToSubFolder) {
                    createPageOrFolder(node, children[i].id);
                }
                else {
                    traverseNodes(node, children[i].id);
                }
                break;
            }
        }
    });
}

function traverseNodes(parentNode, parentId) {
    for (var i = 0; i < parentNode.nodes.length; i++) {
        createPageOrFolder(parentNode.nodes[i], parentId);
    }
}

function createPageOrFolder(node, parentId) {
    chrome.bookmarks.create({'parentId': parentId,
                             'title': node.title,
                             'url': node.url},
                            function(newPageOrFolder) {
                                writeLogMessage(newPageOrFolder, parentId);
                                if (node.isFolder) {
                                    traverseNodes(node, newPageOrFolder.id)
                                }
                            });
}

function node(title, url, nodes=[]) {
    this.id = "-1";
    this.title = title;
    this.url = url;
    this.isFolder = (url == null);
    this.nodes = nodes;
}

function writeLogMessage(node, parentId) {
    console.log("Added page or folder '" + node.title + "' (" + node.id +
                ") to parent folder id " + parentId + ".");
}

//check_for_existing_bookmark_details();

function check_for_existing_bookmark_details() {
 // if (!url_params['url']) { return; }
  var bookmark_details_api = 'https://api.pinboard.in/v1/user/api_token?format=json&auth_token=grant:';

  $.support.cors = true;
  $.get(bookmark_details_api)
    .done(function(response) {
      $('#mainspinner').addClass('hidden');
      $('#submit').data('stateText', 'Add bookmark');
      if (response['posts'].length !== 1) { return; }

      var bookmark = response['posts'][0];

      $('input#title').val(bookmark['description']);

      if (bookmark['extended']) { // previously-saved bookmark description
        if ($.trim(bookmark['extended']) !== $.trim(url_params['description'])) { // ignore duplication
          $('textarea#description').val($.trim(bookmark['extended']) + '\n\n' + $.trim(url_params['description']));
        }
      }
      leave_a_gap();

      prepopulate_tags(bookmark['tags']);

      if (bookmark['shared'] === 'no') {
        $('#private').prop('checked', true).change();
      }
      if (bookmark['toread'] === 'yes') {
        $('#toread').prop('checked', true);
      }
      if (bookmark['time']) {
        var date = new Date(bookmark['time']);
        showBookmarkTimestamp(date);
      }

      $('#submit').data('stateText', 'Update bookmark');
      $('#submit span.text').text('Update bookmark');
    })

    .fail(function(response) {
      if (response.status === 0 && (response.statusText === 'No Transport' || 'Error: Access is denied.')) {
        display_critical_error('Cross-domain request failed. Your browser is denying this request from being sent.');
        display_reload_button();
      }
      if (response.status === 401) {
        display_critical_error('401 Unauthorised. Please check the username and API access token you provided.');
      }
    });
}

// getUserToken('grant','');
//
//  function getUserToken(username, password) {
//
//       console.log('pinboardservice: getting user token...');
//
//       var deferred = $q.defer();
//       // modify url to include username + password,  user:password. See https://pinboard.in/api/ under authentication
//       var authstringReplaced = this.authstring.replace('user', username).replace('password', password);
//       // request API token for session duration
//       var request = authstringReplaced + 'user/api_token' + this.format;
//
//       // execute standard request
//       self.executeStandardRequest(request, deferred);
//
//       console.log(deferred.promise);
//
//       return deferred.promise;
//     };

function makePinboardApiRequest() {
    // var url = "https://api.pinboard.in/v1/posts/update?auth_token=grant:";
    // var url = "https://api.pinboard.in/v1/user/api_token?auth_token=grant:";
    // var representationOfDesiredState = "The cheese is old and moldy, where is the bathroom?";

    var client = new XMLHttpRequest();

    client.open("GET", "https://api.pinboard.in/v1/user/api_token?format=json&auth_token=grant:");

    //client.setRequestHeader("Content-Type", "text/plain");

    client.onload = function(e) {
    //   var img = document.createElement('img');
    //   img.src = window.URL.createObjectURL(this.response);
    //   document.body.appendChild(img);

        if (client.status == 200)
            console.log("The request succeeded!\n\nThe response representation was:\n\n" + client.responseText)
        else
            console.log("The request did not succeed!\n\nThe response status was: " + client.status + " " + client.statusText + ".");
    };

    // client.send(representationOfDesiredState);
    client.send();

    // if (client.status == 200)
    //     console.log("The request succeeded!\n\nThe response representation was:\n\n" + client.responseText)
    // else
    //     console.log("The request did not succeed!\n\nThe response status was: " + client.status + " " + client.statusText + ".");
}
//
//
//
//
//
// // Create the XHR object.
// function createCORSRequest(method, url) {
//   var xhr = new XMLHttpRequest();
//   if ("withCredentials" in xhr) {
//     // XHR for Chrome/Firefox/Opera/Safari.
//     xhr.open(method, url, true);
//   } else if (typeof XDomainRequest != "undefined") {
//     // XDomainRequest for IE.
//     xhr = new XDomainRequest();
//     xhr.open(method, url);
//   } else {
//     // CORS not supported.
//     xhr = null;
//   }
//   return xhr;
// }
//
// // Helper method to parse the title tag from the response.
// function getTitle(text) {
//   return text.match('<title>(.*)?</title>')[1];
// }
//
// // Make the actual CORS request.
// function makeCorsRequest() {
//   // This is a sample server that supports CORS.
//   var url = 'https://api.pinboard.in/v1/user/api_token?format=json&auth_token=grant:';
//
//   var xhr = createCORSRequest('GET', url);
//   if (!xhr) {
//       alert(xhr);
//     alert('CORS not supported');
//     return;
//   }
//
//   // Response handlers.
//   xhr.onload = function() {
//     var text = xhr.responseText;
//     // var title = getTitle(text);
//     alert('Response from CORS request to ' + url + ': ' + text);
//   };
//
//   xhr.onerror = function() {
//     alert('Woops, there was an error making the request.');
//   };
//
//   xhr.send();
// }
//
//
//
// function createRequest() {
//   var result = null;
//   if (window.XMLHttpRequest) {
//     // FireFox, Safari, etc.
//     result = new XMLHttpRequest();
//     if (typeof xmlhttp.overrideMimeType != 'undefined') {
//       result.overrideMimeType('text/xml'); // Or anything else
//     }
//   }
//   else if (window.ActiveXObject) {
//     // MSIE
//     result = new ActiveXObject("Microsoft.XMLHTTP");
//   }
//   else {
//     // No known mechanism -- consider aborting the application
//   }
//   return result;
// }
//
// function whatever() {
//     var req = createRequest(); // defined above
//     // Create the callback:
//     req.onreadystatechange = function() {
//       if (req.readyState != 4) return; // Not there yet
//       if (req.status != 200) {
//         console.log(req.status);
//         return;
//       }
//       // Request successful, read the response
//       var resp = req.responseText;
//         console.log(req);
//       // ... and use it as needed by your app.
//     }
//
//     req.open("GET", "https://api.pinboard.in/v1/user/api_token?auth_token=grant:", true);
//     req.send();
// }

// var login = function(token) {
//     // test auth
//     var path = $.base64.encode("https://api.pinboard.in/v1/user/api_token?format=json&auth_token=grant:"),
//         popup = chrome.extension.getViews({
//             type: 'popup'
//         })[0],
//         jqxhr = $.ajax({
//             url: path,
//             type: 'GET',
//             timeout: 60000,
//             dataType: 'jsonp',
//             crossDomain: true,
//             contentType: 'text/plain'
//         });
//     jqxhr.always(function(data) {
//         console.log('Data: ' + data);
//         // console.log('Data Result: ' + data.result);
//         if (data.result) {
//             // success
//             _userInfo.authToken = token;
//             _userInfo.name = token.split(':')[0];
//             _userInfo.isChecked = true;
//             localStorage[authTokenKey] = token;
//             localStorage[checkedkey] = true;
//             console.log('login-succeed');
//             popup && popup.$rootScope &&
//                 popup.$rootScope.$broadcast('login-succeed');
//             _getTags();
//         } else {
//             // login error
//             console.log('login-failed1');
//             popup && popup.$rootScope &&
//                 popup.$rootScope.$broadcast('login-failed');
//         }
//     });
//     jqxhr.fail(function(data) {
//         if (data.statusText == 'timeout') {
//             console.log('login-failed2');
//             popup && popup.$rootScope &&
//                 popup.$rootScope.$broadcast('login-failed');
//         }
//     });
// };
//
// login('CF100DA71C020A2BC0DF');
<commit_msg>sample storage code.. gonna need that later<commit_after>var googBookmarks = [
    new node('Calendar', 'http://calendar.google.com'),
    new node('Email', 'https://www.gmail.com'),
    new node('Search', 'http://www.google.com')
];
var techBookmarks = [
    new node('Microsoft', 'http://www.microsoft.com'),
    new node('Google', null, googBookmarks),
    new node('Mozilla', 'http://developer.mozilla.org')
];
var topLevel = [
    new node('Tech', null, techBookmarks),
    new node('Trello', 'https://www.trello.com'),
    new node('Hmm', 'http://www.grantwinney.com')
];

var addAllToSubFolder = true;

// makeCorsRequest();
  makePinboardApiRequest();
// populateBookmarks(new node('Ignore', null, topLevel));

function populateBookmarks(node) {
    chrome.bookmarks.getChildren("0", function(children) {
        for (var i = 0; i < children.length; i++) {
            if (children[i].title == 'Bookmarks Bar') {
                if (addAllToSubFolder) {
                    createPageOrFolder(node, children[i].id);
                }
                else {
                    traverseNodes(node, children[i].id);
                }
                break;
            }
        }
    });
}

function traverseNodes(parentNode, parentId) {
    for (var i = 0; i < parentNode.nodes.length; i++) {
        createPageOrFolder(parentNode.nodes[i], parentId);
    }
}

function createPageOrFolder(node, parentId) {
    chrome.bookmarks.create({'parentId': parentId,
                             'title': node.title,
                             'url': node.url},
                            function(newPageOrFolder) {
                                writeLogMessage(newPageOrFolder, parentId);
                                if (node.isFolder) {
                                    traverseNodes(node, newPageOrFolder.id)
                                }
                            });
}

function node(title, url, nodes=[]) {
    this.id = "-1";
    this.title = title;
    this.url = url;
    this.isFolder = (url == null);
    this.nodes = nodes;
}

function writeLogMessage(node, parentId) {
    console.log("Added page or folder '" + node.title + "' (" + node.id +
                ") to parent folder id " + parentId + ".");
}

//check_for_existing_bookmark_details();

function check_for_existing_bookmark_details() {
 // if (!url_params['url']) { return; }
  var bookmark_details_api = 'https://api.pinboard.in/v1/user/api_token?format=json&auth_token=grant:';

  $.support.cors = true;
  $.get(bookmark_details_api)
    .done(function(response) {
      $('#mainspinner').addClass('hidden');
      $('#submit').data('stateText', 'Add bookmark');
      if (response['posts'].length !== 1) { return; }

      var bookmark = response['posts'][0];

      $('input#title').val(bookmark['description']);

      if (bookmark['extended']) { // previously-saved bookmark description
        if ($.trim(bookmark['extended']) !== $.trim(url_params['description'])) { // ignore duplication
          $('textarea#description').val($.trim(bookmark['extended']) + '\n\n' + $.trim(url_params['description']));
        }
      }
      leave_a_gap();

      prepopulate_tags(bookmark['tags']);

      if (bookmark['shared'] === 'no') {
        $('#private').prop('checked', true).change();
      }
      if (bookmark['toread'] === 'yes') {
        $('#toread').prop('checked', true);
      }
      if (bookmark['time']) {
        var date = new Date(bookmark['time']);
        showBookmarkTimestamp(date);
      }

      $('#submit').data('stateText', 'Update bookmark');
      $('#submit span.text').text('Update bookmark');
    })

    .fail(function(response) {
      if (response.status === 0 && (response.statusText === 'No Transport' || 'Error: Access is denied.')) {
        display_critical_error('Cross-domain request failed. Your browser is denying this request from being sent.');
        display_reload_button();
      }
      if (response.status === 401) {
        display_critical_error('401 Unauthorised. Please check the username and API access token you provided.');
      }
    });
}

// getUserToken('grant','');
//
//  function getUserToken(username, password) {
//
//       console.log('pinboardservice: getting user token...');
//
//       var deferred = $q.defer();
//       // modify url to include username + password,  user:password. See https://pinboard.in/api/ under authentication
//       var authstringReplaced = this.authstring.replace('user', username).replace('password', password);
//       // request API token for session duration
//       var request = authstringReplaced + 'user/api_token' + this.format;
//
//       // execute standard request
//       self.executeStandardRequest(request, deferred);
//
//       console.log(deferred.promise);
//
//       return deferred.promise;
//     };

function makePinboardApiRequest() {
    // var url = "https://api.pinboard.in/v1/posts/update?auth_token=grant:";
    // var url = "https://api.pinboard.in/v1/user/api_token?auth_token=grant:";
    // var representationOfDesiredState = "The cheese is old and moldy, where is the bathroom?";

    var client = new XMLHttpRequest();

    client.open("GET", "https://api.pinboard.in/v1/user/api_token?format=json&auth_token=grant:");

    //client.setRequestHeader("Content-Type", "text/plain");

    client.onload = function(e) {
    //   var img = document.createElement('img');
    //   img.src = window.URL.createObjectURL(this.response);
    //   document.body.appendChild(img);

        if (client.status == 200)
            console.log("The request succeeded!\n\nThe response representation was:\n\n" + client.responseText)
        else
            console.log("The request did not succeed!\n\nThe response status was: " + client.status + " " + client.statusText + ".");
    };

    // client.send(representationOfDesiredState);
    client.send();

    // if (client.status == 200)
    //     console.log("The request succeeded!\n\nThe response representation was:\n\n" + client.responseText)
    // else
    //     console.log("The request did not succeed!\n\nThe response status was: " + client.status + " " + client.statusText + ".");
}
//
//
//
//
//
// // Create the XHR object.
// function createCORSRequest(method, url) {
//   var xhr = new XMLHttpRequest();
//   if ("withCredentials" in xhr) {
//     // XHR for Chrome/Firefox/Opera/Safari.
//     xhr.open(method, url, true);
//   } else if (typeof XDomainRequest != "undefined") {
//     // XDomainRequest for IE.
//     xhr = new XDomainRequest();
//     xhr.open(method, url);
//   } else {
//     // CORS not supported.
//     xhr = null;
//   }
//   return xhr;
// }
//
// // Helper method to parse the title tag from the response.
// function getTitle(text) {
//   return text.match('<title>(.*)?</title>')[1];
// }
//
// // Make the actual CORS request.
// function makeCorsRequest() {
//   // This is a sample server that supports CORS.
//   var url = 'https://api.pinboard.in/v1/user/api_token?format=json&auth_token=grant:';
//
//   var xhr = createCORSRequest('GET', url);
//   if (!xhr) {
//       alert(xhr);
//     alert('CORS not supported');
//     return;
//   }
//
//   // Response handlers.
//   xhr.onload = function() {
//     var text = xhr.responseText;
//     // var title = getTitle(text);
//     alert('Response from CORS request to ' + url + ': ' + text);
//   };
//
//   xhr.onerror = function() {
//     alert('Woops, there was an error making the request.');
//   };
//
//   xhr.send();
// }
//
//
//
// function createRequest() {
//   var result = null;
//   if (window.XMLHttpRequest) {
//     // FireFox, Safari, etc.
//     result = new XMLHttpRequest();
//     if (typeof xmlhttp.overrideMimeType != 'undefined') {
//       result.overrideMimeType('text/xml'); // Or anything else
//     }
//   }
//   else if (window.ActiveXObject) {
//     // MSIE
//     result = new ActiveXObject("Microsoft.XMLHTTP");
//   }
//   else {
//     // No known mechanism -- consider aborting the application
//   }
//   return result;
// }
//
// function whatever() {
//     var req = createRequest(); // defined above
//     // Create the callback:
//     req.onreadystatechange = function() {
//       if (req.readyState != 4) return; // Not there yet
//       if (req.status != 200) {
//         console.log(req.status);
//         return;
//       }
//       // Request successful, read the response
//       var resp = req.responseText;
//         console.log(req);
//       // ... and use it as needed by your app.
//     }
//
//     req.open("GET", "https://api.pinboard.in/v1/user/api_token?auth_token=grant:", true);
//     req.send();
// }

// var login = function(token) {
//     // test auth
//     var path = $.base64.encode("https://api.pinboard.in/v1/user/api_token?format=json&auth_token=grant:"),
//         popup = chrome.extension.getViews({
//             type: 'popup'
//         })[0],
//         jqxhr = $.ajax({
//             url: path,
//             type: 'GET',
//             timeout: 60000,
//             dataType: 'jsonp',
//             crossDomain: true,
//             contentType: 'text/plain'
//         });
//     jqxhr.always(function(data) {
//         console.log('Data: ' + data);
//         // console.log('Data Result: ' + data.result);
//         if (data.result) {
//             // success
//             _userInfo.authToken = token;
//             _userInfo.name = token.split(':')[0];
//             _userInfo.isChecked = true;
//             localStorage[authTokenKey] = token;
//             localStorage[checkedkey] = true;
//             console.log('login-succeed');
//             popup && popup.$rootScope &&
//                 popup.$rootScope.$broadcast('login-succeed');
//             _getTags();
//         } else {
//             // login error
//             console.log('login-failed1');
//             popup && popup.$rootScope &&
//                 popup.$rootScope.$broadcast('login-failed');
//         }
//     });
//     jqxhr.fail(function(data) {
//         if (data.statusText == 'timeout') {
//             console.log('login-failed2');
//             popup && popup.$rootScope &&
//                 popup.$rootScope.$broadcast('login-failed');
//         }
//     });
// };
//
// login('CF100DA71C020A2BC0DF');

// chrome.storage.sync.set({'value': theValue}, function() {
//           // Notify that we saved.
//           message('Settings saved');
//         });

// StorageArea.get(string or array of string or object keys, function callback)

// https://developer.chrome.com/extensions/storage
<|endoftext|>