<commit_before>'use strict';

const fs = require('fs-extra');
const inquirer = require('inquirer');
const run = require('./run');
const getProjectOptions = require('./get-project-options');
const getPackageName = require('./get-package-name');
const getPackageVersion = require('./get-package-version');
const getVersions = require('boilerplate-update/src/get-versions');
const getProjectVersion = require('./get-project-version');
const _getTagVersion = require('./get-tag-version');
const getRemoteUrl = require('./get-remote-url');
const boilerplateUpdate = require('boilerplate-update');
const getStartAndEndCommands = require('./get-start-and-end-commands');
const parseBlueprint = require('./parse-blueprint');
const downloadBlueprint = require('./download-blueprint');

module.exports = async function emberCliUpdate({
  blueprint,
  from,
  to,
  resolveConflicts,
  runCodemods,
  reset,
  compareOnly,
  statsOnly,
  listCodemods,
  createCustomDiff,
  wasRunAsExecutable
}) {
  let defaultBlueprint = {
    name: 'ember-cli'
  };

  let ignoredFiles = [];

  if (blueprint) {
    if (!from) {
      throw new Error('A custom blueprint cannot detect --from. You must supply it.');
    }

    blueprint = await parseBlueprint(blueprint);
    blueprint.version = from;
  } else {
    let emberCliUpdateJson;
    try {
      emberCliUpdateJson = await fs.readJson('ember-cli-update.json');
    } catch (err) {}

    let blueprints;
    if (emberCliUpdateJson) {
      ignoredFiles.push('ember-cli-update.json');

      blueprints = emberCliUpdateJson.blueprints;
    } else {
      blueprints = [];
    }

    let completeBlueprints = blueprints.filter(blueprint => !blueprint.isPartial);
    if (!completeBlueprints.length) {
      blueprints.splice(0, 0, defaultBlueprint);
    }

    if (blueprints.length > 1) {
      let answers = await inquirer.prompt([{
        type: 'list',
        message: 'Multiple blueprint updates have been found. Which would you like to update?',
        name: 'blueprint',
        choices: blueprints.map(blueprint => blueprint.name)
      }]);

      blueprint = blueprints.find(blueprint => blueprint.name === answers.blueprint);
    } else {
      blueprint = blueprints[0];
    }

    if (blueprint.location) {
      blueprint.url = (await parseBlueprint(blueprint.location)).url;
    }
  }

  let isCustomBlueprint = blueprint.name !== defaultBlueprint.name;

  if (isCustomBlueprint) {
    createCustomDiff = true;
  }

  let endVersion;

  let result = await (await boilerplateUpdate({
    projectOptions: ({ packageJson }) => getProjectOptions(packageJson, blueprint),
    mergeOptions: async function mergeOptions({
      packageJson,
      projectOptions
    }) {
      let startVersion;
      let startBlueprint;
      let endBlueprint;

      if (isCustomBlueprint) {
        startBlueprint = await downloadBlueprint(blueprint.name, blueprint.url, blueprint.version);
        endBlueprint = await downloadBlueprint(blueprint.name, blueprint.url, to);

        startVersion = startBlueprint.version;
        endVersion = endBlueprint.version;

        blueprint.name = startBlueprint.name;
      } else {
        let packageName = getPackageName(projectOptions);
        let packageVersion = getPackageVersion(packageJson, packageName);

        let versions = await getVersions(packageName);

        let getTagVersion = _getTagVersion(versions, packageName, blueprint.url);

        if (from) {
          startVersion = await getTagVersion(from);
        } else {
          startVersion = getProjectVersion(packageVersion, versions, projectOptions);
        }

        endVersion = await getTagVersion(to);

        startBlueprint = endBlueprint = blueprint;
      }

      let customDiffOptions;
      if (createCustomDiff) {
        customDiffOptions = getStartAndEndCommands({
          packageJson,
          projectOptions,
          startVersion,
          endVersion,
          startBlueprint,
          endBlueprint
        });
      }

      return {
        startVersion,
        endVersion,
        customDiffOptions
      };
    },
    remoteUrl: ({ projectOptions }) => getRemoteUrl(projectOptions),
    compareOnly,
    resolveConflicts,
    reset,
    statsOnly,
    listCodemods,
    runCodemods,
    codemodsUrl: 'https://raw.githubusercontent.com/ember-cli/ember-cli-update-codemods-manifest/v3/manifest.json',
    createCustomDiff,
    ignoredFiles,
    wasRunAsExecutable
  })).promise;

  if (isCustomBlueprint) {
    let emberCliUpdateJson;
    try {
      emberCliUpdateJson = await fs.readJson('ember-cli-update.json');
    } catch (err) {}

    if (emberCliUpdateJson) {
      let { blueprints } = emberCliUpdateJson;
      blueprint = blueprints.find(b => b.name === blueprint.name);

      if (blueprint.version !== endVersion) {
        blueprint.version = endVersion;
        await fs.writeJSON('ember-cli-update.json', emberCliUpdateJson, {
          spaces: 2,
          EOL: require('os').EOL
        });
        await run('git add ember-cli-update.json');
      }
    }
  }

  return result;
};
<commit_msg>remove unused param<commit_after>'use strict';

const fs = require('fs-extra');
const inquirer = require('inquirer');
const run = require('./run');
const getProjectOptions = require('./get-project-options');
const getPackageName = require('./get-package-name');
const getPackageVersion = require('./get-package-version');
const getVersions = require('boilerplate-update/src/get-versions');
const getProjectVersion = require('./get-project-version');
const _getTagVersion = require('./get-tag-version');
const getRemoteUrl = require('./get-remote-url');
const boilerplateUpdate = require('boilerplate-update');
const getStartAndEndCommands = require('./get-start-and-end-commands');
const parseBlueprint = require('./parse-blueprint');
const downloadBlueprint = require('./download-blueprint');

module.exports = async function emberCliUpdate({
  blueprint,
  from,
  to,
  resolveConflicts,
  runCodemods,
  reset,
  compareOnly,
  statsOnly,
  listCodemods,
  createCustomDiff,
  wasRunAsExecutable
}) {
  let defaultBlueprint = {
    name: 'ember-cli'
  };

  let ignoredFiles = [];

  if (blueprint) {
    if (!from) {
      throw new Error('A custom blueprint cannot detect --from. You must supply it.');
    }

    blueprint = await parseBlueprint(blueprint);
    blueprint.version = from;
  } else {
    let emberCliUpdateJson;
    try {
      emberCliUpdateJson = await fs.readJson('ember-cli-update.json');
    } catch (err) {}

    let blueprints;
    if (emberCliUpdateJson) {
      ignoredFiles.push('ember-cli-update.json');

      blueprints = emberCliUpdateJson.blueprints;
    } else {
      blueprints = [];
    }

    let completeBlueprints = blueprints.filter(blueprint => !blueprint.isPartial);
    if (!completeBlueprints.length) {
      blueprints.splice(0, 0, defaultBlueprint);
    }

    if (blueprints.length > 1) {
      let answers = await inquirer.prompt([{
        type: 'list',
        message: 'Multiple blueprint updates have been found. Which would you like to update?',
        name: 'blueprint',
        choices: blueprints.map(blueprint => blueprint.name)
      }]);

      blueprint = blueprints.find(blueprint => blueprint.name === answers.blueprint);
    } else {
      blueprint = blueprints[0];
    }

    if (blueprint.location) {
      blueprint.url = (await parseBlueprint(blueprint.location)).url;
    }
  }

  let isCustomBlueprint = blueprint.name !== defaultBlueprint.name;

  if (isCustomBlueprint) {
    createCustomDiff = true;
  }

  let endVersion;

  let result = await (await boilerplateUpdate({
    projectOptions: ({ packageJson }) => getProjectOptions(packageJson, blueprint),
    mergeOptions: async function mergeOptions({
      packageJson,
      projectOptions
    }) {
      let startVersion;
      let startBlueprint;
      let endBlueprint;

      if (isCustomBlueprint) {
        startBlueprint = await downloadBlueprint(blueprint.name, blueprint.url, blueprint.version);
        endBlueprint = await downloadBlueprint(blueprint.name, blueprint.url, to);

        startVersion = startBlueprint.version;
        endVersion = endBlueprint.version;

        blueprint.name = startBlueprint.name;
      } else {
        let packageName = getPackageName(projectOptions);
        let packageVersion = getPackageVersion(packageJson, packageName);

        let versions = await getVersions(packageName);

        let getTagVersion = _getTagVersion(versions, packageName);

        if (from) {
          startVersion = await getTagVersion(from);
        } else {
          startVersion = getProjectVersion(packageVersion, versions, projectOptions);
        }

        endVersion = await getTagVersion(to);

        startBlueprint = endBlueprint = blueprint;
      }

      let customDiffOptions;
      if (createCustomDiff) {
        customDiffOptions = getStartAndEndCommands({
          packageJson,
          projectOptions,
          startVersion,
          endVersion,
          startBlueprint,
          endBlueprint
        });
      }

      return {
        startVersion,
        endVersion,
        customDiffOptions
      };
    },
    remoteUrl: ({ projectOptions }) => getRemoteUrl(projectOptions),
    compareOnly,
    resolveConflicts,
    reset,
    statsOnly,
    listCodemods,
    runCodemods,
    codemodsUrl: 'https://raw.githubusercontent.com/ember-cli/ember-cli-update-codemods-manifest/v3/manifest.json',
    createCustomDiff,
    ignoredFiles,
    wasRunAsExecutable
  })).promise;

  if (isCustomBlueprint) {
    let emberCliUpdateJson;
    try {
      emberCliUpdateJson = await fs.readJson('ember-cli-update.json');
    } catch (err) {}

    if (emberCliUpdateJson) {
      let { blueprints } = emberCliUpdateJson;
      blueprint = blueprints.find(b => b.name === blueprint.name);

      if (blueprint.version !== endVersion) {
        blueprint.version = endVersion;
        await fs.writeJSON('ember-cli-update.json', emberCliUpdateJson, {
          spaces: 2,
          EOL: require('os').EOL
        });
        await run('git add ember-cli-update.json');
      }
    }
  }

  return result;
};
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const fs = require('fs');

const childProcess = require('child-process-promise');
const express = require('express');

const configPath = path.resolve(process.cwd(), process.argv.slice().pop());
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
const app = express();

async function build (target, args) {
    const commands = args.commands;
    const options = {
        cwd: args.path,
    };

    console.log(`Deploying ${ target }...`);

    for (let i = 0; i < commands.length; i++) {
        const date = (new Date()).toLocaleDateString('sv-SE', {
            hour: 'numeric',
            minute: 'numeric',
            second: 'numeric',
        });

        console.log(`${ date } Running ${ commands[i] }...`);
        await childProcess.exec(commands[i], options);
        console.log('Done');
    }
}

app.post('/', (req, res) => {
    const target = req.query.target;

    if (config.repos[target]) {
        if (req.get('x-github-event') && req.get('x-github-event') === 'push') {
            build(target, config.repos[target]);
            res.status(200).send();
        } else {
            res.status(401).send();
        }
    } else {
        res.status(400).send();
    }
});

app.listen(config.port, config.host);
<commit_msg>Add some basic handling of missing and/or invalid config files. Fixed #5<commit_after>'use strict';

const path = require('path');
const fs = require('fs');

const childProcess = require('child-process-promise');
const express = require('express');

const configPath = path.resolve(process.cwd(), process.argv.slice().pop());
const app = express();

let config = false;

async function build (args) {
    const commands = args.commands;
    const options = {
        cwd: args.path,
    };

    for (let i = 0; i < commands.length; i++) {
        const date = (new Date()).toLocaleDateString('sv-SE', {
            hour: 'numeric',
            minute: 'numeric',
            second: 'numeric',
        });

        console.log(`${ date } Running ${ commands[i] }...`);
        await childProcess.exec(commands[i], options);
        console.log('Done');
    }
}

app.post('/', (req, res) => {
    const target = req.query.target;

    if (config.repos[target]) {
        if(req.get('HTTP_X_GITHUB_EVENT') && req.get('HTTP_X_GITHUB_EVENT') === 'push'){
            build(config.repos[target]);
            res.status(200).send();
        } else {
            res.status(401).send();
        }
    } else {
        res.status(400).send();
    }
});

if(configPath.length < 1 || configPath === __filename ){
    console.error('Didnt\'t get a config file, are you sure you specified one?');
    process.exit(1);
}

fs.access(configPath, fs.R_OK, (err) => {
    if(err){
        console.error('Unable to read file "', configPath, '". Please make sure it exists and is readable.');
        process.exit(1);
    }

    try {
        config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
    } catch (err){
        console.error('Unable to parse config file "' + configPath + '". Please make sure it\'s valid.');
        process.exit(1);
    }

    if(config){
        app.listen(config.port, config.host);
    }
});
<|endoftext|>


<commit_before>/**
 * `chain` is the instance of npm squel module
 * `resource` includes the data to build the query
 */
var lme = require('lme');
var squel = require('squel').useFlavour('postgres');
var handles = require('./handles');

var key;

var sqlify = function (chain, resource) {
	// refrain from sins
	// sometimes if resource contains req.body, this is required to make clear object (as of now)
	resource = JSON.parse(JSON.stringify(resource));

	// iterate through each properties of `resource`
	for (key in resource) {
		if (!resource.hasOwnProperty(key)) {
			continue;
		}
		switch (key) {
		case 'fields':
			handles.field(chain, resource[key]);
			break;

		case 'where':
			handles.where(chain, resource[key]);
			break;

		case 'set':
			handles.set(chain, resource[key]);
			break;

		case 'join':
			handles.join(chain, resource[key]);
			break;

		case 'left_join':
			handles.left_join(chain, resource[key]);
			break;

		case 'right_join':
			handles.right_join(chain, resource[key]);
			break;

		case 'outer_join':
			handles.outer_join(chain, resource[key]);
			break;

		case 'cross_join':
			handles.cross_join(chain, resource[key]);
			break;

		case 'returning':
			handles.returning(chain, resource[key]);
			break;

		default:
			lme.e('method ' + key + ' is not implemented');
			break;
		}
	}
};

// expose squel and sqlify
module.exports = {
	squel: squel,
	sqlify: sqlify
};
<commit_msg>addressing issue 3 partially to see how node versions responds to it<commit_after>/**
 * `chain` is the instance of npm squel module
 * `resource` includes the data to build the query
 */
var lme = require('lme');
var squel = require('squel').useFlavour('postgres');
var handles = require('./handles');

var sqlify = function(chain, resource) {

    // iterate through each properties of `resource`
	Object.keys(resource).forEach(function(key) {
		switch (key) {
		case 'fields':
			handles.field(chain, resource[key]);
			break;

		case 'where':
			handles.where(chain, resource[key]);
			break;

		case 'set':
			handles.set(chain, resource[key]);
			break;

		case 'join':
			handles.join(chain, resource[key]);
			break;

		case 'left_join':
			handles.left_join(chain, resource[key]);
			break;

		case 'right_join':
			handles.right_join(chain, resource[key]);
			break;

		case 'outer_join':
			handles.outer_join(chain, resource[key]);
			break;

		case 'cross_join':
			handles.cross_join(chain, resource[key]);
			break;

		case 'returning':
			handles.returning(chain, resource[key]);
			break;

		default:
			lme.e('method ' + key + ' is not implemented');
			break;
		}
	});
};

// expose squel and sqlify
module.exports = {
	squel: squel,
	sqlify: sqlify
};
<|endoftext|>


<commit_before>import Portal from './components/portal.js'
import PortalTarget from './components/portal-target.js'
import Wormhole from './components/wormhole.js'

function install (Vue, opts = {}) {
  Vue.component(opts.portalName || 'portal', Portal)
  Vue.component(opts.portalTargetName || 'portal-target', PortalTarget)
}
if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use({ install: install })
}

export default {
  install,
  Portal,
  PortalTarget,
  Wormhole,
}
<commit_msg>use camelCase to register component<commit_after>import Portal from './components/portal.js'
import PortalTarget from './components/portal-target.js'
import Wormhole from './components/wormhole.js'

function install(Vue, opts = {}) {
  Vue.component(opts.portalName || 'portal', Portal)
  Vue.component(opts.portalTargetName || 'portalTarget', PortalTarget)
}
if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use({ install: install })
}

export default {
  install,
  Portal,
  PortalTarget,
  Wormhole,
}
<|endoftext|>


<commit_before>
const lambda = Object
  .getOwnPropertyNames(Array.prototype)
  .reduce((lambda, method) => {
    lambda[method] = (['concat', 'every', 'filter', 'find', 'findIndex', 'includes', 'join', 'map', 'reduce', 'reduceRight', 'slice', 'some'].includes(method))
         ? (fn, ...params) => (arr) => arr[method](fn, ...params)
         : (['sort', 'copyWithin', 'fill'].includes(method))
            ? (...params) => arr => [...arr][method](...params)
            : (['toLocaleString', 'indexOf', 'lastIndexOf'].includes(method))
              ? (...params) => arr => arr[method](...params)
              : (['push', 'splice'].includes(method))
                ? (...params) => arr => { var t = [...arr]; t[method](...params); return t }
                : (['toString', 'entries', 'keys'].includes(method))
                  ? arr => arr[method]()
                  : lambda[method];
    return lambda;
  }, {
    pop: arr => arr.slice(0, -1),
    shift: arr => arr.slice(1),
    unshift: params => arr => [params, ...arr],
    reverse: arr => [...arr].reverse(),
    compose: (...fns) => initialValue => fns.reduceRight((value, fn) => fn(value), initialValue),
    pipe: (...fns) => initialValue => fns.reduce((value, fn) => fn(value), initialValue)
  });

if (typeof window !== 'undefined') window.PicoLambda = lambda;
else module.exports = lambda;
<commit_msg>adjust for semistandard<commit_after>
const lambda = Object
  .getOwnPropertyNames(Array.prototype)
  .reduce((lambda, method) => {
    lambda[method] = (['concat', 'every', 'filter', 'find', 'findIndex', 'includes', 'join', 'map', 'reduce', 'reduceRight', 'slice', 'some'].includes(method))
         ? (fn, ...params) => (arr) => arr[method](fn, ...params)
         : (['sort', 'copyWithin', 'fill'].includes(method))
            ? (...params) => arr => [...arr][method](...params)
            : (['toLocaleString', 'indexOf', 'lastIndexOf'].includes(method))
              ? (...params) => arr => arr[method](...params)
              : (['push', 'splice'].includes(method))
                ? (...params) => arr => { var t = [...arr]; t[method](...params); return t; }
                : (['toString', 'entries', 'keys'].includes(method))
                  ? arr => arr[method]()
                  : lambda[method];
    return lambda;
  }, {
    pop: arr => arr.slice(0, -1),
    shift: arr => arr.slice(1),
    unshift: params => arr => [params, ...arr],
    reverse: arr => [...arr].reverse(),
    compose: (...fns) => initialValue => fns.reduceRight((value, fn) => fn(value), initialValue),
    pipe: (...fns) => initialValue => fns.reduce((value, fn) => fn(value), initialValue)
  });

if (typeof window !== 'undefined') window.PicoLambda = lambda;
else module.exports = lambda;
<|endoftext|>


<commit_before>import React from 'react';
import App from './components/App';
import {
  PIVOTAL_TOKEN,
  PIVOTAL_PROJECT_ID,
  GITHUB_TOKEN,
  GITHUB_USER
  GITHUB_REPO
} from './.env';

React.render(
  <App
    pivotalToken={PIVOTAL_TOKEN}
    pivotalProjectId={PIVOTAL_PROJECT_ID}
    gitHubToken={GITHUB_TOKEN}
    gitHubUser={GITHUB_USER}
    gitHubRepo={GITHUB_REPO} />,
  document.getElementById('root')
);
<commit_msg>[touchup] add missing comma<commit_after>import React from 'react';
import App from './components/App';
import {
  PIVOTAL_TOKEN,
  PIVOTAL_PROJECT_ID,
  GITHUB_TOKEN,
  GITHUB_USER,
  GITHUB_REPO
} from './.env';

React.render(
  <App
    pivotalToken={PIVOTAL_TOKEN}
    pivotalProjectId={PIVOTAL_PROJECT_ID}
    gitHubToken={GITHUB_TOKEN}
    gitHubUser={GITHUB_USER}
    gitHubRepo={GITHUB_REPO} />,
  document.getElementById('root')
);
<|endoftext|>


<commit_before>#!/usr/bin/env node

import inquirer from 'inquirer'
import yargs from 'yargs'

import Logger from './logger'
import {
  generateFiles,
  generateFilesFromTemplate,
  generateFilesFromCustom,
} from './files'
import {
  generateQuestions,
  getTemplatesList,
  getConfig,
  getTemplate,
} from './utils'

import { questions } from './questions'

const args = yargs.argv
const config = getConfig(args.config)

async function startTemplateGenerator() {
  try {
    const templatesDirPath = config ? config.templatesDirPath : null
    const templates = getTemplatesList(templatesDirPath)
    const templatesPath = await getTemplate(templates, args.template)

    const requiredAnswers = await inquirer.prompt([
      questions.name,
      questions.path,
    ])

    const results = {
      ...config,
      ...requiredAnswers,
      templatesPath,
    }

    generateFilesFromTemplate(results)
    Logger.log('Your component is created!')
  } catch (error) {
    Logger.error(error.message)
  }
}

/**
 * Start the process to generate component folder and files:
 * Filter question by config file
 * Get from the user the requirements to create the component folder and files
 * Generate files
 */
(async function start() {
  try {
    if (args.template) {
      return await startTemplateGenerator()
    }

    const { template } = await inquirer.prompt([
      {
        type: 'confirm',
        name: 'template',
        message: 'Do you wanna choose a template',
        default: false,
      },
    ])

    if (template) {
      return await startTemplateGenerator()
    }

    const filteredQuestions = generateQuestions(config, questions)
    const requirements = await inquirer.prompt(filteredQuestions)
    const results = {
      ...config,
      ...requirements,
    }

    if (results.type === 'custom') {
      await generateFilesFromCustom(results)
    } else {
      await generateFiles(results)
    }
    Logger.log('Your component is created!')
  } catch (e) {
    Logger.error(e.message)
  }
  return null
}())

export default { generateFiles, generateFilesFromCustom }
<commit_msg>Don't ask for path if it is set in config<commit_after>#!/usr/bin/env node

import inquirer from 'inquirer'
import yargs from 'yargs'

import Logger from './logger'
import {
  generateFiles,
  generateFilesFromTemplate,
  generateFilesFromCustom,
} from './files'
import {
  generateQuestions,
  getTemplatesList,
  getConfig,
  getTemplate,
} from './utils'

import { questions } from './questions'

const args = yargs.argv
const config = getConfig(args.config)

async function startTemplateGenerator() {
  try {
    const { path, templatesDirPath } = config
    const templates = getTemplatesList(templatesDirPath)
    const templatesPath = await getTemplate(templates, args.template)

    const requiredAnswers = await inquirer.prompt([
      questions.name,
      path ? undefined : questions.path,
    ].filter(question => question))

    const results = {
      ...config,
      ...requiredAnswers,
      templatesPath,
    }

    generateFilesFromTemplate(results)
    Logger.log('Your component is created!')
  } catch (error) {
    Logger.error(error.message)
  }
}

/**
 * Start the process to generate component folder and files:
 * Filter question by config file
 * Get from the user the requirements to create the component folder and files
 * Generate files
 */
(async function start() {
  try {
    if (args.template) {
      return await startTemplateGenerator()
    }

    const { template } = await inquirer.prompt([
      {
        type: 'confirm',
        name: 'template',
        message: 'Do you wanna choose a template',
        default: false,
      },
    ])

    if (template) {
      return await startTemplateGenerator()
    }

    const filteredQuestions = generateQuestions(config, questions)
    const requirements = await inquirer.prompt(filteredQuestions)
    const results = {
      ...config,
      ...requirements,
    }

    if (results.type === 'custom') {
      await generateFilesFromCustom(results)
    } else {
      await generateFiles(results)
    }
    Logger.log('Your component is created!')
  } catch (e) {
    Logger.error(e.message)
  }
  return null
}())

export default { generateFiles, generateFilesFromCustom }
<|endoftext|>


<commit_before>
/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
    el: '#app',
    mounted() {
        $('select.selectize').selectize({ maxItems: 3 });
        $('textarea.wysiwyg').markdown({ iconlibrary: 'fa' });
    }
});
<commit_msg>Disable Vue.js<commit_after>
/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

$('select.selectize').selectize({ maxItems: 3 });
$('textarea.wysiwyg').markdown({ iconlibrary: 'fa' });

// const app = new Vue({
//     el: '#app'
// });
<|endoftext|>


<commit_before>import Vue          from 'vue'
import VueRouter    from 'vue-router'
import              '../vue/directives/PathValidator';

// state
import store        from './state/store'
import config       from './functions/config'
config();

// components
import Home         from '../vue/pages/Home.vue'
import Help         from '../vue/pages/Help.vue'
import Favourites   from '../vue/pages/Favourites.vue'
import Search       from '../vue/pages/Search.vue'
import Settings     from '../vue/settings/Settings.vue'
import Console      from '../vue/console/Wrapper.vue'

import App          from '../vue/App.vue'

window.store = store

Vue.use(VueRouter);
window.router = new VueRouter({
	root: $('meta[name="route"]').attr('content'),
	history: true,
	saveScrollPosition: true
});

const routes = {
	// '/': {redirect: '/parent'},
	'/': {
		component: Home
	},
	'/run/*route': {
		component: Console,
		canReuse:false
	},
	'/favourites' : {
		component: Favourites
	},
	'/settings' : {
		component: Settings
	},
	'/search' : {
		component: Search
	},
	'/help': {
		component: Help
	},
	'*' : {
		component: Home
	}
};

router.map(routes);

router.start(App, '#app');
<commit_msg>Fixed #17 - page title now updates for all sections<commit_after>import Vue          from 'vue'
import VueRouter    from 'vue-router'
import              '../vue/directives/PathValidator';

// state
import store        from './state/store'
import config       from './functions/config'
config();

// components
import Home         from '../vue/pages/Home.vue'
import Help         from '../vue/pages/Help.vue'
import Favourites   from '../vue/pages/Favourites.vue'
import Search       from '../vue/pages/Search.vue'
import Settings     from '../vue/settings/Settings.vue'
import Console      from '../vue/console/Wrapper.vue'

import App          from '../vue/App.vue'

window.store = store

Vue.use(VueRouter);
window.router = new VueRouter({
	root: $('meta[name="route"]').attr('content'),
	history: true,
	saveScrollPosition: true
});

const routes = {
	// '/': {redirect: '/parent'},
	'/': {
		component: Home
	},
	'/run/*route': {
		component: Console,
		canReuse:false
	},
	'/favourites' : {
		component: Favourites
	},
	'/settings' : {
		component: Settings
	},
	'/search' : {
		component: Search
	},
	'/help': {
		component: Help
	},
	'*' : {
		component: Home
	}
};

router.map(routes);

router.afterEach(function (transition) {
	if (transition.to.path.indexOf('/run') !== 0)
	{
		document.title = 'Sketchpad - ' + transition.to.matched[0].handler.component.name.toLowerCase();
	}
})

router.start(App, '#app');
<|endoftext|>


<commit_before>/* eslint-disable no-console */
import _ from 'lodash';
import { Observable } from 'rxjs';
import formatter from './formatter';
import createExample from './example-observable';

_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
export const specStream = (specDescription, specCreator) => {
    const examples = [];
    specCreator((description, specification) => {
        const example = specification(createExample(description));
        examples.push(example);
    });

    return Observable.merge(...examples)
        .scan((all, current) => {
            const stepNumber = all.step ? all.step + 1 : 0;
            return {
                step: stepNumber,
                results: _.extend(all.results, {
                    [current.description]: current,
                }),
            };
        }, {});
};

export default (specDescription, specCreator) => {
    specStream(specDescription, specCreator)
        .subscribe(formatter(specDescription));
};
<commit_msg>Properly increment the step number.<commit_after>/* eslint-disable no-console */
import _ from 'lodash';
import { Observable } from 'rxjs';
import formatter from './formatter';
import createExample from './example-observable';

_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
export const specStream = (specDescription, specCreator) => {
    const examples = [];
    specCreator((description, specification) => {
        const example = specification(createExample(description));
        examples.push(example);
    });

    return Observable.merge(...examples)
        .scan((all, current) => ({
            step: all.step !== undefined ? all.step + 1 : 0,
            results: _.extend(all.results, {
                [current.description]: current,
            }),
        }), {});
};

export default (specDescription, specCreator) => {
    specStream(specDescription, specCreator)
        .subscribe(formatter(specDescription));
};
<|endoftext|>


<commit_before>module.exports = {
  detectVulnerabilityAlerts,
};

async function detectVulnerabilityAlerts(input) {
  if (!(input && input.vulnerabilityAlerts)) {
    return input;
  }
  if (input.vulnerabilityAlerts.enabled === false) {
    logger.debug('Vulnerability alerts are disabled');
    return input;
  }
  const alerts = await platform.getVulnerabilityAlerts();
  if (!alerts.length) {
    logger.debug('No vulnerability alerts found');
    if (input.vulnerabilityAlertsOnly) {
      throw new Error('no-vulnerability-alerts');
    }
    return input;
  }
  const config = { ...input };
  const alertPackageRules = alerts
    .map(alert => {
      if (!alert.fixedIn) {
        logger.warn({ alert }, 'Vulnerability alert has no fixedIn version');
        return null;
      }
      const rule = {};
      rule.packageNames = [alert.packageName];
      // Raise only for where the currentVersion is vulnerable
      rule.matchCurrentVersion = `< ${alert.fixedIn}`;
      // Don't propose upgrades to any versions that are still vulnerable
      rule.allowedVersions = `>= ${alert.fixedIn}`;
      rule.force = {
        ...config.vulnerabilityAlerts,
        vulnerabilityAlert: true,
      };
      return rule;
    })
    .filter(Boolean);
  config.packageRules = (config.packageRules || []).concat(alertPackageRules);
  return config;
}
<commit_msg>refactor: info not warn when no fixedIn alert<commit_after>module.exports = {
  detectVulnerabilityAlerts,
};

async function detectVulnerabilityAlerts(input) {
  if (!(input && input.vulnerabilityAlerts)) {
    return input;
  }
  if (input.vulnerabilityAlerts.enabled === false) {
    logger.debug('Vulnerability alerts are disabled');
    return input;
  }
  const alerts = await platform.getVulnerabilityAlerts();
  if (!alerts.length) {
    logger.debug('No vulnerability alerts found');
    if (input.vulnerabilityAlertsOnly) {
      throw new Error('no-vulnerability-alerts');
    }
    return input;
  }
  const config = { ...input };
  const alertPackageRules = alerts
    .map(alert => {
      if (!alert.fixedIn) {
        logger.info({ alert }, 'Vulnerability alert has no fixedIn version');
        return null;
      }
      const rule = {};
      rule.packageNames = [alert.packageName];
      // Raise only for where the currentVersion is vulnerable
      rule.matchCurrentVersion = `< ${alert.fixedIn}`;
      // Don't propose upgrades to any versions that are still vulnerable
      rule.allowedVersions = `>= ${alert.fixedIn}`;
      rule.force = {
        ...config.vulnerabilityAlerts,
        vulnerabilityAlert: true,
      };
      return rule;
    })
    .filter(Boolean);
  config.packageRules = (config.packageRules || []).concat(alertPackageRules);
  return config;
}
<|endoftext|>


<commit_before>/**
 * First we will load all of this project's JavaScript dependencies which
 * include Vue and Vue Resource. This gives a great starting point for
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the body of the page. From here, you may begin adding components to
 * the application, or feel free to tweak this setup for your needs.
 */

import Vue from "vue";

import VueRouter from "vue-router";
Vue.use(VueRouter);

import VueBus from 'vue-bus';
Vue.use(VueBus);

import ElementUI from "element-ui";
import "element-ui/lib/theme-default/index.css";
Vue.use(ElementUI);

import axios from "axios";

import VueCookie from "vue-cookie";
Vue.use(VueCookie);

import VueHtml5Editor from 'vue-html5-editor'
let options = {};
Vue.use(VueHtml5Editor, options);

import navbar from "./components/navbar";
Vue.component("navbar", navbar);
import ojfooter from './components/footer';
Vue.component("ojfooter", ojfooter);

Vue.prototype.$http = axios;

const BASE_URL = 'http://neo.dev/';
axios.defaults.baseURL = BASE_URL;
axios.defaults.headers.common['Accept'] = 'application/json';
axios.interceptors.response.use(function (response) {
    if (response.status !== 200) {
        if (response.status == 401) {
            window.location.href = BASE_URL;
        }
        Vue.$message.error(response.statusText);
    }
    return response;
}, function (error) {
    console.log(error);
});

import routes from './routes';

const router = new VueRouter({
    // mode: 'history',
    hashbang: true,
    saveScrollPosition: true,
    transitionOnLoad: true,
    scrollBehavior (to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return {x: 0, y: 0}
        }
    },
    routes: routes
});

const app = new Vue({
    router: router
}).$mount("#app");
<commit_msg>fix(auth): if meet 401, will redirect to homepage
<commit_after>/**
 * First we will load all of this project's JavaScript dependencies which
 * include Vue and Vue Resource. This gives a great starting point for
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the body of the page. From here, you may begin adding components to
 * the application, or feel free to tweak this setup for your needs.
 */

import Vue from "vue";

import VueRouter from "vue-router";
Vue.use(VueRouter);

import VueBus from 'vue-bus';
Vue.use(VueBus);

import ElementUI from "element-ui";
import "element-ui/lib/theme-default/index.css";
Vue.use(ElementUI);

import axios from "axios";

import VueCookie from "vue-cookie";
Vue.use(VueCookie);

import VueHtml5Editor from 'vue-html5-editor'
let options = {};
Vue.use(VueHtml5Editor, options);

import navbar from "./components/navbar";
Vue.component("navbar", navbar);
import ojfooter from './components/footer';
Vue.component("ojfooter", ojfooter);

Vue.prototype.$http = axios;

const BASE_URL = 'http://neo.dev/';
axios.defaults.baseURL = BASE_URL;
axios.defaults.headers.common['Accept'] = 'application/json';

axios.interceptors.response.use(function (response) {
    return response;
}, function (error) {
    if (error.response.status == 401) {
        return window.location.href = BASE_URL;
    }
    Vue.$message.error(response.statusText);
});

import routes from './routes';

const router = new VueRouter({
    // mode: 'history',
    hashbang: true,
    saveScrollPosition: true,
    transitionOnLoad: true,
    scrollBehavior (to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return {x: 0, y: 0}
        }
    },
    routes: routes
});

const app = new Vue({
    router: router
}).$mount("#app");
<|endoftext|>


<commit_before>window.jQuery = window.$ = $ = require('jquery');
window.Vue = require('vue');
window.perfectScrollbar = require('perfect-scrollbar/jquery')($);
window.Cropper = require('cropperjs');
window.Cropper = 'default' in window.Cropper ? window.Cropper['default'] : window.Cropper;
window.toastr = require('toastr');
window.DataTable = require('datatables');
require('datatables-bootstrap3-plugin/media/js/datatables-bootstrap3');
window.SimpleMDE = require('simplemde');
require('dropzone');
require('jquery-match-height');
require('bootstrap-toggle');
require('nestable2');
require('bootstrap');
require('bootstrap-switch');
require('select2');
require('eonasdan-bootstrap-datetimepicker/src/js/bootstrap-datetimepicker');
var brace = require('brace');
require('brace/mode/json');
require('brace/theme/github');
require('./slugify');
window.TinyMCE = window.tinymce = require('tinymce');
require('./multilingual');
require('./voyager_tinymce');
require('./voyager_ace_editor');
window.helpers = require('./helpers.js');

$(document).ready(function () {

    var appContainer = $(".app-container"),
        fadedOverlay = $('.fadetoblack'),
        hamburger = $('.hamburger');

    $('.side-menu').perfectScrollbar();

    $('#voyager-loader').fadeOut();

    $(".hamburger, .navbar-expand-toggle").on('click', function () {
        appContainer.toggleClass("expanded");
        $(this).toggleClass('is-active');
        if ($(this).hasClass('is-active')) {
            window.localStorage.setItem('voyager.stickySidebar', true);
        } else {
            window.localStorage.setItem('voyager.stickySidebar', false);
        }
    });

    $('select.select2').select2({width: '100%'});
    $('select.select2-ajax').each(function() {
        $(this).select2({
            width: '100%',
            ajax: {
                url: $(this).data('get-items-route'),
                data: function (params) {
                    var query = {
                        search: params.term,
                        type: $(this).data('get-items-field'),
                        page: params.page || 1
                    }
                    return query;
                }
            }
        });

        $(this).on('select2:select',function(e){
            var data = e.params.data;
            $(e.currentTarget).find("option[value='" + data.id + "']").attr('selected','selected');;
        });

        $(this).on('select2:unselect',function(e){
            var data = e.params.data;
            $(e.currentTarget).find("option[value='" + data.id + "']").attr('selected',false);;
        });
    });
    $('select.select2-taggable').select2({
        width: '100%',
        tags: true,
        createTag: function(params) {
            var term = $.trim(params.term);

            if (term === '') {
                return null;
            }

            return {
                id: term,
                text: term,
                newTag: true
            }
        }
    }).on('select2:selecting', function(e) {
        var $el = $(this);
        var route = $el.data('route');
        var label = $el.data('label');
        var errorMessage = $el.data('error-message');
        var newTag = e.params.args.data.newTag;

        if (!newTag) return;

        $el.select2('close');

        $.post(route, {
            [label]: e.params.args.data.text,
        }).done(function(data) {
            var newOption = new Option(e.params.args.data.text, data.data.id, false, true);
            $el.append(newOption).trigger('change');
        }).fail(function(error) {
            toastr.error(errorMessage);
        });

        return false;
    });

    $('.match-height').matchHeight();

    $('.datatable').DataTable({
        "dom": '<"top"fl<"clear">>rt<"bottom"ip<"clear">>'
    });

    $(".side-menu .nav .dropdown").on('show.bs.collapse', function () {
        return $(".side-menu .nav .dropdown .collapse").collapse('hide');
    });

    $('.panel-collapse').on('hide.bs.collapse', function(e) {
        var target = $(event.target);
        if (!target.is('a')) {
            target = target.parent();
        }
        if (!target.hasClass('collapsed')) {
            return;
        }
        e.stopPropagation();
        e.preventDefault();
    });

    $(document).on('click', '.panel-heading a.panel-action[data-toggle="panel-collapse"]', function (e) {
        e.preventDefault();
        var $this = $(this);

        // Toggle Collapse
        if (!$this.hasClass('panel-collapsed')) {
            $this.parents('.panel').find('.panel-body').slideUp();
            $this.addClass('panel-collapsed');
            $this.removeClass('voyager-angle-up').addClass('voyager-angle-down');
        } else {
            $this.parents('.panel').find('.panel-body').slideDown();
            $this.removeClass('panel-collapsed');
            $this.removeClass('voyager-angle-down').addClass('voyager-angle-up');
        }
    });

    //Toggle fullscreen
    $(document).on('click', '.panel-heading a.panel-action[data-toggle="panel-fullscreen"]', function (e) {
        e.preventDefault();
        var $this = $(this);
        if (!$this.hasClass('voyager-resize-full')) {
            $this.removeClass('voyager-resize-small').addClass('voyager-resize-full');
        } else {
            $this.removeClass('voyager-resize-full').addClass('voyager-resize-small');
        }
        $this.closest('.panel').toggleClass('is-fullscreen');
    });

    $('.datepicker').datetimepicker();

    // Save shortcut
    $(document).keydown(function (e) {
        if ((e.metaKey || e.ctrlKey) && e.keyCode == 83) { /*ctrl+s or command+s*/
            $(".btn.save").click();
            e.preventDefault();
            return false;
        }
    });

    /********** MARKDOWN EDITOR **********/

    $('textarea.simplemde').each(function () {
        var simplemde = new SimpleMDE({
            element: this,
        });
        simplemde.render();
    });

    /********** END MARKDOWN EDITOR **********/

});
<commit_msg>Menu doesnt collapse (#3992)<commit_after>window.jQuery = window.$ = $ = require('jquery');
window.Vue = require('vue');
window.perfectScrollbar = require('perfect-scrollbar/jquery')($);
window.Cropper = require('cropperjs');
window.Cropper = 'default' in window.Cropper ? window.Cropper['default'] : window.Cropper;
window.toastr = require('toastr');
window.DataTable = require('datatables');
require('datatables-bootstrap3-plugin/media/js/datatables-bootstrap3');
window.SimpleMDE = require('simplemde');
require('dropzone');
require('jquery-match-height');
require('bootstrap-toggle');
require('nestable2');
require('bootstrap');
require('bootstrap-switch');
require('select2');
require('eonasdan-bootstrap-datetimepicker/src/js/bootstrap-datetimepicker');
var brace = require('brace');
require('brace/mode/json');
require('brace/theme/github');
require('./slugify');
window.TinyMCE = window.tinymce = require('tinymce');
require('./multilingual');
require('./voyager_tinymce');
require('./voyager_ace_editor');
window.helpers = require('./helpers.js');

$(document).ready(function () {

    var appContainer = $(".app-container"),
        fadedOverlay = $('.fadetoblack'),
        hamburger = $('.hamburger');

    $('.side-menu').perfectScrollbar();

    $('#voyager-loader').fadeOut();

    $(".hamburger, .navbar-expand-toggle").on('click', function () {
        appContainer.toggleClass("expanded");
        $(this).toggleClass('is-active');
        if ($(this).hasClass('is-active')) {
            window.localStorage.setItem('voyager.stickySidebar', true);
        } else {
            window.localStorage.setItem('voyager.stickySidebar', false);
        }
    });

    $('select.select2').select2({width: '100%'});
    $('select.select2-ajax').each(function() {
        $(this).select2({
            width: '100%',
            ajax: {
                url: $(this).data('get-items-route'),
                data: function (params) {
                    var query = {
                        search: params.term,
                        type: $(this).data('get-items-field'),
                        page: params.page || 1
                    }
                    return query;
                }
            }
        });

        $(this).on('select2:select',function(e){
            var data = e.params.data;
            $(e.currentTarget).find("option[value='" + data.id + "']").attr('selected','selected');;
        });

        $(this).on('select2:unselect',function(e){
            var data = e.params.data;
            $(e.currentTarget).find("option[value='" + data.id + "']").attr('selected',false);;
        });
    });
    $('select.select2-taggable').select2({
        width: '100%',
        tags: true,
        createTag: function(params) {
            var term = $.trim(params.term);

            if (term === '') {
                return null;
            }

            return {
                id: term,
                text: term,
                newTag: true
            }
        }
    }).on('select2:selecting', function(e) {
        var $el = $(this);
        var route = $el.data('route');
        var label = $el.data('label');
        var errorMessage = $el.data('error-message');
        var newTag = e.params.args.data.newTag;

        if (!newTag) return;

        $el.select2('close');

        $.post(route, {
            [label]: e.params.args.data.text,
        }).done(function(data) {
            var newOption = new Option(e.params.args.data.text, data.data.id, false, true);
            $el.append(newOption).trigger('change');
        }).fail(function(error) {
            toastr.error(errorMessage);
        });

        return false;
    });

    $('.match-height').matchHeight();

    $('.datatable').DataTable({
        "dom": '<"top"fl<"clear">>rt<"bottom"ip<"clear">>'
    });

    $(".side-menu .nav .dropdown").on('show.bs.collapse', function () {
        return $(".side-menu .nav .dropdown .collapse").collapse('hide');
    });

    $('.panel-collapse').on('hide.bs.collapse', function(e) {
        var target = $(e.target);
        if (!target.is('a')) {
            target = target.parent();
        }
        if (!target.hasClass('collapsed')) {
            return;
        }
        e.stopPropagation();
        e.preventDefault();
    });

    $(document).on('click', '.panel-heading a.panel-action[data-toggle="panel-collapse"]', function (e) {
        e.preventDefault();
        var $this = $(this);

        // Toggle Collapse
        if (!$this.hasClass('panel-collapsed')) {
            $this.parents('.panel').find('.panel-body').slideUp();
            $this.addClass('panel-collapsed');
            $this.removeClass('voyager-angle-up').addClass('voyager-angle-down');
        } else {
            $this.parents('.panel').find('.panel-body').slideDown();
            $this.removeClass('panel-collapsed');
            $this.removeClass('voyager-angle-down').addClass('voyager-angle-up');
        }
    });

    //Toggle fullscreen
    $(document).on('click', '.panel-heading a.panel-action[data-toggle="panel-fullscreen"]', function (e) {
        e.preventDefault();
        var $this = $(this);
        if (!$this.hasClass('voyager-resize-full')) {
            $this.removeClass('voyager-resize-small').addClass('voyager-resize-full');
        } else {
            $this.removeClass('voyager-resize-full').addClass('voyager-resize-small');
        }
        $this.closest('.panel').toggleClass('is-fullscreen');
    });

    $('.datepicker').datetimepicker();

    // Save shortcut
    $(document).keydown(function (e) {
        if ((e.metaKey || e.ctrlKey) && e.keyCode == 83) { /*ctrl+s or command+s*/
            $(".btn.save").click();
            e.preventDefault();
            return false;
        }
    });

    /********** MARKDOWN EDITOR **********/

    $('textarea.simplemde').each(function () {
        var simplemde = new SimpleMDE({
            element: this,
        });
        simplemde.render();
    });

    /********** END MARKDOWN EDITOR **********/

});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import csjs from 'csjs';
import insertStyle, { removeStyle, getStyle } from './insert-style';

const cache = new Map();

export default function withStyles(css) {
  return DecoratedComponent =>
    class WithStyleDecorator extends Component {
      static displayName = `csjs(${DecoratedComponent.displayName
                            || DecoratedComponent.name || 'Component'})`

      componentWillMount() {
        let refs = cache.get(DecoratedComponent);
        if (!refs) {
          this.elm = insertStyle(csjs.getCss(css));
          cache.set(DecoratedComponent, { style: this.elm, count: 1 });
        } else {
          this.elm = refs.style;
          refs.count++;
        }
      }

      componentWillUpdate() {
        if (process.env.NODE_ENV !== 'production') {
            // Support React Hot Loader
          const cssText = csjs.getCss(css);
          if (getStyle(this.elm) !== cssText) {
            this.elm = insertStyle(cssText, { element: this.elm });
          }
        }
      }

      componentWillUnmount() {
        let refs = cache.get(DecoratedComponent);
        if (--refs.count === 0) {
            cache.delete(DecoratedComponent)
            removeStyle(this.elm);
            this.elm = null;
        }
      }

      render() {
        return <DecoratedComponent classes={css} {...this.props} />;
      }
    };
}
<commit_msg>de-lint<commit_after>import React, { Component } from 'react';
import csjs from 'csjs';
import insertStyle, { removeStyle, getStyle } from './insert-style';

const cache = new Map();

export default function withStyles(css) {
  return DecoratedComponent =>
    class WithStyleDecorator extends Component {
      static displayName = `csjs(${DecoratedComponent.displayName
                            || DecoratedComponent.name || 'Component'})`

      componentWillMount() {
        const refs = cache.get(DecoratedComponent);
        if (!refs) {
          this.elm = insertStyle(csjs.getCss(css));
          cache.set(DecoratedComponent, { style: this.elm, count: 1 });
        } else {
          this.elm = refs.style;
          refs.count++;
        }
      }

      componentWillUpdate() {
        if (process.env.NODE_ENV !== 'production') {
            // Support React Hot Loader
          const cssText = csjs.getCss(css);
          if (getStyle(this.elm) !== cssText) {
            this.elm = insertStyle(cssText, { element: this.elm });
          }
        }
      }

      componentWillUnmount() {
        const refs = cache.get(DecoratedComponent);
        if (--refs.count === 0) {
          cache.delete(DecoratedComponent);
          removeStyle(this.elm);
          this.elm = null;
        }
      }

      render() {
        return <DecoratedComponent classes={css} {...this.props} />;
      }
    };
}
<|endoftext|>


<commit_before>import { h, Component } from 'preact';
import Portal from 'preact-portal';
import register from './register';
import css from './style';

const ModalWrapper = css`
.modal-background {
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.4);

  & .modal {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 80%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    animation-name: animatetop;
    animation-duration: 0.4s
  }

  & .close {
    position: relative;
    right: 5px;
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;

    &:hover, &:focus {
      color: #000;
      text-decoration: none;
      cursor: pointer;
    }
  }
}

@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}
`;

export class Modal extends Component {
  onClose() {
    this.close()
    this.dispatchEvent(new Event('close'));
  }
  stop(e) {
    e.stopPropagation();
  }
  render ({ open, children }) {
    return open && open != 'false' ? (
      <Portal into="body">
        <ModalWrapper>

              ×
              {children}

        </ModalWrapper>
      </Portal>
    ) : null;
  }
}

function setupModal() {
  this.close = () => {
    this.removeAttribute('open');
  };
  this.open = () => {
    this.setAttribute('open', '');
  };

  this._vdomComponent.prototype.dispatchEvent = this.dispatchEvent.bind(this);
  this._vdomComponent.prototype.close = this.close;
}

register(Modal, 'x-domo-modal', setupModal);

const TitleWrapper = css`
.modal-title {
  padding: 2px 16px;
  background-color: #5cb85c;
  color: white;
}
`;
export const ModalTitle = ({ children }) => (
  <TitleWrapper>

      {children}

  </TitleWrapper>
);

register(ModalTitle, 'x-domo-modal-title');

const BodyWrapper = css`
.modal-body {
  padding: 2px 16px;
}
`;
export const ModalBody = ({ children }) => (
  <BodyWrapper>

{children}

  </BodyWrapper>
);

register(ModalBody, 'x-domo-modal-body');

const FooterWrapper = css`
.modal-footer {
  padding: 2px 16px;
  background-color: #5cb85c;
  color: white;
}
`;
export const ModalFooter = ({ children }) => (
  <FooterWrapper>

{children}

  </FooterWrapper>
);

register(ModalFooter, 'x-domo-modal-footer');
<commit_msg>fix lint<commit_after>import { h, Component } from 'preact';
import Portal from 'preact-portal';
import register from './register';
import css from './style';

const ModalWrapper = css`
.modal-background {
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.4);

  & .modal {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 80%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    animation-name: animatetop;
    animation-duration: 0.4s
  }

  & .close {
    position: relative;
    right: 5px;
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;

    &:hover, &:focus {
      color: #000;
      text-decoration: none;
      cursor: pointer;
    }
  }
}

@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}
`;

export class Modal extends Component {
  onClose() {
    this.close();
    this.dispatchEvent(new Event('close'));
  }
  stop(e) {
    e.stopPropagation();
  }
  render ({ open, children }) {
    return open && open != 'false' ? (
      <Portal into="body">
        <ModalWrapper>

              ×
              {children}

        </ModalWrapper>
      </Portal>
    ) : null;
  }
}

function setupModal() {
  this.close = () => {
    this.removeAttribute('open');
  };
  this.open = () => {
    this.setAttribute('open', '');
  };

  this._vdomComponent.prototype.dispatchEvent = this.dispatchEvent.bind(this);
  this._vdomComponent.prototype.close = this.close;
}

register(Modal, 'x-domo-modal', setupModal);

const TitleWrapper = css`
.modal-title {
  padding: 2px 16px;
  background-color: #5cb85c;
  color: white;
}
`;
export const ModalTitle = ({ children }) => (
  <TitleWrapper>

      {children}

  </TitleWrapper>
);

register(ModalTitle, 'x-domo-modal-title');

const BodyWrapper = css`
.modal-body {
  padding: 2px 16px;
}
`;
export const ModalBody = ({ children }) => (
  <BodyWrapper>

{children}

  </BodyWrapper>
);

register(ModalBody, 'x-domo-modal-body');

const FooterWrapper = css`
.modal-footer {
  padding: 2px 16px;
  background-color: #5cb85c;
  color: white;
}
`;
export const ModalFooter = ({ children }) => (
  <FooterWrapper>

{children}

  </FooterWrapper>
);

register(ModalFooter, 'x-domo-modal-footer');
<|endoftext|>


<commit_before><commit_msg>notes<commit_after>// remove fields or add datepicker (mm/dd/yyyy) - jquery UI
// monthly tracking hide categories link
// delete button on right side of category field (removes row)
// reset button on monthly tracker, with are you sure dialog
// stage for george
<|endoftext|>


<commit_before>import parser from 'posthtml-parser';
import render from 'posthtml-render';
import {walk} from 'posthtml/lib/api';
import rules from './rules.js';
import attrs from './attrs.js';
import tags from './tags.js';
import deepmerge from 'deepmerge';
import {js} from 'js-beautify';

const optionsDefault = {
  rules,
  attrs,
  tags,
  sync: false,
  commentFormat: true,
  mini: {
    removeAttribute: false
  },
  jsBeautifyOptions: {
    indent_size: 2, // eslint-disable-line camelcase
    jslint_happy: true // eslint-disable-line camelcase
  }
};

const COMMENT_START_REG = /^<!--/g;
const COMMENT_END_REG = /-->$/g;

const nodeHasContent = (node, callback) => {
  if (
    typeof node === 'object' &&
    Object.prototype.hasOwnProperty.call(node, 'content')
  ) {
    node.content = callback(node.content);
  }
};

const nodeHasAttrs = (node, callback) => {
  if (
    typeof node === 'object' &&
    Object.prototype.hasOwnProperty.call(node, 'attrs')
  ) {
    node.attrs = Object.keys(node.attrs).reduce(callback, {});
  }
};

const getIndent = (level, {indent, eol}) => {
  const indentString = typeof indent === 'number' ? ' '.repeat(indent) : '\t';

  return `${eol}${indentString.repeat(level)}`;
};

const clean = tree =>
  parser(render(tree))
    .filter(node => {
      return (
        typeof node === 'object' ||
        (typeof node === 'string' &&
          (node.trim().length !== 0 || /doctype/gi.test(node)))
      );
    })
    .map(node => {
      if (Object.prototype.hasOwnProperty.call(node, 'content')) {
        node.content = clean(node.content);
      }

      return typeof node === 'string' ? node.trim() : node;
    });

const parseConditional = tree => {
  return tree.map(node => {
    nodeHasContent(node, parseConditional);

    if (typeof node === 'string' && /<!(?:--)?\[[\S\s]*?]>/.test(node)) {
      const conditional = /^((?:<[^>]+>)?<!(?:--)?\[[\S\s]*?]>(?:<!)?(?:-->)?)([\S\s]*?)(<!(?:--<!)?\[[\S\s]*?](?:--)?>)$/
        .exec(node)
        .slice(1)
        .map((node, index) =>
          index === 1 ?
            {tag: 'conditional-content', content: clean(parser(node))} :
            node
        );

      return {
        tag: 'conditional',
        content: conditional
      };
    }

    return node;
  });
};

const renderConditional = tree => {
  return tree.reduce((previousValue, node) => {
    if (
      typeof node === 'object' &&
      Object.prototype.hasOwnProperty.call(node, 'content')
    ) {
      node.content = renderConditional(node.content);
    }

    if (typeof node === 'object' && node.tag === 'conditional') {
      return [...previousValue, ...node.content];
    }

    if (typeof node === 'object' && node.tag === 'conditional-content') {
      node.tag = false;
      return [...previousValue, node];
    }

    return [...previousValue, node];
  }, []);
};

const indent = (tree, {rules: {indent, eol, blankLines, maxlen}}) => {
  const setIndent = (tree, level = 0) =>
    tree.reduce((previousValue, node, index) => {
      if (
        typeof node === 'object' &&
        Object.prototype.hasOwnProperty.call(node, 'content')
      ) {
        node.content = setIndent(node.content, ++level);
        --level;
      }

      if (tree.length === 1 && typeof tree[index] === 'string') {
        if (tree[index].length >= maxlen) {
          return [
            ...previousValue,
            getIndent(level, {indent, eol}),
            node,
            getIndent(--level, {indent, eol})
          ];
        }

        return [...previousValue, node];
      }

      if (level === 0 && tree.length - 1 === index && tree.length > 1) {
        return [...previousValue, getIndent(level, {indent, eol}), node];
      }

      if (level === 0 && tree.length - 1 === index && tree.length === 1) {
        return [...previousValue, node];
      }

      if (level === 0 && index === 0) {
        return [...previousValue, node, blankLines];
      }

      if (level === 0) {
        return [
          ...previousValue,
          getIndent(level, {indent, eol}),
          node,
          blankLines
        ];
      }

      if (tree.length - 1 === index) {
        return [
          ...previousValue,
          getIndent(level, {indent, eol}),
          node,
          getIndent(--level, {indent, eol})
        ];
      }

      if (typeof node === 'string' && /<!(?:--)?\[endif]*?]>/.test(node)) {
        return [
          ...previousValue,
          getIndent(level, {indent, eol}),
          node,
          blankLines
        ];
      }

      if (typeof node === 'string' && /<!(?:--)?\[[\S\s]*?]>/.test(node)) {
        return [...previousValue, getIndent(level, {indent, eol}), node];
      }

      if (node.tag === false) {
        return [...previousValue, ...node.content.slice(0, -1)];
      }

      return [
        ...previousValue,
        getIndent(level, {indent, eol}),
        node,
        blankLines
      ];
    }, []);

  return setIndent(tree);
};

const attributesBoolean = (tree, {attrs: {boolean}}) => {
  const removeAttributeValue = tree =>
    tree.map(node => {
      nodeHasContent(node, removeAttributeValue);

      if (
        typeof node === 'object' &&
        Object.prototype.hasOwnProperty.call(node, 'attrs')
      ) {
        Object.keys(node.attrs).forEach(key => {
          node.attrs[key] =
            boolean.includes(key) ||
            node.attrs[key]
              .trim()
              .split(' ')
              .filter(value => value.length)
              .join(' ');
        });
      }

      return node;
    });

  return removeAttributeValue(tree);
};

const lowerElementName = (tree, {tags}) => {
  tags = tags.map(({name}) => name);

  const bypass = tree =>
    tree.map(node => {
      nodeHasContent(node, bypass);

      if (
        typeof node === 'object' &&
        Object.prototype.hasOwnProperty.call(node, 'tag') &&
        tags.includes(node.tag.toLowerCase())
      ) {
        node.tag = node.tag.toLowerCase();
      }

      return node;
    });

  return bypass(tree);
};

const lowerAttributeName = tree => {
  const bypass = tree =>
    tree.map(node => {
      nodeHasContent(node, bypass);

      nodeHasAttrs(node, (previousValue, key) =>
        Object.assign(previousValue, {[key.toLowerCase()]: node.attrs[key]})
      );

      return node;
    });

  return bypass(tree);
};

const eof = (tree, {rules: {eof}}) => (eof ? [...tree, eof] : tree);

const mini = (tree, {mini}) => {
  const bypass = tree =>
    tree.map(node => {
      nodeHasContent(node, bypass);

      nodeHasAttrs(node, (previousValue, key) => {
        if (
          mini.removeAttribute &&
          mini.removeAttribute === 'empty' &&
          node.attrs[key].length === 0
        ) {
          return previousValue;
        }

        return Object.assign(previousValue, {
          [key.toLowerCase()]: node.attrs[key]
        });
      });

      return node;
    });

  return bypass(tree);
};

const sortLogic = function (key1, key2) {
  if (key1 < key2) {
    return -1;
  }

  if (key1 > key2) {
    return 1;
  }

  return 0;
};

const sortAttr = (tree, {rules: {sortAttr}}) => {
  tree.walk = walk;
  tree.walk(node => {
    if (sortAttr && node.attrs) {
      const keys = Object.keys(node.attrs);
      if (keys.length > 1) {
        node.attrs = keys
          .sort(sortLogic)
          .reduce(
            (current, key) =>
              Object.assign(current, {[key]: node.attrs[key]}),
            {}
          );
      }
    }

    return node;
  });

  delete tree.walk;
  return tree;
};

const jsPrettier = (tree, {rules: {indent, eol}, jsBeautifyOptions}) => {
  let level = 0;
  const prettier = tree =>
    tree.map(node => {
      ++level;
      nodeHasContent(node, prettier);

      if (node.tag === 'script') {
        const content = node.content ?
          [
            '\n',
            js(node.content.join(''), {
              ...jsBeautifyOptions,
              indent_level: level // eslint-disable-line camelcase
            }),
            getIndent(--level, {indent, eol})
          ] :
          [''];
        node.content = content;
      }

      --level;
      return node;
    });

  return prettier(tree);
};

const addLang = (tree, {rules: {lang}}) => {
  if (!lang) {
    return tree;
  }

  tree.walk = walk;

  tree.walk(node => {
    if (node.tag) {
      if (!node.attrs) {
        node.attrs = {lang};
        return node;
      }

      nodeHasAttrs(node, (previousValue, key) => {
        return Object.assign(
          {},
          {lang, [key]: node.attrs[key]},
          previousValue
        );
      });
    }

    return node;
  });

  delete tree.walk;
  return tree;
};

const commentsFormatting = (tree, {commentFormat}) => {
  if (!commentFormat) {
    return tree;
  }

  tree.walk = walk;
  tree.walk(node => {
    if (typeof node === 'string') {
      const originalComments = node.trim();
      if (/<!--([\S\s]*?)-->/g.test(originalComments)) {
        const content = originalComments
          .replace(COMMENT_START_REG, '')
          .replace(COMMENT_END_REG, '');
        const contentArr = content.split('\n').filter(c => c.trim() !== '');

        const newContent = ['<!--', ...contentArr, '-->'];

        return newContent
          .map(c => c.trim())
          .join(contentArr.length === 1 ? ' ' : '\n');
      }
    }

    return node;
  });

  delete tree.walk;
  return tree;
};

const beautify = (tree, options) =>
  [
    clean,
    parseConditional,
    renderConditional,
    commentsFormatting,
    indent,
    jsPrettier,
    lowerElementName,
    lowerAttributeName,
    attributesBoolean,
    sortAttr,
    addLang,
    eof,
    mini
  ].reduce(
    (previousValue, module) =>
      typeof module === 'function' ?
        module(previousValue, options) :
        previousValue,
    tree
  );

const normalize = (node, options) => {
  let {tree, api} = Object.keys(node).reduce(
    (scope, key) => {
      scope[Number.isNaN(Number(key)) ? 'api' : 'tree'][key] = node[key];

      return scope;
    },
    {tree: [], api: []}
  );

  tree = beautify(tree, deepmerge(optionsDefault, options));

  for (const [key, value] of Object.entries(api)) {
    tree[key] = value;
  }

  return tree;
};

export default (options = {}) => node => {
  if (!Array.isArray(node)) {
    throw new TypeError('tree is not Array');
  }

  if (node.length === 0) {
    return node;
  }

  return normalize(node, options);
};
<commit_msg>refactor: commentsFormatting<commit_after>import parser from 'posthtml-parser';
import render from 'posthtml-render';
import {walk} from 'posthtml/lib/api';
import rules from './rules.js';
import attrs from './attrs.js';
import tags from './tags.js';
import deepmerge from 'deepmerge';
import {js} from 'js-beautify';

const optionsDefault = {
  rules,
  attrs,
  tags,
  sync: false,
  commentFormat: true,
  mini: {
    removeAttribute: false
  },
  jsBeautifyOptions: {
    indent_size: 2, // eslint-disable-line camelcase
    jslint_happy: true // eslint-disable-line camelcase
  }
};

const COMMENT_START = '<!--';
const COMMENT_END = '-->';
const COMMENT_CONTENT_REG = new RegExp(`${COMMENT_START}([\S\s]*?)${COMMENT_END}`, 'g');

const nodeHasContent = (node, callback) => {
  if (
    typeof node === 'object' &&
    Object.prototype.hasOwnProperty.call(node, 'content')
  ) {
    node.content = callback(node.content);
  }
};

const nodeHasAttrs = (node, callback) => {
  if (
    typeof node === 'object' &&
    Object.prototype.hasOwnProperty.call(node, 'attrs')
  ) {
    node.attrs = Object.keys(node.attrs).reduce(callback, {});
  }
};

const getIndent = (level, {indent, eol}) => {
  const indentString = typeof indent === 'number' ? ' '.repeat(indent) : '\t';

  return `${eol}${indentString.repeat(level)}`;
};

const clean = tree =>
  parser(render(tree))
    .filter(node => {
      return (
        typeof node === 'object' ||
        (typeof node === 'string' &&
          (node.trim().length !== 0 || /doctype/gi.test(node)))
      );
    })
    .map(node => {
      if (Object.prototype.hasOwnProperty.call(node, 'content')) {
        node.content = clean(node.content);
      }

      return typeof node === 'string' ? node.trim() : node;
    });

const parseConditional = tree => {
  return tree.map(node => {
    nodeHasContent(node, parseConditional);

    if (typeof node === 'string' && /<!(?:--)?\[[\S\s]*?]>/.test(node)) {
      const conditional = /^((?:<[^>]+>)?<!(?:--)?\[[\S\s]*?]>(?:<!)?(?:-->)?)([\S\s]*?)(<!(?:--<!)?\[[\S\s]*?](?:--)?>)$/
        .exec(node)
        .slice(1)
        .map((node, index) =>
          index === 1 ?
            {tag: 'conditional-content', content: clean(parser(node))} :
            node
        );

      return {
        tag: 'conditional',
        content: conditional
      };
    }

    return node;
  });
};

const renderConditional = tree => {
  return tree.reduce((previousValue, node) => {
    if (
      typeof node === 'object' &&
      Object.prototype.hasOwnProperty.call(node, 'content')
    ) {
      node.content = renderConditional(node.content);
    }

    if (typeof node === 'object' && node.tag === 'conditional') {
      return [...previousValue, ...node.content];
    }

    if (typeof node === 'object' && node.tag === 'conditional-content') {
      node.tag = false;
      return [...previousValue, node];
    }

    return [...previousValue, node];
  }, []);
};

const indent = (tree, {rules: {indent, eol, blankLines, maxlen}}) => {
  const setIndent = (tree, level = 0) =>
    tree.reduce((previousValue, node, index) => {
      if (
        typeof node === 'object' &&
        Object.prototype.hasOwnProperty.call(node, 'content')
      ) {
        node.content = setIndent(node.content, ++level);
        --level;
      }

      if (tree.length === 1 && typeof tree[index] === 'string') {
        if (tree[index].length >= maxlen) {
          return [
            ...previousValue,
            getIndent(level, {indent, eol}),
            node,
            getIndent(--level, {indent, eol})
          ];
        }

        return [...previousValue, node];
      }

      if (level === 0 && tree.length - 1 === index && tree.length > 1) {
        return [...previousValue, getIndent(level, {indent, eol}), node];
      }

      if (level === 0 && tree.length - 1 === index && tree.length === 1) {
        return [...previousValue, node];
      }

      if (level === 0 && index === 0) {
        return [...previousValue, node, blankLines];
      }

      if (level === 0) {
        return [
          ...previousValue,
          getIndent(level, {indent, eol}),
          node,
          blankLines
        ];
      }

      if (tree.length - 1 === index) {
        return [
          ...previousValue,
          getIndent(level, {indent, eol}),
          node,
          getIndent(--level, {indent, eol})
        ];
      }

      if (typeof node === 'string' && /<!(?:--)?\[endif]*?]>/.test(node)) {
        return [
          ...previousValue,
          getIndent(level, {indent, eol}),
          node,
          blankLines
        ];
      }

      if (typeof node === 'string' && /<!(?:--)?\[[\S\s]*?]>/.test(node)) {
        return [...previousValue, getIndent(level, {indent, eol}), node];
      }

      if (node.tag === false) {
        return [...previousValue, ...node.content.slice(0, -1)];
      }

      return [
        ...previousValue,
        getIndent(level, {indent, eol}),
        node,
        blankLines
      ];
    }, []);

  return setIndent(tree);
};

const attributesBoolean = (tree, {attrs: {boolean}}) => {
  const removeAttributeValue = tree =>
    tree.map(node => {
      nodeHasContent(node, removeAttributeValue);

      if (
        typeof node === 'object' &&
        Object.prototype.hasOwnProperty.call(node, 'attrs')
      ) {
        Object.keys(node.attrs).forEach(key => {
          node.attrs[key] =
            boolean.includes(key) ||
            node.attrs[key]
              .trim()
              .split(' ')
              .filter(value => value.length)
              .join(' ');
        });
      }

      return node;
    });

  return removeAttributeValue(tree);
};

const lowerElementName = (tree, {tags}) => {
  tags = tags.map(({name}) => name);

  const bypass = tree =>
    tree.map(node => {
      nodeHasContent(node, bypass);

      if (
        typeof node === 'object' &&
        Object.prototype.hasOwnProperty.call(node, 'tag') &&
        tags.includes(node.tag.toLowerCase())
      ) {
        node.tag = node.tag.toLowerCase();
      }

      return node;
    });

  return bypass(tree);
};

const lowerAttributeName = tree => {
  const bypass = tree =>
    tree.map(node => {
      nodeHasContent(node, bypass);

      nodeHasAttrs(node, (previousValue, key) =>
        Object.assign(previousValue, {[key.toLowerCase()]: node.attrs[key]})
      );

      return node;
    });

  return bypass(tree);
};

const eof = (tree, {rules: {eof}}) => (eof ? [...tree, eof] : tree);

const mini = (tree, {mini}) => {
  const bypass = tree =>
    tree.map(node => {
      nodeHasContent(node, bypass);

      nodeHasAttrs(node, (previousValue, key) => {
        if (
          mini.removeAttribute &&
          mini.removeAttribute === 'empty' &&
          node.attrs[key].length === 0
        ) {
          return previousValue;
        }

        return Object.assign(previousValue, {
          [key.toLowerCase()]: node.attrs[key]
        });
      });

      return node;
    });

  return bypass(tree);
};

const sortLogic = function (key1, key2) {
  if (key1 < key2) {
    return -1;
  }

  if (key1 > key2) {
    return 1;
  }

  return 0;
};

const sortAttr = (tree, {rules: {sortAttr}}) => {
  tree.walk = walk;
  tree.walk(node => {
    if (sortAttr && node.attrs) {
      const keys = Object.keys(node.attrs);
      if (keys.length > 1) {
        node.attrs = keys
          .sort(sortLogic)
          .reduce(
            (current, key) =>
              Object.assign(current, {[key]: node.attrs[key]}),
            {}
          );
      }
    }

    return node;
  });

  delete tree.walk;
  return tree;
};

const jsPrettier = (tree, {rules: {indent, eol}, jsBeautifyOptions}) => {
  let level = 0;
  const prettier = tree =>
    tree.map(node => {
      ++level;
      nodeHasContent(node, prettier);

      if (node.tag === 'script') {
        const content = node.content ?
          [
            '\n',
            js(node.content.join(''), {
              ...jsBeautifyOptions,
              indent_level: level // eslint-disable-line camelcase
            }),
            getIndent(--level, {indent, eol})
          ] :
          [''];
        node.content = content;
      }

      --level;
      return node;
    });

  return prettier(tree);
};

const addLang = (tree, {rules: {lang}}) => {
  if (!lang) {
    return tree;
  }

  tree.walk = walk;

  tree.walk(node => {
    if (node.tag) {
      if (!node.attrs) {
        node.attrs = {lang};
        return node;
      }

      nodeHasAttrs(node, (previousValue, key) => {
        return Object.assign(
          {},
          {lang, [key]: node.attrs[key]},
          previousValue
        );
      });
    }

    return node;
  });

  delete tree.walk;
  return tree;
};

const commentsFormatting = (tree, {commentFormat}) => {
  if (!commentFormat) {
    return tree;
  }

  tree.walk = walk;
  tree.walk(node => {
    if (typeof node === 'string') {
      const contentMatch = node.match(COMMENT_CONTENT_REG)

      if (contentMatch === null) {
        return node;
      }

      const content = contentMatch[1]
        .trim()
        .split('\n')
        .filter(part => part.trim())

      return [
        COMMENT_START,
        ...content,
        COMMENT_END
      ].join('\n')
    }

    return node;
  });

  delete tree.walk;
  return tree;
};

const beautify = (tree, options) =>
  [
    clean,
    parseConditional,
    renderConditional,
    commentsFormatting,
    indent,
    jsPrettier,
    lowerElementName,
    lowerAttributeName,
    attributesBoolean,
    sortAttr,
    addLang,
    eof,
    mini
  ].reduce(
    (previousValue, module) =>
      typeof module === 'function' ?
        module(previousValue, options) :
        previousValue,
    tree
  );

const normalize = (node, options) => {
  let {tree, api} = Object.keys(node).reduce(
    (scope, key) => {
      scope[Number.isNaN(Number(key)) ? 'api' : 'tree'][key] = node[key];

      return scope;
    },
    {tree: [], api: []}
  );

  tree = beautify(tree, deepmerge(optionsDefault, options));

  for (const [key, value] of Object.entries(api)) {
    tree[key] = value;
  }

  return tree;
};

export default (options = {}) => node => {
  if (!Array.isArray(node)) {
    throw new TypeError('tree is not Array');
  }

  if (node.length === 0) {
    return node;
  }

  return normalize(node, options);
};
<|endoftext|>


<commit_before>import * as mixedice from 'mixedice';
import * as EventMap from 'eventmap';

class Model {
  constructor() {
    // Mix in `EventMap` into all `Model` instances
    mixedice([this, Model.prototype], new EventMap());

    // Store attribute data
    this.data = {};
  }

  get() {
    // Get an attribute if it exists
    if (Object.hasOwnProperty.call(this.data, name)) {
      return this.data[name];
    }
  }

  set(name, value) {
    // Set or add an attribute
    this.data[name] = value;
    // Trigger the `change` event with `name` and `value` as its parameters
    this.trigger('change', name, value);
  }
}
<commit_msg>Forgot to export the module<commit_after>import * as mixedice from 'mixedice';
import * as EventMap from 'eventmap';

class Model {
  constructor() {
    // Mix in `EventMap` into all `Model` instances
    mixedice([this, Model.prototype], new EventMap());

    // Store attribute data
    this.data = {};
  }

  get() {
    // Get an attribute if it exists
    if (Object.hasOwnProperty.call(this.data, name)) {
      return this.data[name];
    }
  }

  set(name, value) {
    // Set or add an attribute
    this.data[name] = value;
    // Trigger the `change` event with `name` and `value` as its parameters
    this.trigger('change', name, value);
  }
}

export default Model;
<|endoftext|>